ssplayer_wgpu/mask.rs
1//! Mask planning (stencil) — a Rust port of the WebGL `MaskPlanner`.
2//!
3//! SpriteStudio's "mask" and "clipping mask" both resolve to the same stencil
4//! mechanism. The
5//! runtime only emits `DrawBatchKind::Mask` batches, `mask_indices` and the
6//! per-batch `FLAG_MASK_INFLUENCE` bit; rasterising coverage into a stencil
7//! buffer is the Player's job. This module classifies, per frame, which parts
8//! write coverage (writers) and how, so [`crate::player`] can drive the
9//! pre-write + scoped-replay interleave that a single hardware stencil needs.
10//!
11//! Data sources:
12//! * **Static per-part flags** ([`PartMaskFlags`]) come from ssab `PartData` and
13//! are read once at node-build time.
14//! * **Per-frame values** (`PartState.mask` / `hide`, draw order, batches) come from
15//! `FrameData` and are re-read every frame here.
16
17use crate::frame::{FrameView, SHAPE_VERTICES_STRIDE};
18use ssruntime::runtime::framedata::ss::runtime::{DrawBatchKind, FrameData, root_as_frame_data, root_as_frame_data_unchecked};
19
20/// Writers one coverage layer tells apart: a bit apiece in R, G and B.
21pub const COVERAGE_LAYER_BITS: usize = 24;
22
23/// Upper bound on writers per frame, across one player's whole instance tree —
24/// and so on any one animation in it too.
25///
26/// Every writer of the tree masks from one place — a clipping mask deep inside an
27/// instance keeps clipping its callers — so they are counted together, and a
28/// character built from a few instances with a handful of masks each passes 24
29/// quickly. The coverage backend spends one more layer per
30/// [`COVERAGE_LAYER_BITS`]; the stencil backend could take more but stops here
31/// too, so the two backends draw the same thing, and so does every other Player
32/// holding the same limit. Past this the rest are ignored.
33pub const MAX_MASK_WRITERS: usize = 96;
34
35/// Stencil test mode baked into a content pipeline. Selected per masked part
36/// from the target's `visible_inside_mask` polarity.
37///
38/// Hashable because it is half of the renderer's pipeline cache key.
39#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
40pub enum StencilTest {
41 /// Not masked — compare `Always` (draw everywhere, ignore stencil).
42 None,
43 /// `visible_inside_mask == true`: draw where coverage is set (`NotEqual`, 0).
44 Inside,
45 /// `visible_inside_mask == false`: draw where coverage is clear (`Equal`, 0).
46 Outside,
47}
48
49/// Stencil write operation, resolved by the caller from a writer's op and
50/// whether it is being added or removed from coverage. Increment
51/// pairs with decrement (its inverse); invert is its own inverse.
52///
53/// Hashable because it keys a mask-write pipeline in the renderer cache.
54#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
55pub enum MaskOp {
56 /// `stencil + 1` (increment, clamped).
57 Incr,
58 /// `stencil - 1` (decrement, clamped) — undoes a prior increment.
59 Decr,
60 /// `~stencil` (bitwise invert) — its own inverse.
61 Invert,
62}
63
64/// Geometry a part contributes as a mask writer. Text/Nines are not yet
65/// rendered, so they cannot write coverage yet.
66#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
67pub enum GeomKind {
68 /// Sprite quad (Normal parts and `PartTypeMask` cells).
69 Quad,
70 /// Skinned mesh.
71 Mesh,
72 /// Shape part (rect/circle/…), rasterised from its runtime shape vertices as
73 /// a triangle fan.
74 Shape,
75 /// Not renderable as a writer yet (Text/Nines/Null/etc.).
76 #[default]
77 Unsupported,
78}
79
80/// Static, per-part mask flags read once from ssab `PartData`.
81///
82/// `mask_influence` is deliberately dual-purpose: for a writer
83/// it is the stencil OP (0 = increment, 1 = invert); for a drawn target it is
84/// the mask opt-in. Clipping parts (writer *and* target) use the same value for
85/// both roles.
86#[derive(Clone, Copy, Debug, Default)]
87pub struct PartMaskFlags {
88 /// Part type is `PartTypeMask` — always a pure (colourless) mask.
89 pub is_mask_part: bool,
90 /// A drawn part that also writes coverage (a clipping writer).
91 pub mask_write: bool,
92 /// Dual meaning: OP for writers, mask opt-in for targets.
93 pub mask_influence: bool,
94 /// Polarity: draw inside (true) or outside (false) the coverage.
95 pub visible_inside_mask: bool,
96 /// Shape/Text/Nines promoted to a pure mask.
97 pub draw_as_mask: bool,
98 /// Geometry this part builds when it writes coverage.
99 pub geom: GeomKind,
100}
101
102impl PartMaskFlags {
103 /// A pure (colourless) mask writer.
104 pub fn pure_mask(&self) -> bool {
105 self.is_mask_part || self.draw_as_mask
106 }
107
108 /// Writes coverage into the stencil (pure mask or clipping).
109 pub fn is_writer(&self) -> bool {
110 self.pure_mask() || self.mask_write
111 }
112
113 /// A clipping writer: draws its own colour *and* writes coverage.
114 pub fn is_clipping(&self) -> bool {
115 self.mask_write && !self.pure_mask()
116 }
117
118 /// Stencil test to apply to this part when it is a masked target.
119 pub fn polarity(&self) -> StencilTest {
120 if self.visible_inside_mask { StencilTest::Inside } else { StencilTest::Outside }
121 }
122}
123
124/// One planned stencil writer for the current frame.
125#[derive(Clone, Copy, Debug, Default)]
126pub struct MaskWriter {
127 /// Part index (into parts / draw_order / SoA).
128 pub part_idx: usize,
129 /// Rank in `draw_order`; drives the scope replay (pure = backward scope,
130 /// clipping = forward scope).
131 pub rank: usize,
132 /// Stencil OP: `false` = increment, `true` = invert.
133 pub op_invert: bool,
134 /// `false` = pure mask (pre-written, removed when the cursor passes its
135 /// rank); `true` = clipping (added when the cursor reaches its rank).
136 pub is_clipping: bool,
137 /// Cutout threshold `(255 - mask)/255`, or `-1.0` for no cutout (textureless
138 /// pure masks — the whole quad writes coverage).
139 pub threshold: f32,
140 /// Cellmap texture for the cutout (0 = none → white fallback, no cutout).
141 pub texture_hash: u32,
142 /// Geometry to rasterise.
143 pub geom: GeomKind,
144}
145
146/// A writer placed on its player's tree sequence: the whole instance tree
147/// numbered in drawing order, each sub-animation in its instance part's place.
148///
149/// It holds its bit for the parts strictly between `open` and `close`. A clipping
150/// writer opens at itself and closes at the end of the tree, so one written
151/// inside an instance keeps clipping whatever its callers draw after it; a pure
152/// mask opens where its own animation starts and closes at itself, so it never
153/// reaches past the instance that holds it.
154#[derive(Clone, Copy, Debug)]
155pub struct ScopedWriter {
156 /// `op_invert` is already the effective one — the writer's own
157 /// `mask_influence` AND its instance part's.
158 pub writer: MaskWriter,
159 pub open: i32,
160 pub close: i32,
161}
162
163/// One frame's planned writers, held inline: what [`plan_writers`] hands back.
164///
165/// The draw walk does not use it. It plans once per node per frame into a list
166/// the player keeps across frames, which costs neither the allocator nor the
167/// kilobytes of this array a plan would otherwise fill and copy for every node,
168/// masks or none. Everything that reads a plan reads it as a slice (`Deref`).
169#[derive(Clone, Copy, Debug)]
170pub struct MaskWriters {
171 writers: [MaskWriter; MAX_MASK_WRITERS],
172 len: usize,
173}
174
175// Written out rather than derived: the array `Default` impls stop at 32, and the
176// cap is this module's to choose.
177impl Default for MaskWriters {
178 fn default() -> Self {
179 Self { writers: [MaskWriter::default(); MAX_MASK_WRITERS], len: 0 }
180 }
181}
182
183impl MaskWriters {
184 /// Append a writer.
185 ///
186 /// Panics past `MAX_MASK_WRITERS`. Respecting the cap is the planner's
187 /// job — it stops walking batches at it — so arriving here full is a bug in
188 /// the planner, and a writer dropped quietly instead would clip the frame
189 /// wrong with nothing left to point at.
190 pub fn push(&mut self, writer: MaskWriter) {
191 self.writers[self.len] = writer;
192 self.len += 1;
193 }
194}
195
196impl std::ops::Deref for MaskWriters {
197 type Target = [MaskWriter];
198 fn deref(&self) -> &[MaskWriter] {
199 &self.writers[..self.len]
200 }
201}
202
203/// So the draw walk can retarget each writer's cutout at the renderer key its
204/// node's pack resolved to — see `AtlasKeys`. Planning cannot do it: a writer
205/// takes its `texture_hash` from the batch, which speaks in cellmap hashes.
206impl std::ops::DerefMut for MaskWriters {
207 fn deref_mut(&mut self) -> &mut [MaskWriter] {
208 &mut self.writers[..self.len]
209 }
210}
211
212impl<'a> IntoIterator for &'a MaskWriters {
213 type Item = &'a MaskWriter;
214 type IntoIter = std::slice::Iter<'a, MaskWriter>;
215
216 fn into_iter(self) -> Self::IntoIter {
217 self.iter()
218 }
219}
220
221/// The player-local rectangle a frame's writers cover, as `[min_x, min_y,
222/// max_x, max_y]`, or `None` when they cover nothing.
223///
224/// This is the rectangle the coverage bitmap is stretched over:
225/// normalising it to `[0,1]` is what makes the bitmap's resolution independent
226/// of how big the mask is on screen, and what lets one affine serve both the
227/// bake and the replay.
228///
229/// **Player-local, not world**: the points are taken after each part's own world
230/// matrix but before the player's placement, so moving or scaling the player
231/// does not move the bitmap under its own coverage.
232pub fn writer_bounds(frame: &FrameView, writers: &[MaskWriter]) -> Option<[f32; 4]> {
233 let mut bounds = [f32::INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY];
234 let mut any = false;
235
236 let mut include = |x: f32, y: f32| {
237 // A NaN from a degenerate matrix must not poison the whole rectangle.
238 if !x.is_finite() || !y.is_finite() {
239 return;
240 }
241 bounds[0] = bounds[0].min(x);
242 bounds[1] = bounds[1].min(y);
243 bounds[2] = bounds[2].max(x);
244 bounds[3] = bounds[3].max(y);
245 any = true;
246 };
247
248 for writer in writers {
249 let part = writer.part_idx;
250 match writer.geom {
251 GeomKind::Quad => {
252 let (m, v) = (part * 16, part * 10);
253 if m + 16 > frame.world_matrices.len() || v + 10 > frame.local_vertices.len() {
254 continue;
255 }
256 let mat = &frame.world_matrices[m..m + 16];
257 // The four corners; the fifth pair is the centre, which is inside
258 // them and cannot widen the rectangle.
259 for k in 0..4 {
260 let (lx, ly) = (frame.local_vertices[v + k * 2], frame.local_vertices[v + k * 2 + 1]);
261 include(mat[0] * lx + mat[4] * ly + mat[12], mat[1] * lx + mat[5] * ly + mat[13]);
262 }
263 }
264 GeomKind::Mesh => {
265 let offsets = &frame.mesh_vertex_offsets;
266 if offsets.is_empty() || part >= offsets.len() - 1 {
267 continue;
268 }
269 let (start, end) = (offsets[part] as usize, offsets[part + 1] as usize);
270 if end > frame.mesh_vertices_x.len() || end > frame.mesh_vertices_y.len() {
271 continue;
272 }
273 // Mesh vertices arrive already skinned into player-local space.
274 for i in start..end {
275 include(frame.mesh_vertices_x[i], frame.mesh_vertices_y[i]);
276 }
277 }
278 GeomKind::Shape => {
279 let count = frame.shape_vertex_counts.get(part).copied().unwrap_or(0).max(0) as usize;
280 let (m, base) = (part * 16, part * SHAPE_VERTICES_STRIDE);
281 if count == 0 || m + 16 > frame.world_matrices.len() || base + count * 2 > frame.shape_vertices.len() {
282 continue;
283 }
284 let mat = &frame.world_matrices[m..m + 16];
285 for k in 0..count {
286 let (lx, ly) = (frame.shape_vertices[base + k * 2], frame.shape_vertices[base + k * 2 + 1]);
287 include(mat[0] * lx + mat[4] * ly + mat[12], mat[1] * lx + mat[5] * ly + mat[13]);
288 }
289 }
290 GeomKind::Unsupported => {}
291 }
292 }
293
294 any.then_some(bounds)
295}
296
297/// Plan the frame's stencil writers by walking `draw_batches`, mirroring the
298/// WebGL `MaskPlanner.plan`. `mask_flags` is indexed by part index (static
299/// ssab data). Returns writers in ascending rank order, capped at
300/// `MAX_MASK_WRITERS`.
301///
302/// A writer's `texture_hash` comes from the *batch* it belongs to (like WebGL):
303/// pure `Mask` batches carry `texture_hash == 0` (→ no cutout, whole geometry),
304/// while clipping writers inherit their content batch's real texture.
305///
306/// `op_invert` is the part's own `mask_influence`; inside an instance the caller
307/// ANDs it with the instance part's before the writer is drawn.
308///
309/// `frame.frame_data` is verified first, and bytes that are not a `FrameData`
310/// plan no writers.
311pub fn plan_writers(frame: &FrameView, mask_flags: &[PartMaskFlags]) -> MaskWriters {
312 let mut writers = MaskWriters::default();
313 // Verified, unlike the walk's parse: this view is whatever the caller built,
314 // and read unchecked, bytes that are not a FrameData are read out of bounds.
315 let Ok(fd) = root_as_frame_data(frame.frame_data) else { return writers };
316 let mut planned = Vec::new();
317 plan(fd, mask_flags, &mut planned);
318 for writer in planned {
319 writers.push(writer);
320 }
321 writers
322}
323
324/// [`plan_writers`], appending to `out` instead: the draw walk's form, which
325/// keeps one list for the whole tree across frames. The cap counts this call's
326/// writers only.
327pub(crate) fn plan_writers_into(frame: &FrameView, mask_flags: &[PartMaskFlags], out: &mut Vec<MaskWriter>) {
328 if frame.frame_data.is_empty() {
329 return;
330 }
331 // SAFETY: `frame_data` is a valid FlatBuffers `FrameData` produced by the
332 // runtime for this frame (same contract as the render loop).
333 plan(unsafe { root_as_frame_data_unchecked(frame.frame_data) }, mask_flags, out);
334}
335
336/// The planning both forms share, over a frame already parsed.
337fn plan(fd: FrameData, mask_flags: &[PartMaskFlags], out: &mut Vec<MaskWriter>) {
338 let start = out.len();
339 let draw_order = fd.draw_order();
340 let parts = fd.parts();
341
342 'batches: for batch in fd.draw_batches() {
343 let kind = batch.kind();
344 let start_rank = batch.start_rank() as usize;
345 let count = batch.count() as usize;
346 let texture_hash = batch.texture_hash();
347
348 let is_mask_batch = kind == DrawBatchKind::Mask;
349
350 for rank in start_rank..start_rank + count {
351 let part_idx = draw_order.get(rank) as usize;
352 let flags = mask_flags.get(part_idx).copied().unwrap_or_default();
353
354 // Only pure-mask batches and clipping content parts write coverage.
355 let is_pure = is_mask_batch; // Mask batches are always pure writers.
356 let is_clipping = !is_mask_batch && flags.is_clipping();
357 if !is_pure && !is_clipping {
358 continue;
359 }
360
361 // `mask == 0` or `Hide` opts the writer out. The runtime drops a
362 // hidden part's colour batch but keeps a `draw_as_mask` part's Mask
363 // batch, so Hide has to be read here or a hidden mask shape still cuts.
364 let state = parts.get(part_idx);
365 let mask_val = state.mask();
366 if mask_val <= 0.0 || state.hide() {
367 continue;
368 }
369
370 // texture 0 (pure masks / shapes) → no cutout.
371 let threshold = if texture_hash != 0 { (255.0 - mask_val) / 255.0 } else { -1.0 };
372
373 out.push(MaskWriter { part_idx, rank, op_invert: flags.mask_influence, is_clipping, threshold, texture_hash, geom: flags.geom });
374
375 if out.len() - start >= MAX_MASK_WRITERS {
376 break 'batches;
377 }
378 }
379 }
380}