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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
#[cfg_attr(any(feature = "rs3", feature = "2013_4_shim"), path = "mapsquares/rs3.rs")]
#[cfg_attr(all(feature = "osrs", not(feature = "2013_4_shim")), path = "mapsquares/osrs.rs")]
#[cfg_attr(feature = "legacy", path = "mapsquares/legacy.rs")]
mod iterator;
use std::{
collections::{hash_map, HashMap},
fs::{self, File},
io::Write,
iter::Zip,
ops::Range,
};
use ::error::Context;
use itertools::{iproduct, Product};
use ndarray::{iter::LanesIter, s, Axis, Dim};
use path_macro::path;
use rayon::iter::{ParallelBridge, ParallelIterator};
#[cfg(all(feature = "osrs", not(feature = "2013_4_shim")))]
use rs3cache_backend::xtea::Xtea;
use rs3cache_backend::{
error::{self, CacheResult},
index::{CacheIndex, Initial},
};
use rs3cache_utils::rangeclamp::RangeClamp;
#[cfg(any(feature = "rs3", feature = "2013_4_shim"))]
use {
crate::definitions::indextype::MapFileType,
bytes::Buf,
rs3cache_backend::{arc::Archive, error::CacheError},
rs3cache_utils::lazy::Lazy,
};
pub use self::iterator::*;
use crate::definitions::{
locations::Location,
tiles::{Tile, TileArray},
};
#[derive(Debug)]
pub struct MapSquare {
i: u8,
j: u8,
tiles: Option<TileArray>,
#[cfg(feature = "rs3")]
pub members: Option<u64>,
locations: Option<Vec<Location>>,
#[cfg(feature = "osrs")]
pub xtea: Option<Xtea>,
#[cfg(any(feature = "rs3", feature = "2013_4_shim"))]
water_locations: Option<Lazy<(bytes::Bytes, u8, u8), Vec<Location>, CacheError>>,
}
pub type ColumnIter<'c> = Zip<LanesIter<'c, Tile, Dim<[usize; 2]>>, Product<Range<u32>, Range<u32>>>;
impl MapSquare {
pub fn i(&self) -> u8 {
self.i
}
pub fn j(&self) -> u8 {
self.j
}
#[cfg(all(test, any(feature = "rs3", feature = "2013_4_shim")))]
pub fn new(i: u8, j: u8, config: &crate::cli::Config) -> CacheResult<MapSquare> {
assert!(i < 0x7F, "Index out of range.");
let archive_id = (i as u32) | (j as u32) << 7;
let archive = CacheIndex::new(crate::definitions::indextype::IndexType::MAPSV2, config.input.clone())?.archive(archive_id)?;
Ok(Self::from_archive(archive))
}
#[cfg(all(feature = "osrs", not(feature = "2013_4_shim")))]
fn new(index: &CacheIndex<Initial>, xtea: Option<Xtea>, land: u32, tiles: u32, env: Option<u32>, i: u8, j: u8) -> CacheResult<MapSquare> {
let land = index
.archive_with_xtea(land, xtea)
.and_then(|arch| arch.file(&0).context(rs3cache_backend::index::Other).context(error::Integrity));
let mut tile_bytes = index
.archive(tiles)?
.file(&0)
.context(rs3cache_backend::index::Other)
.context(error::Integrity)?;
let _env = env.map(|k| index.archive(k));
let tiles = Tile::dump(&mut tile_bytes);
let locations = match land {
Ok(land) => Some(Location::dump(i, j, &tiles, land)),
Err(_) => None,
};
Ok(MapSquare {
i,
j,
tiles: Some(tiles),
locations,
xtea,
})
}
#[cfg(feature = "legacy")]
fn new(index: &CacheIndex<Initial>, loc: u32, map: u32, i: u8, j: u8) -> CacheResult<MapSquare> {
let land = index
.archive(loc)?
.file(&0)
.context(rs3cache_backend::index::Other)
.context(error::Integrity)?;
let mut tile_bytes = index
.archive(map)?
.file(&0)
.context(rs3cache_backend::index::Other)
.context(error::Integrity)?;
let tiles = Tile::dump(&mut tile_bytes);
let locations = Location::dump(i, j, &tiles, land);
Ok(MapSquare {
i,
j,
tiles: Some(tiles),
locations: Some(locations),
})
}
#[cfg(any(feature = "rs3", feature = "2013_4_shim"))]
pub(crate) fn from_archive(archive: Archive) -> MapSquare {
let i = (archive.archive_id() & 0x7F) as u8;
let j = (archive.archive_id() >> 7) as u8;
let mut tile_bytes = archive.file(&MapFileType::TILES);
let (tiles, members, locations) = match tile_bytes {
Some(ref mut tile_bytes) => {
let tiles = Tile::dump(tile_bytes);
let members = tile_bytes.get_u64();
let locations = archive.file(&MapFileType::LOCATIONS).map(|file| Location::dump(i, j, &tiles, file));
(Some(tiles), Some(members), locations)
}
None => (None, None, None),
};
let bytes = archive.file(&MapFileType::WATER_LOCATIONS);
let water_locations = bytes.map(|bytes| Lazy::new((bytes, i, j), |(bytes, i, j)| Ok(Location::dump_water_locations(i, j, bytes))));
MapSquare {
i,
j,
tiles,
members,
locations,
water_locations,
}
}
pub fn indexed_columns(&self) -> Option<ColumnIter> {
Some(self.tiles()?.lanes(Axis(0)).into_iter().zip(iproduct!(0..64u32, 0..64u32)))
}
pub fn tiles(&self) -> Option<&TileArray> {
self.tiles.as_ref()
}
pub fn take_tiles(self) -> Option<TileArray> {
self.tiles
}
pub fn locations(&self) -> Option<&[Location]> {
self.locations.as_deref()
}
pub fn take_locations(self) -> Option<Vec<Location>> {
self.locations
}
#[cfg(any(feature = "rs3", feature = "2013_4_shim"))]
pub fn water_locations(&self) -> Option<&Result<Vec<Location>, CacheError>> {
self.water_locations.as_deref()
}
}
pub struct MapSquares {
index: CacheIndex<Initial>,
#[cfg(all(feature = "osrs", not(feature = "2013_4_shim")))]
mapping: std::collections::BTreeMap<(&'static str, u8, u8), u32>,
#[cfg(feature = "legacy")]
meta: std::collections::BTreeMap<(u8, u8), rs3cache_backend::index::MapsquareMeta>,
}
impl IntoIterator for MapSquares {
type Item = CacheResult<MapSquare>;
type IntoIter = MapSquareIterator;
#[cfg(any(feature = "rs3", feature = "2013_4_shim"))]
fn into_iter(self) -> Self::IntoIter {
let state = self
.index
.metadatas()
.keys()
.map(|id| ((id & 0x7F) as u8, (id >> 7) as u8))
.collect::<Vec<_>>()
.into_iter();
MapSquareIterator { mapsquares: self, state }
}
#[cfg(all(feature = "osrs", not(feature = "2013_4_shim")))]
fn into_iter(self) -> Self::IntoIter {
let state = self
.mapping
.keys()
.filter_map(|(ty, i, j)| if *ty == "m" { Some((*i, *j)) } else { None })
.collect::<Vec<_>>()
.into_iter();
MapSquareIterator { mapsquares: self, state }
}
#[cfg(feature = "legacy")]
fn into_iter(self) -> Self::IntoIter {
let state = self.meta.keys().copied().collect::<Vec<_>>().into_iter();
MapSquareIterator { mapsquares: self, state }
}
}
pub struct GroupMapSquare {
core_i: u8,
core_j: u8,
mapsquares: HashMap<(u8, u8), MapSquare>,
}
impl GroupMapSquare {
#[inline(always)]
pub fn core_i(&self) -> u8 {
self.core_i
}
#[inline(always)]
pub fn core_j(&self) -> u8 {
self.core_j
}
pub fn core(&self) -> Option<&MapSquare> {
self.mapsquares.get(&(self.core_i, self.core_j))
}
pub fn iter(&self) -> hash_map::Iter<'_, (u8, u8), MapSquare> {
self.mapsquares.iter()
}
pub fn get(&self, key: &(u8, u8)) -> Option<&MapSquare> {
self.mapsquares.get(key)
}
pub fn tiles_iter(&self, plane: usize, x: usize, y: usize, interp: isize) -> Box<dyn Iterator<Item = &Tile> + '_> {
let low_x = x as isize - interp;
let upper_x = x as isize + interp + 1;
let low_y = y as isize - interp;
let upper_y = y as isize + interp + 1;
Box::new(
self.iter()
.filter_map(move |((i, j), sq)| {
sq.tiles().map(|tiles| {
let di = (*i as isize) - (self.core_i as isize);
let dj = (*j as isize) - (self.core_j as isize);
((di, dj), tiles)
})
})
.flat_map(move |((di, dj), tiles)| {
tiles
.slice(s![
plane,
((low_x - 64 * di)..(upper_x - 64 * di)).clamp(0, 64),
((low_y - 64 * dj)..(upper_y - 64 * dj)).clamp(0, 64)
])
.into_iter()
}),
)
}
pub fn all_locations_iter(&self) -> Box<dyn Iterator<Item = &Location> + '_> {
Box::new(
self.iter()
.filter_map(|(_k, square)| square.locations())
.flat_map(IntoIterator::into_iter),
)
}
}
pub fn export_locations_by_id(config: &crate::cli::Config) -> CacheResult<()> {
let out = path_macro::path!(config.output / "locations");
fs::create_dir_all(&out).with_context(|| error::Io { path: out.clone() })?;
let last_id = {
let squares = MapSquares::new(config)?.into_iter();
squares
.filter_map(|sq| sq.expect("error deserializing mapsquare").take_locations())
.filter(|locs| !locs.is_empty())
.map(|locs| locs.last().expect("locations stopped existing").id)
.max()
.unwrap()
};
let squares = MapSquares::new(config)?.into_iter();
let mut locs: Vec<_> = squares
.filter_map(|sq| sq.expect("error deserializing mapsquare").take_locations())
.map(|locs| locs.into_iter().peekable())
.collect();
(0..=last_id)
.map(|id| {
(
id,
locs.iter_mut()
.flat_map(|iterator| std::iter::repeat_with(move || iterator.next_if(|loc| loc.id == id)).take_while(|item| item.is_some()))
.flatten()
.collect::<Vec<Location>>(),
)
})
.par_bridge()
.for_each(|(id, id_locs)| {
if !id_locs.is_empty() && id != 83 {
let mut file = File::create(path!(&out / format!("{id}.json"))).unwrap();
let data = serde_json::to_string_pretty(&id_locs).unwrap();
file.write_all(data.as_bytes()).unwrap();
}
});
Ok(())
}
pub fn export_locations_by_square(config: &crate::cli::Config) -> CacheResult<()> {
let out = path_macro::path!(config.output / "locations");
fs::create_dir_all(&out).with_context(|| error::Io { path: out.clone() })?;
MapSquares::new(config)?.into_iter().par_bridge().for_each(|sq| {
let sq = sq.expect("error deserializing mapsquare");
let i = sq.i;
let j = sq.j;
if let Some(locations) = sq.take_locations() {
if !locations.is_empty() {
let mut file = File::create(path!(&out / format!("{i}_{j}.json"))).unwrap();
let data = serde_json::to_string_pretty(&locations).unwrap();
file.write_all(data.as_bytes()).unwrap();
}
}
});
Ok(())
}
pub fn export_tiles_by_square(config: &crate::cli::Config) -> CacheResult<()> {
let out = path_macro::path!(config.output / "tiles");
fs::create_dir_all(&out).with_context(|| error::Io { path: out.clone() })?;
MapSquares::new(config)?.into_iter().par_bridge().for_each(|sq| {
let sq = sq.expect("error deserializing mapsquare");
let i = sq.i;
let j = sq.j;
if let Some(tiles) = sq.take_tiles() {
if !tiles.is_empty() {
let mut file = File::create(path!(&out / format!("{i}_{j}.json"))).unwrap();
let data = serde_json::to_string_pretty(&tiles).unwrap();
file.write_all(data.as_bytes()).unwrap();
}
}
});
Ok(())
}
#[cfg(all(test, any(feature = "rs3", feature = "osrs")))]
mod tests {
use super::*;
use crate::cli::Config;
#[test]
fn water() -> CacheResult<()> {
let config = Config::env();
let squares = MapSquares::new(&config)?.into_iter();
for square in squares {
let square = square.unwrap();
if square.i() == 40 && square.j() == 62 {
for i in 0..4 {
let tile = square.tiles().unwrap().get([i, 10, 10]);
dbg!(tile);
}
return Ok(());
}
}
panic!("Unable to get some water");
}
}
#[cfg(all(test, feature = "legacy"))]
mod legacy {
use super::*;
use crate::cli::Config;
#[test]
fn decode_50_50() {
let config = Config::env();
let mut cache = CacheIndex::new(4, config.input).unwrap();
let index = cache.get_index();
let meta = index[&(50, 50)];
dbg!(meta);
let _locs = cache.archive(meta.locfile as u32).unwrap(); let _map = cache.archive(meta.mapfile as u32).unwrap(); }
}
#[cfg(all(test, feature = "legacy"))]
mod mapsquare_iter {
use super::*;
#[test]
fn traverse() -> CacheResult<()> {
let config = crate::cli::Config::env();
let sqs = MapSquares::new(&config)?.into_iter();
for sq in sqs {
if let Some(locations) = sq.expect("error deserializing mapsquare").locations() {
for loc in locations {
if loc.id == 3263 {
println!("{} {} {} {}", loc.i, loc.i, loc.x, loc.y);
if loc.i == 56 && loc.j == 54 && loc.x == 62 && loc.y == 53 {
return Ok(());
}
}
}
}
}
panic!("swamp not found");
}
}
#[cfg(all(test, feature = "rs3"))]
mod map_tests {
use super::*;
#[test]
fn loc_0_50_50_9_16_is_trapdoor() -> CacheResult<()> {
let config = crate::cli::Config::env();
let id = 36687_u32;
let square = MapSquare::new(50, 50, &config)?;
assert!(square
.locations()
.unwrap()
.iter()
.any(|loc| loc.id == id && loc.plane.matches(&0) && loc.x == 9 && loc.y == 16));
Ok(())
}
#[test]
fn get_tile() -> CacheResult<()> {
let config = crate::cli::Config::env();
let square = MapSquare::new(49, 54, &config)?;
let _tile = square.tiles().unwrap().get([0, 24, 25]);
Ok(())
}
#[test]
fn members() -> CacheResult<()> {
let config = crate::cli::Config::env();
let mapsquares = MapSquares::new(&config)?.into_iter();
for sq in mapsquares {
if let Ok(sq) = sq {
if let Some(members) = sq.members {
println!("({},{}):{:b}", sq.i, sq.j, members);
}
}
}
Ok(())
}
}