euv-core 0.56.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
477
478
479
480
481
use super::*;

/// Sanitizes a floating-point scalar by substituting `fallback` when NaN or infinite.
///
/// # Arguments
///
/// - `f32` - Candidate scalar value.
/// - `f32` - Safe finite fallback.
///
/// # Returns
///
/// - `f32` - Guaranteed finite floating-point value.
pub(crate) fn mesher_sanitize_f32(value: f32, fallback: f32) -> f32 {
    if value.is_finite() { value } else { fallback }
}

/// Evaluates the smooth C2 Wyvill metaball kernel `(1 - q^2)^3` for squared normalized distance `q_sq`.
///
/// # Arguments
///
/// - `f32` - Squared normalized distance `(r / R)^2`.
///
/// # Returns
///
/// - `f32` - Smooth scalar weight in `[0.0, 1.0]`.
pub(crate) fn metaball_wyvill_kernel(q_sq: f32) -> f32 {
    if q_sq >= 1.0 {
        return 0.0;
    }
    let diff: f32 = (1.0 - q_sq).max(0.0);
    diff * diff * diff
}

/// Computes per-particle anisotropic inverse axis scales `(inv_rx, inv_ry, inv_rz)` from local particle variance.
///
/// # Arguments
///
/// - `&[Vec3]` - Input particle positions.
/// - `LiquidMesherConfig` - Active mesher configuration.
/// - `&mut Vec<Vec3>` - Output pre-allocated inverse scale buffer.
pub(crate) fn compute_anisotropic_scales(
    positions: &[Vec3],
    config: LiquidMesherConfig,
    out_scales: &mut Vec<Vec3>,
) {
    let radius: f32 = config.get_influence_radius();
    let inv_r: f32 = 1.0 / radius.max(1e-4);
    out_scales.clear();
    out_scales.resize(positions.len(), Vec3::splat(inv_r));
    if !config.get_anisotropic() || config.get_anisotropy_strength() <= 1e-4 || positions.len() < 4
    {
        return;
    }
    let search_r: f32 = radius * 1.5;
    let search_r_sq: f32 = search_r * search_r;
    let strength: f32 = config.get_anisotropy_strength().clamp(0.0, 0.85);
    let max_sample_check: usize = positions.len().min(512);
    for (idx, &pi) in positions.iter().enumerate() {
        let mut var_x: f32 = 0.0;
        let mut var_y: f32 = 0.0;
        let mut var_z: f32 = 0.0;
        let mut w_sum: f32 = 0.0;
        for &pj in positions.iter().take(max_sample_check) {
            let diff: Vec3 = pj.sub(pi);
            let d_sq: f32 = diff.length_sq();
            if d_sq > 1e-10 && d_sq < search_r_sq {
                let w: f32 = 1.0 - (d_sq / search_r_sq);
                var_x += w * diff.get_x() * diff.get_x();
                var_y += w * diff.get_y() * diff.get_y();
                var_z += w * diff.get_z() * diff.get_z();
                w_sum += w;
            }
        }
        if w_sum > 1e-5 {
            let sx: f32 = (var_x / w_sum).sqrt();
            let sy: f32 = (var_y / w_sum).sqrt();
            let sz: f32 = (var_z / w_sum).sqrt();
            let mean: f32 = ((sx + sy + sz) / 3.0).max(1e-4);
            let scale_x: f32 = (1.0 + strength * (sx / mean - 1.0)).clamp(0.65, 1.45);
            let scale_y: f32 = (1.0 + strength * (sy / mean - 1.0)).clamp(0.65, 1.45);
            let scale_z: f32 = (1.0 + strength * (sz / mean - 1.0)).clamp(0.65, 1.45);
            out_scales[idx] = Vec3::new(inv_r / scale_x, inv_r / scale_y, inv_r / scale_z);
        }
    }
}

/// Splats metaball particles onto the 3D scalar grid and returns the resolved `ScalarGrid3DDesc`.
///
/// # Arguments
///
/// - `&[Vec3]` - Finite particle positions.
/// - `LiquidMesherConfig` - Active mesher configuration.
/// - `&mut LiquidMesherScratch` - Reusable scalar-field scratch buffers.
///
/// # Returns
///
/// - `Option<ScalarGrid3DDesc>` - Populated scalar grid descriptor, or `None` when input is empty.
pub(crate) fn build_metaball_scalar_field_3d(
    positions: &[Vec3],
    config: LiquidMesherConfig,
    scratch: &mut LiquidMesherScratch,
) -> Option<ScalarGrid3DDesc> {
    if positions.is_empty() {
        return None;
    }
    let mut bounds: AxisAlignedBox3D = AxisAlignedBox3D::empty();
    let mut valid_count: usize = 0;
    for &p in positions.iter() {
        if p.get_x().is_finite() && p.get_y().is_finite() && p.get_z().is_finite() {
            bounds.expand_point(p);
            valid_count += 1;
        }
    }
    if valid_count == 0 {
        return None;
    }
    let radius: f32 = config.get_influence_radius();
    let base_voxel: f32 = config.get_voxel_size();
    let pad_m: f32 = radius + (config.get_padding_cells() as f32) * base_voxel;
    let origin: Vec3 = bounds.get_min().sub(Vec3::splat(pad_m));
    let upper: Vec3 = bounds.get_max().add(Vec3::splat(pad_m));
    let span: Vec3 = upper.sub(origin);
    let max_dim: usize = config.get_max_grid_dim();
    let max_extent: f32 = span
        .get_x()
        .max(span.get_y())
        .max(span.get_z())
        .max(base_voxel);
    let voxel_size: f32 = base_voxel.max(max_extent / (max_dim.saturating_sub(2).max(4) as f32));
    let nx: usize = ((span.get_x() / voxel_size).ceil() as usize + 1).clamp(4, max_dim);
    let ny: usize = ((span.get_y() / voxel_size).ceil() as usize + 1).clamp(4, max_dim);
    let nz: usize = ((span.get_z() / voxel_size).ceil() as usize + 1).clamp(4, max_dim);
    let total: usize = nx * ny * nz;
    let mut aniso_scales: Vec<Vec3> = take(scratch.get_mut_aniso_scales());
    compute_anisotropic_scales(positions, config, &mut aniso_scales);
    let mut field: Vec<f32> = take(scratch.get_mut_scalar_field());
    field.clear();
    field.resize(total, 0.0);
    let inv_voxel: f32 = 1.0 / voxel_size;
    let max_reach: f32 = radius * 1.5;
    let plane: usize = nx * ny;
    for (idx, &p) in positions.iter().enumerate() {
        if !p.get_x().is_finite() || !p.get_y().is_finite() || !p.get_z().is_finite() {
            continue;
        }
        let inv_scale: Vec3 = aniso_scales[idx];
        let rel: Vec3 = p.sub(origin);
        let cx: f32 = rel.get_x() * inv_voxel;
        let cy: f32 = rel.get_y() * inv_voxel;
        let cz: f32 = rel.get_z() * inv_voxel;
        let reach_cells: f32 = max_reach * inv_voxel;
        let x0: usize = (cx - reach_cells).floor().max(0.0) as usize;
        let x1: usize = (cx + reach_cells).ceil().min((nx - 1) as f32) as usize;
        let y0: usize = (cy - reach_cells).floor().max(0.0) as usize;
        let y1: usize = (cy + reach_cells).ceil().min((ny - 1) as f32) as usize;
        let z0: usize = (cz - reach_cells).floor().max(0.0) as usize;
        let z1: usize = (cz + reach_cells).ceil().min((nz - 1) as f32) as usize;
        for iz in z0..=z1 {
            let wz: f32 = origin.get_z() + iz as f32 * voxel_size;
            let qz: f32 = (wz - p.get_z()) * inv_scale.get_z();
            let qz2: f32 = qz * qz;
            if qz2 >= 1.0 {
                continue;
            }
            let z_off: usize = iz * plane;
            for iy in y0..=y1 {
                let wy: f32 = origin.get_y() + iy as f32 * voxel_size;
                let qy: f32 = (wy - p.get_y()) * inv_scale.get_y();
                let qyz2: f32 = qz2 + qy * qy;
                if qyz2 >= 1.0 {
                    continue;
                }
                let row: usize = z_off + iy * nx;
                for ix in x0..=x1 {
                    let wx: f32 = origin.get_x() + ix as f32 * voxel_size;
                    let qx: f32 = (wx - p.get_x()) * inv_scale.get_x();
                    let q_sq: f32 = qyz2 + qx * qx;
                    if q_sq < 1.0 {
                        field[row + ix] += metaball_wyvill_kernel(q_sq);
                    }
                }
            }
        }
    }
    scratch.set_scalar_field(field);
    scratch.set_aniso_scales(aniso_scales);
    Some(ScalarGrid3DDesc::new(nx, ny, nz, origin, voxel_size))
}

/// Samples the analytical outward unit normal `-grad(phi).normalize()` at continuous world position `world_pos`.
///
/// # Arguments
///
/// - `&[f32]` - Flat 3D scalar field slice.
/// - `ScalarGrid3DDesc` - Grid dimensions, origin, and voxel spacing.
/// - `Vec3` - World-space query point on the isosurface.
///
/// # Returns
///
/// - `Vec3` - Guaranteed finite outward unit normal vector.
pub(crate) fn sample_scalar_gradient_normal(
    field: &[f32],
    grid: ScalarGrid3DDesc,
    world_pos: Vec3,
) -> Vec3 {
    let nx: usize = grid.get_nx();
    let ny: usize = grid.get_ny();
    let nz: usize = grid.get_nz();
    let voxel: f32 = grid.get_voxel_size();
    let rel: Vec3 = world_pos.sub(grid.get_origin()).scale(1.0 / voxel);
    let gx: f32 = rel.get_x().clamp(0.0, (nx - 1) as f32);
    let gy: f32 = rel.get_y().clamp(0.0, (ny - 1) as f32);
    let gz: f32 = rel.get_z().clamp(0.0, (nz - 1) as f32);
    let eps: f32 = 0.5;
    let shape: (usize, usize, usize) = (nx, ny, nz);
    let (fx_p, _, _): (f32, f32, f32) =
        mac_sample_3d_with_bounds(field, shape, Vec3::new(gx + eps, gy, gz));
    let (fx_m, _, _): (f32, f32, f32) =
        mac_sample_3d_with_bounds(field, shape, Vec3::new(gx - eps, gy, gz));
    let (fy_p, _, _): (f32, f32, f32) =
        mac_sample_3d_with_bounds(field, shape, Vec3::new(gx, gy + eps, gz));
    let (fy_m, _, _): (f32, f32, f32) =
        mac_sample_3d_with_bounds(field, shape, Vec3::new(gx, gy - eps, gz));
    let (fz_p, _, _): (f32, f32, f32) =
        mac_sample_3d_with_bounds(field, shape, Vec3::new(gx, gy, gz + eps));
    let (fz_m, _, _): (f32, f32, f32) =
        mac_sample_3d_with_bounds(field, shape, Vec3::new(gx, gy, gz - eps));
    let grad: Vec3 = Vec3::new(fx_m - fx_p, fy_m - fy_p, fz_m - fz_p);
    let len: f32 = grad.length();
    if len.is_finite() && len > 1e-6 {
        grad.scale(1.0 / len)
    } else {
        Vec3::new(0.0, 1.0, 0.0)
    }
}

/// Runs watertight 256-case Marching Cubes over the 3D scalar field with O(1) edge vertex welding.
///
/// # Arguments
///
/// - `ScalarGrid3DDesc` - Grid dimensions, origin, and voxel spacing.
/// - `LiquidMesherConfig` - Extraction configuration (iso level, welding, gradient normals).
/// - `&mut LiquidMesherScratch` - Reusable scratch buffers containing `scalar_field` and `edge_vertices`.
/// - `&str` - Desired mesh asset name.
/// - `PbrMaterial` - Surface PBR material.
///
/// # Returns
///
/// - `Mesh3D` - Extracted watertight 3D liquid mesh with finite positions and unit normals.
pub(crate) fn run_marching_cubes_3d(
    grid: ScalarGrid3DDesc,
    config: LiquidMesherConfig,
    scratch: &mut LiquidMesherScratch,
    name: &str,
    material: PbrMaterial,
) -> Mesh3D {
    let nx: usize = grid.get_nx();
    let ny: usize = grid.get_ny();
    let nz: usize = grid.get_nz();
    let origin: Vec3 = grid.get_origin();
    let voxel: f32 = grid.get_voxel_size();
    let iso: f32 = config.get_iso_level();
    let weld: bool = config.get_weld_vertices();
    let grad_normals: bool = config.get_smooth_normals_from_gradient();
    let plane: usize = nx * ny;
    let field: Vec<f32> = take(scratch.get_mut_scalar_field());
    let mut edge_vertices: Vec<u32> = take(scratch.get_mut_edge_vertices());
    if weld {
        let edge_slots: usize = nx * ny * nz * 3;
        edge_vertices.clear();
        edge_vertices.resize(edge_slots, MC_UNASSIGNED_VERTEX);
    }
    let mut vertices: Vec<Vertex3D> = Vec::new();
    let mut indices: Vec<[u32; 3]> = Vec::new();
    for iz in 0..(nz - 1) {
        for iy in 0..(ny - 1) {
            for ix in 0..(nx - 1) {
                let mut vals: [f32; 8] = [0.0; 8];
                let mut mask: usize = 0;
                for corner in 0..8 {
                    let off: [usize; 3] = FLUID_MC_CORNER_OFFSETS[corner];
                    let cx: usize = ix + off[0];
                    let cy: usize = iy + off[1];
                    let cz: usize = iz + off[2];
                    let val: f32 = field[cz * plane + cy * nx + cx];
                    vals[corner] = val;
                    if val >= iso {
                        mask |= 1usize << corner;
                    }
                }
                if mask == 0 || mask == 255 {
                    continue;
                }
                let tri_row: [i8; 16] = FLUID_MC_TRI_TABLE[mask];
                let mut tri_cursor: usize = 0;
                while tri_cursor < 15 && tri_row[tri_cursor] >= 0 {
                    let mut tri_v: [u32; 3] = [0; 3];
                    for slot in 0..3 {
                        let edge_id: usize = tri_row[tri_cursor + slot] as usize;
                        let edge_slot_off: [usize; 4] = MC_EDGE_SLOT_OFFSET[edge_id];
                        let ex: usize = ix + edge_slot_off[0];
                        let ey: usize = iy + edge_slot_off[1];
                        let ez: usize = iz + edge_slot_off[2];
                        let axis: usize = edge_slot_off[3];
                        let flat_edge: usize = ((ez * plane + ey * nx + ex) * 3) + axis;
                        if weld && edge_vertices[flat_edge] != MC_UNASSIGNED_VERTEX {
                            tri_v[slot] = edge_vertices[flat_edge];
                            continue;
                        }
                        let [c0, c1]: [usize; 2] = FLUID_MC_EDGE_CORNERS[edge_id];
                        let v0: f32 = vals[c0];
                        let v1: f32 = vals[c1];
                        let denom: f32 = v1 - v0;
                        let t: f32 = if denom.abs() > 1e-6 {
                            ((iso - v0) / denom).clamp(0.0, 1.0)
                        } else {
                            0.5
                        };
                        let o0: [usize; 3] = FLUID_MC_CORNER_OFFSETS[c0];
                        let o1: [usize; 3] = FLUID_MC_CORNER_OFFSETS[c1];
                        let p0: Vec3 = Vec3::new(
                            origin.get_x() + (ix + o0[0]) as f32 * voxel,
                            origin.get_y() + (iy + o0[1]) as f32 * voxel,
                            origin.get_z() + (iz + o0[2]) as f32 * voxel,
                        );
                        let p1: Vec3 = Vec3::new(
                            origin.get_x() + (ix + o1[0]) as f32 * voxel,
                            origin.get_y() + (iy + o1[1]) as f32 * voxel,
                            origin.get_z() + (iz + o1[2]) as f32 * voxel,
                        );
                        let pos: Vec3 = p0.lerp(p1, t);
                        let normal: Vec3 = if grad_normals {
                            sample_scalar_gradient_normal(&field, grid, pos)
                        } else {
                            Vec3::new(0.0, 1.0, 0.0)
                        };
                        let vid: u32 = vertices.len() as u32;
                        vertices.push(Vertex3D::new(pos, normal));
                        if weld {
                            edge_vertices[flat_edge] = vid;
                        }
                        tri_v[slot] = vid;
                    }
                    if tri_v[0] != tri_v[1] && tri_v[1] != tri_v[2] && tri_v[2] != tri_v[0] {
                        indices.push(tri_v);
                    }
                    tri_cursor += 3;
                }
            }
        }
    }
    scratch.set_scalar_field(field);
    scratch.set_edge_vertices(edge_vertices);
    let mesh_name: String = if name.is_empty() {
        LIQUID_MESHER_DEFAULT_NAME.to_string()
    } else {
        name.to_string()
    };
    let mut mesh: Mesh3D = Mesh3D::from_parts(mesh_name, vertices, indices, material);
    if !grad_normals {
        mesh.compute_smooth_normals();
    }
    mesh.set_is_closed(true);
    mesh
}

/// Rasterizes 2D liquid particles into a crisp anti-aliased RGBA8 metaball image using reusable scratch storage.
///
/// # Arguments
///
/// - `&[Vec2]` - 2D world-space particle coordinates.
/// - `&LiquidRaster2DDesc` - Output dimensions, world bounds, metaball radius, and shading palette.
/// - `&mut LiquidMesherScratch` - Reusable 2D scalar buffer scratch.
/// - `&mut [u8]` - Destination RGBA8 buffer (`>= width * height * 4` bytes).
pub(crate) fn rasterize_metaballs_2d_impl(
    positions: &[Vec2],
    desc: &LiquidRaster2DDesc,
    scratch: &mut LiquidMesherScratch,
    out_rgba: &mut [u8],
) {
    let width: usize = desc.get_width();
    let height: usize = desc.get_height();
    let total: usize = width.saturating_mul(height);
    if total == 0 || out_rgba.len() < total * 4 {
        return;
    }
    let wmin: Vec2 = desc.get_world_min();
    let wmax: Vec2 = desc.get_world_max();
    let span_x: f32 = (wmax.get_x() - wmin.get_x()).abs().max(1e-4);
    let span_y: f32 = (wmax.get_y() - wmin.get_y()).abs().max(1e-4);
    let radius: f32 = mesher_sanitize_f32(desc.get_influence_radius(), 0.12).max(1e-4);
    let inv_r: f32 = 1.0 / radius;
    let iso: f32 = mesher_sanitize_f32(desc.get_iso_level(), 0.35).clamp(0.05, 5.0);
    let px_per_m_x: f32 = width as f32 / span_x;
    let px_per_m_y: f32 = height as f32 / span_y;
    let rad_px_x: f32 = radius * px_per_m_x;
    let rad_px_y: f32 = radius * px_per_m_y;
    let mut field: Vec<f32> = take(scratch.get_mut_raster_field());
    field.clear();
    field.resize(total, 0.0);
    for &p in positions.iter() {
        let px_w: f32 = p.get_x();
        let py_w: f32 = p.get_y();
        if !px_w.is_finite() || !py_w.is_finite() {
            continue;
        }
        let cx: f32 = (px_w - wmin.get_x()) * px_per_m_x;
        let cy: f32 = (wmax.get_y() - py_w) * px_per_m_y;
        let x0: usize = (cx - rad_px_x).floor().max(0.0) as usize;
        let x1: usize = (cx + rad_px_x).ceil().min((width - 1) as f32) as usize;
        let y0: usize = (cy - rad_px_y).floor().max(0.0) as usize;
        let y1: usize = (cy + rad_px_y).ceil().min((height - 1) as f32) as usize;
        for py in y0..=y1 {
            let wy: f32 = wmax.get_y() - (py as f32 + 0.5) / px_per_m_y;
            let qy: f32 = (wy - py_w) * inv_r;
            let qy2: f32 = qy * qy;
            if qy2 >= 1.0 {
                continue;
            }
            let row: usize = py * width;
            for px in x0..=x1 {
                let wx: f32 = wmin.get_x() + (px as f32 + 0.5) / px_per_m_x;
                let qx: f32 = (wx - px_w) * inv_r;
                let q_sq: f32 = qx * qx + qy2;
                if q_sq < 1.0 {
                    field[row + px] += metaball_wyvill_kernel(q_sq);
                }
            }
        }
    }
    let bg: [u8; 4] = desc.get_background_rgba();
    let bg_r: f32 = bg[0] as f32 / 255.0;
    let bg_g: f32 = bg[1] as f32 / 255.0;
    let bg_b: f32 = bg[2] as f32 / 255.0;
    let deep: Vec3 = desc.get_deep_color();
    let shallow: Vec3 = desc.get_shallow_color();
    let spec_col: Vec3 = desc.get_specular_color();
    let light_dir: Vec3 = Vec3::new(-0.45, 0.72, 0.52).normalize();
    let aa_band: f32 = (iso * 0.22).max(0.03);
    for py in 0..height {
        let row: usize = py * width;
        let row_up: usize = py.saturating_sub(1) * width;
        let row_dn: usize = (py + 1).min(height - 1) * width;
        for px in 0..width {
            let idx: usize = row + px;
            let val: f32 = field[idx];
            let base: usize = idx * 4;
            let cov: f32 = ((val - (iso - aa_band)) / (2.0 * aa_band)).clamp(0.0, 1.0);
            if cov <= 1e-4 {
                out_rgba[base] = bg[0];
                out_rgba[base + 1] = bg[1];
                out_rgba[base + 2] = bg[2];
                out_rgba[base + 3] = bg[3];
                continue;
            }
            let xl: usize = px.saturating_sub(1);
            let xr: usize = (px + 1).min(width - 1);
            let gx: f32 = field[row + xl] - field[row + xr];
            let gy: f32 = field[row_dn + px] - field[row_up + px];
            let normal: Vec3 = Vec3::new(gx * 2.5, gy * 2.5, 0.45).normalize();
            let depth_t: f32 = ((val - iso) / (iso * 2.5)).clamp(0.0, 1.0);
            let tint: Vec3 = shallow.lerp(deep, depth_t);
            let fresnel: f32 =
                (0.04 + 0.96 * (1.0 - normal.get_z().clamp(0.0, 1.0)).powi(4)).clamp(0.0, 1.0);
            let diff: f32 = (0.45 + 0.55 * normal.dot(light_dir).max(0.0)).clamp(0.0, 1.0);
            let half_v: Vec3 = light_dir.add(Vec3::new(0.0, 0.0, 1.0)).normalize();
            let spec: f32 = normal.dot(half_v).max(0.0).powi(18);
            let col: Vec3 = tint
                .scale(diff)
                .add(spec_col.scale(0.32 * fresnel + 0.72 * spec));
            let r: f32 = bg_r + (col.get_x().clamp(0.0, 1.0) - bg_r) * cov;
            let g: f32 = bg_g + (col.get_y().clamp(0.0, 1.0) - bg_g) * cov;
            let b: f32 = bg_b + (col.get_z().clamp(0.0, 1.0) - bg_b) * cov;
            out_rgba[base] = (r.clamp(0.0, 1.0) * 255.0).round() as u8;
            out_rgba[base + 1] = (g.clamp(0.0, 1.0) * 255.0).round() as u8;
            out_rgba[base + 2] = (b.clamp(0.0, 1.0) * 255.0).round() as u8;
            out_rgba[base + 3] = 255;
        }
    }
    scratch.set_raster_field(field);
}