Code-Based Painting Without Image Models: A Technical Guide to Stroke-by-Stroke Rendering

    This article examines an alternative approach to AI image generation where, instead of calling an image model, a system writes an executable Python program that simulates brush movements on a virtual canvas. It explains how code-based painting differs from diffusion-based generation, breaks down a reproducible five-layer engine architecture (DSL, brush and pigment simulation, planning, state management, and quality evaluation), and covers why the stroke-by-stroke paradigm produces recognizable style. It also outlines performance bottlenecks, common failure modes, and practical deployment advice for developers building controllable, editable, and auditable drawing pipelines.

    1. Introduction: When “Generating an Image” Becomes “Writing a Painting Program”

    In the popular understanding, AI art is almost synonymous with “enter a prompt, wait for a finished image.” Most mainstream solutions are built on diffusion models, which start from random noise and progressively approach a target image through multiple denoising steps. Recently, however, a distinctly different practice has emerged: the model does not output pixels directly. Instead, it writes an executable Python program that simulates the movement of a real brush on a virtual canvas, painting the scene stroke by stroke.

    According to a public technical demonstration, one intelligent coding tool was asked to get as close to photorealism as possible and rendered a shopping cart in a parking lot, accumulating roughly 700,000 simulated brush strokes. Each work is essentially a program of 1,000 to 2,000 lines, interpreted and executed by a custom or companion painting engine. It relies on no external image model and uses no pre-rendered or traced base image. Setting aside the specific product, this article abstracts the case into a general technical question: how to achieve high-fidelity drawing in a code-based, explainable, and iterative way, and offers a practical architecture design along with engineering recommendations.

    2. The Fundamental Difference Between the Two Technical Routes

    To understand the value of this approach, it helps to first see how it differs from diffusion-based generation.

    • Different outputs: A diffusion model outputs a pixel tensor; code-based painting outputs a “sequence of stroke instructions plus a rendering context.” The image is the result of execution rather than a direct product.
    • Different process explainability: The former is an end-to-end black box; every step of the latter has clear semantics (pen position, brush type, pressure, pigment water content), and can be replayed, resumed from a breakpoint, or partially repainted.
    • Different correction methods: The former typically relies on resampling or inpainting; the latter can add new strokes to cover and correct deviations after they are discovered, which is closer to real painting habits.
    • Different style formation mechanisms: The style of the former comes mainly from training data and prompts; the style of the latter comes from the model’s long-term preferences in “how to choose a brush, how to arrange hatching, how to control water,” making it easy to evolve relatively stable, personalized stroke characteristics.
    • Different compute structures: The former involves a small number of extremely heavy tensor operations; the latter involves massive but lightweight interpreted execution and state updates, where the bottleneck is often scheduling and memory layout rather than single-pass floating-point throughput.

    It is worth emphasizing that these two routes are not substitutes. Code-based painting has clear advantages in being controllable, editable, and auditable throughout the process, but it still faces challenges in convergence speed for hyperrealistic detail. Diffusion models are mature in texture and semantic consistency, yet struggle to provide a step-by-step traceable creative trajectory.

    3. System Architecture: A Reproducible Code-Based Painting Engine

    Engineering this kind of capability can be broken into five layers.

    1. Instruction Layer (DSL)

    The model does not manipulate pixels directly; it outputs structured stroke instructions. An example:

    1. stroke = {
    2. "brush": "flat", # flat brush
    3. "x": 0.42, "y": 0.61, # normalized canvas coordinates
    4. "angle": 1.57,
    5. "size": 0.018,
    6. "pressure": 0.35, # downward pressure
    7. "water": 0.62, # pigment water content
    8. "color": [0.21, 0.23, 0.25],
    9. "ops": "stroke" # stroke / glaze / scumble / lift
    10. }

    Using a DSL rather than free text makes instructions verifiable, replayable, and incrementally renderable, and makes it easier for the model to plan in batches within a limited context.

    2. Brush and Pigment Model

    The key to realism is “medium simulation.” Common approaches include: using a parameterized brush to describe bristle distribution and elastic deformation; using water content and pigment viscosity together to determine diffusion radius and edge roughness; and using a paper/canvas texture height field to influence pigment deposition. Illustrative pseudocode:

    1. def deposit(canvas, s):
    2. mask = brush_mask(s["brush"], s["size"], s["pressure"])
    3. wet = s["water"] * (1.0 - canvas.dryness[mask].mean())
    4. alpha = clamp(0.15 + 0.85 * wet, 0, 1)
    5. canvas.blend(mask, s["color"], alpha * s["pressure"])
    6. canvas.dryness[mask] += 0.05 * (1.0 - s["water"])

    3. Planning Layer (Model Responsibility)

    The model decides “what to paint and what to paint first.” A reasonable strategy is coarse to fine: first lay in light and dark values and composition with large strokes, then build form with medium strokes, and finally add texture and highlights with small strokes. Dividing the canvas into blocks and maintaining a to-do queue can significantly reduce the difficulty of long-sequence planning.

    4. Execution and State Management Layer

    Maintain four kinds of state: canvas color, humidity, dryness, and stroke history. Support snapshots and rollback so that “discover an error, add corrective strokes” becomes a first-class operation.

    5. Quality Evaluation and Termination Conditions

    Replace “feeling done” with computable metrics, such as edge gradient distribution, local contrast, tonal coverage, and a consistency score against target semantic regions. Terminate when a threshold is reached or when there is no significant improvement over several consecutive rounds.

    4. Why “Stroke by Stroke” Produces Style

    The stroke-by-stroke paradigm breaks creation into a large number of small decisions, which the model solidifies into preferences under reward and feedback: favored hatching directions, habitual wet-dry rhythms, and a restrained approach to highlights. Layered together, these preferences become a recognizable style. In engineering terms, style can be made explicit as a “brush prior plus stroke statistics,” used for style transfer, style consistency checks, or even parallel sampling across multiple styles followed by selection of the best result.

    5. Performance and Cost: The Bottleneck Is Not Peak Compute

    700,000 strokes mean a massive number of small tasks. Optimization in practice usually focuses on four points:

    1. Batching and vectorization: Merge strokes with the same brush and color family into tensor batches to reduce interpreter overhead.
    2. Layered caching: Render the static background layer only once, and update dynamic layers incrementally.
    3. Asynchronous pipelines: Decouple and parallelize planning, rendering, and evaluation so they do not block one another.
    4. Early stopping and budget control: Set a stroke limit and evaluation interval to prevent unproductive refinement.

    Deployment recommendations: put training and batch rendering on an elastic container platform that auto-scales by queue; store render outputs and intermediate snapshots in object storage; decouple task state and the instruction flow with a message queue; and track stroke throughput, per-image time, and retry rate across the full pipeline using logging and monitoring with alerts. If you use Baidu AI Cloud, you can combine its general capabilities such as containers, object storage, message queues, logging, and monitoring into the pipeline above without binding to any proprietary interface.

    6. Quality Evaluation and Common Failure Modes

    • Gray and muddy: Wet-dry control is out of balance, and repeated pigment layering loses value hierarchy; the countermeasure is to enforce “establish black, white, and gray first, then add color.”
    • Stroke overflow: Brush size and pressure are too large; the countermeasure is to introduce edge constraints and automatic edge-trimming strokes.
    • Semantic drift: The refinement stage damages structure that was already correct; the countermeasure is to freeze completed blocks and allow modifications only within a mask.
    • Convergence stall: Evaluation metrics stop improving while budget is still being consumed; the countermeasure is early stopping and switching evaluation dimensions.

    7. Use Cases and Implementation Recommendations

    Code-based painting suits scenarios that need to be editable, auditable, and partially reworkable: design draft iteration, teaching demonstrations (showing the painting process step by step), diagram drawing in industrial visualization, and asset production that requires a clear copyright chain. For implementation, a three-step approach is recommended: first solidify the DSL and rendering engine, then connect the planning model and run small-sample evaluations, and finally complete the pipeline, monitoring, and asset version management.

    8. Conclusion

    Painting stroke by stroke with code instead of calling an image model essentially reconstructs “generation” into a controllable flow of “planning + simulation + evaluation.” It sacrifices some convergence speed in exchange for a transparent process, correctability, and explainable style. For developers, the real barrier is not the model itself but the precision of brush simulation, state management, and the completeness of the engineering pipeline, which is exactly where this type of approach is worth deeper investment.