use std::collections::HashMap;
use std::fs;
use std::io;
use std::path::Path;
use crate::bytecode::{CompiledScript, Opcode, Operand};
use crate::types::Type;
const COMPILER_VERSION: i32 = 27;
fn is_large_operand(opcode: u16) -> bool {
if opcode > 100 {
return false;
}
match opcode {
21 | 22 | 23 | 38 | 39 => false, _ => true,
}
}
fn type_to_char(t: Type) -> u8 {
match t {
Type::Int => b'i',
Type::String => b's',
Type::Boolean => b'1',
Type::Coord => b'c',
Type::Loc => b'l',
Type::Npc => b'n',
Type::Obj => b'o',
Type::NamedObj => b'O',
Type::PlayerUid => b'p',
Type::NpcUid => b'u',
Type::Seq => b'A',
Type::Spotanim => b't',
Type::Synth => b'P',
Type::Stat => b'S',
Type::Component => b'I',
Type::Interface | Type::TopLevelInterface | Type::OverlayInterface => b'a',
Type::Inv => b'v',
Type::Enum => b'g',
Type::Struct => b'J',
Type::DbRow => 0xD0, Type::Category => b'y',
Type::Varp => b'V',
Type::NpcStat => 0xFE, Type::IdKit => b'K',
_ => b'i', }
}
fn encode_rs2_string(s: &str) -> Vec<u8> {
let mut out = Vec::with_capacity(s.len());
for ch in s.chars() {
let cp = ch as u32;
if cp < 0x80 {
out.push(cp as u8);
} else if cp < 0x100 {
out.push(cp as u8);
} else if (0x2010..=0x201F).contains(&cp) {
out.push((cp & 0xFF) as u8);
} else {
out.push((cp & 0xFF) as u8);
}
}
out
}
pub fn encode_script(script: &CompiledScript) -> Vec<u8> {
let mut switch_tables: Vec<Vec<(i32, i32)>> = Vec::new(); enum ResolvedOp {
None,
Small(u8),
Large(i32),
Str(String),
}
struct FlatInstr {
opcode: u16,
op: ResolvedOp,
}
let n = script.instructions.len();
let mut flat: Vec<FlatInstr> = Vec::with_capacity(n);
let mut switch_tbl_idxs: Vec<Option<usize>> = Vec::new(); let mut raw_line_entries: Vec<(usize, i32)> = Vec::new();
for instr in &script.instructions {
let is_command = instr.opcode == Opcode::Command;
let mut cmd_small_operand: u8 = 0;
let eff_opcode: u16 = match instr.opcode {
Opcode::Command => {
match &instr.operand {
Operand::Int(v) => {
cmd_small_operand = ((*v >> 16) & 0xFF) as u8;
(*v & 0xFFFF) as u16
}
Operand::Str(s) => {
let _ = s;
0
}
_ => 0,
}
}
Opcode::LineNumber => {
let line = match &instr.operand {
Operand::Int(v) => *v,
_ => 0,
};
raw_line_entries.push((flat.len(), line));
switch_tbl_idxs.push(None);
flat.push(FlatInstr {
opcode: 0xFFFF,
op: ResolvedOp::None,
}); continue;
}
op => op as u16,
};
if is_command {
switch_tbl_idxs.push(None);
flat.push(FlatInstr {
opcode: eff_opcode,
op: ResolvedOp::Small(cmd_small_operand),
});
continue;
}
let resolved = match &instr.operand {
Operand::None => {
if is_large_operand(eff_opcode) {
ResolvedOp::Large(0)
} else {
ResolvedOp::Small(0)
}
}
Operand::Int(v) => {
if eff_opcode == 3 {
ResolvedOp::Large(*v)
} else if is_large_operand(eff_opcode) {
ResolvedOp::Large(*v)
} else {
ResolvedOp::Small(*v as u8)
}
}
Operand::Long(v) => {
ResolvedOp::Large(*v as i32)
}
Operand::Str(s) => ResolvedOp::Str(s.clone()),
Operand::JumpTarget(target) => {
ResolvedOp::Large(*target as i32) }
Operand::SwitchTable(table) => {
let tbl_idx = switch_tables.len();
let raw: Vec<(i32, i32)> = table
.iter()
.map(|(k, abs_target)| (*k, *abs_target as i32))
.collect();
switch_tables.push(raw);
switch_tbl_idxs.push(Some(tbl_idx));
flat.push(FlatInstr {
opcode: eff_opcode,
op: ResolvedOp::Large(tbl_idx as i32),
});
continue;
}
Operand::StringCount(c) => {
if is_large_operand(eff_opcode) {
ResolvedOp::Large(*c as i32)
} else {
ResolvedOp::Small(*c as u8)
}
}
Operand::ArrayDef(var_id, type_char) => {
let packed = (*var_id << 8) | (*type_char as i32);
if is_large_operand(eff_opcode) {
ResolvedOp::Large(packed)
} else {
ResolvedOp::Small(packed as u8)
}
}
};
switch_tbl_idxs.push(None);
flat.push(FlatInstr {
opcode: eff_opcode,
op: resolved,
});
}
let mut final_instrs: Vec<FlatInstr> = Vec::new();
let mut orig_to_final: Vec<usize> = Vec::new(); for (i, fi) in flat.into_iter().enumerate() {
let _ = i;
if fi.opcode == 0xFFFF {
orig_to_final.push(final_instrs.len()); } else {
orig_to_final.push(final_instrs.len());
final_instrs.push(fi);
}
}
let total = final_instrs.len();
let mut line_table: Vec<(i32, i32)> = Vec::new();
for (flat_idx, line) in &raw_line_entries {
let pc = if *flat_idx < orig_to_final.len() {
orig_to_final[*flat_idx] as i32
} else {
total as i32
};
if let Some(last) = line_table.last_mut() {
if last.0 == pc {
last.1 = *line;
continue;
}
if last.1 == *line {
continue;
}
}
line_table.push((pc, *line));
}
for (i, fi) in final_instrs.iter_mut().enumerate() {
if let ResolvedOp::Large(v) = &fi.op {
let is_branch = matches!(
fi.opcode,
6 | 7 | 8 | 9 | 10 | 31 | 32 | 68 | 69 | 70 | 71 | 72 | 73 | 86 | 87
);
if is_branch {
let abs_target = *v as usize;
let final_target = if abs_target < orig_to_final.len() {
orig_to_final[abs_target]
} else {
total };
let relative = final_target as i32 - (i as i32 + 1);
fi.op = ResolvedOp::Large(relative);
}
}
}
let mut sw_instr_positions: HashMap<usize, usize> = HashMap::new(); {
for (orig_idx, orig_instr) in script.instructions.iter().enumerate() {
if orig_idx >= orig_to_final.len() {
break;
}
if orig_instr.opcode == Opcode::LineNumber {
continue;
}
let final_pos = orig_to_final[orig_idx];
if let Operand::SwitchTable(_) = &orig_instr.operand {
if let Some(tbl_idx) = switch_tbl_idxs.get(orig_idx).and_then(|x| *x) {
sw_instr_positions.insert(tbl_idx, final_pos);
}
}
}
}
let switch_tables_relative: Vec<Vec<(i32, i32)>> = switch_tables
.iter()
.enumerate()
.map(|(tbl_idx, table)| {
let sw_pos = *sw_instr_positions.get(&tbl_idx).unwrap_or(&0);
table
.iter()
.map(|(key, abs_target)| {
let final_target = if (*abs_target as usize) < orig_to_final.len() {
orig_to_final[*abs_target as usize]
} else {
total
};
let rel = final_target as i32 - (sw_pos as i32 + 1);
(*key, rel)
})
.collect()
})
.collect();
let mut buf: Vec<u8> = Vec::new();
buf.extend_from_slice(script.name.as_bytes());
buf.push(0);
buf.extend_from_slice(script.source_path.as_bytes());
buf.push(0);
buf.extend_from_slice(&script.lookup_key.to_be_bytes());
if script.trigger == "debugproc" {
buf.push(script.param_types.len() as u8);
for &pt in &script.param_types {
buf.push(type_to_char(pt));
}
} else {
buf.push(0);
}
buf.extend_from_slice(&(line_table.len() as u16).to_be_bytes());
for (pc, line) in &line_table {
buf.extend_from_slice(&pc.to_be_bytes());
buf.extend_from_slice(&line.to_be_bytes());
}
for fi in &final_instrs {
buf.extend_from_slice(&fi.opcode.to_be_bytes());
match &fi.op {
ResolvedOp::None => {}
ResolvedOp::Small(v) => {
buf.push(*v);
}
ResolvedOp::Large(v) => {
buf.extend_from_slice(&v.to_be_bytes());
}
ResolvedOp::Str(s) => {
buf.extend(encode_rs2_string(s));
buf.push(0); }
}
}
let trailer_start = buf.len();
buf.extend_from_slice(&(final_instrs.len() as i32).to_be_bytes());
buf.extend_from_slice(&script.int_local_count.to_be_bytes());
buf.extend_from_slice(&script.string_local_count.to_be_bytes());
buf.extend_from_slice(&script.int_arg_count.to_be_bytes());
buf.extend_from_slice(&script.string_arg_count.to_be_bytes());
buf.push(switch_tables_relative.len() as u8);
for table in &switch_tables_relative {
buf.extend_from_slice(&(table.len() as u16).to_be_bytes());
for (key, offset) in table {
buf.extend_from_slice(&key.to_be_bytes());
buf.extend_from_slice(&offset.to_be_bytes());
}
}
let switch_section_len = buf.len() - trailer_start - 12; buf.extend_from_slice(&(switch_section_len as u16).to_be_bytes());
buf
}
pub struct ScriptWriter {
output_dir: String,
}
impl ScriptWriter {
pub fn new(output_dir: String) -> Self {
ScriptWriter { output_dir }
}
pub fn write_all(&self, scripts: &[CompiledScript]) -> io::Result<()> {
fs::create_dir_all(&self.output_dir)?;
let max_id = scripts.iter().map(|s| s.id).max().unwrap_or(-1);
let slot_count = if max_id < 0 { 0 } else { (max_id + 1) as usize };
let mut by_id: Vec<Option<&CompiledScript>> = vec![None; slot_count];
for s in scripts {
if s.id >= 0 && (s.id as usize) < slot_count {
by_id[s.id as usize] = Some(s);
}
}
let encoded: Vec<Vec<u8>> = by_id
.iter()
.map(|opt| opt.map(encode_script).unwrap_or_default())
.collect();
let dat_path = Path::new(&self.output_dir).join("script.dat");
{
let mut dat: Vec<u8> = Vec::new();
dat.extend_from_slice(&(slot_count as u32).to_be_bytes());
dat.extend_from_slice(&COMPILER_VERSION.to_be_bytes());
for bytes in &encoded {
dat.extend_from_slice(bytes);
}
fs::write(&dat_path, dat)?;
}
let idx_path = Path::new(&self.output_dir).join("script.idx");
{
let mut idx: Vec<u8> = Vec::new();
idx.extend_from_slice(&(slot_count as u32).to_be_bytes());
for bytes in &encoded {
idx.extend_from_slice(&(bytes.len() as u32).to_be_bytes());
}
fs::write(&idx_path, idx)?;
}
Ok(())
}
}
pub struct PackBuffer {
pub scripts: HashMap<String, Vec<u8>>,
}
impl Default for PackBuffer {
fn default() -> Self {
Self::new()
}
}
impl PackBuffer {
pub fn new() -> Self {
PackBuffer {
scripts: HashMap::new(),
}
}
pub fn add_script(&mut self, script: &CompiledScript) {
let bytes = encode_script(script);
self.scripts.insert(script.name.clone(), bytes);
}
}