opensubdiv-rs 0.7.0

A faithful Rust port of Pixar's OpenSubdiv subdivision-surface library (Sdc / Vtr / Far layers)
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
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
//! Stencil tables (port of `opensubdiv/far/stencilTable.h`,
//! `opensubdiv/far/stencilTableFactory.h` and the limit-stencil half of
//! them, `Far::LimitStencilTable` / `Far::LimitStencilTableFactory`).
//!
//! A *stencil* expresses one refined (or limit) vertex as a weighted sum of
//! the *base level* control vertices, factoring the whole chain of
//! subdivision steps into a single flat table. Once built, a
//! [`StencilTable`] can re-compute all refined/limit values for new control
//! values in a single pass — the core of OpenSubdiv's efficient re-posing of
//! animated meshes — without touching the topology again.
//!
//! Stencils are built for uniform and feature-adaptive hierarchies alike:
//! [`StencilTableFactory::create`] drives identity stencils through the
//! same [`PrimvarRefiner`] passes that interpolate vertex data, sparse
//! levels included.
//!
//! A *limit stencil* ([`LimitStencilTable`]) goes one step further: it
//! evaluates the limit surface — position and first derivatives — at an
//! arbitrary `(ptex face, u, v)` location directly from the base cage.
//! [`LimitStencilTableFactory`] obtains it by factorizing the basis weights
//! of the [`PatchTable`] patch covering the location through the stencils
//! of the patch's control vertices, so each evaluation becomes one sparse
//! dot product over cage vertices with no per-level intermediate buffers.
//! The stencils depend on the topology only and are reused across frames
//! of a deforming cage.

use super::patch_table::{PatchMap, PatchTable, PatchTableFactory};
use super::primvar_refiner::{Primvar, PrimvarRefiner};
use super::topology_refiner::TopologyRefiner;
use crate::vtr::TopologyError;
use crate::Index;

/// A single stencil: parallel slices of control-vertex indices and weights
/// (`Far::Stencil`).
#[derive(Debug, Clone, Copy)]
pub struct Stencil<'a> {
    /// Indices of the contributing control vertices.
    pub indices: &'a [Index],
    /// Weight of each control vertex, in the same order as `indices`.
    pub weights: &'a [f32],
}

impl Stencil<'_> {
    /// The number of control vertices contributing to this stencil
    /// (`GetSize`).
    pub fn size(&self) -> usize {
        self.indices.len()
    }
}

/// Options controlling [`StencilTableFactory`]
/// (`Far::StencilTableFactory::Options`).
#[derive(Debug, Clone, Copy)]
pub struct StencilTableOptions {
    /// Generate stencils for the vertices of all intermediate levels, not
    /// just the last one (`generateIntermediateLevels`; OpenSubdiv default:
    /// true).
    pub generate_intermediate_levels: bool,
    /// Prepend identity stencils for the control (base level) vertices
    /// themselves (`generateControlVerts`; OpenSubdiv default: false).
    pub generate_control_verts: bool,
}

impl Default for StencilTableOptions {
    fn default() -> Self {
        Self {
            generate_intermediate_levels: true,
            generate_control_verts: false,
        }
    }
}

impl StencilTableOptions {
    /// Options producing one stencil per *patch control value*: identity
    /// stencils for the base vertices followed by the stencils of every
    /// refined level, so that stencil `i` evaluates control value `i` of the
    /// buffer a [`PatchTable`] is evaluated against
    /// ([`PatchTable::num_control_values`]). This is the table
    /// [`LimitStencilTableFactory`] factorizes patches through.
    pub fn for_patch_controls() -> Self {
        Self {
            generate_intermediate_levels: true,
            generate_control_verts: true,
        }
    }
}

/// Table of subdivision stencils (`Far::StencilTable`).
///
/// Stencils are stored in flat arrays; stencil `i` covers the half-open
/// range `offsets[i]..offsets[i+1]` of `indices`/`weights`.
#[derive(Debug, Clone)]
pub struct StencilTable {
    num_control_vertices: usize,
    offsets: Vec<u32>,
    indices: Vec<Index>,
    weights: Vec<f32>,
}

impl StencilTable {
    /// The number of stencils in the table (`GetNumStencils`).
    pub fn num_stencils(&self) -> usize {
        self.offsets.len().saturating_sub(1)
    }

    /// The number of control vertices indexed by the table
    /// (`GetNumControlVertices`).
    pub fn num_control_vertices(&self) -> usize {
        self.num_control_vertices
    }

    /// The `i`-th stencil (`GetStencil`).
    pub fn stencil(&self, i: usize) -> Stencil<'_> {
        let (s, e) = (self.offsets[i] as usize, self.offsets[i + 1] as usize);
        Stencil {
            indices: &self.indices[s..e],
            weights: &self.weights[s..e],
        }
    }

    /// The start of every stencil in [`indices`](Self::indices) and
    /// [`weights`](Self::weights), followed by their total length:
    /// [`num_stencils`](Self::num_stencils)` + 1` entries, stencil `i`
    /// covering `offsets[i]..offsets[i + 1]`.
    ///
    /// With [`indices`](Self::indices) and [`weights`](Self::weights), this
    /// is the whole table as flat arrays, ready to upload to a GPU storage
    /// buffer for a compute kernel computing, for each stencil `i`,
    /// `dst[i] = Σ weights[j] · src[indices[j]]` over
    /// `j ∈ offsets[i]..offsets[i + 1]` (the stencil kernel of OpenSubdiv's
    /// `Osd` evaluators, whose separate `sizes` array is
    /// `offsets[i + 1] - offsets[i]`). It is never empty: a table without
    /// stencils has the offsets `[0]`.
    pub fn offsets(&self) -> &[u32] {
        &self.offsets
    }

    /// The control-vertex index of every stencil entry, all stencils
    /// concatenated (`GetControlIndices`); see [`offsets`](Self::offsets).
    pub fn indices(&self) -> &[Index] {
        &self.indices
    }

    /// The weight of every stencil entry, all stencils concatenated
    /// (`GetWeights`); see [`offsets`](Self::offsets).
    pub fn weights(&self) -> &[f32] {
        &self.weights
    }

    /// Update every stencil value from the given control values
    /// (`UpdateValues`): `dst[i]` receives the weighted sum of
    /// `control_values` described by stencil `i`.
    pub fn update_values<T: Primvar>(&self, control_values: &[T], dst: &mut [T]) {
        assert!(
            control_values.len() >= self.num_control_vertices,
            "control buffer too small"
        );
        assert!(dst.len() >= self.num_stencils(), "dst buffer too small");
        apply_weights(
            &self.offsets,
            &self.indices,
            &self.weights,
            control_values,
            dst,
        );
    }
}

/// Accumulate `dst[i] = Σ weights · control_values` over the flat stencil
/// arrays `offsets` / `indices` / `weights`.
fn apply_weights<T: Primvar>(
    offsets: &[u32],
    indices: &[Index],
    weights: &[f32],
    control_values: &[T],
    dst: &mut [T],
) {
    for (i, out) in dst.iter_mut().enumerate().take(offsets.len() - 1) {
        let (s, e) = (offsets[i] as usize, offsets[i + 1] as usize);
        let mut acc = out.clone();
        acc.clear();
        for (&idx, &w) in indices[s..e].iter().zip(&weights[s..e]) {
            acc.add_with_weight(&control_values[idx as usize], w);
        }
        *out = acc;
    }
}

/// A sparse weight vector over the base-level control vertices, driven
/// through [`PrimvarRefiner`] like any other primvar: interpolating identity
/// stencils level by level *factorizes* the subdivision into stencils —
/// exactly the approach of `Far::StencilTableFactory`.
#[derive(Debug, Clone, Default)]
struct StencilAccumulator {
    entries: Vec<(Index, f32)>,
}

impl Primvar for StencilAccumulator {
    fn clear(&mut self) {
        self.entries.clear();
    }
    fn add_with_weight(&mut self, src: &Self, weight: f32) {
        for &(index, w) in &src.entries {
            match self.entries.iter_mut().find(|(i, _)| *i == index) {
                Some((_, acc)) => *acc += w * weight,
                None => self.entries.push((index, w * weight)),
            }
        }
    }
}

/// Factory constructing [`StencilTable`]s from a [`TopologyRefiner`]
/// (`Far::StencilTableFactory`).
pub struct StencilTableFactory;

impl StencilTableFactory {
    /// Instantiate a [`StencilTable`] from a refined [`TopologyRefiner`]
    /// (`StencilTableFactory::Create`), uniformly or feature-adaptively
    /// refined.
    ///
    /// Stencils are ordered by level (level 1 first, then level 2, …); with
    /// [`generate_intermediate_levels`](StencilTableOptions::generate_intermediate_levels)
    /// disabled only the last level is emitted, and with
    /// [`generate_control_verts`](StencilTableOptions::generate_control_verts)
    /// enabled identity stencils for the base vertices are prepended. With
    /// both enabled ([`StencilTableOptions::for_patch_controls`]) the table
    /// has one stencil per control value of the refiner's [`PatchTable`],
    /// in the same order, so [`StencilTable::update_values`] fills the
    /// buffer that patches are evaluated against in one pass.
    ///
    /// For an adaptively refined hierarchy the levels are sparse: each
    /// level's stencils cover exactly the vertices that level holds, with
    /// the values [`PrimvarRefiner::interpolate`] computes for them
    /// (including its fringe fallbacks for support-only vertices, which no
    /// patch references).
    pub fn create(refiner: &TopologyRefiner, options: StencilTableOptions) -> StencilTable {
        let num_control = refiner.level(0).num_vertices();
        let primvar = PrimvarRefiner::new(refiner);

        let mut collected: Vec<StencilAccumulator> = Vec::new();
        if options.generate_control_verts {
            collected.extend((0..num_control).map(identity_stencil));
        }

        let mut src: Vec<StencilAccumulator> = (0..num_control).map(identity_stencil).collect();
        for level in 1..=refiner.max_level() {
            let mut dst = vec![StencilAccumulator::default(); refiner.level(level).num_vertices()];
            primvar.interpolate(level, &src, &mut dst);
            if options.generate_intermediate_levels || level == refiner.max_level() {
                collected.extend(dst.iter().cloned());
            }
            src = dst;
        }

        build_table(num_control, collected)
    }

    /// Instantiate a table of *limit* stencils: one stencil per vertex of
    /// the refiner's last level, evaluating that vertex's limit position
    /// directly from the base-level control vertices
    /// (`LimitStencilTableFactory`, for the vertices of the last level).
    ///
    /// The same constraints as [`PrimvarRefiner::limit`] apply: the refiner
    /// must be uniformly refined (the last level of an adaptive hierarchy
    /// is sparse, so its fringe vertices lack the neighborhoods the limit
    /// masks need — build a [`LimitStencilTableFactory`] table over the
    /// patches instead), and for the Catmark scheme with non-quad base
    /// faces it must hold at least one level of refinement.
    pub fn create_limit(refiner: &TopologyRefiner) -> StencilTable {
        assert!(
            !refiner.is_adaptive(),
            "vertex limit stencils require uniform refinement; use LimitStencilTableFactory for adaptive refiners"
        );
        let num_control = refiner.level(0).num_vertices();
        let primvar = PrimvarRefiner::new(refiner);

        let mut src: Vec<StencilAccumulator> = (0..num_control).map(identity_stencil).collect();
        for level in 1..=refiner.max_level() {
            let mut dst = vec![StencilAccumulator::default(); refiner.level(level).num_vertices()];
            primvar.interpolate(level, &src, &mut dst);
            src = dst;
        }

        let mut limits = vec![StencilAccumulator::default(); src.len()];
        primvar.limit(&src, &mut limits);

        build_table(num_control, limits)
    }

    /// Append the stencils of a patch table's *local points* to the stencils
    /// of its control values (`AppendLocalPointStencilTable`).
    ///
    /// `cv_stencils` must hold one stencil per patch control value — the
    /// table [`StencilTableOptions::for_patch_controls`] builds — and
    /// `local_point_stencils` the local points' stencils over those control
    /// values, such as
    /// [`GpuPatchTable::local_point_stencils`](crate::osd::GpuPatchTable::local_point_stencils).
    /// The result keeps the stencils of `cv_stencils` and appends one per
    /// local point, composed down to the control vertices of `cv_stencils`
    /// (the base cage): applied to the base values, it produces the whole
    /// buffer a [`GpuPatchTable`](crate::osd::GpuPatchTable) evaluates
    /// against, control values then local points, in one pass.
    ///
    /// # Panics
    ///
    /// Panics when `cv_stencils` has fewer stencils than
    /// `local_point_stencils` has control vertices.
    pub fn append_local_point_stencils(
        cv_stencils: &StencilTable,
        local_point_stencils: &StencilTable,
    ) -> StencilTable {
        assert!(
            cv_stencils.num_stencils() >= local_point_stencils.num_control_vertices(),
            "control-vertex stencil table has {} stencils but the local points depend on {} control values; \
             build it with StencilTableOptions::for_patch_controls()",
            cv_stencils.num_stencils(),
            local_point_stencils.num_control_vertices()
        );
        let mut stencils: Vec<StencilAccumulator> = (0..cv_stencils.num_stencils())
            .map(|i| {
                let stencil = cv_stencils.stencil(i);
                StencilAccumulator {
                    entries: stencil
                        .indices
                        .iter()
                        .copied()
                        .zip(stencil.weights.iter().copied())
                        .collect(),
                }
            })
            .collect();
        for i in 0..local_point_stencils.num_stencils() {
            let local = local_point_stencils.stencil(i);
            let mut composed = StencilAccumulator::default();
            for (&cv, &w) in local.indices.iter().zip(local.weights) {
                composed.add_with_weight(&stencils[cv as usize], w);
            }
            stencils.push(composed);
        }
        build_table(cv_stencils.num_control_vertices(), stencils)
    }
}

fn identity_stencil(v: usize) -> StencilAccumulator {
    StencilAccumulator {
        entries: vec![(v as Index, 1.0)],
    }
}

impl StencilTable {
    /// A table of the given stencils, each a list of `(control vertex,
    /// weight)` entries over `num_control_vertices` control vertices.
    /// Entries are sorted by control vertex, as the factory's are.
    pub(crate) fn from_stencils(
        num_control_vertices: usize,
        stencils: Vec<Vec<(Index, f32)>>,
    ) -> StencilTable {
        build_table(
            num_control_vertices,
            stencils
                .into_iter()
                .map(|entries| StencilAccumulator { entries })
                .collect(),
        )
    }
}

fn build_table(num_control_vertices: usize, stencils: Vec<StencilAccumulator>) -> StencilTable {
    let total: usize = stencils.iter().map(|s| s.entries.len()).sum();
    let mut table = StencilTable {
        num_control_vertices,
        offsets: Vec::with_capacity(stencils.len() + 1),
        indices: Vec::with_capacity(total),
        weights: Vec::with_capacity(total),
    };
    table.offsets.push(0);
    for mut stencil in stencils {
        // Sort entries by control index for deterministic output.
        stencil.entries.sort_by_key(|&(i, _)| i);
        for (index, weight) in stencil.entries {
            table.indices.push(index);
            table.weights.push(weight);
        }
        table.offsets.push(table.indices.len() as u32);
    }
    table
}

// ----------------------------------------------------------------------
//  Limit stencils at arbitrary parametric locations
// ----------------------------------------------------------------------

/// A set of parametric locations on one ptex face at which limit stencils
/// are requested (`Far::LimitStencilTableFactory::LocationArray`).
///
/// `u` and `v` are parallel slices of coordinates in the parametric space
/// of `ptex_face` — the same space [`PatchMap::find_patch`] and
/// [`PatchTable::evaluate`] use.
#[derive(Debug, Clone, Copy)]
pub struct LocationArray<'a> {
    /// The ptex face the locations lie on (see
    /// [`PtexIndices`](super::PtexIndices)).
    pub ptex_face: Index,
    /// The `u` coordinate of each location.
    pub u: &'a [f32],
    /// The `v` coordinate of each location, parallel to `u`.
    pub v: &'a [f32],
}

impl<'a> LocationArray<'a> {
    /// Locations `(u[i], v[i])` on `ptex_face`.
    ///
    /// # Panics
    /// Panics if `u` and `v` differ in length.
    pub fn new(ptex_face: Index, u: &'a [f32], v: &'a [f32]) -> Self {
        assert_eq!(
            u.len(),
            v.len(),
            "u and v coordinate arrays must be parallel"
        );
        Self { ptex_face, u, v }
    }

    /// The number of locations in the array (`numLocations`).
    pub fn len(&self) -> usize {
        self.u.len()
    }

    /// Does the array hold no locations?
    pub fn is_empty(&self) -> bool {
        self.u.is_empty()
    }
}

/// A single limit stencil (`Far::LimitStencil`): weights on the base-level
/// control vertices for the limit position and its first derivatives with
/// respect to the ptex-face `(u, v)` coordinates.
#[derive(Debug, Clone, Copy)]
pub struct LimitStencil<'a> {
    /// Indices of the contributing control vertices.
    pub indices: &'a [Index],
    /// Weight of each control vertex for the limit position.
    pub weights: &'a [f32],
    /// Weight of each control vertex for the derivative along `u`
    /// (`GetDuWeights`).
    pub du_weights: &'a [f32],
    /// Weight of each control vertex for the derivative along `v`
    /// (`GetDvWeights`).
    pub dv_weights: &'a [f32],
}

impl LimitStencil<'_> {
    /// The number of control vertices contributing to this stencil
    /// (`GetSize`).
    pub fn size(&self) -> usize {
        self.indices.len()
    }
}

/// Table of limit stencils (`Far::LimitStencilTable`): each stencil
/// evaluates the limit surface at one parametric location — position and
/// first derivatives — directly from the base-level control vertices.
///
/// The position weights form an ordinary [`StencilTable`]
/// ([`point_stencils`](Self::point_stencils)); the derivative weights are
/// stored alongside, over the same control-vertex indices.
#[derive(Debug, Clone)]
pub struct LimitStencilTable {
    points: StencilTable,
    du_weights: Vec<f32>,
    dv_weights: Vec<f32>,
}

impl LimitStencilTable {
    /// The number of stencils in the table (`GetNumStencils`): one per
    /// requested location, in request order.
    pub fn num_stencils(&self) -> usize {
        self.points.num_stencils()
    }

    /// The number of control vertices indexed by the table
    /// (`GetNumControlVertices`): the base level's vertex count.
    pub fn num_control_vertices(&self) -> usize {
        self.points.num_control_vertices()
    }

    /// The `i`-th limit stencil (`GetLimitStencil`).
    pub fn stencil(&self, i: usize) -> LimitStencil<'_> {
        let (s, e) = (
            self.points.offsets[i] as usize,
            self.points.offsets[i + 1] as usize,
        );
        LimitStencil {
            indices: &self.points.indices[s..e],
            weights: &self.points.weights[s..e],
            du_weights: &self.du_weights[s..e],
            dv_weights: &self.dv_weights[s..e],
        }
    }

    /// The weight of every stencil entry for the derivative along the
    /// ptex-face `u` direction (`GetDuWeights`), parallel to
    /// [`StencilTable::weights`] of the [`point_stencils`](Self::point_stencils):
    /// the same [`offsets`](StencilTable::offsets) and
    /// [`indices`](StencilTable::indices) apply.
    pub fn du_weights(&self) -> &[f32] {
        &self.du_weights
    }

    /// The weight of every stencil entry for the derivative along the
    /// ptex-face `v` direction (`GetDvWeights`); see
    /// [`du_weights`](Self::du_weights).
    pub fn dv_weights(&self) -> &[f32] {
        &self.dv_weights
    }

    /// The position stencils alone, as a plain [`StencilTable`]: its
    /// [`offsets`](StencilTable::offsets), [`indices`](StencilTable::indices)
    /// and [`weights`](StencilTable::weights) are the flat arrays of this
    /// table.
    pub fn point_stencils(&self) -> &StencilTable {
        &self.points
    }

    /// Evaluate the limit position of every stencil from the given control
    /// values (`UpdateValues`): `dst[i]` receives the limit position at
    /// location `i`.
    pub fn update_values<T: Primvar>(&self, control_values: &[T], dst: &mut [T]) {
        self.points.update_values(control_values, dst);
    }

    /// Evaluate the first derivatives of every stencil from the given
    /// control values (`UpdateDerivs`): `du[i]` and `dv[i]` receive the
    /// derivatives of the limit surface along the ptex-face `u` and `v`
    /// directions at location `i`.
    pub fn update_derivs<T: Primvar>(&self, control_values: &[T], du: &mut [T], dv: &mut [T]) {
        assert!(
            control_values.len() >= self.num_control_vertices(),
            "control buffer too small"
        );
        assert!(
            du.len() >= self.num_stencils() && dv.len() >= self.num_stencils(),
            "derivative buffers too small"
        );
        apply_weights(
            &self.points.offsets,
            &self.points.indices,
            &self.du_weights,
            control_values,
            du,
        );
        apply_weights(
            &self.points.offsets,
            &self.points.indices,
            &self.dv_weights,
            control_values,
            dv,
        );
    }
}

/// Factory constructing [`LimitStencilTable`]s
/// (`Far::LimitStencilTableFactory`).
pub struct LimitStencilTableFactory;

impl LimitStencilTableFactory {
    /// Build limit stencils at the given parametric locations
    /// (`LimitStencilTableFactory::Create`), for a uniformly or adaptively
    /// refined `refiner`.
    ///
    /// Every location is covered by a patch of the refiner's [`PatchTable`]
    /// (bicubic B-spline, single-crease, Gregory, box-spline, Gregory
    /// triangle or linear alike); the patch's basis weights at the
    /// location — point and first derivatives — are factorized through the
    /// stencils of its control vertices, which puts the limit evaluation
    /// directly on the base cage. The resulting stencils are listed in the
    /// order of `locations` (arrays in order, locations within each array
    /// in order) and reproduce [`PatchTable::evaluate`] over the
    /// concatenated level buffer to floating-point round-off. Gregory and
    /// Gregory-triangle end caps need no separate treatment: their derived
    /// points are themselves stencils on the refined vertices and fold
    /// through the same factorization (the role of OpenSubdiv's
    /// `AppendLocalPointStencilTable`).
    ///
    /// `cv_stencils` and `patch_table` may be supplied to reuse tables
    /// already built for `refiner`; either is built on demand otherwise.
    /// `cv_stencils` must hold one stencil per control value of the patch
    /// table, in order — the table [`StencilTableFactory::create`] builds
    /// with [`StencilTableOptions::for_patch_controls`].
    ///
    /// # Errors
    ///
    /// Returns [`TopologyError::PatchesRequireRefinement`] when a patch
    /// table has to be built for an unrefined mesh with non-quad faces,
    /// [`TopologyError::PatchDepthTooDeep`] when one has to be built for a
    /// refiner deeper than [`PatchParam::MAX_DEPTH`](super::PatchParam::MAX_DEPTH),
    /// [`TopologyError::PtexFaceOutOfRange`] when a non-empty location
    /// array names a ptex face the patch table does not have, and
    /// [`TopologyError::LimitLocationInHole`] when a location lies in a
    /// hole, where the limit surface is undefined. A request without any
    /// location yields an empty table without building either dependency.
    ///
    /// # Panics
    ///
    /// Panics when the supplied `cv_stencils` has fewer stencils than the
    /// patch table has control values.
    pub fn create(
        refiner: &TopologyRefiner,
        locations: &[LocationArray<'_>],
        cv_stencils: Option<&StencilTable>,
        patch_table: Option<&PatchTable>,
    ) -> Result<LimitStencilTable, TopologyError> {
        // Validate the request before building anything: an empty request
        // needs neither table (and must not fail on a mesh no patch table
        // can be built for yet).
        let mut num_locations = 0usize;
        for array in locations {
            assert_eq!(
                array.u.len(),
                array.v.len(),
                "u and v coordinate arrays must be parallel"
            );
            num_locations += array.len();
        }
        let num_control_vertices = refiner.level(0).num_vertices();
        if num_locations == 0 {
            return Ok(LimitStencilTable {
                points: StencilTable {
                    num_control_vertices,
                    offsets: vec![0],
                    indices: Vec::new(),
                    weights: Vec::new(),
                },
                du_weights: Vec::new(),
                dv_weights: Vec::new(),
            });
        }

        let owned_patches;
        let patch_table = match patch_table {
            Some(table) => table,
            None => {
                owned_patches = PatchTableFactory::create(refiner)?;
                &owned_patches
            }
        };
        let num_ptex_faces = patch_table.ptex_indices().num_faces();
        for array in locations {
            if !array.is_empty() && array.ptex_face as usize >= num_ptex_faces {
                return Err(TopologyError::PtexFaceOutOfRange {
                    ptex_face: array.ptex_face,
                    num_faces: num_ptex_faces,
                });
            }
        }

        let owned_stencils;
        let cv_stencils = match cv_stencils {
            Some(table) => table,
            None => {
                owned_stencils =
                    StencilTableFactory::create(refiner, StencilTableOptions::for_patch_controls());
                &owned_stencils
            }
        };
        assert!(
            cv_stencils.num_stencils() >= patch_table.num_control_values(),
            "control-vertex stencil table has {} stencils but the patch table has {} control values; \
             build it with StencilTableOptions::for_patch_controls()",
            cv_stencils.num_stencils(),
            patch_table.num_control_values()
        );
        let num_control_vertices = cv_stencils.num_control_vertices();

        let map = PatchMap::new(patch_table);
        let mut offsets = Vec::with_capacity(num_locations + 1);
        let mut indices = Vec::new();
        let mut weights = Vec::new();
        let mut du_weights = Vec::new();
        let mut dv_weights = Vec::new();
        offsets.push(0u32);

        // Per location: weights on the base cage for (point, du, dv),
        // accumulated in a scratch slot per cage vertex; `touched` lists the
        // slots in use so only those are emitted and reset.
        let mut scratch = vec![[0.0f32; 3]; num_control_vertices];
        let mut in_use = vec![false; num_control_vertices];
        let mut touched: Vec<Index> = Vec::new();
        for array in locations {
            for (&u, &v) in array.u.iter().zip(array.v) {
                let patch = map.find_patch(array.ptex_face as usize, u, v).ok_or(
                    TopologyError::LimitLocationInHole {
                        ptex_face: array.ptex_face,
                        location: offsets.len() - 1,
                    },
                )?;
                let basis = patch_table.evaluate_basis(patch, u, v);

                for (k, &cv) in basis.indices.iter().enumerate() {
                    let stencil = cv_stencils.stencil(cv as usize);
                    let factors = [basis.weights[k], basis.du_weights[k], basis.dv_weights[k]];
                    for (&index, &w) in stencil.indices.iter().zip(stencil.weights) {
                        if !std::mem::replace(&mut in_use[index as usize], true) {
                            touched.push(index);
                        }
                        for (s, f) in scratch[index as usize].iter_mut().zip(factors) {
                            *s += f * w;
                        }
                    }
                }
                // Sort for deterministic output, then emit and reset.
                touched.sort_unstable();
                for &index in &touched {
                    let [w, du, dv] = std::mem::take(&mut scratch[index as usize]);
                    in_use[index as usize] = false;
                    indices.push(index);
                    weights.push(w);
                    du_weights.push(du);
                    dv_weights.push(dv);
                }
                touched.clear();
                offsets.push(indices.len() as u32);
            }
        }

        Ok(LimitStencilTable {
            points: StencilTable {
                num_control_vertices,
                offsets,
                indices,
                weights,
            },
            du_weights,
            dv_weights,
        })
    }
}