Skip to content

Instantly share code, notes, and snippets.

@sharow
Created October 11, 2017 13:40
Show Gist options
  • Save sharow/e0019d1908fcc994370e211dbce4884e to your computer and use it in GitHub Desktop.
Save sharow/e0019d1908fcc994370e211dbce4884e to your computer and use it in GitHub Desktop.
Rust code fragment. load BMFont xml geometries.
extern crate xml;
use std::path::Path;
use std::fs::File;
use xml::reader::EventReader;
use xml::reader::events::*;
#[derive(Clone)]
struct GlyphGeometry {
pub rect: Rect,
pub xoffset: i32,
pub yoffset: i32,
pub xadvance: i32
}
impl Default for GlyphGeometry {
fn default() -> GlyphGeometry {
GlyphGeometry { rect: Rect::new(0, 0, 0, 0),
xoffset: 0,
yoffset: 0,
xadvance: 0 }
}
}
type GlyphGeometries = Vec<Option<GlyphGeometry>>;
fn load_glyph_geometries() -> GlyphGeometries {
let file = File::open("asset/your_font.xml").unwrap();
let mut parser = EventReader::new(file);
let mut v: GlyphGeometries = (0..256).map(|_| None).collect();
let mut tile: GlyphGeometry = Default::default();
let mut id: usize = 0;
for e in parser.events() {
match e {
XmlEvent::StartElement { name, attributes, .. } => {
if name.local_name == "char" && !attributes.is_empty() {
for attr in attributes.iter() {
macro_rules! parse {
($attr: expr, $ty: ty) => ($attr.value.parse::<$ty>().unwrap());
}
match attr.name.local_name.as_ref() {
"id" => id = parse!(attr, usize),
"x" => tile.rect.set_x(parse!(attr, i32)),
"y" => tile.rect.set_y(parse!(attr, i32)),
"width" => tile.rect.set_width(parse!(attr, u32)),
"height" => tile.rect.set_height(parse!(attr, u32)),
"xoffset" => tile.xoffset = parse!(attr, i32),
"yoffset" => tile.yoffset = parse!(attr, i32),
"xadvance" => tile.xadvance = parse!(attr, i32),
_ => {}
}
}
}
}
XmlEvent::EndElement { name } => {
if name.local_name == "char" {
v[id] = Some(tile.clone());
tile = Default::default();
}
}
XmlEvent::Error(e) => { panic!("Error: {}", e) }
_ => {}
}
}
return v;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment