1use super::*;
2
3#[wasm_bindgen]
4pub struct WasmNurbsCurve {
5 pub(crate) curve: NurbsCurve,
6}
7
8#[wasm_bindgen]
9pub struct WasmNurbsSurface {
10 pub(crate) surface: NurbsSurface,
11}
12
13#[wasm_bindgen]
17pub struct WasmSolidBuffer {
18 pub(crate) data: Vec<f64>,
19 pub(crate) names_json: String,
20 pub(crate) metadata_json: String,
21}
22
23#[wasm_bindgen]
24impl WasmSolidBuffer {
25 pub fn take_data(&mut self) -> Vec<f64> {
26 std::mem::take(&mut self.data)
27 }
28
29 pub fn names_json(&self) -> String {
30 self.names_json.clone()
31 }
32
33 pub fn metadata_json(&self) -> String {
36 self.metadata_json.clone()
37 }
38}
39
40pub(crate) fn solid_buffer(solid: &BrepSolid, metadata_json: String) -> Result<WasmSolidBuffer, JsValue> {
41 let (data, names) = encode_solid(solid).map_err(javascript_error)?;
42 Ok(WasmSolidBuffer {
43 data,
44 names_json: serde_json::to_string(&names)
45 .map_err(|error| javascript_error(error.to_string()))?,
46 metadata_json,
47 })
48}
49
50#[wasm_bindgen]
52pub struct WasmMeshBuffers {
53 pub(crate) positions: Vec<f64>,
54 pub(crate) normals: Vec<f64>,
55 pub(crate) indices: Vec<u32>,
56 pub(crate) face_ids: Vec<u32>,
57}
58
59#[wasm_bindgen]
60impl WasmMeshBuffers {
61 pub fn take_positions(&mut self) -> Vec<f64> {
62 std::mem::take(&mut self.positions)
63 }
64
65 pub fn take_normals(&mut self) -> Vec<f64> {
66 std::mem::take(&mut self.normals)
67 }
68
69 pub fn take_indices(&mut self) -> Vec<u32> {
70 std::mem::take(&mut self.indices)
71 }
72
73 pub fn take_face_ids(&mut self) -> Vec<u32> {
74 std::mem::take(&mut self.face_ids)
75 }
76}
77
78thread_local! {
95 static SOLID_REGISTRY: std::cell::RefCell<SolidRegistry> =
96 std::cell::RefCell::new(SolidRegistry::new());
97}
98
99pub(crate) struct SolidRegistry {
100 pub(crate) next: u32,
101 pub(crate) solids: std::collections::HashMap<u32, BrepSolid>,
102}
103
104impl SolidRegistry {
105 fn new() -> Self {
106 Self {
107 next: 1,
108 solids: std::collections::HashMap::new(),
109 }
110 }
111 fn insert(&mut self, solid: BrepSolid) -> u32 {
112 let handle = self.next;
113 self.next = self.next.wrapping_add(1).max(1);
114 self.solids.insert(handle, solid);
115 handle
116 }
117}
118
119pub(crate) fn register_solid_value(solid: BrepSolid) -> u32 {
120 SOLID_REGISTRY.with(|registry| registry.borrow_mut().insert(solid))
121}
122
123pub(crate) fn with_registered_solid<T>(
125 handle: u32,
126 f: impl FnOnce(&BrepSolid) -> Result<T, JsValue>,
127) -> Result<T, JsValue> {
128 SOLID_REGISTRY.with(|registry| {
129 let registry = registry.borrow();
130 let solid = registry
131 .solids
132 .get(&handle)
133 .ok_or_else(|| javascript_error(format!("unknown solid handle {handle}")))?;
134 f(solid)
135 })
136}
137
138pub(crate) fn with_registered_solid_str<T>(
143 handle: u32,
144 f: impl FnOnce(&BrepSolid) -> Result<T, String>,
145) -> Result<T, String> {
146 SOLID_REGISTRY.with(|registry| {
147 let registry = registry.borrow();
148 let solid = registry
149 .solids
150 .get(&handle)
151 .ok_or_else(|| format!("unknown solid handle {handle}"))?;
152 f(solid)
153 })
154}
155
156pub(crate) fn with_two_registered_solids<T>(
161 a: u32,
162 b: u32,
163 f: impl FnOnce(&BrepSolid, &BrepSolid) -> Result<T, String>,
164) -> Result<T, String> {
165 SOLID_REGISTRY.with(|registry| {
166 let registry = registry.borrow();
167 let sa = registry
168 .solids
169 .get(&a)
170 .ok_or_else(|| format!("unknown solid handle {a}"))?;
171 let sb = registry
172 .solids
173 .get(&b)
174 .ok_or_else(|| format!("unknown solid handle {b}"))?;
175 f(sa, sb)
176 })
177}
178
179pub(crate) fn replace_registered_solid(handle: u32, solid: BrepSolid) -> Result<(), String> {
186 SOLID_REGISTRY.with(|registry| {
187 let mut registry = registry.borrow_mut();
188 match registry.solids.get_mut(&handle) {
189 Some(slot) => {
190 *slot = solid;
191 Ok(())
192 }
193 None => Err(format!("unknown solid handle {handle}")),
194 }
195 })
196}
197
198pub(crate) fn free_registered_solid(handle: u32) {
202 SOLID_REGISTRY.with(|registry| {
203 registry.borrow_mut().solids.remove(&handle);
204 });
205}
206
207#[wasm_bindgen]
210pub fn register_solid_buffer(data: &[f64], names_json: &str) -> Result<u32, JsValue> {
211 let names: SolidNames = if names_json.trim().is_empty() {
212 SolidNames::default()
213 } else {
214 serde_json::from_str(names_json).map_err(|error| javascript_error(error.to_string()))?
215 };
216 let solid = decode_solid(data, &names).map_err(javascript_error)?;
217 let solid = TopologyArena::from_brep(&solid)
218 .and_then(|arena| arena.to_brep())
219 .map_err(javascript_error)?;
220 let issues = solid.validate();
221 if !issues.is_empty() {
222 return Err(javascript_error(format!(
223 "register_solid_buffer: invalid topology: {issues:?}"
224 )));
225 }
226 Ok(register_solid_value(solid))
227}
228
229#[wasm_bindgen]
231pub fn register_solid_json(solid_json: &str) -> Result<u32, JsValue> {
232 let solid: BrepSolid =
233 serde_json::from_str(solid_json).map_err(|error| javascript_error(error.to_string()))?;
234 let solid = TopologyArena::from_brep(&solid)
235 .and_then(|arena| arena.to_brep())
236 .map_err(javascript_error)?;
237 let issues = solid.validate();
238 if !issues.is_empty() {
239 return Err(javascript_error(format!(
240 "register_solid_json: invalid topology: {issues:?}"
241 )));
242 }
243 Ok(register_solid_value(solid))
244}
245
246#[wasm_bindgen]
248pub fn free_solid(handle: u32) {
249 SOLID_REGISTRY.with(|registry| {
250 registry.borrow_mut().solids.remove(&handle);
251 });
252}
253
254pub fn registered_solid_clone(handle: u32) -> Result<BrepSolid, String> {
259 with_registered_solid_str(handle, |solid| Ok(solid.clone()))
260}
261
262#[wasm_bindgen]
264pub fn registered_solid_count() -> usize {
265 SOLID_REGISTRY.with(|registry| registry.borrow().solids.len())
266}
267
268#[wasm_bindgen]
272pub fn boolean_handle(
273 a: u32,
274 b: u32,
275 operation: &str,
276 tolerance: f64,
277 merge_coplanar_faces: bool,
278) -> Result<u32, JsValue> {
279 let operation = match operation {
280 "union" => BooleanOperation::Union,
281 "intersect" => BooleanOperation::Intersect,
282 "subtract" => BooleanOperation::Subtract,
283 _ => return Err(javascript_error("unknown boolean operation".into())),
284 };
285 let result = SOLID_REGISTRY.with(|registry| {
286 let registry = registry.borrow();
287 let sa = registry
288 .solids
289 .get(&a)
290 .ok_or_else(|| javascript_error(format!("unknown solid handle {a}")))?;
291 let sb = registry
292 .solids
293 .get(&b)
294 .ok_or_else(|| javascript_error(format!("unknown solid handle {b}")))?;
295 boolean_operation(
296 sa,
297 sb,
298 operation,
299 &BooleanOptions {
300 tolerance,
301 merge_coplanar_faces,
302 ..BooleanOptions::default()
303 },
304 )
305 .map_err(javascript_error)
306 })?;
307 Ok(register_solid_value(result))
308}
309
310#[wasm_bindgen]
313pub fn tessellate_handle(handle: u32, chord_tolerance: f64) -> Result<WasmMeshBuffers, JsValue> {
314 with_registered_solid(handle, |solid| {
315 let mesh = tessellate_brep_watertight(solid, chord_tolerance).map_err(javascript_error)?;
316 Ok(WasmMeshBuffers {
317 positions: mesh.positions,
318 normals: mesh.normals,
319 indices: mesh.indices,
320 face_ids: mesh.face_ids,
321 })
322 })
323}
324
325#[wasm_bindgen]
327pub fn mass_properties_handle(handle: u32) -> Result<String, JsValue> {
328 with_registered_solid(handle, |solid| {
329 let properties = solid_mass_properties(solid).map_err(javascript_error)?;
330 serde_json::to_string(&properties).map_err(|error| javascript_error(error.to_string()))
331 })
332}
333
334#[wasm_bindgen]
338pub fn transform_handle(
339 handle: u32,
340 matrix: &[f64],
341 reverse_orientation: bool,
342) -> Result<u32, JsValue> {
343 let matrix: [f64; 16] = matrix
344 .try_into()
345 .map_err(|_| javascript_error("transform matrix must contain 16 values".into()))?;
346 let transform = AffineTransform::new(matrix).map_err(javascript_error)?;
347 let result = with_registered_solid(handle, |solid| {
348 transform_brep(solid, transform, reverse_orientation).map_err(javascript_error)
349 })?;
350 Ok(register_solid_value(result))
351}
352
353#[wasm_bindgen]
356pub fn face_names_handle(handle: u32) -> Result<String, JsValue> {
357 with_registered_solid(handle, |solid| {
358 let mut map: Vec<(u64, Option<String>)> = Vec::new();
359 for shell in &solid.shells {
360 for face in &shell.faces {
361 map.push((face.id, face.name.clone()));
362 }
363 }
364 serde_json::to_string(&map).map_err(|error| javascript_error(error.to_string()))
365 })
366}
367
368pub fn boolean_handle_native(
380 a: u32,
381 b: u32,
382 operation: BooleanOperation,
383 options: &BooleanOptions,
384) -> Result<u32, String> {
385 let result =
386 with_two_registered_solids(a, b, |sa, sb| boolean_operation(sa, sb, operation, options))?;
387 Ok(register_solid_value(result))
388}