euv-core 0.57.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
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
use super::*;

/// Evaluation, arc-length parameterization, and Bishop frame transport for `Spline3D`.
impl Spline3D {
    /// Constructs a Catmull-Rom `Spline3D` with a precomputed arc-length lookup table.
    ///
    /// # Arguments
    ///
    /// - `Vec<Vec3>` - Control points passed through by the curve.
    /// - `bool` - Whether the spline forms a closed periodic loop.
    ///
    /// # Returns
    ///
    /// - `Self` - Constructed `Spline3D` with precomputed arc-length LUT.
    #[must_use]
    pub fn catmull_rom(points: Vec<Vec3>, closed: bool) -> Self {
        Self::build(points, SplineKind::CatmullRom, closed)
    }

    /// Constructs a chained piecewise Cubic Bezier `Spline3D` with a precomputed arc-length lookup table.
    ///
    /// # Arguments
    ///
    /// - `Vec<Vec3>` - Anchor and handle control points (`[P0, C0, C1, P1, ...]`).
    /// - `bool` - Whether the spline closes back to the initial anchor.
    ///
    /// # Returns
    ///
    /// - `Self` - Constructed `Spline3D` with precomputed arc-length LUT.
    #[must_use]
    pub fn cubic_bezier(points: Vec<Vec3>, closed: bool) -> Self {
        Self::build(points, SplineKind::CubicBezier, closed)
    }

    /// Builds a sanitized `Spline3D` and populates its arc-length parameterization table.
    ///
    /// # Arguments
    ///
    /// - `Vec<Vec3>` - Raw control points.
    /// - `SplineKind` - Curve interpolation family.
    /// - `bool` - Closed-loop flag.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready `Spline3D` instance.
    #[must_use]
    fn build(points: Vec<Vec3>, kind: SplineKind, closed: bool) -> Self {
        let mut clean_pts: Vec<Vec3> = Vec::with_capacity(points.len());
        for pt in points.into_iter() {
            clean_pts.push(sanitize_vec3(pt, Vec3::zero()));
        }
        let is_closed: bool = closed && clean_pts.len() >= 3;
        let mut spline: Self = Self {
            control_points: clean_pts,
            kind,
            closed: is_closed,
            arc_table: Vec::new(),
            total_length: 0.0,
        };
        let segs: usize = spline.segment_count().max(1);
        let sample_count: usize =
            (segs * SPLINE_SAMPLES_PER_SEG).clamp(SPLINE_ARC_MIN_SAMPLES, SPLINE_ARC_MAX_SAMPLES);
        let mut table: Vec<(f32, f32)> = Vec::with_capacity(sample_count + 1);
        let mut accum: f32 = 0.0;
        let mut prev: Vec3 = spline.sample_point(0.0);
        table.push((0.0, 0.0));
        for i in 1..=sample_count {
            let t: f32 = (i as f32) / (sample_count as f32);
            let cur: Vec3 = spline.sample_point(t);
            accum += cur.sub(prev).length();
            table.push((t, accum));
            prev = cur;
        }
        spline.set_arc_table(table);
        spline.set_total_length(accum);
        spline
    }

    /// Returns the number of piecewise cubic segments in this spline.
    ///
    /// # Returns
    ///
    /// - `usize` - Number of curve segments (`0` when fewer than 2 control points exist).
    #[must_use]
    pub fn segment_count(&self) -> usize {
        let n: usize = self.get_control_points().len();
        if n < 2 {
            return 0;
        }
        match self.get_kind() {
            SplineKind::CatmullRom => {
                if self.get_closed() {
                    n
                } else {
                    n - 1
                }
            }
            SplineKind::CubicBezier => {
                if self.get_closed() {
                    (n / 3).max(1)
                } else if n < 4 {
                    1
                } else {
                    ((n - 1) / 3).max(1)
                }
            }
        }
    }

    /// Resolves the four control points and local parameter `u` for a Catmull-Rom evaluation at `t`.
    ///
    /// # Arguments
    ///
    /// - `f32` - Normalized curve parameter.
    ///
    /// # Returns
    ///
    /// - `(Vec3, Vec3, Vec3, Vec3, f32)` - Tuple `(p0, p1, p2, p3, local_u)`.
    #[must_use]
    fn catmull_rom_segment(&self, t: f32) -> (Vec3, Vec3, Vec3, Vec3, f32) {
        let pts: &[Vec3] = self.get_control_points();
        let n: usize = pts.len();
        if n == 0 {
            return (Vec3::zero(), Vec3::zero(), Vec3::zero(), Vec3::zero(), 0.0);
        }
        if n == 1 {
            return (pts[0], pts[0], pts[0], pts[0], 0.0);
        }
        let segs: usize = self.segment_count().max(1);
        let wrapped_t: f32 = if self.get_closed() {
            t.rem_euclid(1.0)
        } else {
            t.clamp(0.0, 1.0)
        };
        let scaled: f32 = wrapped_t * (segs as f32);
        let seg_idx: usize = (scaled.floor() as usize).min(segs - 1);
        let local_u: f32 = (scaled - (seg_idx as f32)).clamp(0.0, 1.0);
        if self.get_closed() {
            let p0: Vec3 = pts[(seg_idx + n - 1) % n];
            let p1: Vec3 = pts[seg_idx % n];
            let p2: Vec3 = pts[(seg_idx + 1) % n];
            let p3: Vec3 = pts[(seg_idx + 2) % n];
            (p0, p1, p2, p3, local_u)
        } else {
            let p1: Vec3 = pts[seg_idx];
            let p2: Vec3 = pts[(seg_idx + 1).min(n - 1)];
            let p0: Vec3 = if seg_idx == 0 {
                p1.add(p1.sub(p2))
            } else {
                pts[seg_idx - 1]
            };
            let p3: Vec3 = if seg_idx + 2 < n {
                pts[seg_idx + 2]
            } else {
                p2.add(p2.sub(p1))
            };
            (p0, p1, p2, p3, local_u)
        }
    }

    /// Resolves the four Bezier control points and local parameter `u` at `t`.
    ///
    /// # Arguments
    ///
    /// - `f32` - Normalized curve parameter.
    ///
    /// # Returns
    ///
    /// - `(Vec3, Vec3, Vec3, Vec3, f32)` - Tuple `(b0, b1, b2, b3, local_u)`.
    #[must_use]
    fn bezier_segment(&self, t: f32) -> (Vec3, Vec3, Vec3, Vec3, f32) {
        let pts: &[Vec3] = self.get_control_points();
        let n: usize = pts.len();
        if n == 0 {
            return (Vec3::zero(), Vec3::zero(), Vec3::zero(), Vec3::zero(), 0.0);
        }
        if n == 1 {
            return (pts[0], pts[0], pts[0], pts[0], 0.0);
        }
        if n == 2 {
            let b0: Vec3 = pts[0];
            let b3: Vec3 = pts[1];
            return (
                b0,
                b0.lerp(b3, 1.0 / 3.0),
                b0.lerp(b3, 2.0 / 3.0),
                b3,
                t.clamp(0.0, 1.0),
            );
        }
        if n == 3 && !self.get_closed() {
            let p0: Vec3 = pts[0];
            let p1: Vec3 = pts[1];
            let p2: Vec3 = pts[2];
            let c1: Vec3 = p0.lerp(p1, 2.0 / 3.0);
            let c2: Vec3 = p2.lerp(p1, 2.0 / 3.0);
            return (p0, c1, c2, p2, t.clamp(0.0, 1.0));
        }
        let segs: usize = self.segment_count().max(1);
        let wrapped_t: f32 = if self.get_closed() {
            t.rem_euclid(1.0)
        } else {
            t.clamp(0.0, 1.0)
        };
        let scaled: f32 = wrapped_t * (segs as f32);
        let seg_idx: usize = (scaled.floor() as usize).min(segs - 1);
        let local_u: f32 = (scaled - (seg_idx as f32)).clamp(0.0, 1.0);
        let base: usize = seg_idx * 3;
        if self.get_closed() {
            let b0: Vec3 = pts[base % n];
            let b1: Vec3 = pts[(base + 1) % n];
            let b2: Vec3 = pts[(base + 2) % n];
            let b3: Vec3 = pts[(base + 3) % n];
            (b0, b1, b2, b3, local_u)
        } else {
            let b0: Vec3 = pts[base.min(n - 1)];
            let b1: Vec3 = pts[(base + 1).min(n - 1)];
            let b2: Vec3 = pts[(base + 2).min(n - 1)];
            let b3: Vec3 = pts[(base + 3).min(n - 1)];
            (b0, b1, b2, b3, local_u)
        }
    }

    /// Evaluates the 3D position on the spline at normalized parameter `t` in `[0, 1]`.
    ///
    /// # Arguments
    ///
    /// - `f32` - Normalized curve parameter.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Interpolated finite 3D curve position.
    #[must_use]
    pub fn sample_point(&self, t: f32) -> Vec3 {
        let clean_t: f32 = sanitize_scalar(t, 0.0);
        match self.get_kind() {
            SplineKind::CatmullRom => {
                let (p0, p1, p2, p3, u): (Vec3, Vec3, Vec3, Vec3, f32) =
                    self.catmull_rom_segment(clean_t);
                let u2: f32 = u * u;
                let u3: f32 = u2 * u;
                let term0: Vec3 = p1.scale(2.0);
                let term1: Vec3 = p2.sub(p0).scale(u);
                let term2: Vec3 = p0
                    .scale(2.0)
                    .sub(p1.scale(5.0))
                    .add(p2.scale(4.0))
                    .sub(p3)
                    .scale(u2);
                let term3: Vec3 = p1.scale(3.0).sub(p0).sub(p2.scale(3.0)).add(p3).scale(u3);
                sanitize_vec3(
                    term0.add(term1).add(term2).add(term3).scale(0.5),
                    Vec3::zero(),
                )
            }
            SplineKind::CubicBezier => {
                let (b0, b1, b2, b3, u): (Vec3, Vec3, Vec3, Vec3, f32) =
                    self.bezier_segment(clean_t);
                let inv: f32 = 1.0 - u;
                let inv2: f32 = inv * inv;
                let inv3: f32 = inv2 * inv;
                let u2: f32 = u * u;
                let u3: f32 = u2 * u;
                let pos: Vec3 = b0
                    .scale(inv3)
                    .add(b1.scale(3.0 * inv2 * u))
                    .add(b2.scale(3.0 * inv * u2))
                    .add(b3.scale(u3));
                sanitize_vec3(pos, Vec3::zero())
            }
        }
    }

    /// Evaluates the unit forward tangent vector on the spline at normalized parameter `t`.
    ///
    /// # Arguments
    ///
    /// - `f32` - Normalized curve parameter.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Unit forward tangent direction.
    #[must_use]
    pub fn sample_tangent(&self, t: f32) -> Vec3 {
        let clean_t: f32 = sanitize_scalar(t, 0.0);
        let raw_deriv: Vec3 = match self.get_kind() {
            SplineKind::CatmullRom => {
                let (p0, p1, p2, p3, u): (Vec3, Vec3, Vec3, Vec3, f32) =
                    self.catmull_rom_segment(clean_t);
                let u2: f32 = u * u;
                let d1: Vec3 = p2.sub(p0);
                let d2: Vec3 = p0
                    .scale(2.0)
                    .sub(p1.scale(5.0))
                    .add(p2.scale(4.0))
                    .sub(p3)
                    .scale(2.0 * u);
                let d3: Vec3 = p1
                    .scale(3.0)
                    .sub(p0)
                    .sub(p2.scale(3.0))
                    .add(p3)
                    .scale(3.0 * u2);
                d1.add(d2).add(d3).scale(0.5)
            }
            SplineKind::CubicBezier => {
                let (b0, b1, b2, b3, u): (Vec3, Vec3, Vec3, Vec3, f32) =
                    self.bezier_segment(clean_t);
                let inv: f32 = 1.0 - u;
                let d0: Vec3 = b1.sub(b0).scale(3.0 * inv * inv);
                let d1: Vec3 = b2.sub(b1).scale(6.0 * inv * u);
                let d2: Vec3 = b3.sub(b2).scale(3.0 * u * u);
                d0.add(d1).add(d2)
            }
        };
        if raw_deriv.length_sq() > MESH_OPS_EPSILON_SQ {
            safe_unit_normal(raw_deriv)
        } else {
            let eps: f32 = 1e-3;
            let p_prev: Vec3 = self.sample_point((clean_t - eps).clamp(0.0, 1.0));
            let p_next: Vec3 = self.sample_point((clean_t + eps).clamp(0.0, 1.0));
            let diff: Vec3 = p_next.sub(p_prev);
            if diff.length_sq() > MESH_OPS_EPSILON_SQ {
                safe_unit_normal(diff)
            } else {
                Vec3::new(0.0, 0.0, 1.0)
            }
        }
    }

    /// Maps an arc-length distance to the corresponding spline parameter `t` in `[0, 1]` using binary search.
    ///
    /// # Arguments
    ///
    /// - `f32` - Distance along the spline from its start.
    ///
    /// # Returns
    ///
    /// - `f32` - Spline parameter `t` in `[0, 1]`.
    #[must_use]
    pub fn sample_t_at_distance(&self, distance: f32) -> f32 {
        let total: f32 = self.get_total_length();
        let table: &[(f32, f32)] = self.get_arc_table();
        if total <= SPLINE_EPSILON || table.len() < 2 {
            return 0.0;
        }
        let clean_d: f32 = sanitize_scalar(distance, 0.0);
        let target: f32 = if self.get_closed() {
            clean_d.rem_euclid(total)
        } else {
            clean_d.clamp(0.0, total)
        };
        let mut lo: usize = 0;
        let mut hi: usize = table.len() - 1;
        while lo + 1 < hi {
            let mid: usize = (lo + hi) / 2;
            if table[mid].1 <= target {
                lo = mid;
            } else {
                hi = mid;
            }
        }
        let (t0, d0): (f32, f32) = table[lo];
        let (t1, d1): (f32, f32) = table[hi];
        let span: f32 = d1 - d0;
        if span > SPLINE_EPSILON {
            let alpha: f32 = ((target - d0) / span).clamp(0.0, 1.0);
            t0 + (t1 - t0) * alpha
        } else {
            t0
        }
    }

    /// Evaluates the 3D spline position at exact arc-length `distance` with zero heap allocations.
    ///
    /// # Arguments
    ///
    /// - `f32` - Arc-length distance along the curve.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Uniformly parameterized 3D position on the curve.
    #[must_use]
    pub fn sample_by_arc_length(&self, distance: f32) -> Vec3 {
        let t: f32 = self.sample_t_at_distance(distance);
        self.sample_point(t)
    }

    /// Computes twist-free parallel-transport Bishop frames uniformly distributed by arc length.
    ///
    /// # Arguments
    ///
    /// - `usize` - Number of frames to generate (clamped to `>= 2`).
    ///
    /// # Returns
    ///
    /// - `Vec<SplineFrame3D>` - Orthonormal twist-free Bishop frames along the spline.
    #[must_use]
    pub fn sample_bishop_frames(&self, samples: usize) -> Vec<SplineFrame3D> {
        let count: usize = samples.max(2);
        let total: f32 = self.get_total_length();
        let is_closed: bool = self.get_closed();
        let denom: f32 = if is_closed {
            count as f32
        } else {
            (count - 1) as f32
        };
        let mut frames: Vec<SplineFrame3D> = Vec::with_capacity(count);
        let t0: f32 = self.sample_t_at_distance(0.0);
        let pos0: Vec3 = self.sample_point(t0);
        let tan0: Vec3 = self.sample_tangent(t0);
        let seed_axis: Vec3 = if tan0.get_y().abs() < 0.9 {
            Vec3::new(0.0, 1.0, 0.0)
        } else {
            Vec3::new(1.0, 0.0, 0.0)
        };
        let mut cur_n: Vec3 = safe_unit_normal(seed_axis.sub(tan0.scale(seed_axis.dot(tan0))));
        let mut cur_t: Vec3 = tan0;
        let cur_b: Vec3 = safe_unit_normal(cur_t.cross(cur_n));
        frames.push(SplineFrame3D::new(pos0, cur_t, cur_n, cur_b, 0.0));
        for i in 1..count {
            let dist: f32 = total * ((i as f32) / denom);
            let ti: f32 = self.sample_t_at_distance(dist);
            let pos: Vec3 = self.sample_point(ti);
            let next_t: Vec3 = self.sample_tangent(ti);
            let axis: Vec3 = cur_t.cross(next_t);
            let axis_len: f32 = axis.length();
            let transported_n: Vec3 = if axis_len > SPLINE_EPSILON {
                let cos_ang: f32 = cur_t.dot(next_t).clamp(-1.0, 1.0);
                let ang: f32 = cos_ang.acos();
                let rot: Quat = Quat::from_axis_angle(axis.scale(1.0 / axis_len), ang);
                rot.rotate_vec3(cur_n)
            } else {
                cur_n
            };
            let ortho_n: Vec3 = transported_n.sub(next_t.scale(transported_n.dot(next_t)));
            cur_n = safe_unit_normal(ortho_n);
            cur_t = next_t;
            let next_b: Vec3 = safe_unit_normal(cur_t.cross(cur_n));
            frames.push(SplineFrame3D::new(pos, cur_t, cur_n, next_b, dist));
        }
        if is_closed && count >= 3 {
            let last_t: Vec3 = frames[count - 1].get_tangent();
            let last_n: Vec3 = frames[count - 1].get_normal();
            let first_t: Vec3 = frames[0].get_tangent();
            let first_n: Vec3 = frames[0].get_normal();
            let first_b: Vec3 = frames[0].get_binormal();
            let axis: Vec3 = last_t.cross(first_t);
            let axis_len: f32 = axis.length();
            let wrapped_n: Vec3 = if axis_len > SPLINE_EPSILON {
                let ang: f32 = last_t.dot(first_t).clamp(-1.0, 1.0).acos();
                Quat::from_axis_angle(axis.scale(1.0 / axis_len), ang).rotate_vec3(last_n)
            } else {
                last_n
            };
            let aligned_n: Vec3 =
                safe_unit_normal(wrapped_n.sub(first_t.scale(wrapped_n.dot(first_t))));
            let twist_error: f32 = aligned_n.dot(first_b).atan2(aligned_n.dot(first_n));
            if twist_error.abs() > SPLINE_EPSILON {
                for (i, frame) in frames.iter_mut().enumerate() {
                    let frac: f32 = (i as f32) / (count as f32);
                    let corr: f32 = -twist_error * frac;
                    let c: f32 = corr.cos();
                    let s: f32 = corr.sin();
                    let old_n: Vec3 = frame.get_normal();
                    let old_b: Vec3 = frame.get_binormal();
                    let new_n: Vec3 = safe_unit_normal(old_n.scale(c).add(old_b.scale(s)));
                    let new_b: Vec3 = safe_unit_normal(frame.get_tangent().cross(new_n));
                    frame.set_normal(new_n);
                    frame.set_binormal(new_b);
                }
            }
        }
        frames
    }
}