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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
//! Brush graph management methods on DarklyEngine.
//!
//! Provides the API surface for the WASM bridge to query node types,
//! get/set the active brush graph, and compile graphs.
use super::{DarklyEngine, ReadbackContext};
use crate::brush::state::BrushState;
use crate::brush::wire::BrushWireType;
use crate::gpu::params::ParamValue;
use crate::nodegraph::Graph;
use crate::nodegraph::{NodeId, PortDir, PortRef, UnitType};
/// Panic message used by every `tool_session` BrushState lookup. The
/// session is seeded with `BrushState::new()` at engine construction;
/// `None` here would mean someone removed the entry, which is a bug.
const NO_BRUSH_STATE: &str = "BrushState registered at session init";
/// Classifies a brush-graph mutation by which preview consumers it
/// actually invalidates.
#[derive(Copy, Clone)]
enum ChangeKind {
/// Structural or non-scrub change: nodes, wires, params, exposed
/// flags, non-exposed port defaults, brush load/reset/clear. Bumps
/// both `brush_graph_version` and `brush_topology_version`.
Topology,
/// Exposed-port scrub on a port marked `persist_in_thumbnail` — its
/// value bleeds through to the dab thumbnail render, so both
/// version counters need to bump to invalidate both preview caches.
/// Used for orientation knobs like `shape.rotation`.
ThumbnailRelevantScrub,
/// User-facing exposed-port scrub on a port the editor preview
/// pipeline actually reads (size, opacity, hardness, …). Bumps only
/// `brush_graph_version` — the dab thumbnail render neutralises
/// scrubs via `reset_exposed_scrubs`, so its cache stays valid.
ScrubOnly,
/// Exposed-port scrub on a port the editor preview pipeline
/// ignores. Two declaration mechanisms route here:
/// - `PortDef::preview_value` — caller-side
/// `Graph::apply_preview_overrides` replaces the scrubbed value
/// with a preview-mode constant before rendering (used by
/// `paint.size`, `watercolor.size`, …).
/// - `PortDef::preview_irrelevant_scrub` — the preview pipeline
/// structurally ignores the port (used by `pen_input.stabilize`,
/// which the synthetic-stroke preview's hard-wired `PassThrough`
/// never reads).
///
/// Either way the rendered output cannot change in response to the
/// scrub, so neither cache needs to bump.
PreviewIrrelevantScrub,
}
impl DarklyEngine {
/// Return metadata for all registered brush node types.
///
/// Returns the bare nodegraph registration (ports, params, display
/// info) — the wrapper's pipeline metadata is engine-internal and the
/// frontend doesn't see it.
pub fn brush_node_types(&self) -> Vec<crate::nodegraph::NodeRegistration<BrushWireType>> {
let registry = crate::brush::registry();
registry.types().map(|r| r.node.clone()).collect()
}
/// Does the active brush graph's terminal honor erase mode?
///
/// True iff every terminal node in the active graph's registration
/// has `supports_erase = true`. Type-owned dispatch — there is no
/// central list of which terminals don't (smudge, liquify,
/// watercolor today); each module's `register()` declares its own
/// value.
///
/// Used by the brush-tool options bar to hide the erase button for
/// terminals where flipping `gpu.blend_mode` would do nothing.
pub fn active_brush_supports_erase(&self) -> bool {
let graph = self.active_brush_graph();
let registry = crate::brush::registry();
for node in graph.nodes().values() {
let Some(reg) = registry.get(&node.type_id) else {
continue;
};
if reg.node.is_terminal && !reg.node.supports_erase {
return false;
}
}
// No terminal, or every terminal supports erase → keep the
// toggle visible.
true
}
/// Return a clone of the default brush graph.
pub fn default_brush_graph(&self) -> Graph<BrushWireType> {
crate::brush::default_graph()
}
// `active_brush_graph()` and `brush_graph_version()` /
// `brush_topology_version()` live on `super::DarklyEngine` (see
// `engine/mod.rs`) — they pull from the shared brush session under
// a read lock. Same public API, different storage.
/// Validate a brush graph from JSON without setting it as active.
///
/// Returns `Ok(())` or an error string describing what's wrong.
pub fn validate_brush_graph(&self, json: &str) -> Result<(), String> {
crate::brush::validate_graph_json(json)
}
/// Compile a brush graph from JSON and set it as the active graph.
///
/// The next stroke will use this graph. Returns `Ok(())` on success
/// or an error string if the graph is invalid.
pub fn set_brush_graph(&mut self, json: &str) -> Result<(), String> {
// Validate by attempting compilation.
let _runner = crate::brush::compile_from_json(json)?;
// If compilation succeeded, store the deserialized graph.
let graph: Graph<BrushWireType> =
serde_json::from_str(json).map_err(|e| format!("JSON parse error: {e}"))?;
self.tool_session
.write()
.get_mut::<BrushState>()
.expect(NO_BRUSH_STATE)
.graph = graph;
self.snapshot_brush_defaults();
// Run the post-mutation pipeline so the brush preview mask (and any
// other graph-dependent state) refreshes from the new graph.
self.compile_active(ChangeKind::Topology)?;
Ok(())
}
/// Export the active brush graph as the human/AI-friendly YAML
/// format defined by [`crate::brush::portable::PortableBrush`].
/// Round-trippable through [`Self::set_brush_graph_yaml`].
pub fn active_brush_graph_yaml(&self) -> Result<String, String> {
let registry = crate::brush::registry();
let portable = crate::brush::portable::PortableBrush::from_graph_only(
&self.active_brush_graph(),
registry,
)?;
serde_yaml_ng::to_string(&portable).map_err(|e| format!("YAML serialize error: {e}"))
}
/// Replace the active brush graph from a YAML string in the
/// [`PortableBrush`](crate::brush::portable::PortableBrush) format.
/// Validates and compiles before swapping; on failure the previous
/// graph is untouched and an error string describes the problem.
pub fn set_brush_graph_yaml(&mut self, yaml: &str) -> Result<(), String> {
let portable: crate::brush::portable::PortableBrush =
serde_yaml_ng::from_str(yaml).map_err(|e| format!("YAML parse error: {e}"))?;
let registry = crate::brush::registry();
let graph = portable.into_graph(registry)?;
self.tool_session
.write()
.get_mut::<BrushState>()
.expect(NO_BRUSH_STATE)
.graph = graph;
self.snapshot_brush_defaults();
self.compile_active(ChangeKind::Topology)?;
Ok(())
}
/// Reset the active brush graph to the built-in default.
pub fn reset_brush_graph(&mut self) {
self.tool_session
.write()
.get_mut::<BrushState>()
.expect(NO_BRUSH_STATE)
.graph = crate::brush::default_graph();
self.snapshot_brush_defaults();
let _ = self.compile_active(ChangeKind::Topology);
}
/// Capture every input port's current default into the shared brush
/// state's `defaults` map. Called whenever the active graph is
/// replaced as a whole — brush load, reset, save — so that "reset to
/// default" returns to the loaded/saved baseline rather than the
/// node-type registration value. Not called on individual port edits;
/// that's the whole point.
pub(crate) fn snapshot_brush_defaults(&mut self) {
let mut tool = self.tool_session.write();
let brush = tool.get_mut::<BrushState>().expect(NO_BRUSH_STATE);
brush.defaults.clear();
// Re-borrow split: walking `brush.graph.nodes()` and inserting
// into `brush.defaults` are reads/writes of disjoint fields on
// `BrushState`, so the borrow checker permits both inside the
// loop with no separate snapshot.
for node in brush.graph.nodes().values() {
for port in &node.ports {
if port.dir == PortDir::Input {
brush
.defaults
.insert((node.id, port.name.clone()), port.default);
}
}
}
}
// --- Fine-grained graph commands ---
/// Re-render the brush preview into the overlay's preview mask using
/// fully-synthetic pen inputs. Fired on graph/param changes where no
/// real pen data is available — clears any hover history so the next
/// hover starts fresh (no bogus direction carried across a brush
/// swap, etc.).
pub fn regenerate_brush_cursor_preview(&mut self) {
self.last_cursor_preview_pose = None;
let dummy = crate::brush::paint_info::PaintInformation::cursor_preview_dummy();
self.regenerate_brush_cursor_preview_with_pen_internal(dummy);
}
/// Drop the remembered hover pose so the next
/// `regenerate_brush_cursor_preview_with_pen` starts a fresh hover with no
/// derived direction/motion/distance/speed. Call this on pointer-leave
/// and at the start of a stroke.
pub fn clear_brush_cursor_preview_pose(&mut self) {
self.last_cursor_preview_pose = None;
}
/// Re-render the brush preview using live hover data.
///
/// Pre-fills `pen`'s segment-derived sensors (drawing_angle, motion,
/// distance, speed) using the previous hover pose — the same helper
/// the stroke engine uses — so a compiled graph wiring any sensor
/// into any input sees the same values the upcoming stroke would.
///
/// The rest of `pen` (pos, pressure, tilts, rotation,
/// tangential_pressure, time) comes from the PointerEvent; tilt
/// magnitude/direction are derived from the reported tilts. The pose
/// is stored for the next call's derivation.
pub fn regenerate_brush_cursor_preview_with_pen(
&mut self,
mut pen: crate::brush::paint_info::PaintInformation,
) {
// Chord length between the previous and current hover positions.
// Chord rather than Catmull-Rom arc length — there is no spline
// through a single sample.
let segment_length = match &self.last_cursor_preview_pose {
Some(prev) => {
let dx = pen.pos[0] - prev.pos[0];
let dy = pen.pos[1] - prev.pos[1];
(dx * dx + dy * dy).sqrt()
}
None => 0.0,
};
pen.derive_sensors(self.last_cursor_preview_pose.as_ref(), segment_length);
self.last_cursor_preview_pose = Some(pen);
self.regenerate_brush_cursor_preview_with_pen_internal(pen);
}
/// Shared render body — no pose tracking, no sensor derivation.
/// `pen` must already be fully populated by the caller.
pub(crate) fn regenerate_brush_cursor_preview_with_pen_internal(
&mut self,
pen: crate::brush::paint_info::PaintInformation,
) {
use crate::brush::gpu_context::{
BrushGpuContext, BrushPerfCounters, CursorPreviewState, DabBatch,
};
// Compile under a read guard; drop the guard before any GPU
// work to keep the critical section narrow. The guard is held
// only for the synchronous compile_graph call.
let mut runner = {
let tool = self.tool_session.read();
let brush = tool.get::<BrushState>().expect(NO_BRUSH_STATE);
match crate::brush::compile_graph(&brush.graph) {
Ok(r) => r,
Err(_) => {
drop(tool);
self.compositor
.tool_overlay_mut()
.clear_cursor_preview_mask();
self.compositor.mark_needs_present();
self.brush_cursor_preview_info = None;
return;
}
}
};
// Always dispatch `render_preview` — individual terminals decide
// whether they produce output this frame. A graph with no
// compiled-terminal hook fires nothing and `brush_cursor_preview_info`
// stays None; the four compiled terminals each fire their
// hook and publish placement info. The post-run
// `info.is_some()` check below routes both outcomes.
// Split-borrow the compositor so we can hold a mutable handle
// on `tool_overlay` (for the terminal's `ensure_cursor_preview_mask`
// grow) alongside an immutable borrow of `selection_state` for
// the brush bind group. The two fields are disjoint;
// `Compositor::split_overlay_and_selection` documents the
// pattern.
let (overlay, selection) = self.compositor.split_overlay_and_selection();
let has_selection = selection.is_some();
let sel_bg = if has_selection {
selection
.map(|s| s.selection_bind_group())
.unwrap_or(&self.brush_pipelines.default_selection_bind_group)
} else {
&self.brush_pipelines.default_selection_bind_group
};
let encoder = self
.gpu
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("brush-preview-regen"),
});
let mut gpu_ctx = BrushGpuContext {
encoder,
device: &self.gpu.device,
queue: &self.gpu.queue,
pipelines: &self.brush_pipelines,
selection_bind_group: sel_bg,
canvas_width: 0,
canvas_height: 0,
canvas_origin: [0, 0],
blend_mode: 0,
view_rotation: self.view_params.rotation,
perf: BrushPerfCounters::default(),
// The preview pipeline doesn't touch the stroke scratch / paint
// target — the terminal's `render_preview` writes to the
// preview mask through `mask_overlay` instead. No
// `StrokeResources` is supplied; any accidental scratch /
// paint-target access will see `None` and either early-out or
// panic, exposing the bug.
stroke: None,
// Tests pre-allocate `mask_view`; the engine path grows the
// mask on demand via `mask_overlay`.
preview: Some(CursorPreviewState {
mask_view: None,
mask_size: (0, 0),
mask_overlay: Some(overlay),
info: None,
}),
dab_batch: DabBatch::default(),
};
self.brush_pipelines.reset_uniform_rings();
runner.clear_slots();
runner.seed_sensors(&pen, [1.0, 1.0, 1.0, 1.0], 0, 0);
runner.execute_cpu();
runner.render_cursor_preview_pipeline(&mut gpu_ctx);
let info = gpu_ctx.preview.as_ref().and_then(|p| p.info);
let command_buf = gpu_ctx.encoder.finish();
self.gpu.queue.submit([command_buf]);
if info.is_some() {
self.compositor
.tool_overlay_mut()
.use_cursor_preview_mask_as_mask();
self.request_brush_cursor_preview_scale_readback();
} else {
self.compositor
.tool_overlay_mut()
.clear_cursor_preview_mask();
}
self.compositor.mark_needs_present();
self.brush_cursor_preview_info = info;
}
/// Queue a readback of the freshly-rendered preview-mask so the
/// completion handler can normalize the cursor overlay's coverage
/// scale to the bake's target mean. Skips when:
/// - the current topology matches the one we already requested a
/// readback for (scale is a property of the graph shape, not
/// the cursor pose);
/// - another `BrushCursorPreviewScale` is already in flight;
/// - the preview-mask texture hasn't been allocated yet.
fn request_brush_cursor_preview_scale_readback(&mut self) {
let current_topology = self.brush_topology_version();
if self.last_requested_cursor_scale_topology_version == current_topology {
return;
}
if self
.readbacks
.any(|c| matches!(c, ReadbackContext::BrushCursorPreviewScale { .. }))
{
return;
}
let overlay = self.compositor.tool_overlay_mut();
let (width, height) = overlay.cursor_preview_mask_size();
if width == 0 || height == 0 {
return;
}
let Some(texture) = overlay.cursor_preview_mask_texture() else {
return;
};
let mut encoder = self
.gpu
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("brush-cursor-preview-scale-readback"),
});
let request = crate::gpu::readback::request_readback(
&self.gpu.device,
&mut encoder,
texture,
wgpu::TextureFormat::Rgba8Unorm,
crate::coord::LayerRect::from_xywh(0, 0, width, height),
);
self.gpu.queue.submit([encoder.finish()]);
self.readbacks.submit(
request,
ReadbackContext::BrushCursorPreviewScale {
topology_version: current_topology,
width,
height,
},
);
self.last_requested_cursor_scale_topology_version = current_topology;
}
/// Read-only snapshot of the current brush preview info, for the
/// frontend to place the hover overlay primitive.
pub fn brush_cursor_preview_info(&self) -> Option<crate::brush::eval::BrushCursorPreviewInfo> {
self.brush_cursor_preview_info
}
/// Compile the active graph in-place.
///
/// `kind` selects which version counters to bump:
/// - [`ChangeKind::Topology`] bumps both the graph version (editor /
/// hover preview) and the topology version (dab thumbnail).
/// - [`ChangeKind::ScrubOnly`] bumps only the graph version. The dab
/// thumbnail render neutralises exposed-port scrubs via
/// [`crate::brush::reset_exposed_scrubs`], so a scrub change can't
/// change its rendered output — no point invalidating its cache.
/// - [`ChangeKind::PreviewIrrelevantScrub`] bumps neither. The
/// scrubbed port is overridden by
/// [`crate::nodegraph::Graph::apply_preview_overrides`] before
/// every editor-preview render, so its rendered output is
/// independent of the user's port value — invalidating the cache
/// would just cause a wasted full-stroke re-render.
///
/// Returns Ok on success or an error string.
fn compile_active(&mut self, kind: ChangeKind) -> Result<(), String> {
{
let tool = self.tool_session.read();
let brush = tool.get::<BrushState>().expect(NO_BRUSH_STATE);
crate::brush::compile_graph(&brush.graph)?;
}
// Bump version counters per the change classification — see the
// `ChangeKind` doc above for the full rule. PreviewIrrelevantScrub
// bumps nothing: the rendered preview output can't have changed.
match kind {
ChangeKind::Topology | ChangeKind::ThumbnailRelevantScrub => {
self.bump_brush_topology_version()
}
ChangeKind::ScrubOnly => self.bump_brush_graph_version(),
ChangeKind::PreviewIrrelevantScrub => {}
}
// Refresh the brush preview overlay now that the graph is compiled —
// size, rotation, and tip changes all land here.
self.regenerate_brush_cursor_preview();
Ok(())
}
/// Set the theme colors used by the stroke preview, the dab preview,
/// and the library thumbnail bake. (The cursor preview composes
/// over the live canvas, not a theme bg, so it ignores this.) All
/// three bake paths share one palette so they visually match each
/// other across the picker grid and the brush editor.
///
/// Invalidates the cached stroke preview, the active-dab preview,
/// and every per-brush PNG thumbnail in the library so the next
/// picker refresh re-bakes against the new palette.
pub fn set_preview_theme(&mut self, fg: [f32; 4], bg: [f32; 4]) {
if self.preview_theme_fg == fg && self.preview_theme_bg == bg {
return;
}
self.preview_theme_fg = fg;
self.preview_theme_bg = bg;
self.invalidate_brush_stroke_preview();
// Drop baked PNG thumbnails so picker tiles re-bake on demand.
// The frontend's rAF poll handles the empty→bake→present flow.
self.brush_library.clear_thumbnails();
}
/// Render a full-stroke brush editor preview and return the most recent
/// cached PNG bytes synchronously. The pixels update on a later frame
/// once the async readback completes — same shape as
/// `brush_active_dab_preview`. Always framed to `BRUSH_THUMBNAIL_SIZE`;
/// the frontend scales the result via CSS to whatever display size it
/// needs.
///
/// Uses the theme colors stored via `set_preview_theme`, not the user's
/// active paint color — keeps the editor preview visually consistent
/// with the brush picker's brush thumbnails.
pub fn brush_stroke_preview(&mut self) -> Vec<u8> {
// Guard against painting while a real stroke is in flight — the
// preview shares `dab_pool` and `brush_pipelines` with the engine,
// and running mid-stroke would step on acquired handles and
// uniform rings.
let in_stroke = self.brush_stroke_engine.is_some();
// Caller's frontend treats an empty Vec as "no fresh bytes
// available" and skips the image update — preserving whatever was
// last shown. A zero-filled buffer would *also* parse cleanly and
// render as a transparent image, wiping the visible preview.
let cached = self.brush_stroke_preview_cache.clone();
// Skip work when nothing has changed and the cache is good. Also
// skip if a real stroke is in progress — return the most recent
// cached bytes so the UI stays responsive without clobbering the
// stroke's GPU state.
let current_graph_version = self.brush_graph_version();
let nothing_to_do = in_stroke
|| (self.last_rendered_stroke_preview_version == current_graph_version
&& self.brush_stroke_preview_cache.is_some());
if nothing_to_do {
return cached.unwrap_or_default();
}
// Don't queue a second readback on top of an in-flight one — it
// would race with whichever lands first and the stale result
// could overwrite the fresh one.
let already_pending = self
.readbacks
.any(|c| matches!(c, ReadbackContext::BrushStrokePreview { .. }));
if already_pending {
return cached.unwrap_or_default();
}
let fg = self.preview_theme_fg;
let bg = self.preview_theme_bg;
// Neutralize ports flagged `preview_value` (paint.size,
// watercolor.size, …) on a clone so the stroke preview matches the
// brush picker's tile-shape thumbnail: size-invariant, fits
// the fixed render canvas regardless of the user's working
// scrubs. Same generalization the dab path relies on via
// `reset_exposed_scrubs`; both previews show brush identity,
// not momentary parameter state. Per-node knowledge about
// what to neutralize lives on the port registrations — this
// pipeline doesn't introspect node types.
let mut graph = self.active_brush_graph();
graph.apply_preview_overrides();
let (rw, rh) = super::brush_library::BRUSH_STROKE_RENDER_SIZE;
let path = crate::brush::preview_renderer::synthesize_stroke_path(
rw as f32,
rh as f32,
30,
super::brush_library::BRUSH_STROKE_PATH_INSET,
);
self.render_preview_and_request_readback(
&graph,
&path,
rw,
rh,
fg,
bg,
ReadbackContext::BrushStrokePreview {
width: rw,
height: rh,
graph_version: current_graph_version,
},
);
self.last_rendered_stroke_preview_version = current_graph_version;
cached.unwrap_or_default()
}
/// Invalidate any cached editor preview — call when the theme colors
/// change so the next `brush_stroke_preview` request re-renders with
/// the new palette instead of returning the stale cached pixels.
/// Also drops the active-dab preview cache so the BrushBar trigger
/// thumbnail and the picker's active-brush strip refresh on the same
/// signal.
pub fn invalidate_brush_stroke_preview(&mut self) {
self.brush_stroke_preview_cache = None;
self.active_dab_preview_cache = None;
// Theme changes alter rendered colors → both editor preview and
// dab thumbnail need to re-render and discard any in-flight
// readbacks. Bump both versions.
self.bump_brush_topology_version();
}
/// Render a single-dab preview of the active brush and return the
/// most recent cached PNG bytes synchronously. Pixels update on a
/// later frame once the async readback completes — same shape as
/// `brush_stroke_preview` and `layer_thumbnail`. Used by the
/// BrushBar trigger button and the picker's active-brush strip.
///
/// Renders at the same fixed `BRUSH_DAB_RENDER_SIZE` the baked
/// thumbnail path uses, and runs the result through the same
/// `frame_dab_thumbnail` framer — so the bytes returned here are
/// byte-identical to a `brush_dab_thumbnail(active_name)` call.
/// The frontend scales the resulting PNG via CSS to whatever
/// display size it needs.
pub fn brush_active_dab_preview(&mut self) -> Vec<u8> {
// Guard against painting while a real stroke is in flight — the
// preview shares `dab_pool` and `brush_pipelines` with the engine,
// and running mid-stroke would step on acquired handles and
// uniform rings.
let in_stroke = self.brush_stroke_engine.is_some();
// See `brush_stroke_preview` for why we return an empty Vec rather
// than a zero-filled one when no cache is available — frontends
// treat empty as "no fresh bytes" and preserve the last successful
// render, while a zero buffer would parse as a transparent image
// and visibly wipe whatever was on screen.
let cached = self.active_dab_preview_cache.clone();
// Skip work when nothing has changed and the cache is good. Also
// skip while a real stroke is in progress — return the most recent
// cached bytes so the UI stays responsive without clobbering the
// stroke's GPU state.
let current_topology = self.brush_topology_version();
let nothing_to_do = in_stroke
|| (self.last_rendered_dab_topology_version == current_topology
&& self.active_dab_preview_cache.is_some());
if nothing_to_do {
return cached.unwrap_or_default();
}
// Don't queue a second readback on top of an in-flight one.
let already_pending = self
.readbacks
.any(|c| matches!(c, ReadbackContext::ActiveBrushDab { .. }));
if already_pending {
return cached.unwrap_or_default();
}
let fg = self.preview_theme_fg;
let bg = self.preview_theme_bg;
// Reset every exposed scrub (size, opacity, hardness, …) to its
// registration default before rendering. The dab thumbnail
// represents the brush's identity (shape, texture, dynamics);
// user-facing scrubs belong in the brush bar, not the icon.
let mut graph = self.active_brush_graph();
crate::brush::reset_exposed_scrubs(&mut graph);
let (rw, rh) = super::brush_library::BRUSH_DAB_RENDER_SIZE;
let path = crate::brush::preview_renderer::synthesize_dab_path(rw as f32, rh as f32);
self.render_preview_and_request_readback(
&graph,
&path,
rw,
rh,
fg,
bg,
ReadbackContext::ActiveBrushDab {
topology_version: current_topology,
},
);
self.last_rendered_dab_topology_version = current_topology;
cached.unwrap_or_default()
}
/// Per-node preview thumbnail. Synchronous PNG render — the caller
/// (brush-builder NodePreview component) treats an empty Vec as
/// "no preview" and shows the placeholder. Adding a new node type's
/// preview means a new arm in the type-id match below; nodes
/// without a preview implementation return empty.
pub fn brush_node_preview(&mut self, node_id: u64) -> Vec<u8> {
let tool = self.tool_session.read();
let brush = tool.get::<BrushState>().expect(NO_BRUSH_STATE);
let Some(node) = brush.graph.nodes().get(&NodeId(node_id)) else {
return Vec::new();
};
match node.type_id.as_str() {
crate::brush::nodes::noise::TYPE_ID => {
crate::brush::nodes::noise::render_preview_png(&node.params, 96)
}
_ => Vec::new(),
}
}
/// Shared helper: render a preview path into the preview renderer's
/// texture, then encode an async readback tagged with `context`. The
/// caller decides what to do with the bytes when they arrive. The
/// graph is taken explicitly so callers can render thumbnails for
/// library brushes without touching the active graph; the path lets
/// callers choose between the S-curve stroke and a single-dab preview.
pub(crate) fn render_preview_and_request_readback(
&mut self,
graph: &Graph<BrushWireType>,
path: &[crate::brush::paint_info::PaintInformation],
width: u32,
height: u32,
fg: [f32; 4],
bg: [f32; 4],
context: ReadbackContext,
) {
let Some(texture) = self.brush_stroke_preview_renderer.render_stroke(
&self.gpu.device,
&self.gpu.queue,
&self.brush_pipelines,
graph,
path,
fg,
bg,
width,
height,
) else {
return;
};
// Encode the readback manually (not via `gpu.encode`) so the
// borrow of `self.brush_stroke_preview_renderer` that produced
// `texture` coexists with borrows of `self.gpu` and
// `self.readbacks` — they're disjoint fields of `self`.
let mut encoder = self
.gpu
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("brush-editor-preview-readback"),
});
let request = crate::gpu::readback::request_readback(
&self.gpu.device,
&mut encoder,
texture,
wgpu::TextureFormat::Rgba8Unorm,
crate::coord::LayerRect::from_xywh(0, 0, width, height),
);
self.gpu.queue.submit([encoder.finish()]);
self.readbacks.submit(request, context);
}
/// Serialize the active graph as JSON.
fn active_graph_json(&self) -> String {
let tool = self.tool_session.read();
let brush = tool.get::<BrushState>().expect(NO_BRUSH_STATE);
serde_json::to_string(&brush.graph).unwrap_or_else(|_| "null".into())
}
/// Apply `mutation` to a clone of the active graph, compile the
/// clone to validate, then commit it as the new active graph and
/// run the post-mutation pipeline. On any failure the active
/// graph is unchanged — this is what makes the mutators atomic.
/// Returns the updated graph JSON on success.
fn try_mutate<F>(&mut self, kind: ChangeKind, mutation: F) -> Result<String, String>
where
F: FnOnce(&mut Graph<BrushWireType>) -> Result<(), String>,
{
let mut candidate = self.active_brush_graph();
mutation(&mut candidate)?;
// Validate by compiling — surfaces e.g. missing-WGSL upstream
// nodes before we commit anything visible.
crate::brush::compile_graph(&candidate)?;
self.tool_session
.write()
.get_mut::<BrushState>()
.expect(NO_BRUSH_STATE)
.graph = candidate;
// compile_active recompiles (slightly redundant with the
// validation above) but it owns the version-bump + preview
// regen rules — keep them in one place.
self.compile_active(kind)?;
Ok(self.active_graph_json())
}
/// Add a node to the active graph and compile.
/// Returns the updated graph JSON on success.
pub fn brush_graph_add_node(&mut self, type_id: &str) -> Result<String, String> {
let registry = crate::brush::registry();
let reg = registry
.get(type_id)
.ok_or_else(|| format!("unknown node type: {type_id}"))?;
let params = reg
.params
.iter()
.map(|p| p.default_value())
.collect::<Vec<_>>();
let ports = reg.ports.clone();
let type_id = type_id.to_string();
self.try_mutate(ChangeKind::Topology, |g| {
g.add_node(type_id, ports, params);
Ok(())
})
}
/// Remove a node from the active graph and compile.
pub fn brush_graph_remove_node(&mut self, node_id: u64) -> Result<String, String> {
self.try_mutate(ChangeKind::Topology, |g| {
g.remove_node(NodeId(node_id)).map_err(|e| format!("{e}"))
})
}
/// Connect two ports in the active graph and compile.
pub fn brush_graph_connect(
&mut self,
from_node: u64,
from_port: &str,
to_node: u64,
to_port: &str,
) -> Result<String, String> {
let from_ref = PortRef {
node: NodeId(from_node),
port: from_port.into(),
};
let to_ref = PortRef {
node: NodeId(to_node),
port: to_port.into(),
};
self.try_mutate(ChangeKind::Topology, |g| {
// Remove any existing connection to this input first.
g.connections.retain(|c| c.to != to_ref);
g.connect(from_ref, to_ref).map_err(|e| format!("{e}"))
})
}
/// Disconnect a specific wire in the active graph and compile.
pub fn brush_graph_disconnect(
&mut self,
from_node: u64,
from_port: &str,
to_node: u64,
to_port: &str,
) -> Result<String, String> {
let from_ref = PortRef {
node: NodeId(from_node),
port: from_port.into(),
};
let to_ref = PortRef {
node: NodeId(to_node),
port: to_port.into(),
};
self.try_mutate(ChangeKind::Topology, |g| {
g.disconnect(&from_ref, &to_ref);
Ok(())
})
}
/// Update a parameter on a node and compile.
pub fn brush_graph_set_param(
&mut self,
node_id: u64,
param_index: usize,
value: ParamValue,
) -> Result<String, String> {
self.try_mutate(ChangeKind::Topology, |g| {
g.set_param(NodeId(node_id), param_index, value)
.map_err(|e| format!("{e}"))
})
}
/// Update a port's default value and compile.
pub fn brush_graph_set_port_default(
&mut self,
node_id: u64,
port_name: &str,
value: f32,
) -> Result<String, String> {
self.try_mutate(ChangeKind::Topology, |g| {
g.set_port_default(NodeId(node_id), port_name, value)
.map_err(|e| format!("{e}"))
})
}
/// Compute auto-layout positions for the active brush graph.
/// `sizes` maps `NodeId` → `[width, height]` measured from the DOM.
/// Returns the layout map directly — positions are a UI-only concern
/// and are not stored on the graph.
pub fn brush_graph_auto_layout(
&self,
sizes: &std::collections::HashMap<NodeId, [f32; 2]>,
) -> crate::nodegraph::NodeLayout {
self.tool_session
.read()
.get::<BrushState>()
.expect(NO_BRUSH_STATE)
.graph
.auto_layout_with_sizes(sizes)
}
/// Upload an RGBA8 image and associate it with a resource name.
///
/// Image-stamp brushes are unsupported — `stamp` only accepts
/// AlphaMask application, which compiles inline without sampling
/// an RGBA tip texture. The entry point remains so the frontend's
/// upload UI doesn't fault on a missing symbol; it returns an
/// error rather than silently dropping the bytes.
pub fn brush_upload_image(
&mut self,
_resource_name: &str,
_width: u32,
_height: u32,
_rgba: &[u8],
) -> Result<(), String> {
Err("image-stamp brushes are unsupported — stamp accepts \
AlphaMask only"
.to_string())
}
/// Set the composite blend mode: 0 = source-over (paint), 1 = destination-out (erase).
pub fn set_brush_blend_mode(&mut self, mode: u32) {
self.brush_blend_mode = mode;
}
/// Return info about every brush-bar entry in the active brush graph,
/// in the dict's insertion order (which is the user-facing display
/// order — the brush-bar node lets the author drag-reorder).
///
/// Entries that reference a node/port no longer present, or whose
/// target port has an incoming connection (the user can't scrub a
/// wire-driven value), are skipped silently.
pub fn brush_exposed_ports(&self) -> Vec<ExposedPortInfo> {
let registry = crate::brush::registry();
let tool = self.tool_session.read();
let brush = tool.get::<BrushState>().expect(NO_BRUSH_STATE);
let mut result: Vec<ExposedPortInfo> = Vec::with_capacity(brush.graph.exposed_ports.len());
for (key, meta) in &brush.graph.exposed_ports {
// Key shape: "<node_id>.<port_name>".
let Some((nid_str, port_name)) = key.split_once('.') else {
continue;
};
let Ok(node_id_raw) = nid_str.parse::<u64>() else {
continue;
};
let node_id = NodeId(node_id_raw);
let Some(node) = brush.graph.nodes().get(&node_id) else {
continue;
};
let Some(port) = node
.ports
.iter()
.find(|p| p.name == port_name && p.dir == PortDir::Input)
else {
continue;
};
// A connected input is driven by its wire, not the user.
if brush
.graph
.connections
.iter()
.any(|c| c.to.node == node_id && c.to.port == port_name)
{
continue;
}
let reg = registry.get(&node.type_id);
let reg_port = reg.and_then(|r| {
r.ports
.iter()
.find(|rp| rp.name == port.name && rp.dir == port.dir)
});
// Build the type-specific payload. Wire types without a
// toolbar widget (Int/Vec2/Vec4) are skipped — the entry
// stays in the dict but doesn't render until a widget exists.
let data = match port.wire_type {
BrushWireType::Scalar => {
let unit_type = reg_port.map_or(port.unit_type, |rp| rp.unit_type);
let reset_default = brush
.defaults
.get(&(node_id, port_name.to_string()))
.copied()
.unwrap_or_else(|| reg_port.map(|rp| rp.default).unwrap_or(port.default));
ExposedValue::Scalar {
value: unit_type.to_display(port.default),
min: unit_type.to_display(port.min),
max: unit_type.to_display(port.max),
default: unit_type.to_display(reset_default),
unit_type,
}
}
BrushWireType::Bool => ExposedValue::Bool {
value: port.default >= 0.5,
},
_ => continue,
};
// Brush-bar entry meta wins; fall back to registration label /
// description / icon, then to the port name.
let label = if !meta.label.is_empty() {
meta.label.clone()
} else {
reg_port
.map(|rp| &rp.label)
.filter(|l| !l.is_empty())
.cloned()
.unwrap_or_else(|| port_name.to_string())
};
let icon = if !meta.icon.is_empty() {
meta.icon.clone()
} else {
reg_port.map_or_else(String::new, |rp| rp.icon.clone())
};
let description = if !meta.description.is_empty() {
meta.description.clone()
} else {
reg_port.map_or_else(String::new, |rp| rp.description.clone())
};
result.push(ExposedPortInfo {
key: key.clone(),
node_id: node_id.0,
port_name: port_name.to_string(),
label,
icon,
description,
node_display_name: reg.map(|r| r.display_name).unwrap_or("").to_string(),
data,
});
}
result
}
/// Set an exposed port's value from display-space, converting to
/// port-space via the port's UnitType. Compiles afterward.
pub fn brush_set_exposed_port(
&mut self,
node_id: u64,
port_name: &str,
display_value: f32,
) -> Result<String, String> {
let nid = NodeId(node_id);
// Snapshot the node's type_id under a brief read guard so the
// registry lookup below doesn't have to re-acquire the lock.
// All later mutation happens through a fresh write guard.
let type_id = {
let tool = self.tool_session.read();
let brush = tool.get::<BrushState>().expect(NO_BRUSH_STATE);
match brush.graph.nodes().get(&nid) {
Some(node) => node.type_id.clone(),
None => return Err(format!("node {node_id} not found")),
}
};
// Look up UnitType + preview_value + persist_in_thumbnail from
// the registration. One port lookup pays for all three flags;
// they determine whether this scrub affects the editor preview
// and/or the dab thumbnail (see `ChangeKind` docs).
let registry = crate::brush::registry();
let port_meta = registry.get(&type_id).and_then(|r| {
r.ports
.iter()
.find(|rp| rp.name == port_name && rp.dir == PortDir::Input)
});
let unit_type = port_meta.map_or(UnitType::default(), |rp| rp.unit_type);
let preview_irrelevant =
port_meta.is_some_and(|rp| rp.preview_value.is_some() || rp.preview_irrelevant_scrub);
let thumbnail_relevant = port_meta.is_some_and(|rp| rp.persist_in_thumbnail);
let port_value = unit_type.from_display(display_value);
let kind = if preview_irrelevant {
ChangeKind::PreviewIrrelevantScrub
} else if thumbnail_relevant {
ChangeKind::ThumbnailRelevantScrub
} else {
ChangeKind::ScrubOnly
};
self.try_mutate(kind, |g| {
g.set_port_default(nid, port_name, port_value)
.map_err(|e| format!("{e}"))
})
}
/// Add a brush-bar entry. Idempotent. Bumps the topology version so
/// the frontend treats the change as structural and clears the active
/// preset name. No recompile — exposure doesn't affect render output.
pub fn brush_graph_expose_port(
&mut self,
node_id: u64,
port_name: &str,
) -> Result<String, String> {
self.tool_session
.write()
.get_mut::<BrushState>()
.expect(NO_BRUSH_STATE)
.graph
.expose_port(NodeId(node_id), port_name)
.map_err(|e| format!("{e}"))?;
self.bump_brush_topology_version();
Ok(self.active_graph_json())
}
/// Remove a brush-bar entry. Idempotent (missing entries aren't an
/// error). Bumps the topology version so the frontend clears the
/// active preset name.
pub fn brush_graph_unexpose_port(
&mut self,
node_id: u64,
port_name: &str,
) -> Result<String, String> {
self.tool_session
.write()
.get_mut::<BrushState>()
.expect(NO_BRUSH_STATE)
.graph
.unexpose_port(NodeId(node_id), port_name);
self.bump_brush_topology_version();
Ok(self.active_graph_json())
}
/// Overwrite the meta (label / description / icon) on a brush-bar
/// entry — single batched call so the brush-bar modal hits the engine
/// once. Icon validation lives in `Graph::set_exposed_port_meta`.
pub fn brush_graph_set_exposed_port_meta(
&mut self,
key: &str,
label: String,
description: String,
icon: String,
) -> Result<String, String> {
self.tool_session
.write()
.get_mut::<BrushState>()
.expect(NO_BRUSH_STATE)
.graph
.set_exposed_port_meta(key, label, description, icon)
.map_err(|e| format!("{e}"))?;
self.bump_brush_topology_version();
Ok(self.active_graph_json())
}
/// Move a brush-bar entry to a target index. Backs the drag-reorder
/// UX in the brush-bar node.
pub fn brush_graph_reorder_exposed_port(
&mut self,
key: &str,
new_index: u32,
) -> Result<String, String> {
self.tool_session
.write()
.get_mut::<BrushState>()
.expect(NO_BRUSH_STATE)
.graph
.reorder_exposed_port(key, new_index as usize)
.map_err(|e| format!("{e}"))?;
self.bump_brush_topology_version();
Ok(self.active_graph_json())
}
}
// ── Exposed port types ──────────────────────────────────────────────
/// Type-specific value data for an exposed port.
///
/// Tagged enum so the frontend can switch on `kind` to render the
/// appropriate widget (scrub slider, toggle, color picker, etc.).
#[derive(Clone, Debug, serde::Serialize)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum ExposedValue {
/// Float scrub slider with unit conversion.
Scalar {
/// Current value in display-space.
value: f32,
/// Display-space minimum.
min: f32,
/// Display-space maximum.
max: f32,
/// Display-space default — what double-click reset returns to.
/// Sourced from the node-type registration, not the loaded brush.
default: f32,
/// Unit type for formatting and conversion.
#[serde(rename = "unitType")]
unit_type: UnitType,
},
/// Boolean toggle. Currently emitted by the Switch node's `select`
/// port; any other Bool input port marked `exposed` works too.
Bool {
/// Current value.
value: bool,
},
// Future variants:
// Int { value: i32, min: i32, max: i32 },
// Color { value: [f32; 4] },
}
/// Info about an exposed port — sent to the frontend for the BrushBar.
#[derive(Clone, Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ExposedPortInfo {
/// `"<node_id>.<port_name>"` — the same string used to address the
/// entry in `Graph::exposed_ports`. Frontend passes it back to
/// `set_exposed_port_meta` / `reorder_exposed_port` without having
/// to reconstruct the format.
pub key: String,
pub node_id: u64,
pub port_name: String,
pub label: String,
pub icon: String,
pub description: String,
pub node_display_name: String,
pub data: ExposedValue,
}