wz-export 0.0.1

冒险岛wz素材导出为json
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
use anyhow::{Context, Result};
use base64::Engine;
use clap::Parser;
use rayon::prelude::*;
use serde_json::{Map, Value, json};
use std::path::{Path, PathBuf};
use std::process::Child;
use std::sync::atomic::{AtomicUsize, Ordering};
use log::{error, info};
use wz_reader::property::{Vector2D, WzSoundType, WzSubProperty, WzValue};
use wz_reader::util::node_util;
use wz_reader::{WzNode, WzNodeArc, WzObjectType};

#[derive(Parser)]
#[command(name = "wz-export", version)]
struct Cli {
    /// Path to .wz file or Data directory
    #[arg(long)]
    base: PathBuf,

    /// Output directory
    #[arg(long)]
    output: PathBuf,

    /// Only convert a specific .img (e.g. "Character/00002000.img" or "00002000.img")
    #[arg(long)]
    img: Option<String>,

    /// Number of worker threads (default: rayon default, typically all CPU cores)
    #[arg(short = 'j', long)]
    jobs: Option<usize>,
}

fn parse_img_filter(filter: &Option<String>) -> (Option<String>, Option<String>) {
    match filter {
        Some(f) if f.contains('/') => {
            let mut parts = f.splitn(2, '/');
            let wz = parts.next().unwrap().to_string();
            let img = parts.next().unwrap().to_string();
            (Some(wz), Some(img))
        }
        Some(f) => (None, Some(f.clone())),
        None => (None, None),
    }
}

fn main() -> anyhow::Result<()> {
    let (_guard, _err_guard) = wz_export::log::init_tracing("info", true)?;
    log::info!("start ...");

    let cli = Cli::parse();

    if let Some(n) = cli.jobs {
        rayon::ThreadPoolBuilder::new()
            .num_threads(n)
            .build_global()
            .map_err(|e| anyhow::anyhow!("Failed to set rayon threads: {}", e))?;
    }

    std::fs::create_dir_all(&cli.output)?;
    let (wz_filter, img_filter) = parse_img_filter(&cli.img);

    if cli.base.is_dir() {
        for entry in std::fs::read_dir(&cli.base)? {
            let path = entry?.path();
            if path.extension().map_or(false, |e| e == "wz") {
                let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                    process_wz_file(&path, &cli.output, &wz_filter, &img_filter)
                }));
                match result {
                    Ok(Ok(())) => {}
                    Ok(Err(e)) => error!("Error processing {}: {:#}", path.display(), e),
                    Err(_) => error!("Skipped {} (unsupported WZ format or panic)", path.display()),
                }
            }
        }
    } else {
        process_wz_file(&cli.base, &cli.output, &wz_filter, &img_filter)?;
    }

    log::info!("success ...");

    Ok(())
}

fn is_sound_wz(name: &str) -> bool {
    name.eq_ignore_ascii_case("Sound")
}

/// Recursively remove empty directories
fn remove_empty_dirs(dir: &Path) {
    if let Ok(entries) = std::fs::read_dir(dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_dir() {
                remove_empty_dirs(&path);
                // Try to remove if empty after cleaning subdirs
                let _ = std::fs::remove_dir(&path);
            }
        }
    }
}

struct ImgJob {
    node: WzNodeArc,
    output_dir: PathBuf,
    img_name: String,
    is_sound: bool,
}

fn process_wz_file(input: &Path, output: &Path, wz_filter: &Option<String>, img_filter: &Option<String>) -> Result<()> {
    let root: WzNodeArc = WzNode::from_wz_file(input, None)
        .with_context(|| format!("Failed to open: {}", input.display()))?
        .into();

    let wz_name = {
        let mut w = root.write().unwrap();
        w.parse(&root)?;
        w.name.to_string()
    };

    if let Some(wz) = wz_filter {
        if !wz.eq_ignore_ascii_case(&wz_name) {
            return Ok(());
        }
    }

    let wz_dir = output.join(&wz_name);
    std::fs::create_dir_all(&wz_dir)?;

    let root_children: Vec<WzNodeArc> = root.read().unwrap().children.values().cloned().collect();
    let is_sound = is_sound_wz(&wz_name);

    // Phase 1: collect all img jobs (sequential - parses the tree)
    let mut jobs: Vec<ImgJob> = Vec::new();
    for child in &root_children {
        collect_img_jobs(child, &wz_dir, is_sound, &mut jobs, img_filter.as_deref())?;
    }

    if jobs.is_empty() {
        if img_filter.is_some() {
            info!("=== {} (filter: not found) ===", wz_name);
        }
        remove_empty_dirs(&wz_dir);
        return Ok(());
    }

    let total = jobs.len();
    info!("=== {} ({} imgs) ===", wz_name, total);
    let remaining = AtomicUsize::new(total);

    // Phase 2: process all imgs in parallel
    jobs.par_iter().for_each(|job| {
        let left = remaining.fetch_sub(1, Ordering::Relaxed);
        if let Err(e) = process_single_img_job(job) {
            error!("[{}] Error processing {}: {:#}", wz_name, job.img_name, e);
        }
        // Log progress periodically (every 100 imgs or last few)
        if left % 100 == 0 || left <= 10 {
            info!("[{}] [{} left] {}", wz_name, left - 1, job.img_name);
        }
    });

    remove_empty_dirs(&wz_dir);
    info!("Done: {}", wz_dir.display());
    Ok(())
}

/// Sequential tree walk to collect all img jobs (parses directories along the way)
fn collect_img_jobs(
    node: &WzNodeArc,
    output_dir: &Path,
    is_sound: bool,
    jobs: &mut Vec<ImgJob>,
    img_filter: Option<&str>,
) -> Result<()> {
    let _ = node_util::parse_node(node);
    let (name, is_dir, is_img, children) = {
        let node_read = node.read().unwrap();
        let name = node_read.name.to_string();
        let is_dir = matches!(node_read.object_type, WzObjectType::Directory(_));
        let is_img = matches!(node_read.object_type, WzObjectType::Image(_));
        let children: Vec<WzNodeArc> = node_read.children.values().cloned().collect();
        (name, is_dir, is_img, children)
    };

    if is_dir {
        let sub_dir = output_dir.join(&name);
        std::fs::create_dir_all(&sub_dir)?;
        for child in children {
            collect_img_jobs(&child, &sub_dir, is_sound, jobs, img_filter)?;
        }
    } else if is_img {
        let match_name = name.trim_end_matches(".img").to_string();
        if let Some(filter) = img_filter {
            if name != filter && format!("{}.img", match_name) != filter {
                return Ok(());
            }
        }
        jobs.push(ImgJob {
            node: node.clone(),
            output_dir: output_dir.to_path_buf(),
            img_name: name,
            is_sound,
        });
    }
    Ok(())
}

/// Process a single img (called from parallel context)
fn process_single_img_job(job: &ImgJob) -> Result<()> {
    let base = job.img_name.strip_suffix(".img").unwrap_or(&job.img_name);
    if job.is_sound {
        let img_dir = job.output_dir.join(&job.img_name);
        std::fs::create_dir_all(&img_dir)?;
        extract_sounds(&job.node, &img_dir, "")?;
    } else {
        let sound_dir = job.output_dir.join(format!("{}.img", base));
        let json = node_to_json(&job.node, &sound_dir)?;
        let json_str = serde_json::to_string(&json)?;
        let out_path = job.output_dir.join(format!("{}.img.json", base));
        std::fs::write(&out_path, json_str)?;
    }
    Ok(())
}

fn extract_sounds(node: &WzNodeArc, sound_dir: &Path, wz_name: &str) -> Result<()> {
    let _ = node_util::parse_node(node);
    let node_read = node.read().unwrap();

    for (key, child) in &node_read.children {
        let child_read = child.read().unwrap();
        if let WzObjectType::Property(WzSubProperty::Sound(sound)) = &child_read.object_type {
            let ext = match sound.sound_type {
                WzSoundType::Mp3 => "mp3",
                WzSoundType::Wav => "wav",
                _ => "bin",
            };
            let filename = format!("{}.{}", key, ext);
            sound
                .save(sound_dir.join(&filename))
                .map_err(|e| anyhow::anyhow!("Sound error: {}", e))?;
            info!("[sound] {}/{}", wz_name, filename);
        }
    }
    Ok(())
}

fn node_to_json(node: &WzNodeArc, sound_dir: &Path) -> Result<Value> {
    node_to_json_with_path(node, sound_dir, "")
}

fn node_to_json_with_path(node: &WzNodeArc, sound_dir: &Path, img_path: &str) -> Result<Value> {
    let _ = node_util::parse_node(node);
    let node_read = node.read().unwrap();
    let name = node_read.name.to_string();

    // Track the img path for better logging
    let current_path = if img_path.is_empty() {
        name.clone()
    } else {
        format!("{}/{}", img_path, name)
    };

    let children: Vec<(String, WzNodeArc)> = node_read
        .children
        .iter()
        .map(|(k, v)| (k.to_string(), v.clone()))
        .collect();

    let needs_wrapper = !children.is_empty() || is_special(&node_read.object_type);

    if !needs_wrapper {
        if let WzObjectType::Value(value) = &node_read.object_type {
            return wz_value_to_json(value);
        }
        return Ok(Value::Null);
    }

    let mut obj = Map::new();
    obj.insert("name".to_string(), Value::String(name.clone()));

    match &node_read.object_type {
        WzObjectType::Value(WzValue::Vector(Vector2D(x, y))) => {
            obj.insert("type".to_string(), Value::String("vector".to_string()));
            obj.insert("X".to_string(), Value::Number((*x).into()));
            obj.insert("Y".to_string(), Value::Number((*y).into()));
        }
        WzObjectType::Value(WzValue::UOL(s)) => {
            obj.insert("type".to_string(), Value::String("uol".to_string()));
            obj.insert(
                "path".to_string(),
                Value::String(s.get_string().unwrap_or_default()),
            );
        }
        WzObjectType::Property(WzSubProperty::PNG(png)) => {
            obj.insert("type".to_string(), Value::String("canvas".to_string()));

            match png.extract_png() {
                Ok(img) => {
                    let mut png_bytes = Vec::new();
                    if img.write_to(
                        &mut std::io::Cursor::new(&mut png_bytes),
                        image::ImageFormat::Png,
                    ).is_ok() {
                        let uri = base64::engine::general_purpose::STANDARD.encode(&png_bytes);
                        let mut image_obj = Map::new();
                        image_obj.insert("width".to_string(), Value::Number(png.width.into()));
                        image_obj.insert("height".to_string(), Value::Number(png.height.into()));
                        image_obj.insert(
                            "uri".to_string(),
                            Value::String(uri),
                        );
                        obj.insert("_image".to_string(), Value::Object(image_obj));
                    } else {
                        error!("PNG encode error at {}", current_path);
                        obj.insert("_image".to_string(), Value::Null);
                    }
                }
                Err(e) => {
                    error!("PNG decode error at {}: {}", current_path, e);
                    obj.insert("_image".to_string(), Value::Null);
                }
            }
        }
        WzObjectType::Property(WzSubProperty::Sound(sound)) => {
            obj.insert("type".to_string(), Value::String("sound".to_string()));

            let ext = match sound.sound_type {
                WzSoundType::Mp3 => "mp3",
                WzSoundType::Wav => "wav",
                _ => "bin",
            };
            std::fs::create_dir_all(sound_dir)?;
            let sound_name = format!("{}.{}", name, ext);
            sound
                .save(sound_dir.join(&sound_name))
                .map_err(|e| anyhow::anyhow!("Sound error: {}", e))?;
            info!("[sound] {}/{}", current_path, sound_name);
            obj.insert("_sound".to_string(), Value::String(sound_name));
        }
        _ => {}
    }

    // Filter out null children and build _keys
    let mut valid_keys: Vec<Value> = Vec::new();
    for (key, child) in &children {
        let child_json = node_to_json_with_path(child, sound_dir, &current_path)?;
        if !child_json.is_null() {
            //valid_keys.push(Value::String(key.clone()));
            obj.insert(key.clone(), child_json);
        }
        else{
            let child_json=json!({"_keys":[]});            
            obj.insert(key.clone(), child_json);
        }
        
         valid_keys.push(Value::String(key.clone()));
       
    }

    // If only "name" remains (no type, no children), skip the wrapper
    let has_type = obj.contains_key("type");
    if valid_keys.is_empty() && !has_type {
        if let WzObjectType::Value(value) = &node_read.object_type {            
            return wz_value_to_json(value);
        }
        //return Ok(Value::Null);
    }

    //if !valid_keys.is_empty() {
    obj.insert("_keys".to_string(), Value::Array(valid_keys));
    //}

    Ok(Value::Object(obj))
}

fn is_special(obj_type: &WzObjectType) -> bool {
    matches!(
        obj_type,
        WzObjectType::Value(WzValue::Vector(_))
            | WzObjectType::Value(WzValue::UOL(_))
            | WzObjectType::Property(WzSubProperty::PNG(_))
            | WzObjectType::Property(WzSubProperty::Sound(_))
    )
}

fn wz_value_to_json(value: &WzValue) -> Result<Value> {
    match value {
        WzValue::Short(v) => Ok(Value::Number((*v).into())),
        WzValue::Int(v) => Ok(Value::Number((*v).into())),
        WzValue::Long(v) => Ok(Value::Number((*v).into())),
        WzValue::Float(v) => Ok(serde_json::Number::from_f64((*v).into())
            .map(Value::Number)
            .unwrap_or(Value::Null)),
        WzValue::Double(v) => Ok(serde_json::Number::from_f64(*v)
            .map(Value::Number)
            .unwrap_or(Value::Null)),
        WzValue::String(s) => Ok(Value::String(s.get_string().unwrap_or_default())),
        WzValue::ParsedString(s) => Ok(Value::String(s.clone())),
        _ => Ok(Value::Null),
    }
}