bevy_lagrange 0.0.3

Bevy camera controller with pan, orbit, zoom-to-fit, queued animations, and trackpad support
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
use bevy::camera::visibility::RenderLayers;
use bevy::prelude::*;
use bevy_kana::ToF32;

use super::convex_hull;
use super::labels;
use super::labels::BoundsLabel;
use super::labels::MarginLabel;
use super::labels::MarginLabelParams;
use super::screen_space;
use super::types::FitTargetGizmo;
use super::types::FitTargetOverlayConfig;
use super::types::FitTargetViewportMarginPcts;
use crate::components::CurrentFitTarget;
use crate::components::FitOverlay;
use crate::constants::TOLERANCE;
use crate::fit::Edge;
use crate::support;
use crate::support::CameraBasis;
use crate::support::ScreenSpaceBounds;

/// Calculates the color for an edge based on balance state.
const fn calculate_edge_color(
    edge: Edge,
    h_balanced: bool,
    v_balanced: bool,
    config: &FitTargetOverlayConfig,
) -> Color {
    match edge {
        Edge::Left | Edge::Right => {
            if h_balanced {
                config.balanced_color
            } else {
                config.unbalanced_color
            }
        },
        Edge::Top | Edge::Bottom => {
            if v_balanced {
                config.balanced_color
            } else {
                config.unbalanced_color
            }
        },
    }
}

/// Creates the 4 corners of the screen-aligned boundary rectangle in world space.
fn create_screen_corners(
    bounds: &ScreenSpaceBounds,
    camera: &CameraBasis,
    avg_depth: f32,
    is_ortho: bool,
) -> [Vec3; 4] {
    [
        screen_space::normalized_to_world(
            bounds.min_norm_x,
            bounds.min_norm_y,
            camera,
            avg_depth,
            is_ortho,
        ),
        screen_space::normalized_to_world(
            bounds.max_norm_x,
            bounds.min_norm_y,
            camera,
            avg_depth,
            is_ortho,
        ),
        screen_space::normalized_to_world(
            bounds.max_norm_x,
            bounds.max_norm_y,
            camera,
            avg_depth,
            is_ortho,
        ),
        screen_space::normalized_to_world(
            bounds.min_norm_x,
            bounds.max_norm_y,
            camera,
            avg_depth,
            is_ortho,
        ),
    ]
}

/// Draws the boundary rectangle outline.
fn draw_rectangle(
    gizmos: &mut Gizmos<FitTargetGizmo>,
    corners: &[Vec3; 4],
    config: &FitTargetOverlayConfig,
) {
    for i in 0..4 {
        let next = (i + 1) % 4;
        gizmos.line(corners[i], corners[next], config.rectangle_color);
    }
}

/// Draws the silhouette polygon (convex hull of projected vertices) using gizmo lines.
fn draw_silhouette(
    gizmos: &mut Gizmos<FitTargetGizmo>,
    vertices: &[Vec3],
    camera: &CameraBasis,
    avg_depth: f32,
    is_ortho: bool,
    color: Color,
) {
    let projected = convex_hull::project_vertices_to_2d(vertices, camera, is_ortho);
    let hull = convex_hull::convex_hull_2d(&projected);

    if hull.len() < 2 {
        return;
    }

    for i in 0..hull.len() {
        let next = (i + 1) % hull.len();
        let start =
            screen_space::normalized_to_world(hull[i].0, hull[i].1, camera, avg_depth, is_ortho);
        let end = screen_space::normalized_to_world(
            hull[next].0,
            hull[next].1,
            camera,
            avg_depth,
            is_ortho,
        );
        gizmos.line(start, end, color);
    }
}

/// Camera-derived drawing parameters shared across margin/bounds rendering.
struct DrawContext<'a> {
    camera:        Entity,
    bounds:        &'a ScreenSpaceBounds,
    camera_basis:  &'a CameraBasis,
    avg_depth:     f32,
    is_ortho:      bool,
    viewport_size: Option<Vec2>,
}

/// Draws margin lines from boundary edges to screen edges and updates margin labels.
/// Returns the set of edges that had visible margins.
fn draw_margin_lines_and_labels(
    commands: &mut Commands,
    gizmos: &mut Gizmos<FitTargetGizmo>,
    label_query: &mut Query<(Entity, &MarginLabel, &mut Text, &mut Node, &mut TextColor)>,
    ctx: &DrawContext,
    config: &FitTargetOverlayConfig,
) -> Vec<Edge> {
    let camera = ctx.camera;
    let bounds = ctx.bounds;
    let camera_basis = ctx.camera_basis;
    let avg_depth = ctx.avg_depth;
    let is_ortho = ctx.is_ortho;
    let viewport_size = ctx.viewport_size;
    let h_balanced = screen_space::is_horizontally_balanced(bounds, TOLERANCE);
    let v_balanced = screen_space::is_vertically_balanced(bounds, TOLERANCE);

    let mut visible_edges: Vec<Edge> = Vec::new();

    for edge in [Edge::Left, Edge::Right, Edge::Top, Edge::Bottom] {
        let Some((boundary_x, boundary_y)) = screen_space::boundary_edge_center(bounds, edge)
        else {
            continue;
        };
        visible_edges.push(edge);

        let (screen_x, screen_y) = screen_space::screen_edge_center(bounds, edge);
        let boundary_pos = screen_space::normalized_to_world(
            boundary_x,
            boundary_y,
            camera_basis,
            avg_depth,
            is_ortho,
        );
        let screen_pos = screen_space::normalized_to_world(
            screen_x,
            screen_y,
            camera_basis,
            avg_depth,
            is_ortho,
        );

        let color = calculate_edge_color(edge, h_balanced, v_balanced, config);
        gizmos.line(boundary_pos, screen_pos, color);

        let Some(vp) = viewport_size else {
            continue;
        };
        let percentage = screen_space::margin_percentage(bounds, edge);
        let text = format!("margin: {percentage:.3}%");
        let label_screen_pos = labels::calculate_label_pixel_position(edge, bounds, vp);

        labels::update_or_create_margin_label(
            commands,
            label_query,
            MarginLabelParams {
                camera,
                edge,
                text,
                color,
                screen_pos: label_screen_pos,
                viewport_size: vp,
            },
        );
    }

    visible_edges
}

/// Removes margin labels for edges no longer visible, scoped to a specific camera.
fn cleanup_stale_margin_labels(
    commands: &mut Commands,
    label_query: &Query<(Entity, &MarginLabel, &mut Text, &mut Node, &mut TextColor)>,
    camera: Entity,
    visible_edges: &[Edge],
) {
    for (entity, label, _, _, _) in label_query {
        if label.camera == camera && !visible_edges.contains(&label.edge) {
            commands.entity(entity).despawn();
        }
    }
}

/// Observer that cleans up visualization state when `FitVisualization` is removed from a camera.
pub(super) fn on_remove_fit_visualization(
    trigger: On<Remove, FitOverlay>,
    mut commands: Commands,
    label_query: Query<(Entity, &MarginLabel)>,
    bounds_label_query: Query<(Entity, &BoundsLabel)>,
) {
    let camera = trigger.entity;

    // Clean up viewport margins from the camera entity.
    // `try_remove` silently skips if the entity was despawned this frame
    // (e.g. closing a secondary window triggers component removal during despawn).
    commands
        .entity(camera)
        .try_remove::<FitTargetViewportMarginPcts>();

    // Clean up labels belonging to this camera
    for (entity, label) in &label_query {
        if label.camera == camera {
            commands.entity(entity).despawn();
        }
    }
    for (entity, label) in &bounds_label_query {
        if label.camera == camera {
            commands.entity(entity).despawn();
        }
    }
}

/// Syncs the gizmo render layers and line width with visualization-enabled cameras.
pub(super) fn sync_gizmo_render_layers(
    mut config_store: ResMut<GizmoConfigStore>,
    viz_config: Res<FitTargetOverlayConfig>,
    camera_query: Query<Option<&RenderLayers>, With<FitOverlay>>,
) {
    let (gizmo_config, _) = config_store.config_mut::<FitTargetGizmo>();
    gizmo_config.line.width = viz_config.line_width;
    gizmo_config.depth_bias = -1.0;

    // Apply render layers from the first visualization-enabled camera
    if let Some(Some(layers)) = camera_query.iter().next() {
        gizmo_config.render_layers = layers.clone();
    }
}

/// Draws screen-aligned bounds for all cameras with `FitVisualization`.
pub(super) fn draw_fit_target_bounds(
    mut commands: Commands,
    mut gizmos: Gizmos<FitTargetGizmo>,
    config: Res<FitTargetOverlayConfig>,
    camera_query: Query<
        (
            Entity,
            &Camera,
            &GlobalTransform,
            &Projection,
            &CurrentFitTarget,
        ),
        With<FitOverlay>,
    >,
    mesh_query: Query<&Mesh3d>,
    children_query: Query<&Children>,
    global_transform_query: Query<&GlobalTransform>,
    meshes: Res<Assets<Mesh>>,
    mut label_query: Query<(Entity, &MarginLabel, &mut Text, &mut Node, &mut TextColor)>,
    mut bounds_label_query: Query<(Entity, &BoundsLabel, &mut Node), Without<MarginLabel>>,
) {
    for (camera, camera_component, camera_global, projection, current_target) in &camera_query {
        let Some((vertices, _)) = support::extract_mesh_vertices(
            current_target.0,
            &children_query,
            &mesh_query,
            &global_transform_query,
            &meshes,
        ) else {
            continue;
        };

        draw_bounds_for_camera(
            &mut commands,
            &mut gizmos,
            &config,
            &BoundsCamera {
                entity: camera,
                camera_component,
                camera_global,
                projection,
            },
            &vertices,
            &mut label_query,
            &mut bounds_label_query,
        );
    }
}

/// Camera data for bounds visualization.
struct BoundsCamera<'a> {
    entity:           Entity,
    camera_component: &'a Camera,
    camera_global:    &'a GlobalTransform,
    projection:       &'a Projection,
}

/// Draws bounds visualization for a single camera/target pair.
fn draw_bounds_for_camera(
    commands: &mut Commands,
    gizmos: &mut Gizmos<FitTargetGizmo>,
    config: &FitTargetOverlayConfig,
    camera_data: &BoundsCamera,
    vertices: &[Vec3],
    label_query: &mut Query<(Entity, &MarginLabel, &mut Text, &mut Node, &mut TextColor)>,
    bounds_label_query: &mut Query<(Entity, &BoundsLabel, &mut Node), Without<MarginLabel>>,
) {
    let camera = camera_data.entity;
    let camera_component = camera_data.camera_component;
    let camera_global = camera_data.camera_global;
    let projection = camera_data.projection;

    let camera_basis = CameraBasis::from_global_transform(camera_global);

    let Some(aspect_ratio) =
        support::projection_aspect_ratio(projection, camera_component.logical_viewport_size())
    else {
        return;
    };

    let Some((bounds, depths)) =
        ScreenSpaceBounds::from_points(vertices, camera_global, projection, aspect_ratio)
    else {
        return;
    };

    let avg_depth = depths.sum / depths.count.to_f32();
    let is_ortho = matches!(projection, Projection::Orthographic(_));
    let viewport_size = camera_component.logical_viewport_size();

    // Update margin percentages on camera entity for BRP inspection.
    // `try_insert` silently skips if the entity was despawned this frame
    // (e.g. closing a secondary window while visualization is active).
    commands
        .entity(camera)
        .try_insert(FitTargetViewportMarginPcts::from_bounds(&bounds));

    // Bounding rectangle
    let corners = create_screen_corners(&bounds, &camera_basis, avg_depth, is_ortho);
    draw_rectangle(gizmos, &corners, config);

    // Silhouette convex hull
    draw_silhouette(
        gizmos,
        vertices,
        &camera_basis,
        avg_depth,
        is_ortho,
        config.silhouette_color,
    );

    // "Screen space bounds" label
    if let Some(vp) = viewport_size {
        let upper_left = screen_space::norm_to_viewport(
            bounds.min_norm_x,
            bounds.max_norm_y,
            bounds.half_extent_x,
            bounds.half_extent_y,
            vp,
        );
        labels::update_or_create_bounds_label(
            commands,
            bounds_label_query,
            camera,
            labels::bounds_label_position(upper_left),
        );
    }

    // Margin lines + labels
    let draw_ctx = DrawContext {
        camera,
        bounds: &bounds,
        camera_basis: &camera_basis,
        avg_depth,
        is_ortho,
        viewport_size,
    };
    let visible_edges =
        draw_margin_lines_and_labels(commands, gizmos, label_query, &draw_ctx, config);

    // Remove stale margin labels for this camera
    cleanup_stale_margin_labels(commands, label_query, camera, &visible_edges);
}