hotline-rs 0.3.2

A high-performance, hot-reload graphics 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
// currently windows only because here we need a concrete gfx and os implementation
#![cfg(target_os = "windows")]

use crate::{client, pmfx, imdraw, gfx_platform, os_platform};

use bevy_ecs::prelude::*;
use maths_rs::prelude::*;

use serde::{Deserialize, Serialize};
use std::ops::Deref;
use std::ops::DerefMut;
use std::collections::HashMap;

/// Schedule info can be filled out and passed to the `ecs` plugin to build a schedulre for a running demo
pub struct ScheduleInfo {
    /// List of setup functions by their name, the function name must be registered in a `get_system_function` 
    /// all setup systems will run concurrently
    pub setup: Vec<String>,
    /// List of update functions by their name, the function name must be registered in a `get_system_function` 
    /// all update systems will run concurrently
    pub update: Vec<String>,
    /// Name of the render graph to load, buld and make active from pmfx
    pub render_graph: &'static str
}

/// Empty schedule info
impl Default for ScheduleInfo {
    fn default() -> ScheduleInfo {
        ScheduleInfo {
            setup: Vec::new(),
            update: Vec::new(),
            render_graph: "",
        }
    }
}

/// Serialisable camera info
#[derive(Serialize, Deserialize, Clone, Copy)]
pub struct CameraInfo {
    pub camera_type: CameraType,
    pub pos: (f32, f32, f32),
    pub rot: (f32, f32, f32),
    pub focus: (f32, f32, f32),
    pub zoom: f32,
    pub aspect: f32,
    pub fov: f32,
}

/// Sensible default values for a 3D perspective camera looking downward in the y-axis to an xz-plane
impl Default for CameraInfo {
    fn default() -> CameraInfo {
        CameraInfo {
            camera_type: CameraType::Fly,
            zoom: 500.0,
            pos: (0.0, 150.0, 150.0),
            rot: (-45.0, 0.0, 0.0),
            focus: (0.0, 0.0, 0.0),
            aspect: 16.0/9.0,
            fov: 60.0
        }
    }
}

bitflags! {
    #[derive(Serialize, Deserialize, Resource, Default)]
    pub struct DebugDrawFlags: u32 {
        const NONE      = 0b00000000;
        const GRID      = 0b00000001;
        const AABB      = 0b00000010;
        const OBB       = 0b00000100;
        const CAMERAS   = 0b00001000;
    }
}

/// Seriablisable user info for maintaining state between reloads and sessions
#[derive(Serialize, Deserialize, Default, Resource, Clone)]
pub struct SessionInfo {
    /// The active running demo will be saved between sessions
    pub active_demo: String,
    /// Main camera setings will be saved between sessions
    pub main_camera: Option<CameraInfo>,
    /// Default camera for a demo, can be set by the camera button in the UI
    pub default_cameras: Option<HashMap<String, CameraInfo>>,
    /// Debug draw flags
    pub debug_draw_flags: DebugDrawFlags
}

/// This macro allows you to create a newtype which will automatically deref and deref_mut
/// you can use it to create resources or compnents and avoid having to use .0 to access the inner data
#[macro_export]
macro_rules! hotline_ecs {
    ($derive:ty, $name:ident, $inner:ty) => {
        #[derive($derive)]
        pub struct $name(pub $inner);
        impl Deref for $name {
            type Target = $inner;
            fn deref(&self) -> &$inner {
                &self.0
            }
        }
        impl DerefMut for $name {
            fn deref_mut(&mut self) -> &mut $inner {
                &mut self.0
            }
        }
    }
}

//
// Resources
//

hotline_ecs!(Resource, TimeRes, client::Time);
hotline_ecs!(Resource, PmfxRes, pmfx::Pmfx<gfx_platform::Device>);
hotline_ecs!(Resource, DeviceRes, gfx_platform::Device);
hotline_ecs!(Resource, AppRes, os_platform::App);
hotline_ecs!(Resource, MainWindowRes,os_platform::Window);
hotline_ecs!(Resource, ImDrawRes, imdraw::ImDraw<gfx_platform::Device>);
hotline_ecs!(Resource, UserConfigRes, client::UserConfig);

//
// Components
//

hotline_ecs!(Component, Name, String);
hotline_ecs!(Component, Parent, Entity);
hotline_ecs!(Component, Velocity, Vec3f);
hotline_ecs!(Component, Position, Vec3f);
hotline_ecs!(Component, Rotation, Quatf);
hotline_ecs!(Component, Scale, Vec3f);
hotline_ecs!(Component, Colour, Vec4f);
hotline_ecs!(Component, LocalMatrix, Mat34f);
hotline_ecs!(Component, WorldMatrix, Mat34f);
hotline_ecs!(Component, ViewProjectionMatrix, Mat4f);
hotline_ecs!(Component, MeshComponent, pmfx::Mesh<gfx_platform::Device>);
hotline_ecs!(Component, PipelineComponent, String);
hotline_ecs!(Component, TextureComponent, gfx_platform::Texture);
hotline_ecs!(Component, BufferComponent, gfx_platform::Buffer);
hotline_ecs!(Component, TextureInstance, u32);
hotline_ecs!(Component, TimeComponent, f32);
hotline_ecs!(Component, CommandSignatureComponent, gfx_platform::CommandSignature);

#[derive(Component)]
pub struct InstanceBuffer {
    pub heap: Option<gfx_platform::Heap>,
    pub buffer: gfx_platform::Buffer,
    pub instance_count: u32
}

#[derive(Bundle)]
pub struct InstanceBatch {
    pub mesh: MeshComponent,
    pub pipeline: PipelineComponent,
    pub instance_buffer: InstanceBuffer,
}

#[derive(Component)]
pub struct Extents {
    pub aabb_min: Vec3f,
    pub aabb_max: Vec3f
}

#[derive(Bundle)]
pub struct Instance {
    pub pos: Position,
    pub rot: Rotation,
    pub scale: Scale,
    pub world_matrix: WorldMatrix,
    pub parent: Parent
}

#[derive(Component)]
pub struct InstanceIds {
    pub entity_id: u32,
    pub material_id: u32
}

#[derive(Component)]
pub struct MaterialResources {
    pub albedo: gfx_platform::Texture,
    pub normal: gfx_platform::Texture,
    pub roughness: gfx_platform::Texture
}

#[derive(Component)]
pub struct Camera {
    pub rot: Vec3f,
    pub focus: Vec3f,
    pub zoom: f32,
    pub camera_type: CameraType
}

#[derive(Component)]
pub struct AnimatedTexture {
    pub frame : u32,
    pub frame_count: u32
}

#[derive(Component)]
pub struct MainCamera;

#[derive(Component)]
pub struct Billboard;

#[derive(Component)]
pub struct CylindricalBillboard;

#[derive(Debug, Clone, Copy)]
pub enum LightType {
    Point,
    Spot,
    Directional
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum CameraType {
    None,
    Fly,
    Orbit,
}

#[derive(Component)]
pub struct LightComponent {
    pub light_type: LightType,
    pub direction: Vec3f,
    pub cutoff: f32,
    pub falloff: f32,
    pub radius: f32,
    pub shadow_map_info: pmfx::ShadowMapInfo
}

impl Default for LightComponent {
    fn default() -> Self {
        Self {
            light_type: LightType::Directional,
            direction: vec3f(0.0, -1.0, 0.0),
            cutoff: f32::pi() / 8.0,
            falloff: 0.5,
            radius: 64.0,
            shadow_map_info: pmfx::ShadowMapInfo::default()
        }
    }
}

#[derive(Debug, Hash, PartialEq, Eq, Clone, SystemSet)]
pub enum SystemSets {
    Setup,
    Update,
    Batch,
    Render,
}

#[macro_export]
macro_rules! system_func {
    ($func:expr) => {
        Some($func.into_configs())
    }
}

#[macro_export]
macro_rules! render_func {
    ($func:expr, $view:expr, $query:ty) => {
        Some(render_func_closure![$func, $view, $query].into_configs().in_set(SystemSets::Render))
    }
}

#[macro_export]
macro_rules! compute_func {
    ($pass:expr) => {
        Some(compute_func_closure![$pass].into_configs().in_set(SystemSets::Render))
    }
}

#[macro_export]
macro_rules! compute_func_query {
    ($func:expr, $pass:expr, $query:ty) => {
        Some(compute_func_query_closure![$func, $pass, $query].into_configs().in_set(SystemSets::Render))
    }
}

/// This macro can be used to export a system render function for bevy ecs. You can pass a compatible 
/// system function with a `view` name which can be looked up when the function is called
/// so that a single render function can have different views
#[macro_export]
macro_rules! render_func_closure {
    ($func:expr, $view_name:expr, $query:ty) => {
        move |
            pmfx: Res<PmfxRes>,
            q: $query | {
                let view = pmfx.get_view(&$view_name);
                let err = match view {
                    Ok(v) => { 
                        let mut view = v.lock().unwrap();
                        
                        let col = view.colour_hash;
                        view.cmd_buf.begin_event(col, &$view_name);
                        view.cmd_buf.begin_render_pass(&view.pass);
                        view.cmd_buf.set_viewport(&view.viewport);
                        view.cmd_buf.set_scissor_rect(&view.scissor_rect);

                        let result = $func(
                            &pmfx,
                            &view,
                            q
                        );

                        view.cmd_buf.end_render_pass();
                        view.cmd_buf.end_event();
                        result
                    }
                    Err(v) => {
                        Err(hotline_rs::Error {
                            msg: v.msg
                        })
                    }
                };

                // record errors
                if let Err(err) = err {
                    pmfx.log_error(&$view_name, &err.msg);
                }
        }
    }
}

/// This macro can be used to export a system compute function for bevy ecs. You can pass a compatible 
/// system function with a `pass` name which can be looked up when the function is called
#[macro_export]
macro_rules! compute_func_closure {
    ($pass_name:expr) => {
        move | pmfx: Res<PmfxRes> | {
                
                let pass = pmfx.get_compute_pass(&$pass_name);
                let err = match pass {
                    Ok(p) => {
                        let mut pass = p.lock().unwrap();
                        let pipeline = pmfx.get_compute_pipeline(&pass.pass_pipline).unwrap();

                        pass.cmd_buf.begin_event(0xffffff, &$pass_name);
                        pass.cmd_buf.set_compute_pipeline(&pipeline);

                        let using_slot = pipeline.get_pipeline_slot(0, 1, gfx::DescriptorType::PushConstants);
                        if let Some(slot) = using_slot {
                            for i in 0..pass.use_indices.len() {
                                let num_constants = gfx::num_32bit_constants(&pass.use_indices[i]);
                                pass.cmd_buf.push_compute_constants(
                                    0, 
                                    num_constants, 
                                    i as u32 * num_constants, 
                                    gfx::as_u8_slice(&pass.use_indices[i])
                                );
                            }
                        }

                        pass.cmd_buf.set_heap(pipeline, &pmfx.shader_heap);
                        
                        pass.cmd_buf.dispatch(
                            pass.group_count,
                            pass.numthreads
                        );
                        pass.cmd_buf.end_event();

                        Ok(())
                    }
                    Err(p) => {
                        Err(hotline_rs::Error {
                            msg: p.msg
                        })
                    }
                };

                // record errors
                if let Err(err) = err {
                    pmfx.log_error(&$pass_name, &err.msg);
                }
            }
    }
}

#[macro_export]
macro_rules! compute_func_query_closure {
    ($func:expr, $pass_name:expr, $query:ty) => {
        move | 
            pmfx: Res<PmfxRes>,
            q: $query  | {
                let pass = pmfx.get_compute_pass(&$pass_name);
                let err = match pass {
                    Ok(p) => {
                        let mut pass = p.lock().unwrap();
                        pass.cmd_buf.begin_event(0xffffff, &$pass_name);

                        let result = $func(
                            &pmfx,
                            &mut pass,
                            q
                        );

                        pass.cmd_buf.end_event();

                        Ok(())
                    }
                    Err(p) => {
                        Err(hotline_rs::Error {
                            msg: p.msg
                        })
                    }
                };

                // record errors
                if let Err(err) = err {
                    pmfx.log_error(&$pass_name, &err.msg);
                }
            }
    }
}

/// You can use this macro to make the exporting of demo names for ecs plugins mor ergonomic, 
/// it will make a `Vec<String>` from a list of `&str`.
/// demos![
///     "primitives,
///     "draw_indexed"
///     "draw_indexed_instance"
/// ]
#[macro_export]
macro_rules! demos {
    ($($entry:expr),*) => {   
        vec![
            $($entry.to_string(),)+
        ]
    }
}

/// You can use this macro to make the exporting of systems names for ecs plugins more ergonomic, 
/// it will make a `Vec<String>` from a list of `&str`.
/// systems![
///     "update_camera,
///     "update_config"
/// ]
#[macro_export]
macro_rules! systems {
    ($($entry:expr),*) => {   
        vec![
            $($entry.to_string(),)+
        ]
    }
}