Code-Generated Animation and 3D Scenes: A Practical Guide to Autonomous LLM Coding
This article examines code-generated animation and 3D scenes, where a large language model writes and runs drawing, audio, and rendering code instead of calling image or video generation tools. It explains why code-based generation is gaining attention, compares it with direct video generation models, and breaks down the full pipeline: intent parsing, scene design, procedural music and sound effects, frame-by-frame rendering, audio-video synchronization, and single-file HTML delivery. It also covers procedural 3D scene generation, the engineering challenges of long-running autonomous coding, context and output-length constraints, cost control, security and compliance, cloud deployment, and a checklist for objectively evaluating autonomy claims. Both the Python audio synthesis example and the Canvas animation example are included with English comments.
A recent animation demo generated autonomously by a large language model has drawn discussion in overseas developer communities. According to the author, the model called no image or video generation tools. Instead, it wrote and ran code continuously for about 2 hours and 40 minutes, producing the visuals, background music, and sound effects for a 66-second animation, all packaged into a single HTML file. Several technology publications have since reported on it.
One point needs to be stated objectively: this kind of demo is currently the claim of an individual developer. The model’s identity and whether the process involved any human intervention have not been independently verified, and the version information that surfaced during the demo has not been officially confirmed by the model’s developer. This article therefore does not target any specific model or product. Instead, it abstracts the discussion into three technical questions of general relevance:
- How to generate animation and sound with code;
- Why a large language model can code autonomously for hours, and how to constrain that process;
- How teams should evaluate, integrate, and govern this capability in production.
1. Understanding the Trend: Why “Build” Animation With Code
1.1 The Fundamental Difference Between Two Technical Routes
Two mainstream routes exist for AI-generated visual content today:
- Generative models that output video frames or pixels directly;
- Code-based generation, the focus of this article, where the model writes drawing and composition code and a program computes each frame and synthesizes the sound.
The fundamental difference lies in the intermediate artifacts. With the code-based route, the intermediate artifact is source code that can be read, debugged, and reproduced. Defects can be traced to specific functions and parameters, and the code fits naturally into version control and continuous integration in a repository. The trade-off is that visual quality, physical realism, and production speed still lag noticeably, so it is unlikely to replace professional production workflows in the near term.
1.2 What Code-Based Generation Delivers
The points repeatedly highlighted about the demo can be summarized as follows:
- Single artifact: the finished work is packaged into one HTML file, easy to share and modify;
- No external assets: the music and sound effects are computed in real time by code the model wrote, with no external images, asset libraries, audio samples, or font files;
- Multi-sensory composition: visuals, music, and sound effects are produced together in one task;
- Long-chain autonomous execution: coding, running, and fixing span hours, far beyond the usual “single-turn generation” interaction pattern.
1.3 Related 3D Scene Cases
Around the same time, interactive 3D scenes said to be written by a large language model also circulated in the community, featuring an old sailing ship, ocean waves, and a sports car. These scenes rely mainly on common JavaScript 3D rendering libraries, with camera, lighting, and object motion controlled programmatically; some scenes can be generated from a simple prompt. Such cases share the same technical thread as the animation demo: natural-language intent → structured scene parameters → executable code → real-time rendering.
2. Route Comparison: Code-Based Animation vs. Video Generation Models
| Dimension | Code-Based Animation | Models That Generate Video Frames Directly |
|---|---|---|
| Generation method | Executes drawing and composition instructions written by the model | Predicts pixels or video frames directly |
| Visual style | Mainly geometric, flat, procedural looks | Stronger at realistic and complex textures |
| Duration and resolution | In principle limited only by rendering compute; can be extended arbitrarily | Constrained by the model’s output specifications |
| Editability | Change parameters or code and re-render; results are reproducible | Usually requires regeneration; local edits are difficult |
| Explainability | High; defects traceable to code | Low; hard to attribute precisely |
| Asset dependency | Can rely on no external assets at all | Generation is tied to training data |
| Main cost | Coding time, model call volume, and rendering compute | Inference compute |
| Typical use cases | Data visualization, concept prototypes, teaching demos, lightweight interactive content | Realistic footage, VFX assets, creative short films |
The conclusion is clear: the two are complementary, not substitutes. For scenarios that demand precise control, reproducibility, and greater certainty about copyright, the code-based route has the advantage. When realistic texture is the goal, generative models remain the primary choice.
3. Breaking Down the Code-Based Animation Pipeline
3.1 Overall Flow
A practical code-based animation pipeline typically has six stages:
- Intent parsing: turn the natural-language request into a structured shot list, timeline, and style parameters;
- Scene design: define subjects, background, color palette, camera moves, and pacing beats;
- Audio synthesis: compose music and sound effects from tempo, chords, and rhythmic patterns;
- Frame-by-frame drawing: compute the state of the scene at each moment from the frame number and rasterize it;
- Audio-video sync and encoding: package at a fixed frame rate into a video or a standalone web page;
- Quality checks: verify duration, resolution, audio-video offset, and encoding integrity.
3.2 Synthesizing Music and Sound Effects Purely in Code
Because the demo uses no audio samples, the music and sound effects must be synthesized from scratch. Common techniques include:
- Layering harmonics over basic waveforms such as sine and sawtooth;
- Using exponential decay envelopes to emulate percussion;
- Using filtered random noise to emulate ambient sounds such as waves and wind.
The example below depends only on the Python standard library. It generates kick drums, bass, and wave sounds on a given beat grid and writes a WAV file:
import mathimport randomimport structimport waveSR = 44100 # Sample rate: 44100 samples per secondBEAT = 60.0 / 96 # At 96 BPM, the duration of one beat (seconds)def kick(t: float) -> float:"""Kick drum: sine wave sweeping quickly from high to low, with an exponential decay envelope."""freq = 45 + 120 * math.exp(-30 * t)return 0.8 * math.sin(2 * math.pi * freq * t) * math.exp(-12 * t)def hat(t: float, rng: random.Random) -> float:"""Hi-hat: filtered noise with a short decay envelope."""noise = (rng.random() * 2 - 1) - (rng.random() * 2 - 1) # First-order difference, attenuates low frequenciesreturn 0.15 * noise * math.exp(-60 * t)def bass(t: float, freq: float) -> float:"""Bass: fundamental plus second harmonic, with fade-in and decay envelope."""env = min(1.0, t / 0.005) * math.exp(-3 * t)return 0.3 * env * (math.sin(2 * math.pi * freq * t)+ 0.3 * math.sin(4 * math.pi * freq * t))def waves(t: float) -> float:"""Waves: several low-frequency sines layered and slowly swelling overall to mimic tides."""swell = 0.6 + 0.4 * math.sin(2 * math.pi * 0.09 * t)v = (math.sin(2 * math.pi * 110 * t)+ 0.5 * math.sin(2 * math.pi * 173 * t + 1.3)+ 0.3 * math.sin(2 * math.pi * 251 * t + 2.1))return 0.12 * swell * vdef render(duration: float) -> list[float]:rng = random.Random(20261104) # Fixed random seed for reproducibilitybuf = [0.0] * int(duration * SR)def add(fn, start: float, length: float, *args) -> None:offset = int(start * SR)for i in range(int(length * SR)):if offset + i < len(buf):buf[offset + i] += fn(i / SR, *args)for step in range(int(duration / (BEAT / 4))): # Grid of sixteenth notest0 = step * BEAT / 4if step % 8 == 0 or step % 8 == 6:add(kick, t0, 0.25)if step % 8 == 4:add(kick, t0, 0.15)if step % 2 == 1:add(hat, t0, 0.08, rng)if step % 4 == 0:chord = [55.0, 65.41, 73.42, 49.0][(step // 16) % 4] # A1 C2 D2 G1add(bass, t0, BEAT * 0.9, chord)for i, x in enumerate(buf): # Layer ambient sound, then normalize and fade out overallt = i / SRy = x + waves(t)fade = min(1.0, max(0.0, (duration - t) / 1.5))buf[i] = max(-1.0, min(1.0, y * 0.9)) * fadereturn bufdef write_wav(path: str, samples: list[float]) -> None:pcm = b"".join(struct.pack("<h", int(s * 32767)) for s in samples)with wave.open(path, "wb") as f:f.setnchannels(1)f.setsampwidth(2)w.setframerate(SR)f.writeframes(pcm)write_wav("score.wav", render(66))
This code illustrates three principles of procedural audio:
- Everything is a function: the pitch, envelope, and filter parameters of every sound are adjustable functions;
- Time is gridded: the timeline is divided by beats, making it easy to align with visual beats;
- Results are reproducible: with a fixed random seed, the same code produces identical output in any environment.
3.3 Frame-by-Frame Rendering and Web Packaging
For the visuals, a drawing library can output a still image per frame, and a video encoding tool can then combine them into a video at a fixed frame rate. To deliver a single HTML file, you can also draw directly in the browser with Canvas, WebGL, or inline SVG. The example below uses the native Canvas API to implement a simple, continuously moving seascape animation:
<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>Procedural Seascape Animation (Illustrative)</title></head><body style="margin:0;background:#000;display:flex;justify-content:center;align-items:center;height:100vh"><canvas id="stage" width="1280" height="720"></canvas><script>const canvas = document.getElementById('stage');const ctx = canvas.getContext('2d');const W = canvas.width, H = canvas.height;// Scene parameters: can be mapped from a natural-language prompt, or overridden via query parametersconst q = new URLSearchParams(location.search);const sunRatio = Math.min(0.95, Math.max(0.05, Number(q.get('sun') ?? 0.68)));const waveAmp = Math.min(120, Math.max(0, Number(q.get('amp') ?? 42)));const waveSpeed = Math.min(3, Math.max(0, Number(q.get('speed') ?? 0.8)));// Gradient background: sky transitions from deep blue to dark teal at the seaconst sky = ctx.createLinearGradient(0, 0, 0, H);sky.addColorStop(0, '#0a1a3a');sky.addColorStop(0.55, '#23518a');sky.addColorStop(0.56, '#06222c');sky.addColorStop(1, '#031017');function draw(t) { // t: animation time in secondsctx.globalAlpha = 1;ctx.fillStyle = sky;ctx.fillRect(0, 0, W, H);// Sun: radial gradient glow plus a circular discconst sx = W * sunRatio, sy = H * 0.42, r = 60;const glow = ctx.createRadialGradient(sx, sy, 0, sx, sy, r * 4);glow.addColorStop(0, 'rgba(255,214,140,0.9)');glow.addColorStop(1, 'rgba(255,214,140,0)');ctx.fillStyle = glow;ctx.fillRect(sx - r * 4, sy - r * 4, r * 8, r * 8);ctx.fillStyle = '#ffe0a3';ctx.beginPath();ctx.arc(sx, sy, r, 0, Math.PI * 2);ctx.fill();// Sea surface: three layered sine waves whose amplitude breathes slowly over timefor (let layer = 0; layer < 3; layer++) {const base = H * (0.56 + 0.1 * layer);const amp = waveAmp * (0.6 + 0.2 * layer) * (0.8 + 0.2 * Math.sin(t * 0.5));ctx.beginPath();ctx.moveTo(0, H);for (let x = 0; x <= W; x += 4) {const y = base+ amp * Math.sin(x * 0.012 + t * waveSpeed + layer)+ amp * 0.4 * Math.sin(x * 0.031 - t * waveSpeed * 1.6);ctx.lineTo(x, y);}ctx.lineTo(W, H);ctx.closePath();ctx.fillStyle = `rgba(${8 + layer * 6}, ${52 + layer * 14}, ${74 + layer * 16}, 0.85)`;ctx.fill();}// Sea reflections: short horizontal dashes flickering with the sun's positionctx.globalAlpha = 0.5;ctx.strokeStyle = '#ffcf87';ctx.lineWidth = 2;for (let i = 0; i < 40; i++) {const y = H * 0.56 + i * 6;const half = 6 + i * 0.8;const x = sx + Math.sin(i * 7.3 + t * 2) * half;ctx.beginPath();ctx.moveTo(x - half * 0.5, y);ctx.lineTo(x + half * 0.5, y);ctx.stroke();}ctx.globalAlpha = 1;// Distant sailboat silhouette: hull plus triangular sail, bobbing gently with the wavesconst bx = W * 0.3 + Math.sin(t * 0.1) * 40;const by = H * 0.55 + Math.sin(t * waveSpeed) * waveAmp * 0.25;ctx.save();ctx.translate(bx, by);ctx.rotate(Math.sin(t * waveSpeed) * 0.02);ctx.fillStyle = '#10151c';ctx.beginPath();ctx.moveTo(-50, 0); ctx.lineTo(50, 0); ctx.lineTo(34, 16); ctx.lineTo(-36, 16);ctx.closePath(); ctx.fill();ctx.beginPath();ctx.moveTo(0, -2); ctx.lineTo(0, -92); ctx.lineTo(38, -2);ctx.closePath(); ctx.fill();ctx.fillRect(-2, -92, 3, 94);ctx.restore();}function frame(ts) { draw(ts / 1000); requestAnimationFrame(frame); }requestAnimationFrame(frame);</script></body></html>
This code reveals the engineering essence of code-based animation: the frame is a function of time. Every element’s properties are uniquely determined by time t. Animation therefore inherently offers:
- Precise seeking to any moment;
- Reproducibility;
- Parameterization.
If music is also needed, it can be synthesized in real time in the browser through audio synthesis APIs, with the drawing logic bound to the audio clock to guarantee strict audio-video synchronization.
4. Procedural Generation of 3D Scenes
4.1 How Scenes Are Organized
A 3D scene typically consists of:
- Geometry: complex objects assembled from basic primitives, such as hull, mast, sail, and wheels;
- Materials and lighting: determining color, reflection, and shadows;
- Camera and animation curves: controlling the viewpoint and object motion.
Converting a prompt into a scene generally takes two steps: the model first outputs structured parameters (JSON, YAML, and so on), which a fixed rendering framework then consumes. The benefit of structuring is a stable rendering logic and controllable parameter boundaries; the model only has to focus on “describing correctly” rather than rewriting the rendering engine each time.
4.2 Illustrative Scene Description and Rendering Skeleton
The example below uses the interface style of a general-purpose 3D rendering library and is illustrative only:
// 1) Structured scene description output by the model (illustrative)const sceneSpec = {duration: 30, fps: 60,camera: { fov: 45, from: [0, 6, 24], lookAt: [0, 2, 0] },objects: [{ type: "hull", size: [12, 2.5, 4], color: "#5a3a22", pos: [0, 0, 0] },{ type: "mast", height: 14, pos: [0, 1, 0], color: "#3b2a1a" },{ type: "sail", width: 8, height: 11, pos: [1.5, 3, 0], color: "#efe6d5" },{ type: "sail", width: 6, height: 9, pos: [-1.5, 3, 0], color: "#efe6d5" }],ocean: { amp: 0.6, wavelength: 9, speed: 1.2, color: "#1b5e7a" },light: { dir: [-0.5, 1, 0.3], intensity: 1.6, color: "#fff2d9" }};// 2) Generic rendering skeleton (interfaces are illustrative)const scene = new Scene();const camera = new PerspectiveCamera(sceneSpec.camera.fov, 16 / 9, 0.1, 500);scene.add(new DirectionalLight(sceneSpec.light.color, sceneSpec.light.intensity, sceneSpec.light.dir));for (const o of sceneSpec.objects) {const mesh = buildMesh(o); // Build geometry by type and assign a materialscene.add(mesh);}const ocean = new OceanMesh(sceneSpec.ocean);scene.add(ocean);function renderAt(t) { // Advance animation state by secondsconst bob = Math.sin(t * 1.3) * 0.15;const roll = Math.sin(t * 0.9) * 0.02;scene.getObjectByName("ship").position.y = bob;scene.getObjectByName("ship").rotation.z = roll;ocean.update(t, sceneSpec.ocean);camera.lookAt(0, 2 + bob, 0);renderer.render(scene, camera);}
4.3 Key Techniques for Complex Objects and Animation
- Old sailing ship: the hull is formed by extruding geometry and adjusting vertices into a streamlined shape; the mast and yards are slender cylinders; the sails use curved meshes to simulate billowing in the wind;
- Ocean waves: a vertex shader commonly layers multiple sine waves over the water mesh, with lighter color and foam added at the crests;
- Sports car: the body is generated by extruding polygonal meshes or parametric curves, with wheels kept as a separate group so they can rotate; car paint materials, ground reflections, and shadows improve realism;
- Lighting and materials: a directional light simulates sunlight, ambient and hemisphere lights fill in the dark areas, and fog creates the sea-to-sky transition.
5. Long-Horizon Autonomous Coding: Why It Can Run for Hours
5.1 From One-Shot Generation to Closed-Loop Iteration
Traditional code generation is one-shot: you provide a requirement, get code back, and a human runs and debugs it. Long-horizon autonomous coding turns this into a loop:
Goal → Plan → Write code → Run/render → Observe result → Fix → Verify → Commit
The roughly 2 hours and 40 minutes of continuous coding in the demo is essentially the model gradually approaching the goal across repeated “run—observe—fix” cycles.
5.2 Observing Results and Self-Correcting
The model can self-correct because it can read program feedback, including:
- Console errors and exception stack traces;
- Program output;
- Rendered screenshots or pixel statistics;
- File existence and artifact validation results.
This information is written back into the context, and the model uses it to locate defects. For example:
- When audio is too short or contains popping, check the sample rate, duration, and peak normalization;
- When audio and video are out of sync, unify the “frame number/sample number → time” conversion baseline;
- When the visuals look wrong, use screenshots or statistics such as brightness and color distribution as supporting evidence.
5.3 Four Engineering Challenges of Long-Horizon Runs
| Challenge | Symptom | Mitigation |
|---|---|---|
| Context bloat | Run logs quickly crowd out the window | Log summarization, per-file retention, structured key information |
| Goal drift | The task gradually diverges from the original requirement | Maintain a task list and acceptance criteria; check against them every round |
| Unstable environment | Missing dependencies, render failures, insufficient resources | Pin dependency versions, enforce timeouts, isolate in a sandbox |
| Error loops | Repeated attempts on the same class of error | Deduplicate errors; escalate or roll back once consecutive failures hit a threshold |
5.4 An Autonomous Coding Loop
"""Long-horizon autonomous coding loop (illustrative; model calls are pseudo-code)."""def run_unattended(task: str, budget_steps: int = 200) -> dict:"""Complete the given task in an unattended execution loop.Args:task: The goal and acceptance criteria described in natural language.budget_steps: Maximum number of iterations, used to constrain cost and duration.Returns:A dict with the final state, iteration count, and per-stage timing stats."""context = [system_prompt(), user_message(task)]todo = planner(task) # Generate a task list (pseudo-code)failures = {}for step in range(budget_steps):if all(item["done"] for item in todo):breakaction = model.next_action( # Pseudo-code: the model decides the next actioncontext + [todo_state(todo), failure_digest(failures)])if action.kind == "write_file":observation = sandbox.write(action.path, action.content)elif action.kind == "run":observation = sandbox.run(action.command, timeout=120, network=False)elif action.kind == "render":observation = render.headless(action.script) # Render in a headless environmentelse:break# Compress observations so logs do not blow up the contextcontext.append(summarize(action, observation, max_chars=4000))result = verifier.check(action, observation, todo) # Validate and update the listif result.error:failures[result.key] = failures.get(result.key, 0) + 1if failures[result.key] >= 3:todo.insert(0, {"item": "Investigate the recurring error", "done": False})return {"done": all(item["done"] for item in todo), "steps": step + 1}
6. Context and Output Length: Two Constraints on Long Tasks
6.1 The Value and Limits of Long Context
One direction in the evolution of LLM applications is “long context”: supported context windows have grown from a few thousand tokens in the early days to hundreds of thousands or even millions of tokens. For long-horizon coding tasks, long context is valuable because it can:
- Hold project structure notes, multiple source files, and run logs at once;
- Keep requirements and design decisions consistent across a long chain.
But it is no substitute for context engineering. Attention gets diluted, cost rises with length, and irrelevant content interferes with judgment. The practical principle: summarize rather than paste verbatim; retrieve on demand rather than stuffing everything in.
6.2 The Chunking Problem Created by Output Length
However large the context, there is a relatively limited maximum output length per response. A full animation project of thousands of lines with asset files is hard to write in a single reply. A common approach is to have the model produce output in stages:
- Stage 1: generate the audio synthesis module;
- Stage 2: generate the scene and rendering modules;
- Stage 3: generate the main entry point, parameter configuration, and build scripts;
- Stage 4: run, check, fix, and integrate.
6.3 The Impact of Separate Input and Output Billing
LLM APIs generally bill input tokens and output tokens separately, with output usually priced higher. Long-horizon tasks are naturally “input-heavy and output-heavy”: context is carried repeatedly, and every loop produces new code and logs. Cost-control measures include:
- Summarizing logs and loading source code on demand;
- Caching fixed system prompts and project notes, using prompt caching to reduce the cost of repeated input;
- Turning “retry” into “locate”: use compiler and unit test output for precise errors instead of blind rewrites;
- Setting budget caps on steps, token usage, and runtime.
7. Security, Compliance, and Tiered Model Governance
7.1 Security Risks in Long Tasks
Long tasks expand the attack surface:
- Prompt injection: task descriptions or external content may carry inducements such as “ignore previous instructions”;
- Runaway execution: generated code may occupy CPU and memory for a long time, or even issue unexpected network requests;
- Supply chain risk: the model may pull in dependencies of unknown origin;
- Information leakage: logs or source code may contain secrets and other sensitive data.
7.2 Defense in Depth
- Sandbox isolation: run code in a container or lightweight virtual machine, restrict network egress, whitelist readable and writable directories, and set caps on CPU, memory, and execution time;
- Dependency governance: pin dependency versions, use a private artifact repository, and scan for known vulnerabilities;
- Least privilege: use short-lived, narrowly scoped temporary tokens for credentials;
- Human review: have a person review dependencies, network behavior, and the final artifact before release.
7.3 Model Tiering and Access Policies
On the model provider side, the industry has tiered access models: the same base model capability is subject to different safety constraints and access policies at different tiers. Uses in highly sensitive industries are opened to vetted organizations; the tiers aimed at general users and developers retain general capabilities while strengthening safeguards. This design balances capability and risk, and it signals to users that a model’s safety policy affects the boundary of available capabilities, so selection should match your own compliance requirements.
7.4 Content Compliance for Code-Based Generation
The code-based route has a natural compliance advantage: visuals and sound are all computed by the program, with no dependence on external images, assets, or samples, which lowers the risk of asset infringement at the source. Two points still deserve attention:
- Style similarity: synthesized music that closely resembles a specific copyrighted work in style may still invite disputes;
- Generated code licensing: check whether model-generated code conflicts with known open source licenses, especially strongly copyleft ones.
8. Engineering Deployment in the Cloud
When integrating this capability into production systems, you can build a pipeline on cloud platform primitives:
- Task orchestration: connect long-running tasks to workflow scheduling with automatic retry and alerting on timeout or failure;
- Elastic compute: use a container platform to scale rendering and compilation stages elastically;
- Artifact storage: store audio, frame sequences, and video in object storage with lifecycle management;
- Logging and monitoring: collect run logs centrally and track task success rate and resource usage with monitoring and alerting;
- Security and compliance: use content safety capabilities to identify risks in model output.
For example, on Baidu AI Cloud, developers can combine container services, object storage, log services, and monitoring and alerting to carry such tasks. Teams can also rely on the tools provided by the large model development platform, combined with knowledge base retrieval augmentation and agent orchestration, to lower the barrier to building long-running tasks.
9. How to Objectively Evaluate “Autonomous Coding” Claims
Developers should stay skeptical about demos circulating in the community. Here is an actionable evaluation checklist:
- Reproducibility: can they provide complete code, a runtime environment, and a one-click reproduction script;
- Degree of human intervention: is the share of prompts, manual fixes, and supplementary assets disclosed;
- Information completeness: was it a single continuous run, or staged with human guidance;
- Environment control: was a preset scaffold used, and were dependencies and tools prepared in advance;
- Objective metrics: task completion rate, number of human interventions, token consumption, execution time, and cost per task;
- Quality assessment: visual and audio quality should be judged by multiple blind reviewers, not a single person’s impression.
10. Conclusion
Code-generated animation and 3D scene generation are a microcosm of large language models moving from “generating content” to “executing tasks.” Their value lies not in how impressive a single generation looks, but in being reproducible, editable, and auditable. For developers, the real barrier is not whether a model can produce a given demo, but whether you can decompose long-horizon autonomous coding into a verifiable, constrainable, and operable engineering process. Look at community demos rationally and build your own evaluation and governance system, and only then can this capability be turned into stable productivity.
