zenith 4 жил өмнө
commit
664d59af6d

+ 2 - 0
.gitignore

@@ -0,0 +1,2 @@
+/target
+/Cargo.lock

+ 25 - 0
Cargo.toml

@@ -0,0 +1,25 @@
+[package]
+name = "chair"
+version = "0.1.0"
+edition = "2021"
+description = "An efficient binary mesh format which is both small and extremely fast to read."
+readme = "README.md"
+repository = "https://gitgud.io/deltanedas/chair"
+license = "GPL-3.0-or-later"
+categories = ["graphics"]
+keywords = ["mesh"]
+
+[dependencies]
+bytemuck = {version = "1", features = ["derive"]}
+byteorder = {version = "1", optional = true}
+enumflags2 = "0.7"
+log = {version = "0.4", optional = true}
+macro_pub = "0.1"
+thiserror = {version = "1", optional = true}
+wgpu = {version = "0.14", optional = true}
+
+[features]
+default = ["io", "mesh", "vertex-impls"]
+io = ["dep:byteorder", "dep:log", "dep:thiserror", "mesh"]
+mesh = ["dep:wgpu"]
+vertex-impls = []

+ 31 - 0
README.md

@@ -0,0 +1,31 @@
+# chair
+
+An efficient binary mesh format which is both small and extremely fast to read.
+
+Textures are supported by loading them from an atlas and mapping mesh uvs to the region.
+
+# loading and drawing meshes with wgpu
+
+```rs
+let bytes = fs::read("chair.chr")?;
+// MyVertex implements the Vertex trait to specify what features are loaded into memory
+let mesh = MeshReader::<MyVertex>::new(atlas, Some("fallback"))
+	.create(device, bytes)?;
+
+// in render pass code
+mesh.draw(&mut pass);
+```
+
+Fallback texture name is specified with the `fallback` parameter of `MeshReader::new`.
+
+If it is not specified, decoding the mesh will fail instead of using a fallback texture if any unknown textures are specified.
+
+# creating meshes
+
+The easy way is use `chair_exporter.py` as a blender addon to export your models from blender.
+
+Use the optimal settings for accuracy and size as you see fit.
+
+For minecraft-like meshes you can easily do short pos, uvs and normals as they are all low-detail.
+
+For more complex ones this will lose accuracy, so using floats may be prefered.

+ 20 - 0
build.rs

@@ -0,0 +1,20 @@
+use std::{
+	env::var,
+	f32::consts::TAU,
+	fs::File,
+	io::{Result, Write},
+	path::PathBuf
+};
+
+fn main() -> Result<()> {
+	let mut path = PathBuf::from(var("OUT_DIR")
+		.expect("Cargo didn't set OUT_DIR"));
+	path.push("normals.rs");
+	let mut f = File::create(path)?;
+	f.write_all(b"[0.0,")?;
+	for n in 1..256 {
+		write!(f, "{},", (n as f32 / 255.0 * TAU).sin())?;
+	}
+
+	f.write_all(b"]")
+}

BIN
chair.blend


BIN
chair.chr


+ 300 - 0
chair_exporter.py

@@ -0,0 +1,300 @@
+# Blender addon to export an object as a lib.rs/chair mesh file
+# Based on the Raw mesh exporter distributed with blender
+
+bl_info = {
+	"name": "Chair Mesh Exporter",
+	"author": "deltanedas",
+	"blender": (3, 0, 0),
+	"location": "File > Import-Export > Chair Mesh (.chr)",
+	# Same as the crate version
+	"version": (0.1, 0),
+	"category": "Import-Export"
+}
+
+# For normal lookup
+import math
+# For writing floats
+import struct
+
+def face_to_tris(face, mesh, matrix, vertices, vertex_ids, indices):
+	i = len(vertices)
+	for verti in face.vertices:
+		vert = mesh.vertices[verti]
+		v = [(matrix @ vert.co)[:], (vert.normal)[:]]
+		key = str(v)
+		if key in vertex_ids:
+			i = vertex_ids[key]
+		else:
+			# new vertex, push to list
+			vertices.append(v)
+			vertex_ids[key] = i
+
+	# TODO: general form for n-gons
+	# Single triangle
+	indices.append(i)
+	indices.append(i + 1)
+	indices.append(i + 2)
+	if len(face.vertices) == 4:
+		# Second triangle of quad
+		indices.append(i)
+		indices.append(i + 2)
+		indices.append(i + 3)
+
+def process_scene(context, apply_modifiers):
+	objects = []
+	indices = []
+
+	scene = context.scene
+	for obj in context.selected_objects:
+		me = None
+		if apply_modifiers or obj.type != "MESH":
+			try:
+				me = obj.to_mesh()
+			except:
+				me = None
+			is_tmp_mesh = True
+		else:
+			me = obj.data
+			is_tmp_mesh = False
+
+		if me is None:
+			continue
+
+		if not me.loop_triangles and me.polygons:
+			me.calc_loop_triangles()
+
+		# TODO: texture used by this object
+		vertices = []
+		vertex_ids = {}
+		matrix = obj.matrix_world.copy()
+		for face in me.loop_triangles:
+			face_to_tris(face, me, matrix, vertices, vertex_ids, indices)
+
+		min_pos = [
+			min(vertices, key=lambda v: v[0][0])[0][0],
+			min(vertices, key=lambda v: v[0][1])[0][1],
+			min(vertices, key=lambda v: v[0][2])[0][2]
+		]
+		max_pos = [
+			max(vertices, key=lambda v: v[0][0])[0][0],
+			max(vertices, key=lambda v: v[0][1])[0][1],
+			max(vertices, key=lambda v: v[0][2])[0][2]
+		]
+		scale = [
+			max_pos[0] - min_pos[0],
+			max_pos[1] - min_pos[1],
+			max_pos[2] - min_pos[2]
+		]
+		objects.append((vertices, scale, min_pos))
+
+		# Remove meshes that are created solely for exporting
+		if is_tmp_mesh:
+			obj.to_mesh_clear()
+
+	return objects, indices
+
+def index_size(vertices):
+	if vertices < 256:
+		return 1
+	if vertices < 65536:
+		return 2
+	return 4
+
+def write_vec3_float(f, v):
+	# <f = little-endian float
+	f.write(bytes(struct.pack("<f", v[0])))
+	# Y = up in chair/wgpu, Z = up in blender so swap them
+	f.write(bytes(struct.pack("<f", v[2])))
+	f.write(bytes(struct.pack("<f", v[1])))
+
+def write_vec3_byte(f, v, scale, offset):
+	# use range 0-128 to allow for even divisions
+	x = 128 * (v[0] - offset[0]) / scale[0]
+	# Y = up in chair/wgpu, Z = up in blender so swap them
+	y = 128 * (v[2] - offset[2]) / scale[2]
+	z = 128 * (v[1] - offset[1]) / scale[1]
+	print("writing float " + str(x) + ", " + str(y) + ", " + str(z))
+	f.write(bytes([int(x), int(y), int(z)]))
+
+def index_normal(n):
+	# asin fairly slow but this is pyton so doesnt matter
+	return 128 + int(math.asin(n) * 255 / math.pi)
+
+def write_vec3_sin(f, v):
+	x = index_normal(v[0])
+	# Y = up in chair/wgpu, Z = up in blender so swap them
+	y = index_normal(v[2])
+	z = index_normal(v[1])
+	f.write(bytes([x, y, z]))
+
+def write_model(path, objects, indices, export_colours, export_normals, export_uvs, export_skeleton, short_pos, short_normals, short_uvs, short_weights):
+	f = open(path, "wb")
+	# Chair file header
+	f.write(bytes("CHAIR", "ascii"))
+	# Format version
+	f.write(bytes([0]))
+
+	# MeshFeatures
+	features = 0
+	if export_colours:
+		features |= 0b0001
+	if export_normals:
+		features |= 0b0010
+	if export_uvs:
+		features |= 0b0100
+	if export_skeleton:
+		features |= 0b1000
+	if short_pos:
+		features |= 0b00010000
+	if short_normals:
+		features |= 0b00100000
+	if short_uvs:
+		features |= 0b01000000
+	if short_weights:
+		features |= 0b10000000
+	f.write(bytes([features]))
+
+	# TODO: export unique vertex colours from objects
+	if export_colours:
+		f.write((1).to_bytes(2, "little"))
+		f.write(bytes([255, 255, 255, 255]))
+
+	# TODO: export texture names
+	if export_uvs:
+		f.write(bytes([1, 5]))
+		f.write(bytes("error", "ascii"))
+
+	# TODO: export skeleton
+
+	f.write(bytes([len(objects)]))
+	for obj in objects:
+		# Vertices count for this object
+		f.write(len(obj[0]).to_bytes(4, "little"))
+		scale = obj[1]
+		offset = obj[2]
+		if short_pos:
+			write_vec3_float(f, scale)
+			write_vec3_float(f, offset)
+			write_pos = lambda f, v: write_vec3_byte(f, v, scale, offset)
+		else:
+			write_pos = write_vec3_float
+
+		if short_normals:
+			write_normals = write_vec3_sin
+		else:
+			write_normals = write_vec3_float
+
+		# TODO: texture name index
+
+		# Write data
+		for v in obj[0]:
+			write_pos(f, v[0])
+			if export_colours:
+				# TODO: colour index
+				f.write(bytes([0]))
+			if export_normals:
+				write_normals(f, v[1])
+			if export_uvs:
+				# TODO uvs, short uvs
+				f.write(struct.pack("<f", 0))
+				f.write(struct.pack("<f", 0))
+			# TODO: bone weights
+
+	# Indices
+	f.write(len(indices).to_bytes(4, "little"))
+	indsize = index_size(sum([len(obj[0]) for obj in objects]))
+	for i in indices:
+		f.write(i.to_bytes(indsize, "little"))
+
+	f.close()
+	return
+
+import bpy
+from bpy_extras.io_utils import ExportHelper
+from bpy.props import StringProperty, BoolProperty
+from bpy.types import Operator
+
+class ModelExporter(Operator, ExportHelper):
+	"""Export geometry to chair mesh format (lib.rs/chair)"""
+	bl_idname = "export.chair"
+	bl_label = "Export Chair Mesh"
+
+	filename_ext = ".chr"
+	filter_glob: StringProperty(
+		default = "*.chr",
+		options = {"HIDDEN"}
+	)
+
+	apply_modifiers: BoolProperty(
+		name = "Apply Modifiers",
+		description = "Use transformed mesh data from each object",
+		default = True
+	)
+
+	export_colours: BoolProperty(
+		name = "Export Colours",
+		description = "Save vertex colours in the exported mesh",
+		default = True
+	)
+
+	export_normals: BoolProperty(
+		name = "Export Normals",
+		description = "Save vertex normals in the exported mesh",
+		default = True
+	)
+
+	export_uvs: BoolProperty(
+		name = "Export UVs",
+		description = "Save vertex texture coordinates (and texture names) in the exported mesh",
+		default = False
+	)
+
+	export_skeleton: BoolProperty(
+		name = "Export Skeleton",
+		description = "Save skeleton and vertex bones/weights in the exported mesh",
+		default = False
+	)
+
+	short_pos: BoolProperty(
+		name = "Short Positions",
+		description = "Use bytes -64 to +64 instead of floats to lossily encode vertex positions.\nAlso stores scale + offset of objects",
+		default = False
+	)
+
+	short_normals: BoolProperty(
+		name = "Short Normals",
+		description = "Use a byte sin lookup table instead of floats to lossily encode vertex normals",
+		default = False
+	)
+
+	short_uvs: BoolProperty(
+		name = "Short UVs",
+		description = "Use bytes 0 to 128 instead of floats to lossily encode vertex texture coordinates",
+		default = False
+	)
+
+	short_weights: BoolProperty(
+		name = "Short Weights",
+		description = "Use bytes -64 to +64 instead of floats to lossily encode vertex weights",
+		default = False
+	)
+
+	def execute(self, context):
+		objects, indices = process_scene(context, self.apply_modifiers)
+		write_model(self.filepath, objects, indices, self.export_colours, self.export_normals, self.export_uvs, self.export_skeleton,
+			self.short_pos, self.short_normals, self.short_uvs, self.short_weights)
+		return {"FINISHED"}
+
+def menu_export(self, context):
+	self.layout.operator(ModelExporter.bl_idname, text = "Chair Mesh (.chr)")
+
+def register():
+	bpy.utils.register_class(ModelExporter)
+	bpy.types.TOPBAR_MT_file_export.append(menu_export)
+
+def unregister():
+	bpy.utils.unregister_class(ModelExporter)
+	bpy.types.TOPBAR_MT_file_export.remove(menu_export)
+
+if __name__ == "__main__":
+	register()

+ 2 - 0
examples/reader/.gitignore

@@ -0,0 +1,2 @@
+/target
+/Cargo.lock

+ 8 - 0
examples/reader/Cargo.toml

@@ -0,0 +1,8 @@
+[package]
+name = "reader"
+version = "0.1.0"
+edition = "2021"
+
+[dependencies]
+chair = {path = "../.."}
+env_logger = "0.9"

+ 29 - 0
examples/reader/src/main.rs

@@ -0,0 +1,29 @@
+use chair::*;
+
+use std::{env, fs};
+
+struct DummyAtlas;
+
+impl Atlas for DummyAtlas {
+	fn get(&self, _: &str) -> Option<&AtlasRegion> {
+		Some(&AtlasRegion {
+			xy: [0.0; 2],
+			x2y: [1.0, 0.0],
+			x2y2: [1.0; 2],
+			xy2: [0.0, 1.0]
+		})
+	}
+}
+
+fn main() {
+	env_logger::init();
+
+	let path = env::args().nth(1).expect("Run with a mesh path");
+	let bytes = fs::read(path)
+		.expect("Failed to read file");
+	let atlas = DummyAtlas;
+	let (vertices, indices) = MeshReader::new::<BasicVertex>(&atlas, None)
+		.read::<BasicVertex>(&bytes)
+		.expect("Failed to read mesh data");
+	println!("Got {} vertices and {} indices", vertices.len(), indices.len());
+}

+ 28 - 0
src/atlas.rs

@@ -0,0 +1,28 @@
+type Pos = [f32; 2];
+
+/// A region from an atlas
+#[derive(Clone, Copy, Debug)]
+pub struct AtlasRegion {
+	pub xy: Pos,
+	pub x2y: Pos,
+	pub x2y2: Pos,
+	pub xy2: Pos
+}
+
+impl AtlasRegion {
+	/// Map UVs from [0, 1] to [x, x + w]
+	pub fn map_uvs(&self, u: f32, v: f32) -> [f32; 2] {
+		let w = self.x2y[0] - self.xy[0];
+		let h = self.xy2[1] - self.xy[1];
+		[
+			self.xy[0] + w * u,
+			self.xy[1] + h * v
+		]
+	}
+}
+
+/// A texture atlas that maps strings to regions
+pub trait Atlas {
+	/// Get a region from this atlas
+	fn get(&self, name: &str) -> Option<&AtlasRegion>;
+}

+ 33 - 0
src/features.rs

@@ -0,0 +1,33 @@
+use enumflags2::*;
+use macro_pub::*;
+
+#[bitflags]
+#[repr(u8)]
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub enum MeshFeature {
+	Coloured,
+	Normals,
+	Textured,
+	Rigged,
+
+	ShortPos,
+	ShortNormals,
+	ShortUvs,
+	ShortWeights
+}
+
+pub type MeshFeatures = BitFlags<MeshFeature>;
+
+#[macro_pub]
+macro_rules! features {
+	() => {
+		MeshFeatures::empty()
+	};
+	($feat: tt) => {
+		MeshFeature::$feat.into()
+	};
+
+	($feat: tt, $($others: tt),+) => {
+		features!($feat) | features!($(others),+)
+	};
+}

+ 362 - 0
src/io.rs

@@ -0,0 +1,362 @@
+use crate::{
+	atlas::*,
+	features::*,
+	mesh::*,
+	vertex::*
+};
+
+use std::io::{Cursor, Read};
+
+use byteorder::*;
+use log::*;
+use thiserror::*;
+use wgpu::*;
+
+#[derive(Debug, Error)]
+pub enum Error {
+	#[error("failed to read mesh")]
+	Io(#[from] std::io::Error),
+	#[error("wrong mesh header")]
+	WrongHeader([u8; 5]),
+	#[error("unknown mesh version {0}")]
+	UnknownVersion(u8),
+	#[error("mesh contains banned features: {0:?}")]
+	BannedFeatures(MeshFeatures),
+	#[error("mesh does not contain required features: {0:?}")]
+	MissingFeatures(MeshFeatures),
+	#[error("non-utf8 texture name #{0}")]
+	InvalidTextureName(u8),
+	#[error("atlas does not contain texture '{0}'")]
+	MissingTexture(String),
+	#[error("object {0} uses an unknown texture index")]
+	UnknownTexture(u8),
+	#[error("unknown colour index {0}")]
+	UnknownColour(u16)
+}
+
+pub type Result<T> = std::result::Result<T, Error>;
+
+/// Configuration for reading meshes
+/// # Examples
+/// ```
+/// # use chair::*;
+/// # struct EmptyAtlas;
+/// # impl Atlas for EmptyAtlas { fn get(&self, name: &str) -> Option<&AtlasRegion> { None } }
+/// # let atlas = EmptyAtlas;
+/// let reader = MeshReader::new::<BasicVertex>(&atlas, None)
+/// 	// refuse to load any meshes that can be animated, even though the information would be discarded
+/// 	.ban_feature(MeshFeature::Rigged);
+/// // Minimal file with no vertices
+/// let bytes = b"CHAIR\x00\x00\x00\x00\x00\x00\x00";
+/// reader.read::<BasicVertex>(bytes).unwrap();
+/// ```
+///
+pub struct MeshReader<'a, A: Atlas> {
+	atlas: &'a A,
+	fallback: Option<&'a AtlasRegion>,
+	banned: MeshFeatures,
+	required: MeshFeatures
+}
+
+impl<'a, A: Atlas> MeshReader<'a, A> {
+	pub fn new<V: Vertex>(atlas: &'a A, fallback: Option<&str>) -> Self {
+		Self {
+			atlas,
+			fallback: match fallback.map(|name| atlas.get(name)) {
+				Some(region) => region,
+				None => {
+					error!("Atlas does not contain fallback texture, will error out if missing textures exist");
+					None
+				}
+			},
+			banned: MeshFeatures::default(),
+			// always require features present in the vertex format
+			required: V::features()
+		}
+	}
+
+	pub fn ban_feature(mut self, feature: MeshFeature) -> Self {
+		self.banned |= feature;
+		self
+	}
+
+	pub fn ban_features(mut self, features: MeshFeatures) -> Self {
+		self.banned |= features;
+		self
+	}
+
+	pub fn require_feature(mut self, feature: MeshFeature) -> Self {
+		self.required |= feature;
+		self
+	}
+
+	pub fn require_features(mut self, features: MeshFeatures) -> Self {
+		self.required |= features;
+		self
+	}
+
+	/// Extract vertices and indices from file contents
+	/// If using wgpu you can use `create` to also upload it to the gpu
+	pub fn read<V: Vertex>(&self, bytes: &[u8]) -> Result<(Vec<V>, Vec<Index>)> {
+		let mut bytes = Cursor::new(bytes);
+		let bytes = &mut bytes;
+		let mut header = [0; 5];
+		bytes.read_exact(&mut header)?;
+		if &header != b"CHAIR" {
+			return Err(Error::WrongHeader(header));
+		}
+
+		let version = bytes.read_u8()?;
+		debug!("Mesh version is {version}");
+		if version != 0 {
+			return Err(Error::UnknownVersion(version));
+		}
+
+		let features = bytes.read_u8()?;
+		// only safe since there are 8 features - none can be unused
+		let features = unsafe {
+			MeshFeatures::from_bits_unchecked(features)
+		};
+		debug!("Mesh features are {features:?}");
+
+		let banned = features & self.banned;
+		if !banned.is_empty() {
+			return Err(Error::BannedFeatures(banned));
+		}
+
+		let missing = self.required & !features;
+		if !missing.is_empty() {
+			return Err(Error::MissingFeatures(missing));
+		}
+
+		let colours = if features.contains(MeshFeature::Coloured) {
+			let len = bytes.read_u16::<LE>()?;
+			debug!("Have {len} colours");
+			(0..len)
+				.map(|_| {
+					Ok([chan(bytes)?, chan(bytes)?, chan(bytes)?, chan(bytes)?])
+				})
+				.collect::<Result<_>>()?
+		} else {
+			vec![]
+		};
+
+		let textures = if features.contains(MeshFeature::Textured) {
+			let len = bytes.read_u8()?;
+			debug!("Have {len} textures");
+			(0..len)
+				.map(|n| {
+					let len = bytes.read_u8()?;
+					let mut data = vec![0; len as usize];
+					bytes.read_exact(&mut data)?;
+					String::from_utf8(data)
+						.map_err(|_| Error::InvalidTextureName(n))
+				})
+				.map(|name| match name {
+					Ok(name) => match self.atlas.get(&name) {
+						Some(region) => Ok(region),
+						None => {
+							warn!("Mesh uses missing texture {name}");
+							if let Some(fallback) = self.fallback {
+								Ok(fallback)
+							} else {
+								Err(Error::MissingTexture(name))
+							}
+						}
+					},
+					Err(e) => Err(e)
+				})
+				.collect::<Result<_>>()?
+		} else {
+			vec![]
+		};
+
+		let read_pos_comp = if features.contains(MeshFeature::ShortPos) {
+			read_pos_short
+		} else {
+			read_pos_long
+		};
+
+		let read_col_index = if colours.len() > 255 {
+			read_col_u16
+		} else {
+			read_col_u8
+		};
+
+		let read_normal = if features.contains(MeshFeature::ShortNormals) {
+			read_normal_short
+		} else {
+			read_f32
+		};
+
+		let read_uv = if features.contains(MeshFeature::ShortUvs) {
+			read_uv_short
+		} else {
+			read_f32
+		};
+
+/*		let skeleton = if features.contains(MeshFeature::Rigged) {
+			// TODO: read skeleton
+			let len = bytes.read_u8()?;
+			(0..len)
+				.map(|_| bytes.read_f32()?)
+				.collect()
+		} else {
+			vec![]
+		};
+
+		let read_bone_indices = if skeleton.len() < 3 {
+			|| {
+				let bits = bytes.read_u8()?;
+				[
+					(bits & 0b11) as u32,
+					(bits & 0b0000_1100) as u32]
+			}
+		} else {
+			|| ()
+		};*/
+
+		// number of textured objects
+		let object_count = bytes.read_u8()?;
+		debug!("Have {object_count} objects");
+		let vertices = (0..object_count)
+			.flat_map(|n| {
+				let vertex_count = bytes.read_u32::<LE>()?;
+				debug!("Object {n} has {vertex_count} vertices");
+
+				// allow going outside 0.0 to 1.0 range by mapping positions
+				let (scale, offset) = if features.contains(MeshFeature::ShortPos) {
+					// 0 to 128 precision as opposed to 0 to 255, which cannot be divided evenly
+					// divided here for efficiency
+					([
+						bytes.read_f32::<LE>()? / 128.0,
+						bytes.read_f32::<LE>()? / 128.0,
+						bytes.read_f32::<LE>()? / 128.0
+					], [
+						bytes.read_f32::<LE>()?,
+						bytes.read_f32::<LE>()?,
+						bytes.read_f32::<LE>()?
+					])
+				} else {
+					([1.0; 3], [0.0; 3])
+				};
+
+				let region = if features.contains(MeshFeature::Textured) {
+					textures.get(bytes.read_u8()? as usize)
+						.ok_or_else(|| Error::UnknownTexture(n))?
+				} else {
+					&AtlasRegion {
+						xy: [0.0; 2],
+						x2y: [0.0; 2],
+						x2y2: [0.0; 2],
+						xy2: [0.0; 2]
+					}
+				};
+
+				(0..vertex_count).map(|_| {
+					let pos = [
+						read_pos_comp(bytes, scale[0], offset[0])?,
+						read_pos_comp(bytes, scale[1], offset[1])?,
+						read_pos_comp(bytes, scale[2], offset[2])?
+					];
+					let col = if features.contains(MeshFeature::Coloured) {
+						let index = read_col_index(bytes)?;
+						colours.get(index as usize).copied()
+							.ok_or_else(|| Error::UnknownColour(index))?
+					} else {
+						[1.0; 4]
+					};
+					let normals = if features.contains(MeshFeature::Normals) {
+						[
+							read_normal(bytes)?,
+							read_normal(bytes)?,
+							read_normal(bytes)?
+						]
+					} else {
+						[0.0; 3]
+					};
+					let uvs = if features.contains(MeshFeature::Textured) {
+						region.map_uvs(read_uv(bytes)?, read_uv(bytes)?)
+					} else {
+						[0.0; 2]
+					};
+/*					let (bones, weights) = if features.contains(MeshFeature::Rigged) {
+						let bones = read_bone_indices()?;
+						let weights = read_weights()?;
+						(bones, weights)
+					} else {
+						([0; 4], [0.0; 4]
+					};*/
+					trace!("Read vertex {pos:?}");
+					Ok(V::new(pos, col, normals, uvs, /*bones, weights*/))
+				}).collect::<Result<Vec<_>>>()
+			})
+			.flatten()
+			.collect::<Vec<V>>();
+
+		// use smallest index size that can hold all vertices
+		let read_index = if vertices.len() > 65535 {
+			read_index_u32
+		} else if vertices.len() > 255 {
+			read_index_u16
+		} else {
+			read_index_u8
+		};
+
+		let index_count = bytes.read_u32::<LE>()?;
+		debug!("Have {index_count} indices");
+		let indices = (0..index_count)
+			.map(|_| read_index(bytes))
+			.collect::<Result<_>>()?;
+
+		Ok((vertices, indices))
+	}
+
+	/// Read and create a mesh on the GPU
+	pub fn create<V: Vertex>(&self, device: &Device, bytes: &[u8]) -> Result<Mesh> {
+		let (vertices, indices) = self.read::<V>(bytes)?;
+		Ok(Mesh::new(device, &vertices, &indices))
+	}
+}
+
+fn read_pos_short(bytes: &mut Cursor<&[u8]>, scale: f32, offset: f32) -> Result<f32> {
+	Ok(bytes.read_u8()? as f32 * scale + offset)
+}
+fn read_pos_long(bytes: &mut Cursor<&[u8]>, _: f32, _: f32) -> Result<f32> {
+	read_f32(bytes)
+}
+
+fn chan(bytes: &mut Cursor<&[u8]>) -> Result<f32> {
+	Ok(bytes.read_u8()? as f32 / 255.0)
+}
+
+fn read_col_u8(bytes: &mut Cursor<&[u8]>) -> Result<u16> {
+	Ok(bytes.read_u8()? as u16)
+}
+fn read_col_u16(bytes: &mut Cursor<&[u8]>) -> Result<u16> {
+	Ok(bytes.read_u16::<LE>()?)
+}
+
+fn read_normal_short(bytes: &mut Cursor<&[u8]>) -> Result<f32> {
+	Ok(NORMAL[bytes.read_u8()? as usize])
+}
+fn read_f32(bytes: &mut Cursor<&[u8]>) -> Result<f32> {
+	Ok(bytes.read_f32::<LE>()?)
+}
+
+fn read_uv_short(bytes: &mut Cursor<&[u8]>) -> Result<f32> {
+	// 64 instead of 127 to be able to evenly divide
+	Ok(bytes.read_i8()? as f32 / 64.0)
+}
+
+fn read_index_u32(bytes: &mut Cursor<&[u8]>) -> Result<Index> {
+	Ok(bytes.read_u32::<LE>()?)
+}
+fn read_index_u16(bytes: &mut Cursor<&[u8]>) -> Result<Index> {
+	Ok(bytes.read_u16::<LE>()? as Index)
+}
+fn read_index_u8(bytes: &mut Cursor<&[u8]>) -> Result<Index> {
+	Ok(bytes.read_u8()? as Index)
+}
+
+const NORMAL: [f32; 256] = include!(concat!(env!("OUT_DIR"), "/normals.rs"));

+ 32 - 0
src/lib.rs

@@ -0,0 +1,32 @@
+#![feature(const_for)]
+#![feature(const_mut_refs)]
+#![feature(decl_macro)]
+// to fix funny bug when `cargo test`ing
+#![feature(rustc_attrs)]
+
+#![allow(clippy::tabs_in_doc_comments)]
+
+//! Efficient binary encoded mesh format
+//! Supports loading meshes that may contain colour, uvs, normals and bone weights
+//! Automatically maps uvs to atlas regions
+
+#[cfg(feature = "io")]
+mod atlas;
+mod features;
+#[cfg(feature = "io")]
+mod io;
+#[cfg(feature = "mesh")]
+mod mesh;
+mod vertex;
+
+#[cfg(feature = "io")]
+pub use crate::{
+	atlas::*,
+	io::*
+};
+#[cfg(feature = "mesh")]
+pub use crate::mesh::{Index, Mesh};
+pub use crate::{
+	features::*,
+	vertex::*
+};

+ 52 - 0
src/mesh.rs

@@ -0,0 +1,52 @@
+//! Single mesh
+
+use crate::vertex::*;
+
+use bytemuck::cast_slice;
+use wgpu::{
+	util::{BufferInitDescriptor, DeviceExt},
+	*
+};
+
+pub type Index = u32;
+
+pub const INDEX_FORMAT: IndexFormat = IndexFormat::Uint32;
+
+pub struct Mesh {
+	vertices: Buffer,
+	indices: Buffer,
+	index_count: u32
+}
+
+impl Mesh {
+	/// Create a new mesh from vertices and indices
+	pub fn new<V: Vertex>(device: &Device, vertex_data: &[V], index_data: &[Index]) -> Self {
+		let vertices = device.create_buffer_init(&BufferInitDescriptor {
+			label: Some("Mesh Vertices"),
+			contents: cast_slice(vertex_data),
+			usage: BufferUsages::VERTEX
+		});
+
+		let indices = device.create_buffer_init(&BufferInitDescriptor {
+			label: Some("Mesh Indices"),
+			contents: cast_slice(index_data),
+			usage: BufferUsages::INDEX
+		});
+
+		let index_count = index_data.len() as u32;
+
+		Self {
+			vertices,
+			indices,
+			index_count
+		}
+	}
+
+	/// Draw a single instance of this mesh
+	/// Drawing indexed or indirectly is prefered.
+	pub fn draw<'a>(&'a self, pass: &mut RenderPass<'a>) {
+		pass.set_vertex_buffer(0, self.vertices.slice(..));
+		pass.set_index_buffer(self.indices.slice(..), INDEX_FORMAT);
+		pass.draw_indexed(0..self.index_count, 0, 0..1);
+	}
+}

+ 68 - 0
src/vertex.rs

@@ -0,0 +1,68 @@
+//! Trait for mesh vertices that may use vertex components from the mesh file
+//! Minimum data is position, maximum includes uvs, colours and normals
+
+#[cfg(feature = "vertex-impls")]
+mod impls;
+
+#[cfg(feature = "vertex-impls")]
+pub use impls::*;
+
+use crate::features::*;
+
+use bytemuck::{Pod, Zeroable};
+#[cfg(feature = "wgpu")]
+use wgpu::*;
+
+/// The vertex trait implemented by vertex types
+/// # Example
+/// ```
+/// # use bytemuck::{Pod, Zeroable};
+/// # use chair::{features, MeshFeatures, Vertex};
+/// # use wgpu::*;
+/// #[derive(Clone, Copy, Pod, Zeroable)]
+/// #[repr(C)]
+/// pub struct BasicVertex {
+/// 	pub pos: [f32; 3]
+/// }
+///
+/// impl Vertex for BasicVertex {
+/// 	fn new(pos: [f32; 3], _: [f32; 4], _: [f32; 3], _: [f32; 2]) -> Self {
+/// 		Self {
+/// 			pos
+/// 		}
+/// 	}
+///
+///		fn features() -> MeshFeatures {
+///			features!()
+///		}
+///
+/// 	#[cfg(feature = "wgpu")]
+/// 	fn attribs() -> &'static [VertexAttribute] {
+/// 		&vertex_attr_array![
+/// 			0 => Float32x3
+/// 		]
+/// 	}
+/// }
+/// ```
+
+pub trait Vertex: Pod + Zeroable {
+	/// Create a new vertex, using at least position
+	fn new(pos: [f32; 3], col: [f32; 4], normals: [f32; 3], uvs: [f32; 2]) -> Self;
+
+	/// Return the features required by this vertex format
+	fn features() -> MeshFeatures;
+
+	/// Return the attributes for each field in this vertex format
+	#[cfg(feature = "wgpu")]
+	fn attribs() -> &'static [VertexAttribute];
+
+	/// Return the vertex buffer layout for this vertex format
+	#[cfg(feature = "wgpu")]
+	fn layout() -> VertexBufferLayout<'static> {
+		VertexBufferLayout {
+			array_stride: std::mem::size_of::<Self>() as BufferAddress,
+			step_mode: VertexStepMode::Vertex,
+			attributes: Self::attribs()
+		}
+	}
+}

+ 66 - 0
src/vertex/impls.rs

@@ -0,0 +1,66 @@
+//! Some implementations of Vertex that you might find useful
+
+use crate::{
+	features::*,
+	vertex::*
+};
+
+use bytemuck::{Pod, Zeroable};
+#[cfg(feature = "wgpu")]
+use wgpu::*;
+
+/// A vertex that just has position
+#[derive(Clone, Copy, Debug, Pod, Zeroable)]
+#[repr(C)]
+pub struct BasicVertex {
+	pub pos: [f32; 3]
+}
+
+impl Vertex for BasicVertex {
+	fn new(pos: [f32; 3], _: [f32; 4], _: [f32; 3], _: [f32; 2]) -> Self {
+		Self {
+			pos
+		}
+	}
+
+	fn features() -> MeshFeatures {
+		// nothing special
+		features!()
+	}
+
+	#[cfg(feature = "wgpu")]
+	fn attribs() -> &'static [VertexAttribute] {
+		&vertex_attrib_array![
+			0 => Float32x3
+		]
+	}
+}
+
+/// A vertex with position and colour
+#[derive(Clone, Copy, Debug, Pod, Zeroable)]
+#[repr(C)]
+pub struct ColouredVertex {
+	pub pos: [f32; 3],
+	pub col: [f32; 4]
+}
+
+impl Vertex for ColouredVertex {
+	fn new(pos: [f32; 3], col: [f32; 4], _: [f32; 3], _: [f32; 2]) -> Self {
+		Self {
+			pos,
+			col
+		}
+	}
+
+	fn features() -> MeshFeatures {
+		features!(Coloured)
+	}
+
+	#[cfg(feature = "wgpu")]
+	fn attribs() -> &'static [VertexAttribute] {
+		&vertex_attrib_array![
+			0 => Float32x3,
+			1 => Float32x4
+		]
+	}
+}