nightshade-api 0.44.1

Procedural high level API for the nightshade 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
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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
//! The editor's wire format: page to worker messages, worker to page state
//! mirrors, and the external agent request and response types.

#[cfg(feature = "protocol-agent")]
mod agent;
#[cfg(feature = "protocol-agent")]
pub use agent::*;

use crate::command::Command;
use nightshade::ecs::audio::components::AudioSource;
use nightshade::ecs::camera::components::Camera;
use nightshade::ecs::decal::components::Decal;
use nightshade::ecs::event::Event;
use nightshade::ecs::gizmos::GizmoMode;
use nightshade::ecs::light::components::Light;
use nightshade::ecs::material::components::Material;
use nightshade::ecs::particles::components::ParticleEmitter;
use nightshade::ecs::scene::{SceneChunkConfig, SceneLayerConfig};
use nightshade::ecs::text::components::TextProperties;
pub use nightshade::prelude::{
    Atmosphere, CharacterControllerComponent, ColliderComponent, NavMeshAgent, RigidBodyComponent,
};
use serde::{Deserialize, Serialize};

pub use nightshade::ecs::audio::components::AudioSource as AudioSourceComponent;
pub use nightshade::ecs::camera::components::{
    Camera as CameraComponent, OrthographicCamera, PerspectiveCamera, Projection,
};
pub use nightshade::ecs::decal::components::Decal as DecalComponent;
pub use nightshade::ecs::gizmos::GizmoMode as GizmoModeKind;
pub use nightshade::ecs::light::components::{AreaLightShape, Light as LightComponent, LightType};
pub use nightshade::ecs::material::components::{AlphaMode, Material as MaterialComponent};
pub use nightshade::ecs::particles::components::ParticleEmitter as ParticleEmitterComponent;
pub use nightshade::ecs::physics::components::ColliderShape;
pub use nightshade::ecs::physics::types::RigidBodyType;
pub use nightshade::ecs::primitives::{CameraCullingMask, CullingMask, RenderLayer};
pub use nightshade::ecs::text::components::TextProperties as TextPropertiesComponent;
pub use nightshade::prelude::{Atmosphere as AtmosphereKind, Vec2, Vec3, Vec4};

/// Envelope field carrying the serialized message in every `postMessage`.
pub const MESSAGE_KEY: &str = "message";
/// Envelope field carrying the transferred `OffscreenCanvas` (on `Init` only).
pub const CANVAS_KEY: &str = "canvas";
/// Envelope field carrying transferred binary bytes (file drops, map saves).
pub const BYTES_KEY: &str = "bytes";
/// Envelope field carrying the transferred glTF bytes of a multi-file bundle.
pub const GLTF_KEY: &str = "gltf";
/// Envelope field carrying a `{ name: Uint8Array }` object of bundle resources.
pub const RESOURCES_KEY: &str = "resources";

/// Lifecycle phase of a forwarded touch contact.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum TouchPhase {
    Started,
    Moved,
    Ended,
    Cancelled,
}

/// A parametric primitive shape used for spawning and block placement.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(
    feature = "protocol-agent",
    derive(enum2schema::Schema),
    schema(string_enum)
)]
pub enum ShapeKind {
    Cube,
    Plane,
    Cylinder,
    Cone,
    Sphere,
    Torus,
}

/// A light kind for the Add menu.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(
    feature = "protocol-agent",
    derive(enum2schema::Schema),
    schema(string_enum)
)]
pub enum LightKind {
    Point,
    Spot,
    Directional,
}

/// A procedural greybox generator.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(
    feature = "protocol-agent",
    derive(enum2schema::Schema),
    schema(string_enum)
)]
pub enum GeneratorKind {
    Building,
    Room,
    Tower,
    Stairs,
    Columns,
    Perimeter,
    CityBlock,
    Courtyard,
    Wfc,
    WfcCity,
}

/// Asset browser category for Polyhaven.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(
    feature = "protocol-agent",
    derive(enum2schema::Schema),
    schema(string_enum)
)]
pub enum PolyhavenCategory {
    Hdris,
    Models,
}

pub use crate::reflect::{ComponentKind, ComponentPatch};

/// Animation playback control for the selected entity's player.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub enum AnimationCommand {
    Play { index: u32 },
    PlayAll,
    Pause,
    Resume,
    Stop,
    Seek { time: f32 },
    SetSpeed { speed: f32 },
    SetLooping { looping: bool },
}

/// Procedural generation settings, mirrored from the worker's resource so the
/// panel edits round-trip.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "protocol-agent", derive(enum2schema::Schema))]
pub struct GenerationSettings {
    pub footprint_x: f32,
    pub footprint_z: f32,
    pub stories: u32,
    pub story_height: f32,
    pub wall_thickness: f32,
    pub floor_thickness: f32,
    pub window_spacing: f32,
    pub seed: u32,
    pub variation: f32,
}

/// Every world-level rendering setting the inspector's world sections edit,
/// synced both ways as one block.
#[derive(Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct RenderSettingsState {
    pub ambient_light: [f32; 4],
    pub bloom_enabled: bool,
    pub bloom_intensity: f32,
    pub bloom_threshold: f32,
    pub bloom_knee: f32,
    pub bloom_filter_radius: f32,
    pub ssao_enabled: bool,
    pub ssao_radius: f32,
    pub ssao_intensity: f32,
    pub ssao_bias: f32,
    pub ssao_sample_count: u32,
    pub ssao_visualization: bool,
    pub ssgi_enabled: bool,
    pub ssgi_radius: f32,
    pub ssgi_intensity: f32,
    pub ssgi_max_steps: u32,
    pub ssr_enabled: bool,
    pub ssr_max_steps: u32,
    pub ssr_thickness: f32,
    pub ssr_max_distance: f32,
    pub ssr_stride: f32,
    pub ssr_fade_start: f32,
    pub ssr_fade_end: f32,
    pub ssr_intensity: f32,
    pub fog_enabled: bool,
    pub fog_color: [f32; 3],
    pub fog_start: f32,
    pub fog_end: f32,
    pub dof_enabled: bool,
    pub dof_focus_distance: f32,
    pub dof_focus_range: f32,
    pub dof_max_blur_radius: f32,
    pub dof_bokeh_threshold: f32,
    pub dof_bokeh_intensity: f32,
    pub dof_quality: u32,
    pub fxaa_enabled: bool,
    pub render_scale: f32,
    pub ibl_blend_factor: f32,
    pub pbr_debug_index: u32,
    pub unlit_mode: bool,
    pub selection_outline_enabled: bool,
    pub selection_outline_color: [f32; 4],
    pub exposure: f32,
    pub saturation: f32,
    pub contrast: f32,
    pub brightness: f32,
    pub gamma: f32,
    pub show_grid: bool,
    pub show_sky: bool,
    pub show_normals: bool,
    pub navmesh_debug: bool,
    pub atmosphere: Atmosphere,
}

/// Editor-side state the page mirrors for toolbar and panel highlights.
#[derive(Clone, PartialEq, Serialize, Deserialize)]
pub struct EditorFlags {
    pub gizmo_mode: GizmoMode,
    pub snap_enabled: bool,
    pub snap_translation_step: f32,
    pub snap_rotation_step_degrees: f32,
    pub snap_scale_step: f32,
    pub greybox_enabled: bool,
    pub greybox_show_final: bool,
    pub placement_active: bool,
    pub placement_shape: ShapeKind,
    pub placement_size: [f32; 3],
    pub placement_orient: bool,
    pub placement_status: String,
    pub push_pull_active: bool,
    pub play_active: bool,
    pub scripting_active: bool,
    pub fly_mode: bool,
    pub viewer_mode: bool,
    pub frame_on_load: bool,
    pub day_night_hour: f32,
    pub day_night_auto: bool,
    pub skeleton_view: bool,
    pub rotation_speed: f32,
    pub active_palette: usize,
    pub edit_mode_target: Option<u32>,
    pub generation: GenerationSettings,
    pub global_scripts: Vec<nightshade::ecs::script::components::GlobalScript>,
}

/// An ordered edit to the scene's global script list.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "protocol-agent", derive(enum2schema::Schema))]
pub enum GlobalScriptCommand {
    Add,
    AddTemplate { name: String, source: String },
    Remove(u32),
    MoveUp(u32),
    MoveDown(u32),
    SetEnabled { index: u32, enabled: bool },
    SetSource { index: u32, source: String },
    Rename { index: u32, name: String },
}

/// One row of the flattened scene tree, in depth-first order.
#[derive(Clone, PartialEq, Serialize, Deserialize)]
pub struct TreeRow {
    pub id: u32,
    pub name: String,
    pub depth: u32,
    pub has_children: bool,
    pub camera: bool,
    pub light: bool,
    pub mesh: bool,
}

/// A greybox material palette swatch.
#[derive(Clone, PartialEq, Serialize, Deserialize)]
pub struct PaletteEntry {
    pub label: String,
    pub color: [f32; 3],
}

/// Prefab link shown in the inspector for instanced prefab roots.
#[derive(Clone, PartialEq, Serialize, Deserialize)]
pub struct PrefabLink {
    pub name: String,
    pub source_path: Option<String>,
}

/// One mesh's morph targets for the scene-wide morph panel: the entity id, a
/// display name, and the current weight per target.
#[derive(Clone, PartialEq, Serialize, Deserialize)]
pub struct MorphMeshInfo {
    pub id: u32,
    pub name: String,
    pub weights: Vec<f32>,
}

/// Animation state of the selected entity, for the inspector's player section.
#[derive(Clone, PartialEq, Serialize, Deserialize)]
pub struct AnimationInfo {
    pub clips: Vec<String>,
    pub current: Option<u32>,
    pub playing: bool,
    pub time: f32,
    pub duration: f32,
    pub speed: f32,
    pub looping: bool,
}

/// The selected entity's full editable detail. Rotation is Euler degrees.
#[derive(Clone, Serialize, Deserialize)]
pub struct SelectedEntity {
    pub id: u32,
    /// Bumped whenever a committed edit or undo changed this entity, so the
    /// page re-seeds its local editor copies exactly then.
    pub revision: u32,
    pub name: String,
    pub translation: [f32; 3],
    pub rotation: [f32; 3],
    pub scale: [f32; 3],
    pub mesh: Option<String>,
    pub material_name: Option<String>,
    pub tags: Vec<String>,
    pub layer: Option<u32>,
    pub chunk: Option<u32>,
    pub prefab: Option<PrefabLink>,
    pub animation: Option<AnimationInfo>,
    pub morph_weights: Option<Vec<f32>>,
    pub selected_count: u32,
    pub visibility: Option<bool>,
    pub casts_shadow: bool,
    pub light: Option<Light>,
    pub camera: Option<Camera>,
    pub is_active_camera: bool,
    pub rigid_body: Option<RigidBodyComponent>,
    pub collider: Option<ColliderComponent>,
    pub character_controller: Option<CharacterControllerComponent>,
    pub navmesh_agent: Option<NavMeshAgent>,
    pub particle_emitter: Option<Box<ParticleEmitter>>,
    pub decal: Option<Decal>,
    pub audio_source: Option<AudioSource>,
    pub render_layer: Option<RenderLayer>,
    pub culling_mask: Option<CullingMask>,
    pub camera_culling_mask: Option<CameraCullingMask>,
    pub ignore_parent_scale: bool,
    pub text: Option<(String, TextProperties)>,
    pub script: Option<String>,
    pub present: Vec<ComponentKind>,
    pub addable: Vec<ComponentKind>,
}

/// A material registry entry for the materials panel.
#[derive(Clone, Serialize, Deserialize)]
pub struct MaterialEntry {
    pub name: String,
    pub material: Material,
}

/// A Khronos sample-asset entry for the browser grid.
#[derive(Clone, PartialEq, Serialize, Deserialize)]
pub struct KhronosEntry {
    pub label: String,
    pub thumbnail: Option<String>,
}

/// A Polyhaven entry for the browser grid.
#[derive(Clone, PartialEq, Serialize, Deserialize)]
pub struct PolyhavenEntry {
    pub slug: String,
    pub name: String,
    pub thumbnail: String,
}

/// Scene layer and chunk authoring data.
#[derive(Clone, PartialEq, Serialize, Deserialize)]
pub struct SceneStructure {
    pub layers: Vec<SceneLayerConfig>,
    pub chunks: Vec<SceneChunkConfig>,
}

/// Editor commands that need no payload beyond what they carry. Entity
/// references are raw entity ids resolved by the worker.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "protocol-agent", derive(enum2schema::Schema))]
pub enum EditorAction {
    ToggleGroundGrid,
    ToggleSky,
    ToggleLitUnlit,
    ToggleViewerMode,
    SetViewerMode(bool),
    FrameScene,
    ToggleFrameOnLoad,
    ClearScene,
    SnapSelectionToFloor,
    BakeNavmesh,
    ToggleNavmeshDebug,
    SetAtmosphere(Atmosphere),
    SetGizmoMode(GizmoMode),
    RandomizeBoth,
    SelectEntity(u32),
    ToggleSelectEntity(u32),
    ClearSelection,
    AddEntityChild(u32),
    ViewCamera(u32),
    ToggleSnap,
    ToggleSkeletonView,
    SetMaterialVariant(Option<String>),
    ToggleCameraGizmos,
    ToggleShowNormals,
    ToggleDayNightCycle,
    SetDayNightHour(f32),
    LoadKhronosByIndex(usize),
    LoadPolyhavenByIndex {
        category: PolyhavenCategory,
        index: usize,
    },
    SetPolyhavenResolution(u32),
    RefreshBrowsers,
    DeepLink(String),
    SpawnLines,
    SpawnMeshes,
    Spawn3DText,
    SpawnTextLattice,
    ClothSponza,
    NewProject,
    LoadExampleProject,
    SaveProject,
    ExportGlb,
    SaveSelectedAsPrefab,
    RefreshSelectedPrefab,
    BreakSelectedPrefabLink,
    SpawnPrefab(String),
    Undo,
    Redo,
    DeleteEntity(u32),
    DeleteSelectedEntity,
    DuplicateEntity(u32),
    DuplicateSelectedEntity,
    AddShape(ShapeKind),
    AddInstancedShape(ShapeKind),
    ConvertSimilarToInstanced,
    AddEmpty,
    AddCamera,
    AddPlayerSpawn,
    AddSavePoint,
    AddPatrolPoint,
    AddTriggerVolume,
    StampDecalAtCursor,
    AddLight(LightKind),
    AddTagToSelected(String),
    RemoveTagFromSelected(String),
    ToggleGreyboxMode,
    ApplyGreyboxToSelection,
    SnapSelectionToGrid,
    MarkSelectionAsBrush,
    ToggleShowFinal,
    TogglePlay,
    ToggleScripting,
    /// Start or stop play mode (the first-person walkthrough) explicitly, so a
    /// caller drives it without knowing the current state, unlike `TogglePlay`.
    SetPlay(bool),
    /// Start or stop scripting mode (run the scene's scripts) explicitly,
    /// unlike `ToggleScripting`.
    SetScripting(bool),
    GlobalScript(GlobalScriptCommand),
    TogglePushPull,
    SetPlacementActive(bool),
    SetPlacementShape(ShapeKind),
    SetPlacementSize([f32; 3]),
    SetOrientToNormal(bool),
    RunGenerator(GeneratorKind),
    SetGenerationSettings(GenerationSettings),
    SetPaletteIndex(usize),
    SetSnapEnabled(bool),
    SetSnapSteps {
        translation: f32,
        rotation_degrees: f32,
        scale: f32,
    },
    SetRotationSpeed(f32),
    SetEntityLayer {
        id: u32,
        layer: Option<u32>,
    },
    SetEntityChunk {
        id: u32,
        chunk: Option<u32>,
    },
    AddSceneLayer,
    RemoveSceneLayer(u32),
    UpdateSceneLayer(SceneLayerConfig),
    AddSceneChunk,
    RemoveSceneChunk(u32),
    UpdateSceneChunk(SceneChunkConfig),
}

/// A camera entity available for multi-view tiling.
#[derive(Clone, Serialize, Deserialize)]
pub struct CameraEntry {
    pub id: u32,
    pub name: String,
}

/// One camera's tile in the multi-view layout, in physical canvas pixels with
/// the origin at the canvas top-left.
#[derive(Clone, Copy, Serialize, Deserialize)]
pub struct ViewportTile {
    pub camera: u32,
    pub x: f32,
    pub y: f32,
    pub width: f32,
    pub height: f32,
}

/// Page to worker. Pixel quantities are physical surface pixels (CSS pixels
/// times the device pixel ratio), origin at the canvas top-left.
#[derive(Clone, Serialize, Deserialize)]
pub enum ClientMessage {
    /// Sent once with the `OffscreenCanvas` in the transfer list.
    Init {
        width: f32,
        height: f32,
    },
    Resize {
        width: f32,
        height: f32,
    },
    /// Replaces the camera tile layout. An empty list returns to the single
    /// full-canvas view.
    SetViewportTiles(Vec<ViewportTile>),
    PointerMove {
        x: f32,
        y: f32,
    },
    /// Raw pointer motion (movementX/Y), forwarded while pointer lock is held
    /// so fly and play modes get first-person look input.
    PointerMotion {
        dx: f32,
        dy: f32,
    },
    /// A mouse button changed. `button` is 0 left, 1 middle, 2 right.
    PointerButton {
        button: u8,
        pressed: bool,
    },
    Wheel {
        delta: f32,
    },
    Touch {
        id: u64,
        phase: TouchPhase,
        x: f32,
        y: f32,
    },
    /// A keyboard event forwarded while the canvas owns the keyboard. `code`
    /// is the DOM `KeyboardEvent.code` string.
    Key {
        code: String,
        pressed: bool,
        text: Option<String>,
    },
    Action(Box<EditorAction>),
    SetTransform {
        id: u32,
        translation: [f32; 3],
        rotation: [f32; 3],
        scale: [f32; 3],
        committed: bool,
    },
    SetEntityName {
        id: u32,
        name: String,
    },
    SetComponent {
        id: u32,
        payload: Box<ComponentPatch>,
        committed: bool,
    },
    AddComponent {
        id: u32,
        kind: ComponentKind,
    },
    RemoveComponent {
        id: u32,
        kind: ComponentKind,
    },
    Animation {
        id: u32,
        command: AnimationCommand,
    },
    UpdateMaterial {
        name: String,
        material: Box<Material>,
        committed: bool,
    },
    SetRenderSettings(Box<RenderSettingsState>),
    /// A dropped or picked file's bytes are in the `bytes` envelope field.
    /// Routed by extension: .glb/.gltf import, .hdr skybox, .nsmap/.json map,
    /// .nsprefab prefab.
    DropAsset {
        name: String,
    },
    /// A multi-file glTF: `gltf` holds the document bytes, `resources` a
    /// `{ name: Uint8Array }` object of buffers and images.
    LoadGltfBundle {
        name: String,
    },
    /// Replace the selected greybox brush's art with this glTF (bytes envelope).
    UpgradeBrush {
        name: String,
    },
    /// Submit a command from the console builder. `command` is the json of a
    /// [`Command`](crate::Command), the one command layer. The worker
    /// deserializes it and pushes it onto the participant command buffer, the
    /// same path a script takes, applied on the next dispatch.
    SubmitCommand {
        command: String,
    },
    /// External agent traffic (Claude Code via the MCP bridge), forwarded over
    /// the page's WebSocket relay onto this same postMessage path.
    #[cfg(feature = "protocol-agent")]
    Agent(Box<AgentRequest>),
}

/// Worker to page.
#[derive(Clone, Serialize, Deserialize)]
pub enum WorkerMessage {
    Ready {
        adapter: String,
    },
    Stats {
        fps: f32,
        entity_count: u32,
    },
    /// The active camera's world-space basis, for the page's nav gizmo.
    Camera {
        right: [f32; 3],
        up: [f32; 3],
        forward: [f32; 3],
    },
    Scene {
        rows: Vec<TreeRow>,
    },
    Selected {
        detail: Option<Box<SelectedEntity>>,
    },
    /// Every camera entity in the world, independent of scene tree filtering,
    /// so multi-view tiling sees cameras inside collapsed prefab instances.
    Cameras {
        entries: Vec<CameraEntry>,
    },
    /// The selected entity's animation playhead, streamed while it changes.
    Animation {
        time: f32,
        duration: f32,
        playing: bool,
        clip: Option<u32>,
    },
    /// One mesh's morph weights, streamed while they change (animation-driven
    /// or edited), so the inspector and scene panel sliders follow.
    MorphWeights {
        id: u32,
        weights: Vec<f32>,
    },
    /// Every mesh in the scene that carries morph targets, synced when the set
    /// changes. Weight values stream separately via `MorphWeights`.
    MorphMeshes {
        entries: Vec<MorphMeshInfo>,
    },
    /// Every material variant name in the scene plus the active one, synced
    /// whenever either changes.
    MaterialVariants {
        names: Vec<String>,
        active: Option<String>,
    },
    RenderSettings(Box<RenderSettingsState>),
    Flags(Box<EditorFlags>),
    Materials {
        entries: Vec<MaterialEntry>,
    },
    Tags {
        entries: Vec<(String, u32)>,
    },
    Structure(SceneStructure),
    Palette {
        entries: Vec<PaletteEntry>,
    },
    KhronosList {
        entries: Vec<KhronosEntry>,
    },
    PolyhavenList {
        category: PolyhavenCategory,
        entries: Vec<PolyhavenEntry>,
    },
    Loading {
        active: bool,
        label: String,
    },
    /// Project status for the title bar.
    Project {
        name: String,
        modified: bool,
        model: Option<String>,
        mode: String,
    },
    /// Serialized file bytes for the page to save (bytes envelope field).
    SaveFile {
        name: String,
    },
    /// Ask the page to acquire or release pointer lock on the canvas.
    PointerLock {
        locked: bool,
    },
    /// Scroll the tree to this entity after a viewport pick.
    FocusEntity {
        id: u32,
    },
    UndoState {
        can_undo: bool,
        can_redo: bool,
    },
    Toast {
        message: String,
        error: bool,
    },
    /// New command and event traffic from the participant cycle, streamed each
    /// frame the journal has anything, for the command and event log panel.
    CommandLog {
        entries: Vec<CommandLogEntry>,
    },
    /// External agent responses and delta batches, relayed back to the MCP
    /// bridge.
    #[cfg(feature = "protocol-agent")]
    Agent(Box<AgentResponse>),
}

/// Whether a [`CommandLogEntry`] is a command that was applied or an event that
/// was published.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum CommandLogKind {
    Command,
    Event,
}

/// One line in the command and event log: the cycle it happened in, whether it
/// was a command or an event, a short label, and the human readable detail.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CommandLogEntry {
    pub cycle: u64,
    pub kind: CommandLogKind,
    pub label: String,
    pub detail: String,
    /// The entities this entry names, by id, so the log row can select and
    /// highlight them in the viewport.
    pub entities: Vec<u32>,
}

impl CommandLogEntry {
    /// Builds a log row from a published event: its cycle, a label and detail
    /// read off the typed value, and the entities it names.
    pub fn from_event(cycle: u64, event: &Event) -> Self {
        Self {
            cycle,
            kind: CommandLogKind::Event,
            label: event_label(event).to_string(),
            detail: event_detail(event),
            entities: event_entities(event),
        }
    }

    /// Builds a log row from a command the script runtime or the console
    /// produced. The variant name is the label, its serialized arguments are the
    /// detail, and the entity ids are read off the value, so a tool surfaces the
    /// traffic without parsing formatted strings back apart.
    pub fn from_command(cycle: u64, command: &Command) -> Self {
        use enum2schema::serde_json::Value;
        let value: Value = enum2schema::serde_json::to_value(command).unwrap_or(Value::Null);
        let detail = value
            .as_object()
            .and_then(|object| object.values().next())
            .map(|inner| inner.to_string())
            .unwrap_or_else(|| value.to_string());
        let mut entities = Vec::new();
        collect_entity_ids(&value, &mut entities);
        Self {
            cycle,
            kind: CommandLogKind::Command,
            label: command.name().to_string(),
            detail,
            entities,
        }
    }
}

fn event_label(event: &Event) -> &'static str {
    match event {
        Event::Collision { .. } => "Collision",
        Event::Despawned { .. } => "Despawned",
        Event::AnimationFinished { .. } => "AnimationFinished",
        Event::AnimationEvent { .. } => "AnimationEvent",
        Event::NavigationArrived { .. } => "NavigationArrived",
    }
}

fn event_detail(event: &Event) -> String {
    match event {
        Event::Collision {
            a,
            b,
            sensor,
            started,
        } => format!(
            "#{} and #{}, {}{}",
            a.id,
            b.id,
            if *started { "started" } else { "ended" },
            if *sensor { ", sensor" } else { "" }
        ),
        Event::AnimationEvent { entity, name } => format!("#{} {}", entity.id, name),
        Event::Despawned { entity }
        | Event::AnimationFinished { entity }
        | Event::NavigationArrived { entity } => format!("#{}", entity.id),
    }
}

fn event_entities(event: &Event) -> Vec<u32> {
    match event {
        Event::Collision { a, b, .. } => vec![a.id, b.id],
        Event::AnimationEvent { entity, .. } => vec![entity.id],
        Event::Despawned { entity }
        | Event::AnimationFinished { entity }
        | Event::NavigationArrived { entity } => vec![entity.id],
    }
}

/// Walks a serialized command for the entity ids it names, reading the
/// `{ "Existing": id }` and `{ "Entity": { "id": id } }` reference forms.
fn collect_entity_ids(value: &enum2schema::serde_json::Value, ids: &mut Vec<u32>) {
    use enum2schema::serde_json::Value;
    match value {
        Value::Object(map) => {
            if let Some(id) = map.get("Existing").and_then(Value::as_u64) {
                ids.push(id as u32);
            }
            if let Some(id) = map
                .get("Entity")
                .and_then(Value::as_object)
                .and_then(|entity| entity.get("id"))
                .and_then(Value::as_u64)
            {
                ids.push(id as u32);
            }
            for nested in map.values() {
                collect_entity_ids(nested, ids);
            }
        }
        Value::Array(array) => {
            for nested in array {
                collect_entity_ids(nested, ids);
            }
        }
        _ => {}
    }
}

#[cfg(all(test, feature = "protocol-agent"))]
mod schema_tests {
    use super::EditorAction;
    use enum2schema::Schema;
    use enum2schema::serde_json::Value;

    /// JSON Schema draft 2020-12 forbids an array-valued `items` (the old
    /// draft-07 tuple form). Positional tuples must use `prefixItems`. The
    /// Anthropic tool API validates against 2020-12 and rejects the whole tool
    /// set otherwise, so the generated action schema must stay clean.
    fn assert_no_array_items(value: &Value) {
        match value {
            Value::Object(object) => {
                if let Some(items) = object.get("items") {
                    assert!(
                        !items.is_array(),
                        "array-valued `items` is invalid in draft 2020-12, use `prefixItems`: {object:?}"
                    );
                }
                for nested in object.values() {
                    assert_no_array_items(nested);
                }
            }
            Value::Array(array) => {
                for nested in array {
                    assert_no_array_items(nested);
                }
            }
            _ => {}
        }
    }

    #[test]
    fn editor_action_schema_is_draft_2020_12() {
        assert_no_array_items(&EditorAction::schema());
    }
}