A drawing app built for agent/human collaboration
Rust
Grass that reads as grass, with brushes the agent makes
Indicode BVa5e2730224c8
diff --git a/README.md b/README.mdindex 2f5fe65..72afdac 100644--- a/README.md+++ b/README.md@@ -51,7 +51,7 @@ There are no downloads yet; build it from source (about ten minutes the first ti1. Install Rust with [rustup](https://rustup.rs) and [`just`](https://github.com/casey/just) (`brew install just`, or `cargo install just`). On Linux also `pkg-config`, `libfreetype-dev` and `libfontconfig1-dev`.2. `git clone https://github.com/klad-app/klad && cd klad`, then `just build` makes the `klad` binary in `target/release/` (on Linux in `target/linux/release/`).3. On a Mac, `target/release/klad open` starts the editor on its start window: make a drawing and start painting.-4. `just samples` builds the sample drawings in `samples/` (a lantern, a walking creature, a running courier, an underground ruin, an inn sign, a tree, painted solids, a bowl of lemons, a bouncing ball, ink examples); open one with `target/release/klad open samples/lantern/lantern.draw`.+4. `just samples` builds the sample drawings in `samples/` (a lantern, a walking creature, a running courier, an underground ruin, an inn sign, a tree, a meadow, painted solids, a bowl of lemons, a bouncing ball, ink examples); open one with `target/release/klad open samples/lantern/lantern.draw`.## Drawing with an agentdiff --git a/crates/app/src/editor.rs b/crates/app/src/editor.rsindex 8b65fac..04226e6 100644--- a/crates/app/src/editor.rs+++ b/crates/app/src/editor.rs@@ -2513,11 +2513,13 @@ impl Editor {let tail = live.recorder.finish();tail.iter().for_each(|s| live.painter.push_on(s, &mut self.buffer, self.scene.active_raster()));+ live.painter.end(&mut self.buffer, self.scene.active_raster());if let Some((axis, copy, painter)) = live.twin.as_mut() {tail.iter().map(|s| make::mirrored(s, *axis)).for_each(|s| {painter.push_on(&s, &mut self.mirror_buffer, self.scene.active_raster());copy.samples.push(s);});+ painter.end(&mut self.mirror_buffer, self.scene.active_raster());}live.stroke.samples.extend(tail);let repainted = needs_repaint(&live.stroke);diff --git a/crates/brush/src/engine.rs b/crates/brush/src/engine.rsindex 2e40f09..ef94037 100644--- a/crates/brush/src/engine.rs+++ b/crates/brush/src/engine.rs@@ -69,6 +69,7 @@ pub struct StrokePainter {seed: u32,last: Option<Point>,heading: f32,+ pending: Option<Point>,speed: f32,carry: f32,walked: f32,@@ -122,6 +123,7 @@ impl StrokePainter {seed: stroke.seed,last: None,heading: 0.0,+ pending: None,speed: 0.0,carry: 0.0,walked: 0.0,@@ -152,6 +154,12 @@ impl StrokePainter {self.push_on(sample, buffer, None);}+ pub fn end(&mut self, buffer: &mut StrokeBuffer, under: Option<&Raster>) {+ if let Some(first) = self.pending.take() {+ self.dab(first, 0.0, buffer, under);+ }+ }+pub fn push_on(&mut self, sample: &Sample, buffer: &mut StrokeBuffer, under: Option<&Raster>) {buffer.mode = self.mode();buffer.body = self.brush.def.body;@@ -164,7 +172,11 @@ impl StrokePainter {tilt: sample.tilt(),};let Some(prev) = self.last else {- self.dab(next, 0.0, buffer, under);+ let pictured = matches!(self.brush.def.tip, klad_core::brushes::TipDef::Image { .. });+ match (self.brush.angle, pictured) {+ (Angle::Follow, true) => self.pending = Some(next),+ _ => self.dab(next, 0.0, buffer, under),+ }self.last = Some(next);return;};@@ -177,11 +189,16 @@ impl StrokePainter {});return;}+ let heading = libm::atan2f(next.y - prev.y, next.x - prev.x);+ if let Some(first) = self.pending.take() {+ self.heading = heading;+ self.dab(first, 0.0, buffer, under);+ }if sample.dt_ms > 0 {let now = length / sample.dt_ms as f32 / self.brush.scale;self.speed += (now - self.speed) * SPEED_EASE;}- self.heading = libm::atan2f(next.y - prev.y, next.x - prev.x);+ self.heading = heading;let mut travelled = 0.0f32;loop {let here = lerp(prev, next, travelled / length);@@ -1090,6 +1107,7 @@ pub fn draw_stroke_on(buffer: &mut StrokeBuffer, brush: &Brush, stroke: &Stroke,let mut painter = StrokePainter::new(brush, stroke);buffer.mode = painter.mode();stroke.samples.iter().for_each(|s| painter.push_on(s, buffer, under));+ painter.end(buffer, under);painter.dabs()}@@ -1366,6 +1384,40 @@ mod tests {assert!(b > a + 0.15, "two strokes {b}");}+ #[test]+ fn the_first_dab_of_a_follow_brush_faces_the_stroke() {+ let mut brushes = BrushSet::presets();+ let mut def = brushes.def("leaves").unwrap().clone();+ def.tip = klad_core::brushes::TipDef::Image {+ image: "leaf-lance".into(),+ more: Vec::new(),+ };+ def.spacing = 10.0;+ def.jitter = Default::default();+ def.color = None;+ brushes.insert("lance", def);+ let up = Stroke::new(1, "lance", [0.0, 0.0, 0.0, 1.0], 80.0, 9)+ .with_points(&[(128.0, 140.0, 1.0), (128.0, 120.0, 1.0)], 5.0);+ let out = replay(256, 256, &[up.into()], &brushes).unwrap();+ let inked: Vec<(usize, usize)> = (0..256)+ .flat_map(|y| (0..256).map(move |x| (x, y)))+ .filter(|&(x, y)| rgba(&out.raster, x, y)[3] > 0.5)+ .collect();+ let span = |pick: fn(&(usize, usize)) -> usize| {+ inked.iter().map(pick).max().unwrap_or(0) - inked.iter().map(pick).min().unwrap_or(0)+ };+ assert!(!inked.is_empty());+ assert!(+ span(|p| p.1) > span(|p| p.0) * 2,+ "a lance leaf along an upward stroke stands up"+ );+ let tap = Stroke::new(2, "lance", [0.0, 0.0, 0.0, 1.0], 80.0, 9).with_points(&[(60.0, 60.0, 1.0)], 5.0);+ assert!(+ replay(256, 256, &[tap.into()], &brushes).unwrap().raster.count() > 0,+ "a tap still leaves a mark"+ );+ }+#[test]fn strokes_off_canvas_are_clipped() {let brushes = BrushSet::presets();diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rsindex 2fe27f1..ad64b34 100644--- a/crates/brush/src/lib.rs+++ b/crates/brush/src/lib.rs@@ -9,7 +9,7 @@ pub mod record;pub mod replay;pub mod tiles;-pub const ENGINE_VERSION: u32 = 5;+pub const ENGINE_VERSION: u32 = 6;pub use brush::{Brush, BrushSet};pub use engine::{diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rsindex ef626e6..57a5a06 100644--- a/crates/cli/src/main.rs+++ b/crates/cli/src/main.rs@@ -29,8 +29,8 @@ use klad_core::fill::{EXPAND, FillSource, TOLERANCE};use klad_core::history::Stack;use klad_core::markedit::{LassoAction, MarkTransform};use klad_core::ops::{- ClipEdit, CopySpec, CopyTarget, FillSpec, FoliageSpec, HatchSpec, InbetweenSpec, InkSpec, LassoSpec, LightSpec, Op,- PaintSpec, PaletteEdit, Place, ScatterSpec, StrokeSpec,+ ClipEdit, CopySpec, CopyTarget, FillSpec, FoliageSpec, GrassSpec, HatchSpec, InbetweenSpec, InkSpec, LassoSpec,+ LightSpec, Op, PaintSpec, PaletteEdit, Place, ScatterSpec, StrokeSpec,};use klad_core::retime::{Retime, RetimeSpec};use klad_core::stroke::{fills_of, strokes_of};@@ -1149,6 +1149,66 @@ enum Command {#[command(flatten)]flags: EditFlags,},+ #[command(+ about = "Grow grass in closed shapes: blades lit by the ground, smaller with distance, breaking the top edge",+ long_about = "Fill closed shapes with grass blades from the far (top) edge to the near (bottom) one: each blade rises from its root, leans with --wind (degrees) and bends, and is smaller and denser towards the top (--far is the far size against the near one). The ground under them rolls in soft patches about --patch px wide, lit by --light (or a --lamp x,y,height): each blade runs from a dark root to a lit tip in a few value families from --shade through --color to --lit. Along the top edge taller blades (--edge) break the outline against what is behind. Near blades are drawn last.\n\nWith a stroke brush (blade, the default, or any round or chalk tip) each blade is a tapered stroke whose colour runs from --color at the root to the lit colour at the tip when the brush blends to a second colour by pressure. With a picture brush (a tip made of pictures, like your own tufts) each blade is one stamp of the picture, turned to the blade. Build your own brush for your grass (klad brushes --picture, --set) and pass it with --brush: the op decides where the marks go and how they are lit, the brush decides what they look like.\n\n klad grass meadow.draw field --in field-shape --color '#6f8a3c' --light -0.9,-0.45 --blade 30 --far 0.22\n klad grass meadow.draw bank --in bank --brush my-tuft --blade 160 --density 0.1\n\nAlso a grass op: {\"op\":\"grass\",\"layer\":\"field\",\"in\":[\"field-shape\"],\"color\":\"#6f8a3c\",\"blade\":30,\"far\":0.22,\"wind\":12}."+ )]+ Grass {+ bundle: PathBuf,+ layer: String,+ #[arg(long = "in", value_delimiter = ',', help = "Closed vector shapes to grow grass in")]+ within: Vec<String>,+ #[arg(long, default_value = "#5f8a3e", help = "The grass's middle colour")]+ color: String,+ #[arg(long, help = "The lit tips' colour (default: lighter and warmer)")]+ lit: Option<String>,+ #[arg(long, help = "The shadowed roots' colour (default: darker and cooler)")]+ shade: Option<String>,+ #[arg(long, value_parser = parse_pair, allow_hyphen_values = true, default_value = "-1,-1")]+ light: [f32; 2],+ #[arg(long, help = "A lamp at x,y,height in canvas px instead of a direction")]+ lamp: Option<String>,+ #[arg(long, default_value_t = 36.0, help = "Blade length in px at the near edge")]+ blade: f32,+ #[arg(long, help = "Blade width in px at the near edge (default: an eighth of the length)")]+ width: Option<f32>,+ #[arg(long, default_value_t = 0.45, help = "Size at the far edge against the near one")]+ far: f32,+ #[arg(+ long,+ default_value_t = 8.0,+ allow_hyphen_values = true,+ help = "How far the blades lean, degrees (negative leans left)"+ )]+ wind: f32,+ #[arg(+ long,+ default_value_t = 1.0,+ help = "How close the blades stand (2 is twice as many)"+ )]+ density: f32,+ #[arg(+ long,+ default_value_t = 1.35,+ help = "How much taller the blades along the top edge are"+ )]+ edge: f32,+ #[arg(+ long,+ help = "Width of the ground's light patches in px (default: four blade lengths)"+ )]+ patch: Option<f32>,+ #[arg(long, default_value = "blade")]+ brush: String,+ #[arg(long, default_value_t = 1)]+ seed: u32,+ #[arg(long, default_value_t = 0)]+ frame: u32,+ #[arg(long, help = "Put the new marks in this part of the drawing (see klad part)")]+ part: Option<String>,+ #[command(flatten)]+ flags: EditFlags,+ },#[command(about = "List closed regions of the lines that no fill on the layer covers",long_about = "List the closed regions of a fill layer's reference (the lines its flood fills fill against) that no fill on the layer covers: pockets a fill missed, or drawings not coloured yet. Regions open to the canvas edge are the outside and do not count. Each pocket prints its bounds and size, and a render of the frame marks them in magenta with a box.\n\n klad gaps art.draw colour --frame 4\n klad gaps art.draw colour --sheet all\n klad gaps art.draw colour --sheet walk --ref lines --gap 4\n\nThe reference, gap and tolerance default to those of the layer's flood fills on those frames."@@ -2497,6 +2557,58 @@ fn run() -> Result<()> {};agent::edit(&bundle, &[Op::Foliage(spec)], &output(&flags, frame))?;}+ Command::Grass {+ bundle,+ layer,+ within,+ color,+ lit,+ shade,+ light,+ lamp,+ blade,+ width,+ far,+ wind,+ density,+ edge,+ patch,+ brush,+ seed,+ frame,+ part,+ flags,+ } => {+ let lamp = lamp+ .as_deref()+ .map(|l| -> Result<[f32; 3]> {+ parse_numbers(l)?+ .try_into()+ .map_err(|_| anyhow!("--lamp {l:?} is not x,y,height"))+ })+ .transpose()?;+ let spec = GrassSpec {+ layer: layer_id(&bundle, &layer)?,+ frame,+ within,+ color,+ lit,+ shade,+ light,+ lamp,+ blade,+ width,+ far,+ wind,+ density,+ edge,+ patch,+ brush,+ seed,+ part,+ };+ agent::edit(&bundle, &[Op::Grass(spec)], &output(&flags, frame))?;+ }Command::Gaps {bundle,layer,diff --git a/crates/cli/src/shapes.rs b/crates/cli/src/shapes.rsindex 4459207..ccaeb0b 100644--- a/crates/cli/src/shapes.rs+++ b/crates/cli/src/shapes.rs@@ -3,7 +3,7 @@ use klad_core::bundle::Bundle;use klad_core::color;use klad_core::doc::Document;use klad_core::ops::{- FillSpec, FoliageSpec, HatchSpec, InkSpec, LightSpec, Op, PaintSpec, ScatterSpec, StrokeSpec, apply_all,+ FillSpec, FoliageSpec, GrassSpec, HatchSpec, InkSpec, LightSpec, Op, PaintSpec, ScatterSpec, StrokeSpec, apply_all,};use klad_render::form::{self, Form, FormRules, Lighting, Shadow};use klad_render::shapes::{self, HatchRules, InkRules, Outline, P, Run, ScatterRules};@@ -527,6 +527,165 @@ fn foliage(doc: &Document, spec: &FoliageSpec) -> Result<Vec<Op>> {Ok(leaves.into_iter().map(|(_, op)| op).collect())}+fn field(x: f32, y: f32, seed: u32) -> f32 {+ let at = |x: f32, y: f32, salt: u32| {+ let (ix, iy) = (x.floor(), y.floor());+ let (fx, fy) = (x - ix, y - iy);+ let (sx, sy) = (fx * fx * (3.0 - 2.0 * fx), fy * fy * (3.0 - 2.0 * fy));+ let h = |dx: i32, dy: i32| klad_core::rng::hash2_unit(ix as i32 + dx, iy as i32 + dy, seed ^ salt);+ let top = h(0, 0) + (h(1, 0) - h(0, 0)) * sx;+ let bottom = h(0, 1) + (h(1, 1) - h(0, 1)) * sx;+ top + (bottom - top) * sy+ };+ at(x, y, 0x51) * 0.7 + at(x * 2.3 + 17.0, y * 2.3 + 5.0, 0xa7) * 0.3+}++fn grass(doc: &Document, bundle: &Bundle, spec: &GrassSpec) -> Result<Vec<Op>> {+ let found = areas(doc, &spec.within, &None, "grass")?;+ let colour = |text: &str| -> Result<[f32; 3]> { Ok(color::to_oklab(color::parse_hex(&doc.resolve_color(text)?)?)) };+ let mid = colour(&spec.color)?;+ let given = |c: &Option<String>, shift: [f32; 3]| -> Result<[f32; 3]> {+ match c {+ Some(c) => colour(c),+ None => Ok(std::array::from_fn(|i| mid[i] + shift[i])),+ }+ };+ let lit = given(&spec.lit, [0.16, -0.012, 0.05])?;+ let shade = given(&spec.shade, [-0.2, -0.01, -0.04])?;+ let hex = |lab: [f32; 3]| color::to_hex(color::from_oklab(lab, 1.0));+ let picture = klad_brush::BrushSet::for_bundle(bundle)?+ .def(&spec.brush)+ .map(|d| matches!(d.tip, klad_core::brushes::TipDef::Image { .. }))+ .ok_or_else(|| anyhow::anyhow!("no brush {}: klad brushes lists them", spec.brush))?;+ let (mut x0, mut y0, mut x1, mut y1) = (f32::MAX, f32::MAX, f32::MIN, f32::MIN);+ found.iter().flatten().for_each(|p| {+ (x0, y0, x1, y1) = (x0.min(p[0]), y0.min(p[1]), x1.max(p[0]), y1.max(p[1]));+ });+ let depth = |y: f32| ((y - y0) / (y1 - y0).max(1.0)).clamp(0.0, 1.0);+ let scale = |y: f32| spec.far + (1.0 - spec.far) * depth(y);+ let width = spec.width.unwrap_or(spec.blade * 0.12).max(0.5);+ let patch = spec.patch.unwrap_or(spec.blade * 4.0).max(4.0);+ let flat = (spec.light[0].powi(2) + spec.light[1].powi(2)).sqrt().max(1e-4);+ let towards = |p: P| -> P {+ match spec.lamp {+ Some([lx, ly, _]) => {+ let (dx, dy) = (lx - p[0], ly - p[1]);+ let d = (dx * dx + dy * dy).sqrt().max(1e-4);+ [dx / d, dy / d]+ }+ None => [spec.light[0] / flat, spec.light[1] / flat],+ }+ };+ let mound = |p: P| {+ let s = scale(p[1]);+ field(p[0] / (patch * s), p[1] / (patch * 0.3 * s), spec.seed)+ };+ let tone_at = |p: P| -> f32 {+ let l = towards(p);+ let d = patch * 0.25;+ let facing = mound([p[0] - l[0] * d, p[1] - l[1] * d]) - mound([p[0] + l[0] * d, p[1] + l[1] * d]);+ let raw = 0.5 + 1.3 * facing + 0.3 * (mound(p) - 0.5);+ let near = 0.6 + 0.4 * depth(p[1]);+ (0.5 + (raw - 0.5) * near).clamp(0.0, 1.0)+ };+ let step = |tone: f32| (tone * 3.0).floor().min(2.0) / 3.0 + 1.0 / 6.0;+ let shaded = |tone: f32| -> [f32; 3] {+ match tone < 0.5 {+ true => mix_lab(shade, mid, (tone * 2.0).clamp(0.0, 1.0)),+ false => mix_lab(mid, lit, (tone * 2.0 - 1.0).clamp(0.0, 1.0)),+ }+ };+ let mut rng = klad_core::rng::Rng::new(spec.seed as u64 * 6_271 + 3);+ let mut blades: Vec<(f32, Op)> = Vec::new();+ let mut blade = |rng: &mut klad_core::rng::Rng, root: P, length: f32, tall: f32| -> Result<()> {+ let s = scale(root[1]);+ let lean = (spec.wind + rng.signed() * 14.0).to_radians();+ let dir = [lean.sin(), -lean.cos()];+ let side = [-dir[1], dir[0]];+ let length = length * s * tall;+ let bend = length * (0.08 + 0.08 * rng.signed().abs()) * if spec.wind < 0.0 { -1.0 } else { 1.0 };+ let tone = tone_at(root);+ let family = step(tone) + (tone - step(tone)) * 0.55;+ let l = towards(root);+ let catches = (dir[0] * l[0] + dir[1] * l[1]).max(0.0) * 0.15;+ let base = shaded((family - 0.28).max(0.0));+ let top = shaded((family + 0.12 + catches + rng.signed() * 0.05 * (0.3 + family)).clamp(0.0, 1.0));+ let jitter = |lab: [f32; 3], r: &mut klad_core::rng::Rng| {+ [lab[0] + r.signed() * 0.02, lab[1], lab[2] + r.signed() * 0.008]+ };+ let (base, top) = (jitter(base, rng), jitter(top, rng));+ let at = |t: f32| -> [f32; 2] {+ let curve = bend * t * t;+ [+ root[0] + dir[0] * length * t + side[0] * curve,+ root[1] + dir[1] * length * t + side[1] * curve,+ ]+ };+ let (run, size): (Run, f32) = match picture {+ true => {+ let (a, b) = (at(0.48), at(0.52));+ (vec![[a[0], a[1], 1.0], [b[0], b[1], 1.0]], length)+ }+ false => (+ [(0.0, 1.0), (0.3, 0.85), (0.6, 0.55), (0.85, 0.25), (1.0, 0.05)]+ .iter()+ .map(|&(t, p)| {+ let q = at(t);+ [q[0], q[1], p]+ })+ .collect(),+ width * s * (0.8 + 0.4 * (rng.signed() + 1.0) / 2.0),+ ),+ };+ let seed = spec.seed.wrapping_mul(1_299_709).wrapping_add(blades.len() as u32 * 7);+ let mut value = json!({+ "layer": spec.layer, "frame": spec.frame, "brush": spec.brush,+ "color": hex(if picture { mix_lab(base, top, 0.45) } else { base }), "second": hex(top),+ "size": size, "points": run, "seed": seed, "taper": [0.0, 0.0],+ });+ if let Some(part) = &spec.part {+ value["part"] = json!(part);+ }+ blades.push((root[1], Op::Stroke(serde_json::from_value(value)?)));+ Ok(())+ };+ let gap = |y: f32| (width * scale(y) * 1.3 / spec.density.max(0.05)).max(1.0);+ let mut y = y0;+ while y <= y1 {+ let mut x = x0 + rng.signed().abs() * gap(y);+ while x <= x1 {+ let root = [x + rng.signed() * gap(y) * 0.4, y + rng.signed() * gap(y) * 0.5];+ if inside(&found, root) {+ let tall = 0.75 + 0.5 * mound(root);+ let length = spec.blade * (0.55 + 0.45 * (rng.signed() + 1.0) / 2.0);+ blade(&mut rng, root, length, tall)?;+ }+ x += gap(y) * 1.2;+ }+ y += gap(y);+ }+ resample(&found, width * 1.4 / spec.density.max(0.05))+ .into_iter()+ .try_for_each(|(p, t)| {+ let probe = (width * 0.5).max(1.0);+ let mut n = [t[1], -t[0]];+ if inside(&found, [p[0] + n[0] * probe, p[1] + n[1] * probe]) {+ n = [-n[0], -n[1]];+ }+ if n[1] > -0.3 || rng.signed() < -0.4 {+ return Ok::<_, anyhow::Error>(());+ }+ let root = [+ p[0] - n[0] * spec.blade * scale(p[1]) * 0.12,+ p[1] - n[1] * spec.blade * scale(p[1]) * 0.12,+ ];+ let length = spec.blade * (0.6 + 0.5 * (rng.signed() + 1.0) / 2.0);+ blade(&mut rng, root, length, spec.edge * (0.8 + 0.45 * mound(root)))+ })?;+ blades.sort_by(|a, b| a.0.total_cmp(&b.0));+ Ok(blades.into_iter().map(|(_, op)| op).collect())+}+fn shapes_change(op: &Op) -> bool {matches!(op,@@ -551,6 +710,7 @@ pub fn expand(bundle: &Bundle, ops: Vec<Op>) -> Result<Vec<Op>> {Op::Paint(spec) => Some(paint(&doc, spec)),Op::Scatter(spec) => Some(scatter(&doc, spec)),Op::Foliage(spec) => Some(foliage(&doc, spec)),+ Op::Grass(spec) => Some(grass(&doc, bundle, spec)),Op::Fill(spec) => spec.shape.as_ref().map(|id| shape_fill(&doc, spec, id)),_ => None,};@@ -638,6 +798,62 @@ mod tests {std::fs::remove_dir_all(&dir).unwrap();}+ #[test]+ fn grass_grows_far_to_near_smaller_far_off_and_breaks_the_top_edge() {+ let (dir, b) = bundle("grass");+ let ops = parse_lines(+ r##"{"op":"add","node":{"id":"field","type":"rect","x":0,"y":150,"w":400,"h":150},"in":"l4","frame":0}+{"op":"grass","layer":"l1","in":["field"],"color":"#6f8a3c","light":[-0.9,-0.45],"blade":30,"far":0.3,"seed":3}"##,+ )+ .unwrap();+ let made = expand(&b, ops.clone()).unwrap();+ assert_eq!(made, expand(&b, ops).unwrap(), "seeded");+ let blades: Vec<(P, P, f32, String, Option<String>)> = made+ .iter()+ .filter_map(|o| match o {+ Op::Stroke(s) => {+ let p = s.points.as_ref()?;+ Some((+ [p[0][0], p[0][1]],+ [p[p.len() - 1][0], p[p.len() - 1][1]],+ s.size,+ s.color.clone(),+ s.second.clone(),+ ))+ }+ _ => None,+ })+ .collect();+ assert!(blades.len() > 500, "{} blades", blades.len());+ assert!(+ blades.windows(2).all(|w| w[0].0[1] <= w[1].0[1]),+ "far blades are drawn first"+ );+ let long = |pick: &dyn Fn(f32) -> bool| {+ let chosen: Vec<f32> = blades+ .iter()+ .filter(|b| pick(b.0[1]))+ .map(|b| ((b.1[0] - b.0[0]).powi(2) + (b.1[1] - b.0[1]).powi(2)).sqrt())+ .collect();+ chosen.iter().sum::<f32>() / chosen.len().max(1) as f32+ };+ let (far, near) = (long(&|y| y < 180.0), long(&|y| y > 270.0));+ assert!(far < near * 0.75, "far blades are shorter: {far} against {near}");+ assert!(blades.iter().all(|b| b.1[1] < b.0[1]), "every blade rises");+ assert!(+ blades.iter().filter(|b| b.1[1] < 140.0).count() > 10,+ "the top edge is broken by blades"+ );+ let light = |hex: &str| color::to_oklab(color::parse_hex(hex).unwrap())[0];+ assert!(+ blades+ .iter()+ .all(|b| b.4.as_deref().is_some_and(|tip| light(tip) > light(&b.3))),+ "each blade is darker at the root than at the tip"+ );+ std::fs::remove_dir_all(&dir).unwrap();+ }+#[test]fn shapes_added_in_a_batch_are_inked_filled_lit_and_textured_in_the_same_batch() {let (dir, mut b) = bundle("batch");diff --git a/crates/core/brushes/library/blade.json b/crates/core/brushes/library/blade.jsonnew file mode 100644index 0000000..7a5284b--- /dev/null+++ b/crates/core/brushes/library/blade.json@@ -0,0 +1,8 @@+{+ "format": "draw-anything-brush/1",+ "name": "Blade",+ "tip": { "round": { "hardness": 0.85 } },+ "spacing": 0.12,+ "dynamics": { "size": { "pressure": { "min": 0.06 } } },+ "color": { "value": 0.03, "strokeValue": 0.03, "pressure": { "min": 0.0 } }+}diff --git a/crates/core/src/brushes.rs b/crates/core/src/brushes.rsindex 4d18947..cb4667c 100644--- a/crates/core/src/brushes.rs+++ b/crates/core/src/brushes.rs@@ -21,6 +21,7 @@ const LIBRARY: &[(&str, &str)] = &[("fog", include_str!("../brushes/library/fog.json")),("leaves", include_str!("../brushes/library/leaves.json")),("grass", include_str!("../brushes/library/grass.json")),+ ("blade", include_str!("../brushes/library/blade.json")),("splatter", include_str!("../brushes/library/splatter.json")),("wet", include_str!("../brushes/library/wet.json")),("smudge", include_str!("../brushes/library/smudge.json")),@@ -531,7 +532,7 @@ mod tests {let back = BrushDef::parse(&def.to_json().unwrap()).unwrap();assert_eq!(back, def, "{id}");});- assert_eq!(library_ids().len(), 21);+ assert_eq!(library_ids().len(), 22);assert!(library("ink").unwrap().taper[1] > 0.0);assert_eq!(legacy_m1("ink").unwrap().taper, [0.0, 0.0]);assert!(legacy_m1("marker").is_none());diff --git a/crates/core/src/bundle.rs b/crates/core/src/bundle.rsindex 51b8ea5..10e03c3 100644--- a/crates/core/src/bundle.rs+++ b/crates/core/src/bundle.rs@@ -528,6 +528,7 @@ pub fn summarize(ops: &[Op]) -> String {Op::Paint(spec) => format!("paint on {}", spec.layer),Op::Scatter(spec) => format!("scatter on {}", spec.layer),Op::Foliage(spec) => format!("foliage on {}", spec.layer),+ Op::Grass(spec) => format!("grass on {}", spec.layer),Op::Inbetween(spec) if spec.redo => "redo in-betweens".to_string(),Op::Inbetween(spec) => format!("in-between {} frames {} to {}",diff --git a/crates/core/src/ops.rs b/crates/core/src/ops.rsindex dcf5f17..f917e69 100644--- a/crates/core/src/ops.rs+++ b/crates/core/src/ops.rs@@ -146,6 +146,7 @@ pub enum Op {Paint(PaintSpec),Scatter(ScatterSpec),Foliage(FoliageSpec),+ Grass(GrassSpec),Clip(ClipEdit),Export {godot: Option<String>,@@ -573,6 +574,70 @@ pub struct FoliageSpec {pub part: Option<String>,}+#[derive(Clone, Debug, PartialEq, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct GrassSpec {+ pub layer: String,+ #[serde(default)]+ pub frame: u32,+ #[serde(default, rename = "in")]+ pub within: Vec<String>,+ #[serde(default = "grass_color")]+ pub color: String,+ #[serde(default)]+ pub lit: Option<String>,+ #[serde(default)]+ pub shade: Option<String>,+ #[serde(default = "default_light")]+ pub light: [f32; 2],+ #[serde(default)]+ pub lamp: Option<[f32; 3]>,+ #[serde(default = "grass_blade")]+ pub blade: f32,+ #[serde(default)]+ pub width: Option<f32>,+ #[serde(default = "grass_far")]+ pub far: f32,+ #[serde(default = "grass_wind")]+ pub wind: f32,+ #[serde(default = "full")]+ pub density: f32,+ #[serde(default = "grass_edge")]+ pub edge: f32,+ #[serde(default)]+ pub patch: Option<f32>,+ #[serde(default = "grass_brush")]+ pub brush: String,+ #[serde(default = "first_seed")]+ pub seed: u32,+ #[serde(default)]+ pub part: Option<String>,+}++fn grass_color() -> String {+ "#5f8a3e".into()+}++fn grass_blade() -> f32 {+ 36.0+}++fn grass_far() -> f32 {+ 0.45+}++fn grass_wind() -> f32 {+ 8.0+}++fn grass_edge() -> f32 {+ 1.35+}++fn grass_brush() -> String {+ "blade".into()+}+fn foliage_color() -> String {"#4f7a3c".into()}@@ -1203,6 +1268,7 @@ impl Op {"paint" => Op::Paint(serde_json::from_value(Value::Object(std::mem::take(&mut map)))?),"scatter" => Op::Scatter(serde_json::from_value(Value::Object(std::mem::take(&mut map)))?),"foliage" => Op::Foliage(serde_json::from_value(Value::Object(std::mem::take(&mut map)))?),+ "grass" => Op::Grass(serde_json::from_value(Value::Object(std::mem::take(&mut map)))?),"clip" => Op::Clip(parse_clip(&mut map)?),"export" => Op::Export {godot: match map.remove("godot") {@@ -2489,9 +2555,9 @@ pub fn apply(doc: &mut Document, op: &Op, out: &mut Applied) -> Result<()> {let id = duplicate_layer(doc, layer, out)?;out.added.push(id);}- Op::Ink(_) | Op::Light(_) | Op::Hatch(_) | Op::Paint(_) | Op::Scatter(_) | Op::Foliage(_) => {+ Op::Ink(_) | Op::Light(_) | Op::Hatch(_) | Op::Paint(_) | Op::Scatter(_) | Op::Foliage(_) | Op::Grass(_) => {bail!(- "ink, light, hatch, paint, scatter and foliage are turned into strokes and fills by klad ink, klad light, klad hatch, klad paint, klad scatter, klad foliage or klad apply first"+ "ink, light, hatch, paint, scatter, foliage and grass are turned into strokes and fills by klad ink, klad light, klad hatch, klad paint, klad scatter, klad foliage, klad grass or klad apply first");}Op::Inbetween(spec) => {diff --git a/docs/DESIGN.md b/docs/DESIGN.mdindex a25c829..5370776 100644--- a/docs/DESIGN.md+++ b/docs/DESIGN.md@@ -239,6 +239,8 @@ Every layer has `blend`, `opacity`, `visible`, `locked`, optional `mask`, `clip`- **Text (M5).** `{"type": "text", "text", "font", "x", "y", "size", "tracking", "leading", "align", "weight"}` with the node's fill and outline. The font is a file in the bundle's `fonts/` folder, so a drawing renders the same anywhere. Each line is shaped by `harfrust` (HarfBuzz's shaping in Rust: GPOS and `kern` kerning, ligatures, marks, scripts), `weight` sets a variable font's `wght` axis, and the outlines come from the file through `skrifa`, each glyph's contours merged with Skia's path ops so an outline never shows the overlaps variable fonts are built with; they are drawn as one path, never by the system's font engine, so the Mac and the container draw the same pixels. A missing font is refused with its name.- **Fonts (M5, S5.26).** klad ships about fifty open families for game art in `fonts/` (sans, serif, mono, display, handwriting, pixel; OFL-1.1 or Apache-2.0, unchanged from the Google Fonts repository at a pinned commit, listed with their licences in the notices; `fonts/update.py` fetches them again). `klad_render::fonts` finds that folder next to the binary (also `../Resources/fonts` in a Mac app and the repository's `fonts/` for development builds; `KLAD_FONTS` overrides), and keeps families downloaded on request in a per-user folder (`~/Library/Application Support/klad/fonts`, `$XDG_DATA_HOME/klad/fonts`, `%APPDATA%\klad\fonts`). `fonts/catalogue.json` lists every open family on Google Fonts (about 1,900) with its group and folder at the same commit, so `klad fonts --search` works offline and a download (`klad fonts --get`, or naming a family anywhere a font is taken) fetches exactly that commit's files with `curl`. Choosing a font anywhere (the CLI's `font=`, `klad font`, the editor's picker) copies the file and its licence into the bundle; the node keeps the file name. This replaces M5 choice 3 (no fonts with the app). The editor's frame and plane caches fold `klad_render::RENDER_VERSION` into their keys, so pictures cached before a renderer change are not shown again. A light layer is no kind of its own: a paint layer set to `add` with a soft glow (a shortcut button for it only confused the layers pane).- **Foliage (M5, S5.27).** `foliage` is a shape op (CLI only, principle 7): each closed shape becomes a clump built from leaf strokes on a jittered grid, each coloured from the clump lit as a round form (a normal from its bounding ellipse, mixed with the normal of an optional `mass` shape so clumps turn with the whole crown, a key light or a lamp, the underside darker) and stepped into three value families between `shade`, `color` and `lit` (OKLab; by default darker and cooler, lighter and warmer), with more variety in the light; then leaves along the outline, kept more where the outline faces the light or the sky, a few in `glow` on the shadow edge. Strokes are sorted dark to light so lit leaves land on top. It puts how foliage is painted (light families on the clump, the big mass before the texture, a broken silhouette) into one op, so an agent does not scatter leaves like confetti.+- **Grass (M5, S5.28).** `grass` is a shape op too: rows of blades from the far (top) edge of the shapes to the near one, scaled from `far` to 1 by depth, leaning by `wind` with a bend, each from a dark root (`color`) to a lit tip (`second`, the `blade` brush blends to it by pressure as the blade thins) over ground that rolls in a value noise foreshortened with depth, lit by the light or lamp in soft value families; taller blades root just inside the top edge and break it; strokes are sorted far to near. A picture brush gets one stamp per blade. Both ops take any brush: they place and light marks, the brush (often the agent's own pictures) gives them their look.+- **Picture brushes start facing the stroke (engine version 6).** A brush whose angle follows the stroke places its first dab before it knows the stroke's direction, so that dab points right. For a picture tip that made one-dab marks (a leaf, a tuft) never turn; such a brush now holds its first dab until the second point gives the direction (a tap is drawn when the stroke ends, `StrokePainter::end`, called by the replay and by the editor at pen up), the same live and in replay. Round, chalk and bristle tips keep the old first dab, so M1 drawings and every painted sample render as before; only strokes with picture tips and a following angle (`leaves`) change.## Strokesdiff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.mdindex 4260a0e..65daf31 100644--- a/docs/skill/SKILL.md+++ b/docs/skill/SKILL.md@@ -195,6 +195,7 @@ klad scatter art.draw lines --in ground --mark "M0 0 Q 3 -22 8 -40" --count 20 -klad paint art.draw paint --in body --color skin --light -1,-1 --weight 12 # a round form, painted from a light modelklad paint art.draw paint --in pillar --form cylinder --axis 90 --lamp 200,600,150 --color '#c9b8a0'klad foliage art.draw canopy --in clump1 --color '#4d7a3b' --light -0.6,-0.8 --leaf 16 --mass crown # a clump built from lit leaves+klad grass art.draw field --in field --color '#6f8a3c' --light -0.9,-0.45 --blade 30 --far 0.22 --wind 12 # blades lit by rolling groundklad prepare art.draw # buffer every drawing before the user opens it```@@ -204,6 +205,8 @@ klad prepare art.draw- `klad prepare art.draw [--from 0 --to 23]` replays every painted drawing of those frames into the cache after a big CLI change, so the editor opens and plays it without replaying strokes. The editor still makes its frame pictures itself, quickly, from the cached drawings.- Foliage: never one leaf picture scattered evenly, and never a smooth blob with leaves sprinkled on its edge; both look fake. Block the crown in as 6 to 12 clump shapes (irregular blobs with lobes) plus one `crown` shape around them all, then for each clump from back to front: fill a darker, slightly smaller core (about 0.82 of the clump, so the sky shows between the edge leaves) and run `foliage` on it with `mass: "crown"`. Every leaf takes its colour from the clump lit as a round form and turned with the whole crown, in three value families from a cool shade through `--color` to a warm `--lit`, with the most variety in the light; leaves along the outline break the silhouette, most where light and sky reach, a few glowing at the shadow edge. Back clumps a darker colour, front ones lighter; leaf size about a fiftieth of the crown's width (`samples/tree`). Far canopies stay soft vector masses.+- Grass: `grass` grows blades from the far (top) edge of a shape to the near one, smaller and denser far off (`--far`), leaning with `--wind`, each from a dark root to a lit tip over ground that rolls in soft light patches, with taller blades breaking the top edge. Fill the shape a dark green first so gaps read as depth. Several passes make a meadow: a field with short blades, a near bank with long ones, accents (tufts, seed heads) with a brush of your own, laid before the blades so the grass grows over their bases. Distant grass is a soft mass, not blades.+- The shape ops decide where marks go and how light colours them; the brush decides what a mark looks like, and it should be yours when the subject needs it. `foliage`, `grass`, `scatter` and `paint` all take `--brush`: a stroke brush (round or chalk tip) draws each leaf or blade as a stroke, a picture brush stamps one picture per mark, turned to it. To make one, draw the shape in a small drawing of its own (black on transparent, pointing right for brushes whose angle follows the stroke), `klad render` it to a PNG, add it with `klad brushes art.draw --picture tuft tuft.png`, and define the brush with `klad brushes art.draw --set tuft tuft.json` (`{"tip":{"image":{"image":"tuft","more":["tuft-b"]}},"angle":"follow","spacing":1}`; several pictures give variety). `samples/meadow/build.sh` does exactly this. Make a new leaf or tuft for each species and style instead of reusing the library's for everything.- Ink rules: heavier on the side away from `--light` (the direction the light comes from, -1,-1 is top left), heavier on the silhouette than on inner lines (an outline inside another shape given in the same call), thinner on tight curves, a seeded wobble (`--wobble 0` for none). Outlines split into separate strokes at corners sharper than `--break` (60 degrees); `--gap 3` leaves inkers' gaps where lines meet. Open details (folds, cracks, ribs) go through `--path "M..."`.- `klad light` writes lasso fills with a cut: on the shade layer the shape minus itself moved towards the light (`--soft 3` overlapping steps soften the inner edge), on the rim layer a band along the lit edge. Clip the shade layer (multiply) and the rim layer to the flats, as in `samples/lantern/`.- `samples/lantern/generate.py` is the whole recipe for a prop in about 100 lines; `samples/ink-shapes/` shows the ink options side by side.diff --git a/justfile b/justfileindex 22313d7..1e39b9b 100644--- a/justfile+++ b/justfile@@ -19,7 +19,7 @@ lint:cargo clippy --workspace --all-targets -- -D warningssamples: build- for s in lantern ink-shapes bounce creature courier solids lemons ruin sign tree; do FORCE=1 bash samples/$s/build.sh >/dev/null && echo "samples/$s/$s.draw"; done+ for s in lantern ink-shapes bounce creature courier solids lemons ruin sign tree meadow; do FORCE=1 bash samples/$s/build.sh >/dev/null && echo "samples/$s/$s.draw"; donenotices:bash licenses/notices.shdiff --git a/samples/README.md b/samples/README.mdindex 4afa3d6..fcb9d82 100644--- a/samples/README.md+++ b/samples/README.md@@ -13,6 +13,7 @@ Drawings made from scratch with the `klad` CLI, each from a generator that print| `lemons` | Painting by form with `klad paint` on locked flats, and a shadow colour: lavender shadows instead of brown ones (`PLAIN=1`: without it; `RELIEF=1`: with a relief effect on every object, lighting the thickness of the oil strokes) || `sign` | Lettering in fonts that come with klad: a gilded inn sign on a painted board, the text clipped to the board with a shadow and grain over it || `tree` | Foliage that reads as leaves: clumps built from leaf marks with `klad foliage`, each lit as a form and turning with the whole crown, leaves breaking the outline, a bark trunk painted as a cylinder |+| `meadow` | Grass that reads as grass with `klad grass`: a field receding in soft light patches, a near bank whose blades break its crest, and tufts with seed heads from a brush the build script makes itself (pictures drawn in klad, added with `klad brushes --picture` and `--set`) || `solids` | Painting stroke by stroke: a sphere, a cube and a cylinder built in 3D with `docs/skill/drawkit.py`, lit, painted with natural strokes |The generated `.draw` bundles and pictures stay out of git.diff --git a/samples/meadow/build.sh b/samples/meadow/build.shnew file mode 100755index 0000000..2a062b2--- /dev/null+++ b/samples/meadow/build.sh@@ -0,0 +1,30 @@+#!/usr/bin/env bash+set -euo pipefail+here="$(cd "$(dirname "$0")" && pwd)"+root="$(cd "$here/../.." && pwd)"+case "$(uname -s)" in+ Darwin) built=target ;;+ Linux) built=target/linux ;;+ *) built=target/windows ;;+esac+klad="${KLAD:-$root/${KLAD_TARGET_DIR:-$built}/release/klad}"+out="${1:-$here/meadow.draw}"+if [ -e "$out" ] && [ "${FORCE:-0}" != 1 ]; then+ echo "$out exists and may hold edits made in the editor; give another path, or FORCE=1 to rebuild it from generate.py" >&2+ exit 1+fi+work="$(mktemp -d)"+trap 'rm -rf "$work"' EXIT+rm -rf "$out"+"$klad" new "$out" --width 1600 --height 760 --layers 0 >/dev/null+for name in tuft tuft-b; do+ "$klad" new "$work/$name.draw" --width 256 --height 256 --layers 0 >/dev/null+ python3 "$here/generate.py" --picture "$name" | "$klad" apply "$work/$name.draw" >/dev/null+ "$klad" render "$work/$name.draw" -o "$work/$name.png" >/dev/null+ "$klad" brushes "$out" --picture "$name" "$work/$name.png" >/dev/null+done+python3 "$here/generate.py" --brush > "$work/tuft.json"+"$klad" brushes "$out" --set tuft "$work/tuft.json" >/dev/null+python3 "$here/generate.py" | "$klad" apply "$out" >/dev/null+"$klad" render "$out" -o "${out%.draw}.png"+"$klad" hash "$out" --no-cachediff --git a/samples/meadow/generate.py b/samples/meadow/generate.pynew file mode 100644index 0000000..2b5f66c--- /dev/null+++ b/samples/meadow/generate.py@@ -0,0 +1,103 @@+import json+import math+import random+import sys++W, H = 1600, 760+LIGHT = [-0.9, -0.45]+COLOURS = {"sky top": "#7fa3c9", "sky low": "#f2dcb0", "hill far": "#8ea6a8", "hill": "#6f8f7c", "field": "#6f8a3c",+ "field deep": "#3e5426", "bank": "#55702f", "bank deep": "#2a3a1c", "tuft": "#6d8a37"}+++def path(points, closed=True):+ d = "M" + " L".join(f"{x:.1f} {y:.1f}" for x, y in points)+ return d + (" Z" if closed else "")+++def ridge(x0, x1, y, amp, seed, step=20):+ rnd = random.Random(seed)+ phases = [rnd.uniform(0, math.tau) for _ in range(3)]+ return [(x, y + amp * (0.6 * math.sin(x * 0.004 + phases[0]) + 0.3 * math.sin(x * 0.011 + phases[1])+ + 0.1 * math.sin(x * 0.03 + phases[2]))) for x in range(x0, x1 + step, step)]+++def blade(root, length, width, lean, bend):+ left, right = [], []+ for i in range(13):+ t = i / 12+ x = root[0] + length * t+ y = root[1] + lean * length * t + bend * length * t * t+ w = width * (1 - t) ** 0.8 / 2+ left.append((x, y - w))+ right.append((x, y + w))+ return path(left + right[::-1])+++def picture(name):+ rnd = random.Random(sum(map(ord, name)))+ blades = 7 if name == "tuft" else 5+ out = [{"op": "add", "layer": {"id": "p", "kind": "vector", "name": "p"}}]+ for i in range(blades):+ root = (14, 128 + rnd.uniform(-10, 10))+ length = rnd.uniform(150, 232)+ lean = (i - blades / 2) / blades * rnd.uniform(0.35, 0.6)+ out.append({"op": "add", "node": {"type": "path", "d": blade(root, length, rnd.uniform(9, 14), lean, rnd.uniform(-0.15, 0.15)),+ "fill": "#000000"}, "in": "p"})+ if name == "tuft-b":+ stalk = [(14 + t * 236, 128 - 6 * math.sin(t * 2)) for t in [k / 10 for k in range(11)]]+ out.append({"op": "add", "node": {"type": "path", "d": path(stalk, False), "fill": "none",+ "stroke": {"paint": "#000000", "width": 3}}, "in": "p"})+ out.append({"op": "add", "node": {"type": "ellipse", "cx": 226, "cy": 124, "rx": 22, "ry": 7, "fill": "#000000"}, "in": "p"})+ return out+++def tuft_brush():+ return {"format": "draw-anything-brush/1", "name": "Tuft", "tip": {"image": {"image": "tuft", "more": ["tuft-b"]}},+ "spacing": 1.0, "angle": "follow", "jitter": {"size": 0.2, "angle": 0.15},+ "color": {"value": 0.05, "saturation": 0.04, "pressure": {"min": 0.0}}}+++def layer(id, kind, **extra):+ return {"op": "add", "layer": {"id": id, "kind": kind, "name": id, **extra}}+++def ops():+ out = [{"op": "palette", "add": c, "name": n} for n, c in COLOURS.items()]+ out += [+ layer("sketch", "vector", visible=False),+ layer("sky", "vector"),+ layer("hills", "vector"),+ layer("field", "paint"),+ layer("bank", "paint"),+ ]+ sky = {"linear": {"from": [0, 0], "to": [0, 470], "stops": [[0, COLOURS["sky top"]], [1, COLOURS["sky low"]]]}}+ out.append({"op": "add", "node": {"type": "rect", "x": 0, "y": 0, "w": W, "h": H, "fill": sky}, "in": "sky"})+ far = ridge(-20, W + 20, 390, 40, 3)+ out.append({"op": "add", "node": {"type": "path", "d": path(far + [(W + 20, 520), (-20, 520)]), "fill": COLOURS["hill far"],+ "blur": 2}, "in": "hills"})+ near = ridge(-20, W + 20, 430, 26, 5)+ out.append({"op": "add", "node": {"type": "path", "d": path(near + [(W + 20, 540), (-20, 540)]), "fill": COLOURS["hill"],+ "blur": 1}, "in": "hills"})+ field = ridge(-20, W + 20, 470, 12, 7, 16) + [(W + 20, H + 20), (-20, H + 20)]+ crest = [(-20, 560), (60, 540), (180, 512), (300, 498), (420, 506), (560, 540), (720, 590), (900, 640), (1080, 690),+ (1260, 740), (1300, H + 20), (-20, H + 20)]+ out += [{"op": "add", "node": {"id": "field-shape", "type": "path", "d": path(field)}, "in": "sketch"},+ {"op": "add", "node": {"id": "bank-shape", "type": "path", "d": path(crest)}, "in": "sketch"}]+ out.append({"op": "fill", "layer": "field", "shape": "field-shape", "color": "field deep", "expand": 0})+ out.append({"op": "grass", "layer": "field", "in": ["field-shape"], "color": COLOURS["field"], "light": LIGHT, "blade": 30,+ "far": 0.22, "wind": 12, "seed": 11})+ out.append({"op": "fill", "layer": "bank", "shape": "bank-shape", "color": "bank deep", "expand": 0})+ out.append({"op": "grass", "layer": "bank", "in": ["bank-shape"], "color": COLOURS["tuft"], "light": LIGHT, "blade": 165,+ "far": 0.85, "wind": 10, "density": 0.12, "edge": 1.2, "brush": "tuft", "seed": 17})+ out.append({"op": "grass", "layer": "bank", "in": ["bank-shape"], "color": COLOURS["bank"], "light": LIGHT, "blade": 58,+ "far": 0.8, "wind": 14, "edge": 1.5, "seed": 13})+ return out+++if __name__ == "__main__":+ if sys.argv[1:2] == ["--picture"]:+ print("\n".join(json.dumps(op) for op in picture(sys.argv[2])))+ elif sys.argv[1:2] == ["--brush"]:+ print(json.dumps(tuft_brush()))+ else:+ print("\n".join(json.dumps(op) for op in ops()))