namigator 0.1.0

Rust bindings for the namigator pathfinding library for World of Warcraft.
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
use crate::error::{error_code_to_error, NamigatorError};
use crate::util::path_to_cstr;
use namigator_sys::{
    pathfind_find_height, pathfind_find_heights, pathfind_find_path,
    pathfind_find_point_in_between_vectors, pathfind_find_random_point_around_circle,
    pathfind_free_map, pathfind_get_zone_and_area, pathfind_has_adts, pathfind_is_adt_loaded,
    pathfind_line_of_sight, pathfind_load_adt, pathfind_load_adt_at, pathfind_load_all_adts,
    pathfind_new_map, pathfind_unload_adt, Vertex, BUFFER_TOO_SMALL, SUCCESS,
};
use std::ffi::{c_float, c_uint, CString};
use std::path::Path;

use wow_world_base::shared::vector2d_vanilla_tbc_wrath::Vector2d;
use wow_world_base::shared::vector3d_vanilla_tbc_wrath::Vector3d;

#[derive(Debug)]
pub struct PathfindMap {
    map: *const namigator_sys::Map,
    // Vector3d does not have repr(c) so we can't be sure that it's correctly set up
    // The benefits of having interop with a wow_world_base type far outweighs the extra
    // ~124 bytes of storage for the vec.
    // This might be replaceable with a const array if we get hard limitations from namigator
    inner_path: Vec<Vertex>,
    path: Vec<Vector3d>,
    height: Vec<f32>,
}

const INITIAL_VEC_SIZE: usize = 10;

// SAFETY: Namigator should allow this.
unsafe impl Send for PathfindMap {}

impl PathfindMap {
    pub fn new(data_path: impl AsRef<Path>, map_name: &str) -> Result<Self, NamigatorError> {
        fn inner(data_path: &Path, map_name: &str) -> Result<PathfindMap, NamigatorError> {
            let data_path = path_to_cstr(data_path)?;
            let map_name = CString::new(map_name)?;

            let mut result: u8 = 0;
            // SAFETY: CStrings are guaranteed to be valid pointers
            let map = unsafe {
                pathfind_new_map(
                    data_path.as_ptr(),
                    map_name.as_ptr(),
                    &mut result as *mut u8,
                )
            };

            if result != SUCCESS {
                return Err(error_code_to_error(result));
            }

            if map.is_null() {
                return Err(NamigatorError::MapIsNullPointer);
            }

            Ok(PathfindMap {
                map,
                inner_path: vec![Vertex::default(); INITIAL_VEC_SIZE],
                path: vec![Vector3d::default(); INITIAL_VEC_SIZE],
                height: vec![f32::default(); INITIAL_VEC_SIZE],
            })
        }
        inner(data_path.as_ref(), map_name)
    }

    pub fn has_adts(&self) -> Result<bool, NamigatorError> {
        let mut has_adts = false;
        let result = unsafe { pathfind_has_adts(self.map, &mut has_adts) };

        if result != SUCCESS {
            return Err(error_code_to_error(result));
        }

        Ok(has_adts)
    }

    pub fn load_all_adts(&mut self) -> Result<u32, NamigatorError> {
        let mut adts_loaded: c_uint = 0;

        // SAFETY: map is guaranteed to be initialized in a member function
        let result = unsafe { pathfind_load_all_adts(self.map, &mut adts_loaded as *mut c_uint) };

        if result != SUCCESS {
            return Err(error_code_to_error(result));
        }

        Ok(adts_loaded)
    }

    pub fn load_adt(&mut self, x: i32, y: i32) -> Result<(f32, f32), NamigatorError> {
        let mut out_adt_x: f32 = 0.0;
        let mut out_adt_y: f32 = 0.0;

        let result = unsafe {
            pathfind_load_adt(
                self.map,
                x,
                y,
                &mut out_adt_x as *mut f32,
                &mut out_adt_y as *mut f32,
            )
        };

        if result == SUCCESS {
            Ok((out_adt_x, out_adt_y))
        } else {
            Err(error_code_to_error(result))
        }
    }

    pub fn load_adt_at(&mut self, x: f32, y: f32) -> Result<(f32, f32), NamigatorError> {
        let mut out_adt_x: f32 = 0.0;
        let mut out_adt_y: f32 = 0.0;

        let result = unsafe {
            pathfind_load_adt_at(
                self.map,
                x,
                y,
                &mut out_adt_x as *mut f32,
                &mut out_adt_y as *mut f32,
            )
        };

        if result == SUCCESS {
            Ok((out_adt_x, out_adt_y))
        } else {
            Err(error_code_to_error(result))
        }
    }

    pub fn unload_adt(&self, x: i32, y: i32) -> Result<(), NamigatorError> {
        let result = unsafe { pathfind_unload_adt(self.map, x, y) };

        if result == SUCCESS {
            Ok(())
        } else {
            Err(error_code_to_error(result))
        }
    }

    pub fn adt_loaded(&self, x: i32, y: i32) -> Result<bool, NamigatorError> {
        let mut out_loaded: u8 = 0;
        let result = unsafe { pathfind_is_adt_loaded(self.map, x, y, &mut out_loaded as *mut u8) };

        if result == SUCCESS {
            Ok(out_loaded == 1)
        } else {
            Err(error_code_to_error(result))
        }
    }

    pub fn get_zone_and_area(&self, x: f32, y: f32, z: f32) -> Result<(u32, u32), NamigatorError> {
        let mut out_zone: c_uint = 0;
        let mut out_area: c_uint = 0;

        // SAFETY: map is guaranteed to be valid in member functions
        let result = unsafe {
            pathfind_get_zone_and_area(
                self.map,
                x,
                y,
                z,
                &mut out_zone as *mut c_uint,
                &mut out_area as *mut c_uint,
            )
        };

        if result != SUCCESS {
            return Err(error_code_to_error(result));
        }

        Ok((out_zone, out_area))
    }

    pub fn find_path(
        &mut self,
        start: Vector3d,
        stop: Vector3d,
    ) -> Result<&[Vector3d], NamigatorError> {
        let mut amount_of_vertices: c_uint = 0;

        let result = unsafe {
            pathfind_find_path(
                self.map,
                start.x,
                start.y,
                start.z,
                stop.x,
                stop.y,
                stop.z,
                self.inner_path.as_mut_ptr(),
                self.inner_path.len() as c_uint,
                &mut amount_of_vertices as *mut c_uint,
            )
        };

        if result == SUCCESS {
            self.transfer_paths();
            return Ok(&self.path[..usize::try_from(amount_of_vertices).unwrap()]);
        } else if result == BUFFER_TOO_SMALL {
            self.resize_paths(amount_of_vertices);

            let result = unsafe {
                pathfind_find_path(
                    self.map,
                    start.x,
                    start.y,
                    start.z,
                    stop.x,
                    stop.y,
                    stop.z,
                    self.inner_path.as_mut_ptr(),
                    self.inner_path.len() as c_uint,
                    &mut amount_of_vertices as *mut c_uint,
                )
            };

            if result == SUCCESS {
                self.transfer_paths();
                return Ok(&self.path[..usize::try_from(amount_of_vertices).unwrap()]);
            } else {
                panic!("buffer was too small even after making it larger")
            }
        }

        Err(error_code_to_error(result))
    }

    pub fn find_heights(&mut self, x: f32, y: f32) -> Result<&[f32], NamigatorError> {
        let mut amount_of_heights: u32 = 0;

        let result = unsafe {
            pathfind_find_heights(
                self.map,
                x,
                y,
                self.height.as_mut_ptr(),
                self.height.len() as c_uint,
                &mut amount_of_heights as *mut c_uint,
            )
        };

        if result == SUCCESS {
            return Ok(&self.height[..usize::try_from(amount_of_heights).unwrap()]);
        } else if result == BUFFER_TOO_SMALL {
            self.height
                .resize(usize::try_from(amount_of_heights).unwrap(), f32::default());

            let result = unsafe {
                pathfind_find_heights(
                    self.map,
                    x,
                    y,
                    self.height.as_mut_ptr(),
                    self.height.len() as c_uint,
                    &mut amount_of_heights as *mut c_uint,
                )
            };

            if result == SUCCESS {
                return Ok(&self.height[..usize::try_from(amount_of_heights).unwrap()]);
            }
        }

        Err(error_code_to_error(result))
    }

    pub fn find_point_between_points(
        &self,
        distance: f32,
        from: Vector3d,
        to: Vector3d,
    ) -> Result<Vector3d, NamigatorError> {
        let mut vertex = Vertex::default();
        let result = unsafe {
            pathfind_find_point_in_between_vectors(
                self.map,
                distance,
                from.x,
                from.y,
                from.z,
                to.x,
                to.y,
                to.z,
                &mut vertex,
            )
        };

        if result != SUCCESS {
            return Err(error_code_to_error(result));
        }

        Ok(Vector3d {
            x: vertex.x,
            y: vertex.y,
            z: vertex.z,
        })
    }

    pub fn line_of_sight(&self, from: Vector3d, to: Vector3d) -> Result<bool, NamigatorError> {
        let mut los: u8 = 0;
        // SAFETY: self.map is always valid in member functions.
        let doodads: u8 = 0;
        let result = unsafe {
            pathfind_line_of_sight(
                self.map,
                from.x,
                from.y,
                from.z,
                to.x,
                to.y,
                to.z,
                &mut los as *mut u8,
                doodads,
            )
        };

        if result == SUCCESS {
            Ok(match los {
                1 => true,
                0 => false,
                los => {
                    panic!(
                        "invalid value received from line_of_sight: '{}', from: '{:?}', to: '{:?}'",
                        los, from, to
                    )
                }
            })
        } else {
            Err(error_code_to_error(result))
        }
    }

    pub fn find_height(&self, start: Vector3d, stop: Vector2d) -> Result<f32, NamigatorError> {
        let mut out_stop_z: c_float = 0.0;

        let result = unsafe {
            pathfind_find_height(
                self.map,
                start.x,
                start.y,
                start.z,
                stop.x,
                stop.y,
                &mut out_stop_z as *mut c_float,
            )
        };

        if result == SUCCESS {
            Ok(out_stop_z)
        } else {
            Err(error_code_to_error(result))
        }
    }

    pub fn find_random_point_around_circle(
        &self,
        start: Vector3d,
        radius: f32,
    ) -> Result<Vector3d, NamigatorError> {
        let mut out_x: c_float = 0.0;
        let mut out_y: c_float = 0.0;
        let mut out_z: c_float = 0.0;

        let result = unsafe {
            pathfind_find_random_point_around_circle(
                self.map,
                start.x,
                start.y,
                start.z,
                radius,
                &mut out_x as *mut c_float,
                &mut out_y as *mut c_float,
                &mut out_z as *mut c_float,
            )
        };

        if result == SUCCESS {
            Ok(Vector3d {
                x: out_x,
                y: out_y,
                z: out_z,
            })
        } else {
            Err(error_code_to_error(result))
        }
    }

    fn resize_paths(&mut self, size: u32) {
        let size = usize::try_from(size).unwrap();
        self.inner_path.resize(size, Vertex::default());
        self.path.resize(size, Vector3d::default());
    }

    fn transfer_paths(&mut self) {
        for (i, v) in self.inner_path.iter().enumerate() {
            self.path[i].x = v.x;
            self.path[i].y = v.y;
            self.path[i].z = v.z;
        }
    }
}

impl Drop for PathfindMap {
    fn drop(&mut self) {
        unsafe { pathfind_free_map(self.map) }
    }
}