Procedural Painting with Code: Stroke Modeling, State Management, and Iterative Refinement

    Procedural painting builds images through explicit brushstroke instructions rather than generating pixels in a single opaque process. This article explains how to model canvas, brush, and paint states; implement stroke sampling, pigment mixing, and moisture diffusion; and organize planning, evaluation, and replay tests. It also compares procedural painting with diffusion models and outlines practical implementation choices and limitations.

    1. Two Approaches to Visual Generation

    Many mainstream image-generation methods rely on diffusion models. These models start with random noise and progressively denoise it over multiple steps, moving toward the pixel distributions learned from training data. They can produce high-quality results, but their intermediate states are difficult to interpret, and precise changes to a specific region can be challenging.

    Procedural generation takes a different approach. It breaks the creative process into structured instructions, each with explicit parameters such as brush position, radius, pressure, and paint load. The resulting artwork becomes a program that can be replayed, edited, and managed with version control.

    Publicly reported examples have shown models writing programs that create paintings stroke by stroke on a virtual canvas. Reports describe programs of roughly 1,000–2,000 lines per painting, executing hundreds of thousands of brushstrokes. These works reportedly use neither prerendered base images nor traced external images: the program itself provides the complete record of the painting.

    This approach treats painting as an evolving state rather than a one-time pixel output.

    2. Modeling the Canvas as State

    The first implementation step is to define the data structures. A minimal procedural painting system usually maintains three types of state.

    Canvas state: A two-dimensional array typically stores each pixel’s color, opacity, and wetness. Some implementations also include a height map to represent paper or canvas texture, allowing strokes to pick up a grainy appearance as the brush passes over uneven surfaces.

    Brush parameters: These include radius, hardness, pressure-response curve, tip shape, spacing, and paint depletion rate. Hardness controls the width of the transition at the brush edge, while spacing determines the distance between consecutive sample points.

    Paint state: This tracks the color and remaining quantity of paint carried by the brush tip. As paint is consumed, strokes become lighter or drier. The program can calculate these effects directly.

    The following simplified stroke implementation illustrates how these states interact:

    1. def apply_stroke(canvas, brush, path, paint):
    2. for point in sample_path(path, step=brush.spacing):
    3. pressure = brush.pressure_curve(point.t)
    4. footprint = brush.footprint(pressure)
    5. deposit = paint.load * footprint.coverage
    6. canvas.blend(point.x, point.y, footprint, paint.color, deposit)
    7. paint.load -= deposit.sum() * brush.drain_rate
    8. canvas.wetness.spread(point.x, point.y, brush.moisture)

    The key is that every sample point updates both the canvas and the paint state. Rather than simply assigning a color, the stroke interacts with existing pixels through blending rules. Stroke order and overlap therefore affect the final result, as they do in physical painting.

    3. Engineering Brushstrokes

    3.1 Path Sampling

    Stroke paths are usually represented by Bézier curves or splines. Using control points directly produces uneven motion, so paths need to be resampled by arc length to maintain consistent distances between adjacent samples.

    If the spacing is too large, strokes appear broken. If it is too small, computation increases unnecessarily. A common approach is to set spacing as a fraction of the brush radius and tune it through testing.

    3.2 Pressure and Brush Deformation

    Pressure changes both the brush tip’s contact area and the amount of paint released. Pressure curves are typically implemented with piecewise functions or smooth interpolation.

    A brush can also include a tilt angle, allowing stroke width to vary with direction and approximating the behavior of flat or broad brushes.

    3.3 Pigment Mixing

    Pigment mixing is central to realistic color behavior. Simply averaging RGB values often produces grayish or overly dark results.

    A common alternative draws on pigment-mixing theories based on reflection and absorption. Mixing is calculated in terms of absorption and scattering coefficients, then converted back into display colors.

    These methods require more computation, so practical implementations often use simplified models to balance visual quality and speed.

    3.4 Moisture Diffusion

    On a wet canvas, pigment spreads into surrounding areas, creating softer edges. Dry regions retain more distinct brush marks.

    An implementation can apply local diffusion to the wetness field at each time step and move pigment between neighboring pixels in proportion to wetness. The number of diffusion steps affects how far the wet effect extends. It should be capped according to canvas dimensions to keep computation under control.

    4. Planning and Error Correction

    The main challenge is not rendering an individual stroke. It is identifying what is wrong with the image and deciding how additional strokes should correct it.

    A typical feedback loop looks like this:

    1. def refine(canvas, target_desc, budget):
    2. for _ in range(budget):
    3. error_map = evaluate(canvas, target_desc)
    4. region = worst_region(error_map)
    5. if region.score < threshold:
    6. break
    7. strokes = plan_corrective_strokes(region, canvas)
    8. for s in strokes:
    9. apply_stroke(canvas, s.brush, s.path, s.paint)
    10. return canvas

    Here, evaluate measures the difference between the current canvas and the target description. It might use rule-based metrics that compare tonal distribution, color deviations, and edge positions, or it might rely on another visual evaluation module.

    The budget limits the number of refinement rounds, preventing the program from repeatedly revising a local area without converging.

    Corrective strokes require two safeguards:

    1. Keep corrections local. Cover the region with the largest error rather than undoing areas that are already correct.
    2. Preserve the painting rules. Corrective strokes should follow the same physical rules as the original strokes. Otherwise, they can introduce unnatural visual discontinuities.

    5. Code Organization and Maintainability

    A painting program exceeding 1,000 lines needs clear module boundaries. A typical structure is:

    1. painting_project/
    2. canvas/ Canvas and pixel storage
    3. brushes/ Brush definitions and parameter library
    4. paint/ Pigment models and mixing rules
    5. strokes/ Path sampling and stroke execution
    6. planning/ Target descriptions and correction strategies
    7. evaluation/ Error calculation and scoring
    8. render/ Final image export
    9. tests/ Replay tests and numerical validation

    Modules should communicate through explicit interfaces. The canvas module should not need to know how brushes are defined, and the planning module should not modify pixel arrays directly.

    This separation makes it possible to replace a component, such as the pigment model, without disrupting the rest of the system.

    Testing is equally important. Painting is order-dependent, and a numerical error in one stroke can accumulate through subsequent steps. Replay tests are useful for critical modules: given a fixed random seed and stroke sequence, verify that the output canvas has the same hash. This helps detect regressions introduced by refactoring.

    6. Procedural Painting vs. Diffusion Models

    The two approaches suit different requirements.

    Control: Procedural painting allows precise specification of every stroke’s position and parameters, along with reconstruction of the state at any step. Diffusion models depend more heavily on prompts and sampling, while local edits often require additional conditioning.

    Interpretability: A procedural system records each operation, making the process easier to audit and debug. Diffusion models’ intermediate representations are harder to interpret directly.

    Computational cost: Procedural painting spends much of its time on point-by-point calculations across many strokes. Parallelization and vectorization can substantially reduce runtime. Diffusion models concentrate their computation in multistep inference. Because the bottlenecks differ, neither approach is universally cheaper.

    Photorealism: Diffusion models have learned extensive patterns of lighting, materials, and complex composition. Reproducing comparable detail procedurally requires more sophisticated physical modeling and a larger number of strokes.

    Dependence on source material: A procedural renderer does not inherently require training data or an external base image; its output can be determined entirely by rules and parameters. This offers some advantages for copyright management and reproducibility, but it also requires creators to define the visual rules themselves.

    Procedural painting is therefore well suited to precise control, traceable workflows, and educational demonstrations. Diffusion models remain more common when the priority is quickly producing highly realistic finished images.

    7. Practical Recommendations and Limitations

    For implementation, start with the following practices:

    1. Fix random seeds. Use seeded randomness for stroke jitter, texture noise, and similar effects so that identical inputs produce identical outputs.
    2. Record the stroke sequence. Save each stroke’s parameters in logs or structured files to support replay, debugging, and version comparison.
    3. Validate in stages. Test blending and wetness behavior for individual strokes first, then overall composition, and finally the correction strategy.
    4. Set resource limits. Cap the stroke count, refinement rounds, and canvas resolution to prevent uncontrolled rendering times.
    5. Use general-purpose computing infrastructure. Long-running rendering jobs can run on container platforms, with intermediate results stored in object storage and execution tracked through logging, monitoring, and alerts.

    The approach also has clear limitations. Complex lighting and fine textures require many strokes, increasing computational cost. Error evaluation depends on rules or external modules, and those evaluation criteria may themselves be biased. The resulting style is also strongly shaped by the brush and pigment parameters defined by the developer, so artistic judgment still requires human involvement.

    Procedural painting shifts visual generation from opaque output toward a readable, editable, and reproducible process. For developers, stroke modeling, state management, and error correction are the three foundations for evaluating and implementing this approach.