honeycomb_render/capture/
mod.rs

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
pub mod ecs_data;
pub mod system;

use crate::bundles::{DartBodyBundle, DartHeadBundle, EdgeBundle, FaceBundle, VertexBundle};
use crate::capture::ecs_data::CaptureId;
use crate::capture::system::{populate_darts, populate_edges, populate_vertices};
use bevy::prelude::*;
use bevy::utils::HashMap;
use honeycomb_core::prelude::{
    CMap2, CoordsFloat, DartIdType, FaceIdType, Orbit2, OrbitPolicy, VertexIdType,
};

/// Plugin handling capture data & entity generation from it.
pub struct CapturePlugin;

impl Plugin for CapturePlugin {
    fn build(&self, app: &mut App) {
        // resource
        app.insert_resource(FocusedCapture::default())
            .insert_resource(CaptureList::default());
        // systems
        app.add_systems(Startup, populate_darts)
            .add_systems(Startup, populate_vertices)
            .add_systems(Startup, populate_edges);
        //.add_systems(Startup, populate_faces);
    }
}

#[derive(Resource)]
pub struct FocusedCapture(pub CaptureId);

impl Default for FocusedCapture {
    fn default() -> Self {
        Self(CaptureId(0))
    }
}

#[derive(Resource, Default)]
pub struct CaptureList(pub Vec<Capture>);

pub struct Capture {
    pub metadata: CaptureMD,
    pub vertex_vals: Vec<Vec3>,
    pub normals: HashMap<FaceIdType, Vec<Vec3>>,
    pub darts: Vec<(DartHeadBundle, DartBodyBundle)>,
    pub vertices: Vec<VertexBundle>,
    pub edges: Vec<EdgeBundle>,
    pub faces: Vec<FaceBundle>,
}

impl Capture {
    #[allow(clippy::too_many_lines)]
    pub fn new<T: CoordsFloat>(cap_id: usize, cmap: &CMap2<T>) -> Self {
        let map_vertices = cmap.fetch_vertices();
        let map_edges = cmap.fetch_edges();
        let map_faces = cmap.fetch_faces();
        let metadata = CaptureMD {
            capture_id: cap_id,
            n_darts: cmap.n_darts() - cmap.n_unused_darts(),
            n_vertices: cmap.n_vertices(),
            n_edges: map_edges.identifiers.len(),
            n_faces: map_faces.identifiers.len(),
            n_volumes: 0,
        };

        let mut index_map: HashMap<VertexIdType, usize> = HashMap::with_capacity(cmap.n_vertices());

        let vertex_vals: Vec<Vec3> = map_vertices
            .identifiers
            .iter()
            .enumerate()
            .map(|(idx, vid)| {
                index_map.insert(*vid, idx);
                let v = cmap
                    .force_read_vertex(*vid)
                    .expect("E: found a topological vertex with no associated coordinates");
                // sane unwraps; will crash if the coordinates cannot be converted to f32
                Vec3::from((v.0.to_f32().unwrap(), v.1.to_f32().unwrap(), 0.0))
            })
            .collect();

        let vertices: Vec<VertexBundle> = map_vertices
            .identifiers
            .iter()
            .map(|id| VertexBundle::new(cap_id, *id, index_map[id]))
            .collect();

        let edges: Vec<EdgeBundle> = map_edges
            .identifiers
            .iter()
            .map(|id| {
                let v1id = cmap.vertex_id(*id as DartIdType);
                let v2id = if cmap.is_i_free::<2>(*id as DartIdType) {
                    cmap.vertex_id(cmap.beta::<1>(*id as DartIdType))
                } else {
                    cmap.vertex_id(cmap.beta::<2>(*id as DartIdType))
                };
                EdgeBundle::new(cap_id, *id, (index_map[&v1id], index_map[&v2id]))
            })
            .collect();

        let mut normals = HashMap::new();
        let mut darts: Vec<(DartHeadBundle, DartBodyBundle)> = Vec::new();

        let faces: Vec<FaceBundle> = map_faces
            .identifiers
            .iter()
            .map(|id| {
                let vertex_ids: Vec<usize> =
                    Orbit2::new(cmap, OrbitPolicy::Custom(&[1]), *id as DartIdType)
                        .map(|dart_id| index_map[&cmap.vertex_id(dart_id)])
                        .collect();
                let n_v = vertex_ids.len();
                let mut loc_normals = vec![{
                    let (ver_in, ver, ver_out) =
                        (&vertex_ids[n_v - 1], &vertex_ids[0], &vertex_ids[1]);
                    let (vec_in, vec_out) = (
                        vertex_vals[*ver] - vertex_vals[*ver_in],
                        vertex_vals[*ver_out] - vertex_vals[*ver],
                    );
                    // vec_in/out belong to X/Y plane => .cross(Z) == normal in the plane
                    // a firts normalization is required because both edges should weight equally
                    (vec_in.cross(Vec3::Z).normalize() + vec_out.cross(Vec3::Z).normalize())
                        .normalize()
                }];
                loc_normals.extend(vertex_ids.windows(3).map(|wdw| {
                    let [ver_in, ver, ver_out] = wdw else {
                        unreachable!("i kneel");
                    };
                    let (vec_in, vec_out) = (
                        vertex_vals[*ver] - vertex_vals[*ver_in],
                        vertex_vals[*ver_out] - vertex_vals[*ver],
                    );
                    (vec_in.cross(Vec3::Z).normalize() + vec_out.cross(Vec3::Z).normalize())
                        .normalize()
                }));
                loc_normals.push({
                    let (ver_in, ver, ver_out) =
                        (&vertex_ids[n_v - 2], &vertex_ids[n_v - 1], &vertex_ids[0]);
                    let (vec_in, vec_out) = (
                        vertex_vals[*ver] - vertex_vals[*ver_in],
                        vertex_vals[*ver_out] - vertex_vals[*ver],
                    );
                    (vec_in.cross(Vec3::Z).normalize() + vec_out.cross(Vec3::Z).normalize())
                        .normalize()
                });

                assert_eq!(loc_normals.len(), n_v);

                normals.insert(*id, loc_normals);

                // common dart iterator
                let mut tmp = Orbit2::new(cmap, OrbitPolicy::Custom(&[1]), *id as DartIdType)
                    .enumerate()
                    .map(|(idx, dart_id)| (dart_id, index_map[&cmap.vertex_id(dart_id)], idx))
                    .collect::<Vec<_>>();
                tmp.push(tmp[0]); // trick for the `.windows` call

                // dart bodies
                let bodies = tmp.windows(2).map(|wd| {
                    let [(dart_id, v1_id, v1n_id), (_, v2_id, v2n_id)] = wd else {
                        unreachable!("i kneel");
                    };
                    DartBodyBundle::new(
                        cap_id,
                        *dart_id,
                        cmap.vertex_id(*dart_id),
                        cmap.edge_id(*dart_id),
                        *id,
                        (*v1_id, *v2_id),
                        (*v1n_id, *v2n_id),
                    )
                });

                let heads = tmp.windows(2).map(|wd| {
                    let [(dart_id, v1_id, v1n_id), (_, v2_id, v2n_id)] = wd else {
                        unreachable!("i kneel");
                    };
                    DartHeadBundle::new(
                        cap_id,
                        *dart_id,
                        cmap.vertex_id(*dart_id),
                        cmap.edge_id(*dart_id),
                        *id,
                        (*v1_id, *v2_id),
                        (*v1n_id, *v2n_id),
                    )
                });

                darts.extend(heads.zip(bodies));

                FaceBundle::new(cap_id, *id, vertex_ids)
            })
            .collect();

        Self {
            metadata,
            vertex_vals,
            normals,
            darts,
            vertices,
            edges,
            faces,
        }
    }
}

pub struct CaptureMD {
    pub capture_id: usize,
    pub n_darts: usize,
    pub n_vertices: usize,
    pub n_edges: usize,
    pub n_faces: usize,
    pub n_volumes: usize,
}