io.rs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. use crate::{
  2. atlas::*,
  3. features::*,
  4. mesh::*,
  5. vertex::*
  6. };
  7. use std::io::{Cursor, Read};
  8. use byteorder::*;
  9. use log::*;
  10. use thiserror::*;
  11. use wgpu::*;
  12. #[derive(Debug, Error)]
  13. pub enum Error {
  14. #[error("failed to read mesh")]
  15. Io(#[from] std::io::Error),
  16. #[error("wrong mesh header")]
  17. WrongHeader([u8; 5]),
  18. #[error("unknown mesh version {0}")]
  19. UnknownVersion(u8),
  20. #[error("mesh contains banned features: {0:?}")]
  21. BannedFeatures(MeshFeatures),
  22. #[error("mesh does not contain required features: {0:?}")]
  23. MissingFeatures(MeshFeatures),
  24. #[error("non-utf8 texture name #{0}")]
  25. InvalidTextureName(u8),
  26. #[error("atlas does not contain texture '{0}'")]
  27. MissingTexture(String),
  28. #[error("object {0} uses an unknown texture index")]
  29. UnknownTexture(u8),
  30. #[error("unknown colour index {0}")]
  31. UnknownColour(u16)
  32. }
  33. pub type Result<T> = std::result::Result<T, Error>;
  34. /// Configuration for reading meshes
  35. /// # Examples
  36. /// ```
  37. /// # use chair::*;
  38. /// # struct EmptyAtlas;
  39. /// # impl Atlas for EmptyAtlas { fn get(&self, name: &str) -> Option<&AtlasRegion> { None } }
  40. /// # let atlas = EmptyAtlas;
  41. /// let reader = MeshReader::new::<BasicVertex>(&atlas, None)
  42. /// // refuse to load any meshes that can be animated, even though the information would be discarded
  43. /// .ban_feature(MeshFeature::Rigged);
  44. /// // Minimal file with no vertices
  45. /// let bytes = b"CHAIR\x00\x00\x00\x00\x00\x00\x00";
  46. /// reader.read::<BasicVertex>(bytes).unwrap();
  47. /// ```
  48. ///
  49. pub struct MeshReader<'a, A: Atlas> {
  50. atlas: &'a A,
  51. fallback: Option<&'a AtlasRegion>,
  52. banned: MeshFeatures,
  53. required: MeshFeatures
  54. }
  55. impl<'a, A: Atlas> MeshReader<'a, A> {
  56. pub fn new<V: Vertex>(atlas: &'a A, fallback: Option<&str>) -> Self {
  57. Self {
  58. atlas,
  59. fallback: match fallback.map(|name| atlas.get(name)) {
  60. Some(region) => region,
  61. None => {
  62. error!("Atlas does not contain fallback texture, will error out if missing textures exist");
  63. None
  64. }
  65. },
  66. banned: MeshFeatures::default(),
  67. // always require features present in the vertex format
  68. required: V::features()
  69. }
  70. }
  71. pub fn ban_feature(mut self, feature: MeshFeature) -> Self {
  72. self.banned |= feature;
  73. self
  74. }
  75. pub fn ban_features(mut self, features: MeshFeatures) -> Self {
  76. self.banned |= features;
  77. self
  78. }
  79. pub fn require_feature(mut self, feature: MeshFeature) -> Self {
  80. self.required |= feature;
  81. self
  82. }
  83. pub fn require_features(mut self, features: MeshFeatures) -> Self {
  84. self.required |= features;
  85. self
  86. }
  87. /// Extract vertices and indices from file contents
  88. /// If using wgpu you can use `create` to also upload it to the gpu
  89. // TODO: remove debug
  90. pub fn read<V: Vertex + std::fmt::Debug>(&self, bytes: &[u8]) -> Result<(Vec<V>, Vec<Index>)> {
  91. let mut bytes = Cursor::new(bytes);
  92. let bytes = &mut bytes;
  93. let mut header = [0; 5];
  94. bytes.read_exact(&mut header)?;
  95. if &header != b"CHAIR" {
  96. return Err(Error::WrongHeader(header));
  97. }
  98. let version = bytes.read_u8()?;
  99. debug!("Mesh version is {version}");
  100. if version != 0 {
  101. return Err(Error::UnknownVersion(version));
  102. }
  103. let features = bytes.read_u8()?;
  104. // only safe since there are 8 features - none can be unused
  105. let features = unsafe {
  106. MeshFeatures::from_bits_unchecked(features)
  107. };
  108. debug!("Mesh features are {features:?}");
  109. let banned = features & self.banned;
  110. if !banned.is_empty() {
  111. return Err(Error::BannedFeatures(banned));
  112. }
  113. let missing = self.required & !features;
  114. if !missing.is_empty() {
  115. return Err(Error::MissingFeatures(missing));
  116. }
  117. let colours = if features.contains(MeshFeature::Coloured) {
  118. let len = bytes.read_u16::<LE>()?;
  119. debug!("Have {len} colours");
  120. (0..len)
  121. .map(|_| {
  122. Ok([chan(bytes)?, chan(bytes)?, chan(bytes)?, chan(bytes)?])
  123. })
  124. .collect::<Result<_>>()?
  125. } else {
  126. vec![]
  127. };
  128. let textures = if features.contains(MeshFeature::Textured) {
  129. let len = bytes.read_u8()?;
  130. debug!("Have {len} textures");
  131. (0..len)
  132. .map(|n| {
  133. let len = bytes.read_u8()?;
  134. let mut data = vec![0; len as usize];
  135. bytes.read_exact(&mut data)?;
  136. String::from_utf8(data)
  137. .map_err(|_| Error::InvalidTextureName(n))
  138. })
  139. .map(|name| match name {
  140. Ok(name) => match self.atlas.get(&name) {
  141. Some(region) => Ok(region),
  142. None => {
  143. warn!("Mesh uses missing texture {name}");
  144. if let Some(fallback) = self.fallback {
  145. Ok(fallback)
  146. } else {
  147. Err(Error::MissingTexture(name))
  148. }
  149. }
  150. },
  151. Err(e) => Err(e)
  152. })
  153. .collect::<Result<_>>()?
  154. } else {
  155. vec![]
  156. };
  157. let read_pos_comp = if features.contains(MeshFeature::ShortPos) {
  158. read_pos_short
  159. } else {
  160. read_pos_long
  161. };
  162. let read_col_index = if colours.len() > 255 {
  163. read_col_u16
  164. } else {
  165. read_col_u8
  166. };
  167. let read_normal = if features.contains(MeshFeature::ShortNormals) {
  168. read_normal_short
  169. } else {
  170. read_f32
  171. };
  172. let read_uv = if features.contains(MeshFeature::ShortUvs) {
  173. read_uv_short
  174. } else {
  175. read_f32
  176. };
  177. /* let skeleton = if features.contains(MeshFeature::Rigged) {
  178. // TODO: read skeleton
  179. let len = bytes.read_u8()?;
  180. (0..len)
  181. .map(|_| bytes.read_f32()?)
  182. .collect()
  183. } else {
  184. vec![]
  185. };
  186. let read_bone_indices = if skeleton.len() < 3 {
  187. || {
  188. let bits = bytes.read_u8()?;
  189. [
  190. (bits & 0b11) as u32,
  191. (bits & 0b0000_1100) as u32]
  192. }
  193. } else {
  194. || ()
  195. };*/
  196. // number of textured objects
  197. let object_count = bytes.read_u8()?;
  198. debug!("Have {object_count} objects");
  199. let vertices = (0..object_count)
  200. .flat_map(|n| {
  201. let vertex_count = bytes.read_u32::<LE>()?;
  202. debug!("Object {n} has {vertex_count} vertices");
  203. // allow going outside 0.0 to 1.0 range by mapping positions
  204. let (scale, offset) = if features.contains(MeshFeature::ShortPos) {
  205. // 0 to 128 precision as opposed to 0 to 255, which cannot be divided evenly
  206. // divided here for efficiency
  207. ([
  208. bytes.read_f32::<LE>()? / 128.0,
  209. bytes.read_f32::<LE>()? / 128.0,
  210. bytes.read_f32::<LE>()? / 128.0
  211. ], [
  212. bytes.read_f32::<LE>()?,
  213. bytes.read_f32::<LE>()?,
  214. bytes.read_f32::<LE>()?
  215. ])
  216. } else {
  217. ([1.0; 3], [0.0; 3])
  218. };
  219. debug!("Scale is {scale:?}, offset is {offset:?}");
  220. let region = if features.contains(MeshFeature::Textured) {
  221. textures.get(bytes.read_u8()? as usize)
  222. .ok_or_else(|| Error::UnknownTexture(n))?
  223. } else {
  224. &AtlasRegion {
  225. xy: [0.0; 2],
  226. x2y: [0.0; 2],
  227. x2y2: [0.0; 2],
  228. xy2: [0.0; 2]
  229. }
  230. };
  231. (0..vertex_count).map(|_| {
  232. let pos = [
  233. read_pos_comp(bytes, scale[0], offset[0])?,
  234. read_pos_comp(bytes, scale[1], offset[1])?,
  235. read_pos_comp(bytes, scale[2], offset[2])?
  236. ];
  237. let col = if features.contains(MeshFeature::Coloured) {
  238. let index = read_col_index(bytes)?;
  239. colours.get(index as usize).copied()
  240. .ok_or_else(|| Error::UnknownColour(index))?
  241. } else {
  242. [1.0; 4]
  243. };
  244. let normals = if features.contains(MeshFeature::Normals) {
  245. [
  246. read_normal(bytes)?,
  247. read_normal(bytes)?,
  248. read_normal(bytes)?
  249. ]
  250. } else {
  251. [0.0; 3]
  252. };
  253. let uvs = if features.contains(MeshFeature::Textured) {
  254. region.map_uvs(read_uv(bytes)?, read_uv(bytes)?)
  255. } else {
  256. [0.0; 2]
  257. };
  258. /* let (bones, weights) = if features.contains(MeshFeature::Rigged) {
  259. let bones = read_bone_indices()?;
  260. let weights = read_weights()?;
  261. (bones, weights)
  262. } else {
  263. ([0; 4], [0.0; 4]
  264. };*/
  265. trace!("Read vertex {pos:?}");
  266. Ok(V::new(pos, col, normals, uvs, /*bones, weights*/))
  267. }).collect::<Result<Vec<_>>>()
  268. })
  269. .flatten()
  270. .collect::<Vec<V>>();
  271. // use smallest index size that can hold all vertices
  272. let read_index = if vertices.len() > 65535 {
  273. read_index_u32
  274. } else if vertices.len() > 255 {
  275. read_index_u16
  276. } else {
  277. read_index_u8
  278. };
  279. let index_count = bytes.read_u32::<LE>()?;
  280. debug!("Have {index_count} indices");
  281. let indices = (0..index_count)
  282. .map(|_| read_index(bytes))
  283. .collect::<Result<_>>()?;
  284. Ok((vertices, indices))
  285. }
  286. /// Read and create a mesh on the GPU
  287. pub fn create<V: Vertex + std::fmt::Debug>(&self, device: &Device, bytes: &[u8]) -> Result<Mesh> {
  288. let (vertices, indices) = self.read::<V>(bytes)?;
  289. Ok(Mesh::new(device, &vertices, &indices))
  290. }
  291. }
  292. fn read_pos_short(bytes: &mut Cursor<&[u8]>, scale: f32, offset: f32) -> Result<f32> {
  293. Ok(bytes.read_u8()? as f32 * scale + offset)
  294. }
  295. fn read_pos_long(bytes: &mut Cursor<&[u8]>, _: f32, _: f32) -> Result<f32> {
  296. read_f32(bytes)
  297. }
  298. fn chan(bytes: &mut Cursor<&[u8]>) -> Result<f32> {
  299. Ok(bytes.read_u8()? as f32 / 255.0)
  300. }
  301. fn read_col_u8(bytes: &mut Cursor<&[u8]>) -> Result<u16> {
  302. Ok(bytes.read_u8()? as u16)
  303. }
  304. fn read_col_u16(bytes: &mut Cursor<&[u8]>) -> Result<u16> {
  305. Ok(bytes.read_u16::<LE>()?)
  306. }
  307. fn read_normal_short(bytes: &mut Cursor<&[u8]>) -> Result<f32> {
  308. Ok(NORMAL[bytes.read_u8()? as usize])
  309. }
  310. fn read_f32(bytes: &mut Cursor<&[u8]>) -> Result<f32> {
  311. Ok(bytes.read_f32::<LE>()?)
  312. }
  313. fn read_uv_short(bytes: &mut Cursor<&[u8]>) -> Result<f32> {
  314. // 128 instead of 255 to be able to evenly divide
  315. Ok(bytes.read_u8()? as f32 / 128.0)
  316. }
  317. fn read_index_u32(bytes: &mut Cursor<&[u8]>) -> Result<Index> {
  318. Ok(bytes.read_u32::<LE>()?)
  319. }
  320. fn read_index_u16(bytes: &mut Cursor<&[u8]>) -> Result<Index> {
  321. Ok(bytes.read_u16::<LE>()? as Index)
  322. }
  323. fn read_index_u8(bytes: &mut Cursor<&[u8]>) -> Result<Index> {
  324. Ok(bytes.read_u8()? as Index)
  325. }
  326. const NORMAL: [f32; 256] = include!(concat!(env!("OUT_DIR"), "/normals.rs"));