use new material loading

This commit is contained in:
Robin Appelman 2023-12-19 17:21:12 +01:00
commit 585a485031
10 changed files with 266 additions and 491 deletions

View file

@ -1,20 +0,0 @@
use crate::loader::LoadError;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum Error {
#[error(transparent)]
Three(#[from] Box<dyn std::error::Error>),
#[error(transparent)]
Mdl(#[from] vmdl::ModelError),
#[error(transparent)]
IO(#[from] std::io::Error),
#[error(transparent)]
Loader(#[from] LoadError),
#[error(transparent)]
Vtf(#[from] vtf::Error),
#[error("{0}")]
Other(&'static str),
#[error("Skin index out of bounds: {0}, model only has {1} skins")]
SkinOutOfBounds(u16, u16),
}

View file

@ -1,118 +0,0 @@
use std::fmt::{Debug, Formatter};
use std::fs;
use std::path::PathBuf;
use steamlocate::SteamDir;
use thiserror::Error;
use tracing::{debug, error, info};
use vpk::VPK;
#[derive(Debug, Error)]
pub enum LoadError {
#[error("{0}")]
Other(&'static str),
#[error(transparent)]
IO(#[from] std::io::Error),
}
impl From<&'static str> for LoadError {
fn from(e: &'static str) -> Self {
LoadError::Other(e)
}
}
pub struct Loader {
tf_dir: PathBuf,
download: PathBuf,
vpks: Vec<VPK>,
}
impl Debug for Loader {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Loader")
.field("tf_dir", &self.tf_dir)
.finish_non_exhaustive()
}
}
impl Loader {
pub fn new() -> Result<Self, LoadError> {
let tf_dir = SteamDir::locate()
.ok_or("Can't find steam directory")?
.app(&440)
.ok_or("Can't find tf2 directory")?
.path
.join("tf");
let download = tf_dir.join("download");
let vpks = tf_dir
.read_dir()?
.filter_map(|item| item.ok())
.filter_map(|item| Some(item.path().to_str()?.to_string()))
.filter(|path| path.ends_with("dir.vpk"))
.map(|path| vpk::from_path(&path))
.filter_map(|res| res.ok())
.collect();
Ok(Loader {
tf_dir,
download,
vpks,
})
}
#[tracing::instrument]
pub fn exists(&self, name: &str) -> bool {
debug!("loading {}", name);
if name.ends_with("bsp") {
let path = self.tf_dir.join(name);
if path.exists() {
return true;
}
let path = self.download.join(name);
if path.exists() {
return true;
}
}
for vpk in self.vpks.iter() {
if vpk.tree.contains_key(name) {
return true;
}
}
false
}
#[tracing::instrument]
pub fn load(&self, name: &str) -> Result<Vec<u8>, LoadError> {
debug!("loading {}", name);
if name.ends_with("bsp") {
let path = self.tf_dir.join(name);
if path.exists() {
debug!("found in tf2 dir");
return Ok(fs::read(path)?);
}
let path = self.download.join(name);
if path.exists() {
debug!("found in download dir");
return Ok(fs::read(path)?);
}
}
for vpk in self.vpks.iter() {
if let Some(entry) = vpk.tree.get(name) {
let data = entry.get()?.into_owned();
debug!("got {} bytes from vpk", data.len());
return Ok(data);
}
}
info!("Failed to find {} in vpk", name);
Err(LoadError::Other("Can't find file in vpks"))
}
pub fn load_from_paths(&self, name: &str, paths: &[String]) -> Result<Vec<u8>, LoadError> {
for path in paths {
if self.exists(&format!("{}{}", path, name)) {
return self.load(&format!("{}{}", path, name));
}
}
error!("Failed to find {} in vpk paths: {}", name, paths.join(", "));
Err(LoadError::Other("Can't find file in vpks"))
}
}

View file

@ -1,6 +1,9 @@
mod convert;
#[path = "../common/error.rs"]
mod error;
#[path = "../common/loader.rs"]
mod loader;
#[path = "../common/materials.rs"]
mod material;
use gltf_json as json;

View file

@ -1,162 +0,0 @@
use crate::loader::Loader;
use crate::Error;
use image::DynamicImage;
use std::str::FromStr;
use steamy_vdf::{Entry, Table};
use tracing::error;
use vtf::vtf::VTF;
fn get_path(vmt: &Entry, name: &str) -> Option<String> {
Some(vmt.lookup(name)?.as_str()?.replace('\\', "/"))
}
pub fn load_material_fallback(name: &str, search_dirs: &[String], loader: &Loader) -> MaterialData {
match load_material(name, search_dirs, loader) {
Ok(mat) => mat,
Err(e) => {
error!(error = ?e, "failed to load material");
MaterialData {
name: name.into(),
color: [255, 0, 255, 255],
..MaterialData::default()
}
}
}
}
#[derive(Default, Debug)]
pub struct MaterialData {
pub name: String,
pub color: [u8; 4],
pub texture: Option<TextureData>,
pub alpha_test: Option<f32>,
pub bump_map: Option<TextureData>,
pub translucent: bool,
}
#[derive(Debug)]
pub struct TextureData {
pub name: String,
pub image: DynamicImage,
}
pub fn load_material(
name: &str,
search_dirs: &[String],
loader: &Loader,
) -> Result<MaterialData, Error> {
let dirs = search_dirs
.iter()
.map(|dir| {
format!(
"materials/{}",
dir.to_ascii_lowercase().trim_start_matches("/")
)
})
.collect::<Vec<_>>();
let path = format!("{}.vmt", name.to_ascii_lowercase().trim_end_matches(".vmt"));
let raw = loader.load_from_paths(&path, &dirs)?;
let vmt = parse_vdf(&raw)?;
let vmt = resolve_vmt_patch(vmt, loader)?;
let table = vmt
.values()
.next()
.cloned()
.ok_or(Error::Other("empty vmt"))?;
let base_texture = get_path(&table, "$basetexture").ok_or(Error::Other("no $basetexture"))?;
let translucent = table
.lookup("$translucent")
.map(|val| val.as_str() == Some("1"))
.unwrap_or_default();
let glass = table
.lookup("$surfaceprop")
.map(|val| val.as_str() == Some("glass"))
.unwrap_or_default();
let alpha_test = table
.lookup("$alphatest")
.map(|val| val.as_str() == Some("1"))
.unwrap_or_default();
let texture = load_texture(
base_texture.as_str(),
loader,
translucent | glass | alpha_test,
)?;
let alpha_cutout = table
.lookup("$alphatestreference")
.and_then(Entry::as_str)
.and_then(|val| f32::from_str(val).ok())
.unwrap_or(1.0);
let bump_map = get_path(&table, "$bumpmap").and_then(|path| {
Some(TextureData {
image: load_texture(&path, loader, true).ok()?,
name: path,
})
});
Ok(MaterialData {
color: [255; 4],
name: name.into(),
texture: Some(TextureData {
name: base_texture,
image: texture,
}),
bump_map,
alpha_test: alpha_test.then_some(alpha_cutout),
translucent: translucent | glass | alpha_test,
})
}
fn parse_vdf(bytes: &[u8]) -> Result<Table, Error> {
let bytes = bytes.to_ascii_lowercase();
let mut reader = steamy_vdf::Reader::from(bytes.as_slice());
Table::load(&mut reader).map_err(|e| {
println!("{}", String::from_utf8_lossy(&bytes));
error!(
source = String::from_utf8_lossy(&bytes).to_string(),
error = ?e,
"failed to parse vmt"
);
Error::Other("failed to parse vdf")
})
}
fn load_texture(name: &str, loader: &Loader, _alpha: bool) -> Result<DynamicImage, Error> {
let path = format!(
"materials/{}.vtf",
name.trim_end_matches(".vtf").trim_start_matches('/')
);
let mut raw = loader.load(&path)?;
let vtf = VTF::read(&mut raw)?;
let image = vtf.highres_image.decode(0)?;
Ok(image)
}
fn resolve_vmt_patch(vmt: Table, loader: &Loader) -> Result<Table, Error> {
if vmt.len() != 1 {
panic!("vmt with more than 1 item?");
}
if let Some(Entry::Table(patch)) = vmt.get("patch") {
let include = patch
.get("include")
.expect("no include in patch")
.as_value()
.expect("include is not a value")
.to_string();
let _replace = patch
.get("replace")
.expect("no replace in patch")
.as_table()
.expect("replace is not a table");
let included_raw = loader.load(&include.to_ascii_lowercase())?;
// todo actually patch
parse_vdf(&included_raw)
} else {
Ok(vmt)
}
}