// SPDX-License-Identifier: MIT OR Apache-2.0
//! Pattern programs with computed parameters: the form compiled pattern maps take when the importer
//! decompiles them. A program (a graph with meta `kind "patterns"`) is a tree of `pp_*` nodes walked from
//! `pp_out`; parameters are numbers or function graphs (`fn.="name"`) evaluated at every visit with
//! variables that persist over the whole walk, so one function can set what a later one reads.
//!
//! - `pp_iterate` (`first`, `body`): runs `first` once, then `body` `count` times; `f_index` is the iteration.
//! - `pp_switch` (`a`, `b`): runs `b` when `cond` is true (non-zero), else `a`.
//! - `pp_quadrant` (`q0`..`q3`): one cell, split in four for its children (top-left, top-right, bottom-left,
//! bottom-right).
//!
//! The drawing rules below were measured against the reference app's engine with generated single-node graphs:
//! - `branch_offset` (uv) moves the quadrant's pattern and its children; `offset` (uv) only its pattern.
//! - `size` is relative to the cell, default 1 (the whole cell); negative flips. `rotation` is in turns, clockwise on
//! screen, around the pattern's centre. Neither reaches the children.
//! - A pattern's brightness is `luminance` (default 1, negative subtracts) times the level of its depth: with
//! roughness r and tree depth D, `r^depth / (1 + r + .. + r^D)`, or 1 when r is 0. Quadrants that draw nothing count
//! towards the depth; iterations and switches don't.
//! - Instances add, or with `max` keep the larger value, on a canvas that starts at the background. Global opacity
//! scales each instance. A grey canvas is clamped to 0..1 once, at the end; a colour canvas is clamped after every
//! additive instance.
//! - Patterns wrap around the canvas. Edges are hard: each pixel is sampled once, at its centre.
use crate::context::Cancel;
use crate::func::{FnEnv, FnFrame, FnState, Prog, Value, compile_named};
use crate::graph::{Graph, Node, Spec};
use crate::lcg_rand;
use crate::math;
use crate::tex::{ImgRef, Tex};
use std::collections::BTreeMap;
use std::rc::Rc;
/// A guard against runaway programs only: the reference draws them all (ground_sand's grain is 81 cells of eight levels of
/// quadrants, 1.8 million and more instances; stopping at 2 million left a third of it black, mean 60 off). Measurement "Fx-maps
/// with random numbers, five shared causes" ("No instance limit is seen ... Our guard is now 20 million").
pub const MAX_INSTANCES: usize = 20_000_000;
/// Deepest nesting a program may reach (a guard, not measured; the library's deepest tree is 9).
const MAX_DEPTH: u32 = 64;
/// A pattern this many canvases wide or more is drawn only up to this width (a guard, not measured).
const MAX_WRAPS: i64 = 16;
/// The most repeats of a pattern a framed canvas draws on each side (a guard, not measured).
const MAX_REPEATS: i64 = 4096;
pub const SPECS: &[Spec] = &[
Spec {
kind: "pp_out",
req: &["in"],
opt: &[],
doc: "start of a pattern program; fn.init, then fn.background, fn.roughness, fn.opacity, fn.frame and fn.frame_offset run first",
},
Spec {
kind: "pp_iterate",
req: &[],
opt: &["first", "body"],
doc: "run first once, then body count times (count or fn.count); f_index is the iteration",
},
Spec { kind: "pp_switch", req: &[], opt: &["a", "b"], doc: "run b when cond (or fn.cond) is true, else a" },
Spec {
kind: "pp_quadrant",
req: &[],
opt: &["q0", "q1", "q2", "q3"],
doc: "one cell, split in four for q0..q3: draws pattern (square, disc, paraboloid, bell, gaussian, thorn, pyramid, brick, gradation, waves, half_bell, ridged_bell, crescent, capsule, cone, gradation_offset, hemisphere), or with image=1 the input image_index, with luminance, branch_offset_x/y, offset_x/y, size_x/y, rotation, variation, max (each also fn.)",
},
];
/// What a program run sees of the graph it is in.
pub struct Context<'a> {
pub lib: &'a BTreeMap,
pub size: [usize; 2],
pub graph_inputs: &'a BTreeMap,
pub seed: u32,
/// In a compiled graph, on a node whose size isn't the graph's: the graph's size, which `$outputsize` reads in the node's
/// expressions, as in a pixel processor.
pub graph: Option<[usize; 2]>,
}
/// The fx-map node's own parameters.
#[derive(Clone, Copy, Debug)]
pub struct Frame {
/// The canvas before anything is drawn.
pub background: f32,
/// How bright deeper levels are, see the module docs.
pub roughness: f32,
/// Scales every instance.
pub opacity: f32,
/// The part of the pattern space the canvas shows: x min, x max, y min, y max. An axis with max <= min shows all of
/// 0..1. The engine uses this to render one row or column of something that varies along one axis only.
pub region: [f32; 4],
/// Whether patterns wrap around the canvas, per axis.
pub tile: [bool; 2],
/// The box of pattern space that repeats: x min, x max, y min, y max. An axis with max <= min repeats every 1.
pub repeat: [f32; 4],
/// Draws in colour: luminance and images have four channels (a colour fx-map).
pub color: bool,
/// The canvas before anything is drawn, in colour.
pub background_color: Option<[f32; 4]>,
}
impl Default for Frame {
fn default() -> Self {
Frame {
background: 0.0,
roughness: 1.0,
opacity: 1.0,
region: [0.0, 1.0, 0.0, 1.0],
tile: [true, true],
repeat: [0.0, 1.0, 0.0, 1.0],
color: false,
background_color: None,
}
}
}
#[derive(Clone, Copy)]
struct Cell {
x: f32,
y: f32,
w: f32,
h: f32,
}
/// What a pattern program draws on: RGBA, or grey (a grey fx-map on a grey background: every instance adds to or keeps
/// the larger of the three colour channels alike and leaves the alpha alone, so one channel and the alpha hold it all).
pub enum Canvas {
Rgba(Tex),
/// grey values and their alpha
Grey(crate::tex::Grey, f32),
}
/// One resolved draw in the order of the original program walk.
pub struct RasterStamp {
/// The pixel bounds (inclusive), unwrapped unless the canvas has a custom frame.
pub bounds: [i32; 4],
/// The repeat bounds (inclusive) for a custom frame.
pub repeats: [i32; 4],
pub center: [f32; 2],
pub half_size: [f32; 2],
pub rotation: [f32; 2],
pub variation: f32,
pub pattern: i32,
pub brightness: [f32; 4],
/// The raster input image, at the mip selected by its footprint.
pub image: Option,
pub nearest: bool,
pub keep_larger: bool,
}
pub struct RasterRequest<'a> {
pub size: [usize; 2],
pub background: Option<&'a Tex>,
pub clear: [f32; 4],
pub color: bool,
/// Write only the brightness when the output is known to be grayscale.
pub grey_alpha: Option,
pub framed: bool,
pub region: [f32; 4],
pub period: [f32; 2],
pub stamps: &'a [RasterStamp],
pub images: &'a [&'a Tex],
pub cancel: &'a Cancel,
}
pub enum RasterOutput {
Grey(crate::tex::Grey, f32),
Rgba(Tex),
}
/// Limits the temporary backend-neutral draw list independently of the GPU's smaller spatial batches.
const MAX_RASTER_STAMPS: usize = 2_000_000;
struct Raster<'a> {
background: Option<&'a Tex>,
clear: [f32; 4],
stamps: Vec,
inputs: Vec<(&'a Tex, Option>)>,
indices: BTreeMap<(usize, u32), u32>,
cancel: &'a Cancel,
full: bool,
}
enum Target<'a> {
Cpu(Canvas),
Raster(Raster<'a>),
}
impl Target<'_> {
fn set_background(&mut self, background: f32) {
let gray = [background, background, background, 1.0];
match self {
Self::Cpu(canvas) => {
let (w, h) = canvas.dims();
*canvas = match canvas {
Canvas::Rgba(_) => Canvas::Rgba(Tex::solid(w, h, gray)),
Canvas::Grey(..) => Canvas::Grey(crate::tex::Grey::solid(w, h, background), 1.0),
};
}
Self::Raster(raster) => {
raster.background = None;
raster.clear = gray;
}
}
}
fn full(&self) -> bool {
matches!(self, Self::Raster(raster) if raster.full)
}
}
impl Canvas {
fn dims(&self) -> (usize, usize) {
match self {
Canvas::Rgba(t) => (t.w, t.h),
Canvas::Grey(t, _) => (t.w, t.h),
}
}
/// One instance onto pixel `i` ([`blend`]).
#[inline]
fn draw(&mut self, i: usize, value: [f32; 4], brightness: [f32; 4], keep_larger: bool, color: bool) {
match self {
Canvas::Rgba(t) => {
if let Some(p) = t.px.get_mut(i) {
blend(p, value, brightness, keep_larger, color);
}
}
// (grey only when the fx-map isn't in colour)
Canvas::Grey(t, _) => {
if let Some(p) = t.px.get_mut(i) {
let v = value[0] * brightness[0];
*p = if keep_larger { p.max(v) } else { *p + v };
}
}
}
}
/// As an RGBA image.
pub fn into_tex(self) -> Tex {
match self {
Canvas::Rgba(t) => t,
Canvas::Grey(t, a) => t.expand(a),
}
}
}
struct Walk<'a> {
g: &'a Graph,
ctx: &'a Context<'a>,
target: Target<'a>,
cancel: Option,
state: FnState,
progs: BTreeMap,
seed: u32,
/// The compiled-graph generator's state of the record being walked; none for the fx-map's own parameters.
rng: Option,
/// `f_pos` in the program's expressions: the centre of the cell being walked (measured).
pos: [f64; 2],
/// `f_cell_size` and `f_cell_depth`: the size of the cell being walked and how many quadrants deep it is (measured).
cell: [f64; 2],
index: i64,
instances: usize,
/// Brightness of each quadrant depth.
levels: Vec,
opacity: f32,
images: &'a [&'a Tex],
region: [f32; 4],
tile: [bool; 2],
/// How far apart the repeats of a pattern are, per axis.
period: [f32; 2],
color: bool,
tree_depth: u32,
/// reduced copies of the images, by image and level
mips: BTreeMap<(usize, u32), Option>>,
}
/// The distance between repeats per axis for a box of pattern space (x min, x max, y min, y max): its size, or 1 on an axis
/// with max <= min.
fn periods(b: [f32; 4]) -> [f32; 2] {
[if b[1] > b[0] { b[1] - b[0] } else { 1.0 }, if b[3] > b[2] { b[3] - b[2] } else { 1.0 }]
}
/// Brightness per depth of a tree `tree_depth` quadrants deep.
fn depth_levels(roughness: f32, tree_depth: u32) -> Vec {
if roughness == 0.0 {
return vec![1.0; tree_depth as usize + 1];
}
let powers: Vec = (0..=tree_depth).map(|d| math::powi(roughness, d as i32)).collect();
let sum: f32 = powers.iter().sum();
powers.iter().map(|p| p / sum).collect()
}
/// Deepest quadrant below `id`, counting from 0 at the first quadrant.
fn tree_depth(g: &Graph, id: u32, memo: &mut BTreeMap, guard: u32) -> i32 {
if let Some(d) = memo.get(&id) {
return *d;
}
let Some(node) = g.nodes.get(&id) else { return -1 };
if guard > MAX_DEPTH {
return -1;
}
let below = |slots: &[&str], memo: &mut BTreeMap| -> i32 {
slots.iter().filter_map(|s| node.ins.get(*s)).map(|c| tree_depth(g, *c, memo, guard + 1)).max().unwrap_or(-1)
};
let d = match node.kind.as_str() {
"pp_quadrant" => below(&["q0", "q1", "q2", "q3"], memo).max(-1) + 1,
_ => below(&["in", "first", "body", "a", "b"], memo),
};
memo.insert(id, d);
d
}
impl<'a> Walk<'a> {
fn stopped(&self) -> bool {
self.target.full() || self.cancel.as_ref().is_some_and(Cancel::is_cancelled)
}
/// Runs a parameter's function, if it has one.
fn function_value(&mut self, node: &Node, name: &str) -> Result