game-toolkit-dosvideo 0.3.0

DOS-era PC graphics and sound for game-toolkit: VGA, Mode X, EGA, CGA, Hercules, Tandy and VESA SVGA at the register level, a beam-accurate CRT, a CRT shader and the PC speaker
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
//! A GPU post-filter that makes the picture look like it is on a CRT: scanlines with a beam
//! that widens on bright pixels, horizontal beam blur (which melts dither patterns into
//! colors, as artists of the era counted on), an RGB phosphor mask, bloom, curvature and a
//! vignette.

use game_toolkit::prelude::*;

use crate::palette::Phosphor;

/// The phosphor arrangement behind the glass.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum PhosphorMask {
    /// No mask: monochrome monitors, or a perfect screen.
    #[default]
    None,
    /// Vertical R, G, B stripes (Trinitron, many later VGA monitors).
    ApertureGrille,
    /// R, G, B slots in staggered columns (most TVs and consumer monitors).
    SlotMask,
    /// R, G, B dot triads in offset rows (classic shadow mask).
    ShadowMask,
}

/// CRT filter settings. Start from a preset ([`CrtFilter::vga_monitor`], [`CrtFilter::tv`],
/// ...) and adjust.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct CrtFilter {
    /// 0 = no scanline structure, 1 = full beam profile with dark gaps.
    pub scanlines: f32,
    /// Beam height (Gaussian sigma, in scanlines) of dark and of bright pixels. Bright pixels
    /// bloom wider and close the gaps, like a real beam.
    pub beam_min: f32,
    pub beam_max: f32,
    /// Horizontal blur of the beam spot, in dots (sigma). ~0.3 is sharp, ~1 is a TV.
    pub blur: f32,
    pub mask: PhosphorMask,
    /// 0..1, how dark the "wrong" phosphors are.
    pub mask_strength: f32,
    /// Width of one R+G+B triad in window pixels. Below ~3 the mask fades out.
    pub mask_pitch: f32,
    /// Overall gain, to make up for light lost to the mask and the gaps.
    pub brightness: f32,
    /// Glow around bright areas.
    pub bloom: f32,
    /// Barrel distortion of a curved tube, 0 = flat.
    pub curvature: f32,
    /// Darkening towards the edges, 0..1.
    pub vignette: f32,
    /// Corner rounding as a fraction of the picture height.
    pub corner_radius: f32,
    /// A monochrome monitor: show only brightness, in this phosphor's color. A color adapter
    /// on a green or amber screen looked like this (colors became shades).
    pub monochrome: Option<Phosphor>,
}

impl CrtFilter {
    /// Sharp pixels with clean scanlines: a high-quality monitor, or a modern "scanline" look.
    pub fn crisp() -> Self {
        Self {
            scanlines: 0.7,
            beam_min: 0.28,
            beam_max: 0.42,
            blur: 0.3,
            mask: PhosphorMask::None,
            mask_strength: 0.0,
            mask_pitch: 3.0,
            brightness: 1.1,
            bloom: 0.0,
            curvature: 0.0,
            vignette: 0.0,
            corner_radius: 0.0,
            monochrome: None,
        }
    }

    /// A 14" VGA monitor: fine aperture grille, light blur, slight curvature.
    pub fn vga_monitor() -> Self {
        Self {
            scanlines: 0.55,
            beam_min: 0.3,
            beam_max: 0.55,
            blur: 0.5,
            mask: PhosphorMask::ApertureGrille,
            mask_strength: 0.3,
            mask_pitch: 3.0,
            brightness: 1.3,
            bloom: 0.1,
            curvature: 0.02,
            vignette: 0.2,
            corner_radius: 0.02,
            monochrome: None,
        }
    }

    /// A consumer TV on composite or RF: blurry, slot mask, strong glow, curved glass.
    pub fn tv() -> Self {
        Self {
            scanlines: 0.85,
            beam_min: 0.25,
            beam_max: 0.6,
            blur: 1.0,
            mask: PhosphorMask::SlotMask,
            mask_strength: 0.4,
            mask_pitch: 4.0,
            brightness: 1.5,
            bloom: 0.3,
            curvature: 0.07,
            vignette: 0.4,
            corner_radius: 0.06,
            monochrome: None,
        }
    }

    /// A monochrome monitor (Hercules, MDA, or a color card on a cheap green or amber screen):
    /// no mask, a long-glowing phosphor, and only shades of the phosphor color.
    pub fn mono_monitor(phosphor: Phosphor) -> Self {
        Self {
            scanlines: 0.6,
            beam_min: 0.3,
            beam_max: 0.55,
            blur: 0.55,
            mask: PhosphorMask::None,
            mask_strength: 0.0,
            mask_pitch: 3.0,
            brightness: 1.15,
            bloom: 0.35,
            curvature: 0.03,
            vignette: 0.25,
            corner_radius: 0.03,
            monochrome: Some(phosphor),
        }
    }

    /// The optics of a monochrome monitor (no mask, soft beam, glowing phosphor) with the
    /// colors kept: a dreamy, forgiving look rather than a historical one.
    pub fn soft_glow() -> Self {
        Self {
            monochrome: None,
            ..Self::mono_monitor(Phosphor::White)
        }
    }

    /// The presets with a name each, in the order Alt+C cycles them (after "off").
    pub fn presets() -> [(&'static str, CrtFilter); 6] {
        [
            ("crisp scanlines", Self::crisp()),
            ("soft glow", Self::soft_glow()),
            ("VGA monitor", Self::vga_monitor()),
            ("TV", Self::tv()),
            ("green screen", Self::mono_monitor(Phosphor::Green)),
            ("amber screen", Self::mono_monitor(Phosphor::Amber)),
        ]
    }

    fn uniforms(&self, rect: [f32; 4], tex: [f32; 2], region: [f32; 4]) -> [u8; UNIFORM_SIZE] {
        let mask = match self.mask {
            PhosphorMask::None => 0.0,
            PhosphorMask::ApertureGrille => 1.0,
            PhosphorMask::SlotMask => 2.0,
            PhosphorMask::ShadowMask => 3.0,
        };
        // The phosphor color in linear light, w = 1 when monochrome is on.
        let mono = self.monochrome.map_or([0.0; 4], |p| {
            let c = p.bright().map(|v| {
                let s = v as f32 / 255.0;
                if s <= 0.04045 {
                    s / 12.92
                } else {
                    ((s + 0.055) / 1.055).powf(2.4)
                }
            });
            [c[0], c[1], c[2], 1.0]
        });
        let v: [f32; UNIFORM_SIZE / 4] = [
            rect[0],
            rect[1],
            rect[2],
            rect[3],
            tex[0],
            tex[1],
            region[0],
            region[1],
            region[2],
            region[3],
            0.0,
            0.0,
            self.scanlines,
            self.beam_min.max(0.05),
            self.beam_max.max(0.05),
            self.blur,
            mask,
            self.mask_strength,
            self.mask_pitch,
            self.brightness,
            self.bloom,
            self.curvature,
            self.vignette,
            self.corner_radius,
            mono[0],
            mono[1],
            mono[2],
            mono[3],
        ];
        let mut out = [0u8; UNIFORM_SIZE];
        for (i, f) in v.iter().enumerate() {
            out[i * 4..i * 4 + 4].copy_from_slice(&f.to_le_bytes());
        }
        out
    }
}

/// Bytes of the `Params` uniform block in the shader: 7 x vec4<f32>.
const UNIFORM_SIZE: usize = 112;

/// GPU resources of the filter.
pub(crate) struct CrtPass {
    pipeline: wgpu::RenderPipeline,
    bgl: wgpu::BindGroupLayout,
    sampler: wgpu::Sampler,
    uniforms: wgpu::Buffer,
    texture: Option<(wgpu::Texture, wgpu::BindGroup, u32, u32)>,
    /// One-shot warnings, so a per-frame failure is reported once instead of every frame.
    warned: Warnings,
}

/// Which one-shot warnings [`CrtPass`] has already printed.
#[derive(Default)]
struct Warnings {
    indexed: std::sync::atomic::AtomicBool,
    no_encoder: std::sync::atomic::AtomicBool,
}

impl Warnings {
    fn first(&self, flag: &std::sync::atomic::AtomicBool) -> bool {
        !flag.swap(true, std::sync::atomic::Ordering::Relaxed)
    }
}

impl CrtPass {
    pub fn new(gfx: &Graphics) -> Self {
        let device = gfx.device();
        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("dosvideo.crt.shader"),
            source: wgpu::ShaderSource::Wgsl(include_str!("crt_filter.wgsl").into()),
        });
        let tex_entry = |binding, ty| wgpu::BindGroupLayoutEntry {
            binding,
            visibility: wgpu::ShaderStages::FRAGMENT,
            ty,
            count: None,
        };
        let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("dosvideo.crt.bgl"),
            entries: &[
                tex_entry(
                    0,
                    wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                ),
                tex_entry(
                    1,
                    wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                ),
                tex_entry(
                    2,
                    wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                ),
            ],
        });
        let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("dosvideo.crt.layout"),
            bind_group_layouts: &[Some(&bgl)],
            immediate_size: 0,
        });
        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("dosvideo.crt.pipeline"),
            layout: Some(&layout),
            vertex: wgpu::VertexState {
                module: &shader,
                entry_point: Some("vs_main"),
                compilation_options: Default::default(),
                buffers: &[],
            },
            fragment: Some(wgpu::FragmentState {
                module: &shader,
                entry_point: Some("fs_main"),
                compilation_options: Default::default(),
                targets: &[Some(wgpu::ColorTargetState {
                    format: gfx.surface_format(),
                    blend: None,
                    write_mask: wgpu::ColorWrites::ALL,
                })],
            }),
            primitive: wgpu::PrimitiveState::default(),
            depth_stencil: None,
            multisample: wgpu::MultisampleState::default(),
            multiview_mask: None,
            cache: None,
        });
        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("dosvideo.crt.sampler"),
            address_mode_u: wgpu::AddressMode::ClampToEdge,
            address_mode_v: wgpu::AddressMode::ClampToEdge,
            address_mode_w: wgpu::AddressMode::ClampToEdge,
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            ..Default::default()
        });
        let uniforms = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("dosvideo.crt.uniforms"),
            size: UNIFORM_SIZE as u64,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        Self {
            pipeline,
            bgl,
            sampler,
            uniforms,
            texture: None,
            warned: Warnings::default(),
        }
    }

    /// Upload a frame (RGBA8, sRGB).
    pub fn upload(&mut self, gfx: &Graphics, w: u32, h: u32, rgba: &[u8]) {
        let device = gfx.device();
        if !matches!(&self.texture, Some((_, _, tw, th)) if *tw == w && *th == h) {
            let texture = device.create_texture(&wgpu::TextureDescriptor {
                label: Some("dosvideo.crt.source"),
                size: wgpu::Extent3d {
                    width: w,
                    height: h,
                    depth_or_array_layers: 1,
                },
                mip_level_count: 1,
                sample_count: 1,
                dimension: wgpu::TextureDimension::D2,
                format: wgpu::TextureFormat::Rgba8UnormSrgb,
                usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
                view_formats: &[],
            });
            let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
            let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some("dosvideo.crt.bg"),
                layout: &self.bgl,
                entries: &[
                    wgpu::BindGroupEntry {
                        binding: 0,
                        resource: wgpu::BindingResource::TextureView(&view),
                    },
                    wgpu::BindGroupEntry {
                        binding: 1,
                        resource: wgpu::BindingResource::Sampler(&self.sampler),
                    },
                    wgpu::BindGroupEntry {
                        binding: 2,
                        resource: self.uniforms.as_entire_binding(),
                    },
                ],
            });
            self.texture = Some((texture, bg, w, h));
        }
        let Some((texture, ..)) = &self.texture else {
            return;
        };
        gfx.queue().write_texture(
            wgpu::TexelCopyTextureInfo {
                texture,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            rgba,
            wgpu::TexelCopyBufferLayout {
                offset: 0,
                bytes_per_row: Some(4 * w),
                rows_per_image: Some(h),
            },
            wgpu::Extent3d {
                width: w,
                height: h,
                depth_or_array_layers: 1,
            },
        );
    }

    /// Draw the uploaded frame into `rect` (drawing pixels, as [`Graphics::size`]), showing
    /// `region` (dots) of it.
    pub fn draw(
        &self,
        gfx: &Graphics,
        frame: &mut Frame,
        filter: &CrtFilter,
        rect: [f32; 4],
        region: [f32; 4],
    ) {
        let Some((_, bg, tw, th)) = &self.texture else {
            return;
        };
        // With indexed colour the target holds palette indices, not colours: drawing the
        // filtered picture there would turn it into garbage indices.
        if frame.target_is_indexed() {
            if self.warned.first(&self.warned.indexed) {
                eprintln!("dosvideo: CRT filter skipped, the toolkit's indexed colour is on");
            }
            return;
        }
        let (ww, wh) = gfx.size();
        // Clip the rectangle to the target for the viewport; the shader works in absolute
        // target coordinates, so clipping does not move the picture.
        let x0 = rect[0].max(0.0);
        let y0 = rect[1].max(0.0);
        let x1 = (rect[0] + rect[2]).min(ww as f32);
        let y1 = (rect[1] + rect[3]).min(wh as f32);
        if x1 - x0 < 1.0 || y1 - y0 < 1.0 {
            return;
        }
        gfx.queue().write_buffer(
            &self.uniforms,
            0,
            &filter.uniforms(rect, [*tw as f32, *th as f32], region),
        );
        // Draw where the painter drew: the toolkit's canvas when it has one (a virtual
        // resolution or post effects), which is scaled onto the window after this pass.
        let view = frame.target_view().clone();
        let Some(encoder) = frame.encoder_mut() else {
            if self.warned.first(&self.warned.no_encoder) {
                eprintln!("dosvideo: CRT filter skipped, the frame has no command encoder");
            }
            return;
        };
        let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
            label: Some("dosvideo.crt.pass"),
            color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                view: &view,
                depth_slice: None,
                resolve_target: None,
                ops: wgpu::Operations {
                    load: wgpu::LoadOp::Load,
                    store: wgpu::StoreOp::Store,
                },
            })],
            depth_stencil_attachment: None,
            occlusion_query_set: None,
            timestamp_writes: None,
            multiview_mask: None,
        });
        pass.set_viewport(x0, y0, x1 - x0, y1 - y0, 0.0, 1.0);
        pass.set_scissor_rect(x0 as u32, y0 as u32, (x1 - x0) as u32, (y1 - y0) as u32);
        pass.set_pipeline(&self.pipeline);
        pass.set_bind_group(0, bg, &[]);
        pass.draw(0..3, 0..1);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The pass holds only `Send + Sync` GPU resources, so a [`DosScreen`] that owns one stays
    /// shareable across threads.
    #[test]
    fn crt_pass_is_send_and_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<CrtPass>();
        assert_send_sync::<crate::DosScreen>();
    }
}