forked from SpaceManiac/SpacemanDMM
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdmm.rs
More file actions
331 lines (277 loc) · 8.85 KB
/
dmm.rs
File metadata and controls
331 lines (277 loc) · 8.85 KB
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
use std::collections::BTreeMap;
use std::path::Path;
use std::fs::File;
use std::io;
use std::fmt;
use ndarray::{self, Array3, Axis};
use linked_hash_map::LinkedHashMap;
use dm::DMError;
use dm::constants::Constant;
use crate::dmi::Dir;
mod read;
mod save_tgm;
const MAX_KEY_LENGTH: u8 = 3;
/// BYOND is currently limited to 65534 keys.
/// https://secure.byond.com/forum/?post=2340796#comment23770802
type KeyType = u16;
/// An opaque map key.
#[derive(Copy, Clone, Debug, Hash, Ord, Eq, PartialOrd, PartialEq, Default)]
pub struct Key(KeyType);
/// An XY coordinate pair in the BYOND coordinate system.
///
/// The lower-left corner is `{ x: 1, y: 1 }`.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub struct Coord2 {
pub x: i32,
pub y: i32,
}
impl Coord2 {
#[inline]
pub fn new(x: i32, y: i32) -> Coord2 {
Coord2 { x, y }
}
#[inline]
pub fn z(self, z: i32) -> Coord3 {
Coord3 { x: self.x, y: self.y, z }
}
fn to_raw(self, (dim_y, dim_x): (usize, usize)) -> (usize, usize) {
assert!(self.x >= 1 && self.x <= dim_x as i32, "x={} not in [1, {}]", self.x, dim_x);
assert!(self.y >= 1 && self.y <= dim_y as i32, "y={} not in [1, {}]", self.y, dim_y);
(dim_y - self.y as usize, self.x as usize - 1)
}
fn from_raw((y, x): (usize, usize), (dim_y, _dim_x): (usize, usize)) -> Coord2 {
Coord2 { x: x as i32 + 1, y: (dim_y - y) as i32 }
}
}
impl std::ops::Add<Dir> for Coord2 {
type Output = Coord2;
fn add(self, rhs: Dir) -> Coord2 {
let (x, y) = rhs.offset();
Coord2 { x: self.x + x, y: self.y + y }
}
}
/// An XYZ coordinate triple in the BYOND coordinate system.
///
/// The lower-left corner of the first level is `{ x: 1, y: 1, z: 1 }`.
///
/// Note that BYOND by default considers "UP" to be Z+1, but this does not
/// necessarily apply to a given game's logic.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub struct Coord3 {
pub x: i32,
pub y: i32,
pub z: i32,
}
impl Coord3 {
#[inline]
pub fn new(x: i32, y: i32, z: i32) -> Coord3 {
Coord3 { x, y, z }
}
#[inline]
pub fn xy(self) -> Coord2 {
Coord2 { x: self.x, y: self.y }
}
fn to_raw(self, (dim_z, dim_y, dim_x): (usize, usize, usize)) -> (usize, usize, usize) {
assert!(self.x >= 1 && self.x <= dim_x as i32, "x={} not in [1, {}]", self.x, dim_x);
assert!(self.y >= 1 && self.y <= dim_y as i32, "y={} not in [1, {}]", self.y, dim_y);
assert!(self.z >= 1 && self.z <= dim_z as i32, "y={} not in [1, {}]", self.z, dim_z);
(self.z as usize - 1, dim_y - self.y as usize, self.x as usize - 1)
}
#[allow(dead_code)]
fn from_raw((z, y, x): (usize, usize, usize), (_dim_z, dim_y, _dim_x): (usize, usize, usize)) -> Coord3 {
Coord3 { x: x as i32 + 1, y: (dim_y - y) as i32, z: z as i32 + 1 }
}
}
/// A BYOND map, structured similarly to its serialized form.
#[derive(Clone)]
pub struct Map {
key_length: u8,
/// The map's dictionary keys in sorted order.
pub dictionary: BTreeMap<Key, Vec<Prefab>>,
/// The map's grid of keys in Z/Y/X order.
pub grid: Array3<Key>,
}
/// A slice referencing one z-level of a `Map`.
#[derive(Clone, Copy)]
pub struct ZLevel<'a> {
pub grid: ndarray::ArrayView<'a, Key, ndarray::Dim<[usize; 2]>>,
}
// TODO: port to ast::Prefab<Constant>
#[derive(Debug, Default, Hash, Eq, PartialEq, Clone)]
pub struct Prefab {
pub path: String,
// insertion order, sort of most of the time alphabetical but not quite
pub vars: LinkedHashMap<String, Constant>,
}
impl Map {
pub fn new(x: usize, y: usize, z: usize, turf: String, area: String) -> Map {
assert!(x > 0 && y > 0 && z > 0, "({}, {}, {})", x, y, z);
let mut dictionary = BTreeMap::new();
dictionary.insert(Key(0), vec![
Prefab::from_path(turf),
Prefab::from_path(area),
]);
let grid = Array3::default((z, y, x)); // default = 0
Map {
key_length: 1,
dictionary,
grid,
}
}
pub fn with_empty_dictionary(x: usize, y: usize, z: usize) -> Map {
Map {
key_length: 1,
dictionary: BTreeMap::new(),
grid: Array3::default((z, y, x)),
}
}
pub fn from_file(path: &Path) -> Result<Map, DMError> {
let mut map = Map {
key_length: 0,
dictionary: Default::default(),
grid: Array3::default((1, 1, 1)),
};
read::parse_map(&mut map, path)?;
Ok(map)
}
pub fn to_file(&self, path: &Path) -> io::Result<()> {
// DMM saver later
save_tgm::save_tgm(self, File::create(path)?)
}
pub fn key_length(&self) -> u8 {
self.key_length
}
pub fn adjust_key_length(&mut self) {
if self.dictionary.len() > 2704 {
self.key_length = 3;
} else if self.dictionary.len() > 52 {
self.key_length = 2;
} else {
self.key_length = 1;
}
}
#[inline]
pub fn dim_xyz(&self) -> (usize, usize, usize) {
let dim = self.grid.dim();
(dim.2, dim.1, dim.0)
}
#[inline]
pub fn dim_z(&self) -> usize {
self.grid.dim().0
}
#[inline]
pub fn z_level(&self, z: usize) -> ZLevel {
ZLevel { grid: self.grid.index_axis(Axis(0), z) }
}
pub fn iter_levels<'a>(&'a self) -> impl Iterator<Item=(i32, ZLevel<'a>)> + 'a {
self.grid.axis_iter(Axis(0)).enumerate().map(|(i, grid)| (i as i32 + 1, ZLevel { grid }))
}
#[inline]
pub fn format_key(&self, key: Key) -> impl std::fmt::Display {
FormatKey(self.key_length, key)
}
}
impl std::ops::Index<Coord3> for Map {
type Output = Key;
#[inline]
fn index(&self, coord: Coord3) -> &Key {
&self.grid[coord.to_raw(self.grid.dim())]
}
}
impl<'a> ZLevel<'a> {
/// Iterate over the z-level in row-major order starting at the top-left.
pub fn iter_top_down<'b>(&'b self) -> impl Iterator<Item=(Coord2, Key)> + 'b {
let dim = self.grid.dim();
self.grid.indexed_iter().map(move |(c, k)| (Coord2::from_raw(c, dim), *k))
}
}
impl<'a> std::ops::Index<Coord2> for ZLevel<'a> {
type Output = Key;
#[inline]
fn index(&self, coord: Coord2) -> &Key {
&self.grid[coord.to_raw(self.grid.dim())]
}
}
impl Prefab {
pub fn from_path<S: Into<String>>(path: S) -> Prefab {
Prefab {
path: path.into(),
vars: Default::default(),
}
}
}
impl fmt::Display for Prefab {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(&self.path)?;
if !self.vars.is_empty() {
write!(f, " {{")?;
let mut first = true;
for (k, v) in self.vars.iter() {
if !first {
write!(f, "; ")?;
}
first = false;
if f.alternate() {
f.write_str("\n ")?;
}
write!(f, "{} = {}", k, v)?;
}
if f.alternate() {
f.write_str("\n")?;
}
write!(f, "}}")?;
}
Ok(())
}
}
impl fmt::Display for Coord2 {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, {})", self.x, self.y)
}
}
impl fmt::Display for Coord3 {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, {}, {})", self.x, self.y, self.z)
}
}
impl Key {
pub fn invalid() -> Key {
Key(KeyType::max_value())
}
pub fn next(self) -> Key {
Key(self.0 + 1)
}
}
#[derive(Copy, Clone)]
struct FormatKey(u8, Key);
impl fmt::Display for FormatKey {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use std::fmt::Write;
let FormatKey(key_length, Key(key)) = *self;
if key_length < MAX_KEY_LENGTH && key >= 52u16.pow(key_length as u32) {
panic!("Attempted to format an out-of-range key");
}
let mut current = 52usize.pow(key_length as u32 - 1);
for _ in 0..key_length {
f.write_char(BASE_52[(key as usize / current) % 52] as char)?;
current /= 52;
}
Ok(())
}
}
const BASE_52: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
fn base_52_reverse(ch: u8) -> Result<KeyType, String> {
if ch >= b'a' && ch <= b'z' {
Ok(ch as KeyType - b'a' as KeyType)
} else if ch >= b'A' && ch <= b'Z' {
Ok(26 + ch as KeyType - b'A' as KeyType)
} else {
Err(format!("Not a base-52 character: {:?}", ch as char))
}
}
fn advance_key(current: KeyType, next_digit: KeyType) -> Result<KeyType, &'static str> {
current.checked_mul(52).and_then(|b| b.checked_add(next_digit)).ok_or_else(|| {
// https://secure.byond.com/forum/?post=2340796#comment23770802
"Key overflow, max is 'ymo'"
})
}