fyroxed_base 1.0.0

A scene editor for Fyrox 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
// Copyright (c) 2019-present Dmitry Stepanov and Fyrox Engine contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

use crate::{
    command::{Command, CommandGroup},
    fyrox::{
        core::pool::Handle,
        engine::Engine,
        graph::SceneGraph,
        gui::{
            button::Button,
            button::{ButtonBuilder, ButtonMessage},
            grid::{Column, GridBuilder, Row},
            message::UiMessage,
            scroll_viewer::ScrollViewerBuilder,
            stack_panel::StackPanel,
            stack_panel::StackPanelBuilder,
            text::{Text, TextBuilder, TextMessage},
            utils::make_simple_tooltip,
            widget::WidgetBuilder,
            widget::WidgetMessage,
            window::{Window, WindowAlignment},
            window::{WindowBuilder, WindowMessage, WindowTitle},
            BuildContext, Thickness,
        },
        scene::mesh::surface::SurfaceData,
        scene::{
            base::BaseBuilder,
            collider::{ColliderBuilder, ColliderShape, ConvexPolyhedronShape, GeometrySource},
            mesh::{
                surface::{SurfaceBuilder, SurfaceResource},
                Mesh, MeshBuilder,
            },
            node::Node,
            rigidbody::{RigidBody, RigidBodyBuilder, RigidBodyType},
            Scene,
        },
    },
    message::MessageSender,
    preview::PreviewPanel,
    scene::{
        commands::graph::{AddNodeCommand, LinkNodesCommand},
        GameScene, Selection,
    },
    world::selection::GraphSelection,
    Message,
};
use fyrox::core::math::TriangleDefinition;
use fyrox::gui::VerticalAlignment;

pub struct MeshControlPanel {
    pub root_widget: Handle<StackPanel>,
    create_trimesh_collider: Handle<Button>,
    create_convex_collider: Handle<Button>,
    create_trimesh_rigid_body: Handle<Button>,
    add_convex_collider: Handle<Button>,
    add_trimesh_collider: Handle<Button>,
}

fn make_button(text: &str, tooltip: &str, ctx: &mut BuildContext) -> Handle<Button> {
    ButtonBuilder::new(
        WidgetBuilder::new()
            .with_margin(Thickness::uniform(1.0))
            .with_tooltip(make_simple_tooltip(ctx, tooltip)),
    )
    .with_text(text)
    .build(ctx)
}

fn meshes_iter<'a>(
    selection: &'a GraphSelection,
    scene: &'a Scene,
) -> impl Iterator<Item = (Handle<Node>, &'a Mesh)> + 'a {
    selection.nodes.iter().filter_map(|handle| {
        scene
            .graph
            .try_get_of_type::<Mesh>(*handle)
            .ok()
            .map(|mesh| (*handle, mesh))
    })
}

impl MeshControlPanel {
    pub fn new(inspector_head: Handle<StackPanel>, ctx: &mut BuildContext) -> Self {
        let create_trimesh_collider = make_button(
            "Create Trimesh Collider",
            "Creates a new trimesh collider and attaches it to the selected mesh(es)",
            ctx,
        );
        let create_convex_collider = make_button(
            "Create Convex Collider",
            "Creates a new convex (polyhedron) collider and attaches it to the selected mesh(es).",
            ctx,
        );
        let create_trimesh_rigid_body = make_button(
            "Create Trimesh Rigid Body",
            "Creates a new static rigid body with trimesh collider and attaches the selected \
            mesh(es) to it.",
            ctx,
        );
        let add_convex_collider = make_button(
            "Add Convex Collider",
            "Creates a new convex (polyhedron) collider and attaches it to an ancestor rigid \
            body. This option could be useful if you have multiple meshes and want to put them into \
            a single rigid body.",
            ctx,
        );
        let add_trimesh_collider = make_button(
            "Add Trimesh Collider",
            "Creates a new trimesh collider and attaches it to an ancestor rigid body. This \
            option could be useful if you have multiple meshes and want to put them into a single \
            rigid body.",
            ctx,
        );
        let root_widget = StackPanelBuilder::new(
            WidgetBuilder::new()
                .with_visibility(false)
                .with_child(create_trimesh_collider)
                .with_child(create_convex_collider)
                .with_child(create_trimesh_rigid_body)
                .with_child(add_convex_collider)
                .with_child(add_trimesh_collider),
        )
        .build(ctx);

        ctx.inner()
            .send(root_widget, WidgetMessage::link_with(inspector_head));

        Self {
            root_widget,
            create_trimesh_collider,
            create_convex_collider,
            create_trimesh_rigid_body,
            add_convex_collider,
            add_trimesh_collider,
        }
    }

    pub fn handle_ui_message(
        &mut self,
        message: &UiMessage,
        editor_selection: &Selection,
        game_scene: &mut GameScene,
        engine: &mut Engine,
        sender: &MessageSender,
    ) {
        let Some(selection) = editor_selection.as_graph() else {
            return;
        };

        let scene = &engine.scenes[game_scene.scene];

        let mut commands = Vec::new();

        if let Some(ButtonMessage::Click) = message.data() {
            if message.destination() == self.create_trimesh_collider {
                for (mesh_handle, _) in meshes_iter(selection, scene) {
                    let collider =
                        ColliderBuilder::new(BaseBuilder::new().with_name("TrimeshCollider"))
                            .with_shape(ColliderShape::trimesh(vec![GeometrySource(mesh_handle)]))
                            .build_node();
                    commands.push(Command::new(AddNodeCommand::new(
                        collider,
                        mesh_handle,
                        false,
                    )))
                }
            } else if message.destination() == self.create_convex_collider {
                for (mesh_handle, _) in meshes_iter(selection, scene) {
                    let collider =
                        ColliderBuilder::new(BaseBuilder::new().with_name("ConvexCollider"))
                            .with_shape(ColliderShape::Polyhedron(ConvexPolyhedronShape {
                                geometry_source: GeometrySource(mesh_handle),
                            }))
                            .build_node();
                    commands.push(Command::new(AddNodeCommand::new(
                        collider,
                        mesh_handle,
                        false,
                    )))
                }
            } else if message.destination() == self.create_trimesh_rigid_body {
                let handles = scene
                    .graph
                    .generate_free_handles(2 * meshes_iter(selection, scene).count());

                for (rb_collider_handles, (mesh_handle, mesh)) in
                    handles.chunks(2).zip(meshes_iter(selection, scene))
                {
                    let rigid_body_handle = rb_collider_handles[0];
                    let collider_handle = rb_collider_handles[1];

                    let rigid_body =
                        RigidBodyBuilder::new(BaseBuilder::new().with_name("RigidBody"))
                            .with_body_type(RigidBodyType::Static)
                            .build_node();
                    let collider =
                        ColliderBuilder::new(BaseBuilder::new().with_name("TrimeshCollider"))
                            .with_shape(ColliderShape::trimesh(vec![GeometrySource(mesh_handle)]))
                            .build_node();
                    commands.extend([
                        Command::new(AddNodeCommand::new(rigid_body, mesh_handle, false)),
                        Command::new(AddNodeCommand::new(collider, rigid_body_handle, false)),
                        Command::new(LinkNodesCommand::new(rigid_body_handle, mesh.parent())),
                        Command::new(LinkNodesCommand::new(mesh_handle, rigid_body_handle)),
                        Command::new(LinkNodesCommand::new(collider_handle, rigid_body_handle)),
                    ]);
                }
            } else if message.destination() == self.add_convex_collider {
                for (mesh_handle, _) in meshes_iter(selection, scene) {
                    if let Some((ancestor_rigid_body, _)) =
                        scene.graph.find_component_up::<RigidBody>(mesh_handle)
                    {
                        let collider =
                            ColliderBuilder::new(BaseBuilder::new().with_name("ConvexCollider"))
                                .with_shape(ColliderShape::Polyhedron(ConvexPolyhedronShape {
                                    geometry_source: GeometrySource(mesh_handle),
                                }))
                                .build_node();
                        commands.push(Command::new(AddNodeCommand::new(
                            collider,
                            ancestor_rigid_body,
                            false,
                        )))
                    }
                }
            } else if message.destination() == self.add_trimesh_collider {
                for (mesh_handle, _) in meshes_iter(selection, scene) {
                    if let Some((ancestor_rigid_body, _)) =
                        scene.graph.find_component_up::<RigidBody>(mesh_handle)
                    {
                        let collider =
                            ColliderBuilder::new(BaseBuilder::new().with_name("TrimeshCollider"))
                                .with_shape(ColliderShape::trimesh(vec![GeometrySource(
                                    mesh_handle,
                                )]))
                                .build_node();
                        commands.push(Command::new(AddNodeCommand::new(
                            collider,
                            ancestor_rigid_body,
                            false,
                        )))
                    }
                }
            }
        }

        if !commands.is_empty() {
            sender.do_command(CommandGroup::from(commands));
        }
    }

    pub fn handle_message(
        &mut self,
        message: &Message,
        editor_selection: &Selection,
        game_scene: Option<&mut GameScene>,
        engine: &mut Engine,
    ) {
        let Message::SelectionChanged { .. } = message else {
            return;
        };

        let any_mesh = if let Some(game_scene) = game_scene {
            let scene = &engine.scenes[game_scene.scene];
            editor_selection.as_graph().is_some_and(|s| {
                s.nodes()
                    .iter()
                    .any(|n| scene.graph.try_get_of_type::<Mesh>(*n).is_ok())
            })
        } else {
            false
        };
        engine
            .user_interfaces
            .first()
            .send(self.root_widget, WidgetMessage::Visibility(any_mesh));
    }
}

pub struct SurfaceDataViewer {
    pub window: Handle<Window>,
    info: Handle<Text>,
    preview_panel: PreviewPanel,
}

fn surface_data_statistics(surface_data: &SurfaceData) -> Result<String, std::fmt::Error> {
    use std::fmt::Write;
    let mut stats = String::new();
    writeln!(
        &mut stats,
        "Vertices: {}\nVertex Size: {} bytes\nVertex Buffer Size: {} bytes",
        surface_data.vertex_buffer.vertex_count(),
        surface_data.vertex_buffer.vertex_size(),
        surface_data.vertex_buffer.raw_data().len()
    )?;
    for (i, attribute) in surface_data.vertex_buffer.layout().iter().enumerate() {
        writeln!(&mut stats, "[{i}]{attribute}")?;
    }
    let triangle_size = size_of::<TriangleDefinition>();
    writeln!(
        &mut stats,
        "Triangles: {}\nTriangle Size: {} bytes\nTriangle Buffer Size: {} bytes",
        surface_data.geometry_buffer.len(),
        triangle_size,
        surface_data.geometry_buffer.len() * triangle_size
    )?;
    Ok(stats)
}

impl SurfaceDataViewer {
    pub fn new(engine: &mut Engine) -> Self {
        let preview_panel = PreviewPanel::new(engine, 386, 386);

        let ctx = &mut engine.user_interfaces.first_mut().build_ctx();

        let info =
            TextBuilder::new(WidgetBuilder::new().with_vertical_alignment(VerticalAlignment::Top))
                .build(ctx);

        let content = GridBuilder::new(
            WidgetBuilder::new()
                .with_child(preview_panel.root)
                .with_child(
                    ScrollViewerBuilder::new(WidgetBuilder::new().on_row(0).on_column(1))
                        .with_content(info)
                        .build(ctx),
                ),
        )
        .add_row(Row::stretch())
        .add_column(Column::stretch())
        .add_column(Column::strict(220.0))
        .build(ctx);

        let window = WindowBuilder::new(WidgetBuilder::new().with_width(650.0).with_height(400.0))
            .open(false)
            .with_title(WindowTitle::text("Surface Data"))
            .with_content(content)
            .build(ctx);

        Self {
            window,
            info,
            preview_panel,
        }
    }

    pub fn open(&mut self, surface_data: SurfaceResource, engine: &mut Engine) {
        let guard = surface_data.data_ref();
        let ui = engine.user_interfaces.first();
        ui.send(
            self.info,
            TextMessage::Text(surface_data_statistics(&guard).unwrap_or_default()),
        );
        ui.send(
            self.window,
            WindowMessage::Open {
                alignment: WindowAlignment::Center,
                modal: true,
                focus_content: true,
            },
        );
        drop(guard);

        let graph = &mut engine.scenes[self.preview_panel.scene()].graph;
        let mesh = MeshBuilder::new(BaseBuilder::new())
            .with_surfaces(vec![SurfaceBuilder::new(surface_data).build()])
            .build(graph);

        self.preview_panel.set_model(mesh, engine);
    }

    pub fn handle_ui_message(mut self, message: &UiMessage, engine: &mut Engine) -> Option<Self> {
        self.preview_panel.handle_message(message, engine);

        if let Some(WindowMessage::Close) = message.data() {
            if message.destination() == self.window {
                self.preview_panel.destroy(engine);
                return None;
            }
        }

        Some(self)
    }

    pub fn update(&mut self, engine: &mut Engine) {
        self.preview_panel.update(engine)
    }
}