tuneutils 0.1.1

Utilities for interfacing with, diagnosing, and tuning cars
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
extern crate serde_yaml;
extern crate byteorder;
extern crate bv;
use self::bv::BitVec;

use std::fs;
use std::io;
use std::path::{PathBuf};
use std::rc::Rc;
use std::collections::HashMap;
use std::convert;
use std::marker;

use self::byteorder::{ByteOrder, BigEndian, LittleEndian, ReadBytesExt, WriteBytesExt};

use super::{Rom, RomManager};

use crate::{
	error::{Error, Result},
	definition::{self, DataType, Endianness},
	numvariant::NumVariant,
};



pub struct TableMeta {
	name: String,
	description: String,
}

trait TableDataTrait {
	fn size(&self) -> usize;
	fn get(&self, i: usize) -> NumVariant;
	fn set(&mut self, i: usize, data: NumVariant);
	fn serialize(&self, endianness: Endianness) -> Result<Vec<u8>>;
}

struct TableData<T> {
	data: Vec<T>,
}

trait TableType
where Self: Sized {
	fn deserialize<R: ReadBytesExt, O: ByteOrder>(data: &mut R) -> io::Result<Self>;
	fn serialize<W: WriteBytesExt, O: ByteOrder>(&self, data: &mut W) -> io::Result<()>;
}

impl TableType for u8 {
	fn deserialize<R: ReadBytesExt, O: ByteOrder>(data: &mut R) -> io::Result<Self> {
		data.read_u8()
	}

	fn serialize<W: WriteBytesExt, O: ByteOrder>(&self, data: &mut W) -> io::Result<()> {
		data.write_u8(*self)
	}
}

impl TableType for u16 {
	fn deserialize<R: ReadBytesExt, O: ByteOrder>(data: &mut R) -> io::Result<Self> {
		data.read_u16::<O>()
	}

	fn serialize<W: WriteBytesExt, O: ByteOrder>(&self, data: &mut W) -> io::Result<()> {
		data.write_u16::<O>(*self)
	}
}

impl TableType for u32 {
	fn deserialize<R: ReadBytesExt, O: ByteOrder>(data: &mut R) -> io::Result<Self> {
		data.read_u32::<O>()
	}

	fn serialize<W: WriteBytesExt, O: ByteOrder>(&self, data: &mut W) -> io::Result<()> {
		data.write_u32::<O>(*self)
	}
}

impl TableType for u64 {
	fn deserialize<R: ReadBytesExt, O: ByteOrder>(data: &mut R) -> io::Result<Self> {
		data.read_u64::<O>()
	}

	fn serialize<W: WriteBytesExt, O: ByteOrder>(&self, data: &mut W) -> io::Result<()> {
		data.write_u64::<O>(*self)
	}
}

impl TableType for i8 {
	fn deserialize<R: ReadBytesExt, O: ByteOrder>(data: &mut R) -> io::Result<Self> {
		data.read_i8()
	}

	fn serialize<W: WriteBytesExt, O: ByteOrder>(&self, data: &mut W) -> io::Result<()> {
		data.write_i8(*self)
	}
}

impl TableType for i16 {
	fn deserialize<R: ReadBytesExt, O: ByteOrder>(data: &mut R) -> io::Result<Self> {
		data.read_i16::<O>()
	}

	fn serialize<W: WriteBytesExt, O: ByteOrder>(&self, data: &mut W) -> io::Result<()> {
		data.write_i16::<O>(*self)
	}
}

impl TableType for i32 {
	fn deserialize<R: ReadBytesExt, O: ByteOrder>(data: &mut R) -> io::Result<Self> {
		data.read_i32::<O>()
	}

	fn serialize<W: WriteBytesExt, O: ByteOrder>(&self, data: &mut W) -> io::Result<()> {
		data.write_i32::<O>(*self)
	}
}

impl TableType for i64 {
	fn deserialize<R: ReadBytesExt, O: ByteOrder>(data: &mut R) -> io::Result<Self> {
		data.read_i64::<O>()
	}

	fn serialize<W: WriteBytesExt, O: ByteOrder>(&self, data: &mut W) -> io::Result<()> {
		data.write_i64::<O>(*self)
	}
}

impl TableType for f32 {
	fn deserialize<R: ReadBytesExt, O: ByteOrder>(data: &mut R) -> io::Result<Self> {
		data.read_f32::<O>()
	}

	fn serialize<W: WriteBytesExt, O: ByteOrder>(&self, data: &mut W) -> io::Result<()> {
		data.write_f32::<O>(*self)
	}
}

impl TableType for f64 {
	fn deserialize<R: ReadBytesExt, O: ByteOrder>(data: &mut R) -> io::Result<Self> {
		data.read_f64::<O>()
	}

	fn serialize<W: WriteBytesExt, O: ByteOrder>(&self, data: &mut W) -> io::Result<()> {
		data.write_f64::<O>(*self)
	}
}


impl<T> TableData<T> 
where T: TableType {
	/// Deserializes a table with the specified size in T units
	fn deserialize<O: ByteOrder>(data: &[u8], size: usize) -> Result<TableData<T>> {
		let mut reader = data;
		let mut deserialized = Vec::new();
		for _ in 0..size {
			deserialized.push(T::deserialize::<_,O>(&mut reader)?);
		}
		Ok(TableData {
			data: deserialized,
		})
	}

	fn serialize_order<O: ByteOrder>(&self) -> Result<Vec<u8>> {
		let mut serialized = Vec::new();
		for data in self.data.iter() {
			data.serialize::<_,O>(&mut serialized)?;
		}
		Ok(serialized)
	}
}

impl<T> TableDataTrait for TableData<T> where
T: convert::From<NumVariant> + marker::Copy + TableType, NumVariant: convert::From<T> {
	fn size(&self) -> usize {
		self.data.len()
	}

	fn get(&self, i: usize) -> NumVariant {
		NumVariant::from(self.data[i])
	}

	fn set(&mut self, i: usize, data: NumVariant) {
		self.data[i] = data.into();
	}

	fn serialize(&self, endianness: Endianness) -> Result<Vec<u8>> {
		match endianness {
			Endianness::Big => self.serialize_order::<BigEndian>(),
			Endianness::Little => self.serialize_order::<LittleEndian>(),
		}
	}
}

fn deserialize_table<O: ByteOrder>(datatype: DataType, data: &[u8], size: usize) -> Result<Box<TableDataTrait>> {
	match datatype {
		DataType::Uint8 => Ok(Box::new(TableData::<u8>::deserialize::<O>(data, size)?)),
		DataType::Uint16 => Ok(Box::new(TableData::<u16>::deserialize::<O>(data, size)?)),
		DataType::Uint32 => Ok(Box::new(TableData::<u32>::deserialize::<O>(data, size)?)),
		DataType::Uint64 => Ok(Box::new(TableData::<u64>::deserialize::<O>(data, size)?)),
		DataType::Int8 => Ok(Box::new(TableData::<i8>::deserialize::<O>(data, size)?)),
		DataType::Int16 => Ok(Box::new(TableData::<i16>::deserialize::<O>(data, size)?)),
		DataType::Int32 => Ok(Box::new(TableData::<i32>::deserialize::<O>(data, size)?)),
		DataType::Int64 => Ok(Box::new(TableData::<i64>::deserialize::<O>(data, size)?)),
		DataType::Float32 => Ok(Box::new(TableData::<f32>::deserialize::<O>(data, size)?)),
		DataType::Float64 => Ok(Box::new(TableData::<f64>::deserialize::<O>(data, size)?)),
	}
}

#[derive(Debug, Deserialize, Serialize)]
pub struct SerializedTable {
	id: usize,
	data: Vec<u8>,
}

pub struct Table {
	pub data_type: DataType,
	pub dirty: bool,
	modified: BitVec,
	data: Box<TableDataTrait>,
	height: usize,

	meta: TableMeta,
}

impl Table {
	/// Loads a table from the definition and raw data
	pub fn load_raw(definition: &definition::Table, data: &[u8], endianness: Endianness) -> Result<Table> {
		let size = definition.width * definition.height;
		let data = match endianness {
			Endianness::Big => deserialize_table::<BigEndian>(definition.data_type, data, size)?,
			Endianness::Little => deserialize_table::<LittleEndian>(definition.data_type, data, size)?,
		};
		Ok(Table {
			data_type: definition.data_type,
			dirty: false,
			modified: BitVec::new_fill(false, size as u64),
			data,
			height: definition.height,
			meta: TableMeta {
				name: definition.name.clone(),
				description: definition.description.clone(),
			},
		})
	}

	pub fn save_raw(&self, endianness: Endianness) -> Result<Vec<u8>> {
		self.data.serialize(endianness)
	}

	pub fn height(&self) -> usize {
		self.height
	}

	pub fn width(&self) -> usize {
		self.data.size() / self.height
	}

	/// Returns true if the data at (`x`, `y`) has been modified
	pub fn modified(&self, x: usize, y: usize) -> bool {
		self.modified[(y * self.height + x) as u64]
	}

	/// Returns true if the table has been modified from the original ROM
	pub fn dirty(&self) -> bool {
		self.dirty
	}

	pub fn name(&self) -> &str {
		&self.meta.name
	}

	pub fn description(&self) -> &str {
		&self.meta.description
	}

	/// Returns true if this is a two-dimensional table
	pub fn is_2d(&self) -> bool {
		self.height > 1
	}

	/// Returns true if this is a one-dimensional table
	pub fn is_1d(&self) -> bool {
		self.height == 1
	}

	/// Returns true if this table has one entry
	pub fn is_single(&self) -> bool {
		self.data.size() == 1
	}

	pub fn set(&mut self, x: usize, y: usize, data: NumVariant) {
		// TODO: Convert data to the correct type
		self.data.set(y * self.height + x, data);
	}

	/// Expects the data to be in range. If not, it will panic.
	pub fn get(&self, x: usize, y: usize) -> NumVariant {
		self.data.get(y * self.height + x)
	}
}


#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct TuneMeta {
	pub name: String,
	pub id: String,
	pub rom_id: String,

	#[serde(skip)]
	pub data_path: PathBuf,
}

pub struct Tune {
	pub rom: Rc<Rom>,
	pub tables: HashMap<usize, Table>,
	pub meta: TuneMeta,
}

impl Tune {
	/// Loads a tune from file
	pub fn load(meta: &TuneMeta, roms: &RomManager) -> Result<Tune> {
		// Search for the ROM
		let rom_meta = roms.search(&meta.rom_id).ok_or(Error::InvalidRomId)?;
		let rom = roms.load_rom(rom_meta)?;

		let mut tables = HashMap::new();
		// Load tables from file
		if meta.data_path.exists() {
			// A blank tune may not have a file, in which case it is the same as the unmodified ROM
			let contents = fs::read_to_string(&meta.data_path)?;
			let table_array: Vec<SerializedTable> = serde_yaml::from_str(&contents)?;
			for table in table_array {
				// Locate table definition
				if let Some(table_def) = rom_meta.platform.find_table(table.id) {
					tables.insert(table.id, Table::load_raw(table_def, &table.data, rom_meta.platform.endianness)?);
				} else {
					return Err(Error::InvalidTableId);
				}
			}
		}

		Ok(Tune {
			rom: rom.clone(),
			tables,
			meta: meta.clone(),
		})
	}

	/// Saves the tune to file. The filepath is Tune::meta::data_path
	pub fn save(&self) -> Result<()> {
		let mut tables = Vec::new();
		for table in self.tables.iter() {
			if table.1.dirty() {
				// We only save modified tables
				tables.push(SerializedTable {
					id: *table.0,
					data: table.1.save_raw(self.rom.meta.platform.endianness)?,
				});
			}
		}
		// Write to file
		fs::write(&self.meta.data_path, serde_yaml::to_string(&tables).unwrap())?;
		Ok(())
	}

	/// Gets a table. Returns Error::NotLoaded even if the id is invalid
	pub fn get_table(&self, id: usize) -> Result<&Table> {
		self.tables.get(&id).ok_or(Error::NotLoaded)
	}

	/// Loads a table
	pub fn load_table(&mut self, id: usize) -> Result<&Table> {
		// Search for the table id
		if let Some(table_def) = self.rom.meta.platform.tables.iter().find(|ref table| table.id == id) {
			// Get the offset
			let offset = self.rom.meta.model.table_offsets.get(&id).ok_or(Error::NoTableOffset)?;

			// Load the table from the ROM
			let table = Table::load_raw(table_def, &self.rom.data[*offset..], self.rom.meta.platform.endianness)?;
			self.tables.insert(id, table);
			// Unwrap because we just inserted it
			return Ok(self.tables.get(&id).unwrap());
		}
		// The table does not exist
		Err(Error::InvalidTableId)
	}

	/// Gets or loads a table.
	pub fn get_or_load_table(&mut self, id: usize) -> Result<&Table> {
		// This is an ugly pattern that can't be fixed without NLL
		if self.tables.contains_key(&id) {
			return self.tables.get(&id).ok_or(Error::InvalidTableId); // This should never error
		}
		self.load_table(id)
	}
}

#[derive(Debug)]
pub struct TuneManager {
	pub tunes: Vec<TuneMeta>,
	base: PathBuf,
}

impl TuneManager {
	pub fn load(base: PathBuf) -> Result<TuneManager> {
		let path = base.join("tunes.yaml");
		if !path.is_file() {
			return Ok(TuneManager {
				tunes: Vec::new(),
				base,
			});
		}

		// Load metadata
		Ok(TuneManager {
			tunes: serde_yaml::from_str(&fs::read_to_string(&path)?)?,
			base,
		})
	}

	pub fn save(&self) -> Result<()> {
		fs::write(&self.base.join("tunes.yaml"), serde_yaml::to_string(&self.tunes).unwrap())?;
		Ok(())
	}

	/// Adds a new tune to the database. Note: this WILL NOT save, you must call `save()`
	/// The data_path may not be preserved; it will be loaded as "$TUNE_PATH/id"
	fn add(&mut self, tune: &Tune) {
		self.tunes.push(tune.meta.clone());
	}

	pub fn add_meta(&mut self, name: String, id: String, rom_id: String) {
		self.tunes.push(TuneMeta {
			data_path: self.base.join(&id),
			name,
			id,
			rom_id,
		})
	}

	/// Creates a new tune from a ROM and adds it to the database.
	/// Note: this WILL NOT save, you must call `save()`
	pub fn new(&mut self, name: String, id: String, rom: &Rc<Rom>) -> Tune {
		let tune = Tune {
			rom: rom.clone(),
			tables: HashMap::new(),
			meta: TuneMeta {
				data_path: self.base.join(&id),
				name,
				id,
				rom_id: rom.meta.id.clone(),
			}
		};
		self.add(&tune);
		tune
	}
}