ratty 0.4.1

A GPU-rendered terminal emulator that supports inline 3D graphics
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
//! Scene setup and presentation resources.

mod mobius;

pub use mobius::{MobiusTransition, MobiusTransitionDirection};

use bevy::asset::RenderAssetUsages;
use bevy::camera::ClearColorConfig;
use bevy::ecs::query::With;
use bevy::ecs::system::SystemParam;
use bevy::image::ImageSampler;
use bevy::mesh::{Indices, PrimitiveTopology};
use bevy::prelude::*;
use bevy::render::render_resource::{Extent3d, Face, TextureDimension, TextureFormat};

use crate::config::AppConfig;
use crate::terminal::TerminalSurface;

/// Marker for the 2D terminal sprite.
#[derive(Component)]
pub struct TerminalSprite;

/// Marker for the front 3D terminal plane.
#[derive(Component)]
pub struct TerminalPlane;

/// Marker for the back 3D terminal plane.
#[derive(Component)]
pub struct TerminalPlaneBack;

/// Marker for the 3D presentation camera.
#[derive(Component)]
pub struct TerminalPlaneCamera;

/// Handles for terminal plane meshes.
#[derive(Resource)]
pub struct TerminalPlaneMeshes {
    /// Front plane mesh.
    pub front: Handle<Mesh>,
    /// Back plane mesh.
    pub back: Handle<Mesh>,
}

/// Plane warp state.
#[derive(Resource, Default)]
pub struct TerminalPlaneWarp {
    /// Warp amount.
    pub amount: f32,
}

impl TerminalPlaneWarp {
    /// Adjusts the warp amount.
    pub fn adjust(&mut self, delta: f32) {
        self.amount = (self.amount + delta).clamp(0.0, 1.0);
    }
}

/// Terminal viewport geometry.
#[derive(Resource, Clone, Copy)]
pub struct TerminalViewport {
    /// Viewport size in logical pixels.
    pub size: Vec2,
    /// Viewport center in world space.
    pub center: Vec2,
}

/// Terminal presentation mode.
#[derive(Resource, Clone, Copy, PartialEq, Eq)]
pub enum TerminalPresentationMode {
    /// Flat 2D presentation.
    Flat2d,
    /// Warped 3D presentation.
    Plane3d,
    /// Mobius-strip 3D presentation.
    Mobius3d,
}

impl TerminalPresentationMode {
    /// Returns whether the mode uses the 3D presentation camera and terminal plane.
    pub const fn is_3d(self) -> bool {
        !matches!(self, Self::Flat2d)
    }

    /// Returns whether the mode uses the Mobius-strip terminal surface.
    pub const fn is_mobius(self) -> bool {
        matches!(self, Self::Mobius3d)
    }
}

/// Active terminal presentation.
#[derive(Resource)]
pub struct TerminalPresentation {
    /// Current presentation mode.
    pub mode: TerminalPresentationMode,
}

impl TerminalPresentation {
    /// Toggles between the flat and warped 3D terminal views.
    pub fn toggle_plane_mode(&mut self) {
        self.mode = match self.mode {
            TerminalPresentationMode::Flat2d => TerminalPresentationMode::Plane3d,
            TerminalPresentationMode::Plane3d | TerminalPresentationMode::Mobius3d => {
                TerminalPresentationMode::Flat2d
            }
        };
    }

    /// Toggles the Mobius-strip terminal view.
    pub fn toggle_mobius_mode(&mut self) {
        self.mode = match self.mode {
            TerminalPresentationMode::Mobius3d => TerminalPresentationMode::Flat2d,
            TerminalPresentationMode::Flat2d | TerminalPresentationMode::Plane3d => {
                TerminalPresentationMode::Mobius3d
            }
        };
    }
}

/// Camera state for 3D presentation.
#[derive(Resource)]
pub struct TerminalPlaneView {
    /// Camera yaw.
    pub yaw: f32,
    /// Camera pitch.
    pub pitch: f32,
    /// Camera zoom factor.
    pub zoom: f32,
    /// Camera pan offset.
    pub camera_offset: Vec2,
    /// Indicates drag rotation.
    pub rotating: bool,
    /// Indicates drag panning.
    pub panning: bool,
    /// Last rotation cursor position.
    pub last_rotate_cursor: Option<Vec2>,
    /// Last pan cursor position.
    pub last_pan_cursor: Option<Vec2>,
}

impl Default for TerminalPlaneView {
    fn default() -> Self {
        Self {
            yaw: 0.18,
            pitch: 0.08,
            zoom: 1.0,
            camera_offset: Vec2::ZERO,
            rotating: false,
            panning: false,
            last_rotate_cursor: None,
            last_pan_cursor: None,
        }
    }
}

/// Model loading state.
#[derive(Resource)]
pub struct ModelLoadState {
    /// Indicates the scene has loaded models.
    pub loaded: bool,
    /// Indicates the first terminal frame was uploaded.
    pub first_frame_uploaded: bool,
}

type SpriteVisibilityQuery<'w, 's> = Query<'w, 's, &'static mut Visibility, With<TerminalSprite>>;
type PlaneVisibilityQuery<'w, 's> = Query<'w, 's, &'static mut Visibility, With<TerminalPlane>>;
type PlaneBackVisibilityQuery<'w, 's> =
    Query<'w, 's, &'static mut Visibility, With<TerminalPlaneBack>>;
type PlaneMaterialQuery<'w, 's> =
    Query<'w, 's, &'static MeshMaterial3d<StandardMaterial>, With<TerminalPlane>>;
type PlaneTransformQuery<'w, 's> = Query<'w, 's, &'static mut Transform, With<TerminalPlane>>;
type PlaneBackTransformQuery<'w, 's> =
    Query<'w, 's, &'static mut Transform, With<TerminalPlaneBack>>;
type PlaneCameraQuery<'w, 's> =
    Query<'w, 's, (&'static mut Projection, &'static mut Transform), With<TerminalPlaneCamera>>;

#[derive(SystemParam)]
pub(crate) struct PresentationParams<'w, 's> {
    visibility_queries: ParamSet<
        'w,
        's,
        (
            SpriteVisibilityQuery<'w, 's>,
            PlaneVisibilityQuery<'w, 's>,
            PlaneBackVisibilityQuery<'w, 's>,
        ),
    >,
    plane_materials: PlaneMaterialQuery<'w, 's>,
    materials: ResMut<'w, Assets<StandardMaterial>>,
    plane_transforms: ParamSet<
        'w,
        's,
        (
            PlaneTransformQuery<'w, 's>,
            PlaneBackTransformQuery<'w, 's>,
            PlaneCameraQuery<'w, 's>,
        ),
    >,
}

/// Sets up the terminal presentation scene.
///
/// This startup system creates the 2D and 3D cameras, terminal sprite, terminal plane meshes,
/// backing images, lighting and presentation resources used by later update systems.
pub fn setup_scene(
    mut commands: Commands,
    app_config: Res<AppConfig>,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
    mut images: ResMut<Assets<Image>>,
    mut terminal: NonSendMut<TerminalSurface>,
) {
    let terminal_opacity = app_config.window.opacity.clamp(0.0, 1.0);

    commands.spawn((
        Camera2d,
        Camera {
            order: 0,
            ..default()
        },
        Msaa::Off,
    ));
    commands.spawn((
        TerminalPlaneCamera,
        Camera3d::default(),
        Camera {
            order: 1,
            clear_color: ClearColorConfig::None,
            ..default()
        },
        Projection::Orthographic(OrthographicProjection {
            near: -2000.0,
            far: 2000.0,
            ..OrthographicProjection::default_3d()
        }),
        Transform::from_xyz(0.0, 0.0, 800.0).looking_at(Vec3::ZERO, Vec3::Y),
        Msaa::Off,
    ));

    let pixmap = terminal.pixmap_dimensions();
    let pixmap_width = pixmap.x;
    let pixmap_height = pixmap.y;

    let terminal_alpha = (terminal_opacity * 255.0).round() as u8;
    let mut image = create_terminal_image(pixmap_width, pixmap_height, [0, 0, 0, 0]);
    image.data = Some(vec![0; (pixmap_width * pixmap_height * 4) as usize]);

    let image_handle = images.add(image);
    terminal.image_handle = Some(image_handle.clone());

    let [r, g, b] = app_config.theme.background;
    let back_image = create_terminal_image(
        pixmap_width,
        pixmap_height,
        [
            r.saturating_sub(13),
            g.saturating_sub(11),
            b.saturating_sub(3),
            terminal_alpha,
        ],
    );
    let back_image_handle = images.add(back_image);
    terminal.back_image_handle = Some(back_image_handle.clone());

    let viewport_size = Vec2::new(
        app_config.window.width as f32,
        app_config.window.height as f32,
    );
    let viewport_center = Vec2::ZERO;
    commands.insert_resource(TerminalViewport {
        size: viewport_size,
        center: viewport_center,
    });

    let mut sprite = Sprite::from_image(image_handle);
    sprite.custom_size = Some(viewport_size);
    sprite.color = Color::srgba(1.0, 1.0, 1.0, terminal_opacity);
    commands.spawn((
        TerminalSprite,
        sprite,
        Transform::from_translation(Vec3::new(viewport_center.x, viewport_center.y, 0.0)),
    ));

    let front_mesh = meshes.add(terminal_plane_mesh(32, 20));
    let back_mesh = meshes.add(terminal_plane_mesh(32, 20));
    commands.insert_resource(TerminalPlaneMeshes {
        front: front_mesh.clone(),
        back: back_mesh.clone(),
    });
    commands.insert_resource(TerminalPlaneWarp::default());

    commands.spawn((
        TerminalPlane,
        Mesh3d(front_mesh),
        MeshMaterial3d(materials.add(StandardMaterial {
            base_color: Color::srgba(1.0, 1.0, 1.0, terminal_opacity),
            base_color_texture: terminal.image_handle.clone(),
            alpha_mode: AlphaMode::Blend,
            unlit: true,
            ..default()
        })),
        Transform::from_scale(viewport_size.extend(1.0)),
        Visibility::Hidden,
    ));

    commands.spawn((
        TerminalPlaneBack,
        Mesh3d(back_mesh),
        MeshMaterial3d(materials.add(StandardMaterial {
            base_color: Color::srgba(1.0, 1.0, 1.0, terminal_opacity),
            base_color_texture: terminal.back_image_handle.clone(),
            alpha_mode: AlphaMode::Blend,
            unlit: true,
            ..default()
        })),
        Transform {
            translation: Vec3::new(0.0, 0.0, -2.0),
            rotation: Quat::from_rotation_y(std::f32::consts::PI),
            scale: viewport_size.extend(1.0),
        },
        Visibility::Hidden,
    ));

    commands.spawn((
        PointLight {
            intensity: 190_000.0,
            range: 2200.0,
            shadows_enabled: false,
            ..default()
        },
        Transform::from_xyz(220.0, 320.0, 1000.0),
    ));
    commands.spawn((
        DirectionalLight {
            illuminance: 15_000.0,
            shadows_enabled: false,
            ..default()
        },
        Transform::from_rotation(Quat::from_euler(EulerRot::ZYX, 0.0, -0.9, -0.45)),
    ));
    commands.spawn((
        PointLight {
            intensity: 45_000.0,
            range: 1800.0,
            shadows_enabled: false,
            ..default()
        },
        Transform::from_xyz(-280.0, -120.0, 700.0),
    ));
    commands.insert_resource(TerminalPresentation {
        mode: TerminalPresentationMode::Flat2d,
    });
    commands.insert_resource(TerminalPlaneView::default());
    commands.insert_resource(MobiusTransition::default());
    commands.insert_resource(ModelLoadState {
        loaded: false,
        first_frame_uploaded: false,
    });
}

fn create_terminal_image(width: u32, height: u32, fill: [u8; 4]) -> Image {
    let mut image = Image::new_fill(
        Extent3d {
            width,
            height,
            depth_or_array_layers: 1,
        },
        TextureDimension::D2,
        &fill,
        TextureFormat::Rgba8UnormSrgb,
        RenderAssetUsages::default(),
    );
    image.sampler = ImageSampler::nearest();
    image
}

/// Applies the active terminal presentation mode.
pub(crate) fn apply_terminal_presentation(
    presentation: Res<TerminalPresentation>,
    plane_view: Res<TerminalPlaneView>,
    mobius_transition: Res<MobiusTransition>,
    mut params: PresentationParams,
) {
    let PresentationParams {
        visibility_queries,
        plane_materials,
        materials,
        plane_transforms,
    } = &mut params;
    let is_3d = presentation.mode.is_3d();
    let is_mobius = presentation.mode.is_mobius();
    let yaw = if is_mobius && mobius_transition.active {
        mobius_transition.current_yaw()
    } else {
        plane_view.yaw
    };
    let pitch = if is_mobius && mobius_transition.active {
        mobius_transition.current_pitch()
    } else {
        plane_view.pitch
    };
    let camera_offset = if is_mobius && mobius_transition.active {
        mobius_transition.current_camera_offset()
    } else {
        plane_view.camera_offset
    };
    let sprite_visibility = if is_3d {
        Visibility::Hidden
    } else {
        Visibility::Visible
    };
    let plane_visibility = if is_3d {
        Visibility::Visible
    } else {
        Visibility::Hidden
    };

    for mut visibility in &mut visibility_queries.p0() {
        *visibility = sprite_visibility;
    }

    for mut visibility in &mut visibility_queries.p1() {
        *visibility = plane_visibility;
    }

    for mut visibility in &mut visibility_queries.p2() {
        // A Mobius strip is one continuous ribbon, so the separate back sheet model does not map
        // cleanly. Render the front material double-sided instead.
        *visibility = if is_3d && !is_mobius {
            Visibility::Visible
        } else {
            Visibility::Hidden
        };
    }

    if let Ok(front_material) = plane_materials.single()
        && let Some(material) = materials.get_mut(&front_material.0)
    {
        material.cull_mode = if is_mobius { None } else { Some(Face::Back) };
    }

    for mut transform in &mut plane_transforms.p0() {
        transform.rotation = if is_3d {
            Quat::from_euler(EulerRot::XYZ, pitch, yaw, 0.0)
        } else {
            Quat::IDENTITY
        };
    }

    for mut transform in &mut plane_transforms.p1() {
        if is_3d {
            transform.rotation =
                Quat::from_euler(EulerRot::XYZ, pitch, yaw + std::f32::consts::PI, 0.0);
            transform.translation = if is_mobius {
                Vec3::ZERO
            } else {
                Vec3::new(0.0, 0.0, -2.0)
            };
        } else {
            transform.rotation = Quat::IDENTITY;
            transform.translation = Vec3::new(0.0, 0.0, -2.0);
        }
    }

    for (mut projection, mut transform) in &mut plane_transforms.p2() {
        if let Projection::Orthographic(ortho) = projection.as_mut() {
            let zoom = if is_mobius && mobius_transition.active {
                mobius_transition.current_zoom()
            } else {
                plane_view.zoom
            };
            ortho.scale = if is_3d { zoom } else { 1.0 };
        }

        let offset = if is_3d {
            camera_offset.extend(0.0)
        } else {
            Vec3::ZERO
        };
        transform.translation = Vec3::new(0.0, 0.0, 800.0) + offset;
        transform.look_at(offset, Vec3::Y);
    }
}

fn terminal_plane_mesh(x_segments: u32, y_segments: u32) -> Mesh {
    let x_segments = x_segments.max(2);
    let y_segments = y_segments.max(2);
    let vertex_count = ((x_segments + 1) * (y_segments + 1)) as usize;

    let mut positions = Vec::with_capacity(vertex_count);
    let mut normals = Vec::with_capacity(vertex_count);
    let mut uvs = Vec::with_capacity(vertex_count);
    let mut indices = Vec::with_capacity((x_segments * y_segments * 6) as usize);

    for y in 0..=y_segments {
        let v = y as f32 / y_segments as f32;
        let py = 0.5 - v;
        for x in 0..=x_segments {
            let u = x as f32 / x_segments as f32;
            let px = u - 0.5;
            positions.push([px, py, 0.0]);
            normals.push([0.0, 0.0, 1.0]);
            uvs.push([u, v]);
        }
    }

    for y in 0..y_segments {
        for x in 0..x_segments {
            let row = y * (x_segments + 1);
            let next_row = (y + 1) * (x_segments + 1);
            let i0 = row + x;
            let i1 = i0 + 1;
            let i2 = next_row + x;
            let i3 = i2 + 1;
            indices.extend_from_slice(&[i0, i2, i1, i1, i2, i3]);
        }
    }

    Mesh::new(
        PrimitiveTopology::TriangleList,
        RenderAssetUsages::default(),
    )
    .with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, positions)
    .with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, normals)
    .with_inserted_attribute(Mesh::ATTRIBUTE_UV_0, uvs)
    .with_inserted_indices(Indices::U32(indices))
}