darkly 0.5.0

A GPU-native paint engine on wgpu: brushes, layers, blend modes, masks, selections, and undo.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
//! End-to-end tests for wire-boundary range remap (`PortDef::natural_range`).
//!
//! The bug that motivated this: `random.value → shape.seed` produced the
//! same seed every dab because random's output (`[-1, 1]`) collapsed to 0
//! when seed cast it through `as u32` (range `[0, 1024]`). The fix is that
//! when both ends of a wire declare a `natural_range`, the runner remaps
//! the value at slot-read time.
//!
//! These tests exercise the runner-level remap path with hand-built graphs
//! that customize port natural ranges per-instance (the registration ports
//! are cloned into each `NodeInstance`, so we can declare a non-default
//! `natural_range` on a single test instance without touching any node's
//! registration).

use darkly::brush::eval::BrushGraphRunner;
use darkly::brush::paint_info::PaintInformation;
use darkly::brush::registry;
use darkly::brush::wire::ScalarValue;
use darkly::gpu::params::ParamValue;
use darkly::nodegraph::{Graph, PortDef, PortRef};

/// Per-instance params for the `random` node: mode=0 (per-dab, the default).
fn random_params() -> Vec<ParamValue> {
    vec![ParamValue::Int(0)]
}

fn read_scalar(runner: &BrushGraphRunner, type_id: &str, port: &str) -> f32 {
    let slot = runner
        .find_output_slot(type_id, port)
        .unwrap_or_else(|| panic!("no slot for {type_id}.{port}"));
    match runner.read_slot(slot).expect("slot has value") {
        ScalarValue::Scalar(v) => v,
        other => panic!("expected Scalar, got {other:?}"),
    }
}

fn run_one_dab(runner: &mut BrushGraphRunner, pressure: f32, dab_index: u32) {
    let info = PaintInformation {
        pressure,
        ..Default::default()
    };
    runner.seed_sensors(&info, [0.0, 0.0, 0.0, 1.0], 42, dab_index);
    runner.clear_slots();
    runner.seed_sensors(&info, [0.0, 0.0, 0.0, 1.0], 42, dab_index);
    runner.execute_cpu();
}

/// Regression for the original bug: `random` output is now in `[0, 1)` (the
/// natural PRNG range), no longer the old `[-1, 1]` remap, and produces a
/// fresh value each dab. The previous behavior — `random` outputting in
/// `[-1, 1]` and any downstream `as u32` cast collapsing it to 0 — is what
/// caused `random → shape.seed` to repeat.
#[test]
fn random_outputs_unit_range_and_varies_per_dab() {
    let registry = registry();
    let mut graph = Graph::new();
    let random_reg = registry.get("random").unwrap();
    graph.add_node("random", random_reg.ports.clone(), random_params());

    let mut runner =
        BrushGraphRunner::new(&graph, registry.as_map(), registry.evaluators()).unwrap();

    let mut samples = Vec::with_capacity(16);
    for dab in 0..16 {
        run_one_dab(&mut runner, 0.5, dab);
        let v = read_scalar(&runner, "random", "value");
        assert!(
            (0.0..1.0).contains(&v),
            "random output {v} outside [0, 1) on dab {dab}",
        );
        samples.push(v);
    }

    // Strong evidence the value actually varies per dab — at least 10 of 16
    // distinct values rules out "always returns the same thing."
    let mut sorted = samples.clone();
    sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());
    sorted.dedup_by(|a, b| (*a - *b).abs() < 1e-6);
    assert!(
        sorted.len() >= 10,
        "expected ≥10 distinct random values over 16 dabs, got {} (samples: {:?})",
        sorted.len(),
        samples,
    );
}

/// `random → seed-style port (natural_range [0, 1024])` produces values
/// spread across the destination range, varying per dab.
///
/// We can't observe `shape.seed` directly without a GPU, but the runner's
/// remap step happens at `gather_inputs` — same code path for CPU and GPU
/// nodes. So we exercise it through a CPU node (`multiply`) with a
/// per-instance override on its `a` port: `natural_range = Some((0, 1024))`.
/// The multiply evaluator computes `a * b` with the default `b = 1`, so
/// `multiply.result == a_after_remap`.
#[test]
fn random_to_wide_range_input_remaps() {
    let registry = registry();
    let mut graph = Graph::new();

    let random_reg = registry.get("random").unwrap();
    let random = graph.add_node("random", random_reg.ports.clone(), random_params());

    // Clone multiply's ports, then widen the `a` input's natural_range to
    // simulate wiring random into something like `shape.seed`.
    let multiply_reg = registry.get("multiply").unwrap();
    let mut multiply_ports = multiply_reg.ports.clone();
    for p in multiply_ports.iter_mut() {
        if p.name == "a" {
            *p = std::mem::replace(p, PortDef::input("placeholder", p.wire_type))
                .with_natural_range(0.0, 1024.0);
        }
    }
    let multiply = graph.add_node("multiply", multiply_ports, vec![]);

    graph
        .connect(
            PortRef {
                node: random,
                port: "value".into(),
            },
            PortRef {
                node: multiply,
                port: "a".into(),
            },
        )
        .unwrap();

    let mut runner =
        BrushGraphRunner::new(&graph, registry.as_map(), registry.evaluators()).unwrap();

    let mut samples = Vec::new();
    for dab in 0..16 {
        run_one_dab(&mut runner, 0.5, dab);
        let v = read_scalar(&runner, "multiply", "result");
        assert!(
            (0.0..=1024.0).contains(&v),
            "multiply.result {v} outside [0, 1024] on dab {dab}",
        );
        samples.push(v);
    }
    // Values should span a meaningful chunk of [0, 1024]: max - min > 500.
    let min = samples.iter().cloned().fold(f32::INFINITY, f32::min);
    let max = samples.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
    assert!(
        max - min > 500.0,
        "expected wide spread across [0, 1024], got [{min}, {max}] (samples {samples:?})",
    );
}

/// `pen.pressure → frequency-style port (natural_range [1, 16])` — the
/// other half of the bug class. Today this works; before the fix, pen
/// pressure ∈ [0, 1] cast to a frequency in [1, 16] rounded to 1 forever.
#[test]
fn pen_pressure_to_frequency_range_remaps() {
    let registry = registry();
    let mut graph = Graph::new();

    let pen_reg = registry.get("pen_input").unwrap();
    let pen = graph.add_node("pen_input", pen_reg.ports.clone(), vec![]);

    let multiply_reg = registry.get("multiply").unwrap();
    let mut multiply_ports = multiply_reg.ports.clone();
    for p in multiply_ports.iter_mut() {
        if p.name == "a" {
            *p = std::mem::replace(p, PortDef::input("placeholder", p.wire_type))
                .with_natural_range(1.0, 16.0);
        }
    }
    let multiply = graph.add_node("multiply", multiply_ports, vec![]);

    graph
        .connect(
            PortRef {
                node: pen,
                port: "pressure".into(),
            },
            PortRef {
                node: multiply,
                port: "a".into(),
            },
        )
        .unwrap();

    let mut runner =
        BrushGraphRunner::new(&graph, registry.as_map(), registry.evaluators()).unwrap();

    // pressure 0.0 → a 1.0
    run_one_dab(&mut runner, 0.0, 0);
    let v = read_scalar(&runner, "multiply", "result");
    assert!(
        (v - 1.0).abs() < 1e-4,
        "pressure 0 → a expected 1.0, got {v}"
    );

    // pressure 0.5 → a 8.5
    run_one_dab(&mut runner, 0.5, 1);
    let v = read_scalar(&runner, "multiply", "result");
    assert!(
        (v - 8.5).abs() < 1e-4,
        "pressure 0.5 → a expected 8.5, got {v}"
    );

    // pressure 1.0 → a 16.0
    run_one_dab(&mut runner, 1.0, 2);
    let v = read_scalar(&runner, "multiply", "result");
    assert!(
        (v - 16.0).abs() < 1e-4,
        "pressure 1.0 → a expected 16.0, got {v}"
    );
}

/// Source-side opt-out: `multiply.result` has no natural_range, so wiring
/// it into a port that does still passes the raw value through (math nodes
/// are intentionally unbounded — their range depends on inputs). This is
/// the invariant that lets us reshape random's behavior without disturbing
/// any existing math-node-based brush.
#[test]
fn math_node_output_passes_through_to_ranged_input() {
    let registry = registry();
    let mut graph = Graph::new();

    // Source multiply with explicit defaults a=0.5, b=0.5 → result=0.25.
    let multiply_src_reg = registry.get("multiply").unwrap();
    let mut multiply_src_ports = multiply_src_reg.ports.clone();
    for p in multiply_src_ports.iter_mut() {
        if p.name == "a" || p.name == "b" {
            p.default = 0.5;
        }
    }
    let multiply_src = graph.add_node("multiply", multiply_src_ports, vec![]);

    // Sink multiply: `a` carries an overridden natural_range Some((0, 1024)).
    // If multiply_src were mistakenly opted in to source-side remap, we'd
    // see 0.25 stretched to 256. The passthrough invariant says we should
    // see 0.25 raw.
    let multiply_sink_reg = registry.get("multiply").unwrap();
    let mut multiply_sink_ports = multiply_sink_reg.ports.clone();
    for p in multiply_sink_ports.iter_mut() {
        if p.name == "a" {
            *p = std::mem::replace(p, PortDef::input("placeholder", p.wire_type))
                .with_natural_range(0.0, 1024.0);
        }
    }
    let multiply_sink = graph.add_node("multiply", multiply_sink_ports, vec![]);

    graph
        .connect(
            PortRef {
                node: multiply_src,
                port: "result".into(),
            },
            PortRef {
                node: multiply_sink,
                port: "a".into(),
            },
        )
        .unwrap();

    let mut runner =
        BrushGraphRunner::new(&graph, registry.as_map(), registry.evaluators()).unwrap();

    run_one_dab(&mut runner, 0.0, 0);
    // Sink's b defaults to 1.0, so result == a (the value that reached
    // the evaluator after any wire remap). Read by node id to disambiguate
    // from the source multiply.
    let slot = runner
        .find_node_output_slot(multiply_sink, "result")
        .expect("sink slot exists");
    let v = match runner.read_slot(slot).expect("slot has value") {
        ScalarValue::Scalar(v) => v,
        other => panic!("expected Scalar, got {other:?}"),
    };
    assert!((v - 0.25).abs() < 1e-4, "expected raw 0.25, got {v}");
}

/// Dest-side opt-out: wiring a normalized source (random, `[0, 1)`) into a
/// port without a natural_range passes the value through raw. This is the
/// invariant that lets `stamp.size` keep its over-drag behavior — even if
/// you wire pen.pressure into it, the value flows as raw `[0, 1)` instead
/// of being mapped onto the slider's `[0, 4]` hint.
#[test]
fn ranged_source_to_unranged_input_passes_through() {
    let registry = registry();
    let mut graph = Graph::new();

    let random_reg = registry.get("random").unwrap();
    let random = graph.add_node("random", random_reg.ports.clone(), random_params());

    // multiply.a — explicitly STRIP the natural_range so this node-instance
    // behaves as if the consumer hadn't opted in.
    let multiply_reg = registry.get("multiply").unwrap();
    let mut multiply_ports = multiply_reg.ports.clone();
    for p in multiply_ports.iter_mut() {
        if p.name == "a" {
            p.natural_range = None;
        }
    }
    let multiply = graph.add_node("multiply", multiply_ports, vec![]);

    graph
        .connect(
            PortRef {
                node: random,
                port: "value".into(),
            },
            PortRef {
                node: multiply,
                port: "a".into(),
            },
        )
        .unwrap();

    let mut runner =
        BrushGraphRunner::new(&graph, registry.as_map(), registry.evaluators()).unwrap();

    for dab in 0..8 {
        run_one_dab(&mut runner, 0.5, dab);
        let v = read_scalar(&runner, "multiply", "result");
        // Raw random value, unscaled — should stay in [0, 1).
        assert!(
            (0.0..1.0).contains(&v),
            "unranged dest should see raw random in [0, 1), got {v} on dab {dab}",
        );
    }
}

/// Identity-range remap (source range == dest range) is a no-op. Wiring
/// `pen.pressure → curve.input` (both `Some((0, 1))`) preserves the value
/// exactly, so the identity curve's output equals pressure.
#[test]
fn identity_range_is_a_noop() {
    let registry = registry();
    let mut graph = Graph::new();

    let pen_reg = registry.get("pen_input").unwrap();
    let pen = graph.add_node("pen_input", pen_reg.ports.clone(), vec![]);

    let curve_reg = registry.get("curve").unwrap();
    let curve = graph.add_node(
        "curve",
        curve_reg.ports.clone(),
        vec![darkly::gpu::params::ParamValue::Curve(vec![
            [0.0, 0.0],
            [1.0, 1.0],
        ])],
    );

    graph
        .connect(
            PortRef {
                node: pen,
                port: "pressure".into(),
            },
            PortRef {
                node: curve,
                port: "input".into(),
            },
        )
        .unwrap();

    let mut runner =
        BrushGraphRunner::new(&graph, registry.as_map(), registry.evaluators()).unwrap();

    for pressure in [0.0_f32, 0.25, 0.5, 0.75, 1.0] {
        run_one_dab(&mut runner, pressure, 0);
        let v = read_scalar(&runner, "curve", "output");
        // Identity curve has small LUT-quantization noise — same tolerance
        // the existing `curve_spline_identity` test uses.
        assert!(
            (v - pressure).abs() < 0.02,
            "identity remap should preserve pressure {pressure}, got {v}",
        );
    }
}

/// Bipolar destination range: `random [0, 1] → [-100, 100]` spans both
/// halves, verifying the affine remap handles a negative `dst_min`.
///
/// Note: radian-typed ports (`shape.rotation`, `liquify.direction`, etc.)
/// deliberately do NOT have a `natural_range` — radians are a unit, not
/// a normalized signal, and wires like `pen.drawing_angle → rotation`
/// must preserve them exactly. This test uses an abstract `[-100, 100]`
/// to exercise the math without conflating "negative remap target" with
/// "angular signal."
#[test]
fn unit_source_to_bipolar_dest_spans_full_range() {
    let registry = registry();
    let mut graph = Graph::new();

    let random_reg = registry.get("random").unwrap();
    let random = graph.add_node("random", random_reg.ports.clone(), random_params());

    let multiply_reg = registry.get("multiply").unwrap();
    let mut multiply_ports = multiply_reg.ports.clone();
    for p in multiply_ports.iter_mut() {
        if p.name == "a" {
            *p = std::mem::replace(p, PortDef::input("placeholder", p.wire_type))
                .with_natural_range(-100.0, 100.0);
        }
    }
    let multiply = graph.add_node("multiply", multiply_ports, vec![]);

    graph
        .connect(
            PortRef {
                node: random,
                port: "value".into(),
            },
            PortRef {
                node: multiply,
                port: "a".into(),
            },
        )
        .unwrap();

    let mut runner =
        BrushGraphRunner::new(&graph, registry.as_map(), registry.evaluators()).unwrap();

    let mut min = f32::INFINITY;
    let mut max = f32::NEG_INFINITY;
    for dab in 0..32 {
        run_one_dab(&mut runner, 0.5, dab);
        let v = read_scalar(&runner, "multiply", "result");
        assert!(
            (-100.0..=100.0).contains(&v),
            "value {v} outside [-100, 100] on dab {dab}",
        );
        if v < min {
            min = v;
        }
        if v > max {
            max = v;
        }
    }
    // We should see both halves of the range — at least one negative and
    // one positive sample across 32 dabs.
    assert!(
        min < 0.0,
        "expected at least one negative sample, min was {min}"
    );
    assert!(
        max > 0.0,
        "expected at least one positive sample, max was {max}"
    );
}

/// Radian-unit ports (`pen.drawing_angle → stamp.rotation`) are
/// unit-preserving identity wires — both speak radians, so the value
/// must pass through raw without any range remap. This is the regression
/// the broader [`rotation.rs`] integration test covers; this minimal
/// CPU-only test pins the contract at the runner level.
#[test]
fn radian_to_radian_wire_passes_through() {
    let registry = registry();
    let mut graph = Graph::new();

    let pen_reg = registry.get("pen_input").unwrap();
    let pen = graph.add_node("pen_input", pen_reg.ports.clone(), vec![]);

    // multiply.a with no natural_range (radians-style dest).
    let multiply_reg = registry.get("multiply").unwrap();
    let mut multiply_ports = multiply_reg.ports.clone();
    for p in multiply_ports.iter_mut() {
        if p.name == "a" {
            p.natural_range = None;
        }
    }
    let multiply = graph.add_node("multiply", multiply_ports, vec![]);

    graph
        .connect(
            PortRef {
                node: pen,
                port: "drawing_angle".into(),
            },
            PortRef {
                node: multiply,
                port: "a".into(),
            },
        )
        .unwrap();

    let mut runner =
        BrushGraphRunner::new(&graph, registry.as_map(), registry.evaluators()).unwrap();

    // drawing_angle defaults to 0 in PaintInformation. Set it explicitly
    // via a custom PaintInformation to a known radian value and confirm
    // multiply sees the same raw value (no [0, TAU] → [???] remap).
    let info = PaintInformation {
        drawing_angle: std::f32::consts::PI,
        ..Default::default()
    };
    runner.seed_sensors(&info, [0.0, 0.0, 0.0, 1.0], 42, 0);
    runner.clear_slots();
    runner.seed_sensors(&info, [0.0, 0.0, 0.0, 1.0], 42, 0);
    runner.execute_cpu();

    let v = read_scalar(&runner, "multiply", "result");
    assert!(
        (v - std::f32::consts::PI).abs() < 1e-5,
        "drawing_angle PI rad should pass through to rotation as PI rad, got {v}",
    );
}