Code-Only Video Generation: A Practical Engineering Guide
Learn how to build visually compelling short videos entirely with code, without external media assets or generative media APIs. This guide covers visual planning, procedural rendering, synthesized audio, deterministic frame export, performance tiers, and validation criteria for a reproducible project.
1. Why Code-Only Video Generation Is an Engineering Challenge
Developers have been exploring whether large language models can help create visually compelling short videos under strict constraints: no external images, video clips, or audio assets; no generative media APIs; and all visuals and sound synthesized programmatically. The deliverables must include both a complete, reproducible project and an actual exported video file.
These constraints are useful because they separate generative content from reproducible engineering. The former often depends on uncontrolled sampling, while the latter requires the same inputs to produce the same outputs. Without external assets, visual quality must come from three sources: mathematical representations, rendering pipeline design, and narrative sequencing. These are core capabilities of graphics programming.
An important distinction follows: a model’s ability to write complex visual effects does not make the resulting implementation reliable. Success depends on measurable acceptance criteria, including resolution, frame rate, duration, deliverable formats, fallback strategies, and evaluation dimensions. Clear requirements help turn an effects demonstration into a deliverable engineering project.
2. Visual Concept and Pacing: Design Before Writing Shaders
A common failure mode is treating procedural video as a collection of unrelated technical demos. A better approach is to choose a visual motif that can be expressed mathematically.
“Gravity and accretion,” for example, offers a dense central celestial body, a surrounding disk with differential rotation, and distorted background starlight. It naturally supports multiple layers of scale, from individual particles to a broad star field; color, from cool dark red to hot cyan-white; and movement, including rotation, precession, and camera movement.
A four-part sequence, with each section lasting 8–15 seconds, provides a practical structure:
- Opening: An almost dark scene with sparse stars and low-frequency noise establishes a sense of space.
- Development: The camera slowly moves forward. The accretion disk expands from a thin line into a surface, while particle density increases.
- Turning point: A sudden change in color temperature and exposure strengthens the gravitational lensing effect, producing noticeable distortion.
- Resolution: The camera pulls back as bloom and grain are layered into the image. The audio settles into a single sustained tone.
For camera movement, one continuous motion—a slow push-in with slight roll—is generally more manageable than repeated cuts. A procedural scene offers less room to hide inconsistencies than an edit assembled from filmed footage.
3. Core Technical Challenges
3.1 Hybrid Fractal Signed Distance Fields
Represent geometry with signed distance functions (SDFs), then use sphere tracing, a form of ray marching, to find surface intersections.
For hybrid fractals, iteration counts and step scaling require careful control. Too few iterations lose detail; too many increase both visual noise and rendering time. Make the iteration limit adjustable and connect it to the project’s quality tiers.
3.2 Approximate Gravitational Lensing
Physically accurate light tracing is expensive. A practical alternative is a single screen-space UV distortion.
Calculate a radial offset relative to the scene center, reduce its strength with distance, and sample the background using the displaced coordinates. This creates a convincing impression of bent starlight at relatively low cost.
3.3 Doppler-Inspired Accretion Disk Shading
Modulate disk brightness asymmetrically along the tangential velocity direction: brighten one side and darken the other. Combine this with a radial temperature falloff mapped to a color palette to reinforce the impression of rotation.
The brightness modulation must agree with the direction of motion. Otherwise, the scene sends conflicting visual cues.
3.4 Particle Curl Fields
Tens of thousands of instanced particles can move through a curl field. The approximately incompressible flow helps avoid unwanted local particle accumulation.
Derive the curl field from a noise-based potential function, rather than storing an entire velocity field.
3.5 Anti-Flicker Bloom and Tone Mapping
Bloom driven by independently evaluated highlight thresholds can flicker between frames. Apply temporal smoothing to the thresholding result using an exponential blend with the previous frame.
Finally, use a consistent tone-mapping curve to compress high-dynamic-range values into the display range and avoid hard highlight clipping.
3.6 Procedural Audio and Audiovisual Synchronization
Generate the audio in code as well. Combine low-frequency sine waves with noise for the underlying sound bed, then use envelopes to shape the rise and fall of each section.
Instead of aligning sound and visuals manually, make visual parameters and audio envelopes read from the same timeline function.
4. Shader Core and Rendering Workflow
The following shader sketch outlines the SDF scene function, lensing approximation, and disk modulation:
// Fragment shader core: SDF stepping + lens approximation + disk modulationfloat mapScene(vec3 p, float t) {float d = length(p) - 0.85; // Central bodyfloat f = 1.0;for (int i = 0; i < ITER; i++) { // ITER is adjustable by quality tierp = abs(p) / dot(p, p) - 0.35;d = min(d, f * length(p) / f);f *= 1.6;}return d;}vec3 render(vec2 uv, float t) {vec2 dir = uv;float r2 = dot(uv, uv);dir += uv * LENS_K / (r2 + 0.05); // Gravitational lensing approximationvec3 bg = sampleStars(dir, t);float spin = atan(uv.y, uv.x) + t * 0.6;float doppler = 0.6 + 0.4 * cos(spin); // Doppler-inspired asymmetryfloat radial = smoothstep(0.9, 0.25, length(uv));vec3 disk = palette(radial) * doppler * radial;return bg + disk;}
At the project level, use a fixed random seed and a fixed timestep. Export a lossless image sequence frame by frame rather than recording the renderer in real time. Real-time capture can drop frames and undermine reproducibility.
render.py --frames 1800 --fps 30 --width 1920 --height 1080 \--seed 20260826 --out ./frames# Output: frames/f_00000.png ... f_01799.png
5. Running, Exporting, and Naming Frames
Two implementation paths are practical:
- Browser-based: Use a single-page entry point served locally for offline operation. Render each frame explicitly, then read back the pixels and write them to an image sequence.
- Server-side: Pin the scripting environment to fixed versions and render lossless images frame by frame.
For final delivery, use an encoding tool to assemble the image sequence into an MP4 at a fixed frame rate, or sample frames to create a GIF.
Use a consistent naming convention such as f_%05d.png. Frame indices must correspond precisely to frame rate multiplied by elapsed time. This makes frame-by-frame inspection and resuming interrupted renders easier.
Pin dependencies to exact versions and record them in a dependency manifest. Without that, reproducibility remains an aspiration rather than an engineering property.
6. Performance Budgets and Quality Tiers
A baseline of 1080p, 30 fps, and 1,800 frames provides a useful example for planning. Keeping total rendering time acceptable requires budgeting both the time per frame and the total frame count.
Use multiple quality tiers rather than a single on/off fallback:
- High: Full fractal iterations, the complete particle count, and temporally smoothed bloom on every frame.
- Medium: Half the fractal iterations, fewer particles, and lower-resolution bloom.
- Low: Disable fractal detail, replace moving particles with a static distribution, and retain only one bloom layer.
Every tier should preserve the complete narrative. The goal is to make rendering cheaper without losing the visual design.
7. Evaluation and Acceptance Criteria
Evaluate the project across five dimensions, using measurable checks wherever possible:
- Visual impact: Do composition and color reflect a deliberate design?
- Technical complexity: Are the effects implemented through substantive algorithms rather than supplied textures?
- Code quality: Is the implementation modular and parameterized, with hard-coded values kept out of core logic?
- Reproducibility: Do runs with the same seed and software versions produce pixel-identical results?
- Performance and stability: How much does frame time vary, and are there crashes or continuing memory growth?
The main challenge in code-only video generation is not simply writing shaders. It is translating aesthetic intent into adjustable parameters and packaging the entire process so another person can reproduce it with a single command.
This methodology does not depend on a particular model or platform. Any coding assistant with code-generation capabilities can provide a starting point. Final delivery quality still depends on well-designed constraints and engineering validation.
