Code-Based Painting: Simulating Real Brushstrokes Without an Image Model

    This article explores an alternative to diffusion-based image generation: using a language model to output an executable drawing program that drives a virtual painting engine, rendering an image stroke by stroke without any external image generation model or pre-rendered base image. It explains why this approach matters to developers, covering interpretable and reproducible output, editable code as the final asset, and style driven by decisions rather than weights. The article then breaks down the engine side (brush geometry, pigment transfer, wetness and drying, canvas texture) and the model side (composition planning, stroke scheduling, self-inspection and correction), with illustrative Python snippets. It closes with performance and engineering recommendations, limitations, and suitable use cases.

    1. From Direct Image Output to Writing a Brush: A Different Generation Paradigm

    When discussing generative visual content, the most common approach in the industry is diffusion-based: a model repeatedly denoises in latent space, gradually converging random perturbations into a finished image. Its strengths are that it is end-to-end and fast, but the process is a black box—users receive the result, not the process.

    A different approach that has been discussed repeatedly works entirely differently: a language model does not output pixels, but instead outputs an executable drawing program. This program drives a virtual painting engine that simulates the landing, movement, and lifting of a real brush on a canvas, painting the picture stroke by stroke. According to public technical sharing, such works often correspond to roughly one to two thousand lines of code, a single image may involve hundreds of thousands of stroke calls, and the approach relies on no external image generation model and no pre-rendered or traced base image.

    This is not marketing language, but a difference with clear engineering implications: the generated artifact changes from an “image” into “reproducible, editable, and explainable code.” This article centers on this paradigm and breaks down its technical composition and engineering practice.

    2. Why Code-Based Painting Matters to Developers

    1. Explainable Process, Reproducible Results

    The intermediate noise in a diffusion process has no semantics and is hard to diagnose. In programmatic painting, every step is a semantically clear instruction: brush model, coordinates, pressure, angle, pigment water content. When something goes wrong, you can pinpoint the specific range of strokes, rather than resampling and hoping for luck.

    2. Natural Support for “Non-Maximum-Likelihood” Corrections

    A real painter steps back to view the whole, then adds another stroke. The programmatic path can likewise append corrective strokes based on the current canvas state after the main subject is complete—because the canvas state is always readable in-memory data, not an irretrievable intermediate tensor.

    3. Output Is an Asset

    The final deliverable is a Python program. It can be version-controlled, parameterized for batch image generation, embedded into a rendering pipeline, and run concurrently at scale on a container platform, with results written to object storage for archival. This is hard to achieve with pure image output.

    4. Style Comes from “Decisions,” Not “Weights”

    Because the stroke scheduling strategy is planned by the model itself, different runs settle into relatively stable color and brushwork preferences, forming a recognizable personal style, rather than a mean regression toward the training distribution.

    3. Engine Side: Simulating a “Real Brush”

    For a program to paint a believable picture, the engine must model at least four layers of physical and geometric properties.

    Brush geometry: tip shape (round, flat, fan), number and arrangement of bristles, and the angle of each bristle relative to the handle. A stroke is not a thick line, but the result of dozens of bristles each leaving a trajectory that are then overlaid.

    Pigment transfer: each bristle carries a limited amount of pigment that decreases with movement distance; pigment deposits more on the raised parts of the canvas texture and leaves the recesses blank, forming natural dry-brush breaks.

    Wetness and drying: water content affects the diffusion radius and edge softness. High-wetness strokes have semi-transparent edges and blend easily; low-wetness strokes have sharp edges and strong coverage.

    Canvas texture: a height map describes the texture relief, and strokes apply masking and offset based on height—this is the source of the “canvas texture.”

    The illustrative code below emphasizes structure over values:

    1. @dataclass
    2. class Brush:
    3. kind: str # round / flat / fan
    4. bristles: int
    5. angle: float
    6. load: float # pigment load
    7. wetness: float # water content
    8. def stroke(canvas, brush: Brush, pts: list[Point], color):
    9. for i in range(brush.bristles):
    10. offset = bristle_offset(brush, i)
    11. load = brush.load
    12. for a, b in zip(pts, pts[1:]):
    13. p = a + offset
    14. h = canvas.height_at(p) # canvas texture height
    15. mask = deposit_mask(h, brush.wetness)
    16. load = canvas.blend(p, color, mask, load)
    17. load *= 0.97 # natural pigment consumption
    18. if load < 0.02:
    19. break

    4. Model Side: Turning “Painting” into a Controllable Code-Generation Task

    What the model faces is not pixels, but a drawing API and a summary of the current canvas. Engineering practice is usually organized in three layers:

    1. Composition planning layer: determine the subject, viewpoint, light direction, and primary/secondary relationships, outputting a coarse-grained layout and color palette.
    2. Stroke scheduling layer: expand the layout into a stroke sequence, advancing in the order of “large areas to details, dark to light, background to subject,” controlling the decreasing scale of individual strokes.
    3. Self-inspection and correction layer: periodically read canvas statistics (regional brightness, edge contrast, color shift), and after detecting deviations, append covering strokes or softening strokes.

    A simplified scheduling loop can be written as:

    1. plan = plan_composition(scene, palette)
    2. for layer in plan.layers: # background → subject → highlights
    3. for region in layer.regions:
    4. b = pick_brush(region.scale, region.wetness)
    5. stroke(canvas, b, hatch(region), region.color)
    6. report = inspect(canvas, layer.roi) # self-check: brightness/contrast/color shift
    7. if report.needs_fix:
    8. stroke(canvas, soften_brush(), report.fix_path, report.color)

    The key engineering constraint here is the context budget: hundreds of thousands of strokes cannot all fit into the model context. A viable approach is to express the stroke sequence in a compact DSL, generate it in segments, and read back canvas summaries on demand, rather than stuffing the complete history back into the prompt.

    5. Performance and Engineering Recommendations

    • Decouple rendering from generation: the model only produces a stream of stroke instructions, while rasterization is handled by a separate rendering process, making it easy to swap backends and scale horizontally.
    • Incremental persistence: append the stroke stream to disk as it is produced, and combine it with logging services and monitoring alerts so that interrupted long-running tasks can resume from the breakpoint.
    • Determinism first: fix random seeds and brush jitter parameters to ensure the same program produces consistent results across multiple runs, facilitating regression testing.
    • Layered caching: static resources such as the canvas height map and texture masks can be reused, avoiding per-stroke recomputation.
    • Quality evaluation: establish metrics such as edge sharpness, color distribution, and structural similarity to replace the subjective judgment of “looks good.”

    6. Limitations and Applicability Boundaries

    The cost of this path must be stated clearly: it is slow, with high compute and time costs, and is not suitable for real-time image generation; it has limited stability for very small-scale details (such as hair strands and text); and image quality depends heavily on the engine’s stroke-modeling precision and the model’s planning ability. Therefore, it is better suited to scenarios that prioritize controllability and high single-image value, such as concept design, teaching demonstrations, stylized asset production, and content production pipelines that require an “auditable process.”

    7. Conclusion

    Reducing painting to “code + strokes” is essentially replacing unexplainable tensors with an explainable program. For developers, the real gain is not another way to produce images, but a path to engineering the generation task: reproducible, correctable, orchestrable, and cloud-deployable. In a cloud environment such as Baidu AI Cloud that provides general capabilities like container platforms, object storage, and monitoring alerts, this “model planning + engine rendering” architecture can be implemented relatively naturally as a stable content production pipeline.