Code-Driven Painting with LLMs: Simulating Real Brushstrokes Through Code
This article examines an alternative image-generation paradigm in which an LLM writes code to simulate real brushstrokes on a virtual canvas instead of calling an image-generation model. It compares this process-oriented approach with diffusion models, breaks down the core modules of a simulated painting engine, discusses the non-revocable stroke constraint and its implications for planning and correction, explores how explicit code control can support original style construction, and outlines key engineering considerations for practical deployment.
Code-Driven Painting with LLMs: Simulating Real Brushstrokes Through Code
Introduction: Two Technical Routes for AI Image Generation
When people think of AI-generated images, most immediately think of diffusion models: starting from random noise, running multiple denoising iterations, and eventually “emerging” with a complete image. This route is highly mature and widely used by mainstream text-to-image tools.
Recently, however, the industry has seen another instructive approach: do not call any image-generation model; instead, have a large language model write code that simulates the movement of real brushes on a virtual canvas, painting the image stroke by stroke. The model outputs not pixels, but hundreds or thousands of lines of brush-control programs; the image is a byproduct of running the program.
The significance of this paradigm is that it turns “generating an image” from a black-box sampling process into an interpretable, plannable, and auditable sequence of decisions—exactly the kind of problem large language models excel at. This article breaks down this route across four layers: technical principles, engine design, constraint mechanisms, and engineering practice.
1. Diffusion Models vs. Stroke-Based Painting: A Fundamental Paradigm Difference
To understand the value of code-driven painting, we first need to see the essential difference between the two paradigms:
| Dimension | Diffusion Models | Code-Simulated Brushstrokes |
|---|---|---|
| Generation unit | Pixels/latent variables of the whole image | Single-stroke instructions |
| Process interpretability | Low (black-box iteration) | High (each stroke has explicit coordinates, color, and brush width) |
| Creation order | Globally formed at once | Similar to human painters: background to subject, blocking in to detail |
| Style source | Training data distribution | Can be explicitly programmed and constrained by prompts |
| Error correction | Resample | Overlay new strokes to cover and correct, consistent with human painting |
| Compute cost | Several inference steps | May involve hundreds of thousands of stroke simulations, but no GPU diffusion inference |
Diffusion models are “result-oriented”: they do not know or care how an image was painted; they only learn statistical patterns in pixel distributions. Stroke-based painting is “process-oriented”: the model must think like a painter—first lay in large color blocks to set the tone, then gradually define structure and detail, and finally finish with highlights and edge treatment.
In one demonstrated case, a frontier language model was asked to create a work approaching photo-realistic quality. It ultimately painted a scene of shopping carts in a parking lot, using about 700,000 simulated brushstrokes in total, all driven by programs the model wrote autonomously (typically on the order of 1,000 to 2,000 lines of code), without relying on any external image model and without tracing a base image.
2. Simulated Painting Engine: Core Modules
Code-driven painting depends on having a sufficiently “physical” painting engine. The quality of the engine directly determines whether the work can move beyond the stiffness of vector graphics and approach the texture of real hand-drawn art. A usable engine typically includes the following modules:
1. Brush Model
A brush is not a point, but a bundle of shaped “bristles.” Key parameters include:
- Brush width and shape: round, flat, fan-shaped, etc., determining the stroke cross-section;
- Texture: irregular edges caused by gaps between bristles, which can be implemented by overlaying noise functions;
- Pressure sensitivity: pressure at different positions along the path affects brush width and pigment concentration.
2. Paint Model
In real painting, paint mixes, dries, and accumulates. The engine needs to simulate:
- Wetness: wet paint landing on a wet underpainting spreads and blends (watercolor-like), while dry paint overlays;
- Color mixing: new paint blends with existing canvas color according to opacity, rather than simply replacing it;
- Paint load: as a stroke is drawn, paint gradually depletes, and the stroke fades from dense to light—this is the source of the “dry brush” feel.
3. Canvas Model
The grain texture of the canvas causes pigment to adhere unevenly, creating subtle light and dark variation. Typically, a pre-generated noise texture image is used to slightly modulate color when a stroke lands.
4. Path and Jitter
Human arms cannot draw absolutely straight lines. The engine (or the model itself) needs to add pixel-level random perturbation to path points—in one case, the model deliberately added about 7 pixels of wobble to a path precisely to eliminate a mechanical feel.
A minimal engine interface sketch is as follows:
class Stroke:color: str # e.g., "#30346a"brush_width: int # brush width in pixelswetness: float # 0.0~1.0 paint wetnesspressure: list # pressure at each path pointpath: list # [(x1,y1), (x2,y2), ...] path pointsdef render_stroke(canvas: Canvas, stroke: Stroke):"""Lay down paint point by point along the path, handling blending, load depletion, and canvas texture"""for i, (x, y) in enumerate(stroke.path):load = paint_remaining(stroke, i) # paint load depletionjittered = apply_hand_jitter(x, y) # hand jitterblended = mix(canvas.at(jittered), stroke.color,alpha=load * stroke.pressure[i])canvas.set(jittered, texture_modulate(blended, canvas.texture))
3. The Non-Revocable Constraint: Letting the Model “Make Mistakes and Correct Like a Human”
One interesting experimental setting is: once a stroke lands on the canvas, it cannot be undone. The model must output each stroke as an independent, irreversible decision.
This constraint seems harsh, but it is highly meaningful:
- Forced planning ability: The model must first think through the compositional layers of the whole painting (background → midground → subject → detail), then decide stroke order; otherwise, once a large color block is laid down incorrectly, it cannot be undone.
- Encouraging real “correction techniques”: What happens when a mistake is made? Just like a real person—cover it with new strokes, blend incorrect edges into shadows, or adjust the composition by turning the error into an intentional choice. This “error-driven re-creation” is precisely a source of naturalness in artistic work.
- Auditable output: Every stroke is a parameterized instruction and can be replayed stroke by stroke. In one experiment, a bird-at-sunrise image composed of 111 strokes was recorded as a 21-second painting-process video, from the first deep-blue underpainting stroke (90-pixel brush width, containing 5 slightly wavering path points) to the final highlighted feathers, with the entire process clearly visible.
4. Shaping Artistic Style: From Imitation to a “Self-Created Persona”
Code-driven painting also unexpectedly touches on a sensitive issue in AI art: style plagiarism. Some model-generated paintings have previously been criticized for over-imitating specific existing artistic styles.
The stroke-based route offers a more elegant solution: since every stroke is explicitly controlled by code, style is no longer a “learned statistical preference” from training data; it can be explicitly designed and constrained. One approach shown to be effective is:
- Have the model build a fictional “artist persona”—including a fictional biography, creative philosophy, preferred subjects, and color habits;
- Use the persona as an anchor to stabilize style: multiple works under the same “persona” maintain a consistent brushstroke language;
- Iteratively tune parameters through textual feedback: based on the work’s effect, feed back to the model to adjust brush types, blending strategies, and engine parameters, forming a “creation—evaluation—adjustment” loop.
The implication for engineering teams is that style control does not necessarily depend on fine-tuning or massive samples. Through a combination of system prompts and generation strategies, it is also possible to achieve a stable and original visual language in procedural generation scenarios.
5. Key Engineering Considerations for Deployment
To use this approach in practical systems (such as creative assistance tools, procedural illustration generation, and teaching demonstrations), several engineering issues still need to be addressed:
- Cost and latency: Hundreds of thousands of strokes mean a large amount of token generation. It is necessary to evaluate the token budget for a single painting and, when needed, use staged generation with a “draft layer (large strokes for blocking in) + refinement layer.”
- Deterministic reproduction: Random jitter and noise should use a fixed random seed to ensure that the same program output can be reproduced.
- Rendering performance: The engine can use vectorized array operations to accelerate paint blending; for large-canvas scenarios, tiled rendering can be considered.
- Artifact storage and distribution: Generated programs and rendering results can be stored in object storage, combined with content delivery and monitoring/alerting capabilities to build a stable online service.
- Quality evaluation: Establishing an automated review step (for example, letting the model self-evaluate intermediate results and decide the next stroke order) has a higher success rate than generating all instructions at once.
Conclusion
“Having a language model write code to paint” is not a replacement for diffusion models, but a paradigm complement: it trades a black-box generation process for planning, controllability, and process aesthetics that black-box generation does not provide. For developers, the real value of this route is that it demonstrates—when a generation task is reformulated as a serialized code decision problem, the capability boundary of large language models is far broader than often imagined. In the future, as the physical realism of simulation engines improves and multimodal feedback loops are introduced, procedural painting may become a distinctive “brush” in the AI creative toolbox.
