nightshade 0.57.0

A cross-platform data-oriented game engine.
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
//! The console's presentation, built from retained widgets.
//!
//! The tree is built once on the first frame the console renders and then
//! mutated in place: line labels are pooled, the panel's height follows the open
//! and close animation, and the scroll area owns scrolling, its own scrollbar,
//! and the wheel. Because the widgets are real entities they take part in
//! picking, so the console claims the pointer the same way any other panel does
//! and a click inside it no longer falls through to the game.
//!
//! Every length here is logical. The retained layout multiplies by the layout
//! root's scale and the window DPI, so the console keeps its proportions on a
//! high-DPI display instead of rendering at half size.
//!
//! Nothing is written to the tree unless it changed. `ui_set_text` bumps the
//! global text generation and `ui_set_visible` marks the layout dirty, both
//! unconditionally, so writing every line every frame would relayout the whole
//! interface for as long as the console stayed open. The last written value of
//! every field lives beside its entity for that reason.

use crate::ecs::world::{Entity, World};
use crate::ui::builder::UiTreeBuilder;
use crate::ui::components::{UiNodeInteraction, UiScrollAreaData};
use crate::ui::layer::UiLayer;
use crate::ui::layout_types::UiLayoutType;
use crate::ui::state::{UiBase, UiStateTrait};
use crate::ui::units::Ab;
use crate::ui::widgets::world_interaction::ui_mark_layout_dirty;
use crate::ui::widgets::world_layout::{ui_set_text, ui_set_visible};
use nalgebra_glm::{Vec2, Vec4};

use super::ShellState;

const FONT_SIZE: f32 = 14.0;
const LINE_HEIGHT_RATIO: f32 = 1.4;
const PADDING: f32 = 10.0;
const INPUT_HEIGHT: f32 = 32.0;
const SEPARATOR_HEIGHT: f32 = 1.0;
const RESIZE_HANDLE_HEIGHT: f32 = 6.0;
const MIN_HEIGHT: f32 = 100.0;
const PROMPT_WIDTH: f32 = 18.0;

/// How many of the most recent output rows keep a live entity. Older output
/// stays in [`ShellState::output`] but stops being laid out, which bounds the
/// tree for a console that has been open a long time.
const MAX_SCROLLBACK_ROWS: usize = 2000;

const BACKGROUND: Vec4 = Vec4::new(0.06, 0.06, 0.08, 0.95);
const BORDER: Vec4 = Vec4::new(0.4, 0.4, 0.45, 1.0);
const PROMPT: Vec4 = Vec4::new(0.39, 0.78, 0.39, 1.0);
const COMMAND_TEXT: Vec4 = Vec4::new(0.59, 0.78, 1.0, 1.0);
const OUTPUT_TEXT: Vec4 = Vec4::new(0.78, 0.78, 0.78, 1.0);
const HANDLE_IDLE: Vec4 = Vec4::new(0.5, 0.5, 0.55, 0.8);
const HANDLE_ACTIVE: Vec4 = Vec4::new(0.6, 0.8, 1.0, 1.0);

/// A pooled output label and the values last written to it.
struct LineState {
    entity: Entity,
    text: String,
    is_command: bool,
    visible: bool,
}

/// Handles into the console's retained tree, built on first render and reused
/// for the life of the console, alongside the last state written to each so a
/// frame that changes nothing writes nothing.
pub struct ShellOverlay {
    panel: Entity,
    scroll: Entity,
    content: Entity,
    lines: Vec<LineState>,
    input_text: Entity,
    resize_handle: Entity,
    panel_visible: bool,
    panel_size: Vec2,
    input_cache: String,
    handle_active: bool,
    last_content_height: f32,
    /// Output length the rows were last rebuilt from. Lines are appended and
    /// cleared rather than edited, so a matching length means the rows are
    /// still current and the frame can skip rebuilding them.
    last_output_len: usize,
    /// Set when the console had to switch the retained interface on for itself,
    /// so closing it can hand the game back the state it chose.
    forced_ui_visible: bool,
}

/// Writes a node's base colour directly. The console's colours are fixed rather
/// than theme-bound, so they are set on the node instead of through a role.
fn set_node_color(world: &mut World, entity: Entity, color: Vec4) {
    if let Some(node_color) = world.get_mut::<crate::ui::components::UiNodeColor>(entity) {
        node_color.colors[UiBase::INDEX] = Some(color);
        node_color.computed_color = color;
    }
}

/// One rendered line of console output, after multi-line command results have
/// been split into the lines they occupy.
struct OutputRow {
    text: String,
    is_command: bool,
}

fn output_rows<C>(shell: &ShellState<C>) -> Vec<OutputRow> {
    let mut rows = Vec::new();
    for line in &shell.output {
        if line.text.is_empty() {
            rows.push(OutputRow {
                text: String::new(),
                is_command: line.is_command,
            });
            continue;
        }
        for segment in line.text.split('\n') {
            rows.push(OutputRow {
                text: segment.to_string(),
                is_command: line.is_command,
            });
        }
    }
    if rows.len() > MAX_SCROLLBACK_ROWS {
        rows.drain(..rows.len() - MAX_SCROLLBACK_ROWS);
    }
    rows
}

fn build_overlay(world: &mut World) -> ShellOverlay {
    let forced_ui_visible = !world
        .res::<crate::ui::resources::RetainedUiRuntime>()
        .visible;
    world
        .res_mut::<crate::ui::resources::RetainedUiRuntime>()
        .visible = true;

    let mut tree = UiTreeBuilder::new(world);

    let panel = tree
        .add_node()
        .window_at(Ab(Vec2::zeros()), Ab(Vec2::new(0.0, 0.0)))
        .rect(0.0)
        .color_raw::<UiBase>(BACKGROUND)
        .with_layer(UiLayer::Tooltips)
        .with_clip()
        .with_interaction()
        .flow_vertical()
        .padding(0.0)
        .gap(0.0)
        .entity();

    let (scroll, content, input_text, resize_handle) = tree.in_parent(panel, |tree| {
        let scroll = tree.add_scroll_area_fill(PADDING, 0.0);
        let content = tree
            .world_mut()
            .get::<UiScrollAreaData>(scroll)
            .map(|data| data.content_entity)
            .unwrap_or(scroll);

        tree.add_node()
            .fill_width()
            .size_px(0.0, SEPARATOR_HEIGHT)
            .rect(0.0)
            .color_raw::<UiBase>(BORDER);

        let input_row = tree
            .add_node()
            .fill_width()
            .size_px(0.0, INPUT_HEIGHT)
            .flow_horizontal()
            .padding(0.0)
            .gap(0.0)
            .align_cross(crate::ui::layout_types::FlowAlignment::Center)
            .entity();

        let input_text = tree.in_parent(input_row, |tree| {
            tree.add_node()
                .size_px(PROMPT_WIDTH, INPUT_HEIGHT)
                .with_text(">", FONT_SIZE)
                .color_raw::<UiBase>(PROMPT);
            tree.add_node()
                .fill_width()
                .flex_grow(1.0)
                .with_text("", FONT_SIZE)
                .color_raw::<UiBase>(OUTPUT_TEXT)
                .entity()
        });

        let resize_handle = tree
            .add_node()
            .fill_width()
            .size_px(0.0, RESIZE_HANDLE_HEIGHT)
            .rect(RESIZE_HANDLE_HEIGHT * 0.5)
            .color_raw::<UiBase>(HANDLE_IDLE)
            .with_interaction()
            .with_cursor_icon(nightshade_platform::CursorIcon::NsResize)
            .entity();

        (scroll, content, input_text, resize_handle)
    });

    tree.finish();

    ShellOverlay {
        panel,
        scroll,
        content,
        lines: Vec::new(),
        input_text,
        resize_handle,
        panel_visible: false,
        panel_size: Vec2::new(-1.0, -1.0),
        input_cache: String::new(),
        handle_active: false,
        last_content_height: f32::NAN,
        last_output_len: usize::MAX,
        forced_ui_visible,
    }
}

/// Grows the pooled labels until there is one per row, then writes only the
/// rows whose text, colour, or visibility actually moved.
fn sync_output(world: &mut World, overlay: &mut ShellOverlay, rows: &[OutputRow]) {
    if overlay.lines.len() < rows.len() {
        let content = overlay.content;
        let mut tree = UiTreeBuilder::from_parent(&mut world.ecs, content);
        for _ in overlay.lines.len()..rows.len() {
            let entity = tree
                .add_node()
                .fill_width()
                .size_px(0.0, (FONT_SIZE * LINE_HEIGHT_RATIO).round())
                .with_text("", FONT_SIZE)
                .color_raw::<UiBase>(OUTPUT_TEXT)
                .entity();
            overlay.lines.push(LineState {
                entity,
                text: String::new(),
                is_command: false,
                visible: true,
            });
        }
        tree.finish();
    }

    for index in 0..overlay.lines.len() {
        match rows.get(index) {
            Some(row) => {
                let entity = overlay.lines[index].entity;
                if !overlay.lines[index].visible {
                    ui_set_visible(&mut world.ecs, entity, true);
                    overlay.lines[index].visible = true;
                }
                if overlay.lines[index].text != row.text {
                    ui_set_text(&mut world.ecs, entity, &row.text);
                    overlay.lines[index].text.clear();
                    overlay.lines[index].text.push_str(&row.text);
                }
                if overlay.lines[index].is_command != row.is_command {
                    let color = if row.is_command {
                        COMMAND_TEXT
                    } else {
                        OUTPUT_TEXT
                    };
                    set_node_color(world, entity, color);
                    overlay.lines[index].is_command = row.is_command;
                }
            }
            None => {
                if overlay.lines[index].visible {
                    let entity = overlay.lines[index].entity;
                    ui_set_visible(&mut world.ecs, entity, false);
                    overlay.lines[index].visible = false;
                }
            }
        }
    }
}

/// Drags the console's bottom edge. The handle is a real widget, so the drag is
/// picked like any other and the pointer belongs to the console while it runs.
fn apply_resize<C>(
    shell: &mut ShellState<C>,
    world: &mut World,
    overlay: &mut ShellOverlay,
    max: f32,
) {
    let interaction = world
        .get::<UiNodeInteraction>(overlay.resize_handle)
        .map(|interaction| (interaction.dragging, interaction.drag_start));
    let Some((dragging, drag_start)) = interaction else {
        return;
    };

    let scale = crate::platform::window::window_scale_factor(world).max(f32::EPSILON);
    let mouse_y = crate::platform::input::access::mouse_for_active(world)
        .position
        .y
        / scale;

    if dragging {
        if !shell.dragging_resize {
            shell.dragging_resize = true;
            shell.drag_start_y = drag_start.map(|start| start.y / scale).unwrap_or(mouse_y);
            shell.drag_start_height = shell.height;
        }
        shell.height = (shell.drag_start_height + (mouse_y - shell.drag_start_y))
            .clamp(MIN_HEIGHT.min(max), max);
    } else {
        shell.dragging_resize = false;
    }

    if overlay.handle_active != shell.dragging_resize {
        overlay.handle_active = shell.dragging_resize;
        let color = if shell.dragging_resize {
            HANDLE_ACTIVE
        } else {
            HANDLE_IDLE
        };
        set_node_color(world, overlay.resize_handle, color);
    }
}

/// Resizes the panel, marking the layout dirty itself. Writing the node alone
/// would not, because the layout pass is gated on the dirty flag rather than on
/// component change ticks.
fn set_panel_rect(world: &mut World, overlay: &mut ShellOverlay, size: Vec2) {
    if overlay.panel_size == size {
        return;
    }
    overlay.panel_size = size;
    if let Some(node) = world.get_mut::<crate::ui::components::UiLayoutNode>(overlay.panel)
        && let Some(UiLayoutType::Window(window)) = node.base_layout.as_mut()
    {
        window.position = Ab(Vec2::zeros()).into();
        window.size = Ab(size).into();
    }
    ui_mark_layout_dirty(&mut world.ecs);
}

fn set_panel_visible(world: &mut World, overlay: &mut ShellOverlay, visible: bool) {
    if overlay.panel_visible == visible {
        return;
    }
    overlay.panel_visible = visible;
    ui_set_visible(&mut world.ecs, overlay.panel, visible);
}

/// Scrolls to the newest output. The scroll area measures its content from the
/// previous layout, so a request made on the frame that added lines would land
/// short; the request is held until the measured height stops moving.
fn apply_scroll_to_bottom<C>(
    shell: &mut ShellState<C>,
    world: &mut World,
    overlay: &mut ShellOverlay,
) {
    let scale = crate::platform::window::window_scale_factor(world).max(f32::EPSILON);
    let Some((content_height, visible_height)) = world
        .get::<UiScrollAreaData>(overlay.scroll)
        .map(|data| (data.content_height, data.visible_height))
    else {
        return;
    };

    // The measured heights are physical; the offset the scroll area reads is
    // logical, so the span has to come back through the scale.
    let bottom = ((content_height - visible_height).max(0.0)) / scale;
    if let Some(data) = world.get_mut::<UiScrollAreaData>(overlay.scroll) {
        data.scroll_offset = bottom;
    }

    let settled = (content_height - overlay.last_content_height).abs() < f32::EPSILON;
    overlay.last_content_height = content_height;
    if settled {
        shell.scroll_to_bottom = false;
    }
}

pub fn shell_retained_ui<C>(shell: &mut ShellState<C>, world: &mut World) {
    if !shell.should_render() {
        if let Some(mut overlay) = shell.overlay.take() {
            set_panel_visible(world, &mut overlay, false);
            if overlay.forced_ui_visible {
                world
                    .res_mut::<crate::ui::resources::RetainedUiRuntime>()
                    .visible = false;
            }
            shell.overlay = Some(overlay);
        }
        // A key pressed as the console closed must not fire when it reopens.
        shell.pending_enter = false;
        shell.pending_up = false;
        shell.pending_down = false;
        shell.pending_escape = false;
        shell.dragging_resize = false;
        world
            .res_mut::<crate::user_interface::UserInterface>()
            .hud_wants_keyboard = false;
        return;
    }

    let mut overlay = match shell.overlay.take() {
        Some(overlay) => overlay,
        None => build_overlay(world),
    };

    if overlay.forced_ui_visible {
        world
            .res_mut::<crate::ui::resources::RetainedUiRuntime>()
            .visible = true;
    }

    // The console takes typing while it is open, even when the pointer is
    // nowhere near it, so keyboard-driven systems stand down.
    world
        .res_mut::<crate::user_interface::UserInterface>()
        .hud_wants_keyboard = shell.visible;

    let scale = crate::platform::window::window_scale_factor(world).max(f32::EPSILON);
    let viewport = crate::platform::window::window_viewport_size(world)
        .map(|(width, height)| Vec2::new(width as f32, height as f32))
        .unwrap_or(Vec2::new(1920.0, 1080.0))
        / scale;

    // A window shorter than the console's minimum would invert the clamp range,
    // which panics, so the floor gives way to the ceiling on a tiny window.
    let max_height = (viewport.y * 0.9).max(0.0);
    shell.height = shell.height.clamp(MIN_HEIGHT.min(max_height), max_height);

    apply_resize(shell, world, &mut overlay, max_height);

    let open_height = shell.height * shell.animation_progress;
    set_panel_visible(world, &mut overlay, true);
    set_panel_rect(world, &mut overlay, Vec2::new(viewport.x, open_height));

    if overlay.last_output_len != shell.output.len() {
        overlay.last_output_len = shell.output.len();
        let rows = output_rows(shell);
        sync_output(world, &mut overlay, &rows);
    }

    let cursor = if shell.visible && shell.animation_progress > 0.9 {
        "_"
    } else {
        ""
    };
    let input_display = format!("{}{}", shell.input_buffer, cursor);
    if overlay.input_cache != input_display {
        ui_set_text(&mut world.ecs, overlay.input_text, &input_display);
        overlay.input_cache = input_display;
    }

    if shell.scroll_to_bottom {
        apply_scroll_to_bottom(shell, world, &mut overlay);
    }

    if shell.visible && shell.animation_progress > 0.9 {
        if shell.pending_enter {
            shell.pending_enter = false;
            shell.execute_command(world);
        }
        if shell.pending_up {
            shell.pending_up = false;
            shell.history_up();
        }
        if shell.pending_down {
            shell.pending_down = false;
            shell.history_down();
        }
        if shell.pending_escape {
            shell.pending_escape = false;
            shell.visible = false;
        }
    }

    shell.overlay = Some(overlay);
}