From e61e15770ec679fa68118f069ab3c8bdfab510a6 Mon Sep 17 00:00:00 2001 From: Timothy Warren Date: Thu, 20 Apr 2023 11:06:52 -0400 Subject: [PATCH] Deduplicate vertices for model rendering --- src/app/data.rs | 13 ++++++++++--- src/app/structs.rs | 22 ++++++++++++++++++++++ 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/src/app/data.rs b/src/app/data.rs index cfc866f..4787193 100644 --- a/src/app/data.rs +++ b/src/app/data.rs @@ -8,7 +8,6 @@ use ::std::collections::HashMap; use ::std::collections::HashSet; use ::std::ffi::CStr; use ::std::fs::File; -use ::std::hash::{Hash, Hasher}; use ::std::io::BufReader; use ::std::os::raw::c_void; use ::std::ptr::copy_nonoverlapping as memcpy; @@ -926,6 +925,8 @@ impl AppData { |_| Ok(Default::default()), )?; + let mut unique_vertices = HashMap::new(); + for model in &models { for index in &model.mesh.indices { let pos_offset = (3 * index) as usize; @@ -944,8 +945,14 @@ impl AppData { ), ); - self.vertices.push(vertex); - self.indices.push(self.indices.len() as u32); + if let Some(index) = unique_vertices.get(&vertex) { + self.indices.push(*index as u32); + } else { + let index = self.vertices.len(); + unique_vertices.insert(vertex, index); + self.vertices.push(vertex); + self.indices.push(index as u32); + } } } diff --git a/src/app/structs.rs b/src/app/structs.rs index 4125466..cf0bcd3 100644 --- a/src/app/structs.rs +++ b/src/app/structs.rs @@ -1,6 +1,7 @@ use ::anyhow::{anyhow, Result}; use ::log::*; use ::nalgebra_glm as glm; +use ::std::hash::{Hash, Hasher}; use ::std::mem::size_of; use ::thiserror::Error; use ::vulkanalia::prelude::v1_0::*; @@ -145,6 +146,27 @@ impl Vertex { } } +impl PartialEq for Vertex { + fn eq(&self, other: &Self) -> bool { + self.pos == other.pos && self.color == other.color && self.tex_coord == other.tex_coord + } +} + +impl Eq for Vertex {} + +impl Hash for Vertex { + fn hash(&self, state: &mut H) { + self.pos[0].to_bits().hash(state); + self.pos[1].to_bits().hash(state); + self.pos[2].to_bits().hash(state); + self.color[0].to_bits().hash(state); + self.color[1].to_bits().hash(state); + self.color[2].to_bits().hash(state); + self.tex_coord[0].to_bits().hash(state); + self.tex_coord[1].to_bits().hash(state); + } +} + // ---------------------------------------------------------------------------- // Resource Descriptors // ----------------------------------------------------------------------------