bimifc-bevy 0.3.0

Bevy-based 3D viewer for IFC models with WebGPU/WebGL2 rendering
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
//! Picking and selection system
//!
//! Handles raycasting for object selection and hover detection.

use crate::camera::MainCamera;
use crate::mesh::{BatchedMesh, TriangleEntityMapping};
use crate::storage::{save_selection, SelectionStorage};
use bevy::math::Affine3A;
use bevy::prelude::*;
use bevy::window::PrimaryWindow;
use rustc_hash::FxHashSet;

/// Picking plugin
pub struct PickingPlugin;

impl Plugin for PickingPlugin {
    fn build(&self, app: &mut App) {
        app.init_resource::<SelectionState>()
            .init_resource::<PickingSettings>()
            .init_resource::<MeasurementState>()
            // Run picking after camera input so we can see just_clicked flag
            .add_systems(
                Update,
                (
                    poll_active_tool,
                    // measure_system must run before picking_system
                    // because both consume just_clicked
                    measure_system.after(poll_active_tool),
                    picking_system.after(measure_system),
                    hover_system,
                    draw_measurements,
                )
                    .after(crate::camera::CameraPlugin::input_system_set()),
            );
    }
}

/// Active measurements in the scene
#[derive(Resource, Default)]
pub struct MeasurementState {
    /// Completed measurements: (start, end)
    pub measurements: Vec<(Vec3, Vec3)>,
    /// First point of in-progress measurement
    pub pending: Option<Vec3>,
    /// Whether measure tool is active (polled from localStorage periodically)
    pub active: bool,
}

/// Current selection state
#[derive(Resource, Default)]
pub struct SelectionState {
    /// Currently selected entity IDs
    pub selected: FxHashSet<u64>,
    /// Currently hovered entity ID
    pub hovered: Option<u64>,
}

impl SelectionState {
    /// Check if entity is selected
    pub fn is_selected(&self, id: u64) -> bool {
        self.selected.contains(&id)
    }

    /// Select single entity (clears previous selection)
    pub fn select(&mut self, id: u64) {
        self.selected.clear();
        self.selected.insert(id);
        self.save();
    }

    /// Toggle selection for entity
    pub fn toggle(&mut self, id: u64) {
        if self.selected.contains(&id) {
            self.selected.remove(&id);
        } else {
            self.selected.insert(id);
        }
        self.save();
    }

    /// Add to selection
    pub fn add(&mut self, id: u64) {
        self.selected.insert(id);
        self.save();
    }

    /// Remove from selection
    pub fn remove(&mut self, id: u64) {
        self.selected.remove(&id);
        self.save();
    }

    /// Clear all selection
    pub fn clear(&mut self) {
        self.selected.clear();
        self.save();
    }

    /// Save to localStorage
    fn save(&self) {
        let storage = SelectionStorage {
            selected_ids: self.selected.iter().copied().collect(),
            hovered_id: self.hovered,
        };
        save_selection(&storage);
    }
}

/// Picking settings
#[derive(Resource)]
pub struct PickingSettings {
    /// Whether picking is enabled
    pub enabled: bool,
    /// Hover detection throttle (frames)
    pub hover_throttle: u32,
}

impl Default for PickingSettings {
    fn default() -> Self {
        Self {
            enabled: true,
            hover_throttle: 3, // Check every 3 frames
        }
    }
}

/// Picking system - handles click selection on batched meshes
#[allow(clippy::too_many_arguments)]
fn picking_system(
    keyboard: Res<ButtonInput<KeyCode>>,
    cameras: Query<(&Camera, &GlobalTransform), With<MainCamera>>,
    batched_meshes: Query<(&BatchedMesh, &GlobalTransform, &Mesh3d)>,
    triangle_mapping: Res<TriangleEntityMapping>,
    meshes: Res<Assets<Mesh>>,
    mut selection: ResMut<SelectionState>,
    settings: Res<PickingSettings>,
    mut camera_controller: ResMut<crate::camera::CameraController>,
) {
    if !settings.enabled {
        return;
    }

    // Use camera controller's click detection (click = press+release without drag)
    if !camera_controller.just_clicked {
        return;
    }

    // Reset the flag so we only process once
    camera_controller.just_clicked = false;

    let Ok((camera, camera_transform)) = cameras.single() else {
        return;
    };

    // Use the position where the click started
    let click_pos = camera_controller.drag_start_pos;

    // Create ray from camera through click position
    let Ok(ray) = camera.viewport_to_world(camera_transform, click_pos) else {
        return;
    };

    // Find closest intersection in batched meshes
    let mut closest: Option<(u64, f32, Vec3)> = None;

    for (batched_mesh, transform, mesh_handle) in batched_meshes.iter() {
        if let Some(mesh) = meshes.get(&mesh_handle.0) {
            if let Some((distance, triangle_index, hit_point)) =
                ray_mesh_intersection_with_triangle(&ray, mesh, transform)
            {
                // Look up which entity this triangle belongs to
                if let Some(entity_id) =
                    triangle_mapping.get_entity(batched_mesh.is_transparent, triangle_index)
                {
                    if closest.map(|(_, d, _)| distance < d).unwrap_or(true) {
                        closest = Some((entity_id, distance, hit_point));
                    }
                }
            }
        }
    }

    // Update selection based on result
    if let Some((entity_id, _, _)) = closest {
        let ctrl_pressed = keyboard.pressed(KeyCode::ControlLeft)
            || keyboard.pressed(KeyCode::ControlRight)
            || keyboard.pressed(KeyCode::SuperLeft)
            || keyboard.pressed(KeyCode::SuperRight);

        if ctrl_pressed {
            selection.toggle(entity_id);
        } else {
            selection.select(entity_id);
        }
    } else {
        // Clicked on empty space - clear selection
        if !keyboard.pressed(KeyCode::ControlLeft) && !keyboard.pressed(KeyCode::ControlRight) {
            selection.clear();
        }
    }
}

/// Hover system - detects entity under cursor using batched meshes
#[allow(clippy::too_many_arguments)]
fn hover_system(
    windows: Query<&Window, With<PrimaryWindow>>,
    cameras: Query<(&Camera, &GlobalTransform), With<MainCamera>>,
    batched_meshes: Query<(&BatchedMesh, &GlobalTransform, &Mesh3d)>,
    triangle_mapping: Res<TriangleEntityMapping>,
    meshes: Res<Assets<Mesh>>,
    mut selection: ResMut<SelectionState>,
    settings: Res<PickingSettings>,
    mut frame_counter: Local<u32>,
) {
    if !settings.enabled {
        return;
    }

    // Throttle hover detection
    *frame_counter += 1;
    if !(*frame_counter).is_multiple_of(settings.hover_throttle) {
        return;
    }

    let Ok(window) = windows.single() else { return };
    let Some(cursor_pos) = window.cursor_position() else {
        if selection.hovered.is_some() {
            selection.hovered = None;
        }
        return;
    };
    let Ok((camera, camera_transform)) = cameras.single() else {
        return;
    };

    // Create ray from camera through cursor
    let Ok(ray) = camera.viewport_to_world(camera_transform, cursor_pos) else {
        return;
    };

    // Find closest intersection in batched meshes
    let mut closest: Option<(u64, f32)> = None;

    for (batched_mesh, transform, mesh_handle) in batched_meshes.iter() {
        if let Some(mesh) = meshes.get(&mesh_handle.0) {
            if let Some((distance, triangle_index, _hit)) =
                ray_mesh_intersection_with_triangle(&ray, mesh, transform)
            {
                // Look up which entity this triangle belongs to
                if let Some(entity_id) =
                    triangle_mapping.get_entity(batched_mesh.is_transparent, triangle_index)
                {
                    if closest.map(|(_, d)| distance < d).unwrap_or(true) {
                        closest = Some((entity_id, distance));
                    }
                }
            }
        }
    }

    // Update hover state
    let new_hovered = closest.map(|(id, _)| id);
    if selection.hovered != new_hovered {
        selection.hovered = new_hovered;
    }
}

/// Ray-mesh intersection with triangle index for batched mesh picking
/// Returns (distance, triangle_index, hit_point) of the closest hit
fn ray_mesh_intersection_with_triangle(
    ray: &Ray3d,
    mesh: &Mesh,
    transform: &GlobalTransform,
) -> Option<(f32, usize, Vec3)> {
    // Get vertex positions
    let positions = mesh.attribute(Mesh::ATTRIBUTE_POSITION)?.as_float3()?;

    // First do a quick AABB check from vertex positions
    let transform_matrix = transform.affine();
    let (min, max) = compute_world_aabb(positions, &transform_matrix);

    // Quick AABB rejection test
    if !ray_aabb_intersects(ray, min, max) {
        return None;
    }

    // Get indices
    let indices = mesh.indices()?;
    let indices: Vec<usize> = indices.iter().collect();

    let mut closest: Option<(f32, usize, Vec3)> = None;

    // Iterate through triangles
    for (tri_idx, chunk) in indices.chunks(3).enumerate() {
        if chunk.len() < 3 {
            continue;
        }
        let v0 = transform_matrix.transform_point3(Vec3::from(positions[chunk[0]]));
        let v1 = transform_matrix.transform_point3(Vec3::from(positions[chunk[1]]));
        let v2 = transform_matrix.transform_point3(Vec3::from(positions[chunk[2]]));

        if let Some(t) = ray_triangle_intersection(ray, v0, v1, v2) {
            if t > 0.0 && closest.map(|(d, _, _)| t < d).unwrap_or(true) {
                let hit_point = ray.origin + *ray.direction * t;
                closest = Some((t, tri_idx, hit_point));
            }
        }
    }

    closest
}

/// Compute world-space AABB from vertex positions
fn compute_world_aabb(positions: &[[f32; 3]], transform: &Affine3A) -> (Vec3, Vec3) {
    let mut min = Vec3::splat(f32::MAX);
    let mut max = Vec3::splat(f32::MIN);

    for pos in positions {
        let world_pos = transform.transform_point3(Vec3::from(*pos));
        min = min.min(world_pos);
        max = max.max(world_pos);
    }

    (min, max)
}

/// Möller–Trumbore ray-triangle intersection algorithm
fn ray_triangle_intersection(ray: &Ray3d, v0: Vec3, v1: Vec3, v2: Vec3) -> Option<f32> {
    const EPSILON: f32 = 1e-7;

    let edge1 = v1 - v0;
    let edge2 = v2 - v0;
    let h = ray.direction.cross(edge2);
    let a = edge1.dot(h);

    // Ray is parallel to triangle
    if a.abs() < EPSILON {
        return None;
    }

    let f = 1.0 / a;
    let s = ray.origin - v0;
    let u = f * s.dot(h);

    if !(0.0..=1.0).contains(&u) {
        return None;
    }

    let q = s.cross(edge1);
    let v = f * ray.direction.dot(q);

    if v < 0.0 || u + v > 1.0 {
        return None;
    }

    let t = f * edge2.dot(q);
    if t > EPSILON {
        Some(t)
    } else {
        None
    }
}

/// Poll active tool from localStorage (every ~10 frames to avoid DOM thrashing)
fn poll_active_tool(mut measurement: ResMut<MeasurementState>, mut frame: Local<u32>) {
    *frame += 1;
    if !(*frame).is_multiple_of(10) {
        return;
    }
    let is_measure = crate::storage::load_active_tool()
        .map(|t| t == "measure")
        .unwrap_or(false);
    measurement.active = is_measure;
}

/// Measurement system — when "measure" tool is active, clicks add measurement points
#[allow(clippy::too_many_arguments)]
fn measure_system(
    cameras: Query<(&Camera, &GlobalTransform), With<MainCamera>>,
    batched_meshes: Query<(&BatchedMesh, &GlobalTransform, &Mesh3d)>,
    meshes: Res<Assets<Mesh>>,
    mut measurement: ResMut<MeasurementState>,
    mut camera_controller: ResMut<crate::camera::CameraController>,
    keyboard: Res<ButtonInput<KeyCode>>,
) {
    if !measurement.active {
        return;
    }

    // Escape clears pending + all measurements
    if keyboard.just_pressed(KeyCode::Escape) {
        measurement.pending = None;
        measurement.measurements.clear();
        crate::log_info("[Measure] Cleared all measurements");
        return;
    }

    if !camera_controller.just_clicked {
        return;
    }

    // Consume the click so picking_system doesn't also process it
    camera_controller.just_clicked = false;

    let Ok((camera, camera_transform)) = cameras.single() else {
        return;
    };
    let click_pos = camera_controller.drag_start_pos;
    let Ok(ray) = camera.viewport_to_world(camera_transform, click_pos) else {
        return;
    };

    // Find closest hit point
    let mut closest: Option<(f32, Vec3)> = None;
    for (_batched_mesh, transform, mesh_handle) in batched_meshes.iter() {
        if let Some(mesh) = meshes.get(&mesh_handle.0) {
            if let Some((distance, _tri, hit_point)) =
                ray_mesh_intersection_with_triangle(&ray, mesh, transform)
            {
                if closest.map(|(d, _)| distance < d).unwrap_or(true) {
                    closest = Some((distance, hit_point));
                }
            }
        }
    }

    if let Some((_, hit_point)) = closest {
        // Save point to bridge for Leptos
        crate::storage::save_measure_point(&crate::storage::MeasurePointStorage {
            x: hit_point.x,
            y: hit_point.y,
            z: hit_point.z,
        });

        if let Some(start) = measurement.pending.take() {
            // Complete measurement
            let dist = (hit_point - start).length();
            measurement.measurements.push((start, hit_point));
            crate::log_info(&format!("[Measure] Distance: {:.3}m", dist));
        } else {
            // Start new measurement
            measurement.pending = Some(hit_point);
            crate::log_info(&format!(
                "[Measure] Point 1 set ({:.2}, {:.2}, {:.2}) — click point 2",
                hit_point.x, hit_point.y, hit_point.z,
            ));
        }
    }
}

/// Draw measurement lines and distance labels as gizmos
fn draw_measurements(measurement: Res<MeasurementState>, mut gizmos: Gizmos) {
    if !measurement.active && measurement.measurements.is_empty() && measurement.pending.is_none() {
        return;
    }

    let yellow = Color::srgb(1.0, 0.85, 0.0);
    let red = Color::srgb(1.0, 0.3, 0.3);
    let cyan = Color::srgb(0.0, 0.9, 1.0);

    // Draw completed measurements
    for (start, end) in &measurement.measurements {
        // Main measurement line
        gizmos.line(*start, *end, yellow);
        // Parallel offset lines for visibility
        let dir = (*end - *start).normalize();
        let offset = if dir.cross(Vec3::Y).length() > 0.1 {
            dir.cross(Vec3::Y).normalize() * 0.02
        } else {
            dir.cross(Vec3::X).normalize() * 0.02
        };
        gizmos.line(*start + offset, *end + offset, yellow);
        gizmos.line(*start - offset, *end - offset, yellow);

        // Endpoint markers — small spheres via circle gizmos
        let sphere_size = 0.06;
        gizmos.sphere(Isometry3d::from_translation(*start), sphere_size, red);
        gizmos.sphere(Isometry3d::from_translation(*end), sphere_size, red);

        // Distance text via midpoint marker (larger sphere shows there's a measurement)
        let mid = (*start + *end) / 2.0;
        gizmos.sphere(Isometry3d::from_translation(mid), 0.03, yellow);
    }

    // Draw pending measurement (first point — pulsing crosshair)
    if let Some(start) = measurement.pending {
        let size = 0.12;
        gizmos.sphere(Isometry3d::from_translation(start), 0.08, cyan);
        gizmos.line(start - Vec3::X * size, start + Vec3::X * size, cyan);
        gizmos.line(start - Vec3::Y * size, start + Vec3::Y * size, cyan);
        gizmos.line(start - Vec3::Z * size, start + Vec3::Z * size, cyan);
    }
}

/// Quick ray-AABB intersection test
fn ray_aabb_intersects(ray: &Ray3d, min: Vec3, max: Vec3) -> bool {
    let inv_dir = Vec3::new(
        1.0 / ray.direction.x,
        1.0 / ray.direction.y,
        1.0 / ray.direction.z,
    );

    let t1 = (min - ray.origin) * inv_dir;
    let t2 = (max - ray.origin) * inv_dir;

    let tmin = t1.min(t2);
    let tmax = t1.max(t2);

    let t_enter = tmin.x.max(tmin.y).max(tmin.z);
    let t_exit = tmax.x.min(tmax.y).min(tmax.z);

    t_enter <= t_exit && t_exit >= 0.0
}