-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlib.rs
511 lines (474 loc) · 15.1 KB
/
lib.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
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
#![deny(unsafe_op_in_unsafe_fn)]
use std::cell::RefCell;
use std::ffi::CString;
use std::fmt::Display;
use std::mem::MaybeUninit;
use libc::{c_char, size_t};
use nalgebra::{Vector2, Vector3};
use asdfspline::{AsdfPosSpline, MonotoneCubicSpline, NormWrapper, PiecewiseCubicCurve, Spline};
thread_local! {
static LAST_ERROR: RefCell<CString> = RefCell::new(CString::new("no error").unwrap());
}
fn set_error<D: Display>(error: D) {
LAST_ERROR.with(|cell| {
*cell.borrow_mut() = CString::new(error.to_string()).unwrap();
});
}
/// The error message will be freed if another error occurs. It is the caller's
/// responsibility to make sure they're no longer using the string before
/// calling any other function which may fail.
#[no_mangle]
pub extern "C" fn asdf_last_error() -> *const c_char {
LAST_ERROR.with(|cell| cell.borrow().as_ptr())
}
trait ResultExt<T, E> {
fn into_box(self) -> Option<Box<T>>;
}
impl<T, E: Display> ResultExt<T, E> for Result<T, E> {
fn into_box(self) -> Option<Box<T>> {
self.map(Box::new).map_err(|e| set_error(e)).ok()
}
}
pub type Vec2 = Vector2<f32>;
pub type Vec3 = Vector3<f32>;
pub struct Norm3;
impl NormWrapper<Norm3> for Vec3 {
fn norm(&self) -> f32 {
self.norm()
}
}
/// A (three-dimensional) ASDF spline.
pub type AsdfPosSpline3 = AsdfPosSpline<Vec3, Norm3>;
pub type AsdfCubicCurve3 = PiecewiseCubicCurve<Vec3>;
pub type AsdfCubicCurve2 = PiecewiseCubicCurve<Vec2>;
pub type AsdfCubicCurve1 = PiecewiseCubicCurve<f32>;
pub type AsdfMonotoneCubic = MonotoneCubicSpline;
/// Create slice from pointer and length.
///
/// # Safety
///
/// If ptr is not NULL, it must be correctly aligned and
/// point to `len` initialized items of type `T`.
unsafe fn ffi_slice<'a, T>(ptr: *const T, len: usize) -> &'a [T] {
if ptr.is_null() {
// NB: `len` is assumed to be 0.
&[]
} else {
// SAFETY: see function docstring.
unsafe { std::slice::from_raw_parts(ptr, len) }
}
}
/// Create mutable slice from pointer and length.
///
/// # Safety
///
/// If ptr is not NULL, it must be correctly aligned and
/// point to `len` initialized items of type `T`.
unsafe fn ffi_slice_mut<'a, T>(ptr: *mut T, len: usize) -> &'a mut [T] {
if ptr.is_null() {
// NB: `len` is assumed to be 0.
&mut []
} else {
// SAFETY: see function docstring.
unsafe { std::slice::from_raw_parts_mut(ptr, len) }
}
}
/// Creates an `AsdfPosSpline3`.
///
/// Each element in `positions` (3D coordinates) and `tcb`
/// (tension, continuity, bias) contains *three* `float` values,
/// `times` and `speeds` contain one `float` per element.
///
/// # Safety
///
/// All input pointers must be valid for the corresponding `*_count` numbers
/// of elements (not bytes).
#[no_mangle]
pub unsafe extern "C" fn asdf_asdfposspline3(
positions: *const f32,
positions_count: size_t,
times: *const f32,
times_count: size_t,
speeds: *const f32,
speeds_count: size_t,
tcb: *const f32,
tcb_count: size_t,
closed: bool,
) -> Option<Box<AsdfPosSpline3>> {
let positions: Vec<_> = unsafe { ffi_slice(positions.cast::<[f32; 3]>(), positions_count) }
.iter()
.map(|coords| Vec3::from_column_slice(coords))
.collect();
let times: Vec<_> = unsafe { ffi_slice(times, times_count) }
.iter()
.map(|&t| if t.is_nan() { None } else { Some(t) })
.collect();
let speeds: Vec<_> = unsafe { ffi_slice(speeds, speeds_count) }
.iter()
.map(|&t| if t.is_nan() { None } else { Some(t) })
.collect();
let tcb = unsafe { ffi_slice(tcb.cast::<[f32; 3]>(), tcb_count) };
AsdfPosSpline3::new(positions, times, speeds, tcb, closed).into_box()
}
/// Frees an `AsdfPosSpline3`
///
/// # Safety
///
/// The pointer must have been obtained with `asdf_asdfposspline3()`.
/// Each pointer can only be freed once.
/// Passing NULL is allowed.
#[no_mangle]
pub unsafe extern "C" fn asdf_asdfposspline3_free(_: Option<Box<AsdfPosSpline3>>) {}
/// Returns curve value(s) at given time(s).
///
/// # Safety
///
/// All pointers must be valid.
/// `times` contains one `float` per element,
/// `output` must provide space for *three* `float`s per element.
/// Pointers can be NULL, but in this case `count` must be 0.
#[no_mangle]
pub unsafe extern "C" fn asdf_asdfposspline3_evaluate(
curve: &mut AsdfPosSpline3,
times: *const f32,
count: size_t,
output: *mut f32,
) {
let times = unsafe { ffi_slice(times, count) };
let output = unsafe { ffi_slice_mut(output.cast::<MaybeUninit<[f32; 3]>>(), count) };
for (time, out) in times.iter().zip(output) {
*out = MaybeUninit::new(curve.evaluate(*time).into());
}
}
/// Provides a pointer to (and number of) grid elements.
///
/// # Safety
///
/// All pointers must be valid.
#[no_mangle]
pub unsafe extern "C" fn asdf_asdfposspline3_grid(
curve: &mut AsdfPosSpline3,
output: *mut *const f32,
) -> size_t {
let grid = curve.grid();
unsafe { output.write(grid.as_ptr()) };
grid.len()
}
/// Creates a three-dimensional KB-spline.
///
/// Each element in `positions` (3D coordinates) and `tcb`
/// (tension, continuity, bias) contains *three* `float` values,
///
/// # Safety
///
/// All input pointers must be valid for the corresponding `*_count` numbers
/// of elements (not bytes).
#[no_mangle]
pub unsafe extern "C" fn asdf_centripetalkochanekbartelsspline3(
positions: *const f32,
positions_count: size_t,
tcb: *const f32,
tcb_count: size_t,
closed: bool,
) -> Option<Box<AsdfCubicCurve3>> {
let positions = unsafe { ffi_slice(positions.cast::<[f32; 3]>(), positions_count) };
let positions: Vec<_> = positions
.iter()
.map(|coords| Vec3::from_column_slice(coords))
.collect();
let tcb = unsafe { ffi_slice(tcb.cast::<[f32; 3]>(), tcb_count) };
PiecewiseCubicCurve::new_centripetal_kochanek_bartels(&positions, tcb, closed, Vec3::norm)
.into_box()
}
/// Creates a two-dimensional KB-spline.
///
/// Each element in `positions` (2D coordinates) contains *two* `float` values,
/// each element in `tcb` (tension, continuity, bias) contains *three* `float` values,
///
/// # Safety
///
/// All input pointers must be valid for the corresponding `*_count` numbers
/// of elements (not bytes).
#[no_mangle]
pub unsafe extern "C" fn asdf_centripetalkochanekbartelsspline2(
positions: *const f32,
positions_count: size_t,
tcb: *const f32,
tcb_count: size_t,
closed: bool,
) -> Option<Box<AsdfCubicCurve2>> {
let positions = unsafe { ffi_slice(positions.cast::<[f32; 2]>(), positions_count) };
let positions: Vec<_> = positions
.iter()
.map(|coords| Vec2::from_column_slice(coords))
.collect();
let tcb = unsafe { ffi_slice(tcb.cast::<[f32; 3]>(), tcb_count) };
PiecewiseCubicCurve::new_centripetal_kochanek_bartels(&positions, tcb, closed, Vec2::norm)
.into_box()
}
/// Creates a one-dimensional piecewise monotone cubic spline.
///
/// # Safety
///
/// All input pointers must be valid for the corresponding `*_count` numbers
/// of elements (not bytes).
#[no_mangle]
pub unsafe extern "C" fn asdf_piecewisemonotonecubicspline(
values: *const f32,
values_count: size_t,
grid: *const f32,
grid_count: size_t,
closed: bool,
) -> Option<Box<AsdfCubicCurve1>> {
let values = unsafe { ffi_slice(values, values_count) };
let grid = unsafe { ffi_slice(grid, grid_count) };
PiecewiseCubicCurve::new_piecewise_monotone(values, grid, closed).into_box()
}
/// Creates a one-dimensional piecewise monotone cubic spline (given values and slopes).
///
/// # Safety
///
/// All input pointers must be valid for the corresponding `*_count` numbers
/// of elements (not bytes).
#[no_mangle]
pub unsafe extern "C" fn asdf_piecewisemonotonecubicspline_with_slopes(
values: *const f32,
values_count: size_t,
slopes: *const f32,
slopes_count: size_t,
grid: *const f32,
grid_count: size_t,
closed: bool,
) -> Option<Box<AsdfCubicCurve1>> {
let values = unsafe { ffi_slice(values, values_count) };
let slopes = unsafe { ffi_slice(slopes, slopes_count) };
let slopes: Vec<_> = slopes
.iter()
.map(|&x| if x.is_nan() { None } else { Some(x) })
.collect();
let grid = unsafe { ffi_slice(grid, grid_count) };
PiecewiseCubicCurve::new_piecewise_monotone_with_slopes(values, slopes, grid, closed).into_box()
}
/// Creates a one-dimensional monotone cubic spline.
///
/// # Safety
///
/// All input pointers must be valid for the corresponding `*_count` numbers
/// of elements (not bytes).
#[no_mangle]
pub unsafe extern "C" fn asdf_monotonecubic(
values: *const f32,
values_count: size_t,
grid: *const f32,
grid_count: size_t,
cyclic: bool,
) -> Option<Box<AsdfMonotoneCubic>> {
let values = unsafe { ffi_slice(values, values_count) };
let grid = unsafe { ffi_slice(grid, grid_count) };
MonotoneCubicSpline::new(values, grid, cyclic).into_box()
}
/// Creates a one-dimensional monotone cubic spline (given values and slopes).
///
/// # Safety
///
/// All input pointers must be valid for the corresponding `*_count` numbers
/// of elements (not bytes).
#[no_mangle]
pub unsafe extern "C" fn asdf_monotonecubic_with_slopes(
values: *const f32,
values_count: size_t,
slopes: *const f32,
slopes_count: size_t,
grid: *const f32,
grid_count: size_t,
cyclic: bool,
) -> Option<Box<AsdfMonotoneCubic>> {
let values = unsafe { ffi_slice(values, values_count) };
let slopes = unsafe { ffi_slice(slopes, slopes_count) };
let slopes: Vec<_> = slopes
.iter()
.map(|&x| if x.is_nan() { None } else { Some(x) })
.collect();
let grid = unsafe { ffi_slice(grid, grid_count) };
MonotoneCubicSpline::with_slopes(values, slopes, grid, cyclic).into_box()
}
/// Frees an `AsdfMonotoneCubic`
///
/// # Safety
///
/// The pointer must have been obtained with `asdf_monotonecubic()`.
/// Each pointer can only be freed once.
/// Passing NULL is allowed.
#[no_mangle]
pub unsafe extern "C" fn asdf_monotonecubic_free(_: Option<Box<AsdfMonotoneCubic>>) {}
/// Returns a pointer to `AsdfCubicCurve1` from `AsdfMonotoneCubic`.
///
/// # Safety
///
/// The pointer must be valid.
#[no_mangle]
pub unsafe extern "C" fn asdf_monotonecubic_inner(
curve: &mut AsdfMonotoneCubic,
) -> *const AsdfCubicCurve1 {
curve.inner_ref()
}
/// Returns the time instance(s) for the given value(s).
///
/// # Safety
///
/// All pointers must be valid.
/// `values` contains one `float` per element,
/// `output` must provide space for one `float` per element.
/// Pointers can be NULL, but in this case `count` must be 0.
#[no_mangle]
pub unsafe extern "C" fn asdf_monotonecubic_get_time(
curve: &mut AsdfMonotoneCubic,
values: *const f32,
count: size_t,
output: *mut f32,
) {
let values = unsafe { ffi_slice(values, count) };
let output = unsafe { ffi_slice_mut(output.cast::<MaybeUninit<_>>(), count) };
for (val, out) in values.iter().zip(output) {
*out = MaybeUninit::new(curve.get_time(*val).unwrap_or(std::f32::NAN));
}
}
// TODO: avoid duplication for 1, 2 and 3 dimensions ...
/// Frees an `AsdfCubicCurve3`
///
/// # Safety
///
/// The pointer must have been obtained with `asdf_centripetalkochanekbartelsspline3()`.
/// Each pointer can only be freed once.
/// Passing NULL is allowed.
#[no_mangle]
pub unsafe extern "C" fn asdf_cubiccurve3_free(_: Option<Box<AsdfCubicCurve3>>) {}
/// Returns curve value(s) at given time(s).
///
/// # Safety
///
/// All pointers must be valid.
/// `times` contains one `float` per element,
/// `output` must provide space for *three* `float`s per element.
/// Pointers can be NULL, but in this case `count` must be 0.
#[no_mangle]
pub unsafe extern "C" fn asdf_cubiccurve3_evaluate(
curve: &mut AsdfCubicCurve3,
times: *const f32,
count: size_t,
output: *mut f32,
) {
let times = unsafe { ffi_slice(times, count) };
let output = unsafe { ffi_slice_mut(output.cast::<MaybeUninit<[f32; 3]>>(), count) };
for (time, out) in times.iter().zip(output) {
*out = MaybeUninit::new(curve.evaluate(*time).into());
}
}
/// Provides a pointer to (and number of) grid elements.
///
/// # Safety
///
/// All pointers must be valid.
#[no_mangle]
pub unsafe extern "C" fn asdf_cubiccurve3_grid(
curve: &mut AsdfCubicCurve3,
output: *mut *const f32,
) -> size_t {
let grid = curve.grid();
unsafe {
output.write(grid.as_ptr());
}
grid.len()
}
/// Frees an `AsdfCubicCurve2`
///
/// # Safety
///
/// The pointer must have been obtained with `asdf_centripetalkochanekbartelsspline2()`.
/// Each pointer can only be freed once.
#[no_mangle]
pub unsafe extern "C" fn asdf_cubiccurve2_free(_: Option<Box<AsdfCubicCurve2>>) {}
/// Returns curve value(s) at given time(s).
///
/// # Safety
///
/// All pointers must be valid.
/// `times` contains one `float` per element,
/// `output` must provide space for *two* `float`s per element.
/// Pointers can be NULL, but in this case `count` must be 0.
#[no_mangle]
pub unsafe extern "C" fn asdf_cubiccurve2_evaluate(
curve: &mut AsdfCubicCurve2,
times: *const f32,
count: size_t,
output: *mut f32,
) {
let times = unsafe { ffi_slice(times, count) };
let output = unsafe { ffi_slice_mut(output.cast::<MaybeUninit<[f32; 2]>>(), count) };
for (time, out) in times.iter().zip(output) {
*out = MaybeUninit::new(curve.evaluate(*time).into());
}
}
/// Provides a pointer to (and number of) grid elements.
///
/// # Safety
///
/// All pointers must be valid.
#[no_mangle]
pub unsafe extern "C" fn asdf_cubiccurve2_grid(
curve: &mut AsdfCubicCurve2,
output: *mut *const f32,
) -> size_t {
let grid = curve.grid();
unsafe {
output.write(grid.as_ptr());
}
grid.len()
}
/// Frees an `AsdfCubicCurve1`
///
/// # Safety
///
/// The pointer must have been obtained with `asdf_piecewisemonotonecubicspline()` or
/// `asdf_piecewisemonotonecubicspline_with_slopes()`.
/// Each pointer can only be freed once.
/// Passing NULL is allowed.
#[no_mangle]
pub unsafe extern "C" fn asdf_cubiccurve1_free(_: Option<Box<AsdfCubicCurve1>>) {}
/// Returns curve value(s) at given time(s).
///
/// # Safety
///
/// All pointers must be valid.
/// `times` contains one `float` per element,
/// `output` must provide space for *one* `float` per element.
/// Pointers can be NULL, but in this case `count` must be 0.
#[no_mangle]
pub unsafe extern "C" fn asdf_cubiccurve1_evaluate(
curve: &mut AsdfCubicCurve1,
times: *const f32,
count: size_t,
output: *mut f32,
) {
let times = unsafe { ffi_slice(times, count) };
let output = unsafe { ffi_slice_mut(output.cast::<MaybeUninit<f32>>(), count) };
for (time, out) in times.iter().zip(output) {
*out = MaybeUninit::new(curve.evaluate(*time));
}
}
/// Provides a pointer to (and number of) grid elements.
///
/// # Safety
///
/// All pointers must be valid.
#[no_mangle]
pub unsafe extern "C" fn asdf_cubiccurve1_grid(
curve: &mut AsdfCubicCurve1,
output: *mut *const f32,
) -> size_t {
let grid = curve.grid();
unsafe {
output.write(grid.as_ptr());
}
grid.len()
}