Stroke-by-Stroke Drawing: A Technical Look at Code-Based Painting with Large Models
This article explains how large models can approach image creation not as a single forward pass but as an executable drawing program, where each brush stroke is emitted as code and rendered step by step. It covers the full pipeline of intent parsing, action planning, execution, observation, and correction; the structure of a stroke instruction including coordinates, color, width, opacity, wetness, and brush type; and how structured self-checks let the model fix mistakes by adding覆盖 strokes rather than undoing them. It also discusses engineering practices such as treating code as the deliverable, keeping intermediate canvas states, and encoding constraints as hard rules, followed by a comparison with diffusion-based pixel generation, common misconceptions, and the broader methodology of decompose, parallelize, verify, and merge.
1. The Starting Point: When Image Generation Is More Than One Forward Pass
Most mainstream image generation approaches treat “generation” as a one-shot tensor transformation: text or initial noise goes in, passes through multiple network layers within one or a few iterations, and comes out as a tensor the size of the canvas, which is then encoded into pixel colors. This path is end-to-end and high-throughput, but the process is invisible, non-interventable, and non-reversible—the model delivers only the result, not the “how it was drawn.”
Another approach treats painting as an executable program: the model outputs drawing code that describes the brush, the paint, the canvas, and the motion trajectory of each stroke. The image only gradually “grows” when that code is executed. The difference is not about which one draws better, but about the level of abstraction: the former solves the problem at the pixel level, the latter at the action level.
Working at the action level brings three direct benefits:
- Explainability: Every stroke has explicit semantics (color, width, coordinates, opacity) and can be traced, reproduced, and debugged step by step.
- Correctability: If a stroke is wrong, you add another stroke to cover it or layer color on top, matching how humans “revise—cover—adjust” when painting.
- Constrainability: The number of strokes, paint wetness, maximum stroke width, and similar limits can be written into the code or validation logic as hard constraints, instead of relying on prompt “prayers.”
2. The Overall Pipeline: Plan, Execute, Observe, Correct
Programmatic painting is not “write all the code in one go,” but a multi-turn closed loop:
(Blank canvas)│ 1. Intent parsing: translate "what to draw" into scene structure and a layer list▼(Scene plan: background / subject / lighting / details)│ 2. Action planning: determine stroke order (large areas before details, far before near)▼(Stroke sequence: coordinates + color + brush parameters + wetness)│ 3. Execution: render stroke by stroke, each stroke irreversible▼(Intermediate frame)│ 4. Observation: sample the current canvas state and run a structured self-check▼(Deviation list: too fine / too coarse / color drift / blurry lighting)│ 5. Correction: add covering strokes, repaint, adjust the strategy for subsequent strokes▼(Target frame → code archived)
The key is step 4: the model does not “finish and stop after writing the code.” Instead, it takes the current canvas state as new input and then decides the next stroke. This turns painting from “one-shot generation” into a “control process with feedback,” methodologically isomorphic to robot grasping and robotic arm trajectory planning—both are closed loops of “perceive—decide—execute.”
3. How a Stroke Is Encoded: What’s Inside a Single Instruction
A stroke instruction typically contains the following fields, shown here as a generic structure (not the interface of any specific product):
{"id": "stroke_037","tool": "flat_brush","color_hex": "#30346a","width_px": 90,"opacity": 0.82,"wetness": 0.35,"points": [{"x": 412, "y": 508},{"x": 415, "y": 509},{"x": 418, "y": 511},{"x": 421, "y": 512},{"x": 424, "y": 513}],"jitter_note": "slight wobble to simulate a non-straight human arm"}
The design motivations behind several fields are worth expanding on:
- A coordinate sequence rather than start and end points: Real brush movement is continuous and carries inertia. Describing a stroke with multiple path points is what produces the entry and exit of the brush tip, the variation in thickness along the way, and the “tail flick” at the end.
- Deliberately adding tiny wobble: A human arm cannot draw an absolutely straight line, and low-frequency jitter on the order of about 7 pixels actually makes lines “look hand-drawn.” This explicitly models “imperfection” as a parameter instead of adding noise in post-processing.
- Wetness and opacity affect color mixing: Wet paint slightly diffuses into the underlying color after landing, which is usually approximated in code by “multiple overlays at low opacity” rather than a single solid-color fill.
- Brush type determines texture: Flat brushes, round brushes, and fan brushes differ completely in edge roughness and coverage evenness. Abstracting the “tool” in code into a parameterized brush function is what allows switching between “broad background sweeps” and “fine detail outlining.”
In terms of overall scale, the code for this kind of work is usually on the order of a thousand lines (roughly 1,000–2,000 lines). The core is not the line count but how the stroke sequence is organized: grouped by layer, chunked by region, and segmented by lighting stage. The total number of strokes can range from hundreds to hundreds of thousands depending on complexity—simple scenes take shape with a hundred or so strokes, while complex scenes rely on massive amounts of short strokes stacked to build texture and the sense of light.
4. Self-Correction: From “Drawing It Wrong” to “Fixing It Right”
The most valuable part of programmatic painting is that the model can check and repair its own errors during execution. Typical scenarios include:
- Form too fine: A contour segment is drawn narrower and messier than the target. The fix is not to erase (strokes are irreversible) but to cover the area with a thicker stroke, so the residual bristle marks at the edges are closer to a “fluffy” texture.
- Lighting handling damages the foreground: When adding a halo or light-dark transition to the frame, objects on the table get covered. The fix is to redraw those objects at their original coordinates and adjust the sharpness of their edges to match the new lighting.
- Compositional relationship fails a prompt constraint: For example, two figures are required to have their inner shoulders touching. If the first pass draws their inner arms reaching toward each other while the shoulders end up apart, the arms need to be repainted so that the hands on the outer sides carry the “painting” action, pushing the inner shoulders into contact.
The design philosophy here is: treat “modification” as a kind of stroke too. Erasing and undoing do not exist in physical painting; covering, layering, and repainting are the real means. Once the model thinks according to these rules, its output naturally has physical consistency.
The self-check mechanism usually does not rely on free-form “look at the image and comment” evaluation, but on structured deviation checks: comparing contour width against a target range, measuring color distance from a reference palette, checking the lighting layer’s coverage of the foreground, and verifying whether key constraints (contact, orientation, count) are satisfied. Only when evaluation criteria are written as decidable logic does correction have a direction.
5. Engineering Implementation: Code as the Deliverable
Writing painting as a program brings the direct benefit that the output can be archived, reproduced, and version-controlled:
- The deliverable is a script: Each run starts from a blank canvas and executes stroke by stroke, with deterministic results.
- The process can be replayed: Keeping the stroke sequence makes it possible to generate time-lapse videos, step-by-step teaching images, and process recordings.
- Parameterized reuse: Extracting color, width, and wetness into configuration lets the same structure generate a series of works in the same style.
- Parallel and segmented execution: Complex scenes can be split into background, subject, and lighting layers, generated separately and then composited, in combination with multi-agent division of labor.
In multi-agent collaboration mode, the model can split the task among multiple sub-agents: one handles the compositional skeleton, one handles background texture, one handles lighting and shadows, and finally a controller performs consistency checks and conflict resolution. Public technical talks have featured long-cycle engineering cases such as “coordinating over a thousand sub-agents to build an operating system that runs on an ordinary laptop within about a week,” showing that this “decompose—parallelize—verify—merge” paradigm is not limited to painting but is a general way to organize complex tasks.
For developers, three points are recommended when putting this into practice:
- Define the evaluation system first, then write the generation logic. There must be decidable criteria for stroke quality; otherwise the correction step cannot converge.
- Write constraints as hard rules. Stroke limits, width ranges, forbidden regions, and contact relationships should all be validation conditions, not “wishes” in a prompt.
- Keep intermediate states. The canvas snapshot after each execution, the deviation report, and the correction actions are all the basis for later tuning and reproduction.
6. The Essential Difference from Diffusion-Based Generation
| Dimension | Diffusion-based pixel generation | Code-based stroke-by-stroke painting |
|---|---|---|
| Output form | Finished image tensor | Runnable drawing program |
| Process visibility | Black box, process not interventable | Fully transparent, every stroke traceable |
| Correction method | Regenerate or local inpainting | Add covering strokes, layer color |
| Constraint expression | Mainly prompts, hard guarantees difficult | Code and validation logic, hard constraints |
| Physical consistency | Implicitly learned from data distribution | Explicitly models brush, wetness, texture |
| Reproducibility | Depends on random seed and version | Deterministic code, stable results |
It should be emphasized that the two paths are not replacements for each other. Pixel diffusion still has clear advantages in “high-fidelity texture and massive styles”; the strength of code-based painting lies in controllable process, provable constraints, and explainable results. A common practice in real systems is to combine them: use a programmatic approach to determine composition, lighting, and key structures, then use a generative model to fill in local texture.
7. Capability Boundaries and Common Misconceptions
- It is not the same as “text-to-image”: The core of this capability is long-task planning and execution, not producing an image from a single prompt. It is more like an executor that can write code and self-check.
- Stroke count does not equal quality: Stacking hundreds of thousands of strokes without the correct layering and lighting order just turns into noise. Order and coverage relationships matter more than count.
- Irreversibility is a feature, not a defect: Precisely because it is irreversible, the model must “think before drawing,” which in turn forces out more reasonable planning ability.
- Evaluation must be closed-loop: Stroke-by-stroke drawing without structured self-checks easily keeps stacking on top of an incorrect basis, getting worse with every fix.
8. Summary
The value of code-based stroke-by-stroke painting is not in replicating a particular art style, but in transforming “painting” from one-shot generation into a controllable process that can be planned, observed, and corrected. It turns the brush, the paint, and the canvas into parameters, turns every stroke into an instruction, and turns modification into an added stroke—this path gives visual creation, for the first time, the engineering property of an “auditable process.”
For developers and enterprise users, what is truly worth borrowing is the methodology behind it: decompose complex tasks first, then parallelize, then verify; write constraints as hard rules; fix errors with executable actions rather than starting over. This paradigm can be used for visual generation and also transferred to a broader range of automated execution scenarios—a clear example of large models moving from “being able to answer” to “being able to do things.”
