Painting With Code: How to Simulate Brush Strokes Stroke by Stroke Without Calling an Image Model
This article examines a code-driven approach to image generation that skips diffusion and image-generation models entirely. A large language model (LLM) first writes a program that simulates brushes and paint, then lays down strokes one by one on a virtual canvas until an image emerges. We break down the underlying architecture—a virtual canvas with a color model, a brush engine that models the interaction among brush, pigment, and canvas, and an LLM that runs a plan–render–observe–revise loop. Along the way you'll find a runnable Python example of stroke physics, practical lessons on irreversible strokes and feedback loops, engineering concerns around rendering performance and reproducibility, and a clear-eyed view of the method's limitations and possible improvements. The takeaway: code-driven painting trades speed for a transparent, controllable, and reproducible creative process.
Recently, a practice of “drawing with code without calling an image generation model” has been drawing attention in the community. An LLM first writes a program that simulates a brush and paint, then runs that program to lay down strokes one by one on a virtual canvas, eventually producing a picture. Some developers have publicly shared a set of such experiments: one near-photorealistic image was built from roughly 700,000 brush strokes; another, “a bird at sunrise,” was written stroke by stroke using coordinate commands from the model—and once a stroke lands, it can’t be undone.
It’s clear that code-driven painting is not simply about “generating a piece of code.” It’s a systems-engineering effort that involves color mixing, brush physics, stroke planning, and iterative correction. This article breaks down how this approach works, how to implement it, and what matters in practice.
1. Rethinking “AI image generation”
When people discuss “AI image generation,” they usually assume it means calling a dedicated image generation model. In fact, there’s a less-discussed path for LLMs to produce images: instead of relying on any built-in painting capability, break painting down into a series of instructions that can be inspected, executed, and corrected one at a time, then hand them to a program to render on the canvas. This approach has two intuitive characteristics:
- Visible: For every stroke, you can separately inspect what color it used, where it landed, and what width and tilt angle swept across—effectively preserving the entire creative process.
- Intervenable: The model can “look back” at the canvas during drawing, spot problems with proportions, lines, or color, and adjust them with new strokes.
This means the generated image is no longer just an untraceable pile of pixels, but a program with a clear structure that is reproducible and can be optimized step by step.
2. The essential difference between two image-generation paradigms
Diffusion-model-based text-to-image solutions learn a mapping from “noise to image.” Starting from random noise, the model denoises step by step under text-conditioning guidance, finally decoding finished pixels in latent space. Its strengths are fast output and rich imagery. Its weakness is that the generation process is a “black box” to the user: you can’t ask it to make a particular line a bit thinner, and it’s hard to precisely control the direction and pressure of a stroke.
Code-driven simulated painting takes a different road, reducing painting to a physical process:
- The model first plans the overall composition, color scheme, and drawing order of the piece at the “thinking” level.
- It then translates each stroke into structured instructions, including brush type, color, width, path points, pressure, and wetness.
- A program deposits pigment onto canvas pixels according to physical rules.
- The model reads the current canvas state, decides how to place the next stroke, and repeats.
The table below compares the two paradigms across several dimensions:
| Dimension | Diffusion-based text-to-image | Code-simulated brush painting |
|---|---|---|
| Intermediate output | Latent variable tensors | Stroke instruction sequence + drawing program |
| Granularity of intervention | Prompts, parameters | Attributes and position of any single stroke |
| Reproducibility | Affected by random seed and implementation details | Deterministic code and seed; results are reproducible |
| Iteration method | Regenerate or inpaint | Continue laying strokes on the existing image |
| Error handling | Rely on the model to resample | Patch specific strokes |
| Compute cost | Relatively concentrated at inference time | Many strokes, longer rendering time |
The code approach offers stronger controllability, at the cost of slower output and a huge number of strokes. It’s better suited to scenarios that need precise control and traceable modification.
3. Architecture breakdown: what makes up a “program that can paint”
Handing painting to code essentially means building a “virtual painting engine,” with the LLM serving as this engine’s “operator.” The whole process breaks into three layers.
3.1 The virtual canvas and the color model
The canvas is the foundation of the entire system and needs to answer at least three questions: how to represent color, how to store pixels, and what happens when pigments overlap.
For color, the most direct approach is to use RGB space, but if you want natural transitions, it’s better to use linear-light space for intermediate calculations. This is because the brightness perceived by the human eye is not linearly related to physical light intensity; averaging directly on sRGB values makes colors too dark. A common practice is to first gamma-decode sRGB values (exponent around 2.2) to get linear values, do the mixing, then encode back to sRGB.
Pigment overlap requires distinguishing two classic models:
- Additive model: simulates the superposition of light, suited to emissive scenes like screens and lighting, with red, green, and blue as the primaries.
- Subtractive model: simulates pigments absorbing light, ideally with cyan, magenta, and yellow as the primaries; the more that overlaps, the darker the color, approaching black.
Strictly simulating pigment mixing can use Kubelka-Munk theory, which describes the optical behavior of a pigment layer based on the absorption coefficient K and the scattering coefficient S, but it’s computationally expensive. A more common engineering compromise is “weighted averaging”: first compute a weighted average of each pigment’s light absorption, then convert back to RGB. Its result falls between directly averaging RGB and strict K/S mixing—simple to implement and visually fairly natural.
3.2 The brush engine: the interaction among brush, pigment, and canvas
The brush engine is the most core module of the whole solution and needs to simulate three types of objects:
- Brush: determines the shape and distribution of pigment. Common parameters include tip shape (round, flat, fan), number and hardness of bristles, bristle stiffness, and tilt angle. Bristle stiffness affects how the tip bends and springs back, while the tilt angle determines the color depth on either side of the stroke.
- Pigment: needs to record each pigment layer’s color, opacity, thickness, and “wetness.” Freshly laid, wet pigment is more easily dragged and bled by subsequent strokes, while dried pigment behaves more like coverage.
- Canvas: surface texture determines how pigment adheres. On a textured canvas, pigment tends to pile up on raised fibers while recessed areas stay blank—this is the source of the “grain” in watercolor and oil painting.
Put the three together, and each stroke’s rendering can be summarized as: sample the brush cross-section along the path according to pressure, compute which pixels each sample position covers, then composite with canvas pixels according to the pigment model above.
3.3 The LLM: from “intent” to “stroke instructions” and then “evaluation”
In this architecture the LLM plays the role of “artist,” responsible for three actions:
- Planning: first conceive the overall image—for example, the subject, the light-source direction, the light-and-dark distribution, and the color tone.
- Laying strokes: translate the concept into structured instructions stroke by stroke. Each instruction usually needs to include brush type, color, width, pressure sequence, path control points, and wetness.
- Observing: at key points, feed the current canvas state back to the model—it can be a thumbnail, a zoomed-in region, or simple statistics (such as the image’s brightness distribution)—so the model can judge “where the next stroke should go.”
This is a typical “generate–execute–observe–revise” loop, in which the model is both the painter and its own reviewer.
4. Code example: the physics of a single stroke
To illustrate how the brush engine works, here’s some illustrative code that breaks a stroke into three stages—path, pressure, and color deposition:
import mathdef gamma_to_linear(c): # convert sRGB to linear lightreturn (c / 255.0) ** 2.2def linear_to_gamma(c): # convert linear light back to sRGBreturn int(round(255.0 * (c ** (1 / 2.2))))def mix_paint(base, pigment, alpha, absorption):"""Subtractive mixing based on weighted-average absorption"""# base/pigment are (r,g,b) tuples; absorption is the pigment's light-absorbing strengthout = []for b, p in zip(base, pigment):lb, lp = gamma_to_linear(b), gamma_to_linear(p)k = absorption * (1.0 - lb) * (1.0 - lp) # simplified light-absorption approximation# the higher the absorption weight, the darker the resultmixed = lb * (1 - alpha) + lp * alpha * (1 - k)out.append(linear_to_gamma(max(0.0, min(1.0, mixed))))return tuple(out)def sample_bristle(t, brush):"""Sample bristles along the brush width: t is in [0,1]"""center = 0.5dist = abs(t - center)# bristles near the center take more load, laying down more inkload = (1.0 - dist) ** brush["softness"]return max(0.0, min(1.0, load * brush["ink"]))def draw_stroke(canvas, points, color, width, wobble=0.0, seed=0):"""Draw a stroke on canvas with wobble and wetness effects"""x, y = points[0]for i in range(1, len(points)):nx, ny = points[i]steps = max(1, int(math.hypot(nx - x, ny - y) / max(1.0, width / 4)))for s in range(steps):f = s / stepspx, py = x + (nx - x) * f, y + (ny - y) * f# add slight sinusoidal jitter to mimic subtle hand instabilityjitter = wobble * math.sin((i + f) * math.pi * 2)deposit(canvas, px + jitter, py - jitter, color, width)x, y = nx, nydef deposit(canvas, x, y, color, width):"""Deposit the brush cross-section onto canvas pixels"""x0, y0 = int(x - width), int(y - width)x1, y1 = int(x + width), int(y + width)for py in range(max(0, y0), min(canvas.height, y1)):for px in range(max(0, x0), min(canvas.width, x1)):d = math.hypot(px - x, py - y)if d > width:continuet = d / width # position along the brush-width directionload = sample_bristle(t, canvas.brush)if load <= 0:continue# canvas texture: recessed areas hold less ink, creating graintexture = 0.6 + 0.4 * canvas.texture(px, py)alpha = load * texturecanvas.pixels[py][px] = mix_paint(canvas.pixels[py][px], color, alpha, 0.5)
This code reflects three key design choices:
- A stroke is not a line, but a distributed patch of pigment: bristle sampling lets the edges of a stroke transition naturally instead of looking like a rigid vector line.
- Jitter is deliberately introduced: a moderate amount of randomness avoids a mechanical feel, but the jitter amplitude should be proportional to the stroke width; otherwise visible aliasing appears.
- Color mixing and canvas texture together determine the “feel”: the same color and path yield completely different visual effects on canvas surfaces with different textures.
5. Key practical details
5.1 How the first stroke sets the tone for the whole image
The publicly shared experiment showed that when drawing “a bird at sunrise,” the model’s first stroke chose a deep blue-purple (#30346a), a stroke width of about 90 pixels, and a path with 5 control points carrying slight undulations. Three design choices here are worth borrowing:
- Starting color: choosing deep blue-purple fits the cool tone of the sky before sunrise while leaving room for later warm gradients.
- Stroke width: a wide 90-pixel stroke suits laying down large color blocks, first fixing the broad light-and-dark relationships of the sky rather than getting bogged down in detail from the start.
- Path jitter: the roughly 7-pixel sway from 5 path points is meant to simulate the human arm’s inability to draw a perfectly straight line. This “imperfection” is precisely an important source of the image’s naturalness.
As for drawing order, it generally follows the principle of “large before small, dark before light, background before subject,” which aligns closely with traditional painting order.
5.2 Irreversibility and feedback: why the model “edits while drawing”
In that experiment, a stroke couldn’t be undone once laid down, which is closer to real painting. The model’s coping strategies include:
- Cover-up correction: when a line is found to be too thin or messy, cover or deepen it with new opaque strokes rather than erasing.
- Observe–evaluate loop: after completing a number of strokes, the model checks both local and overall regions of the current canvas and decides whether adjustments are needed.
- Constrained feedback: if the image shows imbalanced proportions, prompt-level constraints such as “don’t make the bird’s back too thin” can guide the model to converge.
The advantages of this approach are a trustworthy process and explainable results; the cost is a higher risk of accumulating errors. That’s why an intermediate-snapshot mechanism is needed, so you can roll back to some “healthy state” and continue painting when things drift from expectations.
6. Engineering implementation
6.1 Performance: number of strokes and rendering time
The biggest bottleneck in code-based painting is often not model generation speed but rendering. A single stroke contains hundreds of sample points, each involving pixel-level color-mixing math; when the total number of strokes reaches the tens of thousands or hundreds of thousands, a naive Python implementation may take anywhere from several minutes to tens of minutes. Common optimization directions include:
- Layered compositing: render background, subject, and detail layers separately, then composite them.
- Vector first: describe paths with Bézier curves or splines, doing pixel-level deposition only when necessary.
- Batching and caching: cache recurring brush shapes to avoid recomputing textures.
- Hybrid backends: push per-pixel computation down into C extensions or GPU shaders, keeping only Python as the scheduling layer.
6.2 Reproducibility and observability
Because each stroke is a structured instruction, code-based painting is naturally suited to “recording the process”: log every instruction, every model call, and every revision, and you can fully reconstruct a painting’s creation path. This is clearly valuable in scenarios like teaching, art restoration, and style transfer. Combined with object storage for intermediate canvas snapshots and a message queue to decouple the “plan–execute–render” pipeline, you can build an elastically scalable asynchronous drawing pipeline.
6.3 Shaping style: giving the model its own “brush personality”
In multiple cases, the model displayed a “make mistakes first, then correct” behavior pattern, such as lines being too thin or stroke directions being chaotic. Retaining these traits in the final image instead forms a recognizable “painting personality.” If you want to shape style further, you can approach it from three directions:
- Define an “artist profile”: give the model a fictional creator identity, including background, aesthetic preferences, and commonly used color palettes and brushes; the model will maintain a stable style around this profile.
- Make style constraints explicit: writing preferences such as “restrained use of color,” “preference for dry brush,” and “slightly jittery lines” as tunable parameters is more controllable than relying on prompts alone.
- Keep a preference log: retain an effect score and the reason for each adjustment per iteration, forming a traceable style-evolution log.
7. Limitations and directions for improvement
Code-simulated painting is not a cure-all and still has several clear shortcomings:
- Slow output: the computation for stroke-level simulation is far greater than a single image generation.
- Reliance on the model’s “spatial intuition”: the model’s understanding of proportion, perspective, and occlusion is still limited, so structural errors can easily appear.
- Lack of global optimization: greedily “patching wherever something is missing” one stroke at a time can lead to regions that are locally reasonable but globally imbalanced.
To address these, you could: introduce a two-stage “rough draft–refinement” flow that first fixes composition with low-resolution color blocks and then refines stroke by stroke; transfer the model’s spatial reasoning to 3D scene layout and use geometric constraints to reduce structural errors; and introduce global objectives at the rendering stage (such as overall contrast or edge density) so the drawing process gains an optimization loop.
8. Summary
Handing painting to code essentially transforms “generating an image” from a one-shot black-box inference into an observable, intervenable, reproducible stroke pipeline. Its core components are the virtual canvas, the brush engine, and the model’s closed-loop feedback. Its value lies not in replacing text-to-image models, but in offering an alternative path that is “transparent in process and controllable in result.” For developers who want to understand the boundaries of generative AI, this paradigm is a reminder: when a model is given a finer-grained action space, it can do more than “output a piece of text or an image”—it can “build a work step by step, like a human.”
