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
514
515
516
517
518
519
520
521
522
523
524
525
//! Storage types and localStorage bridge
//!
//! In unified mode (bevy-ui): No external JS bridge needed, files loaded directly
//! In external-ui mode: Uses localStorage/JS bridge to communicate with Yew

use serde::{Deserialize, Serialize};

#[cfg(target_arch = "wasm32")]
use wasm_bindgen::prelude::*;

// JavaScript FFI to get geometry from JS bridge (set by Yew)
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen]
extern "C" {
    /// Get timestamp from JS bridge
    #[wasm_bindgen(js_name = getIfcTimestamp)]
    fn js_get_ifc_timestamp() -> Option<String>;

    /// Get geometry binary from JS bridge
    #[wasm_bindgen(js_name = getIfcGeometryBinary)]
    fn js_get_ifc_geometry_binary() -> Option<js_sys::Uint8Array>;

    /// Get entities JSON from JS bridge
    #[wasm_bindgen(js_name = getIfcEntities)]
    fn js_get_ifc_entities() -> Option<String>;

    /// Clear geometry from JS bridge to free memory
    #[wasm_bindgen(js_name = clearIfcGeometryBridge)]
    fn js_clear_ifc_geometry_bridge();
}

/// Selection state for storage
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct SelectionStorage {
    pub selected_ids: Vec<u64>,
    pub hovered_id: Option<u64>,
}

/// Visibility state for storage
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct VisibilityStorage {
    pub hidden: Vec<u64>,
    pub isolated: Option<Vec<u64>>,
}

/// Camera state for storage
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CameraStorage {
    pub azimuth: f32,
    pub elevation: f32,
    pub distance: f32,
    pub target: [f32; 3],
}

impl Default for CameraStorage {
    fn default() -> Self {
        Self {
            azimuth: 0.785,   // 45 degrees
            elevation: 0.615, // ~35 degrees (isometric)
            distance: 10.0,
            target: [0.0, 0.0, 0.0],
        }
    }
}

/// Section plane state for storage
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct SectionStorage {
    pub enabled: bool,
    pub axis: String,  // "x", "y", or "z"
    pub position: f32, // 0.0 to 1.0
    pub flipped: bool,
}

/// Focus command for zooming to entity
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct FocusStorage {
    pub entity_id: u64,
}

/// Camera command from UI
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CameraCommandStorage {
    pub cmd: String,
    pub mode: Option<String>,
}

// ============================================================================
// JS Bridge functions - used in unified Yew+Bevy mode
// ============================================================================

/// Get timestamp from JS bridge
#[cfg(target_arch = "wasm32")]
pub fn get_timestamp() -> Option<String> {
    js_get_ifc_timestamp()
}

#[cfg(not(target_arch = "wasm32"))]
pub fn get_timestamp() -> Option<String> {
    None
}

/// Binary format magic number (must match bridge.rs)
#[allow(dead_code)]
const BINARY_MAGIC: u32 = 0x49464342; // "IFCB"

/// Read f32 values from unaligned byte slice
#[cfg(target_arch = "wasm32")]
fn read_f32_vec(data: &[u8], offset: &mut usize, count: usize) -> Option<Vec<f32>> {
    let bytes_needed = count * 4;
    if *offset + bytes_needed > data.len() {
        return None;
    }
    let mut result = Vec::with_capacity(count);
    for _ in 0..count {
        let bytes: [u8; 4] = data[*offset..*offset + 4].try_into().ok()?;
        result.push(f32::from_le_bytes(bytes));
        *offset += 4;
    }
    Some(result)
}

/// Read u32 values from unaligned byte slice
#[cfg(target_arch = "wasm32")]
fn read_u32_vec(data: &[u8], offset: &mut usize, count: usize) -> Option<Vec<u32>> {
    let bytes_needed = count * 4;
    if *offset + bytes_needed > data.len() {
        return None;
    }
    let mut result = Vec::with_capacity(count);
    for _ in 0..count {
        let bytes: [u8; 4] = data[*offset..*offset + 4].try_into().ok()?;
        result.push(u32::from_le_bytes(bytes));
        *offset += 4;
    }
    Some(result)
}

/// Deserialize geometry from binary format
#[cfg(target_arch = "wasm32")]
fn deserialize_geometry_binary(data: &[u8]) -> Option<Vec<crate::IfcMesh>> {
    use crate::mesh::MeshGeometry;
    use std::sync::Arc;

    if data.len() < 12 {
        return None;
    }

    let mut offset = 0;

    // Read header
    let magic = u32::from_le_bytes(data[offset..offset + 4].try_into().ok()?);
    offset += 4;
    if magic != BINARY_MAGIC {
        web_sys::console::error_1(&format!("[Bevy] Invalid geometry magic: {:08x}", magic).into());
        return None;
    }

    let _version = u32::from_le_bytes(data[offset..offset + 4].try_into().ok()?);
    offset += 4;

    let mesh_count = u32::from_le_bytes(data[offset..offset + 4].try_into().ok()?) as usize;
    offset += 4;

    let mut meshes = Vec::with_capacity(mesh_count);

    for _ in 0..mesh_count {
        if offset + 8 > data.len() {
            break;
        }

        // entity_id
        let entity_id = u64::from_le_bytes(data[offset..offset + 8].try_into().ok()?);
        offset += 8;

        // positions
        let positions_len = u32::from_le_bytes(data[offset..offset + 4].try_into().ok()?) as usize;
        offset += 4;
        if offset + positions_len * 4 > data.len() {
            break;
        }
        let positions = read_f32_vec(data, &mut offset, positions_len)?;

        // normals
        let normals_len = u32::from_le_bytes(data[offset..offset + 4].try_into().ok()?) as usize;
        offset += 4;
        if offset + normals_len * 4 > data.len() {
            break;
        }
        let normals = read_f32_vec(data, &mut offset, normals_len)?;

        // indices
        let indices_len = u32::from_le_bytes(data[offset..offset + 4].try_into().ok()?) as usize;
        offset += 4;
        if offset + indices_len * 4 > data.len() {
            break;
        }
        let indices = read_u32_vec(data, &mut offset, indices_len)?;

        // color (4 floats)
        if offset + 16 > data.len() {
            break;
        }
        let color_vec = read_f32_vec(data, &mut offset, 4)?;
        let color: [f32; 4] = [color_vec[0], color_vec[1], color_vec[2], color_vec[3]];

        // transform (16 floats)
        if offset + 64 > data.len() {
            break;
        }
        let transform_vec = read_f32_vec(data, &mut offset, 16)?;
        let transform: [f32; 16] = transform_vec.try_into().ok()?;

        // entity_type
        if offset >= data.len() {
            break;
        }
        let type_len = data[offset] as usize;
        offset += 1;
        if offset + type_len > data.len() {
            break;
        }
        let entity_type = String::from_utf8_lossy(&data[offset..offset + type_len]).to_string();
        offset += type_len;

        // name
        if offset >= data.len() {
            break;
        }
        let name_len = data[offset] as usize;
        offset += 1;
        let name = if name_len > 0 && offset + name_len <= data.len() {
            let n = String::from_utf8_lossy(&data[offset..offset + name_len]).to_string();
            offset += name_len;
            Some(n)
        } else {
            None
        };

        meshes.push(crate::IfcMesh {
            entity_id,
            geometry: Arc::new(MeshGeometry {
                positions,
                normals,
                indices,
            }),
            color,
            transform,
            entity_type,
            name,
            has_ifc_color: false,
        });
    }

    Some(meshes)
}

/// Load geometry from JS bridge
#[cfg(target_arch = "wasm32")]
pub fn load_geometry() -> Option<Vec<crate::IfcMesh>> {
    let uint8_array = js_get_ifc_geometry_binary()?;
    let data = uint8_array.to_vec();
    web_sys::console::log_1(
        &format!(
            "[Bevy] Loading geometry from JS bridge: {} bytes",
            data.len()
        )
        .into(),
    );
    let meshes = deserialize_geometry_binary(&data)?;
    web_sys::console::log_1(&format!("[Bevy] Deserialized {} meshes", meshes.len()).into());
    // Clear the JS bridge to free memory
    js_clear_ifc_geometry_bridge();
    Some(meshes)
}

#[cfg(not(target_arch = "wasm32"))]
pub fn load_geometry() -> Option<Vec<crate::IfcMesh>> {
    None
}

/// Load entities from JS bridge
#[cfg(target_arch = "wasm32")]
pub fn load_entities() -> Option<Vec<crate::EntityInfo>> {
    let json = js_get_ifc_entities()?;
    serde_json::from_str(&json).ok()
}

#[cfg(not(target_arch = "wasm32"))]
pub fn load_entities() -> Option<Vec<crate::EntityInfo>> {
    None
}

/// Load selection from localStorage
#[cfg(target_arch = "wasm32")]
pub fn load_selection() -> Option<SelectionStorage> {
    let storage = web_sys::window()?.local_storage().ok()??;
    let json = storage.get_item("ifc_lite_selection").ok()??;
    serde_json::from_str(&json).ok()
}

#[cfg(not(target_arch = "wasm32"))]
pub fn load_selection() -> Option<SelectionStorage> {
    None
}

/// Save selection to localStorage
#[cfg(target_arch = "wasm32")]
pub fn save_selection(selection: &SelectionStorage) {
    if let Some(window) = web_sys::window() {
        if let Ok(Some(storage)) = window.local_storage() {
            if let Ok(json) = serde_json::to_string(selection) {
                let _ = storage.set_item("ifc_lite_selection", &json);
                // Mark source as "bevy" so Yew knows to pick up this change
                let _ = storage.set_item("ifc_lite_selection_source", "bevy");
            }
        }
    }
}

#[cfg(not(target_arch = "wasm32"))]
pub fn save_selection(_selection: &SelectionStorage) {}

/// Get selection source from localStorage
#[cfg(target_arch = "wasm32")]
pub fn get_selection_source() -> Option<String> {
    let storage = web_sys::window()?.local_storage().ok()??;
    storage.get_item("ifc_lite_selection_source").ok()?
}

#[cfg(not(target_arch = "wasm32"))]
pub fn get_selection_source() -> Option<String> {
    None
}

/// Load visibility from localStorage
#[cfg(target_arch = "wasm32")]
pub fn load_visibility() -> Option<VisibilityStorage> {
    let storage = web_sys::window()?.local_storage().ok()??;
    let json = storage.get_item("ifc_lite_visibility").ok()??;
    serde_json::from_str(&json).ok()
}

#[cfg(not(target_arch = "wasm32"))]
pub fn load_visibility() -> Option<VisibilityStorage> {
    None
}

/// Load camera from localStorage
#[cfg(target_arch = "wasm32")]
pub fn load_camera() -> Option<CameraStorage> {
    let storage = web_sys::window()?.local_storage().ok()??;
    let json = storage.get_item("ifc_lite_camera").ok()??;
    serde_json::from_str(&json).ok()
}

#[cfg(not(target_arch = "wasm32"))]
pub fn load_camera() -> Option<CameraStorage> {
    None
}

/// Save camera to localStorage
#[cfg(target_arch = "wasm32")]
pub fn save_camera(camera: &CameraStorage) {
    if let Some(window) = web_sys::window() {
        if let Ok(Some(storage)) = window.local_storage() {
            if let Ok(json) = serde_json::to_string(camera) {
                let _ = storage.set_item("ifc_lite_camera", &json);
            }
        }
    }
}

#[cfg(not(target_arch = "wasm32"))]
pub fn save_camera(_camera: &CameraStorage) {}

/// Load section plane from localStorage
#[cfg(target_arch = "wasm32")]
pub fn load_section() -> Option<SectionStorage> {
    let storage = web_sys::window()?.local_storage().ok()??;
    let json = storage.get_item("ifc_lite_section").ok()??;
    serde_json::from_str(&json).ok()
}

#[cfg(not(target_arch = "wasm32"))]
pub fn load_section() -> Option<SectionStorage> {
    None
}

/// Load focus command from localStorage
#[cfg(target_arch = "wasm32")]
pub fn load_focus() -> Option<FocusStorage> {
    let storage = web_sys::window()?.local_storage().ok()??;
    let json = storage.get_item("ifc_lite_focus").ok()??;
    serde_json::from_str(&json).ok()
}

#[cfg(not(target_arch = "wasm32"))]
pub fn load_focus() -> Option<FocusStorage> {
    None
}

/// Clear focus command
#[cfg(target_arch = "wasm32")]
pub fn clear_focus() {
    if let Some(window) = web_sys::window() {
        if let Ok(Some(storage)) = window.local_storage() {
            let _ = storage.remove_item("ifc_lite_focus");
        }
    }
}

#[cfg(not(target_arch = "wasm32"))]
pub fn clear_focus() {}

/// Load camera command from localStorage
#[cfg(target_arch = "wasm32")]
pub fn load_camera_cmd() -> Option<CameraCommandStorage> {
    let storage = web_sys::window()?.local_storage().ok()??;
    let json = storage.get_item("ifc_lite_camera_cmd").ok()??;
    serde_json::from_str(&json).ok()
}

#[cfg(not(target_arch = "wasm32"))]
pub fn load_camera_cmd() -> Option<CameraCommandStorage> {
    None
}

/// Clear camera command
#[cfg(target_arch = "wasm32")]
pub fn clear_camera_cmd() {
    if let Some(window) = web_sys::window() {
        if let Ok(Some(storage)) = window.local_storage() {
            let _ = storage.remove_item("ifc_lite_camera_cmd");
        }
    }
}

#[cfg(not(target_arch = "wasm32"))]
pub fn clear_camera_cmd() {}

/// Load palette from localStorage
#[cfg(target_arch = "wasm32")]
pub fn load_palette() -> Option<String> {
    let storage = web_sys::window()?.local_storage().ok()??;
    storage.get_item("ifc_lite_palette").ok()?
}

#[cfg(not(target_arch = "wasm32"))]
pub fn load_palette() -> Option<String> {
    None
}

/// Clear palette
#[cfg(target_arch = "wasm32")]
pub fn clear_palette() {
    if let Some(window) = web_sys::window() {
        if let Ok(Some(storage)) = window.local_storage() {
            let _ = storage.remove_item("ifc_lite_palette");
        }
    }
}

#[cfg(not(target_arch = "wasm32"))]
pub fn clear_palette() {}

/// Measurement point storage
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MeasurePointStorage {
    pub x: f32,
    pub y: f32,
    pub z: f32,
}

/// Save a measurement point to localStorage (Bevy → Leptos)
#[cfg(target_arch = "wasm32")]
pub fn save_measure_point(point: &MeasurePointStorage) {
    if let Some(window) = web_sys::window() {
        if let Ok(Some(storage)) = window.local_storage() {
            if let Ok(json) = serde_json::to_string(point) {
                let _ = storage.set_item("ifc_lite_measure_point", &json);
            }
        }
    }
}

#[cfg(not(target_arch = "wasm32"))]
pub fn save_measure_point(_point: &MeasurePointStorage) {}

/// Load active tool mode from localStorage
#[cfg(target_arch = "wasm32")]
pub fn load_active_tool() -> Option<String> {
    let storage = web_sys::window()?.local_storage().ok()??;
    storage.get_item("ifc_lite_active_tool").ok()?
}

#[cfg(not(target_arch = "wasm32"))]
pub fn load_active_tool() -> Option<String> {
    None
}

/// Load lighting toggle command from localStorage
#[cfg(target_arch = "wasm32")]
pub fn load_lighting_cmd() -> Option<String> {
    let storage = web_sys::window()?.local_storage().ok()??;
    storage.get_item("ifc_lite_lighting_cmd").ok()?
}

#[cfg(not(target_arch = "wasm32"))]
pub fn load_lighting_cmd() -> Option<String> {
    None
}

/// Clear lighting command
#[cfg(target_arch = "wasm32")]
pub fn clear_lighting_cmd() {
    if let Some(window) = web_sys::window() {
        if let Ok(Some(storage)) = window.local_storage() {
            let _ = storage.remove_item("ifc_lite_lighting_cmd");
        }
    }
}

#[cfg(not(target_arch = "wasm32"))]
pub fn clear_lighting_cmd() {}