Writing Art with Code: A Practical Guide to Building a Programmable Brush Engine
This article explores an emerging paradigm in AI image generation where a model does not paint pixels directly but instead drives a programmable brush engine through code. It compares the diffusion-model route with the code-driven brush route, breaks down how a single stroke is computed (brush tip and bristle modeling, paint load and moisture behavior, canvas texture, and alpha compositing), and provides a minimal Python brush engine that demonstrates path sampling, jitter, pigment decay, and canvas compositing. It then covers the stroke instruction protocol models use to control brushes, painting strategies under irreversible-stroke constraints, the render–review–revise feedback loop, long-run stability, artist-persona design for consistent style, and engineering practices for running such engines in production, along with the route's current limitations and best-fit scenarios.
1. The Starting Point: When the Model Stops “Generating Images” and Starts “Wielding a Brush”
A recent AI art experiment shared by the developer community drew wide attention. The experimenters called no text-to-image model. Instead, they had a coding agent simulate a real brush and paint with code: laying down marks one stroke at a time on a virtual canvas to produce a photorealistic “shopping cart in a parking lot.” According to the experimenters, the image had no pre-rendered or traced base layer—the work was essentially a Python program written by the model, containing hundreds of thousands of stroke commands.
A second, more minimalist experiment went the opposite direction. The model could only simulate the brush’s physical properties, wet paint, and canvas texture through code. Every stroke had to be output as an individual coordinate command, and once a stroke landed on the canvas it could not be undone. The result was a 21-second video capturing the model painting “a bird at sunrise” from a blank canvas using just 111 strokes. Its first stroke used a low-saturation deep blue, a brush width of about 90 pixels, and five slightly wavering path points. The designers deliberately gave each path point about 7 pixels of sway, because even a human arm cannot draw a perfectly straight line.
Together, these two experiments point to a new technical paradigm: the model holds the decision-making power over the image, while a verified rendering codebase holds the execution power over painting. The model no longer “guesses” at an image in pixel space; instead, like a painter, it thinks about “where the next stroke goes, which brush to use, what color to load, and how much pressure to apply.” To understand this paradigm, it helps to start with how it fundamentally differs from mainstream image-generation approaches.
2. Route Comparison: Diffusion Models vs. Code-Driven Brushes
Most mainstream image-generation products today use diffusion models. Their core idea is to start from random noise and iteratively denoise under the guidance of conditions such as text, producing a complete image in “one shot.” The code-driven brush route instead decomposes creation into an ordered sequence of strokes that a procedural rendering engine composites one by one:
| Dimension | Diffusion-model route | Code-driven brush route |
|---|---|---|
| Generation method | Iterative denoising in pixel/latent space | Model outputs stroke commands; engine renders them stroke by stroke |
| Intermediate output | Denoising intermediate states (noise maps) | A traceable, reproducible stroke stream and painting code |
| Control granularity | Prompts, seeds, sampling parameters | Position, shape, color, wetness, and force of every stroke |
| Process visibility | Only the progressively denoised image | The painting process can be replayed stroke by stroke |
| Local edits | Post-processing such as repainting and inpainting | Adding covering or correcting strokes on top of existing marks |
| Real-time interaction | Single-image inference can take a while | Can render progressively and display stroke by stroke |
| Compute profile | Parallel compute concentrated in the inference stage | Light rendering compute; the hard part is long-sequence modeling |
| Main weakness | Uncontrollable process, prone to detail distortion | Hard to achieve photorealistic detail, large stroke counts |
It is worth stating plainly: the two routes are not replacements for each other; they suit different needs.
- When the goal is to quickly and cheaply produce stylized illustrations, concept art, or marketing images, diffusion models remain a mature and efficient choice.
- When a business needs an explainable process, reproducible results, and locally editable output—or needs to generate content that shows the drawing process itself (such as art tutorials, step-by-step demonstrations, or tech-style promotional videos)—the code-driven brush route has a structural advantage.
3. How a Stroke Is Actually Computed
Real painting is determined jointly by the brush, the paint, and the canvas. A brush engine’s job is to describe each of them mathematically, then composite them in a sensible order.
3.1 Modeling the Brush: Tip, Bristles, and Motion Path
- Tip shape: A round brush produces marks closer to circles or ellipses; a flat brush leaves a line-shaped mark and shows “press-and-lift” at turns, tapering to points at both ends and thick in the middle, like a willow leaf; a fan brush leaves several separate, parallel marks at once.
- Bristle structure: A finer simulation discretizes the brush head into dozens of individual bristles. Each bristle has its own position offset, paint load, and degree of wear; gaps between bristles naturally form the dry-brush (skipping) effect.
- Motion path: First define a path with anchor points, then interpolate a smooth stroke centerline via cubic Bézier curves, and finally resample at a fixed arc length. Equal-spacing sampling both lets stamps overlap evenly and lets the model use a uniform “spacing” parameter to control stroke density.
3.2 Modeling the Paint: Load, Moisture, and Blending
- Load decay: A real brush loaded once with paint can only cover a limited length, and the color fades as the tip moves. The model can make the paint load decay exponentially along the path, naturally producing a dark-to-light gradient within a single stroke.
- Moisture diffusion: Wet, high-water paint bleeds outward along the paper fibers when it lands, with soft edges and sometimes a watercolor “watermark” where the edge is darker than the center. This can be approximated with an “edge-darkening factor plus blur radius”; the lower the water content, the weaker the diffusion and the sharper the edges.
- Pigment blending: At the optical level, the Kubelka-Munk theory describes pigment absorption and scattering, while engineering practice can approximate it with a simplified subtractive model. Blending is not simple linear RGB interpolation—otherwise “muddiness” appears—and should be mitigated by raising the blend weight or converting to a more suitable color space.
3.3 Modeling the Canvas: Texture, Absorption, and Medium Differences
- Texture height field: Use procedural noise to generate a 2D height map that simulates the surface relief of paper or canvas. When compositing stamps, modulate opacity using the height map to leave fine grain inside strokes, close to how real pigment settles on a rough paper surface.
- Absorption and drying: The more absorbent the canvas, the faster the paint spreads and the softer the color; a smooth canvas keeps the paint on the surface, looking more vivid.
- Medium differences: Oil paint is viscous, has strong coverage, and can be layered repeatedly; watercolor is transparent, values negative space, and is hard to fix once laid down; sketching relies on monochrome lines and hatching for light and shade. Different media correspond to different parameter combinations and suit different styles.
3.4 The Compositing Model: Stamp Overlap and Layers
A stroke is essentially a continuous overlap of many semi-transparent “stamps” along a path, alpha-blended with the canvas’s existing color:
C_out = C_src * α + C_dst * (1 - α)
Here C_src is the current stamp color, C_dst is the color already on the canvas, and α is the stamp’s effective opacity at that pixel.
The industry-standard “source-over” compositing formula, C_out = (1 - α_b)·C_b + α_b·C_s, is essentially equivalent. The spacing between stamps determines line continuity: when spacing is less than the tip radius, the line is continuous and solid; when spacing approaches or exceeds the tip radius, stamps separate and produce a grainy or dashed effect.
In addition, engines usually support multiple layers: a bottom layer for laying in large color blocks and light-shadow relationships, a middle layer for structure, and a top layer for highlights and details. Each layer manages its own opacity and blend mode, which makes corrections easier and matches real painting’s “whole to part” order.
4. Code Practice: Building a Minimal Brush Engine
The example below uses only the Python standard library to illustrate the core mechanics. It covers four points: stroke path, jitter, paint-load decay, and canvas compositing; advanced features such as edge darkening and medium blending can be extended in the stamp function as needed:
import mathimport randomdef bezier_chain(anchors, samples=32):"""Starting from the first anchor, treat every group of 3 anchors as the control points of a cubic Bézier curve and sample a smooth trajectory."""points = []for i in range(1, len(anchors), 3):p0 = anchors[i - 1]p1, p2, p3 = anchors[i:i + 3]for k in range(1, samples + 1):t = k / samplesu = 1 - tpoints.append((u**3 * p0[0] + 3 * u**2 * t * p1[0] + 3 * u * t**2 * p2[0] + t**3 * p3[0],u**3 * p0[1] + 3 * u**2 * t * p1[1] + 3 * u * t**2 * p2[1] + t**3 * p3[1],))return pointsdef tremble(points, amplitude=7.0, freq=0.05):"""Overlay low-frequency sinusoidal jitter along the trajectory normal to simulate how a human hand cannot draw perfectly straight lines."""shaken = []for i, (x, y) in enumerate(points):a = points[max(i - 1, 0)]b = points[min(i + 1, len(points) - 1)]dx, dy = b[0] - a[0], b[1] - a[1]length = math.hypot(dx, dy) or 1.0offset = amplitude * math.sin(2 * math.pi * freq * i)# Normal vector (-dy, dx) / lengthshaken.append((x - dy / length * offset, y + dx / length * offset))return shakendef stroke(canvas, anchors, width=90, color=(48, 52, 106), wetness=0.8,spacing=0.25, decay=0.985):"""Draw a single stroke: sample points evenly in proportion to the tip radius, and stamp semi-transparent marks at each point.Does not modify the passed-in canvas; returns a new canvas, making it easy to keep drafts for comparison across multiple rounds.canvas: a 2D list where each pixel is (r, g, b); outside the canvas you can fill a paper base color."""points = tremble(bezier_chain(anchors))step = max(spacing * width / 2, 1.0) # Stamp spacing (pixels)radius = width / 2remaining, acc = 1.0, step # remaining: remaining paint load; acc: accumulated distance to the next stamplayer = [row[:] for row in canvas]prev = points[0]for curr in points:acc += math.hypot(curr[0] - prev[0], curr[1] - prev[1])prev = currwhile acc >= step:acc -= stepif remaining < 0.02: # Brush runs out of paint, tapering off naturally (dry-brush skipping)breakcx, cy = currfor y in range(max(int(cy - radius), 0), min(int(cy + radius) + 1, len(layer))):for x in range(max(int(cx - radius), 0), min(int(cx + radius) + 1, len(layer[0]))):d = math.hypot(x - cx, y - cy) / radiusif d >= 1:continue# Solid center, soft edges; adding the paper base brightness creates subtle texturealpha = wetness * (1 - d * d) * (0.96 + 0.04 * sum(layer[y][x]) / 765)src = layer[y][x]layer[y][x] = tuple(min(255, int(round(color[c] * alpha + src[c] * (1 - alpha))))for c in range(3))remaining *= decay # Paint load decays along the stroke, forming a rich-to-light transitionreturn layer
Here is how to call it. This code draws a wavering deep-blue arc, useful for demonstrating a “gradient sky band” or a “bird’s back outline”:
canvas = [[(250, 245, 235) for _ in range(960)] for _ in range(540)] # Paper-like warm-white basecanvas = stroke(canvas, anchors=[(60, 180), (260, 120), (420, 160), (900, 130)],width=90, wetness=0.85, decay=0.99)
This illustrative code deliberately stays simple so readers can see the full chain: “path sampling → jitter perturbation → stamp overlap → paint-load decay.” In the example, every step truncates with int() and quantizes colors with rounding. A production-grade engine would at least need to add the following:
- Use premultiplied-alpha floating-point buffers as the internal representation to avoid banding and accumulated error from repeated quantization, converting to 8-bit integers only at final output.
- Use a blur kernel to implement wet diffusion, and a height-map threshold to implement dry-brush skipping.
- Redraw only the “dirty rectangles” covered by each stroke instead of iterating over the whole canvas for every stroke.
5. From “One Stroke” to “One Painting”: How the Model Wields the Brush
5.1 Stroke Instructions: the Model’s Output Protocol
The engine needs to expose a set of parameters to the model with clear semantics and well-defined ranges. The table below shows a typical set of stroke-instruction fields:
| Field | Meaning | Values and constraint examples | Design intent |
|---|---|---|---|
layer |
Layer it belongs to | underpainting / midtones / details |
Controls drawing order and overlap relationships |
brush |
Brush type | round / flat / fan / dry |
Corresponds to different tip shapes and bristle structures |
points |
Path anchors | 1–5 points; each coordinate within the canvas bounds | Controls stroke count and shape complexity |
width |
Brush width (pixels) | 1–128 | Thin brushes for distance and detail, thick for large color blocks |
color |
Color | Hex color value | Maps directly to pigment color |
wetness |
Wetness level | 0–1 | Controls diffusion radius and edge sharpness |
tremble |
Jitter amplitude (pixels) | 0–10 | Simulates hand tremor; shorter lines should have smaller jitter |
Take the first stroke of “a bird at sunrise,” for example—it can be encoded as an instruction like this:
{"layer": "underpainting","brush": "round","points": [[160, 300], [175, 285], [190, 278], [205, 276], [220, 282]],"width": 90,"color": "#30346a","wetness": 0.75,"tremble": 7}
With such a protocol, what the model outputs is no longer hard-to-control pixels but a readable, verifiable, versionable painting script. Before instructions reach the engine, they should pass parameter validation, canvas-bound clipping, and path-length checks to avoid rendering anomalies from invalid commands.
5.2 Painting Strategy Under Irreversible Constraints
“Not being able to undo a stroke” is one of the most valuable designs in these experiments. It forces the model to think like a real painter rather than rely on unlimited trial and error. A few rules from human painting transfer directly to agents:
- Whole to part: First use large, low-saturation strokes to lay in big color blocks like sky and ground, then gradually reduce brush size to render details.
- Dark before light: Dark tones build volume; light tones brighten and accent. Putting light over dark easily looks muddy and is harder to cover.
- Leave room: Don’t commit an outline fully in one stroke—later you can still cover and adjust it with ambient color.
- Control rhythm: Stroke length, spacing, and jitter amplitude vary with the image scale. Foreground strokes can be long and continuous; background strokes should be short and broken.
For “a bird at sunrise,” a reasonable progression is:
- Use wide, wet strokes to lay in a gradient sky from warm orange to cool purple, bottom to top.
- Use a mid gray-purple to block in the bird’s silhouette and the dark areas of the ground.
- Use a thin brush to trace the contours of the beak, claws, and tail feathers, and the direction of the branch.
- Use a few high-transparency warm strokes to mark the rising sunlight and the lit areas of the feathers.
- Finally, use a thin dry brush to sweep out feather texture.
5.3 The Observe–Revise Loop: Letting the Model “See” Its Own Painting
Across multiple rounds, the model needs to review the current result like a painter stepping back. A common closed-loop flow looks like this:
def paint(engine, budget=8000):plan = engine.plan(1200) # Model outputs the first batch of strokes: lay in large color blocks and light-shadowfor round_no in range(6):engine.render(plan) # Engine renders deterministically, ensuring reproducibilitypreview = engine.preview(256) # Downsampled thumbnail for the model to "look at" the current imagenotes = engine.review(preview) # Compare against the target and check for issues, e.g., overly thin bird back, messy linesif not notes or len(plan) >= budget:breakplan += engine.plan(400, feedback=notes) # Generate correcting strokes based on the feedbackreturn engine.canvas()
Combined with the original experiment, the model’s multi-round painting usually follows this pattern:
- The model first observes the current canvas (typically a downsampled thumbnail) and identifies obvious defects.
- When it finds the bird’s back is drawn too thin and the lines look messy, it does not try to “erase.” Instead, it re-covers along the original outline with a wider brush whose color is closer to the surrounding environment, then layers fine strokes for adjustment.
- Correcting strokes themselves also require planning placement and force—the whole process remains “add-only, never remove.”
Two easily overlooked engineering points here:
- Thumbnail observation: When letting the model “look at” the painting, the original resolution is often far beyond the image size the model can accept in a single call. Downsampling to a thumbnail of a few hundred pixels square both covers the overall composition and keeps the input size manageable.
- Local cropping: When checking details, crop and enlarge the relevant region, forming a “global–local” combined observation strategy.
This “render–observe–revise” loop essentially lets the model iterate within closed-loop feedback, closely aligned with the agent’s basic “plan–act–reflect” paradigm.
5.4 Long-Run Stability: Context and Cost
Stroke counts range from 111 to hundreds of thousands, meaning the model’s output span can reach tens of thousands to hundreds of thousands of tokens, which raises the bar for long-sequence modeling:
- Structured output: Outputting JSON stroke by stroke is easier to parse, validate, and resume from checkpoints than continuous text; once a format error is found, you can have the model resend only that stroke.
- Batch progression: Divide painting into stages such as “block in—shape—render—finish,” each planned and validated independently, avoiding generating all instructions at once.
- Idempotent rendering: Given the same stroke stream and random seed, the engine should render exactly the same image, making it easy to reproduce problems.
- Cost and quotas: High-frequency output significantly affects call quotas and fees, so it needs unified management combined with budget, rate limiting, and caching strategies.
6. From “Imitation” to “Style”: Designing an Artist Persona
One of the most interesting byproducts of these experiments is that models begin to develop a relatively independent artistic style. In early practice, some works drew “imitation” criticism for looking too close to existing art movements—which shows that style consistency must be actively designed, not passively inherited.
An effective approach is to have the model first design an “artist persona”: one with a fictional background, preferred subjects and colors, and a relatively stable set of technique habits, including habitual brushes, stroke rhythm, and color-mixing logic. Only after the persona is set does painting begin, and based on the visual result, text feedback guides the model to adjust brush parameters and engine configuration. You can think of it as “prompt-driven workflow optimization”: the persona handles style direction, and the feedback loop handles parameter convergence.
A persona prompt can be organized along the following structure:
You are the painter "Lin Yu." You grew up in a seaside town and are used to observing light changes at dawn and dusk.Your creative preferences:- Subjects: natural and everyday scenes, favoring backlight- Colors: mainly low-saturation warm tones; cool tones only for dark areas- Strokes: wide, wet strokes for mid- and far-ground color blocking; thin dry strokes for foreground outlines- Taboos: no high-purity fluorescent colors, no repeatedly stacking dark tones in the same areaPlan the painting steps based on the settings above; after each batch of strokes is output, wait for my image feedback.
To build a stable feedback loop, pay attention to a few points:
- Be specific with feedback: Don’t just say “looks good overall”—point out actionable issues like “the sky is too gray, the beak too thin, the lower-left corner too heavy,” so the model knows which parameter to adjust.
- Converge parameters: Maintain a “symptom → adjustment” mapping for each type of issue, such as “stiff lines → increase jitter amplitude” and “colors look muddy → increase saturation or lower the white-mixing ratio,” to avoid the model changing parameters arbitrarily each time.
- Solidify style: Distill validated parameter combinations into reusable “style profiles” as default configurations for future creation.
- Hold the line on boundaries: Persona settings should stay original and should not ask the model to imitate the personal style of a specific living artist. This both respects creators’ rights and helps form a genuinely original visual language.
7. Engineering Deployment: Running a Brush Engine in Production
7.1 Decoupling the Engine from the Model
A brush engine is a deterministic program module that only receives stroke instructions and renders a canvas. The model makes decisions and does not participate in rendering compute. This means:
- The engine can be covered by unit tests to ensure correct stroke rendering;
- Swapping the underlying model requires no engine changes;
- The rendering service can scale independently.
7.2 Performance Optimization
- Dirty-rectangle updates: Redraw only the regions covered by a stroke; the finer the stroke, the greater the benefit.
- Downsampled previews: Generate a low-resolution preview during painting for observation and frontend display, then render the final high-res image.
- Parallel tiled rendering: Divide the canvas into non-overlapping tiles for parallel rendering, taking care with strokes that cross tile boundaries.
- Profiling and progressive enhancement: First use profiling tools to locate time-consuming hotspots, then decide whether to introduce vectorization or GPU acceleration; meanwhile, provide “draft—standard—high-res” quality tiers to balance latency and quality.
7.3 Storage and Scheduling
- Stroke-stream persistence: Append strokes line by line in JSON Lines format, which naturally supports checkpoint resume and incremental rendering, and lets you save the painting code along with the artwork as a “source file.”
- Object storage: Store original artwork, stroke streams, and thumbnails for easy distribution and further processing.
- Message queues: Decouple “painting-task submission” from “stroke rendering” to smooth out spikes.
- Container platforms: Deploy rendering services in containers and scale elastically by task volume.
7.4 Observability and Quality Assurance
- Monitoring metrics: stroke count, per-stroke rendering time, model-call success rate, task completion time.
- Logging: Record the generation and validation result of each stroke batch, making it easier to trace problematic images.
- Alerting rules: Notify promptly when stroke counts spike abnormally, rendering failure rates rise, or tasks back up.
If building such a system on Baidu AI Cloud, you could use a container platform to host rendering services, object storage to store artwork and stroke streams, message queues to schedule painting tasks, and logging with monitoring alerts to continuously observe generation quality. All products should be understood per their official documentation; this article makes no specific performance claims.
7.5 Cost and Rate Limiting
- Caching: Cache stroke-generation results for requests with the same persona and same feedback to avoid repeated calls.
- Budget control: Set stroke-count and call-count caps per painting; once the cap is reached, shift to human review or auto-finish.
- Multi-model collaboration: Use a model with stronger reasoning for the planning stage, and switch to a lighter model for simple brush generation to reduce cost.
8. Limitations and Applicability Boundaries
To view this route rationally, we need to acknowledge its current shortcomings:
- Photorealistic detail is hard: Tens of thousands of strokes are manageable, but stroke sequences in the hundreds of thousands severely test a model’s planning ability, and micro-details like fur and skin texture still fall short.
- Long-run planning errors accumulate: Strokes cannot be undone, so early mistakes are amplified by later strokes, requiring more robust layered planning and backtracking mechanisms.
- Rendering performance challenges: Stroke count and image resolution together determine the compute; traditional per-pixel Python implementations struggle to meet real-time requirements.
- The boundary of style originality: Even with a fully fictional persona, we must stay alert to outputs that overly resemble existing works.
In terms of scenarios, this route is currently best suited for:
- Interactive applications that need to show the “creative process,” such as art education, children’s art learning, and creative marketing interactions;
- Batch production of illustrations, icons, and texture assets that need consistent style and controllable detail;
- Design and research work where the artwork needs to be editable, reproducible, and versionable.
For scenarios that pursue extreme realism, require fast single-image output, or need complex light-and-shadow simulation, diffusion models remain the more pragmatic choice.
9. Conclusion
From the 111-stroke “sunrise bird” to the hundreds-of-thousands-stroke “shopping cart in a parking lot,” painting with code reveals an important trend: the model’s role is shifting from “content generator” to “tool user” and “process planner.” The brush engine encodes the physics of painting into reliable code, while the model focuses on composition, color, and stroke decisions. Their division of labor forms an explainable, controllable, reproducible creative loop.
For developers, rather than waiting for a “better painting model,” it is better to build your own brush engine and feedback loop. Starting from a small scenario and a set of stroke instructions, then gradually layering in moisture diffusion, canvas texture, and an artist persona, you can turn “painting with code” from an experimental demo into a deployable product capability.
