How LLMs Draw Stroke by Stroke with Code: Technical Principles and Engineering Practices
This article examines an unconventional approach to AI image generation in which a large language model writes executable Python code to simulate brush movements on a virtual canvas, completing a painting stroke by stroke instead of generating pixels directly through a diffusion model. It explains the underlying technical principles, how this paradigm differs from mainstream text-to-image generation, the core challenges of reliable long-code generation and spatial reasoning, and key engineering practices such as visual feedback pipelines, a stroke DSL, and progressive correction. It also discusses what the "plan-observe-correct" loop implies for embodied intelligence and robot control, where actions are irreversible.
Introduction: A Counterintuitive Path to AI-Generated Art
The mainstream approach to AI image generation today relies heavily on diffusion models. Starting from a random noise image, the model runs multiple denoising iterations until the target image gradually emerges. This path is end-to-end and can produce high-quality images without manual intervention, but it is essentially a black box: the user supplies a prompt, the model outputs a finished image, and the generation logic in between is nearly invisible to humans.
A very different direction has recently emerged. Instead of generating pixels, a large language model writes a complete Python program that simulates the trajectory of a real brush on a virtual canvas, completing a painting stroke by stroke. This approach depends on no image generation model, and it does not use any pre-rendered base image or reference image to trace over. The position, angle, color, thickness, and wetness of the paint for every stroke are all planned and output autonomously by the model through code logic.
On the surface, this “simulate a brush and paint stroke by stroke with code” method looks like an art experiment. But the technical capabilities it demonstrates underneath—step-by-step planning, observing intermediate results, and correcting errors autonomously—are deeply connected to complex tasks such as robot control and physical-world interaction. This article provides a systematic analysis of this technical route, covering how it works, how it differs from mainstream solutions, its core challenges, key engineering implementation points, and what it offers to the field of embodied intelligence.
1. Technical Principles: Breaking Painting Down into Discrete Stroke Instructions
The key to understanding this technical route is recognizing its fundamental difference in generation paradigm from traditional text-to-image.
The traditional diffusion model path can be compared to “sculpting in one pass.” The model receives a text prompt and generates all pixels collaboratively through gradual denoising in latent space. All pixels are coupled during generation. Internally, the model has no explicit plan for “what to draw first and what to draw later,” and no feedback mechanism for “finish one step, check the result, then decide the next step.”
The code-driven stroke-by-stroke path is more like “how a real painter works.” The model first understands the creative goal (for example, “paint a bird at sunrise”), then breaks the task into a series of ordered stroke instructions. Each stroke contains specific parameters—start and end coordinates, a sequence of path points, color values, brush width, paint wetness, blending mode, and so on. These instructions are encoded into an executable Python program that outputs the final image file when run.
Consider a publicly discussed example: the model was asked to paint a bird at sunrise, with the constraint that each stroke must be output individually as coordinate instructions and that a stroke could not be undone once it landed on the canvas. A 21-second video captured the entire process from a blank canvas to the finished work, using 111 strokes in total. The first stroke used a specific blue color value and a brush width of 90 pixels, and included 5 slightly wobbling path points. The model explained that the roughly 7-pixel wobble was deliberate, because a human arm cannot draw a perfectly straight line—this subtle irregularity actually makes the result closer to the texture of real hand drawing.
This detail is highly revealing: the model is not only drawing, but also “understanding why it draws this way” and translating that understanding into executable code logic.
2. Core Technical Feature: Simulating Physical Media and Stroke Texture
The reason code-driven stroke-by-stroke painting can produce convincing visual results is its fine-grained simulation of the physical painting process. This involves several technical elements.
2.1 Simulating the Physical Properties of Brush and Canvas
In real painting, the shape of the brush (round, flat, fan), the stiffness of the bristles, the amount of ink it holds, and the canvas texture roughness and absorbency all directly affect how a stroke finally appears. Code simulation needs to parameterize these physical properties into controllable variables, such as brush width (at the pixel level), path curvature, paint drying time, and canvas texture noise.
# Illustrative pseudocode: simulation logic for a single brush strokeclass BrushStroke:def __init__(self, color, width, opacity, path_points, jitter=0):self.color = color # color value, e.g. #30346aself.width = width # brush width, e.g. 90pxself.opacity = opacity # paint opacityself.path = path_points # list of path coordinatesself.jitter = jitter # path jitter amplitudedef render(self, canvas):for i in range(len(self.path) - 1):p1, p2 = self.path[i], self.path[i + 1]# interpolate between p1 and p2, adding jitter to mimic hand-drawn instabilitypoints = self._interpolate_with_jitter(p1, p2, self.jitter)for pt in points:canvas.draw_brush(pt, self.color, self.width, self.opacity)return canvas
2.2 Paint Wetness and Layering Effects
In real oil or watercolor painting, while the paint is still wet, a new stroke blends naturally with the underlying color; once it dries, a new layer produces a covering effect. Code simulation reproduces this physical behavior by adjusting paint opacity, blend modes (such as multiply or screen), and a simulated “wetness” parameter.
2.3 Stroke Correction Mechanism
This is the most engineering-valuable design in this route. Because strokes cannot be undone, any mistake must be fixed by “repainting the correct content over the erroneous area.” The model needs to observe the current canvas state, determine which regions need to be covered, and choose an appropriate color and brush to repaint. In the public example, when the model found that the lines on the bird’s back were too thin and the edges were messy, it used a thicker stroke to cover the original area, making the residual bristle marks closer to the texture of fluffy feathers.
3. The “Plan-Observe-Correct” Loop: From Painting to General Task Solving
If stroke simulation solves the problem of “how to draw,” then the “plan-observe-correct” loop solves the problem of “how to autonomously complete a multi-step complex task.” This is also the core reason this technical route is considered to offer lessons for fields such as robot control.
3.1 Staged Planning Capability
After receiving an instruction such as “paint a work that is as photorealistic as possible,” the model does not output all strokes at once. Instead, it plans in stages: first determining the overall composition and large color blocks, then progressively refining local details. In the public example, a photorealistic work of a parking lot shopping cart used about 700,000 simulated strokes and roughly 1,000 to 2,000 lines of code—meaning the model must be capable of decomposing and scheduling long-horizon tasks.
3.2 Observing Intermediate Results and Self-Evaluation
During stroke execution, the model periodically “observes” the current state of the canvas, compares it against the creative goal, and identifies deviations. This is similar to “closed-loop feedback” in robot control: sensors capture the current state, the controller computes the error against the target state, and then generates a corrective action.
3.3 Autonomous Error Correction
In another work completed with 280 strokes depicting a dusk scene, the lighting effects added later accidentally blurred the paint tubes and cups on the table. After detecting this problem, the model repainted these objects with new strokes. It also adjusted the poses of two figures so that each used the hand on the outer side of the body to paint, allowing their inner shoulders to touch each other as originally required—a complex correction involving spatial-relationship reasoning.
# Illustrative pseudocode: the observe-correct loopdef draw_with_correction(target_description, canvas):plan = model.plan_strokes(target_description)for stroke in plan:canvas = execute_stroke(canvas, stroke)# observe the current result and identify regions that need correctionissues = model.inspect_and_compare(canvas, target_description)while issues:fix_stroke = model.plan_correction(issues, canvas)canvas = execute_stroke(canvas, fix_stroke)issues = model.inspect_and_compare(canvas, target_description)return canvas
3.4 Implications for Robot Control
The “plan-observe-correct” loop above is highly isomorphic to the architecture of a robot control system:
| Painting Task | Robot Control Task |
|---|---|
| Understand the creative goal | Understand the task instruction |
| Decompose into ordered strokes | Decompose into an action sequence (trajectory planning) |
| Execute a single stroke | Execute joint / end-effector motion |
| Observe the current canvas state | Sensors read the environment state |
| Identify deviations and repaint | Compute the error and generate a corrective action |
| Strokes cannot be undone | Physical actions are irreversible |
The “strokes cannot be undone” constraint deserves special attention. In the real physical world, the vast majority of a robot’s actions are likewise irreversible—a wrong grasp may damage an object, and a wrong move may cause a collision. Therefore, the “plan carefully, verify thoroughly before executing” strategy the model exhibits under the irreversible-stroke condition has direct reference value for safety constraints and risk assessment in robot control.
4. Key Engineering Challenges
Although the concept is feasible, turning code-driven stroke-by-stroke painting into a stable, reusable technical capability still faces several challenges.
1. Reliable generation and maintenance of long code. The program for a complex work may reach thousands of lines, and the model must ensure syntactic correctness, logical consistency, and the integrity of variable references. This requires code generation capability with long-context understanding and self-verification mechanisms.
2. Combining spatial reasoning with visual feedback. The model must maintain the current image state in a “mental canvas” and, when planning new strokes, account for their relationship to existing content (color harmony, spatial occlusion, perspective consistency). This places high demands on multimodal understanding.
3. Computational efficiency and cost control. Simulating hundreds of thousands of strokes means a large amount of rendering computation. Optimizing the rendering pipeline and reducing unnecessary strokes while preserving image quality is key to engineering deployment. Using a container platform for elastic scaling, using object storage to manage intermediate canvas states, and using a message queue to decouple stroke generation from rendering execution are all viable engineering directions.
4. Multi-sub-agent coordination. For complex tasks, different regions or different types of strokes can be assigned to multiple sub-agents for parallel processing, with a main agent then aggregating and verifying the results. This architecture is similar to the “task splitting—parallel processing—result aggregation” pattern in microservices.
5. Essential Differences from Mainstream AI Art Solutions
Understanding how this route differs from diffusion model solutions helps determine their respective use cases.
Different generation paradigms: A diffusion model is end-to-end generation “from noise to image”; code-driven stroke-by-stroke painting is an explicit planning process “from intent to an instruction sequence to rendering.” The former is fast and suited to batch production; the latter offers strong controllability and an explainable process.
Different explainability: Every step in the code path is readable, auditable code logic, and developers can know precisely “what stroke number drew what, and why.” The evolution of the diffusion model’s latent space is a black box to humans.
Different interaction modes: The code path naturally supports a human-machine collaboration mode of “pause, inspect, adjust, continue”; with a diffusion model, intervening mid-generation is relatively difficult.
Different hardware dependencies: Diffusion models typically require GPUs for large-scale matrix operations; the main computation in the code path lies in program generation and rendering simulation, which is theoretically friendlier to general-purpose compute resources.
6. Practical Advice for Developers
If you want to explore code-driven stroke-by-stroke painting or a similar “programmatic content generation” direction, the following practical suggestions are worth considering.
Start with simple scenes: First try using code to generate simple geometric shapes or a simple landscape sketch (within a few dozen strokes) to verify the correctness of the stroke simulation engine, then gradually increase the complexity.
Build a visual feedback pipeline: After each round of drawing, feed the current canvas state back to the model for visual evaluation. You can use a logging service to record the inputs and outputs of each evaluation, making later debugging and optimization easier.
Design a stroke DSL (domain-specific language): Abstract stroke parameters (color, width, path, opacity, blend mode) into a structured data format, so that model output is easier to validate and debug, rather than directly generating error-prone native Python code.
Introduce a progressive correction strategy: Do not expect a single generation to be perfect. Split the task into multiple rounds of iteration—“rough sketch—refine—fine-tune”—with each round making local optimizations based on the previous round’s result, which can significantly improve final quality.
Pay attention to compute resource planning: For large-scale stroke rendering tasks, it is advisable to use a monitoring and alerting system to track rendering time and resource consumption so that bottlenecks can be identified promptly.
Conclusion
Code-driven stroke-by-stroke painting represents a technical paradigm different from the mainstream diffusion model. Rather than pursuing the efficiency of “one-click image generation,” it explores AI’s ability to execute autonomously under long-horizon, multi-step, irreversible constraints through explicit stroke planning, physical-property simulation, and closed-loop correction. From an engineering perspective, its core value lies not in painting itself, but in validating the feasibility of the “large language model as task planner + executor” paradigm—a paradigm with far-reaching implications for fields such as robot control, automated operations, and complex engineering tasks. As model reasoning capabilities continue to improve and multi-agent coordination frameworks mature, “driving the physical world with code” may evolve from a painting experiment into a foundational methodology for the era of embodied intelligence.
