mirror of
https://github.com/storytold/materialcraft.git
synced 2026-11-20 14:30:59 +01:00
Add 25 nodes: FX-Map, SVG, Text, tileable 3D noises, weathering and filters
Clean-room implementations, all tileable when they generate: - fx_map (Atomic): grid / random / random-quadtree instancer of up to three patterns with scale, rotation, position and luminance jitter and Max / Add / Alpha-over blending, on a shared binned splatting engine. - svg (Atomic): SVG path data parser (M L H V C S Q T Z, absolute and relative, errors instead of panics) with even-odd / non-zero fill (exact horizontal coverage on 4 sub-scanlines) and anti-aliased stroke. - text (Atomic): original single-stroke vector font rendered as capsules, with alignment, spacing, multi-line, rotation and edge wrapping. - perlin_noise_3d, worley_noise_3d (periodic 3D lattice, z scrubs) and simplex_noise_3d (4D simplex on a flat torus). - shape_splatter, paint_strokes, scratches_generator, cracks, rust, moss, leaks, edge_damage, tile_random, ambient_occlusion_fast, normal_from_height_hq, histogram_select, quantize_color, pixelate_color. Every new node cooks under 100 ms at 1024x1024 in release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
30020a9078
commit
cba0bd440a
10 files changed
+1833
-1
No files matched your search
@@ -22,6 +22,7 @@ images, materials, sample graphs, presets, environments) may ever be added.
|
||||
| `docs/images/materialcraft-new-graph.png` | README screenshot: the New graph dialog | MaterialCraft contributors | Offscreen render of MaterialCraft's UI | MIT OR Apache-2.0 |
|
||||
| `docs/images/materialcraft-materials.png` | README render: six sample materials on the material ball | MaterialCraft contributors | `materialcraft-cli render --scene material_ball --full`, six renders side by side | MIT OR Apache-2.0 |
|
||||
| `docs/brand/artcraft-*.svg`, `docs/brand/artcraft-*.png` | ArtCraft logo and mark | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms, not open source ([`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt)) |
|
||||
| `crates/nodes/src/text.rs` (`GLYPHS`) | Single-stroke vector font of the Text node (A–Z, a–z, 0–9, punctuation) | MaterialCraft contributors | Original, designed as stroke data in code | MIT OR Apache-2.0 |
|
||||
|
||||
## Third-party assets compiled into the binary
|
||||
|
||||
|
||||
@@ -317,15 +317,21 @@ pub fn catalog() -> &'static [NodeDef] {
|
||||
CAT.get_or_init(|| {
|
||||
let mut v = Vec::new();
|
||||
v.extend(crate::atomic::defs());
|
||||
v.extend(crate::fx_map::defs());
|
||||
v.extend(crate::svg::defs());
|
||||
v.extend(crate::text::defs());
|
||||
v.extend(crate::generators::defs());
|
||||
v.extend(crate::noises_more::defs());
|
||||
v.extend(crate::noise3d::defs());
|
||||
v.extend(crate::patterns::defs());
|
||||
v.extend(crate::patterns_more::defs());
|
||||
v.extend(crate::filters::defs());
|
||||
v.extend(crate::filters_more::defs());
|
||||
v.extend(crate::filters_extra::defs());
|
||||
v.extend(crate::flood_fill::defs());
|
||||
v.extend(crate::material::defs());
|
||||
v.extend(crate::material_more::defs());
|
||||
v.extend(crate::weathering::defs());
|
||||
v
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
//! More filters: random per-tile transforms, horizon-based ambient occlusion, a 5×5 Sobel normal
|
||||
//! map, value band selection, palette quantization and block-averaged pixelation.
|
||||
|
||||
use std::f32::consts::TAU;
|
||||
|
||||
use materialcraft_image::{Image, Kind, luminance};
|
||||
use rayon::prelude::*;
|
||||
|
||||
use crate::catalog::{CookResult, Ctx, NodeDef, node};
|
||||
use crate::filters_more::pack;
|
||||
use crate::noise::rand2;
|
||||
use crate::noises_more::smoothstep;
|
||||
|
||||
const ADJ: &str = "Filters/Adjustments";
|
||||
const EFFECTS: &str = "Filters/Effects";
|
||||
const NORMAL: &str = "Filters/Normal map";
|
||||
const TILING: &str = "Filters/Tiling";
|
||||
|
||||
pub(crate) fn defs() -> Vec<NodeDef> {
|
||||
vec![
|
||||
node("tile_random", "Tile Random", TILING)
|
||||
.desc("Cuts the image into a grid and shows a randomly offset, flipped and rotated window of the input in each tile (breaks up repetition).")
|
||||
.any_in("input", "Input")
|
||||
.int("x_amount", "X amount", 4, 1, 256)
|
||||
.int("y_amount", "Y amount", 4, 1, 256)
|
||||
.float("offset_random", "Offset random", 1.0, 0.0, 1.0)
|
||||
.boolean("rotate", "Random 90° rotation", true)
|
||||
.boolean("flip", "Random flip", true)
|
||||
.float("luminance_random", "Luminance random", 0.0, 0.0, 1.0)
|
||||
.cook(tile_random),
|
||||
node("ambient_occlusion_fast", "Ambient Occlusion (Fast)", EFFECTS)
|
||||
.desc("Horizon-based ambient occlusion of a height map: how much of the sky each pixel sees within the radius.")
|
||||
.gray_in("height", "Height")
|
||||
.float("radius", "Radius", 12.0, 1.0, 128.0)
|
||||
.float("height_depth", "Height depth", 0.3, 0.0, 1.0)
|
||||
.float("intensity", "Intensity", 1.0, 0.0, 2.0)
|
||||
.gray_out()
|
||||
.cook(ambient_occlusion_fast),
|
||||
node("normal_from_height_hq", "Normal from Height HQ", NORMAL)
|
||||
.desc("A smooth normal map from a height map with 5×5 Sobel slopes.")
|
||||
.gray_in("input", "Height")
|
||||
.float("intensity", "Intensity", 1.0, 0.0, 10.0)
|
||||
.choice("format", "Normal format", &["OpenGL", "DirectX"], 0)
|
||||
.color_out()
|
||||
.cook(normal_from_height_hq),
|
||||
node("histogram_select", "Histogram Select", ADJ)
|
||||
.desc("White where values lie in a band around the position, fading out with the contrast.")
|
||||
.gray_in("input", "Input")
|
||||
.float("position", "Position", 0.5, 0.0, 1.0)
|
||||
.float("range", "Range", 0.25, 0.0, 1.0)
|
||||
.float("contrast", "Contrast", 0.5, 0.0, 1.0)
|
||||
.gray_out()
|
||||
.cook(histogram_select),
|
||||
node("quantize_color", "Quantize Color", ADJ)
|
||||
.desc("Reduces the image to a palette of its most representative colors (k-means), with optional ordered dithering.")
|
||||
.color_in("input", "Input")
|
||||
.int("colors", "Colors", 8, 2, 64)
|
||||
.float("dither", "Dither", 0.0, 0.0, 1.0)
|
||||
.color_out()
|
||||
.cook(quantize_color),
|
||||
node("pixelate_color", "Pixelate Color", EFFECTS)
|
||||
.desc("Averages the image over blocks (separate X and Y counts).")
|
||||
.any_in("input", "Input")
|
||||
.int("x_cells", "X cells", 32, 1, 1024)
|
||||
.int("y_cells", "Y cells", 32, 1, 1024)
|
||||
.cook(pixelate_color),
|
||||
]
|
||||
}
|
||||
|
||||
fn tile_random(ctx: &Ctx) -> CookResult {
|
||||
let img = ctx.any_or(0, Kind::Gray, [0.0; 4]);
|
||||
let (nx, ny) = (ctx.i("x_amount").clamp(1, 256) as f32, ctx.i("y_amount").clamp(1, 256) as f32);
|
||||
let (off, rot, flip, lr, s) = (ctx.f("offset_random"), ctx.b("rotate"), ctx.b("flip"), ctx.f("luminance_random"), ctx.seed);
|
||||
Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| {
|
||||
let (cx, cy) = ((u * nx).floor(), (v * ny).floor());
|
||||
let (ci, cj) = ((cx as i32).rem_euclid(nx as i32), (cy as i32).rem_euclid(ny as i32));
|
||||
let r = |k: u32| rand2(ci, cj, s ^ k.wrapping_mul(0x2545_f491));
|
||||
// Offset from the tile center in uv, flipped and turned by quarter turns.
|
||||
let (mut a, mut b) = ((u * nx - cx - 0.5) / nx, (v * ny - cy - 0.5) / ny);
|
||||
if flip && r(1) < 0.5 {
|
||||
a = -a;
|
||||
}
|
||||
if rot {
|
||||
for _ in 0..(r(2) * 4.0) as i32 {
|
||||
(a, b) = (-b, a);
|
||||
}
|
||||
}
|
||||
let su = (cx + 0.5) / nx + a + (r(3) - 0.5) * off;
|
||||
let sv = (cy + 0.5) / ny + b + (r(4) - 0.5) * off;
|
||||
let p = img.sample(su, sv, true);
|
||||
let k = 1.0 - lr * r(5);
|
||||
[p[0] * k, p[1] * k, p[2] * k, p[3]]
|
||||
})])
|
||||
}
|
||||
|
||||
fn ambient_occlusion_fast(ctx: &Ctx) -> CookResult {
|
||||
const DIRS: usize = 8;
|
||||
const STEPS: usize = 6;
|
||||
let h = ctx.gray_or(0, 0.0);
|
||||
let scale = ctx.w as f32 / 256.0;
|
||||
let rad = (ctx.f("radius") * scale).clamp(1.0, 1024.0);
|
||||
let hs = ctx.f("height_depth") * 64.0 * scale;
|
||||
let k = ctx.f("intensity");
|
||||
// Integer offsets along each direction, denser near the pixel, and their true distances.
|
||||
let taps: Vec<(i64, i64, f32)> = (0..DIRS)
|
||||
.flat_map(|d| {
|
||||
let (sn, cs) = ((d as f32 + 0.5) / DIRS as f32 * TAU).sin_cos();
|
||||
(1..=STEPS).map(move |s| {
|
||||
let dist = rad * (s as f32 / STEPS as f32).powf(1.5);
|
||||
let (ox, oy) = ((cs * dist).round(), (sn * dist).round());
|
||||
(ox as i64, oy as i64, (ox * ox + oy * oy).sqrt().max(1.0))
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let tile = ctx.tile;
|
||||
Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Gray, |x, y| {
|
||||
let (x, y) = (x as i64, y as i64);
|
||||
let h0 = h.get_gray(x, y, tile);
|
||||
let occ: f32 = taps
|
||||
.chunks(STEPS)
|
||||
.map(|dir| {
|
||||
// Tangent of the highest horizon in this direction, as the sine of its angle.
|
||||
let m = dir.iter().fold(0.0f32, |m, &(ox, oy, d)| m.max((h.get_gray(x + ox, y + oy, tile) - h0) * hs / d));
|
||||
m / (1.0 + m * m).sqrt()
|
||||
})
|
||||
.sum();
|
||||
[(1.0 - k * occ / DIRS as f32).clamp(0.0, 1.0), 0.0, 0.0, 0.0]
|
||||
})])
|
||||
}
|
||||
|
||||
fn normal_from_height_hq(ctx: &Ctx) -> CookResult {
|
||||
const SMOOTH: [f32; 5] = [1.0, 4.0, 6.0, 4.0, 1.0];
|
||||
const DERIV: [f32; 5] = [-1.0, -2.0, 0.0, 2.0, 1.0];
|
||||
let h = ctx.gray_or(0, 0.0);
|
||||
// The kernels sum to 128 × the slope of a linear ramp.
|
||||
let k = ctx.f("intensity") * ctx.w as f32 / 32.0 / 128.0;
|
||||
let dx_fmt = ctx.i("format") == 1;
|
||||
Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Color, |x, y| {
|
||||
let (mut gx, mut gy) = (0.0, 0.0);
|
||||
for j in 0..5 {
|
||||
for i in 0..5 {
|
||||
let v = h.get_gray(x as i64 + i as i64 - 2, y as i64 + j as i64 - 2, ctx.tile);
|
||||
gx += SMOOTH[j] * DERIV[i] * v;
|
||||
gy += DERIV[j] * SMOOTH[i] * v;
|
||||
}
|
||||
}
|
||||
let ny = gy * k;
|
||||
pack([-gx * k, if dx_fmt { -ny } else { ny }, 1.0], 1.0)
|
||||
})])
|
||||
}
|
||||
|
||||
fn histogram_select(ctx: &Ctx) -> CookResult {
|
||||
let (pos, half) = (ctx.f("position"), ctx.f("range") * 0.5);
|
||||
let soft = (1.0 - ctx.f("contrast").clamp(0.0, 1.0)) * 0.25 + 1e-3;
|
||||
let img = ctx.gray_or(0, 0.0);
|
||||
Ok(vec![img.map(Kind::Gray, |p| [1.0 - smoothstep(half, half + soft, (p[0] - pos).abs()), 0.0, 0.0, 0.0])])
|
||||
}
|
||||
|
||||
/// Index of the color in `pal` nearest to `c`.
|
||||
fn nearest(pal: &[[f32; 3]], c: [f32; 3]) -> usize {
|
||||
let d = |p: &[f32; 3]| (p[0] - c[0]).powi(2) + (p[1] - c[1]).powi(2) + (p[2] - c[2]).powi(2);
|
||||
pal.iter().enumerate().min_by(|a, b| d(a.1).total_cmp(&d(b.1))).map_or(0, |(i, _)| i)
|
||||
}
|
||||
|
||||
fn quantize_color(ctx: &Ctx) -> CookResult {
|
||||
const BAYER: [f32; 16] = [0.0, 8.0, 2.0, 10.0, 12.0, 4.0, 14.0, 6.0, 3.0, 11.0, 1.0, 9.0, 15.0, 7.0, 13.0, 5.0];
|
||||
let img = ctx.any_or(0, Kind::Color, [0.5, 0.5, 0.5, 1.0]).to_color();
|
||||
let k = ctx.i("colors").clamp(2, 64) as usize;
|
||||
let rgb = |p: &[f32]| [p[0], p[1], p[2]];
|
||||
// Lloyd's k-means on up to ~4096 samples, seeded at luminance quantiles.
|
||||
let step = (img.data.len() / 4 / 4096).max(1);
|
||||
let mut samples: Vec<[f32; 3]> = img.data.chunks_exact(4).step_by(step).map(rgb).collect();
|
||||
samples.sort_by(|a, b| luminance([a[0], a[1], a[2], 1.0]).total_cmp(&luminance([b[0], b[1], b[2], 1.0])));
|
||||
let mut pal: Vec<[f32; 3]> = (0..k).filter_map(|j| samples.get(((j as f32 + 0.5) / k as f32 * samples.len() as f32) as usize).copied()).collect();
|
||||
for _ in 0..8 {
|
||||
let mut acc = vec![[0.0f32; 4]; pal.len()];
|
||||
for s in &samples {
|
||||
if let Some(a) = acc.get_mut(nearest(&pal, *s)) {
|
||||
*a = [a[0] + s[0], a[1] + s[1], a[2] + s[2], a[3] + 1.0];
|
||||
}
|
||||
}
|
||||
for (p, a) in pal.iter_mut().zip(&acc) {
|
||||
if a[3] > 0.0 {
|
||||
*p = [a[0] / a[3], a[1] / a[3], a[2] / a[3]];
|
||||
}
|
||||
}
|
||||
}
|
||||
let spread = ctx.f("dither") / (k as f32).cbrt();
|
||||
Ok(vec![Image::generate(img.w, img.h, Kind::Color, |x, y| {
|
||||
let p = img.get(x as i64, y as i64, false);
|
||||
let d = ((BAYER[(y as usize % 4) * 4 + x as usize % 4] + 0.5) / 16.0 - 0.5) * spread;
|
||||
let c = pal.get(nearest(&pal, [p[0] + d, p[1] + d, p[2] + d])).copied().unwrap_or([p[0], p[1], p[2]]);
|
||||
[c[0], c[1], c[2], p[3]]
|
||||
})])
|
||||
}
|
||||
|
||||
fn pixelate_color(ctx: &Ctx) -> CookResult {
|
||||
let img = ctx.any_or(0, Kind::Color, [0.0, 0.0, 0.0, 1.0]);
|
||||
let (w, h) = (img.w as usize, img.h as usize);
|
||||
let (nx, ny) = (ctx.i("x_cells").clamp(1, 1024) as usize, ctx.i("y_cells").clamp(1, 1024) as usize);
|
||||
// Block `b` of `n` over `len` pixels covers `b·len/n .. (b+1)·len/n` (at least one pixel).
|
||||
let range = |n: usize, len: usize, b: usize| (b * len / n, ((b + 1) * len / n).max(b * len / n + 1).min(len));
|
||||
let block = |n: usize, len: usize, p: usize| (((p + 1) * n).saturating_sub(1) / len).min(n - 1);
|
||||
let means: Vec<[f32; 4]> = (0..nx * ny)
|
||||
.into_par_iter()
|
||||
.map(|bi| {
|
||||
let ((x0, x1), (y0, y1)) = (range(nx, w, bi % nx), range(ny, h, bi / nx));
|
||||
let mut s = [0.0f32; 4];
|
||||
for y in y0..y1 {
|
||||
for x in x0..x1 {
|
||||
let p = img.get(x as i64, y as i64, false);
|
||||
s = std::array::from_fn(|c| s[c] + p[c]);
|
||||
}
|
||||
}
|
||||
let n = ((x1 - x0) * (y1 - y0)).max(1) as f32;
|
||||
s.map(|v| v / n)
|
||||
})
|
||||
.collect();
|
||||
Ok(vec![Image::generate(img.w, img.h, img.kind, |x, y| {
|
||||
means.get(block(ny, h, y as usize) * nx + block(nx, w, x as usize)).copied().unwrap_or([0.0, 0.0, 0.0, 1.0])
|
||||
})])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn nearest_and_block_math() {
|
||||
assert_eq!(nearest(&[[0.0; 3], [1.0; 3]], [0.7; 3]), 1);
|
||||
// Pixelate: a 2-cell split of a black/white image averages each half exactly.
|
||||
let img = Image::gray(8, 2, |x, _| if x < 4 { 0.0 } else { 1.0 });
|
||||
let def = crate::catalog::find("pixelate_color").unwrap();
|
||||
let mut p = crate::catalog::resolve_params(def, &Default::default());
|
||||
p.insert("x_cells".into(), materialcraft_core::Value::Int(2));
|
||||
p.insert("y_cells".into(), materialcraft_core::Value::Int(1));
|
||||
let no_res = |_: &str| None;
|
||||
let vars = Default::default();
|
||||
let inputs = [Some(img)];
|
||||
let ctx = Ctx { w: 8, h: 2, seed: 0, tile: true, inputs: &inputs, params: &p, resource: &no_res, vars: &vars };
|
||||
let out = &pixelate_color(&ctx).unwrap()[0];
|
||||
assert_eq!((out.get(3, 1, false)[0], out.get(4, 0, false)[0]), (0.0, 1.0));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
//! Atomic › FX-Map: a pattern instancer (regular grid, random scatter or random quadtree
|
||||
//! subdivision), plus the shared splatting engine of the scatter nodes. Instances wrap across the
|
||||
//! edges, so the output tiles.
|
||||
|
||||
use std::f32::consts::{SQRT_2, TAU};
|
||||
|
||||
use materialcraft_image::{Image, Kind};
|
||||
|
||||
use crate::atomic::ATOMIC;
|
||||
use crate::catalog::{CookResult, Ctx, NodeDef, node};
|
||||
use crate::noise::{hash, rand1};
|
||||
use crate::patterns::{PATTERNS, SHAPES, shape};
|
||||
|
||||
/// One placed pattern: center (uv), half extents (uv), rotation (turns), luminance and the index
|
||||
/// of the pattern it shows.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct Inst {
|
||||
pub c: [f32; 2],
|
||||
pub r: [f32; 2],
|
||||
pub rot: f32,
|
||||
pub lum: f32,
|
||||
pub pat: usize,
|
||||
}
|
||||
|
||||
pub(crate) const BLENDS: &[&str] = &["Max", "Add", "Alpha over"];
|
||||
|
||||
/// Renders `items` over black. Item `i` covers the rotated box ±`r` around its center, where
|
||||
/// `pat(i, x, y)` is its pattern (0..1) at local coordinates -1..1. Items are binned on a grid about
|
||||
/// their size so a pixel only tests its neighbours; later items draw on top (Alpha over).
|
||||
pub(crate) fn splat(ctx: &Ctx, items: &[Inst], blend: i32, pat: impl Fn(usize, f32, f32) -> f32 + Sync) -> Image {
|
||||
let valid = |it: &Inst| it.r[0] > 1e-6 && it.r[1] > 1e-6 && it.c.iter().chain(&it.r).all(|v| v.is_finite());
|
||||
let n = items.iter().filter(|it| valid(it)).count().max(1);
|
||||
let mean_r = items.iter().filter(|it| valid(it)).map(|it| it.r[0].max(it.r[1])).sum::<f32>() / n as f32;
|
||||
let g = ((0.5 / mean_r.max(1e-4)) as usize).clamp(1, 256);
|
||||
let gf = g as f32;
|
||||
let mut bins: Vec<Vec<u32>> = vec![Vec::new(); g * g];
|
||||
for (i, it) in items.iter().enumerate().filter(|(_, it)| valid(it)) {
|
||||
let br = it.r[0].max(it.r[1]) * SQRT_2;
|
||||
// At most one full turn of bins per axis, so no item lands twice in a bin.
|
||||
let span = |c: f32| {
|
||||
let a = ((c - br) * gf).floor() as i64;
|
||||
(a, (((c + br) * gf).floor() as i64).min(a + g as i64 - 1))
|
||||
};
|
||||
let ((x0, x1), (y0, y1)) = (span(it.c[0]), span(it.c[1]));
|
||||
for gy in y0..=y1 {
|
||||
for gx in x0..=x1 {
|
||||
if let Some(b) = bins.get_mut(gy.rem_euclid(g as i64) as usize * g + gx.rem_euclid(g as i64) as usize) {
|
||||
b.push(i as u32);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let rots: Vec<(f32, f32)> = items.iter().map(|it| (-it.rot * TAU).sin_cos()).collect();
|
||||
let tile = ctx.tile;
|
||||
Image::generate_uv(ctx.w, ctx.h, Kind::Gray, |u, v| {
|
||||
let mut acc = 0.0f32;
|
||||
let bin = bins.get(((v * gf) as usize).min(g - 1) * g + ((u * gf) as usize).min(g - 1));
|
||||
for &i in bin.into_iter().flatten() {
|
||||
let (Some(it), Some(&(s, c))) = (items.get(i as usize), rots.get(i as usize)) else { continue };
|
||||
let (mut dx, mut dy) = (u - it.c[0], v - it.c[1]);
|
||||
if tile {
|
||||
dx -= dx.round();
|
||||
dy -= dy.round();
|
||||
}
|
||||
let (x, y) = ((dx * c - dy * s) / it.r[0], (dx * s + dy * c) / it.r[1]);
|
||||
if x.abs() > 1.0 || y.abs() > 1.0 {
|
||||
continue;
|
||||
}
|
||||
let p = pat(i as usize, x, y);
|
||||
if p <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
acc = match blend {
|
||||
1 => acc + p * it.lum,
|
||||
2 => acc + (it.lum - acc) * p.min(1.0),
|
||||
_ => acc.max(p * it.lum),
|
||||
};
|
||||
}
|
||||
[acc, 0.0, 0.0, 0.0]
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn defs() -> Vec<NodeDef> {
|
||||
vec![
|
||||
node("fx_map", "FX-Map", ATOMIC)
|
||||
.desc(
|
||||
"Instances up to three patterns on a grid, at random positions or in a random quadtree, with per-instance scale, rotation, \
|
||||
position and luminance jitter. Scale 1 fills an instance's cell. Unconnected: soft discs. Tiles.",
|
||||
)
|
||||
.atomic()
|
||||
.generator()
|
||||
.gray_in("pattern0", "Pattern 0")
|
||||
.gray_in("pattern1", "Pattern 1")
|
||||
.gray_in("pattern2", "Pattern 2")
|
||||
.choice("mode", "Mode", &["Grid", "Random", "Quadtree"], 2)
|
||||
.int("count", "Count (random)", 64, 1, 20000)
|
||||
.int("x_amount", "X amount", 4, 1, 256)
|
||||
.int("y_amount", "Y amount", 4, 1, 256)
|
||||
.int("subdivisions", "Subdivisions (quadtree)", 3, 0, 8)
|
||||
.float("split_chance", "Subdivide chance", 0.5, 0.0, 1.0)
|
||||
.float("scale", "Scale", 0.9, 0.0, 2.0)
|
||||
.float("scale_random", "Scale random", 0.2, 0.0, 1.0)
|
||||
.angle("rotation", "Rotation", 0.0)
|
||||
.float("rotation_random", "Rotation random", 0.0, 0.0, 1.0)
|
||||
.float("position_random", "Position random", 0.0, 0.0, 1.0)
|
||||
.float("luminance", "Luminance", 1.0, 0.0, 1.0)
|
||||
.float("luminance_random", "Luminance random", 0.4, 0.0, 1.0)
|
||||
.float("pattern_random", "Pattern random", 1.0, 0.0, 1.0)
|
||||
.choice("blending", "Blending", BLENDS, 0)
|
||||
.int("seed_offset", "Seed offset", 0, 0, 10000)
|
||||
.gray_out()
|
||||
.cook(fx_map),
|
||||
node("shape_splatter", "Shape Splatter", PATTERNS)
|
||||
.desc("Scatters the pattern input (or a shape) with random scale, rotation and luminance; the mask input sets where instances land.")
|
||||
.generator()
|
||||
.gray_in("pattern", "Pattern")
|
||||
.gray_in("mask", "Mask")
|
||||
.choice("shape", "Shape (no input)", SHAPES, 3)
|
||||
.int("count", "Count", 300, 1, 20000)
|
||||
.float("size", "Size", 0.05, 0.0, 1.0)
|
||||
.float("size_random", "Size random", 0.5, 0.0, 1.0)
|
||||
.float("rotation_random", "Rotation random", 1.0, 0.0, 1.0)
|
||||
.float("luminance_random", "Luminance random", 0.4, 0.0, 1.0)
|
||||
.choice("blending", "Blending", BLENDS, 0)
|
||||
.gray_out()
|
||||
.cook(shape_splatter),
|
||||
]
|
||||
}
|
||||
|
||||
/// A connected pattern at local `(x, y)` (-1..1), or a soft disc when there is none.
|
||||
pub(crate) fn sample_pattern(pats: &[Image], k: usize, x: f32, y: f32) -> f32 {
|
||||
match pats.get(k) {
|
||||
Some(img) => img.sample_gray((x + 1.0) * 0.5, (y + 1.0) * 0.5, false),
|
||||
None => shape(3, x, y),
|
||||
}
|
||||
}
|
||||
|
||||
/// Cells of a random quadtree over an `nx × ny` root grid: (center, size, key). A cell splits
|
||||
/// with probability `chance` until `depth`.
|
||||
fn quadtree(nx: i32, ny: i32, depth: i32, chance: f32, seed: u32) -> Vec<([f32; 2], [f32; 2], u32)> {
|
||||
const MAX_CELLS: usize = 1 << 18;
|
||||
let mut out = Vec::new();
|
||||
let mut stack: Vec<([f32; 2], [f32; 2], i32, u32)> = Vec::new();
|
||||
for j in (0..ny).rev() {
|
||||
for i in (0..nx).rev() {
|
||||
let size = [1.0 / nx as f32, 1.0 / ny as f32];
|
||||
stack.push(([i as f32 * size[0], j as f32 * size[1]], size, 0, hash((j * nx + i) as u32 ^ 0x5157_0000)));
|
||||
}
|
||||
}
|
||||
while let Some((p, s, lvl, key)) = stack.pop() {
|
||||
if lvl < depth && rand1(key, seed ^ 0x51ed) < chance && out.len() + stack.len() + 4 <= MAX_CELLS {
|
||||
let h = [s[0] * 0.5, s[1] * 0.5];
|
||||
for q in (0..4u32).rev() {
|
||||
let o = [p[0] + (q & 1) as f32 * h[0], p[1] + (q >> 1) as f32 * h[1]];
|
||||
stack.push((o, h, lvl + 1, hash(key.wrapping_mul(4).wrapping_add(q + 1))));
|
||||
}
|
||||
} else {
|
||||
out.push(([p[0] + s[0] * 0.5, p[1] + s[1] * 0.5], s, key));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The instances an FX-Map places (separate from rendering, so it can be tested).
|
||||
pub(crate) fn fx_instances(ctx: &Ctx, n_patterns: usize) -> Vec<Inst> {
|
||||
let seed = ctx.seed.wrapping_add(ctx.i("seed_offset") as u32);
|
||||
let (nx, ny) = (ctx.i("x_amount").clamp(1, 256), ctx.i("y_amount").clamp(1, 256));
|
||||
let cells: Vec<([f32; 2], [f32; 2], u32)> = match ctx.i("mode") {
|
||||
0 => (0..ny)
|
||||
.flat_map(|j| {
|
||||
(0..nx).map(move |i| ([(i as f32 + 0.5) / nx as f32, (j as f32 + 0.5) / ny as f32], [1.0 / nx as f32, 1.0 / ny as f32], (j * nx + i) as u32))
|
||||
})
|
||||
.collect(),
|
||||
1 => {
|
||||
let count = ctx.i("count").clamp(1, 20000) as u32;
|
||||
let side = 1.0 / (count as f32).sqrt();
|
||||
(0..count).map(|i| ([rand1(i * 2, seed ^ 0xa11), rand1(i * 2 + 1, seed ^ 0xa11)], [side, side], i)).collect()
|
||||
}
|
||||
_ => quadtree(nx, ny, ctx.i("subdivisions").clamp(0, 8), ctx.f("split_chance"), seed),
|
||||
};
|
||||
let (sc, sr, rot, rr, pr) = (ctx.f("scale"), ctx.f("scale_random"), ctx.f("rotation"), ctx.f("rotation_random"), ctx.f("position_random"));
|
||||
let (lum, lr, patr) = (ctx.f("luminance"), ctx.f("luminance_random"), ctx.f("pattern_random"));
|
||||
let n = n_patterns.max(1);
|
||||
cells
|
||||
.into_iter()
|
||||
.map(|(c, size, key)| {
|
||||
let r = |k: u32| rand1(key.wrapping_mul(8).wrapping_add(k), seed);
|
||||
let s = sc * (1.0 - sr * r(2));
|
||||
Inst {
|
||||
c: [c[0] + (r(0) - 0.5) * pr * size[0], c[1] + (r(1) - 0.5) * pr * size[1]],
|
||||
r: [size[0] * 0.5 * s, size[1] * 0.5 * s],
|
||||
rot: rot + (r(3) - 0.5) * rr,
|
||||
lum: lum * (1.0 - lr * r(4)),
|
||||
pat: if r(5) < patr { ((r(6) * n as f32) as usize).min(n - 1) } else { 0 },
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn fx_map(ctx: &Ctx) -> CookResult {
|
||||
let pats: Vec<Image> = (0..3).filter_map(|i| ctx.input(i).map(Image::to_gray)).collect();
|
||||
let items = fx_instances(ctx, pats.len());
|
||||
Ok(vec![splat(ctx, &items, ctx.i("blending"), |i, x, y| sample_pattern(&pats, items.get(i).map_or(0, |it| it.pat), x, y))])
|
||||
}
|
||||
|
||||
fn shape_splatter(ctx: &Ctx) -> CookResult {
|
||||
let pats: Vec<Image> = ctx.input(0).map(Image::to_gray).into_iter().collect();
|
||||
let mask = ctx.input(1);
|
||||
let (k, s) = (ctx.i("shape"), ctx.seed);
|
||||
let (size, sr, rr, lr) = (ctx.f("size"), ctx.f("size_random"), ctx.f("rotation_random"), ctx.f("luminance_random"));
|
||||
let items: Vec<Inst> = (0..ctx.i("count").clamp(1, 20000) as u32)
|
||||
.filter_map(|i| {
|
||||
let r = |k: u32| rand1(i * 8 + k, s);
|
||||
let c = [r(0), r(1)];
|
||||
// Instances land where the mask is bright: kept with probability = mask value.
|
||||
if mask.is_some_and(|m| r(2) >= m.sample_gray(c[0], c[1], ctx.tile)) {
|
||||
return None;
|
||||
}
|
||||
let rad = size * (1.0 - sr * r(3));
|
||||
Some(Inst { c, r: [rad, rad], rot: (r(4) - 0.5) * rr, lum: 1.0 - lr * r(5), pat: 0 })
|
||||
})
|
||||
.collect();
|
||||
Ok(vec![splat(ctx, &items, ctx.i("blending"), |_, x, y| if pats.is_empty() { shape(k, x, y) } else { sample_pattern(&pats, 0, x, y) })])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use materialcraft_core::Value;
|
||||
|
||||
use super::*;
|
||||
use crate::catalog::{find, resolve_params};
|
||||
|
||||
fn with(params: &[(&str, Value)], f: impl FnOnce(&Ctx)) {
|
||||
let def = find("fx_map").unwrap();
|
||||
let mut p = resolve_params(def, &BTreeMap::new());
|
||||
for (k, v) in params {
|
||||
p.insert(k.to_string(), v.clone());
|
||||
}
|
||||
let no_res = |_: &str| None;
|
||||
let vars = BTreeMap::new();
|
||||
let inputs = [None, None, None];
|
||||
f(&Ctx { w: 64, h: 64, seed: 3, tile: true, inputs: &inputs, params: &p, resource: &no_res, vars: &vars });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fx_map_instance_counts() {
|
||||
with(&[("mode", Value::Enum(0)), ("x_amount", Value::Int(5)), ("y_amount", Value::Int(3))], |c| assert_eq!(fx_instances(c, 1).len(), 15));
|
||||
with(&[("mode", Value::Enum(1)), ("count", Value::Int(77))], |c| assert_eq!(fx_instances(c, 1).len(), 77));
|
||||
let quad = |chance: f32, depth: i32| {
|
||||
let mut n = 0;
|
||||
with(
|
||||
&[
|
||||
("mode", Value::Enum(2)),
|
||||
("x_amount", Value::Int(2)),
|
||||
("y_amount", Value::Int(1)),
|
||||
("subdivisions", Value::Int(depth)),
|
||||
("split_chance", Value::Float(chance)),
|
||||
],
|
||||
|c| n = fx_instances(c, 1).len(),
|
||||
);
|
||||
n
|
||||
};
|
||||
assert_eq!(quad(0.0, 3), 2);
|
||||
assert_eq!(quad(1.0, 3), 2 * 64);
|
||||
let some = quad(0.5, 4);
|
||||
assert!(some > 2 && some < 2 * 256, "{some}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fx_map_is_deterministic_per_seed() {
|
||||
let cook = |off: i32| {
|
||||
let mut img = None;
|
||||
with(&[("seed_offset", Value::Int(off))], |c| img = Some(fx_map(c).unwrap().remove(0)));
|
||||
img.unwrap()
|
||||
};
|
||||
assert_eq!(cook(0), cook(0));
|
||||
assert_ne!(cook(0), cook(1));
|
||||
assert!(cook(0).mean()[0] > 0.05);
|
||||
}
|
||||
}
|
||||
@@ -10,17 +10,23 @@
|
||||
pub mod atomic;
|
||||
pub mod catalog;
|
||||
pub mod filters;
|
||||
pub mod filters_extra;
|
||||
pub mod filters_more;
|
||||
pub mod flood_fill;
|
||||
pub mod function;
|
||||
pub mod fx_map;
|
||||
pub mod generators;
|
||||
pub mod material;
|
||||
pub mod material_more;
|
||||
pub mod noise;
|
||||
pub mod noise3d;
|
||||
pub mod noises_more;
|
||||
pub mod ops;
|
||||
pub mod patterns;
|
||||
pub mod patterns_more;
|
||||
pub mod svg;
|
||||
pub mod text;
|
||||
pub mod weathering;
|
||||
|
||||
pub use catalog::{CookResult, Ctx, NodeDef, ParamDef, PortDef, PortKind, catalog, categories, find, resolve_params};
|
||||
|
||||
@@ -99,6 +105,16 @@ mod tests {
|
||||
"chevron",
|
||||
"basketweave",
|
||||
"tread_plate",
|
||||
"fx_map",
|
||||
"shape_splatter",
|
||||
"perlin_noise_3d",
|
||||
"simplex_noise_3d",
|
||||
"worley_noise_3d",
|
||||
"cracks",
|
||||
"paint_strokes",
|
||||
"scratches_generator",
|
||||
"rust",
|
||||
"moss",
|
||||
] {
|
||||
let def = find(id).unwrap();
|
||||
let img = &cook(def, &[], 64).unwrap()[0];
|
||||
|
||||
@@ -0,0 +1,281 @@
|
||||
//! Texture generators › Noises: 3D noises that still tile. Perlin and Worley use a 3D lattice that
|
||||
//! is periodic in x and y (whole-number scales) and free in z, so scrubbing `z` animates the
|
||||
//! pattern. The simplex variant samples 4D simplex noise on a flat torus (u and v each mapped to a
|
||||
//! circle), which tiles at any scale; `z` slides the torus through the 4D field.
|
||||
|
||||
use std::f32::consts::TAU;
|
||||
|
||||
use crate::catalog::{B, CookResult, Ctx, NodeDef, node};
|
||||
use crate::generators::NOISES;
|
||||
use crate::noise::{hash, hash3};
|
||||
use crate::noises_more::fractal;
|
||||
|
||||
#[inline]
|
||||
fn wrap(i: i32, p: i32) -> i32 {
|
||||
if p <= 0 { i } else { i.rem_euclid(p) }
|
||||
}
|
||||
|
||||
/// A hash of a 3D lattice point, periodic in x and y.
|
||||
#[inline]
|
||||
fn hash_xyz(i: i32, j: i32, k: i32, px: i32, py: i32, seed: u32) -> u32 {
|
||||
hash(hash3(wrap(i, px), wrap(j, py), seed) ^ (k as u32).wrapping_mul(0x9e37_79b1))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn fade(t: f32) -> f32 {
|
||||
t * t * t * (t * (t * 6.0 - 15.0) + 10.0)
|
||||
}
|
||||
|
||||
/// 3D gradient (Perlin) noise in about -1..1, periods `px`, `py` cells in x and y.
|
||||
pub fn perlin3(x: f32, y: f32, z: f32, px: i32, py: i32, seed: u32) -> f32 {
|
||||
const G: [[f32; 3]; 12] = [
|
||||
[1.0, 1.0, 0.0],
|
||||
[-1.0, 1.0, 0.0],
|
||||
[1.0, -1.0, 0.0],
|
||||
[-1.0, -1.0, 0.0],
|
||||
[1.0, 0.0, 1.0],
|
||||
[-1.0, 0.0, 1.0],
|
||||
[1.0, 0.0, -1.0],
|
||||
[-1.0, 0.0, -1.0],
|
||||
[0.0, 1.0, 1.0],
|
||||
[0.0, -1.0, 1.0],
|
||||
[0.0, 1.0, -1.0],
|
||||
[0.0, -1.0, -1.0],
|
||||
];
|
||||
let (x0, y0, z0) = (x.floor(), y.floor(), z.floor());
|
||||
let (fx, fy, fz) = (x - x0, y - y0, z - z0);
|
||||
let (ix, iy, iz) = (x0 as i32, y0 as i32, z0 as i32);
|
||||
let g = |a: i32, b: i32, c: i32| {
|
||||
let gr = G[(hash_xyz(ix + a, iy + b, iz + c, px, py, seed) % 12) as usize];
|
||||
gr[0] * (fx - a as f32) + gr[1] * (fy - b as f32) + gr[2] * (fz - c as f32)
|
||||
};
|
||||
let (u, v, w) = (fade(fx), fade(fy), fade(fz));
|
||||
let lerp = |a: f32, b: f32, t: f32| a + (b - a) * t;
|
||||
let x00 = lerp(g(0, 0, 0), g(1, 0, 0), u);
|
||||
let x10 = lerp(g(0, 1, 0), g(1, 1, 0), u);
|
||||
let x01 = lerp(g(0, 0, 1), g(1, 0, 1), u);
|
||||
let x11 = lerp(g(0, 1, 1), g(1, 1, 1), u);
|
||||
lerp(lerp(x00, x10, v), lerp(x01, x11, v), w)
|
||||
}
|
||||
|
||||
/// Uniform 0..1 from a hash.
|
||||
#[inline]
|
||||
fn unit(h: u32) -> f32 {
|
||||
(h >> 8) as f32 / (1u32 << 24) as f32
|
||||
}
|
||||
|
||||
/// 3D Worley noise: nearest and second-nearest feature distances (cells), periodic in x and y.
|
||||
pub fn worley3(x: f32, y: f32, z: f32, px: i32, py: i32, jitter: f32, seed: u32) -> (f32, f32) {
|
||||
let (ix, iy, iz) = (x.floor() as i32, y.floor() as i32, z.floor() as i32);
|
||||
let (mut f1, mut f2) = (f32::MAX, f32::MAX);
|
||||
for k in -1..=1 {
|
||||
for j in -1..=1 {
|
||||
for i in -1..=1 {
|
||||
let (cx, cy, cz) = (ix + i, iy + j, iz + k);
|
||||
let h = hash_xyz(cx, cy, cz, px, py, seed);
|
||||
let o = |s: u32| 0.5 + (unit(hash(h ^ s)) - 0.5) * jitter;
|
||||
let (dx, dy, dz) = (cx as f32 + o(1) - x, cy as f32 + o(2) - y, cz as f32 + o(3) - z);
|
||||
let d = (dx * dx + dy * dy + dz * dz).sqrt();
|
||||
if d < f1 {
|
||||
f2 = f1;
|
||||
f1 = d;
|
||||
} else if d < f2 {
|
||||
f2 = d;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
(f1, f2)
|
||||
}
|
||||
|
||||
/// 4D simplex noise in about -1..1 (after Gustavson's public description of the algorithm).
|
||||
pub fn simplex4(p: [f32; 4], seed: u32) -> f32 {
|
||||
const F4: f32 = 0.309_017; // (√5 − 1) / 4
|
||||
const G4: f32 = 0.138_196_6; // (5 − √5) / 20
|
||||
let s = (p[0] + p[1] + p[2] + p[3]) * F4;
|
||||
let i: [f32; 4] = std::array::from_fn(|k| (p[k] + s).floor());
|
||||
let t = (i[0] + i[1] + i[2] + i[3]) * G4;
|
||||
let x0: [f32; 4] = std::array::from_fn(|k| p[k] - (i[k] - t));
|
||||
// Rank the coordinates to find the simplex the point is in.
|
||||
let mut rank = [0i32; 4];
|
||||
for a in 0..4 {
|
||||
for b in a + 1..4 {
|
||||
if x0[a] > x0[b] {
|
||||
rank[a] += 1;
|
||||
} else {
|
||||
rank[b] += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let ii: [i32; 4] = std::array::from_fn(|k| i[k] as i32);
|
||||
let mut n = 0.0;
|
||||
for c in 0..5 {
|
||||
let off: [i32; 4] = std::array::from_fn(|k| (rank[k] >= 4 - c) as i32);
|
||||
let x: [f32; 4] = std::array::from_fn(|k| x0[k] - off[k] as f32 + c as f32 * G4);
|
||||
let t = 0.6 - x.iter().map(|v| v * v).sum::<f32>();
|
||||
if t <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let h = hash(hash3(ii[0] + off[0], ii[1] + off[1], seed) ^ hash3(ii[2] + off[2], ii[3] + off[3], seed ^ 0x68e3_1da4));
|
||||
// 32 gradients: one coordinate zero, the other three ±1.
|
||||
let zero = (h >> 3) as usize & 3;
|
||||
let mut dot = 0.0;
|
||||
let mut bit = 0;
|
||||
for k in 0..4 {
|
||||
if k != zero {
|
||||
dot += if h >> bit & 1 == 0 { x[k] } else { -x[k] };
|
||||
bit += 1;
|
||||
}
|
||||
}
|
||||
n += t * t * t * t * dot;
|
||||
}
|
||||
27.0 * n
|
||||
}
|
||||
|
||||
/// Fractal 4D simplex on a torus at `(u, v)`: tiles in u and v for any scale.
|
||||
fn simplex_torus(u: f32, v: f32, z: f32, scale: f32, octaves: i32, gain: f32, seed: u32) -> f32 {
|
||||
let (su, cu) = (u * TAU).sin_cos();
|
||||
let (sv, cv) = (v * TAU).sin_cos();
|
||||
// Circumference `scale` cells per axis.
|
||||
let r = scale / TAU;
|
||||
fractal(octaves, gain, |m, o| {
|
||||
let (r, z) = (r * m, z * m);
|
||||
let p = [r * cu + z * 0.7, r * su + z * 0.3, r * cv - z * 0.5, r * sv + z * 0.4];
|
||||
(simplex4(p, seed.wrapping_add(o * 977)) * 0.5 + 0.5).clamp(0.0, 1.0)
|
||||
})
|
||||
}
|
||||
|
||||
/// Shared noise parameters.
|
||||
fn noise_params(b: B, scale: f32, octaves: i32) -> B {
|
||||
b.generator()
|
||||
.float("scale", "Scale", scale, 1.0, 64.0)
|
||||
.int("octaves", "Octaves", octaves, 1, 10)
|
||||
.float("roughness", "Roughness", 0.5, 0.0, 1.0)
|
||||
.float("z", "Z (slice)", 0.0, 0.0, 16.0)
|
||||
.float("contrast", "Contrast", 0.5, 0.0, 1.0)
|
||||
.gray_out()
|
||||
}
|
||||
|
||||
pub(crate) fn defs() -> Vec<NodeDef> {
|
||||
let n = |id, label| node(id, label, NOISES);
|
||||
vec![
|
||||
noise_params(n("perlin_noise_3d", "Perlin Noise 3D").desc("Fractal 3D gradient noise; Z scrubs through the volume. Tiles."), 4.0, 5)
|
||||
.cook(perlin_noise_3d),
|
||||
noise_params(
|
||||
n("simplex_noise_3d", "Simplex Noise 3D").desc("Fractal simplex noise sampled on a 4D torus; Z moves through it. Tiles at any scale."),
|
||||
4.0,
|
||||
5,
|
||||
)
|
||||
.cook(simplex_noise_3d),
|
||||
noise_params(
|
||||
n("worley_noise_3d", "Worley Noise 3D")
|
||||
.desc("Cellular noise from 3D feature points; Z scrubs through the cells. Tiles.")
|
||||
.choice("distance", "Distance", &["F1", "F2", "F2 - F1"], 0)
|
||||
.float("jitter", "Jitter", 1.0, 0.0, 1.0),
|
||||
6.0,
|
||||
1,
|
||||
)
|
||||
.cook(worley_noise_3d),
|
||||
]
|
||||
}
|
||||
|
||||
/// Common noise settings: whole-number scale, octaves, gain, z, contrast gain, seed.
|
||||
fn settings(ctx: &Ctx) -> (f32, i32, f32, f32, f32, u32) {
|
||||
(ctx.f("scale").max(1.0).round(), ctx.i("octaves"), ctx.f("roughness"), ctx.f("z"), 1.0 + ctx.f("contrast") * 3.0, ctx.seed)
|
||||
}
|
||||
|
||||
/// Expand around mid gray by `k`.
|
||||
#[inline]
|
||||
fn spread(v: f32, k: f32) -> f32 {
|
||||
((v - 0.5) * k + 0.5).clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
fn perlin_noise_3d(ctx: &Ctx) -> CookResult {
|
||||
let (s, oct, gain, z, k, seed) = settings(ctx);
|
||||
Ok(vec![ctx.gen_gray(|u, v| {
|
||||
let n = fractal(oct, gain, |m, o| {
|
||||
let p = s * m;
|
||||
perlin3(u * p, v * p, z * m + o as f32 * 17.31, p as i32, p as i32, seed.wrapping_add(o * 977)) * 0.5 + 0.5
|
||||
});
|
||||
spread(n, k)
|
||||
})])
|
||||
}
|
||||
|
||||
fn simplex_noise_3d(ctx: &Ctx) -> CookResult {
|
||||
let (_, oct, gain, z, k, seed) = settings(ctx);
|
||||
let s = ctx.f("scale").max(0.1);
|
||||
Ok(vec![ctx.gen_gray(|u, v| spread(simplex_torus(u, v, z, s, oct, gain, seed), k))])
|
||||
}
|
||||
|
||||
fn worley_noise_3d(ctx: &Ctx) -> CookResult {
|
||||
let (s, oct, gain, z, k, seed) = settings(ctx);
|
||||
let (mode, jit) = (ctx.i("distance"), ctx.f("jitter").clamp(0.0, 1.0));
|
||||
Ok(vec![ctx.gen_gray(|u, v| {
|
||||
let n = fractal(oct, gain, |m, o| {
|
||||
let p = s * m;
|
||||
let (f1, f2) = worley3(u * p, v * p, z * m, p as i32, p as i32, jit, seed.wrapping_add(o * 977));
|
||||
match mode {
|
||||
1 => f2 * 0.75,
|
||||
2 => (f2 - f1) * 1.5,
|
||||
_ => f1,
|
||||
}
|
||||
.clamp(0.0, 1.0)
|
||||
});
|
||||
// Cell distances already span 0..1: contrast 0.5 leaves them as they are.
|
||||
spread(n, k * 0.4)
|
||||
})])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use super::*;
|
||||
use crate::catalog::{find, resolve_params};
|
||||
|
||||
#[test]
|
||||
fn primitives_tile_and_stay_in_range() {
|
||||
for k in 0..20 {
|
||||
let (y, z) = (k as f32 * 0.37, k as f32 * 0.11);
|
||||
assert!((perlin3(0.0, y, z, 4, 4, 7) - perlin3(4.0, y, z, 4, 4, 7)).abs() < 1e-5);
|
||||
assert!((perlin3(y, 0.0, z, 4, 4, 7) - perlin3(y, 4.0, z, 4, 4, 7)).abs() < 1e-5);
|
||||
assert!((worley3(0.0, y, z, 5, 5, 1.0, 3).0 - worley3(5.0, y, z, 5, 5, 1.0, 3).0).abs() < 1e-4);
|
||||
}
|
||||
let mut lo = f32::MAX;
|
||||
let mut hi = f32::MIN;
|
||||
for k in 0..20000 {
|
||||
let p = [k as f32 * 0.131, k as f32 * 0.071 + 0.3, (k as f32 * 0.017).sin() * 9.0, k as f32 * 0.029];
|
||||
let v = simplex4(p, 1);
|
||||
lo = lo.min(v);
|
||||
hi = hi.max(v);
|
||||
}
|
||||
assert!(lo > -1.2 && hi < 1.2 && hi - lo > 1.0, "{lo} {hi}");
|
||||
}
|
||||
|
||||
/// Each 3D noise matches across u = 0/1 and v = 0/1, and z changes it.
|
||||
#[test]
|
||||
fn noises_3d_tile_both_ways() {
|
||||
let no_res = |_: &str| None;
|
||||
let vars = BTreeMap::new();
|
||||
for id in ["perlin_noise_3d", "simplex_noise_3d", "worley_noise_3d"] {
|
||||
let def = find(id).unwrap();
|
||||
let cook = |z: f32| {
|
||||
let mut p = resolve_params(def, &BTreeMap::new());
|
||||
p.insert("z".into(), materialcraft_core::Value::Float(z));
|
||||
let ctx = Ctx { w: 64, h: 64, seed: 5, tile: true, inputs: &[], params: &p, resource: &no_res, vars: &vars };
|
||||
(def.cook)(&ctx).unwrap().remove(0)
|
||||
};
|
||||
let img = cook(0.5);
|
||||
let (mut seam_x, mut seam_y, mut inner) = (0.0f32, 0.0f32, 0.0f32);
|
||||
for i in 0..64 {
|
||||
seam_x += (img.get(63, i, false)[0] - img.get(0, i, false)[0]).abs();
|
||||
seam_y += (img.get(i, 63, false)[0] - img.get(i, 0, false)[0]).abs();
|
||||
inner += (img.get(31, i, false)[0] - img.get(32, i, false)[0]).abs() + (img.get(i, 31, false)[0] - img.get(i, 32, false)[0]).abs();
|
||||
}
|
||||
assert!(seam_x <= inner * 1.5 + 0.2 && seam_y <= inner * 1.5 + 0.2, "{id}: seams {seam_x} {seam_y} vs inner {inner}");
|
||||
assert_ne!(img, cook(1.7), "{id}: z changes the slice");
|
||||
let (lo, hi) = img.range();
|
||||
assert!(hi - lo > 0.3, "{id}: contrast {lo}..{hi}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -38,7 +38,7 @@ pub(crate) fn perlin_xy(x: f32, y: f32, px: i32, py: i32, seed: u32) -> f32 {
|
||||
|
||||
/// Fractal sum of `f(level multiplier, octave)` (each 0..1): `octaves` layers, each twice as fine
|
||||
/// and `gain` times weaker. Normalized to 0..1.
|
||||
fn fractal(octaves: i32, gain: f32, f: impl Fn(f32, u32) -> f32) -> f32 {
|
||||
pub(crate) fn fractal(octaves: i32, gain: f32, f: impl Fn(f32, u32) -> f32) -> f32 {
|
||||
let (mut sum, mut amp, mut norm, mut m) = (0.0, 1.0, 0.0, 1.0);
|
||||
for o in 0..octaves.clamp(1, 10) as u32 {
|
||||
sum += f(m, o) * amp;
|
||||
|
||||
@@ -0,0 +1,487 @@
|
||||
//! Atomic › SVG: rasterizes SVG path data (the `d` attribute: M L H V C S Q T Z, absolute and
|
||||
//! relative) with an even-odd or non-zero fill and an optional stroke. Fill coverage is exact
|
||||
//! horizontally over four sub-scanlines per pixel. Also the shared capsule (thick line)
|
||||
//! rasterizer used by the stroke, the Text node and the scratches.
|
||||
|
||||
use materialcraft_image::{Image, Kind};
|
||||
use rayon::prelude::*;
|
||||
|
||||
use crate::atomic::ATOMIC;
|
||||
use crate::catalog::{CookResult, Ctx, NodeDef, node};
|
||||
|
||||
/// A leaf with a midrib slit, in 0..100 units.
|
||||
const DEFAULT_PATH: &str = "M50 4 C80 20 94 55 52 96 L50 90 L48 96 C6 55 20 20 50 4 Z M49 22 Q46 55 50 84 Q54 55 51 22 Z";
|
||||
|
||||
/// Most points a path may flatten to (an allocation cap for hostile input).
|
||||
const MAX_POINTS: usize = 400_000;
|
||||
|
||||
pub(crate) fn defs() -> Vec<NodeDef> {
|
||||
vec![
|
||||
node("svg", "SVG", ATOMIC)
|
||||
.desc("Draws SVG path data (M L H V C S Q T Z, absolute and relative; y points down) filled and optionally stroked, anti-aliased.")
|
||||
.atomic()
|
||||
.generator()
|
||||
.text("path", "Path data", DEFAULT_PATH)
|
||||
.choice("units", "Units", &["0..1", "0..100"], 1)
|
||||
.color("fill", "Fill color", [1.0, 1.0, 1.0, 1.0])
|
||||
.choice("fill_rule", "Fill rule", &["Even-odd", "Non-zero"], 1)
|
||||
.float("stroke_width", "Stroke width", 0.0, 0.0, 64.0)
|
||||
.color("stroke", "Stroke color", [0.5, 0.5, 0.5, 1.0])
|
||||
.color_out()
|
||||
.cook(svg),
|
||||
]
|
||||
}
|
||||
|
||||
/// A flattened subpath in path units; `closed` after Z.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Poly {
|
||||
pub pts: Vec<[f32; 2]>,
|
||||
pub closed: bool,
|
||||
}
|
||||
|
||||
struct Lexer<'a> {
|
||||
s: &'a [u8],
|
||||
i: usize,
|
||||
}
|
||||
|
||||
impl Lexer<'_> {
|
||||
fn skip(&mut self) {
|
||||
while self.s.get(self.i).is_some_and(|c| c.is_ascii_whitespace() || *c == b',') {
|
||||
self.i += 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn peek(&mut self) -> Option<u8> {
|
||||
self.skip();
|
||||
self.s.get(self.i).copied()
|
||||
}
|
||||
|
||||
fn at_number(&mut self) -> bool {
|
||||
self.peek().is_some_and(|c| c.is_ascii_digit() || matches!(c, b'-' | b'+' | b'.'))
|
||||
}
|
||||
|
||||
fn number(&mut self) -> Result<f32, String> {
|
||||
self.skip();
|
||||
let (start, s) = (self.i, self.s);
|
||||
let digit = |j: usize| s.get(j).is_some_and(u8::is_ascii_digit);
|
||||
let mut j = start + matches!(s.get(start), Some(b'+' | b'-')) as usize;
|
||||
let mut digits = 0;
|
||||
while digit(j) {
|
||||
j += 1;
|
||||
digits += 1;
|
||||
}
|
||||
if s.get(j) == Some(&b'.') {
|
||||
j += 1;
|
||||
while digit(j) {
|
||||
j += 1;
|
||||
digits += 1;
|
||||
}
|
||||
}
|
||||
if digits == 0 {
|
||||
return Err(format!("expected a number at byte {start}"));
|
||||
}
|
||||
if matches!(s.get(j), Some(b'e' | b'E')) {
|
||||
let mut k = j + 1 + matches!(s.get(j + 1), Some(b'+' | b'-')) as usize;
|
||||
let k0 = k;
|
||||
while digit(k) {
|
||||
k += 1;
|
||||
}
|
||||
if k > k0 {
|
||||
j = k;
|
||||
}
|
||||
}
|
||||
let txt = s.get(start..j).and_then(|b| std::str::from_utf8(b).ok()).unwrap_or("");
|
||||
let v: f32 = txt.parse().map_err(|_| format!("bad number '{txt}' at byte {start}"))?;
|
||||
if !v.is_finite() {
|
||||
return Err(format!("number out of range at byte {start}"));
|
||||
}
|
||||
self.i = j;
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
fn pair(&mut self) -> Result<[f32; 2], String> {
|
||||
Ok([self.number()?, self.number()?])
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds flattened subpaths while parsing.
|
||||
struct Pen {
|
||||
polys: Vec<Poly>,
|
||||
cur: [f32; 2],
|
||||
start: [f32; 2],
|
||||
/// The previous segment's last control point and whether it was cubic (for S and T).
|
||||
ctrl: Option<([f32; 2], bool)>,
|
||||
steps_per_unit: f32,
|
||||
points: usize,
|
||||
}
|
||||
|
||||
impl Pen {
|
||||
fn push(&mut self, p: [f32; 2]) -> Result<(), String> {
|
||||
self.points += 1;
|
||||
if self.points > MAX_POINTS {
|
||||
return Err(format!("path too complex (over {MAX_POINTS} points)"));
|
||||
}
|
||||
match self.polys.last_mut() {
|
||||
Some(poly) if !poly.closed => poly.pts.push(p),
|
||||
// Drawing after Z starts a new subpath at the closed one's start.
|
||||
_ => self.polys.push(Poly { pts: vec![self.start, p], closed: false }),
|
||||
}
|
||||
self.cur = p;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn move_to(&mut self, p: [f32; 2]) {
|
||||
self.polys.push(Poly { pts: vec![p], closed: false });
|
||||
(self.cur, self.start) = (p, p);
|
||||
}
|
||||
|
||||
/// A Bézier through `ctrl` (2 or 3 points after the current one), flattened in steps of
|
||||
/// about 1 / `steps_per_unit` along its control polygon.
|
||||
fn curve(&mut self, ctrl: &[[f32; 2]]) -> Result<(), String> {
|
||||
let mut pts = vec![self.cur];
|
||||
pts.extend_from_slice(ctrl);
|
||||
let len: f32 = pts.windows(2).map(|w| ((w[1][0] - w[0][0]).powi(2) + (w[1][1] - w[0][1]).powi(2)).sqrt()).sum();
|
||||
let n = (len * self.steps_per_unit).ceil().clamp(2.0, 256.0) as usize;
|
||||
for k in 1..=n {
|
||||
let t = k as f32 / n as f32;
|
||||
// De Casteljau.
|
||||
let mut q = pts.clone();
|
||||
while q.len() > 1 {
|
||||
q = q.windows(2).map(|w| [w[0][0] + (w[1][0] - w[0][0]) * t, w[0][1] + (w[1][1] - w[0][1]) * t]).collect();
|
||||
}
|
||||
self.push(q.first().copied().unwrap_or(self.cur))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn reflect(&self, cubic: bool) -> [f32; 2] {
|
||||
match self.ctrl {
|
||||
Some((c, was_cubic)) if was_cubic == cubic => [2.0 * self.cur[0] - c[0], 2.0 * self.cur[1] - c[1]],
|
||||
_ => self.cur,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses SVG path data into flattened subpaths. Curves get about `steps_per_unit` segments per
|
||||
/// unit of control-polygon length (2..256 per curve). Bad input is an error, never a panic.
|
||||
pub fn parse_path(d: &str, steps_per_unit: f32) -> Result<Vec<Poly>, String> {
|
||||
let mut lx = Lexer { s: d.as_bytes(), i: 0 };
|
||||
let steps_per_unit = if steps_per_unit.is_finite() { steps_per_unit.max(0.0) } else { 0.0 };
|
||||
let mut pen = Pen { polys: Vec::new(), cur: [0.0; 2], start: [0.0; 2], ctrl: None, steps_per_unit, points: 0 };
|
||||
let mut prev: Option<u8> = None;
|
||||
while let Some(c) = lx.peek() {
|
||||
let op = if c.is_ascii_alphabetic() {
|
||||
lx.i += 1;
|
||||
c
|
||||
} else if lx.at_number() {
|
||||
// Repeated arguments repeat the command; extra pairs after a move are lines.
|
||||
match prev {
|
||||
Some(b'M') => b'L',
|
||||
Some(b'm') => b'l',
|
||||
Some(p) if !matches!(p, b'Z' | b'z') => p,
|
||||
_ => return Err(format!("number without a command at byte {}", lx.i)),
|
||||
}
|
||||
} else {
|
||||
return Err(format!("unexpected '{}' at byte {}", c as char, lx.i));
|
||||
};
|
||||
if prev.is_none() && !matches!(op, b'M' | b'm') {
|
||||
return Err("path data must start with a move (M)".into());
|
||||
}
|
||||
let rel = op.is_ascii_lowercase();
|
||||
let o = if rel { pen.cur } else { [0.0; 2] };
|
||||
let at = |p: [f32; 2]| [p[0] + o[0], p[1] + o[1]];
|
||||
let mut ctrl = None;
|
||||
match op.to_ascii_uppercase() {
|
||||
b'M' => pen.move_to(at(lx.pair()?)),
|
||||
b'L' => pen.push(at(lx.pair()?))?,
|
||||
b'H' => pen.push([lx.number()? + o[0], pen.cur[1]])?,
|
||||
b'V' => pen.push([pen.cur[0], lx.number()? + o[1]])?,
|
||||
b'C' => {
|
||||
let (c1, c2, p) = (at(lx.pair()?), at(lx.pair()?), at(lx.pair()?));
|
||||
pen.curve(&[c1, c2, p])?;
|
||||
ctrl = Some((c2, true));
|
||||
}
|
||||
b'S' => {
|
||||
let c1 = pen.reflect(true);
|
||||
let (c2, p) = (at(lx.pair()?), at(lx.pair()?));
|
||||
pen.curve(&[c1, c2, p])?;
|
||||
ctrl = Some((c2, true));
|
||||
}
|
||||
b'Q' => {
|
||||
let (c1, p) = (at(lx.pair()?), at(lx.pair()?));
|
||||
pen.curve(&[c1, p])?;
|
||||
ctrl = Some((c1, false));
|
||||
}
|
||||
b'T' => {
|
||||
let c1 = pen.reflect(false);
|
||||
pen.curve(&[c1, at(lx.pair()?)])?;
|
||||
ctrl = Some((c1, false));
|
||||
}
|
||||
b'Z' => {
|
||||
if let Some(p) = pen.polys.last_mut() {
|
||||
p.closed = true;
|
||||
}
|
||||
pen.cur = pen.start;
|
||||
}
|
||||
b'A' => return Err("arc commands (A) are not supported; use curves".into()),
|
||||
_ => return Err(format!("unknown command '{}'", op as char)),
|
||||
}
|
||||
pen.ctrl = ctrl;
|
||||
prev = Some(op);
|
||||
}
|
||||
Ok(pen.polys)
|
||||
}
|
||||
|
||||
/// Fill coverage (0..1 per pixel, row-major) of polygons in pixel coordinates (each implicitly
|
||||
/// closed): exact horizontal span coverage on four sub-scanlines per pixel row.
|
||||
pub(crate) fn fill(w: u32, h: u32, polys: &[Vec<[f32; 2]>], even_odd: bool) -> Vec<f32> {
|
||||
// Edges as (x0, y0, x1, y1, winding) with y0 < y1.
|
||||
let mut edges: Vec<(f32, f32, f32, f32, i32)> = Vec::new();
|
||||
for p in polys {
|
||||
for (k, a) in p.iter().enumerate() {
|
||||
let b = p.get(k + 1).or(p.first()).copied().unwrap_or(*a);
|
||||
if a[1] < b[1] {
|
||||
edges.push((a[0], a[1], b[0], b[1], 1));
|
||||
} else if b[1] < a[1] {
|
||||
edges.push((b[0], b[1], a[0], a[1], -1));
|
||||
}
|
||||
}
|
||||
}
|
||||
let wu = w as usize;
|
||||
let rows: Vec<Vec<f32>> = (0..h)
|
||||
.into_par_iter()
|
||||
.map(|y| {
|
||||
let mut row = vec![0.0f32; wu];
|
||||
let mut xs: Vec<(f32, i32)> = Vec::new();
|
||||
for s in 0..4 {
|
||||
let sy = y as f32 + (s as f32 + 0.5) * 0.25;
|
||||
xs.clear();
|
||||
xs.extend(edges.iter().filter(|e| e.1 <= sy && sy < e.3).map(|e| (e.0 + (sy - e.1) * (e.2 - e.0) / (e.3 - e.1), e.4)));
|
||||
xs.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let mut wind = 0;
|
||||
for k in 0..xs.len() {
|
||||
wind += xs[k].1;
|
||||
let inside = if even_odd { wind & 1 != 0 } else { wind != 0 };
|
||||
if let (true, Some(next)) = (inside, xs.get(k + 1)) {
|
||||
add_span(&mut row, xs[k].0, next.0, 0.25);
|
||||
}
|
||||
}
|
||||
}
|
||||
row
|
||||
})
|
||||
.collect();
|
||||
rows.concat()
|
||||
}
|
||||
|
||||
/// Adds `wt` × the overlap of `[a, b)` with each pixel of `row`.
|
||||
fn add_span(row: &mut [f32], a: f32, b: f32, wt: f32) {
|
||||
let n = row.len() as f32;
|
||||
let (a, b) = (a.clamp(0.0, n), b.clamp(0.0, n));
|
||||
if b <= a {
|
||||
return;
|
||||
}
|
||||
for px in a.floor() as usize..(b.ceil() as usize).min(row.len()) {
|
||||
let ov = b.min(px as f32 + 1.0) - a.max(px as f32);
|
||||
if let Some(v) = row.get_mut(px) {
|
||||
*v += ov.max(0.0) * wt;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A line segment with a weight (its peak coverage).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct Seg {
|
||||
pub a: [f32; 2],
|
||||
pub b: [f32; 2],
|
||||
pub wt: f32,
|
||||
}
|
||||
|
||||
/// Thick line segments ("capsules") of radius `r` in pixel space, binned on a grid for fast
|
||||
/// lookups. Coverage ramps over one pixel at the border (anti-aliased); with `tile` it wraps.
|
||||
pub(crate) struct Capsules {
|
||||
segs: Vec<Seg>,
|
||||
r: f32,
|
||||
g: usize,
|
||||
cell: [f32; 2],
|
||||
bins: Vec<Vec<u32>>,
|
||||
size: [f32; 2],
|
||||
tile: bool,
|
||||
}
|
||||
|
||||
impl Capsules {
|
||||
pub fn new(segs: Vec<Seg>, r: f32, w: u32, h: u32, tile: bool) -> Capsules {
|
||||
let r = if r.is_finite() { r.max(0.0) } else { 0.0 };
|
||||
let reach = r + 1.0;
|
||||
let g = ((w.max(h) as f32 / (reach * 4.0).max(8.0)) as usize).clamp(1, 128);
|
||||
let cell = [w as f32 / g as f32, h as f32 / g as f32];
|
||||
let mut bins: Vec<Vec<u32>> = vec![Vec::new(); g * g];
|
||||
for (i, s) in segs.iter().enumerate() {
|
||||
if !s.a.iter().chain(&s.b).all(|v| v.is_finite()) {
|
||||
continue;
|
||||
}
|
||||
let span = |a: f32, b: f32, c: f32| {
|
||||
let lo = ((a.min(b) - reach) / c).floor() as i64;
|
||||
(lo, (((a.max(b) + reach) / c).floor() as i64).min(lo + g as i64 - 1))
|
||||
};
|
||||
let ((x0, x1), (y0, y1)) = (span(s.a[0], s.b[0], cell[0]), span(s.a[1], s.b[1], cell[1]));
|
||||
for gy in y0..=y1 {
|
||||
for gx in x0..=x1 {
|
||||
if !tile && (gx < 0 || gy < 0 || gx >= g as i64 || gy >= g as i64) {
|
||||
continue;
|
||||
}
|
||||
if let Some(b) = bins.get_mut(gy.rem_euclid(g as i64) as usize * g + gx.rem_euclid(g as i64) as usize) {
|
||||
b.push(i as u32);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Capsules { segs, r, g, cell, bins, size: [w as f32, h as f32], tile }
|
||||
}
|
||||
|
||||
/// Coverage (0..1, the strongest segment's weight) at pixel coordinates `(x, y)`.
|
||||
pub fn coverage(&self, x: f32, y: f32) -> f32 {
|
||||
let (gx, gy) = (((x / self.cell[0]) as usize).min(self.g - 1), ((y / self.cell[1]) as usize).min(self.g - 1));
|
||||
let mut best = 0.0f32;
|
||||
for &i in self.bins.get(gy * self.g + gx).into_iter().flatten() {
|
||||
let Some(s) = self.segs.get(i as usize) else { continue };
|
||||
let (mut px, mut py) = (x - s.a[0], y - s.a[1]);
|
||||
if self.tile {
|
||||
px -= (px / self.size[0]).round() * self.size[0];
|
||||
py -= (py / self.size[1]).round() * self.size[1];
|
||||
}
|
||||
let (dx, dy) = (s.b[0] - s.a[0], s.b[1] - s.a[1]);
|
||||
let t = ((px * dx + py * dy) / (dx * dx + dy * dy).max(1e-12)).clamp(0.0, 1.0);
|
||||
let d = ((px - dx * t).powi(2) + (py - dy * t).powi(2)).sqrt();
|
||||
best = best.max((self.r - d + 0.5).clamp(0.0, 1.0) * s.wt);
|
||||
}
|
||||
best
|
||||
}
|
||||
}
|
||||
|
||||
/// A color image from fill and stroke coverage over transparent black (premultiplied).
|
||||
pub(crate) fn composite(
|
||||
w: u32,
|
||||
h: u32,
|
||||
fill: [f32; 4],
|
||||
cover: impl Fn(u32, u32) -> f32 + Sync,
|
||||
stroke: [f32; 4],
|
||||
stroke_cover: impl Fn(u32, u32) -> f32 + Sync,
|
||||
) -> Image {
|
||||
Image::generate(w, h, Kind::Color, |x, y| {
|
||||
let f = cover(x, y).clamp(0.0, 1.0) * fill[3];
|
||||
let s = stroke_cover(x, y).clamp(0.0, 1.0) * stroke[3];
|
||||
let k = f * (1.0 - s);
|
||||
[fill[0] * k + stroke[0] * s, fill[1] * k + stroke[1] * s, fill[2] * k + stroke[2] * s, k + s]
|
||||
})
|
||||
}
|
||||
|
||||
fn svg(ctx: &Ctx) -> CookResult {
|
||||
let unit = if ctx.i("units") == 1 { 100.0 } else { 1.0 };
|
||||
let (sx, sy) = (ctx.w as f32 / unit, ctx.h as f32 / unit);
|
||||
// About one curve segment per 3 pixels.
|
||||
let polys = parse_path(ctx.text("path"), sx.max(sy) / 3.0)?;
|
||||
let rings: Vec<Vec<[f32; 2]>> = polys.iter().map(|p| p.pts.iter().map(|q| [q[0] * sx, q[1] * sy]).collect()).collect();
|
||||
let cov = fill(ctx.w, ctx.h, &rings, ctx.i("fill_rule") == 0);
|
||||
let sw = ctx.f("stroke_width").max(0.0) * ctx.w as f32 / 256.0;
|
||||
let caps = (sw > 0.0).then(|| {
|
||||
let mut segs = Vec::new();
|
||||
for (p, ring) in polys.iter().zip(&rings) {
|
||||
segs.extend(ring.windows(2).map(|w| Seg { a: w[0], b: w[1], wt: 1.0 }));
|
||||
if let (true, Some(a), Some(b)) = (p.closed, ring.last(), ring.first()) {
|
||||
segs.push(Seg { a: *a, b: *b, wt: 1.0 });
|
||||
}
|
||||
if ring.len() == 1 {
|
||||
segs.extend(ring.first().map(|a| Seg { a: *a, b: *a, wt: 1.0 }));
|
||||
}
|
||||
}
|
||||
Capsules::new(segs, sw * 0.5, ctx.w, ctx.h, false)
|
||||
});
|
||||
let w = ctx.w as usize;
|
||||
Ok(vec![composite(
|
||||
ctx.w,
|
||||
ctx.h,
|
||||
ctx.v4("fill"),
|
||||
|x, y| cov.get(y as usize * w + x as usize).copied().unwrap_or(0.0),
|
||||
ctx.v4("stroke"),
|
||||
|x, y| caps.as_ref().map_or(0.0, |c| c.coverage(x as f32 + 0.5, y as f32 + 0.5)),
|
||||
)])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn pts(d: &str) -> Vec<Vec<[f32; 2]>> {
|
||||
parse_path(d, 1.0).unwrap().into_iter().map(|p| p.pts).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_lines_absolute_and_relative() {
|
||||
assert_eq!(pts("M0 0 L10 0 L10 10 Z"), vec![vec![[0.0, 0.0], [10.0, 0.0], [10.0, 10.0]]]);
|
||||
assert_eq!(pts("m1,1 l2,0 0,2 h-2 v-1"), vec![vec![[1.0, 1.0], [3.0, 1.0], [3.0, 3.0], [1.0, 3.0], [1.0, 2.0]]]);
|
||||
// Extra pairs after M are lines; compact number syntax.
|
||||
assert_eq!(pts("M0 0 1 1 2-2"), vec![vec![[0.0, 0.0], [1.0, 1.0], [2.0, -2.0]]]);
|
||||
assert_eq!(pts("M.5.5L1e1-1E0"), vec![vec![[0.5, 0.5], [10.0, -1.0]]]);
|
||||
assert_eq!(pts("M0 0H5V5H0z M8 8 L9 9").len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_curves_to_their_endpoints() {
|
||||
for d in
|
||||
["M0 0 C0 10 10 10 10 0", "M0 0 c0 10 10 10 10 0", "M0 0 Q5 10 10 0", "M0 0 q5 10 10 0", "M0 0 Q5 5 5 0 T10 0", "M0 0 C0 5 5 5 5 0 S10 -5 10 0"]
|
||||
{
|
||||
let p = pts(d);
|
||||
let last = *p[0].last().unwrap();
|
||||
assert!((last[0] - 10.0).abs() < 1e-4 && last[1].abs() < 1e-4, "{d}: {last:?}");
|
||||
assert!(p[0].len() > 3, "{d} is flattened");
|
||||
}
|
||||
// The cubic's midpoint bulges to 7.5.
|
||||
let p = parse_path("M0 0 C0 10 10 10 10 0", 0.0).unwrap();
|
||||
assert_eq!(p[0].pts.len(), 3);
|
||||
assert!((p[0].pts[1][1] - 7.5).abs() < 1e-4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_paths_are_errors() {
|
||||
for d in ["L0 0", "M0", "M0 0 L1", "M0 0 X1 1", "M0 0 L1 1e99", "M0 0 A1 1 0 0 1 2 2", "5 5", "M0 0 Z 3 4", "M 0 0 L - 1"] {
|
||||
assert!(parse_path(d, 1.0).is_err(), "{d}");
|
||||
}
|
||||
assert!(parse_path("", 1.0).unwrap().is_empty());
|
||||
assert!(parse_path("M0 0 C1 1 2 2 3 3", f32::NAN).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_rules_and_coverage() {
|
||||
let sq = |a: f32, b: f32, ccw: bool| {
|
||||
let mut v = vec![[a, a], [b, a], [b, b], [a, b]];
|
||||
if ccw {
|
||||
v.reverse();
|
||||
}
|
||||
v
|
||||
};
|
||||
// Square of 4..12 on a 16×16 grid: area 64; a half-pixel edge gives half coverage.
|
||||
let c = fill(16, 16, &[sq(4.0, 12.0, false)], false);
|
||||
assert!((c.iter().sum::<f32>() - 64.0).abs() < 1e-3);
|
||||
let c = fill(16, 16, &[sq(4.5, 12.0, false)], false);
|
||||
assert!((c[8 * 16 + 4] - 0.5).abs() < 1e-4);
|
||||
// A hole: even-odd always; non-zero only with opposite winding.
|
||||
let eo = fill(16, 16, &[sq(2.0, 14.0, false), sq(6.0, 10.0, false)], true);
|
||||
let nz_same = fill(16, 16, &[sq(2.0, 14.0, false), sq(6.0, 10.0, false)], false);
|
||||
let nz_opp = fill(16, 16, &[sq(2.0, 14.0, false), sq(6.0, 10.0, true)], false);
|
||||
let center = 8 * 16 + 8;
|
||||
assert_eq!((eo[center], nz_same[center], nz_opp[center]), (0.0, 1.0, 0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_svg_draws_the_leaf() {
|
||||
let def = crate::catalog::find("svg").unwrap();
|
||||
let p = crate::catalog::resolve_params(def, &Default::default());
|
||||
let no_res = |_: &str| None;
|
||||
let vars = Default::default();
|
||||
let ctx = Ctx { w: 64, h: 64, seed: 0, tile: true, inputs: &[], params: &p, resource: &no_res, vars: &vars };
|
||||
let img = &svg(&ctx).unwrap()[0];
|
||||
let a = img.mean()[3];
|
||||
assert!(a > 0.2 && a < 0.7, "{a}");
|
||||
assert!(img.get(20, 32, false)[3] > 0.9 && img.get(2, 2, false)[3] == 0.0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
//! Atomic › Text: renders a string with MaterialCraft's own single-stroke vector font, drawn as
|
||||
//! anti-aliased capsules. The font is original data defined below.
|
||||
|
||||
use std::f32::consts::TAU;
|
||||
|
||||
use crate::atomic::ATOMIC;
|
||||
use crate::catalog::{CookResult, Ctx, NodeDef, node};
|
||||
use crate::svg::{Capsules, Seg, composite};
|
||||
|
||||
/// The font: each glyph is strokes separated by spaces, each stroke a polyline of `xy` digit
|
||||
/// pairs on a grid 4 wide where y = 0 is the cap height, 2 the x-height, 6 the baseline and 8
|
||||
/// the descender. A single pair is a dot. Original design for MaterialCraft.
|
||||
const GLYPHS: &[(char, &str)] = &[
|
||||
('A', "062046 1333"),
|
||||
('B', "06003041423303 3344453606"),
|
||||
('C', "4130100105163645"),
|
||||
('D', "06003041453606"),
|
||||
('E', "40000646 0333"),
|
||||
('F', "400006 0333"),
|
||||
('G', "41301001051636454323"),
|
||||
('H', "0006 4046 0343"),
|
||||
('I', "1030 2026 1636"),
|
||||
('J', "4045361605"),
|
||||
('K', "0006 4004 1346"),
|
||||
('L', "000646"),
|
||||
('M', "0600234046"),
|
||||
('N', "06004640"),
|
||||
('O', "103041453616050110"),
|
||||
('P', "06003041423303"),
|
||||
('Q', "103041453616050110 2446"),
|
||||
('R', "06003041423303 2346"),
|
||||
('S', "413010010213334445361605"),
|
||||
('T', "0040 2026"),
|
||||
('U', "000516364540"),
|
||||
('V', "002640"),
|
||||
('W', "0016233640"),
|
||||
('X', "0046 4006"),
|
||||
('Y', "002340 2326"),
|
||||
('Z', "00400646"),
|
||||
('a', "4246 4332120305163645"),
|
||||
('b', "0006 0312324345361605"),
|
||||
('c', "4332120305163645"),
|
||||
('d', "4046 4332120305163645"),
|
||||
('e', "04444332120305163645"),
|
||||
('f', "4130201116 0232"),
|
||||
('g', "4247381807 4332120305163645"),
|
||||
('h', "0006 0312324346"),
|
||||
('i', "2226 20"),
|
||||
('j', "3237281807 30"),
|
||||
('k', "0006 3205 1436"),
|
||||
('l', "10202536"),
|
||||
('m', "0206 03122326 23324346"),
|
||||
('n', "0206 0312324346"),
|
||||
('o', "123243453616050312"),
|
||||
('p', "0208 0312324345361605"),
|
||||
('q', "4248 4332120305163645"),
|
||||
('r', "0206 04223243"),
|
||||
('s', "43321203143445361605"),
|
||||
('t', "10152636 0232"),
|
||||
('u', "0205163645 4246"),
|
||||
('v', "022642"),
|
||||
('w', "0216243642"),
|
||||
('x', "0246 4206"),
|
||||
('y', "0226 4218"),
|
||||
('z', "02420646"),
|
||||
('0', "103041453616050110 3115"),
|
||||
('1', "112026 1636"),
|
||||
('2', "01103041420646"),
|
||||
('3', "01103041423313 334445361605"),
|
||||
('4', "36300444"),
|
||||
('5', "400003334445361605"),
|
||||
('6', "30100105163645443303"),
|
||||
('7', "004016"),
|
||||
('8', "13020110304142331304051636454433"),
|
||||
('9', "43130201103041453616"),
|
||||
('.', "26"),
|
||||
(',', "2617"),
|
||||
('!', "2024 26"),
|
||||
('?', "0110304142332324 26"),
|
||||
(':', "22 26"),
|
||||
(';', "22 2617"),
|
||||
('-', "1333"),
|
||||
('+', "1333 2224"),
|
||||
('=', "1232 1434"),
|
||||
('*', "1135 3115 0333"),
|
||||
('/', "4006"),
|
||||
('\\', "0046"),
|
||||
('(', "30212536"),
|
||||
(')', "10212516"),
|
||||
('[', "30202636"),
|
||||
(']', "10202616"),
|
||||
('<', "410345"),
|
||||
('>', "014305"),
|
||||
('\'', "2021"),
|
||||
('"', "1011 3031"),
|
||||
('_', "0747"),
|
||||
('#', "1115 3135 0242 0444"),
|
||||
('%', "4006 01 45"),
|
||||
(' ', ""),
|
||||
];
|
||||
|
||||
/// A character's strokes; unknown characters show as `?`.
|
||||
fn glyph(c: char) -> &'static str {
|
||||
let find = |c: char| GLYPHS.iter().find(|(g, _)| *g == c).map(|(_, s)| *s);
|
||||
find(c).or_else(|| find('?')).unwrap_or("")
|
||||
}
|
||||
|
||||
/// The strokes of `s` as polylines in grid units.
|
||||
fn strokes(s: &str) -> impl Iterator<Item = Vec<[f32; 2]>> + '_ {
|
||||
s.split(' ')
|
||||
.filter(|t| !t.is_empty())
|
||||
.map(|t| t.as_bytes().chunks_exact(2).map(|p| [p[0].saturating_sub(b'0') as f32, p[1].saturating_sub(b'0') as f32]).collect())
|
||||
}
|
||||
|
||||
/// Longest text drawn (an allocation cap).
|
||||
const MAX_CHARS: usize = 10_000;
|
||||
|
||||
pub(crate) fn defs() -> Vec<NodeDef> {
|
||||
vec![
|
||||
node("text", "Text", ATOMIC)
|
||||
.desc("Draws text with a built-in single-stroke font (A–Z, a–z, 0–9, punctuation). \\n starts a new line.")
|
||||
.atomic()
|
||||
.generator()
|
||||
.text("text", "Text", "MaterialCraft")
|
||||
.float("size", "Size", 0.09, 0.0, 1.0)
|
||||
.float2("position", "Position", [0.5, 0.5], 0.0, 1.0)
|
||||
.choice("alignment", "Alignment", &["Left", "Center", "Right"], 1)
|
||||
.color("color", "Color", [1.0, 1.0, 1.0, 1.0])
|
||||
.float("weight", "Stroke weight", 0.7, 0.05, 3.0)
|
||||
.float("letter_spacing", "Letter spacing", 1.0, 0.0, 5.0)
|
||||
.float("line_spacing", "Line spacing", 1.0, 0.0, 5.0)
|
||||
.angle("rotation", "Rotation", 0.0)
|
||||
.boolean("tiling", "Tiling (wrap at edges)", true)
|
||||
.color_out()
|
||||
.cook(text),
|
||||
]
|
||||
}
|
||||
|
||||
/// The capsule segments of `txt` in pixel space.
|
||||
fn layout(ctx: &Ctx, txt: &str) -> Vec<Seg> {
|
||||
let unit = ctx.f("size").max(0.0) * ctx.h as f32 / 8.0;
|
||||
let (adv, line_h) = (4.0 + 2.0 * ctx.f("letter_spacing"), 10.0 * ctx.f("line_spacing"));
|
||||
let (align, pos) = (ctx.i("alignment"), ctx.v2("position"));
|
||||
let (s, c) = (ctx.f("rotation") * TAU).sin_cos();
|
||||
let anchor = [pos[0] * ctx.w as f32, pos[1] * ctx.h as f32];
|
||||
let lines: Vec<&str> = txt.split('\n').collect();
|
||||
// The block is centered vertically on the anchor (cap height of the first line to baseline of the last).
|
||||
let top = -((lines.len().max(1) - 1) as f32 * line_h + 6.0) * 0.5;
|
||||
let mut segs = Vec::new();
|
||||
for (li, line) in lines.iter().enumerate() {
|
||||
let n = line.chars().count() as f32;
|
||||
let width = if n > 0.0 { (n - 1.0) * adv + 4.0 } else { 0.0 };
|
||||
let x0 = match align {
|
||||
0 => 0.0,
|
||||
1 => -width * 0.5,
|
||||
_ => -width,
|
||||
};
|
||||
let y0 = top + li as f32 * line_h;
|
||||
for (ci, ch) in line.chars().enumerate() {
|
||||
let gx = x0 + ci as f32 * adv;
|
||||
for stroke in strokes(glyph(ch)) {
|
||||
let px: Vec<[f32; 2]> = stroke
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let (x, y) = ((gx + p[0]) * unit, (y0 + p[1]) * unit);
|
||||
[anchor[0] + x * c + y * s, anchor[1] - x * s + y * c]
|
||||
})
|
||||
.collect();
|
||||
match px.as_slice() {
|
||||
[a] => segs.push(Seg { a: *a, b: *a, wt: 1.0 }),
|
||||
_ => segs.extend(px.windows(2).map(|w| Seg { a: w[0], b: w[1], wt: 1.0 })),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
segs
|
||||
}
|
||||
|
||||
fn text(ctx: &Ctx) -> CookResult {
|
||||
let txt: String = ctx.text("text").replace("\\n", "\n").chars().take(MAX_CHARS).collect();
|
||||
let r = ctx.f("weight").max(0.0) * ctx.f("size").max(0.0) * ctx.h as f32 / 16.0;
|
||||
let caps = Capsules::new(layout(ctx, &txt), r, ctx.w, ctx.h, ctx.b("tiling"));
|
||||
Ok(vec![composite(ctx.w, ctx.h, ctx.v4("color"), |x, y| caps.coverage(x as f32 + 0.5, y as f32 + 0.5), [0.0; 4], |_, _| 0.0)])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use super::*;
|
||||
use crate::catalog::{find, resolve_params};
|
||||
|
||||
#[test]
|
||||
fn font_data_is_well_formed() {
|
||||
for (c, s) in GLYPHS {
|
||||
for t in s.split(' ').filter(|t| !t.is_empty()) {
|
||||
assert!(t.len() % 2 == 0 && t.bytes().all(|b| b.is_ascii_digit()), "{c:?}: {t}");
|
||||
assert!(t.as_bytes().chunks(2).all(|p| p[0] <= b'4' && p[1] <= b'8'), "{c:?}: {t} leaves the grid");
|
||||
}
|
||||
}
|
||||
for c in ('A'..='Z').chain('a'..='z').chain('0'..='9') {
|
||||
assert!(GLYPHS.iter().any(|(g, _)| *g == c), "{c} missing");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renders_material_craft() {
|
||||
let def = find("text").unwrap();
|
||||
let p = resolve_params(def, &BTreeMap::new());
|
||||
let no_res = |_: &str| None;
|
||||
let vars = BTreeMap::new();
|
||||
let ctx = Ctx { w: 256, h: 256, seed: 0, tile: true, inputs: &[], params: &p, resource: &no_res, vars: &vars };
|
||||
let img = &text(&ctx).unwrap()[0];
|
||||
let lit = img.data.chunks(4).filter(|p| p[3] > 0.5).count();
|
||||
assert!(lit > 300, "{lit} pixels");
|
||||
// Centered: nothing in the top and bottom quarters.
|
||||
assert!((0..256).all(|x| img.get(x, 20, false)[3] == 0.0 && img.get(x, 236, false)[3] == 0.0));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
//! Wear and weathering: cracks, paint strokes, scratches along a direction field, rust, moss and
|
||||
//! lichen, leaks (drips running down from a mask) and chipped edges. The generators tile.
|
||||
|
||||
use std::f32::consts::{PI, TAU};
|
||||
|
||||
use materialcraft_image::{Image, Kind};
|
||||
use rayon::prelude::*;
|
||||
|
||||
use crate::catalog::{CookResult, Ctx, NodeDef, PortKind, node};
|
||||
use crate::fx_map::{BLENDS, Inst, splat};
|
||||
use crate::generators::NOISES;
|
||||
use crate::noise::{cellular, fbm, rand1, value};
|
||||
use crate::noises_more::smoothstep;
|
||||
use crate::ops;
|
||||
use crate::patterns::PATTERNS;
|
||||
use crate::svg::{Capsules, Seg};
|
||||
|
||||
const WEATHER: &str = "Material filters/Weathering";
|
||||
|
||||
pub(crate) fn defs() -> Vec<NodeDef> {
|
||||
vec![
|
||||
node("cracks", "Cracks", NOISES)
|
||||
.desc("A connected network of thin cracks along warped cell borders, with finer branching cracks. White = crack.")
|
||||
.generator()
|
||||
.float("scale", "Scale", 5.0, 1.0, 32.0)
|
||||
.float("width", "Width", 1.5, 0.0, 16.0)
|
||||
.float("warp", "Warp", 0.5, 0.0, 1.0)
|
||||
.float("branches", "Branches", 0.5, 0.0, 1.0)
|
||||
.gray_out()
|
||||
.cook(cracks),
|
||||
node("paint_strokes", "Paint Strokes", PATTERNS)
|
||||
.desc("Overlapping brush strokes with bristle streaks and ragged ends.")
|
||||
.generator()
|
||||
.int("count", "Count", 150, 1, 5000)
|
||||
.float("length", "Length", 0.35, 0.0, 1.0)
|
||||
.float("width", "Width", 0.07, 0.0, 0.5)
|
||||
.angle("angle", "Angle", 0.0)
|
||||
.float("angle_random", "Angle random", 0.08, 0.0, 1.0)
|
||||
.int("bristles", "Bristles", 20, 1, 256)
|
||||
.float("luminance_random", "Luminance random", 0.5, 0.0, 1.0)
|
||||
.choice("blending", "Blending", BLENDS, 2)
|
||||
.gray_out()
|
||||
.cook(paint_strokes),
|
||||
node("scratches_generator", "Scratches Generator", PATTERNS)
|
||||
.desc("Thin tapered scratches that bend along a direction field (gray = angle in turns) and land where the mask is bright.")
|
||||
.generator()
|
||||
.gray_in("direction", "Direction field")
|
||||
.gray_in("mask", "Mask")
|
||||
.int("count", "Count", 200, 0, 5000)
|
||||
.float("length", "Length", 0.25, 0.0, 1.0)
|
||||
.float("width", "Width", 1.0, 0.1, 16.0)
|
||||
.angle("angle", "Angle", 0.0)
|
||||
.float("angle_random", "Angle random", 0.15, 0.0, 1.0)
|
||||
.float("curvature", "Curvature", 0.1, 0.0, 1.0)
|
||||
.float("field_intensity", "Field intensity", 0.25, 0.0, 1.0)
|
||||
.float("luminance_random", "Luminance random", 0.6, 0.0, 1.0)
|
||||
.gray_out()
|
||||
.cook(scratches_generator),
|
||||
node("rust", "Rust", WEATHER)
|
||||
.desc("A mask of rust blotches and pitting; with a mask input it grows out from the mask (edges, cavities).")
|
||||
.generator()
|
||||
.gray_in("mask", "Mask (optional)")
|
||||
.float("amount", "Amount", 0.45, 0.0, 1.0)
|
||||
.float("scale", "Scale", 6.0, 1.0, 64.0)
|
||||
.float("spread", "Spread", 12.0, 0.0, 128.0)
|
||||
.float("pitting", "Pitting", 0.5, 0.0, 1.0)
|
||||
.float("contrast", "Contrast", 0.7, 0.0, 1.0)
|
||||
.gray_out()
|
||||
.cook(rust),
|
||||
node("moss", "Moss / Lichen", WEATHER)
|
||||
.desc("Fuzzy moss clumps (gathering in low areas) or round lichen rosettes (on high areas) of an optional height map.")
|
||||
.generator()
|
||||
.gray_in("height", "Height (optional)")
|
||||
.choice("style", "Style", &["Moss", "Lichen"], 0)
|
||||
.float("amount", "Amount", 0.5, 0.0, 1.0)
|
||||
.float("scale", "Scale", 6.0, 1.0, 64.0)
|
||||
.float("height_bias", "Height bias", 0.5, 0.0, 1.0)
|
||||
.float("contrast", "Contrast", 0.6, 0.0, 1.0)
|
||||
.gray_out()
|
||||
.cook(moss),
|
||||
node("leaks", "Leaks", WEATHER)
|
||||
.desc("Streaky drips running down from a mask (unconnected: random stains), fading with length and meandering.")
|
||||
.gray_in("mask", "Mask")
|
||||
.float("length", "Length", 0.35, 0.0, 1.0)
|
||||
.float("length_random", "Length random", 0.7, 0.0, 1.0)
|
||||
.float("streaks", "Streaks", 32.0, 1.0, 256.0)
|
||||
.float("wobble", "Wobble", 0.3, 0.0, 1.0)
|
||||
.gray_out()
|
||||
.cook(leaks),
|
||||
node("edge_damage", "Edge Damage", WEATHER)
|
||||
.desc("Chips the edges of a height mask (white = material) in chunky, ragged bites; also outputs the damage mask.")
|
||||
.gray_in("height", "Height")
|
||||
.float("width", "Width", 8.0, 0.0, 64.0)
|
||||
.float("amount", "Amount", 0.5, 0.0, 1.0)
|
||||
.float("scale", "Chip scale", 12.0, 1.0, 64.0)
|
||||
.float("roughness", "Roughness", 0.5, 0.0, 1.0)
|
||||
.float("depth", "Depth", 1.0, 0.0, 1.0)
|
||||
.gray_out()
|
||||
.output("mask", "Damage mask", PortKind::Gray)
|
||||
.cook(edge_damage),
|
||||
]
|
||||
}
|
||||
|
||||
/// `v` pixels at 256 px, at the output size.
|
||||
fn px(ctx: &Ctx, v: f32) -> f32 {
|
||||
v * ctx.w as f32 / 256.0
|
||||
}
|
||||
|
||||
fn whole(ctx: &Ctx, id: &str) -> f32 {
|
||||
ctx.f(id).max(1.0).round()
|
||||
}
|
||||
|
||||
/// A soft threshold: 1 where `v` is above `1 - amount`; `contrast` 1 is hard, 0 soft.
|
||||
fn thresh(v: f32, amount: f32, contrast: f32) -> f32 {
|
||||
let soft = (1.0 - contrast.clamp(0.0, 1.0)) * 0.25 + 0.005;
|
||||
smoothstep(1.0 - amount - soft, 1.0 - amount + soft, v)
|
||||
}
|
||||
|
||||
/// A gray image from `f(pixel index, u, v)`.
|
||||
fn gen_px(ctx: &Ctx, f: impl Fn(usize, f32, f32) -> f32 + Sync) -> Image {
|
||||
let (w, h) = (ctx.w.max(1), ctx.h.max(1));
|
||||
Image::generate(w, h, Kind::Gray, |x, y| [f(y as usize * w as usize + x as usize, (x as f32 + 0.5) / w as f32, (y as f32 + 0.5) / h as f32), 0.0, 0.0, 0.0])
|
||||
}
|
||||
|
||||
fn cracks(ctx: &Ctx) -> CookResult {
|
||||
let (s, wpx, warp, br, seed) = (whole(ctx, "scale"), px(ctx, ctx.f("width")), ctx.f("warp"), ctx.f("branches"), ctx.seed);
|
||||
let cell_px = ctx.w as f32 / s;
|
||||
Ok(vec![ctx.gen_gray(|u, v| {
|
||||
// Broad bends plus fine jaggedness, both in cell units.
|
||||
let k = warp / s;
|
||||
let wu = u + (fbm(u, v, 4.0, 4, 0.5, seed ^ 11) - 0.5) * 2.0 * k + (fbm(u, v, s * 4.0, 3, 0.5, seed ^ 14) - 0.5) * 0.3 * k;
|
||||
let wv = v + (fbm(u, v, 4.0, 4, 0.5, seed ^ 12) - 0.5) * 2.0 * k + (fbm(u, v, s * 4.0, 3, 0.5, seed ^ 15) - 0.5) * 0.3 * k;
|
||||
let line = |m: f32, sd: u32, half: f32| {
|
||||
let c = cellular(wu * s * m, wv * s * m, (s * m) as i32, 1.0, 0, sd);
|
||||
1.0 - smoothstep(half, half + 1.0, (c.f2 - c.f1) * 0.5 * cell_px / m)
|
||||
};
|
||||
let main = line(1.0, seed, wpx * 0.5);
|
||||
if br <= 0.0 {
|
||||
return main;
|
||||
}
|
||||
let keep = smoothstep(1.0 - br, 1.0 - br + 0.2, fbm(u, v, s, 3, 0.5, seed ^ 13));
|
||||
main.max(line(3.0, seed ^ 7, wpx * 0.3) * keep * 0.8)
|
||||
})])
|
||||
}
|
||||
|
||||
fn paint_strokes(ctx: &Ctx) -> CookResult {
|
||||
let (len, wid, ang, ar, lr, s) = (ctx.f("length"), ctx.f("width"), ctx.f("angle"), ctx.f("angle_random"), ctx.f("luminance_random"), ctx.seed);
|
||||
let bristles = ctx.i("bristles").clamp(1, 256) as f32;
|
||||
let items: Vec<Inst> = (0..ctx.i("count").clamp(1, 5000) as u32)
|
||||
.map(|i| {
|
||||
let r = |k: u32| rand1(i * 8 + k, s);
|
||||
Inst {
|
||||
c: [r(0), r(1)],
|
||||
r: [len * 0.5 * (0.7 + 0.3 * r(2)), wid * 0.5 * (0.8 + 0.4 * r(3))],
|
||||
rot: ang + (r(4) - 0.5) * ar,
|
||||
lum: 1.0 - lr * r(5),
|
||||
pat: 0,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
Ok(vec![splat(ctx, &items, ctx.i("blending"), |i, x, y| {
|
||||
let sd = s ^ (i as u32).wrapping_mul(0x9e37_79b9);
|
||||
// Bristle density across the stroke; the ends are ragged per bristle.
|
||||
let b = value(y * bristles + 0.5, 0.5, 0, sd);
|
||||
let ragged = value(y * bristles * 0.5 + 3.1, x * 2.0, 0, sd ^ 1);
|
||||
let end = 1.0 - smoothstep(0.55 + 0.4 * ragged, 1.0, x.abs());
|
||||
let edge = 1.0 - smoothstep(0.7, 1.0, y.abs());
|
||||
end * edge * (0.45 + 0.55 * b)
|
||||
})])
|
||||
}
|
||||
|
||||
fn scratches_generator(ctx: &Ctx) -> CookResult {
|
||||
const STEPS: u32 = 12;
|
||||
let (len, ang, ar, curv, fi, lr, s) =
|
||||
(ctx.f("length"), ctx.f("angle"), ctx.f("angle_random"), ctx.f("curvature"), ctx.f("field_intensity"), ctx.f("luminance_random"), ctx.seed);
|
||||
let (field, mask) = (ctx.input(0), ctx.input(1));
|
||||
let (w, h) = (ctx.w as f32, ctx.h as f32);
|
||||
let mut segs = Vec::new();
|
||||
for i in 0..ctx.i("count").clamp(0, 5000) as u32 {
|
||||
let r = |k: u32| rand1(i * 8 + k, s);
|
||||
let mut p = [r(0), r(1)];
|
||||
if mask.is_some_and(|m| r(2) >= m.sample_gray(p[0], p[1], ctx.tile)) {
|
||||
continue;
|
||||
}
|
||||
let (base, bend, lum) = (ang + (r(3) - 0.5) * ar, (r(4) - 0.5) * curv, 1.0 - lr * r(6));
|
||||
let step = len * (0.4 + 0.6 * r(5)) / STEPS as f32;
|
||||
for k in 0..STEPS {
|
||||
let t = k as f32 / STEPS as f32;
|
||||
let a = (base + bend * t + field.map_or(0.0, |f| f.sample_gray(p[0], p[1], ctx.tile) * fi)) * TAU;
|
||||
let q = [p[0] + a.cos() * step, p[1] - a.sin() * step];
|
||||
let taper = ((t + 0.5 / STEPS as f32) * PI).sin().sqrt();
|
||||
segs.push(Seg { a: [p[0] * w, p[1] * h], b: [q[0] * w, q[1] * h], wt: lum * taper });
|
||||
p = q;
|
||||
}
|
||||
}
|
||||
let caps = Capsules::new(segs, px(ctx, ctx.f("width")) * 0.5, ctx.w, ctx.h, ctx.tile);
|
||||
Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Gray, |x, y| [caps.coverage(x as f32 + 0.5, y as f32 + 0.5), 0.0, 0.0, 0.0])])
|
||||
}
|
||||
|
||||
fn rust(ctx: &Ctx) -> CookResult {
|
||||
let (amt, s, pit, con, seed) = (ctx.f("amount"), whole(ctx, "scale"), ctx.f("pitting"), ctx.f("contrast"), ctx.seed);
|
||||
let grow = ctx.sized(0).map(|m| ops::gaussian(&m.to_gray(), px(ctx, ctx.f("spread")), ctx.tile));
|
||||
Ok(vec![gen_px(ctx, |i, u, v| {
|
||||
let blotch = fbm(u, v, s, 6, 0.55, seed);
|
||||
let base = match &grow {
|
||||
Some(g) => 0.5 * blotch + 0.6 * g.data.get(i).copied().unwrap_or(0.0),
|
||||
None => blotch,
|
||||
};
|
||||
let c = cellular(u * s * 8.0, v * s * 8.0, (s * 8.0) as i32, 1.0, 0, seed ^ 3);
|
||||
let pits = (1.0 - smoothstep(0.05, 0.4, c.f1)) * (c.id < pit) as i32 as f32;
|
||||
// Pits speckle the surroundings of the blotches only.
|
||||
thresh(base + pits * 0.2 * smoothstep(0.3, 0.5, base), amt, con) * (0.7 + 0.3 * fbm(u, v, s * 16.0, 3, 0.6, seed ^ 5))
|
||||
})])
|
||||
}
|
||||
|
||||
fn moss(ctx: &Ctx) -> CookResult {
|
||||
let (lichen, amt, s, bias, con, seed) = (ctx.i("style") == 1, ctx.f("amount"), whole(ctx, "scale"), ctx.f("height_bias"), ctx.f("contrast"), ctx.seed);
|
||||
let hgt = ctx.sized(0).map(|h| h.to_gray());
|
||||
Ok(vec![gen_px(ctx, |i, u, v| {
|
||||
let hb = hgt.as_ref().map_or(0.0, |h| (h.data.get(i).copied().unwrap_or(0.5) - 0.5) * bias);
|
||||
let fine = |m: f32, sd: u32| value(u * s * m, v * s * m, (s * m) as i32, seed ^ sd);
|
||||
if !lichen {
|
||||
// Fuzzy clumps, thicker in low areas.
|
||||
let clump = fbm(u, v, s, 5, 0.6, seed) - hb + (fine(24.0, 9) - 0.5) * 0.25;
|
||||
return thresh(clump, amt, con) * (0.55 + 0.45 * fine(48.0, 10));
|
||||
}
|
||||
// Round rosettes with brighter rims, on high areas.
|
||||
let c = cellular(u * s, v * s, s as i32, 0.9, 0, seed);
|
||||
if c.id >= amt * 1.4 + hb {
|
||||
return 0.0;
|
||||
}
|
||||
let rad = (0.25 + 0.35 * (c.id * 7.31).fract()) * (0.8 + 0.4 * fbm(u, v, s * 8.0, 3, 0.5, seed ^ 4));
|
||||
let soft = 0.01 + (1.0 - con) * 0.06;
|
||||
(1.0 - smoothstep(rad - soft, rad, c.f1)) * (0.55 + 0.45 * smoothstep(rad * 0.4, rad, c.f1)) * (0.8 + 0.2 * fine(32.0, 6))
|
||||
})])
|
||||
}
|
||||
|
||||
fn leaks(ctx: &Ctx) -> CookResult {
|
||||
let (w, h, seed) = (ctx.w as usize, ctx.h as usize, ctx.seed);
|
||||
let src = match ctx.sized(0) {
|
||||
Some(m) => m.to_gray(),
|
||||
None => ctx.gen_gray(|u, v| smoothstep(0.62, 0.7, fbm(u, v, 4.0, 4, 0.5, seed ^ 21))),
|
||||
};
|
||||
let (len, lr, streaks, wob) = (ctx.f("length").max(0.0) * h as f32, ctx.f("length_random"), whole(ctx, "streaks"), ctx.f("wobble"));
|
||||
// Each column carries its value down, fading over a length that varies across columns.
|
||||
let cols: Vec<Vec<f32>> = (0..w)
|
||||
.into_par_iter()
|
||||
.map(|x| {
|
||||
let u = (x as f32 + 0.5) / w as f32;
|
||||
let r = 0.6 * value(u * streaks, 0.5, streaks as i32, seed ^ 23) + 0.4 * value(u * streaks * 4.0, 0.5, (streaks * 4.0) as i32, seed ^ 24);
|
||||
let decay = (-3.0 / (len * (1.0 - lr * r)).max(1.0)).exp();
|
||||
let mut col = vec![0.0f32; h];
|
||||
let mut acc = 0.0f32;
|
||||
// Tiling: a second pass carries drips over the bottom edge to the top.
|
||||
let passes = if ctx.tile { 2 } else { 1 };
|
||||
for pass in 0..passes {
|
||||
for (y, out) in col.iter_mut().enumerate() {
|
||||
acc = src.data.get(y * w + x).copied().unwrap_or(0.0).max(acc * decay);
|
||||
if pass + 1 == passes {
|
||||
*out = acc;
|
||||
}
|
||||
}
|
||||
}
|
||||
col
|
||||
})
|
||||
.collect();
|
||||
let run = Image::gray(ctx.w, ctx.h, |x, y| cols.get(x as usize).and_then(|c| c.get(y as usize)).copied().unwrap_or(0.0));
|
||||
Ok(vec![ctx.gen_gray(|u, v| {
|
||||
let dx = (fbm(u, v, 8.0, 3, 0.5, seed ^ 22) - 0.5) * wob * 0.04;
|
||||
run.sample_gray(u + dx, v, ctx.tile) * (0.75 + 0.25 * value(u * streaks * 2.0, v * 3.0, (streaks * 2.0) as i32, seed ^ 25))
|
||||
})])
|
||||
}
|
||||
|
||||
fn edge_damage(ctx: &Ctx) -> CookResult {
|
||||
let hgt = ctx.gray_or(0, 0.0);
|
||||
let data = hgt.data.clone();
|
||||
let solid = |i: usize| data.get(i).is_some_and(|v| *v > 0.5);
|
||||
let dist = ops::distance_sq(ctx.w, ctx.h, |i| !solid(i), ctx.tile);
|
||||
let (wpx, amt, s, rough, depth, seed) = (px(ctx, ctx.f("width")), ctx.f("amount"), whole(ctx, "scale"), ctx.f("roughness"), ctx.f("depth"), ctx.seed);
|
||||
let mask = gen_px(ctx, |i, u, v| {
|
||||
if !solid(i) {
|
||||
return 0.0;
|
||||
}
|
||||
let d = dist.get(i).map_or(0.0, |d| d.sqrt());
|
||||
// Chunky bites per cell, made ragged by noise.
|
||||
let c = cellular(u * s, v * s, s as i32, 1.0, 0, seed);
|
||||
let r = c.id * (1.0 - rough * 0.5) + (fbm(u, v, s * 2.0, 4, 0.5, seed ^ 3) - 0.5) * rough * 1.5;
|
||||
let reach = wpx * 2.0 * amt * r.max(0.0);
|
||||
1.0 - smoothstep(reach - 0.75, reach + 0.75, d)
|
||||
});
|
||||
let out = Image::gray(ctx.w, ctx.h, |x, y| {
|
||||
let i = (y * ctx.w + x) as usize;
|
||||
data.get(i).copied().unwrap_or(0.0) * (1.0 - depth * mask.data.get(i).copied().unwrap_or(0.0))
|
||||
});
|
||||
Ok(vec![out, mask])
|
||||
}
|
||||
Reference in new issue
Block a user