sgl-3d 0.2.0

Caller-driven 3D rendering for SGL games, native and in the browser (WebGPU)
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
//! A caller-owned native loop with procedural content: geometry, an
//! environment and point, spot and rectangle lights added to a scene, lit by a
//! sun with a cascaded shadow, and exposed automatically.
//!
//! Run with `cargo run -p sgl-3d --example offscreen -- target/offscreen.png`.
//! Optional `--frames N`, `--light F` and `--emission F` vary the animation and
//! source intensities (the post's emission and its light). `--anisotropy 0.5` demonstrates authored tangent transport
//! and Enhanced reflections on the moving cube. `--alpha` adds a masked grate,
//! whose cut-out texels the sun's shadow passes through, and two overlapping
//! blended glass panes. The grate's base map is `grate.ktx2`, a BC7 mip chain
//! as a game's export step writes one (written by the `export_grate`
//! example); it needs `wgpu::Features::TEXTURE_COMPRESSION_BC`.
//! `--decals` projects painted hazard stripes, rough and matte, onto the
//! ground in front of the cube. `--motion-blur` blurs the moving cube along
//! its motion, `MotionBlur::Full` over the default shutter.
//! `--fog` fills the view with haze that the sun and lights scatter, denser
//! in a box over the cubes.
//! Printed pixel measurements are diagnostics,
//! not image QA.
use sgl_3d::glam::camera;
use sgl_3d::{
    AlphaMode, AutoExposure, Camera, CompensationCurve, Decal, DirectionalLight, DirectionalShadow,
    Fog, FogVolume, FrameInput, HemisphereLight, InstanceState, Light, LightShape, Mobility,
    Renderer, Scene,
    asset::{Asset, CompressedImage, CpuMesh, Image, Material, Vertex},
    environment::{EnvironmentMap, PmremAtlas},
    glam::{Mat4, Quat, Vec3},
    settings::{MotionBlur, RenderPreset, Settings},
};
use std::{error::Error, path::PathBuf};

struct Options {
    output: PathBuf,
    frames: u32,
    light: f32,
    emission: f32,
    anisotropy: f32,
    alpha: bool,
    decals: bool,
    motion_blur: bool,
    fog: bool,
}
impl Options {
    fn parse() -> Result<Self, Box<dyn Error>> {
        let mut options = Self {
            output: "target/sgl-3d-offscreen.png".into(),
            frames: 8,
            light: 3.,
            emission: 2.,
            anisotropy: 0.,
            alpha: false,
            decals: false,
            motion_blur: false,
            fog: false,
        };
        let mut args = std::env::args().skip(1);
        while let Some(arg) = args.next() {
            match arg.as_str() {
                "--frames" => {
                    options.frames = args.next().ok_or("--frames requires a count")?.parse()?
                }
                "--light" => {
                    options.light = args
                        .next()
                        .ok_or("--light requires an intensity")?
                        .parse()?
                }
                "--anisotropy" => {
                    options.anisotropy = args
                        .next()
                        .ok_or("--anisotropy requires strength 0..1")?
                        .parse()?;
                }
                "--emission" => {
                    options.emission = args
                        .next()
                        .ok_or("--emission requires an intensity")?
                        .parse()?
                }
                "--alpha" => options.alpha = true,
                "--decals" => options.decals = true,
                "--motion-blur" => options.motion_blur = true,
                "--fog" => options.fog = true,
                "--help" | "-h" => {
                    println!(
                        "offscreen [output.png] [--frames N] [--light F] [--emission F] [--anisotropy F] [--alpha] [--decals] [--motion-blur] [--fog]"
                    );
                    std::process::exit(0);
                }
                flag if flag.starts_with('-') => {
                    return Err(format!("unknown option {flag}").into());
                }
                _ => options.output = arg.into(),
            }
        }
        if options.frames == 0 {
            return Err("--frames must be at least one".into());
        }
        if !(0.0..=1.0).contains(&options.anisotropy) {
            return Err("anisotropy strength must be finite in 0..1".into());
        }
        if !options.light.is_finite()
            || options.light < 0.
            || !options.emission.is_finite()
            || options.emission < 0.
        {
            return Err("light and emission intensities must be finite and nonnegative".into());
        }
        Ok(options)
    }
}

fn material(base: [f32; 4], emissive: [f32; 3], metallic: f32, roughness: f32) -> Material {
    Material {
        name: "procedural surface".into(),
        base,
        emissive,
        metallic,
        roughness,
        coat_roughness: 0.3,
        ..Default::default() // glTF's default material
    }
}

fn cuboid(center: Vec3, size: Vec3, material: usize) -> CpuMesh {
    let half = size * 0.5;
    let mut mesh = CpuMesh {
        vertices: Vec::new(),
        indices: Vec::new(),
        material,
        deformation: Default::default(),
    };
    for (normal, u, v) in [
        (Vec3::X, -Vec3::Z, Vec3::Y),
        (-Vec3::X, Vec3::Z, Vec3::Y),
        (Vec3::Y, Vec3::X, -Vec3::Z),
        (-Vec3::Y, Vec3::X, Vec3::Z),
        (Vec3::Z, Vec3::X, Vec3::Y),
        (-Vec3::Z, -Vec3::X, Vec3::Y),
    ] {
        let start = mesh.vertices.len() as u32;
        for [s, t] in [[-1., -1.], [1., -1.], [1., 1.], [-1., 1.]] {
            mesh.vertices.push(Vertex {
                tangent: [u.x, u.y, u.z, 1.],
                lightmap_bounds: [0., 0., 1., 1.],
                lightmap_uv: [0.; 2],
                position: (center + (normal + u * s + v * t) * half).to_array(),
                normal: normal.to_array(),
                uv: [(s + 1.) * 0.5, (t + 1.) * 0.5],
                color: [1.; 4],
            });
        }
        mesh.indices.extend([0, 1, 2, 0, 2, 3].map(|i| start + i));
    }
    mesh
}

/// A double-sided quad at `center` spanning `u` and `v` (half extents), its
/// texture coordinates running 0..1 along them.
fn panel(center: Vec3, u: Vec3, v: Vec3, material: usize) -> CpuMesh {
    let normal = u.cross(v).normalize();
    CpuMesh {
        vertices: [[-1., -1.], [1., -1.], [1., 1.], [-1., 1.]]
            .map(|[s, t]| Vertex {
                tangent: [u.x, u.y, u.z, 1.],
                lightmap_bounds: [0., 0., 1., 1.],
                lightmap_uv: [0.; 2],
                position: (center + u * s + v * t).to_array(),
                normal: normal.to_array(),
                uv: [(s + 1.) * 0.5, (1. - t) * 0.5],
                color: [1.; 4],
            })
            .to_vec(),
        indices: vec![0, 1, 2, 0, 2, 3],
        material,
        deformation: Default::default(),
    }
}

/// A masked grate over the ground, which the sun shadows through its holes,
/// and two overlapping blended glass panes in front of the post.
fn alpha_content() -> Result<Asset, Box<dyn Error>> {
    // Square holes in a lattice of bars, block-compressed with its mips:
    // alpha 0 in the holes.
    let grate = CompressedImage::from_ktx2(include_bytes!("grate.ktx2"))?;
    let mut bars = material([0.6, 0.6, 0.62, 1.], [0.; 3], 0.8, 0.35);
    bars.base_texture = Some(0);
    bars.double_sided = true;
    bars.alpha = AlphaMode::Mask { cutoff: 0.5 };
    let glass = |base: [f32; 4]| Material {
        double_sided: true,
        alpha: AlphaMode::Blend {
            receives_screen_space_reflections: false,
        },
        ..material(base, [0.; 3], 0., 0.05)
    };
    Ok(Asset {
        meshes: vec![
            panel(Vec3::new(1.4, 2.4, 1.2), Vec3::X * 1.2, Vec3::Z * 1.2, 0),
            panel(Vec3::new(-1.2, 1., 1.9), Vec3::X * 0.7, Vec3::Y * 0.9, 1),
            panel(Vec3::new(-0.7, 0.8, 2.6), Vec3::X * 0.7, Vec3::Y * 0.7, 2),
        ],
        materials: vec![
            bars,
            glass([0.2, 0.5, 1., 0.35]),
            glass([1., 0.55, 0.15, 0.45]),
        ],
        images: vec![Image::Compressed(grate)],
        rig: Default::default(),
    })
}

/// Two strips of hazard paint on the ground: diagonal yellow and black
/// stripes whose alpha fades at their long edges, and a matte, rough
/// metallic-roughness image (roughness in green, metallic in blue), added
/// once as decal images and projected by two decals, the second turned.
fn add_decals(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    scene: &mut Scene,
) -> Result<(), Box<dyn Error>> {
    let stripes = image::RgbaImage::from_fn(128, 32, |x, y| {
        let paint = if (x + y) / 16 % 2 == 0 {
            [230, 170, 20]
        } else {
            [20, 20, 22]
        };
        let edge = y.min(31 - y).min(4) * 255 / 4;
        image::Rgba([paint[0], paint[1], paint[2], edge as u8])
    });
    let base_color = scene.add_decal_image(Image::Rgba8(stripes))?;
    let matte = image::RgbaImage::from_pixel(4, 4, image::Rgba([0, 230, 0, 255]));
    let metallic_roughness = scene.add_decal_image(Image::Rgba8(matte))?;
    let stripe = |position: Vec3, turn: f32| Decal {
        position,
        rotation: Quat::from_rotation_y(turn),
        // Shallow, so the paint keeps to the ground's top face.
        size: Vec3::new(2.4, 0.3, 0.6),
        metallic_roughness: Some(metallic_roughness),
        normal_fade: 0.5,
        ..Decal::new(base_color) // Godot's decal defaults
    };
    scene.add_decal(device, queue, stripe(Vec3::new(0.6, -0.05, 2.), 0.))?;
    scene.add_decal(device, queue, stripe(Vec3::new(2.4, -0.05, 0.6), 1.2))?;
    Ok(())
}

fn neutral_environment() -> EnvironmentMap {
    // A constant radiance field is unchanged by convolution at every roughness.
    // 16px cube faces need a 336x64 cube-UV atlas including the six extra filter
    // bands. RGBA16F texels encode exactly (1/32, 1/32, 1/32, 1).
    EnvironmentMap {
        panorama: image::RgbaImage::from_pixel(4, 2, image::Rgba([50, 50, 50, 255])),
        filtered: PmremAtlas {
            width: 336,
            height: 64,
            rgba16: [0x2800u16, 0x2800, 0x2800, 0x3c00]
                .into_iter()
                .flat_map(u16::to_le_bytes)
                .cycle()
                .take(336 * 64 * 8)
                .collect(),
        },
    }
}

fn read_pixels(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    texture: &wgpu::Texture,
) -> Result<Vec<u8>, Box<dyn Error>> {
    let stride = (texture.width() * 4).div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT)
        * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
    let buffer = device.create_buffer(&wgpu::BufferDescriptor {
        label: Some("offscreen image readback"),
        size: u64::from(stride) * u64::from(texture.height()),
        usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
        mapped_at_creation: false,
    });
    let mut encoder = device.create_command_encoder(&Default::default());
    encoder.copy_texture_to_buffer(
        texture.as_image_copy(),
        wgpu::TexelCopyBufferInfo {
            buffer: &buffer,
            layout: wgpu::TexelCopyBufferLayout {
                offset: 0,
                bytes_per_row: Some(stride),
                rows_per_image: Some(texture.height()),
            },
        },
        texture.size(),
    );
    queue.submit([encoder.finish()]);
    let (send, receive) = std::sync::mpsc::channel();
    buffer
        .slice(..)
        .map_async(wgpu::MapMode::Read, move |result| {
            let _ = send.send(result);
        });
    device.poll(wgpu::PollType::wait_indefinitely())?;
    receive.recv()??;
    let mapped = buffer.slice(..).get_mapped_range().unwrap();
    Ok(mapped
        .chunks_exact(stride as usize)
        .flat_map(|row| row[..texture.width() as usize * 4].iter().copied())
        .collect())
}

async fn run(options: Options) -> Result<(), Box<dyn Error>> {
    let adapter = wgpu::Instance::default()
        .request_adapter(&Default::default())
        .await?;
    let (device, queue) = adapter
        .request_device(&wgpu::DeviceDescriptor {
            required_features: (adapter.features()
                & (wgpu::Features::SHADER_F16 | wgpu::Features::TEXTURE_COMPRESSION_BC))
                | sgl_3d::graphics_device::features(&adapter),
            required_limits: sgl_3d::graphics_device::limits(&adapter),
            ..Default::default()
        })
        .await?;
    println!(
        "GPU: {} ({:?})",
        adapter.get_info().name,
        adapter.get_info().backend
    );
    let world = Asset {
        meshes: vec![
            cuboid(Vec3::new(0., -0.25, 0.), Vec3::new(10., 0.4, 8.), 0),
            cuboid(Vec3::new(-2.4, 1.1, 0.), Vec3::new(0.18, 2.2, 0.18), 1),
        ],
        materials: vec![
            material([0.12, 0.16, 0.2, 1.], [0.; 3], 0.1, 0.4),
            material(
                [0.02, 0.03, 0.04, 1.],
                [0.1, 0.55, 1.].map(|x| x * options.emission),
                0.,
                0.5,
            ),
        ],
        images: Vec::new(),
        rig: Default::default(),
    };
    let mut cube = Asset {
        meshes: vec![cuboid(Vec3::ZERO, Vec3::splat(1.6), 0)],
        materials: vec![material([0.7, 0.18, 0.05, 1.], [0.; 3], 0.25, 0.27)],
        images: Vec::new(),
        rig: Default::default(),
    };
    cube.materials[0].anisotropy_strength = options.anisotropy;
    cube.materials[0].anisotropy_rotation = std::f32::consts::FRAC_PI_4;
    let size = [320, 240];
    // Content is added once; each addition returns its identity.
    let mut scene = Scene::new(&device, &queue);
    let world = scene.add_asset(&device, &queue, world)?.model;
    scene.add_instance(&device, &queue, InstanceState::new(world), Mobility::Static)?;
    let cube = scene.add_asset(&device, &queue, cube)?.model;
    let mut moving = InstanceState::new(cube);
    let instance = scene.add_instance(&device, &queue, moving, Mobility::Moving)?;
    if options.alpha {
        let alpha = scene.add_asset(&device, &queue, alpha_content()?)?.model;
        scene.add_instance(&device, &queue, InstanceState::new(alpha), Mobility::Static)?;
    }
    if options.fog {
        // Denser haze in a box over the cubes, added to the frame's.
        scene.update_fog_volumes(
            &device,
            &queue,
            &[FogVolume {
                center: Vec3::new(0., 1.5, 0.),
                size: Vec3::new(6., 3., 6.),
                density: 0.15,
                albedo: [0.9, 0.95, 1.],
                edge_fade: 0.5,
                ..Default::default()
            }],
        )?;
    }
    if options.decals {
        add_decals(&device, &queue, &mut scene)?;
    }
    let environment = scene.add_environment(&device, &queue, &neutral_environment())?;
    // Point, spot and rectangle lights are content too: the post's light and
    // a lamp overhead, both casting the moving cube's shadow, and a strip
    // panel beside the ground.
    scene.add_light(
        &device,
        &queue,
        Light {
            position: Vec3::new(-2.1, 1.6, 0.3),
            shape: LightShape::Point {
                radius: LightShape::DEFAULT_RADIUS,
            },
            color: [0.1, 0.55, 1.],
            intensity: 2. * options.emission,
            range: 8.,
            baked: false,
            specular: 1.,
            casts_shadow: true,
            ..Default::default()
        },
    )?;
    scene.add_light(
        &device,
        &queue,
        Light {
            position: Vec3::new(1.8, 3.5, 1.5),
            shape: LightShape::Spot {
                direction: Vec3::NEG_Y,
                inner_angle: 0.35,
                outer_angle: 0.6,
                radius: LightShape::DEFAULT_RADIUS,
            },
            color: [1., 0.8, 0.6],
            intensity: 40.,
            range: 6.,
            baked: false,
            specular: 1.,
            casts_shadow: true,
            ..Default::default()
        },
    )?;
    scene.add_light(
        &device,
        &queue,
        Light {
            position: Vec3::new(0., 2.2, -2.),
            shape: LightShape::Rect {
                direction: Vec3::new(0., -0.6, 1.),
                width_axis: Vec3::X,
                width: 2.4,
                height: 0.3,
            },
            color: [0.7, 0.9, 1.],
            intensity: 12.,
            range: 7.,
            baked: false,
            specular: 1.,
            casts_shadow: false,
            ..Default::default()
        },
    )?;
    let output = device.create_texture(&wgpu::TextureDescriptor {
        label: Some("offscreen output"),
        size: wgpu::Extent3d {
            width: size[0],
            height: size[1],
            depth_or_array_layers: 1,
        },
        mip_level_count: 1,
        sample_count: 1,
        dimension: wgpu::TextureDimension::D2,
        format: wgpu::TextureFormat::Rgba8Unorm,
        usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
        view_formats: &[],
    });
    let output_view = output.create_view(&Default::default());
    // The game's rendering settings; a game stores this value.
    let settings = Settings {
        preset: RenderPreset::Low,
        atmosphere: options.fog,
        motion_blur: if options.motion_blur {
            MotionBlur::Full
        } else {
            MotionBlur::Off
        },
        ..Settings::default()
    };
    // A window's scale factor goes where the 1 is.
    let mut renderer = Renderer::new(&device, &queue, output.format(), size, 1., &settings)?;
    let eye = Vec3::new(6., 4., 7.);
    let view = camera::rh::view::look_at_mat4(eye, Vec3::new(0., 0.7, 0.), Vec3::Y);
    let projection = sgl_3d::perspective(50f32.to_radians(), size[0] as f32 / size[1] as f32, 0.1);
    let mut frame = FrameInput::new(Camera {
        view,
        projection,
        eye,
    });
    frame.environment = Some(environment);
    // The sun casts the scene's shadow in two cascades, which SGL3D fits
    // to the camera's view out to 20 m.
    frame.directional_lights[0] = Some(DirectionalLight {
        direction: Vec3::new(0.4, -1., -0.5),
        color: [1., 0.85, 0.7],
        illuminance: options.light,
        shadow: Some(DirectionalShadow {
            distance: 20.,
            cascades: 2,
        }),
        ..Default::default()
    });
    // A thin haze the sun scatters forward, thinning above 2 m, where the
    // settings allow the atmosphere.
    frame.atmosphere = true;
    frame.fog = Fog {
        density: 0.04,
        anisotropy: 0.5,
        height: 2.,
        height_falloff: 0.5,
        length: 40.,
        ..Fog::default()
    };
    frame.hemisphere_light = HemisphereLight {
        sky_color: [0.2, 0.3, 0.5],
        ground_color: [0.05, 0.03, 0.02],
        intensity: 0.2,
    };
    // Automatic exposure: the metered average luminance becomes middle grey
    // (2^-2.5), within two stops either way.
    frame.exposure.automatic = Some(AutoExposure {
        compensation: CompensationCurve::new(&[[0., -2.5]])?,
        correction_min: -2.,
        correction_max: 2.,
        ..Default::default()
    });
    let mut first = Vec::new();
    for frame_index in 0..options.frames {
        let phase = frame_index as f32 / options.frames.max(2) as f32;
        moving.pose = Mat4::from_translation(Vec3::new(-0.5 + phase, 0.85, 0.))
            * Mat4::from_rotation_y(phase);
        scene.set_instance(&queue, instance, moving)?;
        frame.elapsed_seconds = frame_index as f64 / 60.;
        frame.camera_cut = frame_index == 0;
        // Cheap when neither the output size nor the settings changed.
        renderer.resize(&device, size, 1., &settings);
        let mut encoder = device.create_command_encoder(&Default::default());
        renderer.render(
            &device,
            &queue,
            &mut encoder,
            &mut scene,
            &frame,
            &settings,
            &output_view,
            None,
        );
        queue.submit([encoder.finish()]);
        // After submitting: this frame becomes the next one's history.
        renderer.finish_frame(&mut scene);
        if frame_index == 0 {
            first = read_pixels(&device, &queue, &output)?;
        }
    }
    let pixels = read_pixels(&device, &queue, &output)?;
    let changed = pixels
        .chunks_exact(4)
        .zip(first.chunks_exact(4))
        .filter(|(last, first)| last[..3] != first[..3])
        .count();
    let mean = pixels
        .chunks_exact(4)
        .map(|p| 0.2126 * f64::from(p[0]) + 0.7152 * f64::from(p[1]) + 0.0722 * f64::from(p[2]))
        .sum::<f64>()
        / f64::from(size[0] * size[1]);
    if let Some(parent) = options
        .output
        .parent()
        .filter(|p| !p.as_os_str().is_empty())
    {
        std::fs::create_dir_all(parent)?;
    }
    image::save_buffer(
        &options.output,
        &pixels,
        size[0],
        size[1],
        image::ColorType::Rgba8,
    )?;
    println!(
        "Rendered {} frames, {}x{}, light={}, emission={}; mean encoded luma={mean:.3}/255, first/final changed pixels={changed}; {}",
        options.frames,
        size[0],
        size[1],
        options.light,
        options.emission,
        options.output.display()
    );
    Ok(())
}

fn main() -> Result<(), Box<dyn Error>> {
    pollster::block_on(run(Options::parse()?))
}