wows_minimap_renderer 0.7.0

Library/CLI application for rendering World of Warships replay files as a minimap render "
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
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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
use image::{RgbImage, RgbaImage};
use std::collections::HashMap;
use std::path::Path;
use tracing::{debug, warn};
use wowsunpack::data::idx::FileNode;
use wowsunpack::data::pkg::PkgFileLoader;

use crate::MINIMAP_SIZE;
use crate::map_data;

/// Icon size in pixels for rasterized ship icons.
/// Scales proportionally with minimap size (18px at 768px minimap).
pub const ICON_SIZE: u32 = MINIMAP_SIZE * 3 / 128;

pub fn load_packed_image(
    path: &str,
    file_tree: &FileNode,
    pkg_loader: &PkgFileLoader,
) -> Option<image::DynamicImage> {
    let file_path = Path::new(path);
    let mut buf = Vec::new();
    if file_tree
        .read_file_at_path(file_path, pkg_loader, &mut buf)
        .is_ok()
        && let Ok(img) = image::load_from_memory(&buf)
    {
        return Some(img);
    }
    None
}

pub fn load_map_image(
    map_name: &str,
    file_tree: &FileNode,
    pkg_loader: &PkgFileLoader,
) -> Option<RgbImage> {
    // map_name from meta is e.g. "spaces/28_naval_mission"
    // minimap images live at spaces/<map>/minimap.png in the packed files
    let bare_name = map_name.strip_prefix("spaces/").unwrap_or(map_name);

    let water_path = format!("spaces/{}/minimap_water.png", bare_name);
    let land_path = format!("spaces/{}/minimap.png", bare_name);

    // Load water (background) and land (foreground with alpha) separately,
    // then composite land over water to get the final map image.
    let water = load_packed_image(&water_path, file_tree, pkg_loader);
    let land = load_packed_image(&land_path, file_tree, pkg_loader);

    let result = match (water, land) {
        (Some(water_img), Some(land_img)) => {
            // Composite: start with water, overlay land using alpha
            let mut base = water_img.to_rgba8();
            let overlay = land_img.to_rgba8();
            image::imageops::overlay(&mut base, &overlay, 0, 0);
            debug!(
                width = base.width(),
                height = base.height(),
                "Loaded map image (water + land composited)"
            );
            image::DynamicImage::ImageRgba8(base).to_rgb8()
        }
        (Some(water_img), None) => {
            debug!("Loaded map image: water only");
            water_img.to_rgb8()
        }
        (None, Some(land_img)) => {
            debug!("Loaded map image: land only (no water background)");
            land_img.to_rgb8()
        }
        (None, None) => {
            warn!(map = %map_name, "Could not load map image, using blank background");
            return None;
        }
    };

    if result.width() != MINIMAP_SIZE || result.height() != MINIMAP_SIZE {
        let resized = image::imageops::resize(
            &result,
            MINIMAP_SIZE,
            MINIMAP_SIZE,
            image::imageops::FilterType::Lanczos3,
        );
        return Some(resized);
    }
    Some(result)
}

pub fn load_map_info(
    map_name: &str,
    file_tree: &FileNode,
    pkg_loader: &PkgFileLoader,
) -> Option<map_data::MapInfo> {
    let bare_name = map_name.strip_prefix("spaces/").unwrap_or(map_name);

    // Try multiple path variants — the virtual filesystem layout may differ
    let candidates = [
        format!("spaces/{}/space.settings", bare_name),
        format!("content/gameplay/{}/space.settings", bare_name),
    ];
    let mut buf = Vec::new();
    let mut found = false;
    for candidate in &candidates {
        buf.clear();
        let file_path = Path::new(candidate);
        if file_tree
            .read_file_at_path(file_path, pkg_loader, &mut buf)
            .is_ok()
            && !buf.is_empty()
        {
            debug!(path = %candidate, "Loaded space.settings");
            found = true;
            break;
        }
    }
    if !found {
        warn!(map = %bare_name, tried = ?candidates, "Could not load space.settings, using defaults");
        return None;
    }

    let content = String::from_utf8_lossy(&buf);
    let doc = roxmltree::Document::parse(&content).ok()?;

    // Helper: read a value either as an attribute on `node` or as a child element's text
    let read_value = |parent: &roxmltree::Node, name: &str| -> Option<String> {
        // Try attribute first (e.g. <bounds minX="-9" />)
        if let Some(v) = parent.attribute(name) {
            return Some(v.to_string());
        }
        // Then try child element (e.g. <bounds><minX> -9 </minX></bounds>)
        parent
            .children()
            .find(|c| c.has_tag_name(name))
            .and_then(|c| c.text())
            .map(|t| t.trim().to_string())
    };

    let bounds = doc.descendants().find(|n| n.has_tag_name("bounds"))?;
    let min_x: i32 = read_value(&bounds, "minX")?.parse().ok()?;
    let max_x: i32 = read_value(&bounds, "maxX")?.parse().ok()?;
    let min_y: i32 = read_value(&bounds, "minY")?.parse().ok()?;
    let max_y: i32 = read_value(&bounds, "maxY")?.parse().ok()?;

    // chunkSize can be a child element of root or of <terrain>
    let chunk_size: f64 = doc
        .descendants()
        .find(|n| n.has_tag_name("chunkSize"))
        .and_then(|n| n.text().and_then(|t| t.trim().parse().ok()))
        .unwrap_or(100.0);

    // Formula from Python spaces.py:
    // w = len(range(min_x, max_x + 1)) * chunk_size - 4 * chunk_size
    let chunks_x = (max_x - min_x + 1) as f64;
    let chunks_y = (max_y - min_y + 1) as f64;
    let space_w = ((chunks_x - 4.0) * chunk_size).round() as i32;
    let space_h = ((chunks_y - 4.0) * chunk_size).round() as i32;

    // Use the larger dimension as space_size (maps should be square)
    let space_size = space_w.max(space_h);

    debug!(
        map = %bare_name,
        bounds_min = ?(min_x, min_y),
        bounds_max = ?(max_x, max_y),
        chunk_size,
        space_size,
        "Map metadata"
    );

    Some(map_data::MapInfo { space_size })
}

/// Load and rasterize ship SVG icons from game files.
/// Returns a map from species name to RGBA image.
///
/// Loads 5 variants per species:
/// - `"{Species}"` — base icon (visible ally/enemy)
/// - `"{Species}_self"` — player's own ship
/// - `"{Species}_dead"` — destroyed ship
/// - `"{Species}_invisible"` — not currently detected
/// - `"{Species}_last_visible"` — last known position (minimap-only)
pub fn load_ship_icons(
    file_tree: &FileNode,
    pkg_loader: &PkgFileLoader,
) -> HashMap<String, RgbaImage> {
    let species_names = [
        "Destroyer",
        "Cruiser",
        "Battleship",
        "AirCarrier",
        "Submarine",
        "Auxiliary",
    ];
    // (file suffix, key suffix) — all in gui/fla/minimap/ship_icons/
    let variants: &[(&str, &str)] = &[
        ("", ""),
        ("_dead", "_dead"),
        ("_invisible", "_invisible"),
        ("_last_visible", "_last_visible"),
    ];
    let mut icons = HashMap::new();
    let load_svg = |path: &str, key: &str, icons: &mut HashMap<String, RgbaImage>| {
        let file_path = Path::new(path);
        let mut buf = Vec::new();
        if file_tree
            .read_file_at_path(file_path, pkg_loader, &mut buf)
            .is_ok()
            && !buf.is_empty()
            && let Some(img) = rasterize_svg(&buf, ICON_SIZE)
        {
            icons.insert(key.to_string(), img);
            return true;
        }
        false
    };
    for name in &species_names {
        let lower = name.to_ascii_lowercase();
        for &(file_suffix, key_suffix) in variants {
            let path = format!(
                "gui/fla/minimap/ship_icons/minimap_{}{}.svg",
                lower, file_suffix
            );
            let key = format!("{}{}", name, key_suffix);
            load_svg(&path, &key, &mut icons);
        }
        // Self icons from ship_icons_self/ directory
        // Try species-specific first, then generic fallback
        let self_key = format!("{}_self", name);
        let self_paths = [
            format!(
                "gui/fla/minimap/ship_icons_self/minimap_self_alive_{}.svg",
                lower
            ),
            "gui/fla/minimap/ship_icons_self/minimap_self_alive.svg".to_string(),
        ];
        for path in &self_paths {
            if load_svg(path, &self_key, &mut icons) {
                break;
            }
        }
        // Dead-self variant
        let dead_self_key = format!("{}_dead_self", name);
        let dead_self_paths = [
            format!(
                "gui/fla/minimap/ship_icons_self/minimap_self_dead_{}.svg",
                lower
            ),
            "gui/fla/minimap/ship_icons_self/minimap_self_dead.svg".to_string(),
        ];
        for path in &dead_self_paths {
            if load_svg(path, &dead_self_key, &mut icons) {
                break;
            }
        }
    }
    debug!(count = icons.len(), "Loaded ship icons");
    if icons.is_empty() {
        warn!("No ship icons loaded, using fallback circles");
    }
    icons
}

/// Load all plane icons from game files into a HashMap keyed by name (e.g. "fighter_ally").
pub fn load_plane_icons(
    file_tree: &FileNode,
    pkg_loader: &PkgFileLoader,
) -> HashMap<String, RgbaImage> {
    let dirs = [
        "gui/battle_hud/markers_minimap/plane/consumables",
        "gui/battle_hud/markers_minimap/plane/controllable",
        "gui/battle_hud/markers_minimap/plane/airsupport",
    ];
    let suffixes = ["ally", "enemy", "own", "division", "teamkiller"];
    let base_names = [
        // controllable
        "fighter_he",
        "fighter_ap",
        "fighter_he_st2024",
        "bomber_he",
        "bomber_ap",
        "bomber_ap_st2024",
        "skip_he",
        "skip_ap",
        "torpedo_regular",
        "torpedo_regular_st2024",
        "torpedo_deepwater",
        "auxiliary",
        // consumables
        "fighter",
        "fighter_upgrade",
        "scout",
        "smoke",
        // airsupport
        "bomber_depth_charge",
        "bomber_mine",
    ];

    let mut icons = HashMap::new();
    for dir in &dirs {
        // Use the last path component as namespace (e.g. "consumables", "controllable", "airsupport")
        let dir_name = dir.rsplit('/').next().unwrap_or(dir);
        for base in &base_names {
            for suffix in &suffixes {
                let name = format!("{}_{}", base, suffix);
                let path = format!("{}/{}.png", dir, name);
                if let Some(img) = load_packed_image(&path, file_tree, pkg_loader) {
                    let key = format!("{}/{}", dir_name, name);
                    let rgba = img.to_rgba8();
                    // Resize to ICON_SIZE to scale with minimap
                    let resized = image::imageops::resize(
                        &rgba,
                        ICON_SIZE,
                        ICON_SIZE,
                        image::imageops::FilterType::Lanczos3,
                    );
                    icons.insert(key, resized);
                }
            }
        }
    }
    debug!(count = icons.len(), "Loaded plane icons");
    icons
}

/// Load consumable icons from game files into a HashMap keyed by PCY name.
///
/// Discovers all `consumable_PCY*.png` files in `gui/consumables/` to support
/// all ability variants (base, Premium, Super, TimeBased, etc.).
pub fn load_consumable_icons(
    file_tree: &FileNode,
    pkg_loader: &PkgFileLoader,
) -> HashMap<String, RgbaImage> {
    let mut icons = HashMap::new();

    // Navigate to gui/consumables/ directory and enumerate all files
    let consumables_dir = file_tree
        .children()
        .get("gui")
        .and_then(|gui| gui.children().get("consumables"));

    if let Some(dir) = consumables_dir {
        for filename in dir.children().keys() {
            // Match files like "consumable_PCY009_CrashCrewPremium.png"
            if let Some(pcy_name) = filename
                .strip_prefix("consumable_")
                .and_then(|s| s.strip_suffix(".png"))
            {
                if !pcy_name.starts_with("PCY") {
                    continue;
                }
                let path = format!("gui/consumables/{}", filename);
                if let Some(img) = load_packed_image(&path, file_tree, pkg_loader) {
                    let resized = image::imageops::resize(
                        &img,
                        28,
                        28,
                        image::imageops::FilterType::Lanczos3,
                    );
                    icons.insert(pcy_name.to_string(), resized);
                }
            }
        }
    }

    debug!(count = icons.len(), "Loaded consumable icons");
    icons
}

/// Load death cause icons from game files into a HashMap keyed by cause name.
///
/// Discovers `icon_frag_*.png` files in `gui/battle_hud/icon_frag/` and stores
/// them resized to `size x size` pixels, keyed by the base name (e.g. `"main_caliber"`).
pub fn load_death_cause_icons(
    file_tree: &FileNode,
    pkg_loader: &PkgFileLoader,
    size: u32,
) -> HashMap<String, RgbaImage> {
    let mut icons = HashMap::new();

    let frag_dir = file_tree
        .children()
        .get("gui")
        .and_then(|gui| gui.children().get("battle_hud"))
        .and_then(|bh| bh.children().get("icon_frag"));

    if let Some(dir) = frag_dir {
        for filename in dir.children().keys() {
            if let Some(base_name) = filename
                .strip_prefix("icon_frag_")
                .and_then(|s| s.strip_suffix(".png"))
            {
                let path = format!("gui/battle_hud/icon_frag/{}", filename);
                if let Some(img) = load_packed_image(&path, file_tree, pkg_loader) {
                    let resized = image::imageops::resize(
                        &img,
                        size,
                        size,
                        image::imageops::FilterType::Lanczos3,
                    );
                    icons.insert(base_name.to_string(), resized);
                }
            }
        }
    }

    debug!(count = icons.len(), "Loaded death cause icons");
    icons
}

/// Load powerup (arms race buff) icons from game files.
///
/// Discovers `icon_marker_*.png` files in `gui/powerups/drops/` and stores them
/// resized to `size x size` pixels, keyed by marker name (e.g. `"damage_active"`).
pub fn load_powerup_icons(
    file_tree: &FileNode,
    pkg_loader: &PkgFileLoader,
    size: u32,
) -> HashMap<String, RgbaImage> {
    let mut icons = HashMap::new();

    let drops_dir = file_tree
        .children()
        .get("gui")
        .and_then(|gui| gui.children().get("powerups"))
        .and_then(|pu| pu.children().get("drops"));

    if let Some(dir) = drops_dir {
        for filename in dir.children().keys() {
            if let Some(marker_name) = filename
                .strip_prefix("icon_marker_")
                .and_then(|s| s.strip_suffix(".png"))
            {
                // Skip _small variants
                if marker_name.ends_with("_small") {
                    continue;
                }
                let path = format!("gui/powerups/drops/{}", filename);
                if let Some(img) = load_packed_image(&path, file_tree, pkg_loader) {
                    let resized = image::imageops::resize(
                        &img,
                        size,
                        size,
                        image::imageops::FilterType::Lanczos3,
                    );
                    icons.insert(marker_name.to_string(), resized);
                }
            }
        }
    }

    debug!(count = icons.len(), "Loaded powerup icons");
    icons
}

/// Rasterize an SVG byte buffer to an RGBA image at the given size.
///
/// Automatically crops transparent padding from the SVG and fills the output
/// as much as possible.
pub fn rasterize_svg(svg_data: &[u8], size: u32) -> Option<RgbaImage> {
    let opt = resvg::usvg::Options::default();
    let tree = resvg::usvg::Tree::from_data(svg_data, &opt).ok()?;

    // Render at a larger internal size for accurate bounding-box detection.
    // Use pre_scale so the offset is in output-pixel space (not scaled).
    let internal_size = size * 4;
    let tree_size = tree.size();
    let sx = internal_size as f32 / tree_size.width();
    let sy = internal_size as f32 / tree_size.height();
    let scale = sx.min(sy);

    let mut pixmap = tiny_skia::Pixmap::new(internal_size, internal_size)?;

    let offset_x = (internal_size as f32 - tree_size.width() * scale) / 2.0;
    let offset_y = (internal_size as f32 - tree_size.height() * scale) / 2.0;
    let transform =
        tiny_skia::Transform::from_scale(scale, scale).post_translate(offset_x, offset_y);

    resvg::render(&tree, transform, &mut pixmap.as_mut());

    // Find bounding box of non-transparent pixels
    let w = pixmap.width();
    let h = pixmap.height();
    let data = pixmap.data();
    let mut min_x = w;
    let mut min_y = h;
    let mut max_x = 0u32;
    let mut max_y = 0u32;
    for y in 0..h {
        for x in 0..w {
            let idx = (y * w + x) as usize * 4;
            if data[idx + 3] > 0 {
                min_x = min_x.min(x);
                min_y = min_y.min(y);
                max_x = max_x.max(x);
                max_y = max_y.max(y);
            }
        }
    }

    if max_x < min_x || max_y < min_y {
        // Fully transparent — return empty icon at target size
        return RgbaImage::from_raw(size, size, vec![0u8; (size * size * 4) as usize]);
    }

    // Crop to bounding box with 1px margin
    let margin = 1u32;
    let crop_x = min_x.saturating_sub(margin);
    let crop_y = min_y.saturating_sub(margin);
    let crop_w = (max_x + 1 + margin).min(w) - crop_x;
    let crop_h = (max_y + 1 + margin).min(h) - crop_y;

    // Extract cropped RGBA data (unpremultiply alpha from tiny-skia's premultiplied format)
    let mut cropped = RgbaImage::new(crop_w, crop_h);
    for y in 0..crop_h {
        for x in 0..crop_w {
            let src_idx = ((crop_y + y) * w + crop_x + x) as usize * 4;
            let a = data[src_idx + 3];
            let (r, g, b) = if a > 0 {
                let af = a as f32 / 255.0;
                (
                    (data[src_idx] as f32 / af).min(255.0) as u8,
                    (data[src_idx + 1] as f32 / af).min(255.0) as u8,
                    (data[src_idx + 2] as f32 / af).min(255.0) as u8,
                )
            } else {
                (0, 0, 0)
            };
            cropped.put_pixel(x, y, image::Rgba([r, g, b, a]));
        }
    }

    // Resize cropped image to fit within size x size, maintaining aspect ratio
    let fit_sx = size as f32 / crop_w as f32;
    let fit_sy = size as f32 / crop_h as f32;
    let fit_scale = fit_sx.min(fit_sy);
    let final_w = (crop_w as f32 * fit_scale).round().max(1.0) as u32;
    let final_h = (crop_h as f32 * fit_scale).round().max(1.0) as u32;

    let resized = image::imageops::resize(
        &cropped,
        final_w,
        final_h,
        image::imageops::FilterType::Lanczos3,
    );

    // Center in size x size canvas
    let mut output = RgbaImage::new(size, size);
    let ox = (size.saturating_sub(final_w)) / 2;
    let oy = (size.saturating_sub(final_h)) / 2;
    image::imageops::overlay(&mut output, &resized, ox as i64, oy as i64);

    Some(output)
}