1use std::fs;
7use std::path::Path;
8
9use tracing::{info, warn};
10
11use crate::symbol::{SymbolKind, SymbolRegistry};
12use crate::types::Type;
13
14pub fn load_engine_command_params(registry: &mut SymbolRegistry, engine_rs2: &Path) {
19 let text = match fs::read_to_string(engine_rs2) {
20 Ok(t) => t,
21 Err(_) => return,
22 };
23 for line in text.lines() {
24 let line = line.trim();
25 if !line.starts_with("[command,") {
27 continue;
28 }
29 let rest = &line["[command,".len()..];
31 let name_end = match rest.find(']') {
32 Some(i) => i,
33 None => continue,
34 };
35 let name = rest[..name_end].trim().to_string();
36
37 let after_bracket = &rest[name_end + 1..];
39 let params_start = match after_bracket.find('(') {
40 Some(i) => i + 1,
41 None => {
42 registry.command_param_types.insert(name, Vec::new());
44 continue;
45 }
46 };
47 let params_end = match after_bracket[params_start..].find(')') {
48 Some(i) => params_start + i,
49 None => continue,
50 };
51 let params_str = &after_bracket[params_start..params_end];
52
53 let mut param_types: Vec<Type> = Vec::new();
54 for param in params_str.split(',') {
55 let param = param.trim();
56 if param.is_empty() {
57 continue;
58 }
59 let type_name = param.split_whitespace().next().unwrap_or(param);
61 if let Some(t) = Type::from_name(type_name) {
62 param_types.push(t);
63 } else {
64 param_types.push(Type::Int);
66 }
67 }
68 registry
69 .command_param_types
70 .insert(name.clone(), param_types.clone());
71
72 if let Some(sym) = registry.commands.get_mut(&name)
73 && let SymbolKind::Command {
74 param_types: ref mut pt,
75 ..
76 } = sym.kind
77 {
78 *pt = param_types;
79 }
80
81 let after_params = &after_bracket[params_end + 1..];
83 if let Some(ret_start) = after_params.find('(')
84 && let Some(ret_end) = after_params[ret_start + 1..].find(')')
85 {
86 let ret_str = &after_params[ret_start + 1..ret_start + 1 + ret_end];
87 let mut return_types: Vec<Type> = Vec::new();
88 for ret in ret_str.split(',') {
89 let ret = ret.trim();
90 if ret.is_empty() {
91 continue;
92 }
93 if let Some(t) = Type::from_name(ret) {
94 return_types.push(t);
95 }
96 }
97 if !return_types.is_empty() {
98 if let Some(sym) = registry.commands.get_mut(&name)
100 && let SymbolKind::Command {
101 return_types: ref mut rt,
102 ..
103 } = sym.kind
104 {
105 *rt = return_types;
106 }
107 }
108 }
109 }
110}
111
112pub fn patch_command_return_types(registry: &mut SymbolRegistry) {
116 let patches: &[(&str, Vec<Type>)] = &[
117 ("db_find_with_count", vec![Type::Int]),
118 ("db_find_refine_with_count", vec![Type::Int]),
119 ("db_listall_with_count", vec![Type::Int]),
120 ];
121 for (name, ret_types) in patches {
122 if let Some(sym) = registry.commands.get_mut(*name)
123 && let SymbolKind::Command { return_types, .. } = &mut sym.kind
124 && return_types.is_empty()
125 {
126 *return_types = ret_types.clone();
127 }
128 }
129}
130
131fn load_script_pack(registry: &mut SymbolRegistry, path: &Path) {
134 let text = match fs::read_to_string(path) {
135 Ok(t) => t,
136 Err(_) => return,
137 };
138 for line in text.lines() {
139 let line = line.trim();
140 if line.is_empty() {
141 continue;
142 }
143 let (id_str, rest) = match line.split_once('=') {
144 Some(pair) => pair,
145 None => continue,
146 };
147 let id: i32 = match id_str.parse() {
148 Ok(v) => v,
149 Err(_) => continue,
150 };
151 let rest = rest.trim();
152 if !rest.starts_with('[') || !rest.ends_with(']') {
154 continue;
155 }
156 let inner = &rest[1..rest.len() - 1];
157 let comma = match inner.find(',') {
158 Some(i) => i,
159 None => continue,
160 };
161 let trigger = &inner[..comma];
162 let name = &inner[comma + 1..];
163 if trigger.is_empty() || name.is_empty() {
164 continue;
165 }
166 let key = format!("{}:{}", trigger, name);
167 registry.preloaded_script_ids.insert(key, id);
168 }
169}
170
171pub fn generate_script_pack(
174 scripts_dir: &Path,
175 pack_dir: &Path,
176 sources: &std::collections::HashMap<std::path::PathBuf, std::sync::Arc<String>>,
177) {
178 use std::collections::BTreeMap;
179
180 let pack_path = pack_dir.join("script.pack");
181
182 let mut id_to_name: BTreeMap<i32, String> = BTreeMap::new();
184 let mut name_to_id: std::collections::HashMap<String, i32> = std::collections::HashMap::new();
185 let mut max_id: i32 = 0;
186
187 if let Ok(text) = fs::read_to_string(&pack_path) {
188 for line in text.lines() {
189 let line = line.trim();
190 if line.is_empty() {
191 continue;
192 }
193 if let Some((id_str, name)) = line.split_once('=')
194 && let Ok(id) = id_str.parse::<i32>()
195 {
196 let name = name.trim().to_string();
197 name_to_id.insert(name.clone(), id);
198 id_to_name.insert(id, name);
199 if id >= max_id {
200 max_id = id + 1;
201 }
202 }
203 }
204 }
205
206 let mut rs2_files = Vec::new();
208 collect_rs2_files(scripts_dir, &mut rs2_files);
209 rs2_files.sort();
210
211 for path in &rs2_files {
212 if path.file_name().and_then(|n| n.to_str()) == Some("engine.rs2") {
214 continue;
215 }
216 let fallback;
220 let text: &str = if let Some(rc) = sources.get(path) {
221 rc
222 } else {
223 fallback = match fs::read_to_string(path) {
224 Ok(t) => t,
225 Err(_) => continue,
226 };
227 &fallback
228 };
229 for line in text.lines() {
230 let line = line.split("//").next().unwrap_or("").trim();
231 if !line.starts_with('[') {
232 continue;
233 }
234 let bracket_end = match line.find(']') {
235 Some(i) => i,
236 None => continue,
237 };
238 let full_name = &line[..bracket_end + 1]; let inner = &line[1..bracket_end];
240 let comma = match inner.find(',') {
241 Some(i) => i,
242 None => continue,
243 };
244 let trigger = &inner[..comma];
245 if trigger == "command" {
247 continue;
248 }
249
250 if !name_to_id.contains_key(full_name) {
251 name_to_id.insert(full_name.to_string(), max_id);
252 id_to_name.insert(max_id, full_name.to_string());
253 max_id += 1;
254 }
255 }
256 }
257
258 if let Err(e) = std::fs::create_dir_all(pack_dir) {
260 warn!(target: "runec", "Failed to create pack dir: {}", e);
261 return;
262 }
263 let mut out = String::new();
264 for (id, name) in &id_to_name {
265 out.push_str(&format!("{}={}\n", id, name));
266 }
267 if let Err(e) = fs::write(&pack_path, &out) {
268 warn!(target: "runec", "Failed to write script.pack: {}", e);
269 } else {
270 info!(target: "runec", "script.pack: {} entries", id_to_name.len());
271 }
272}
273
274fn collect_rs2_files(dir: &Path, out: &mut Vec<std::path::PathBuf>) {
275 let Ok(entries) = fs::read_dir(dir) else {
276 return;
277 };
278 let mut sorted: Vec<(std::path::PathBuf, bool)> = entries
282 .flatten()
283 .map(|e| {
284 let p = e.path();
285 let is_dir = entry_is_dir(&e, &p);
286 (p, is_dir)
287 })
288 .collect();
289 sorted.sort_by(|a, b| a.0.cmp(&b.0));
290 for (path, is_dir) in sorted {
291 if is_dir {
292 collect_rs2_files(&path, out);
293 } else if path.extension().and_then(|e| e.to_str()) == Some("rs2") {
294 out.push(path);
295 }
296 }
297}
298
299pub fn load_packs(registry: &mut SymbolRegistry, pack_dir: &Path) {
304 if !pack_dir.exists() {
305 return;
306 }
307
308 register_engine_constants(registry);
311
312 load_commands(registry, &pack_dir.join("command.pack"));
313
314 load_game_vars(registry, &pack_dir.join("varp.pack"), "varp");
315 load_game_vars(registry, &pack_dir.join("varn.pack"), "varn");
316 load_game_vars(registry, &pack_dir.join("vars.pack"), "vars");
317 load_game_vars(registry, &pack_dir.join("varbit.pack"), "varbit");
318
319 for (file, type_hint) in &[
334 ("category.pack", Type::Category),
336 ("idk.pack", Type::IdKit),
338 ("interface.pack", Type::Interface), ("overlayinterface.pack", Type::OverlayInterface),
340 ("struct.pack", Type::Struct),
342 ("dbrow.pack", Type::DbRow),
343 ("dbtable.pack", Type::DbTable),
344 ("dbcolumn.pack", Type::DbColumn),
345 ("param.pack", Type::Param),
346 ("model.pack", Type::Model),
348 ("fontmetrics.pack", Type::FontMetrics),
349 ("mesanim.pack", Type::MesAnim),
350 ("jingle.pack", Type::Jingle),
351 ("midi.pack", Type::Midi),
352 ("synth.pack", Type::Synth),
353 ("spotanim.pack", Type::Spotanim),
354 ("seq.pack", Type::Seq),
355 ("locshape.pack", Type::LocShape),
357 ("hunt.pack", Type::Hunt),
358 ("npc_mode.pack", Type::NpcMode),
359 ("enum.pack", Type::Enum),
360 ("writeinv.pack", Type::WriteinvObj),
361 ("inv.pack", Type::Inv),
362 ("loc.pack", Type::Loc),
363 ("npc_stat.pack", Type::NpcStat),
364 ("stat.pack", Type::Stat),
365 ("npc.pack", Type::Npc),
366 ("obj.pack", Type::Obj),
367 ("controller.pack", Type::Controller),
368 ] {
369 load_entity_ids(registry, &pack_dir.join(file), *type_hint);
370 }
371
372 load_entity_ids_typed_only(registry, &pack_dir.join("obj.pack"), Type::NamedObj);
376
377 register_type_chars(registry);
379}
380
381pub fn load_script_ids(registry: &mut SymbolRegistry, pack_dir: &Path) {
386 load_script_pack(registry, &pack_dir.join("script.pack"));
388
389 load_clientscript_pack(registry, &pack_dir.join("clientscript.pack"));
393}
394
395fn load_clientscript_pack(registry: &mut SymbolRegistry, path: &Path) {
399 let text = match fs::read_to_string(path) {
400 Ok(t) => t,
401 Err(_) => return,
402 };
403 for line in text.lines() {
404 let line = line.trim();
405 if line.is_empty() {
406 continue;
407 }
408 let (id_str, rest) = match line.split_once('=') {
409 Some(pair) => pair,
410 None => continue,
411 };
412 let id: i32 = match id_str.parse() {
413 Ok(v) => v,
414 Err(_) => continue,
415 };
416 let rest = rest.trim();
417 if !rest.starts_with('[') || !rest.ends_with(']') {
418 continue;
419 }
420 let inner = &rest[1..rest.len() - 1];
421 let (_trigger, name) = match inner.split_once(',') {
422 Some(pair) => pair,
423 None => continue,
424 };
425 if name.is_empty() {
426 continue;
427 }
428 registry.script_ids.insert(name.to_string(), id);
429 registry
430 .trigger_script_ids
431 .insert(format!("clientscript:{}", name), id);
432 }
433}
434
435fn load_commands(registry: &mut SymbolRegistry, path: &Path) {
442 let text = match fs::read_to_string(path) {
443 Ok(t) => t,
444 Err(_) => return,
445 };
446 for line in text.lines() {
447 let line = line.trim();
448 if line.is_empty() {
449 continue;
450 }
451 let (id_str, name) = match line.split_once('=') {
452 Some(pair) => pair,
453 None => continue,
454 };
455 let opcode: i32 = match id_str.parse() {
456 Ok(v) => v,
457 Err(_) => continue,
458 };
459 let name = name.trim().to_string();
460 if name.is_empty() {
461 continue;
462 }
463 registry.register_command(name, opcode, Vec::new(), Vec::new());
464 }
465}
466
467fn load_game_vars(registry: &mut SymbolRegistry, path: &Path, category: &str) {
468 let text = match fs::read_to_string(path) {
469 Ok(t) => t,
470 Err(_) => return,
471 };
472 for line in text.lines() {
473 let line = line.trim();
474 if line.is_empty() {
475 continue;
476 }
477 let (id_str, name) = match line.split_once('=') {
478 Some(pair) => pair,
479 None => continue,
480 };
481 let idx: i32 = match id_str.parse() {
482 Ok(v) => v,
483 Err(_) => continue,
484 };
485 let name = name.trim().to_string();
486 if name.is_empty() {
487 continue;
488 }
489 registry.register_game_var(format!(".{}", name), Type::Int, idx, category.to_string());
493 registry.register_game_var(name, Type::Int, idx, category.to_string());
494 }
495}
496
497pub fn load_dbtable_configs(
510 registry: &mut SymbolRegistry,
511 files: &[std::path::PathBuf],
512 dbtable_ids: &std::collections::HashMap<String, u16>,
513) {
514 let mut dbtable_files: Vec<&std::path::PathBuf> = files
515 .iter()
516 .filter(|p| p.extension().and_then(|e| e.to_str()) == Some("dbtable"))
517 .collect();
518 dbtable_files.sort();
519
520 for path in dbtable_files {
521 let Ok(text) = fs::read_to_string(path) else {
522 continue;
523 };
524 let lines = strip_comments(&text);
525
526 let mut current_table: Option<String> = None;
527 let mut col_idx: u16 = 0;
528 for line in &lines {
529 if line.starts_with('[') && line.ends_with(']') {
531 let name = line[1..line.len() - 1].trim().to_string();
532 current_table = Some(name);
533 col_idx = 0;
534 continue;
535 }
536 let Some(rest) = line.strip_prefix("column=") else {
538 continue;
539 };
540 let Some(table_name) = current_table.as_deref() else {
541 continue;
542 };
543 let Some(&table_id) = dbtable_ids.get(table_name) else {
544 continue;
545 };
546
547 let parts: Vec<&str> = rest.split(',').map(str::trim).collect();
548 if parts.is_empty() {
549 continue;
550 }
551 let col_name = parts[0];
552 if col_name.is_empty() {
553 continue;
554 }
555
556 let types: Vec<Type> = parts[1..]
558 .iter()
559 .filter(|s| !matches!(**s, "INDEXED" | "REQUIRED"))
560 .filter_map(|s| Type::from_name(s))
561 .collect();
562
563 let compound = format!("{}:{}", table_name, col_name);
564 let packed = ((table_id as i32) << 12) | ((col_idx as i32) << 4);
565
566 registry.register_entity_id(compound.clone(), Type::DbColumn, packed);
568
569 if types.len() > 1 {
571 for (i, _) in types.iter().enumerate() {
572 let slot_compound = format!("{}:{}:{}", table_name, col_name, i);
573 let slot_packed = packed | (((i as i32) + 1) & 0xF);
574 registry.register_entity_id(slot_compound, Type::DbColumn, slot_packed);
575 }
576 }
577
578 if let Some(first_type) = types.first().copied() {
580 registry.dbcolumn_types.insert(compound, first_type);
581 }
582
583 col_idx += 1;
584 }
585 }
586}
587
588pub fn load_dbtable_pack(path: &Path) -> std::collections::HashMap<String, u16> {
590 let mut out = std::collections::HashMap::new();
591 let Ok(text) = fs::read_to_string(path) else {
592 return out;
593 };
594 for line in text.lines() {
595 let line = line.trim();
596 if line.is_empty() {
597 continue;
598 }
599 let Some((id_str, name)) = line.split_once('=') else {
600 continue;
601 };
602 let Ok(id) = id_str.parse::<u16>() else {
603 continue;
604 };
605 let name = name.trim();
606 if name.is_empty() {
607 continue;
608 }
609 out.insert(name.to_string(), id);
610 }
611 out
612}
613
614pub fn load_constant_files(registry: &mut SymbolRegistry, files: &[std::path::PathBuf]) {
619 let mut constant_files: Vec<&std::path::PathBuf> = files
620 .iter()
621 .filter(|p| p.extension().and_then(|e| e.to_str()) == Some("constant"))
622 .collect();
623 constant_files.sort();
624
625 for path in constant_files {
626 let text = match fs::read_to_string(path) {
627 Ok(t) => t,
628 Err(_) => continue,
629 };
630 let lines = strip_comments(&text);
631 for line in &lines {
632 let eq_pos = match line.find('=') {
634 Some(i) => i,
635 None => continue,
636 };
637 let mut name = line[..eq_pos].trim();
638 let value = line[eq_pos + 1..].trim();
639
640 if let Some(stripped) = name.strip_prefix('^') {
642 name = stripped;
643 }
644
645 if name.is_empty() {
646 continue;
647 }
648
649 let val_str = if value.starts_with('"') && value.ends_with('"') && value.len() >= 2 {
651 &value[1..value.len() - 1]
652 } else {
653 value
654 };
655
656 register_constant_value(registry, name.to_string(), val_str);
657 }
658 }
659}
660
661fn register_constant_value(registry: &mut SymbolRegistry, name: String, val_str: &str) {
663 if let Ok(i) = val_str.parse::<i32>() {
664 registry.register_constant(name, Type::Int, Some(i), None);
665 } else if let Some(hex_str) = val_str
666 .strip_prefix("0x")
667 .or_else(|| val_str.strip_prefix("0X"))
668 {
669 let v = u32::from_str_radix(hex_str, 16).unwrap_or(0) as i32;
670 registry.register_constant(name, Type::Int, Some(v), None);
671 } else if let Some(packed) = parse_coord_string(val_str) {
672 registry.register_constant(name, Type::Coord, Some(packed), None);
673 } else {
674 registry.register_constant(name, Type::String, None, Some(val_str.to_string()));
675 }
676}
677
678fn strip_comments(text: &str) -> Vec<String> {
681 let mut result = Vec::new();
682 let mut multi_depth: usize = 0;
683
684 for line in text.lines() {
685 let mut line = line.trim().to_string();
686
687 if multi_depth > 0 {
689 while let Some(start) = line.find("/*") {
690 line = line[start + 2..].trim_start().to_string();
691 multi_depth += 1;
692 }
693 while let Some(end) = line.find("*/") {
694 line = line[end + 2..].trim_start().to_string();
695 multi_depth -= 1;
696 if multi_depth == 0 {
697 break;
698 }
699 }
700 if multi_depth > 0 {
701 continue;
702 }
703 }
704
705 if line.is_empty() {
706 continue;
707 }
708
709 if let Some(idx) = line.find("//") {
711 line = line[..idx].trim_end().to_string();
712 if line.is_empty() {
713 continue;
714 }
715 }
716
717 if let Some(start) = line.find("/*") {
719 if let Some(end) = line.find("*/") {
720 line = format!("{}{}", &line[..start], &line[end + 2..]);
721 } else {
722 line = line[..start].to_string();
723 multi_depth += 1;
724 }
725 if line.is_empty() {
726 continue;
727 }
728 }
729
730 result.push(line);
731 }
732
733 result
734}
735
736pub fn load_game_var_types(registry: &mut SymbolRegistry, files: &[std::path::PathBuf]) {
741 let mut next_auto_id: std::collections::HashMap<String, i32> = std::collections::HashMap::new();
743 for ext in &["varp", "varn", "vars", "varbit"] {
744 let max_id = registry
746 .game_vars
747 .values()
748 .filter_map(|sym| {
749 if let crate::symbol::SymbolKind::GameVar {
750 var_id, category, ..
751 } = &sym.kind
752 {
753 if category == *ext {
754 Some(*var_id)
755 } else {
756 None
757 }
758 } else {
759 None
760 }
761 })
762 .max()
763 .unwrap_or(-1);
764 next_auto_id.insert(ext.to_string(), max_id + 1);
765 }
766
767 for ext in &["varp", "varn", "vars", "varbit"] {
768 let ext_files = files
769 .iter()
770 .filter(|p| p.extension().and_then(|e| e.to_str()) == Some(*ext));
771 for path in ext_files {
772 let Ok(text) = fs::read_to_string(path) else {
773 continue;
774 };
775 let mut current_name: Option<String> = None;
776 for line in text.lines() {
777 let line = line.trim();
778 if line.is_empty() || line.starts_with("//") {
779 continue;
780 }
781 if let Some(inner) = line.strip_prefix('[').and_then(|s| s.strip_suffix(']')) {
782 let name = inner.trim().to_string();
783 if !registry.game_vars.contains_key(&name) {
785 let id = next_auto_id.get_mut(*ext).unwrap();
786 let auto_id = *id;
787 *id += 1;
788 registry.register_game_var(
789 name.clone(),
790 Type::Int,
791 auto_id,
792 ext.to_string(),
793 );
794 registry.register_game_var(
795 format!(".{}", name),
796 Type::Int,
797 auto_id,
798 ext.to_string(),
799 );
800 }
801 current_name = Some(name);
802 continue;
803 }
804 let Some(name) = current_name.as_ref() else {
805 continue;
806 };
807 if let Some((k, v)) = line.split_once('=')
808 && k.trim() == "type"
809 {
810 let type_name = v.trim();
811 if let Some(ty) = Type::from_name(type_name) {
812 if let Some(sym) = registry.game_vars.get_mut(name)
813 && let crate::symbol::SymbolKind::GameVar { var_type, .. } =
814 &mut sym.kind
815 {
816 *var_type = ty;
817 }
818 let dot_name = format!(".{}", name);
819 if let Some(sym) = registry.game_vars.get_mut(&dot_name)
820 && let crate::symbol::SymbolKind::GameVar { var_type, .. } =
821 &mut sym.kind
822 {
823 *var_type = ty;
824 }
825 }
826 }
827 }
828 }
829 }
830}
831
832pub(crate) fn entry_is_dir(entry: &fs::DirEntry, path: &Path) -> bool {
840 match entry.file_type() {
841 Ok(ft) if !ft.is_symlink() => ft.is_dir(),
842 _ => path.is_dir(),
843 }
844}
845
846pub fn collect_all_files(dir: &Path, out: &mut Vec<std::path::PathBuf>) {
859 let entries = match fs::read_dir(dir) {
860 Ok(e) => e,
861 Err(_) => return,
862 };
863 for entry in entries.flatten() {
864 let path = entry.path();
865 if entry_is_dir(&entry, &path) {
866 collect_all_files(&path, out);
867 } else {
868 out.push(path);
869 }
870 }
871}
872
873fn parse_coord_string(s: &str) -> Option<i32> {
876 let parts: Vec<&str> = s.split('_').collect();
877 if parts.len() != 5 {
878 return None;
879 }
880 let y: i32 = parts[0].parse().ok()?;
881 let bx: i32 = parts[1].parse().ok()?;
882 let bz: i32 = parts[2].parse().ok()?;
883 let lx: i32 = parts[3].parse().ok()?;
884 let lz: i32 = parts[4].parse().ok()?;
885 let x = bx * 64 + lx;
886 let z = bz * 64 + lz;
887 Some((y << 28) | (x << 14) | z)
888}
889
890fn load_entity_ids(registry: &mut SymbolRegistry, path: &Path, entity_type: Type) {
904 let text = match fs::read_to_string(path) {
905 Ok(t) => t,
906 Err(_) => return,
907 };
908
909 let is_interface_pack = entity_type == Type::Interface;
910
911 let mut iface_id_to_name: std::collections::HashMap<i32, String> =
914 std::collections::HashMap::new();
915
916 for line in text.lines() {
917 let line = line.trim();
918 if line.is_empty() {
919 continue;
920 }
921 let (id_str, name) = match line.split_once('=') {
922 Some(pair) => pair,
923 None => continue,
924 };
925 let name = name.trim();
926 if name.is_empty() || name == "null" {
927 continue;
928 }
929
930 if is_interface_pack
931 && !id_str.contains(':')
932 && !name.contains(':')
933 && let Ok(id) = id_str.parse::<i32>()
934 {
935 registry.interface_ids.insert(name.to_string(), id);
936 iface_id_to_name.insert(id, name.to_string());
937 }
938 }
939
940 for line in text.lines() {
942 let line = line.trim();
943 if line.is_empty() {
944 continue;
945 }
946 let (id_str, name) = match line.split_once('=') {
947 Some(pair) => pair,
948 None => continue,
949 };
950 let name = name.trim();
951 if name.is_empty() || name == "null" {
952 continue;
953 }
954
955 let (idx, component_key, register_name): (i32, Option<String>, String) =
958 if let Some((iface_str, comp_str)) = id_str.split_once(':') {
959 let iface: i32 = match iface_str.parse() {
961 Ok(v) => v,
962 Err(_) => continue,
963 };
964 let comp: i32 = match comp_str.parse() {
965 Ok(v) => v,
966 Err(_) => continue,
967 };
968 let packed = (iface << 16) | comp;
969 let key = iface_id_to_name
970 .get(&iface)
971 .map(|iface_name| format!("{}:{}", iface_name, name));
972 (packed, key, name.to_string())
973 } else if is_interface_pack {
974 let flat_id: i32 = match id_str.parse() {
975 Ok(v) => v,
976 Err(_) => continue,
977 };
978 if name.contains(':') {
979 (flat_id, Some(name.to_string()), name.to_string())
981 } else {
982 (flat_id, None, name.to_string())
984 }
985 } else {
986 let id: i32 = match id_str.parse() {
988 Ok(v) => v,
989 Err(_) => continue,
990 };
991 (id, None, name.to_string())
992 };
993
994 let actual_type = if is_interface_pack && component_key.is_some() {
997 Type::Component
998 } else {
999 entity_type
1000 };
1001
1002 let normalized = register_name.to_lowercase().replace(' ', "_");
1005 registry.register_entity_id(normalized, actual_type, idx);
1006
1007 if is_interface_pack && let Some(key) = component_key {
1008 let normalized_key = if let Some((iface_part, comp_part)) = key.split_once(':') {
1009 format!(
1010 "{}:{}",
1011 iface_part,
1012 crate::symbol::normalize_comp_name(comp_part)
1013 )
1014 } else {
1015 key
1016 };
1017 registry.components.insert(normalized_key, idx);
1018 }
1019 }
1020}
1021
1022fn load_entity_ids_typed_only(registry: &mut SymbolRegistry, path: &Path, entity_type: Type) {
1026 let text = match fs::read_to_string(path) {
1027 Ok(t) => t,
1028 Err(_) => return,
1029 };
1030 for line in text.lines() {
1031 let line = line.trim();
1032 if line.is_empty() {
1033 continue;
1034 }
1035 let (id_str, name) = match line.split_once('=') {
1036 Some(pair) => pair,
1037 None => continue,
1038 };
1039 let name = name.trim();
1040 if name.is_empty() || name == "null" {
1041 continue;
1042 }
1043 let id: i32 = match id_str.parse() {
1044 Ok(v) => v,
1045 Err(_) => continue,
1046 };
1047 let normalized = name.to_lowercase().replace(' ', "_");
1048 registry.register_entity_id_typed_only(normalized, entity_type, id);
1049 }
1050}
1051
1052fn register_type_chars(registry: &mut SymbolRegistry) {
1056 let type_chars: &[(&str, i32)] = &[
1057 ("int", b'i' as i32), ("string", b's' as i32), ("boolean", b'1' as i32), ("bool", b'1' as i32),
1061 ("coord", b'c' as i32), ("loc", b'l' as i32), ("npc", b'n' as i32), ("obj", b'o' as i32), ("namedobj", b'O' as i32), ("playeruid", b'p' as i32), ("player_uid", b'p' as i32),
1068 ("npcuid", b'u' as i32), ("npc_uid", b'u' as i32),
1070 ("seq", b'A' as i32), ("spotanim", b't' as i32), ("synth", b'P' as i32), ("stat", b'S' as i32), ("component", b'I' as i32), ("interface", b'a' as i32), ("toplevelinterface", b'a' as i32),
1077 ("overlayinterface", b'a' as i32),
1078 ("inv", b'v' as i32), ("enum", b'g' as i32), ("struct", b'J' as i32), ("dbrow", 0xD0), ("dbtable", b'i' as i32), ("dbcolumn", b'i' as i32),
1084 ("category", b'y' as i32), ("varp", b'V' as i32), ("npc_stat", 0xFE), ("npcstat", 0xFE),
1088 ("idkit", b'K' as i32), ("idk", b'K' as i32),
1090 ];
1091 for (name, val) in type_chars {
1092 registry.type_chars.insert(name.to_string(), *val);
1093 }
1094}
1095
1096fn register_engine_constants(registry: &mut SymbolRegistry) {
1100 let npc_modes: &[(&str, i32)] = &[
1102 ("null", -1),
1103 ("none", 0),
1104 ("wander", 1),
1105 ("patrol", 2),
1106 ("playerescape", 3),
1107 ("playerfollow", 4),
1108 ("playerface", 5),
1109 ("playerfaceclose", 6),
1110 ("opplayer1", 7),
1111 ("opplayer2", 8),
1112 ("opplayer3", 9),
1113 ("opplayer4", 10),
1114 ("opplayer5", 11),
1115 ("applayer1", 12),
1116 ("applayer2", 13),
1117 ("applayer3", 14),
1118 ("applayer4", 15),
1119 ("applayer5", 16),
1120 ("oploc1", 17),
1121 ("oploc2", 18),
1122 ("oploc3", 19),
1123 ("oploc4", 20),
1124 ("oploc5", 21),
1125 ("aploc1", 22),
1126 ("aploc2", 23),
1127 ("aploc3", 24),
1128 ("aploc4", 25),
1129 ("aploc5", 26),
1130 ("opobj1", 27),
1131 ("opobj2", 28),
1132 ("opobj3", 29),
1133 ("opobj4", 30),
1134 ("opobj5", 31),
1135 ("apobj1", 32),
1136 ("apobj2", 33),
1137 ("apobj3", 34),
1138 ("apobj4", 35),
1139 ("apobj5", 36),
1140 ("opnpc1", 37),
1141 ("opnpc2", 38),
1142 ("opnpc3", 39),
1143 ("opnpc4", 40),
1144 ("opnpc5", 41),
1145 ("apnpc1", 42),
1146 ("apnpc2", 43),
1147 ("apnpc3", 44),
1148 ("apnpc4", 45),
1149 ("apnpc5", 46),
1150 ("queue1", 47),
1151 ("queue2", 48),
1152 ("queue3", 49),
1153 ("queue4", 50),
1154 ("queue5", 51),
1155 ("queue6", 52),
1156 ("queue7", 53),
1157 ("queue8", 54),
1158 ("queue9", 55),
1159 ("queue10", 56),
1160 ("queue11", 57),
1161 ("queue12", 58),
1162 ("queue13", 59),
1163 ("queue14", 60),
1164 ("queue15", 61),
1165 ("queue16", 62),
1166 ("queue17", 63),
1167 ("queue18", 64),
1168 ("queue19", 65),
1169 ("queue20", 66),
1170 ];
1171 fn is_trigger_collision(name: &str) -> bool {
1182 matches!(
1183 name,
1184 "oploc1"
1185 | "oploc2"
1186 | "oploc3"
1187 | "oploc4"
1188 | "oploc5"
1189 | "aploc1"
1190 | "aploc2"
1191 | "aploc3"
1192 | "aploc4"
1193 | "aploc5"
1194 | "opnpc1"
1195 | "opnpc2"
1196 | "opnpc3"
1197 | "opnpc4"
1198 | "opnpc5"
1199 | "apnpc1"
1200 | "apnpc2"
1201 | "apnpc3"
1202 | "apnpc4"
1203 | "apnpc5"
1204 | "opobj1"
1205 | "opobj2"
1206 | "opobj3"
1207 | "opobj4"
1208 | "opobj5"
1209 | "apobj1"
1210 | "apobj2"
1211 | "apobj3"
1212 | "apobj4"
1213 | "apobj5"
1214 | "opplayer1"
1215 | "opplayer2"
1216 | "opplayer3"
1217 | "opplayer4"
1218 | "opplayer5"
1219 | "applayer1"
1220 | "applayer2"
1221 | "applayer3"
1222 | "applayer4"
1223 | "applayer5"
1224 | "queue1"
1225 | "queue2"
1226 | "queue3"
1227 | "queue4"
1228 | "queue5"
1229 | "queue6"
1230 | "queue7"
1231 | "queue8"
1232 | "queue9"
1233 | "queue10"
1234 | "queue11"
1235 | "queue12"
1236 | "queue13"
1237 | "queue14"
1238 | "queue15"
1239 | "queue16"
1240 | "queue17"
1241 | "queue18"
1242 | "queue19"
1243 | "queue20"
1244 )
1245 }
1246 for &(name, id) in npc_modes {
1247 if is_trigger_collision(name) {
1248 registry.register_entity_id_typed_only(name.to_string(), Type::NpcMode, id);
1249 } else {
1250 registry.register_entity_id(name.to_string(), Type::NpcMode, id);
1251 }
1252 }
1253
1254 let npc_stats: &[(&str, i32)] = &[
1256 ("attack", 0),
1257 ("defence", 1),
1258 ("strength", 2),
1259 ("hitpoints", 3),
1260 ("ranged", 4),
1261 ("magic", 5),
1262 ];
1263 for &(name, id) in npc_stats {
1264 registry.register_entity_id(name.to_string(), Type::NpcStat, id);
1265 }
1266
1267 let stats: &[(&str, i32)] = &[
1270 ("attack", 0),
1271 ("defence", 1),
1272 ("strength", 2),
1273 ("hitpoints", 3),
1274 ("ranged", 4),
1275 ("prayer", 5),
1276 ("magic", 6),
1277 ("cooking", 7),
1278 ("woodcutting", 8),
1279 ("fletching", 9),
1280 ("fishing", 10),
1281 ("firemaking", 11),
1282 ("crafting", 12),
1283 ("smithing", 13),
1284 ("mining", 14),
1285 ("herblore", 15),
1286 ("agility", 16),
1287 ("thieving", 17),
1288 ("slayer", 18),
1289 ("stat18", 18),
1290 ("farming", 19),
1291 ("stat19", 19),
1292 ("runecraft", 20),
1293 ("hunter", 21),
1294 ("construction", 22),
1295 ("summoning", 23),
1296 ("dungeoneering", 24),
1297 ];
1298 for &(name, id) in stats {
1299 registry.register_entity_id(name.to_string(), Type::Stat, id);
1300 }
1301
1302 let fontmetrics: &[(&str, i32)] = &[
1304 ("p11", 0),
1305 ("p12", 1),
1306 ("b12", 2),
1307 ("q8", 3),
1308 ("p11_full", 0),
1309 ("p12_full", 1),
1310 ("b12_full", 2),
1311 ("q8_full", 3),
1312 ];
1313 for &(name, id) in fontmetrics {
1314 registry.register_entity_id(name.to_string(), Type::FontMetrics, id);
1315 }
1316
1317 let locshapes: &[(&str, i32)] = &[
1319 ("wall_straight", 0),
1320 ("wall_diagonalcorner", 1),
1321 ("wall_l", 2),
1322 ("wall_squarecorner", 3),
1323 ("walldecor_straight_nooffset", 4),
1324 ("walldecor_straight_offset", 5),
1325 ("walldecor_diagonal_offset", 6),
1326 ("walldecor_diagonal_nooffset", 7),
1327 ("walldecor_diagonal_both", 8),
1328 ("wall_diagonal", 9),
1329 ("centrepiece_straight", 10),
1330 ("centrepiece_diagonal", 11),
1331 ("roof_straight", 12),
1332 ("roof_diagonal_with_roofedge", 13),
1333 ("roof_diagonal", 14),
1334 ("roof_l_concave", 15),
1335 ("roof_l_convex", 16),
1336 ("roof_flat", 17),
1337 ("roofedge_straight", 18),
1338 ("roofedge_diagonalcorner", 19),
1339 ("roofedge_l", 20),
1340 ("roofedge_squarecorner", 21),
1341 ("grounddecor", 22),
1342 ];
1343 for &(name, id) in locshapes {
1344 registry.register_entity_id(name.to_string(), Type::LocShape, id);
1345 }
1346}
1347
1348#[cfg(test)]
1349mod tests {
1350 use super::*;
1351 use crate::symbol::SymbolRegistry;
1352 use crate::types::Type;
1353 use std::io::Write;
1354 use std::path::PathBuf;
1355
1356 fn write_temp_pack(name: &str, content: &str) -> PathBuf {
1357 let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1358 .join("target")
1359 .join("test-symloader");
1360 fs::create_dir_all(&dir).unwrap();
1361 let path = dir.join(name);
1362 let mut f = fs::File::create(&path).unwrap();
1363 f.write_all(content.as_bytes()).unwrap();
1364 path
1365 }
1366
1367 #[test]
1371 fn load_647_style_registers_components() {
1372 let pack = write_temp_pack(
1373 "interface_647.pack",
1374 "\
1375228=multi2\n\
1376228:0=com0\n\
1377228:1=com1\n\
1378228:2=com2\n\
1379228:3=com3\n\
1380228:6=thin_swords\n\
1381228:9=wide_swords\n",
1382 );
1383 let mut r = SymbolRegistry::new();
1384 load_entity_ids(&mut r, &pack, Type::Interface);
1385
1386 assert_eq!(r.interface_ids.get("multi2"), Some(&228));
1388
1389 assert_eq!(r.lookup_component("multi2", "com0"), Some(228 << 16));
1391 assert_eq!(r.lookup_component("multi2", "com2"), Some((228 << 16) | 2));
1392 assert_eq!(r.lookup_component("multi2", "com3"), Some((228 << 16) | 3));
1393
1394 assert_eq!(
1396 r.lookup_component("multi2", "thin_swords"),
1397 Some((228 << 16) | 6)
1398 );
1399 assert_eq!(
1400 r.lookup_component("multi2", "wide_swords"),
1401 Some((228 << 16) | 9)
1402 );
1403 }
1404
1405 #[test]
1406 fn load_647_style_resolves_225_references() {
1407 let pack = write_temp_pack(
1408 "interface_647_cross.pack",
1409 "\
1410228=multi2\n\
1411228:0=com0\n\
1412228:1=com1\n\
1413228:2=com2\n",
1414 );
1415 let mut r = SymbolRegistry::new();
1416 load_entity_ids(&mut r, &pack, Type::Interface);
1417
1418 assert_eq!(r.lookup_component("multi2", "com_0"), Some(228 << 16));
1420 assert_eq!(r.lookup_component("multi2", "com_1"), Some((228 << 16) | 1));
1421 assert_eq!(r.lookup_component("multi2", "com_2"), Some((228 << 16) | 2));
1422 }
1423
1424 #[test]
1428 fn load_225_style_registers_components() {
1429 let pack = write_temp_pack(
1430 "interface_225.pack",
1431 "\
14322459=multi2\n\
14332460=multi2:com_0\n\
14342461=multi2:com_1\n\
14352462=multi2:com_2\n\
14362463=multi2:com_4\n\
14372464=multi2:com_5\n",
1438 );
1439 let mut r = SymbolRegistry::new();
1440 load_entity_ids(&mut r, &pack, Type::Interface);
1441
1442 assert_eq!(r.interface_ids.get("multi2"), Some(&2459));
1444
1445 assert_eq!(r.lookup_component("multi2", "com_0"), Some(2460));
1447 assert_eq!(r.lookup_component("multi2", "com_2"), Some(2462));
1448 assert_eq!(r.lookup_component("multi2", "com_5"), Some(2464));
1449 }
1450
1451 #[test]
1452 fn load_225_style_resolves_647_references() {
1453 let pack = write_temp_pack(
1454 "interface_225_cross.pack",
1455 "\
14562459=multi2\n\
14572460=multi2:com_0\n\
14582461=multi2:com_1\n\
14592462=multi2:com_2\n",
1460 );
1461 let mut r = SymbolRegistry::new();
1462 load_entity_ids(&mut r, &pack, Type::Interface);
1463
1464 assert_eq!(r.lookup_component("multi2", "com0"), Some(2460));
1466 assert_eq!(r.lookup_component("multi2", "com1"), Some(2461));
1467 assert_eq!(r.lookup_component("multi2", "com2"), Some(2462));
1468 }
1469
1470 #[test]
1473 fn components_register_as_component_type() {
1474 let pack = write_temp_pack(
1475 "interface_types.pack",
1476 "\
1477228=multi2\n\
1478228:0=com0\n",
1479 );
1480 let mut r = SymbolRegistry::new();
1481 load_entity_ids(&mut r, &pack, Type::Interface);
1482
1483 assert!(
1485 r.lookup_entity_id_typed("multi2", Type::Interface)
1486 .is_some()
1487 );
1488 assert!(r.lookup_entity_id_typed("com0", Type::Component).is_some());
1489 assert!(r.lookup_entity_id_typed("com0", Type::Interface).is_none());
1490 }
1491}