Evaluating AI-Generated Graphics Code: From Animated SVG to Realistic Lighting
Graphics tasks offer a practical way to evaluate AI code generation beyond algorithmic correctness. This article examines interactive SVG animation, rasterization, and path tracing, explains common rendering defects, and outlines a reproducible evaluation process and engineering safeguards for using generated graphics code.
1. Why Graphics Tasks Help Evaluate Code Generation
Code generation is often evaluated through algorithm problems or API completion tasks. Their text-based outputs are relatively easy to check, but they reveal less about a model’s understanding of space, time, and physical behavior.
Graphics tasks make those capabilities visible. Results can also be measured through pixel comparisons, frame rates, and rendering time. Whether an SVG animation moves smoothly or an interior scene has convincing lighting can often be assessed within seconds.
These tasks test three capabilities at once:
- Structural understanding: Can the model break a room, window, chair, and floor into a hierarchy of geometric objects?
- Mathematical and physical knowledge: Do coordinate transformations, light propagation, and occlusion behave plausibly?
- Engineering constraints: Does the output run independently, avoid external dependencies, and deliver acceptable performance?
Graphics tasks therefore make a useful complement to conventional code-generation tests. However, they require a consistent evaluation framework. Otherwise, a few selected images can easily be mistaken for evidence of overall capability.
2. Task One: Generate an Interactive Animated SVG
A common test asks a model to generate an animated SVG—for example, an animal riding a bicycle, with rotating wheels and a background that changes over time.
The requirements usually fall into three groups:
- Static structure: The positions and layering of the character, bicycle frame, wheels, and background.
- Animation: Wheel rotation, clothing or accessories moving with speed, and day-to-night transitions.
- Interaction: Controls for pausing, adjusting speed, and switching themes.
Key Technical Details
SVG uses a coordinate system with its origin at the upper-left corner and its y-axis pointing downward. For rotating wheels, the critical issue is the rotation center. Without an appropriate transform-origin, an element may rotate around the canvas origin rather than its own center, sending the wheel out of position.
There are two main animation approaches:
- CSS animations: Use
@keyframesandanimationfor looping motion and style changes. - SMIL animations: Use SVG’s native
<animate>and<animateTransform>elements. These require no script, and the file can be opened directly offline.
The following minimal example shows wheel rotation and a function for adjusting speed. A CSS variable controls the animation duration.
<style>:root { --speed: 1; }.wheel {transform-box: fill-box;transform-origin: center;animation: spin calc(1s / var(--speed)) linear infinite;}.wheel.paused { animation-play-state: paused; }@keyframes spin { to { transform: rotate(360deg); } }</style><svg viewBox="0 0 400 200" width="400" height="200"><circle class="wheel" cx="100" cy="150" r="30"fill="none" stroke="#333" stroke-width="4"/><circle class="wheel" cx="300" cy="150" r="30"fill="none" stroke="#333" stroke-width="4"/></svg><script>function setSpeed(value) {document.documentElement.style.setProperty('--speed', value);}</script>
Two details matter here. First, transform-box: fill-box makes the element’s own bounding box the reference for the transformation, allowing transform-origin: center to place the rotation center correctly. Second, using a CSS variable allows the duration to update without rebuilding the animation.
Evaluation Criteria
An animated SVG should be checked across the following dimensions:
| Dimension | What to Check | How to Test |
|---|---|---|
| Valid syntax | Closed tags and correct attribute names | Open in a browser and inspect the console |
| Offline operation | No external images, fonts, or scripts | Disconnect from the network and reload |
| Correct animation | Rotation centers and smooth looping | Inspect frame-by-frame screenshots or a recording |
| Working interaction | Pause, speed adjustment, and theme switching | Operate each control and record the results |
3. Task Two: Generate Realistic Lighting with Code
Asking a model to “draw a photograph with code” is more demanding than generating an animation. The code must describe geometry as well as simulate light. Two common implementation approaches are rasterization and path tracing.
Approach One: Rasterization
Rasterization uses GPU shaders to calculate pixel colors and is well suited to real-time interaction. WebGL is a common platform for this approach. Rendering shadows cast through a window typically requires shadow mapping.
The main challenges in shadow mapping are precision and self-shadowing. Without a depth-comparison bias, surfaces can develop striped artifacts known as shadow acne. Sampling only one point also produces harsh shadow edges.
The following GLSL snippet uses a bias and 3×3 percentage-closer filtering (PCF) to reduce these problems:
float shadowFactor(sampler2D shadowMap, vec4 lightSpacePos, float bias) {vec3 p = lightSpacePos.xyz / lightSpacePos.w * 0.5 + 0.5;if (p.z > 1.0) return 1.0;float texel = 1.0 / float(textureSize(shadowMap, 0).x);float lit = 0.0;for (int x = -1; x <= 1; ++x) {for (int y = -1; y <= 1; ++y) {float depth = texture(shadowMap, p.xy + vec2(x, y) * texel).r;lit += (p.z - bias > depth) ? 0.0 : 1.0;}}return lit / 9.0;}
The bias must be adjusted to the scene’s scale. Too much bias makes objects appear detached from the floor; too little leaves shadow acne visible.
A key limitation of conventional rasterization is indirect lighting. Light entering through a window can bounce repeatedly between walls and floors, which is difficult to represent with a basic rasterization pipeline. Developers commonly approximate these effects using ambient occlusion or precomputed lightmaps.
Approach Two: Path Tracing
Path tracing sends rays from the camera, follows their bounces through a scene, and averages many random paths to estimate physically plausible lighting. It produces natural soft shadows and indirect illumination, but at a substantial computational cost.
Random sampling error decreases in proportion to the inverse square root of the sample count. A small experiment illustrates this behavior:
import randomdef estimate(n: int, p: float = 0.3) -> float:hits = sum(1 for _ in range(n) if random.random() < p)return hits / nfor n in (16, 256, 4096):print(n, round(estimate(n), 4))
As the sample count increases from 16 to 4,096, estimates generally become more tightly concentrated around 0.3, although an individual run is not guaranteed to improve at every step.
Noise in a path-traced image similarly reflects insufficient sampling. Increasing the sample count by a factor of 256 reduces the typical sampling error to one-sixteenth of its previous level. Rendering time and image quality therefore do not improve in a simple linear relationship.
Color processing is also necessary at the output stage. Results calculated in linear space usually need a display transfer conversion. The following code uses a common approximate gamma correction:
float toSRGB(float linear) {linear = std::clamp(linear, 0.0f, 1.0f);return std::pow(linear, 1.0f / 2.2f);}
Although the function is named toSRGB, the power operation is an approximation rather than the exact sRGB transfer function. Missing or incorrect color conversion can make an image appear washed out or too dark.
Common Rendering Defects
Common issues to look for in scenes produced by AI-generated code include:
- Overly hard shadow edges: Often associated with insufficient sampling or missing filtering.
- Harsh lines at wall corners: Incorrect surface normals or seam handling can produce conspicuous dark lines.
- A staged appearance: Missing contact shadows and uniform material roughness can make objects look artificially placed rather than integrated into the scene.
- Uniform patches of light: Missing brightness gradients can indicate an incomplete light-intensity falloff model.
These defects are more useful as clues to specific rendering-pipeline problems than as a single judgment of whether an image “looks good.”
4. Build a Reproducible Evaluation Process
A single example says little about a model’s consistency. A more reliable evaluation follows these steps:
- Fix the input: Use the same prompt and record the model version, execution time, and tool configuration.
- Generate multiple samples: Run each prompt at least three to five times. Record the pass rate and the best and worst results.
- Score separate dimensions: Rate structure, lighting, transitions, detail, and performance individually on a scale of 1 to 5.
- Use blind review: Keep reviewers unaware of which system produced each result to reduce subjective preferences.
- Retain the original artifacts: Archive the code, screenshots, and rendering logs for later inspection.
Results from different rendering approaches should not be compared without accounting for their operating conditions. Rasterization may run in real time, while path tracing may take hours. Report rendering time separately from visual quality rather than folding it into the image-quality score.
5. Interpret Demonstrations Carefully
Public demonstration videos and screenshots are often selected from multiple attempts and may be edited afterward. Keep the following limitations in mind:
- Selection bias: Showing only successful examples overstates reliability.
- Unspecified conditions: Without rendering time, hardware configuration, and sample counts, results cannot be compared meaningfully.
- Limited reproducibility: If neither code nor prompts are available, conclusions should be treated as indicative rather than definitive.
- Overgeneralization: Performance on one scene does not establish capability across all graphics tasks.
The most reliable way to understand a model’s limits is to run it on your own task set and document failures as well as successes.
6. Engineering Recommendations
Teams using AI-generated code in graphics production should consider the following practices:
- Static validation: Check generated HTML, SVG, and shaders for syntax errors, invalid tags, and undeclared variables.
- Dependency review: Inspect external resources and unfamiliar scripts, especially when offline operation is required.
- Screenshot regression testing: Render a fixed viewpoint after each change and compare it with a reference image. Flag pixel differences that exceed a defined threshold.
- Execution isolation: Run generated scripts in a sandbox or restricted environment rather than granting direct access to local files and the network.
- Human review: Retain manual checks for lighting, perspective, proportions, and other visual qualities.
Graphics code can be generated quickly, but validating it remains costly. Building verification into the workflow early is more efficient than correcting defects after the final output has been produced.
