graphics 0.5.12

A 3D rendering engine for rust programs, with GUI integration
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
//! Handles keyboard and mouse input, eg for moving the camera.

use lin_alg::f32::{Quaternion, Vec3};
// todo: remove Winit from this module if you can, and make it agnostic?
use winit::event::{DeviceEvent, ElementState, MouseButton, MouseScrollDelta, WindowEvent};
use winit::keyboard::{KeyCode, PhysicalKey::Code};

use crate::{
    ScrollBehavior,
    camera::Camera,
    graphics::{FWD_VEC, RIGHT_VEC, UP_VEC},
    types::InputSettings,
};

const EPS_MOUSE: f32 = 0.00001;

#[derive(Default, Debug)]
pub struct InputsCommanded {
    pub fwd: bool,
    pub back: bool,
    pub left: bool,
    pub right: bool,
    pub up: bool,
    pub down: bool,
    pub roll_ccw: bool,
    pub roll_cw: bool,
    pub mouse_delta_x: f32,
    pub mouse_delta_y: f32,
    pub run: bool,
    pub scroll_up: bool,
    pub scroll_down: bool,
    pub free_look: bool,
    pub panning: bool, // todo: Implement A/R
    // todo: Move this A/R. Currently use it e.g. to disable scrolling moving if cursor
    // todo is not in window,
    pub cursor_out_of_window: bool,
}

impl InputsCommanded {
    /// Return true if there are any inputs.
    pub fn inputs_present(&self) -> bool {
        // Note; We don't include `run` or `free_look` here, since they're modifiers.
        self.fwd
            || self.back
            || self.left
            || self.right
            || self.up
            || self.down
            || self.roll_ccw
            || self.roll_cw
            || self.mouse_delta_x.abs() > EPS_MOUSE
            || self.mouse_delta_y.abs() > EPS_MOUSE
            || self.scroll_up
            || self.scroll_down
    }
}

/// Modifies the commanded inputs in place; triggered by a single input event.
/// dt is in seconds.
/// We use this for handling mouse movement. Note that the Wayland Linux UI backend doesn't support
/// any other types of device events.
///
/// If not configured to use device events, this only handles mouse motion.
pub(crate) fn add_input_cmd_device(
    event: &DeviceEvent,
    inputs: &mut InputsCommanded,
    use_dev_events: bool,
) {
    // This blocks all key and mouse commands from activating if the cursor has left
    // the window.
    // Device events can happen even if the window isn't active; use the cursor position
    // to identify this application as active.
    if inputs.cursor_out_of_window {
        // Resetting inputs effectively "lifts" all pressed keys, so we don't get stuck
        // moving in a direction when the cursor leaves.
        *inputs = InputsCommanded {
            cursor_out_of_window: true,
            ..Default::default()
        };
        return;
    }

    // Note: We only handle mouse movement events here; we now handle key and button
    // inputs in the window event handler.
    match event {
        DeviceEvent::Key(key) => {
            if !use_dev_events {
                return;
            }

            if let Code(key_code) = key.physical_key {
                handle_physical_key(inputs, key_code, key.state);
            };
        }

        DeviceEvent::Button { button, state } => {
            if !use_dev_events {
                return;
            }

            #[cfg(target_os = "linux")]
            let button_ = match button {
                1 => MouseButton::Left,
                3 => MouseButton::Right,
                2 => MouseButton::Middle,
                _ => MouseButton::Other(0), // Placeholder.
            };
            #[cfg(not(target_os = "linux"))]
            let button_ = match button {
                0 => MouseButton::Left,
                1 => MouseButton::Right,
                2 => MouseButton::Middle,
                _ => MouseButton::Other(0), // Placeholder.
            };

            handle_mouse_buttons(inputs, button_, *state);
        }

        // Move the camera forward and back on scroll.
        DeviceEvent::MouseWheel { delta } => {
            if !use_dev_events {
                return;
            }

            handle_mouse_wheel(inputs, delta)
        }
        DeviceEvent::MouseMotion { delta } => {
            inputs.mouse_delta_x += delta.0 as f32;
            inputs.mouse_delta_y += delta.1 as f32;
        }

        _ => (),
    }
}

/// Modifies the commanded inputs in place; triggered by a single input event.
/// dt is in seconds.
///
/// We use this for handling key, button, and scroll inputs.
pub(crate) fn add_input_cmd_window(
    event_: &WindowEvent,
    inputs: &mut InputsCommanded,
    use_dev_events: bool,
) {
    if use_dev_events {
        return;
    }

    match event_ {
        WindowEvent::KeyboardInput {
            device_id: _,
            event,
            is_synthetic: _,
        } => {
            if let Code(code) = event.physical_key {
                handle_physical_key(inputs, code, event.state)
            }
        }
        WindowEvent::MouseInput {
            device_id: _,
            state,
            button,
        } => handle_mouse_buttons(inputs, *button, *state),
        WindowEvent::MouseWheel {
            device_id: _,
            delta,
            phase: _,
        } => handle_mouse_wheel(inputs, delta),
        _ => (),
    }
}

fn handle_mouse_buttons(inputs: &mut InputsCommanded, button: MouseButton, state: ElementState) {
    if button == MouseButton::Left {
        inputs.free_look = match state {
            ElementState::Pressed => true,
            ElementState::Released => false,
        }
    }
}

fn handle_mouse_wheel(inputs: &mut InputsCommanded, delta: &MouseScrollDelta) {
    match delta {
        MouseScrollDelta::PixelDelta(_) => (),
        MouseScrollDelta::LineDelta(_x, y) => {
            if *y > 0. {
                inputs.scroll_down = true;
            } else {
                inputs.scroll_up = true;
            }
        }
    }
}

/// Handles keyboard input from either device, or window events.
/// Updates `inputs` with the result. For use with this library's built in commands, e.g.
/// for camera control.
fn handle_physical_key(inputs: &mut InputsCommanded, code: KeyCode, state: ElementState) {
    match state {
        ElementState::Pressed => match code {
            KeyCode::KeyW => {
                inputs.fwd = true;
            }
            KeyCode::KeyS => {
                inputs.back = true;
            }
            KeyCode::KeyA => {
                inputs.left = true;
            }
            KeyCode::KeyD => {
                inputs.right = true;
            }
            KeyCode::Space => {
                inputs.up = true;
            }
            KeyCode::KeyC => {
                inputs.down = true;
            }
            KeyCode::KeyQ => {
                inputs.roll_ccw = true;
            }
            KeyCode::KeyE => {
                inputs.roll_cw = true;
            }
            KeyCode::ShiftLeft => {
                inputs.run = true;
            }
            _ => (),
        },
        ElementState::Released => match code {
            KeyCode::KeyW => {
                inputs.fwd = false;
            }
            KeyCode::KeyS => {
                inputs.back = false;
            }
            KeyCode::KeyA => {
                inputs.left = false;
            }
            KeyCode::KeyD => {
                inputs.right = false;
            }
            KeyCode::Space => {
                inputs.up = false;
            }
            KeyCode::KeyC => {
                inputs.down = false;
            }
            KeyCode::KeyQ => {
                inputs.roll_ccw = false;
            }
            KeyCode::KeyE => {
                inputs.roll_cw = false;
            }
            KeyCode::ShiftLeft => {
                inputs.run = false;
            }
            _ => (),
        },
    }
}

/// For this library's built-in inputs, e.g. camera control.
fn handle_scroll(
    cam: &mut Camera,
    inputs: &mut InputsCommanded,
    input_settings: &InputSettings,
    dt: f32,
    movement_vec: &mut Vec3,
    rotation: &mut Quaternion,
    cam_moved: &mut bool,
    cam_rotated: &mut bool,
) {
    if inputs.scroll_down || inputs.scroll_up {
        if let ScrollBehavior::MoveRoll {
            move_amt,
            rotate_amt,
        } = input_settings.scroll_behavior
        {
            if inputs.free_look {
                // Roll if left button down while scrolling
                let fwd = cam.orientation.rotate_vec(FWD_VEC);

                let mut rot_amt = -rotate_amt * dt;
                if inputs.scroll_down {
                    rot_amt *= -1.; // todo: Allow reversed behavior for arc cam?
                }

                *rotation = Quaternion::from_axis_angle(fwd, rot_amt);
                *cam_rotated = true;
            } else {
                // Otherwise, move forward and backward.
                let mut movement = Vec3::new(0., 0., move_amt);
                if inputs.scroll_up {
                    movement *= -1.;
                }
                *movement_vec += movement;

                *cam_moved = true;
            }
        }

        // Immediately send the "release" command; not on a Release event like keys.
        inputs.scroll_down = false;
        inputs.scroll_up = false;
    }
}

/// Used internally for inputs, and externally, e.g. to command an arc rotation.
pub fn arc_rotation(cam: &mut Camera, axis: Vec3, amt: f32, center: Vec3) {
    let rotation = Quaternion::from_axis_angle(axis, amt);

    cam.orientation = (rotation * cam.orientation).to_normalized();

    let dist = (cam.position - center).magnitude();
    // Update position based on the new orientation.
    cam.position = center - cam.orientation.rotate_vec(FWD_VEC) * dist;
}

/// Adjust the camera orientation and position. Return if there was a change, so we know to update the buffer.
/// For the free (6DOF first-person) camera.
pub fn adjust_camera_free(
    cam: &mut Camera,
    inputs: &mut InputsCommanded,
    input_settings: &InputSettings,
    dt: f32,
) -> bool {
    let mut move_amt = input_settings.move_sens * dt;
    let mut rotate_key_amt = input_settings.rotate_key_sens * dt;

    let mut cam_moved = false;
    let mut cam_rotated = false;

    let mut movement_vec = Vec3::new_zero();
    let mut rotation = Quaternion::new_identity();

    if inputs.run {
        move_amt *= input_settings.run_factor;
        rotate_key_amt *= input_settings.run_factor;
    }

    if inputs.fwd {
        movement_vec.z += move_amt;
        cam_moved = true;
    } else if inputs.back {
        movement_vec.z -= move_amt;
        cam_moved = true;
    }

    if inputs.right {
        movement_vec.x += move_amt;
        cam_moved = true;
    } else if inputs.left {
        movement_vec.x -= move_amt;
        cam_moved = true;
    }

    if inputs.up {
        movement_vec.y += move_amt;
        cam_moved = true;
    } else if inputs.down {
        movement_vec.y -= move_amt;
        cam_moved = true;
    }

    if inputs.roll_cw {
        let fwd = cam.orientation.rotate_vec(FWD_VEC);
        rotation = Quaternion::from_axis_angle(fwd, -rotate_key_amt);
        cam_rotated = true;
    } else if inputs.roll_ccw {
        let fwd = cam.orientation.rotate_vec(FWD_VEC);
        rotation = Quaternion::from_axis_angle(fwd, rotate_key_amt);
        cam_rotated = true;
    }

    if inputs.free_look
        && (inputs.mouse_delta_x.abs() > EPS_MOUSE || inputs.mouse_delta_y.abs() > EPS_MOUSE)
    {
        let rotate_amt = input_settings.rotate_sens * dt;
        let up = cam.orientation.rotate_vec(-UP_VEC);
        let right = cam.orientation.rotate_vec(-RIGHT_VEC);

        rotation = Quaternion::from_axis_angle(up, -inputs.mouse_delta_x * rotate_amt)
            * Quaternion::from_axis_angle(right, -inputs.mouse_delta_y * rotate_amt)
            * rotation;

        cam_rotated = true;
    }

    handle_scroll(
        cam,
        inputs,
        input_settings,
        dt,
        &mut movement_vec,
        &mut rotation,
        &mut cam_moved,
        &mut cam_rotated,
    );

    // todo: Handle middleclick + drag here too. Move `mol_dock`'s impl here.

    if cam_rotated {
        cam.orientation = (rotation * cam.orientation).to_normalized();
    }

    if cam_moved {
        cam.position += cam.orientation.rotate_vec(movement_vec);
    }

    cam_moved || cam_rotated
}

/// Adjust the camera orientation and position. Return if there was a change, so we know to update the buffer.
/// For the arc (orbital) camera.
pub fn adjust_camera_arc(
    cam: &mut Camera,
    inputs: &mut InputsCommanded,
    input_settings: &InputSettings,
    center: Vec3,
    dt: f32,
) -> bool {
    // How fast we rotate, derived from your input settings:
    // Track if we actually moved/rotated:
    let mut cam_moved = false;
    let mut cam_rotated = false;

    let mut movement_vec = Vec3::new_zero();
    let mut rotation = Quaternion::new_identity();

    // todo: Combine this fn with adjust_free, and accept ControlScheme as a param.

    // Inverse of free
    let rotate_key_amt = -input_settings.rotate_key_sens * dt;

    if inputs.roll_cw {
        let fwd = cam.orientation.rotate_vec(FWD_VEC);
        rotation = Quaternion::from_axis_angle(fwd, -rotate_key_amt);
        cam_rotated = true;
    } else if inputs.roll_ccw {
        let fwd = cam.orientation.rotate_vec(FWD_VEC);
        rotation = Quaternion::from_axis_angle(fwd, rotate_key_amt);
        cam_rotated = true;
    }

    let mut skip_move_vec = false;
    // Only rotate if "free look" is active and the mouse moved enough:
    if inputs.free_look
        && (inputs.mouse_delta_x.abs() > EPS_MOUSE || inputs.mouse_delta_y.abs() > EPS_MOUSE)
    {
        let rotate_amt = input_settings.rotate_sens * dt;
        let up = cam.orientation.rotate_vec(-UP_VEC);
        let right = cam.orientation.rotate_vec(-RIGHT_VEC);

        // Rotation logic: Equivalent to the free camera.
        rotation = Quaternion::from_axis_angle(up, -inputs.mouse_delta_x * rotate_amt)
            * Quaternion::from_axis_angle(right, -inputs.mouse_delta_y * rotate_amt);

        // Distance between cam and center is invariant under this change.
        skip_move_vec = true;

        cam_moved = true;
        cam_rotated = true;
    }

    handle_scroll(
        cam,
        inputs,
        input_settings,
        dt,
        &mut movement_vec,
        &mut rotation,
        &mut cam_moved,
        &mut cam_rotated,
    );

    // todo: Handle middleclick + drag here too. Move `mol_dock`'s impl here.

    // note: We are not using our `arc_roation` fn here due to needing to handle both x and y. Hmm.
    // arc_rotation(cam, axis, amt, center);

    if cam_rotated {
        cam.orientation = (rotation * cam.orientation).to_normalized();
    }

    if cam_moved && !skip_move_vec {
        cam.position += cam.orientation.rotate_vec(movement_vec);
    } else if cam_moved {
        // todo: Bit odd to break this off from the above.
        let dist = (cam.position - center).magnitude();
        // Update position based on the new orientation.
        cam.position = center - cam.orientation.rotate_vec(FWD_VEC) * dist;
    }

    cam_moved || cam_rotated
}