omt 0.6.3-alpha

A set of tiny tools mostly used for game development. A Texture atlas packer, a font converter, a pakfile creator.
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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
use std::fs::File;
use std::io::{BufReader, Read, Write};
use std::path::{Path, PathBuf};

use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use image::{DynamicImage, GenericImage, GenericImageView, ImageFormat};
use regex::Regex;

use crate::atlas::AtlasFitter;

#[derive(Clone)]
pub struct Entry {
	filename:   String,
	pub image:  Option<DynamicImage>,
	pub x:      u32,
	pub y:      u32,
	pub width:  u32,
	pub height: u32,
}

impl std::fmt::Debug for Entry {
	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::result::Result<(), std::fmt::Error> {
		f.debug_struct("Entry")
			.field("filename", &self.filename)
			//			.field("image", if self.image.is_some() {"YES"} else {"NO"} )
			.field("x", &self.x)
			.field("y", &self.y)
			.field("width", &self.width)
			.field("height", &self.height)
			.finish()
	}
}
impl Entry {
	fn new(filename: &str, width: u32, height: u32) -> Entry {
		Entry {
			filename: filename.to_string(),
			image:    None,
			x:        0,
			y:        0,
			width:    width,
			height:   height,
		}
	}

	fn set_image(&mut self, image: DynamicImage) {
		self.width = image.dimensions().0;
		self.height = image.dimensions().1;
		self.image = Some(image);
	}

	fn set_position(&mut self, x: u32, y: u32) {
		self.x = x;
		self.y = y;
	}
	fn get_basename(&self) -> String {
		let basename = Path::new(&self.filename)
			.file_name()
			.unwrap()
			.to_str()
			.unwrap();
		basename.to_string()
	}
	fn get_stem(&self) -> String {
		let stem = Path::new(&self.filename)
			.file_stem()
			.unwrap()
			.to_str()
			.unwrap();
		stem.to_string()
	}
	/*
			sx = s[ 0 ].to_f/size
			sy = s[ 1 ].to_f/size
			ex = e[ 0 ].to_f/size
			ey = e[ 1 ].to_f/size

			t.scaleX = (ex-sx)
			t.scaleY = (ey-sy)

			def getMatrix
				# :HACK: :TODO: add rotation
				[
					@scaleX	, 0.0		, @x,
					0.0		, @scaleY	, @y
				]
			end
	*/
	fn get_matrix(&self, size: u32) -> [f32; 6] {
		// :TODO: cleanup please
		let sx = self.x as f32 / size as f32;
		let sy = self.y as f32 / size as f32;
		//		let ex = ( self.x + self.width ) as f32 / size as f32;
		//		let ey = ( self.y + self.height ) as f32 / size as f32;
		let scale_x = self.width as f32 / size as f32; //ex - sx;
		let scale_y = self.height as f32 / size as f32; //ey - sy;
		[scale_x, 0.0, sx, 0.0, scale_y, sy]
	}
}

fn simple_format_u32(f: &str, n: u32) -> String {
	let s = f.clone();
	let re = Regex::new(r"(%d)").unwrap();

	//	println!("simple_format_u32 {:?} with {:?}", s, re );
	let s = re.replace_all(&s, |c: &regex::Captures| {
		let placeholder = c.get(1).map_or("", |m| m.as_str());
		//			println!("Found {:?}", placeholder );
		match placeholder {
			"" => "".to_string(),
			"%d" => n.to_string(),
			x => {
				println!("simple_format_u32 got {:?}", x);
				x.to_string()
			},
		}
	});

	s.to_string()
}

//#[derive()]
pub struct Atlas {
	size:           u32,
	border:         u32,
	pub entries:    Vec<Entry>,
	pub image:      Option<DynamicImage>,
	atlas_filename: Option<String>,
	image_filename: Option<String>,
}

impl std::fmt::Debug for Atlas {
	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::result::Result<(), std::fmt::Error> {
		f.debug_struct("Atlas")
			.field("size", &self.size)
			.field("border", &self.border)
			.field("entries", &self.entries)
			//			.field("image", if self.image.is_some() {"YES"} else {"NO"} )
			.finish()
	}
}

impl Atlas {
	fn new(size: u32, border: u32) -> Atlas {
		Atlas {
			size:           size,
			border:         border,
			entries:        Vec::new(),
			image:          Some(image::DynamicImage::new_rgba8(size, size)),
			atlas_filename: None,
			image_filename: None,
		}
	}

	pub fn add_entry(&mut self, entry: Entry) {
		self.entries.push(entry);
	}

	pub fn blit_entries(&mut self) {
		match &mut self.image {
			None => {},
			Some(di) => {
				for entry in &self.entries {
					match &entry.image {
						None => {},
						Some(image) => {
							Atlas::blit(di, &image, entry.x, entry.y);
						},
					}
				}
			},
		}
	}

	fn new_from_atlas(atlasname: &str, size: u32) -> Atlas {
		let mut a = Atlas {
			size:           size,
			border:         0,
			entries:        Vec::new(),
			image:          None,
			atlas_filename: Some(atlasname.to_string()),
			image_filename: None,
		};

		match a.load_atlas(&atlasname, a.size) {
			Err(e) => println!("{:?}", e),
			_ => {},
		};

		a
	}

	fn blit(
		dest: &mut image::DynamicImage,
		source: &image::DynamicImage,
		start_x: u32,
		start_y: u32,
	) {
		let w = source.dimensions().0;
		let h = source.dimensions().1;

		for y in 0..h {
			for x in 0..w {
				let dx = start_x + x;
				let dy = start_y + y;

				let pixel = source.get_pixel(x, y);
				dest.put_pixel(dx, dy, pixel);
			}
		}
	}

	fn save_png(&self, filename: &str) -> anyhow::Result<()> {
		match self
			.image
			.as_ref()
			.unwrap()
			.save_with_format(filename, ImageFormat::Png)
		{
			_ => Ok(()),
		}
	}

	fn load_atlas(&mut self, filename: &str, size: u32) -> anyhow::Result<()> {
		let f = match File::open(filename) {
			Ok(f) => f,
			Err(_) => anyhow::bail!("io"),
		};

		let mut bufreader = BufReader::new(f);
		let magic = match bufreader.read_u16::<LittleEndian>() {
			//.unwrap_or( 0xffff );
			Ok(m) => m,
			x => {
				println!("{:?}", x);
				anyhow::bail!("reading from buffer");
			},
		};
		if magic != 0x4f53 {
			println!("Got magic {:?} from {:?}", magic, bufreader);
			anyhow::bail!("Broken file magic");
		}
		let v = bufreader.read_u16::<LittleEndian>().unwrap_or(0);
		if v != 1 {
			anyhow::bail!("Wrong version");
		}
		let chunk_magic = [0x4fu8, 0x4d, 0x41, 0x54, 0x4c, 0x41, 0x53];
		for m in &chunk_magic {
			let b = bufreader.read_u8().unwrap_or(0);
			if b != *m {
				anyhow::bail!("Broken chunk magic");
			}
		}
		let flags = bufreader.read_u8().unwrap_or(0);
		if flags != 'S' as u8 {
			anyhow::bail!(":TODO: compression not implemented");
		}
		let chunk_version = [0x01u8, 0x00, 0x00, 0x00];
		for m in &chunk_version {
			let b = bufreader.read_u8().unwrap_or(0);
			if b != *m {
				anyhow::bail!("Broken chunk version");
			}
		}
		let entry_count = bufreader.read_u16::<LittleEndian>().unwrap_or(0);

		println!("Got {:?} entries", entry_count);

		for _ei in 0..entry_count {
			let mut name_buffer = [0u8; 128];
			bufreader.read_exact(&mut name_buffer).unwrap();
			let mut name = String::from_utf8(name_buffer.to_vec()).unwrap();
			let first_zero = name.find("\u{0}").unwrap_or(name.len());
			name.truncate(first_zero);
			let mut matrix_buffer = [0f32; 6];
			for m in &mut matrix_buffer {
				*m = bufreader.read_f32::<LittleEndian>().unwrap_or(0.0);
			}

			let w = (matrix_buffer[0 * 3 + 0] * size as f32).trunc() as u32;
			let h = (matrix_buffer[1 * 3 + 1] * size as f32).trunc() as u32;
			let mut e = Entry::new(&name, w, h);
			let x = (matrix_buffer[0 * 3 + 2] * size as f32).trunc() as u32;
			let y = (matrix_buffer[1 * 3 + 2] * size as f32).trunc() as u32;
			e.set_position(x, y);
			self.entries.push(e);
		}
		Ok(())
	}

	// :TODO: support compression
	fn save_atlas(&self, filename: &str) -> anyhow::Result<()> {
		let mut f = match File::create(filename) {
			Ok(f) => f,
			Err(_) => anyhow::bail!("io"),
		};
		f.write_u16::<LittleEndian>(0x4f53).unwrap();
		f.write_u16::<LittleEndian>(0x0001).unwrap();
		let compress = 'S';
		f.write_all(&[
			0x4f,
			0x4d,
			0x41,
			0x54,
			0x4c,
			0x41,
			0x53, // OMATLAS
			compress as u8,
			0x01,
			0x00,
			0x00,
			0x00,
		])
		.unwrap();
		f.write_u16::<LittleEndian>(self.entries.len() as u16)
			.unwrap();
		for e in &self.entries {
			let n = e.get_basename();
			let mut c = 0;
			for nn in n.as_bytes() {
				f.write_u8(*nn).unwrap();
				c += 1;
			}
			while c < 128 {
				f.write_u8(0).unwrap();
				c += 1;
			}
			let m = e.get_matrix(self.size);
			//			println!("Matrix {:?}", m );
			for mm in &m {
				f.write_f32::<LittleEndian>(*mm).unwrap();
			}
		}
		Ok(())
	}

	fn save_map(&self, filename: &str) -> anyhow::Result<()> {
		let mut f = match File::create(filename) {
			Ok(f) => f,
			Err(_) => anyhow::bail!("io"),
		};

		//		println!("{:?}", self );

		for e in &self.entries {
			//			println!("{:?}", e );
			// overlay-00-title-square.png:0,0-2048,1536
			let basename = e.get_basename();
			let l = format!(
				"{}:{},{}-{},{}\n",
				basename,
				e.x,
				e.y,
				e.x + e.width,
				e.y + e.height
			);
			//			println!("{}", l);
			write!(f, "{}", l).unwrap();
		}
		Ok(())
	}

	pub fn hello() {
		println!("Atlas::hello()");
	}

	pub fn all_for_template(input: &str) -> Vec<Atlas> {
		let mut result = Vec::new();
		let mut n = 0;
		loop {
			let inname = simple_format_u32(input, n); //format!(output, n);
			let atlasname = format!("{}.atlas", inname);
			let pngname = format!("{}.png", inname);
			if !Path::new(&atlasname).exists() {
				println!("{:?} not found. Stopping", atlasname);
				break;
			}
			if !Path::new(&pngname).exists() {
				println!("{:?} not found. Stopping", pngname);
				break;
			}
			// load image, to get the size
			let img = image::open(&pngname).unwrap();
			if img.dimensions().0 != img.dimensions().1 {
				println!(
					"Error: Non-square texture atlas found with dimensions {:?}",
					img.dimensions()
				);
			}

			let size = img.dimensions().0;

			let mut a = Atlas::new_from_atlas(&atlasname, size);
			a.image_filename = Some(pngname.to_string());
			a.image = Some(img);

			result.push(a);
			n += 1;
			dbg!(&input);
			dbg!(&inname);
			if input == inname {
				// for non-template aka single file cases
				break;
			}
		}
		result
	}

	pub fn info(input: &str) -> anyhow::Result<u32> {
		let atlases = Atlas::all_for_template(&input);

		for a in &atlases {
			//			println!("Atlas {} {}", atlasname, pngname);
			match (&a.atlas_filename, &a.image_filename) {
				(None, None) => {},
				(Some(n), None) => {
					println!("Atlas {}", n);
				},
				(Some(a), Some(i)) => {
					println!("Atlas {} {}", a, i);
				},
				(None, Some(i)) => {
					println!("Atlas Image: {}", i);
				},
			}
			println!("\tSize  : {}", a.size);
			println!("\tBorder: {}", a.border);
			for e in &a.entries {
				println!(
					"\t\t{:>5} x {:>5}  @  {:>5},{:>5}   | {}",
					e.width, e.height, e.x, e.y, e.filename
				);
			}
		}

		let n = atlases.len() as u32;
		if n == 0 {
			anyhow::bail!("No matching atlas found.");
		} else {
			Ok(n)
		}
	}

	pub fn combine(
		output: &PathBuf,
		size: u32,
		border: u32,
		input: &Vec<PathBuf>,
		reference_path: Option<&PathBuf>,
	) -> anyhow::Result<u32> {
		let mut entries = Vec::new();
		// collect inputs
		for i in input {
			println!("Analysing {:?}", i);
			let img = image::open(i).unwrap();

			let i_os_string = i.clone().into_os_string();
			let i_string = match i_os_string.to_str() {
				Some(s) => s,
				None => anyhow::bail!("Error converting path to string"),
			};

			let mut e = Entry::new(i_string, 0, 0);
			e.set_image(img);
			entries.push(e);
		}

		// sort entries by size
		entries.sort_by(
			|a, b| b.height.cmp(&a.height), // higher ones first
		);

		let mut atlases: Vec<Atlas> = Vec::new();

		// something that takes a list of entries, and return a list of pages with those entries

		let mut atlas_fitter = AtlasFitter::new();

		for (idx, e) in entries.iter().enumerate() {
			atlas_fitter.add_entry(idx, e.width, e.height);
		}

		//		println!("atlas_fitter {:#?}", atlas_fitter);

		let pages = atlas_fitter.fit(size, border);
		//		println!("pages {:#?}", pages);

		// create atlases
		for p in &pages {
			let mut a = Atlas::new(size, border);
			for e in &p.entries {
				println!("{:#?}", e);
				let entry = &entries[e.id];
				let mut entry = entry.clone();
				entry.set_position(e.x, e.y);
				println!("{:#?}", entry);
				a.add_entry(entry);
			}
			a.blit_entries();
			atlases.push(a);
		}
		/*
		// combine outputs
		for e in entries.drain(..) {
			let mut did_fit = false;
			for a in &mut atlases {
				if a.add_entry( &e) {
					did_fit = true;
					break;
				}
			}
			if !did_fit {
				let mut a = Atlas::new( size, border );
				if !a.add_entry( &e ) {
					println!("‼️ Image doesn't fit into empty atlas {:?}", e );
					anyhow::bail!("‼️ Image doesn't fit into empty atlas");
				}
				atlases.push( a );
			}
		}
		*/
		// write outputs
		let mut n = 0;
		let output_os_string = output.clone().into_os_string();
		let output_string = match output_os_string.to_str() {
			Some(s) => s,
			None => anyhow::bail!("Error converting path to string"),
		};

		for a in atlases {
			//			println!("Atlas #{} {:?}", n, a );
			let outname = simple_format_u32(&output_string, n); //format!(output, n);
			let pngname = format!("{}.png", outname);
			let atlasname = format!("{}.atlas", outname);
			let mapname = format!("{}.map", outname);
			match a.save_png(&pngname) {
				Ok(_bytes_written) => {
					//					println!("{:?} bytes written to image {}", bytes_written, pngname );
				},
				Err(e) => {
					println!("Error writing .png to {}", &pngname);
					return Err(e);
				},
			}
			match a.save_atlas(&atlasname) {
				Ok(_bytes_written) => {
					//					println!("{:?} bytes written to atlas {}", bytes_written, atlasname );
				},
				Err(e) => {
					println!("Error writing .atlas to {}", &atlasname);
					return Err(e);
				},
			}
			match a.save_map(&mapname) {
				Ok(_bytes_written) => {
					//					println!("{:?} bytes written to map {}", bytes_written, atlasname );
				},
				Err(e) => {
					println!("Error writing .map to {}", &mapname);
					return Err(e);
				},
			}
			if let Some(rp) = &reference_path {
				let atlas_stem = Path::new(&atlasname)
					.file_stem()
					.unwrap()
					.to_str()
					.unwrap()
					.to_string();
				println!("Writing references for {} to {}", &atlas_stem, rp.display());
				for e in a.entries {
					//dbg!(&e);
					let stem = e.get_stem();
					//println!("{} in {}", &stem, &atlas_stem);
					let mut omtr = PathBuf::new();
					omtr.push(&rp);
					omtr.push(&stem);
					omtr.set_extension(&"omtr");
					//dbg!(&omtr);
					let mut f = match File::create(omtr) {
						Ok(f) => f,
						Err(_) => anyhow::bail!("io"),
					};
					write!(f, "{}\n", &atlas_stem).unwrap();
				}
			}
			n += 1;
		}

		Ok(n)
	}
}