use crate::colour::ColourSpace;
use crate::data::texture::{TextureRequirement, TextureRole};
use crate::plugin::material::{
MATERIAL_PLUGIN_MAX_PARAMS, MATERIAL_PLUGIN_MAX_TEXTURES, ParamValue,
};
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ItemSettings {
pub hidden: bool,
pub unlit: bool,
pub opacity: f32,
pub colour: Option<crate::colour::Colour>,
pub wireframe: bool,
pub pick_id: crate::ids::PickId,
pub selected: bool,
pub cast_shadows: bool,
pub receive_shadows: bool,
pub ignore_clip: bool,
pub custom_data: [f32; 8],
pub visibility_mask: u32,
#[cfg_attr(feature = "serde", serde(default))]
pub draw_priority: i8,
#[cfg_attr(feature = "serde", serde(default))]
pub blend_order: Option<u16>,
}
impl Default for ItemSettings {
fn default() -> Self {
Self {
hidden: false,
unlit: false,
opacity: 1.0,
colour: None,
wireframe: false,
pick_id: crate::ids::PickId::NONE,
selected: false,
cast_shadows: true,
receive_shadows: true,
ignore_clip: false,
custom_data: [0.0; 8],
visibility_mask: !0,
draw_priority: 0,
blend_order: None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum ShadingModel {
Phong,
Pbr,
Matcap(crate::ids::MatcapId),
Flat,
}
impl Default for ShadingModel {
fn default() -> Self {
Self::Phong
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ParamVisMode {
Checker = 1,
Grid = 2,
LocalChecker = 3,
LocalRadial = 4,
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ParamVis {
pub mode: ParamVisMode,
pub scale: f32,
}
impl Default for ParamVis {
fn default() -> Self {
Self {
mode: ParamVisMode::Checker,
scale: 8.0,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum BackfacePattern {
Checker = 0,
Hatching = 1,
Crosshatch = 2,
Stripes = 3,
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PatternConfig {
pub pattern: BackfacePattern,
pub colour: crate::colour::Colour,
pub scale: f32,
}
impl Default for PatternConfig {
fn default() -> Self {
Self {
pattern: BackfacePattern::Checker,
colour: crate::colour::Colour::linear_rgb(1.0, 0.5, 0.0),
scale: 20.0,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum BackfacePolicy {
Cull,
Identical,
DifferentColour(crate::colour::Colour),
Tint(f32),
Pattern(PatternConfig),
}
impl Default for BackfacePolicy {
fn default() -> Self {
BackfacePolicy::Cull
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum AlphaMode {
Opaque,
Mask(f32),
Blend,
BlendPremultiplied,
}
impl Default for AlphaMode {
fn default() -> Self {
AlphaMode::Opaque
}
}
pub const MATERIAL_TEXTURE_SLOTS: usize = 5;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum TextureSlot {
Albedo = 0,
Normal = 1,
Ao = 2,
MetallicRoughness = 3,
Emissive = 4,
}
impl TextureSlot {
pub const ALL: [TextureSlot; MATERIAL_TEXTURE_SLOTS] = [
TextureSlot::Albedo,
TextureSlot::Normal,
TextureSlot::Ao,
TextureSlot::MetallicRoughness,
TextureSlot::Emissive,
];
pub const fn index(self) -> usize {
self as usize
}
pub const fn requirement(self) -> TextureRequirement {
match self {
TextureSlot::Albedo => TextureRequirement::colour("Material::texture_id"),
TextureSlot::Normal => TextureRequirement::normal_map("Material::normal_map_id"),
TextureSlot::Ao => TextureRequirement::linear("Material::ao_map_id"),
TextureSlot::MetallicRoughness => {
TextureRequirement::linear("Material::metallic_roughness_texture_id")
}
TextureSlot::Emissive => TextureRequirement::colour("Material::emissive_texture_id"),
}
}
pub const fn colour_space(self) -> ColourSpace {
self.requirement().colour_space()
}
pub const fn role(self) -> TextureRole {
self.requirement().role()
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct UvTransform {
pub offset: [f32; 2],
pub scale: [f32; 2],
pub rotation: f32,
pub uv_set: u32,
}
impl Default for UvTransform {
fn default() -> Self {
UvTransform {
offset: [0.0, 0.0],
scale: [1.0, 1.0],
rotation: 0.0,
uv_set: 0,
}
}
}
impl UvTransform {
pub const IDENTITY: UvTransform = UvTransform {
offset: [0.0, 0.0],
scale: [1.0, 1.0],
rotation: 0.0,
uv_set: 0,
};
pub fn from_rotation(radians: f32) -> Self {
UvTransform {
rotation: radians,
..UvTransform::IDENTITY
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum WrapMode {
#[default]
Repeat,
ClampToEdge,
MirrorRepeat,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum TextureFilter {
Nearest,
#[default]
Linear,
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SamplerKey {
pub wrap_u: WrapMode,
pub wrap_v: WrapMode,
pub filter: TextureFilter,
pub anisotropy: u16,
pub lod_bias: f32,
}
impl Default for SamplerKey {
fn default() -> Self {
SamplerKey {
wrap_u: WrapMode::Repeat,
wrap_v: WrapMode::Repeat,
filter: TextureFilter::Linear,
anisotropy: 1,
lod_bias: 0.0,
}
}
}
impl SamplerKey {
pub fn clamp() -> Self {
SamplerKey {
wrap_u: WrapMode::ClampToEdge,
wrap_v: WrapMode::ClampToEdge,
..SamplerKey::default()
}
}
pub fn nearest() -> Self {
SamplerKey {
filter: TextureFilter::Nearest,
..SamplerKey::default()
}
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Material {
pub base_colour: crate::colour::Colour,
pub ambient: f32,
pub diffuse: f32,
pub specular: f32,
pub shininess: f32,
pub metallic: f32,
pub roughness: f32,
pub texture_id: Option<crate::ids::TextureId>,
pub normal_map_id: Option<crate::ids::TextureId>,
#[cfg_attr(feature = "serde", serde(default = "default_normal_strength"))]
pub normal_strength: f32,
pub ao_map_id: Option<crate::ids::TextureId>,
pub metallic_roughness_texture_id: Option<crate::ids::TextureId>,
pub emissive: crate::colour::Colour,
pub emissive_strength: f32,
#[cfg_attr(feature = "serde", serde(default = "default_emissive_exposure_weight"))]
pub emissive_exposure_weight: f32,
pub emissive_texture_id: Option<crate::ids::TextureId>,
pub alpha_mode: AlphaMode,
pub shading_model: ShadingModel,
pub param_vis: Option<ParamVis>,
pub backface_policy: BackfacePolicy,
pub uv_offset: [f32; 2],
pub uv_scale: [f32; 2],
pub uv_rotation: f32,
pub texture_transforms: [Option<UvTransform>; MATERIAL_TEXTURE_SLOTS],
pub sampler: [Option<SamplerKey>; MATERIAL_TEXTURE_SLOTS],
pub ao_range: [f32; 2],
pub metallic_range: [f32; 2],
pub roughness_range: [f32; 2],
#[cfg_attr(feature = "serde", serde(default))]
pub shading_plugin: Option<MaterialPluginId>,
#[cfg_attr(feature = "serde", serde(default))]
pub plugin_params: PluginParams,
#[cfg_attr(feature = "serde", serde(default))]
pub plugin_textures: [Option<crate::ids::TextureId>; MATERIAL_PLUGIN_MAX_TEXTURES],
#[cfg_attr(feature = "serde", serde(default = "default_reflectance"))]
pub reflectance: f32,
#[cfg_attr(feature = "serde", serde(default = "default_specular_factor"))]
pub specular_factor: f32,
#[cfg_attr(feature = "serde", serde(default = "default_specular_colour"))]
pub specular_colour: crate::colour::Colour,
#[cfg_attr(feature = "serde", serde(default = "default_ior"))]
pub ior: f32,
#[cfg_attr(feature = "serde", serde(default))]
pub clearcoat: f32,
#[cfg_attr(feature = "serde", serde(default))]
pub clearcoat_roughness: f32,
#[cfg_attr(feature = "serde", serde(default = "default_sheen_colour"))]
pub sheen_colour: crate::colour::Colour,
#[cfg_attr(feature = "serde", serde(default))]
pub sheen_roughness: f32,
#[cfg_attr(feature = "serde", serde(default))]
pub anisotropy: f32,
#[cfg_attr(feature = "serde", serde(default))]
pub anisotropy_rotation: f32,
#[cfg_attr(feature = "serde", serde(default))]
pub transmission: f32,
#[cfg_attr(feature = "serde", serde(default))]
pub thickness: f32,
#[cfg_attr(feature = "serde", serde(default = "default_attenuation_colour"))]
pub attenuation_colour: crate::colour::Colour,
#[cfg_attr(feature = "serde", serde(default = "default_attenuation_distance"))]
pub attenuation_distance: f32,
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PluginParams {
names: [u64; MATERIAL_PLUGIN_MAX_PARAMS],
values: [ParamValue; MATERIAL_PLUGIN_MAX_PARAMS],
len: u8,
overflowed: bool,
}
impl Default for PluginParams {
fn default() -> Self {
Self {
names: [0; MATERIAL_PLUGIN_MAX_PARAMS],
values: [ParamValue::F32(0.0); MATERIAL_PLUGIN_MAX_PARAMS],
len: 0,
overflowed: false,
}
}
}
impl PluginParams {
pub fn set(&mut self, name: &str, value: impl Into<ParamValue>) {
let key = param_name_hash(name);
let value = value.into();
let n = self.len as usize;
if let Some(i) = self.names[..n].iter().position(|&k| k == key) {
self.values[i] = value;
} else if n < MATERIAL_PLUGIN_MAX_PARAMS {
self.names[n] = key;
self.values[n] = value;
self.len += 1;
} else {
self.overflowed = true;
}
}
pub fn get(&self, name: &str) -> Option<ParamValue> {
let key = param_name_hash(name);
self.iter().find(|(k, _)| *k == key).map(|(_, v)| v)
}
pub fn unset(&mut self, name: &str) {
let key = param_name_hash(name);
let n = self.len as usize;
if let Some(i) = self.names[..n].iter().position(|&k| k == key) {
self.names.copy_within(i + 1..n, i);
self.values.copy_within(i + 1..n, i);
self.len -= 1;
}
}
pub fn len(&self) -> usize {
self.len as usize
}
pub fn is_empty(&self) -> bool {
self.len == 0
}
#[doc(hidden)]
pub fn iter(&self) -> impl Iterator<Item = (u64, ParamValue)> + '_ {
let n = self.len as usize;
self.names[..n]
.iter()
.copied()
.zip(self.values[..n].iter().copied())
}
#[doc(hidden)]
pub fn overflowed(&self) -> bool {
self.overflowed
}
}
#[doc(hidden)]
pub fn param_name_hash(name: &str) -> u64 {
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
for b in name.bytes() {
h ^= b as u64;
h = h.wrapping_mul(0x0000_0100_0000_01b3);
}
h
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct MaterialPluginId {
pub(crate) plugin: u32,
#[cfg_attr(feature = "serde", serde(default))]
pub(crate) generation: u32,
}
impl MaterialPluginId {
pub fn plugin_index(&self) -> u32 {
self.plugin
}
pub fn generation(&self) -> u32 {
self.generation
}
#[doc(hidden)]
pub fn from_index(plugin: u32) -> Self {
Self::from_parts(plugin, 0)
}
#[doc(hidden)]
pub fn from_parts(plugin: u32, generation: u32) -> Self {
Self { plugin, generation }
}
}
#[cfg(feature = "serde")]
fn default_normal_strength() -> f32 {
1.0
}
#[cfg(feature = "serde")]
fn default_reflectance() -> f32 {
0.5
}
#[cfg(feature = "serde")]
fn default_specular_factor() -> f32 {
1.0
}
#[cfg(feature = "serde")]
fn default_specular_colour() -> crate::colour::Colour {
crate::colour::Colour::linear_rgb(1.0, 1.0, 1.0)
}
#[cfg(feature = "serde")]
fn default_emissive_exposure_weight() -> f32 {
1.0
}
#[cfg(feature = "serde")]
fn default_ior() -> f32 {
1.5
}
#[cfg(feature = "serde")]
fn default_attenuation_colour() -> crate::colour::Colour {
crate::colour::Colour::linear_rgb(1.0, 1.0, 1.0)
}
#[cfg(feature = "serde")]
fn default_attenuation_distance() -> f32 {
f32::MAX
}
#[cfg(feature = "serde")]
fn default_sheen_colour() -> crate::colour::Colour {
crate::colour::Colour::linear_rgb(0.0, 0.0, 0.0)
}
impl Default for Material {
fn default() -> Self {
Self {
base_colour: crate::colour::Colour::linear_rgb(0.7, 0.7, 0.7),
ambient: 0.15,
diffuse: 0.75,
specular: 0.4,
shininess: 32.0,
metallic: 0.0,
roughness: 0.5,
texture_id: None,
normal_map_id: None,
normal_strength: 1.0,
ao_map_id: None,
metallic_roughness_texture_id: None,
emissive: crate::colour::Colour::BLACK,
emissive_strength: 1.0,
emissive_exposure_weight: 1.0,
emissive_texture_id: None,
alpha_mode: AlphaMode::Opaque,
shading_model: ShadingModel::Phong,
param_vis: None,
backface_policy: BackfacePolicy::Cull,
uv_offset: [0.0, 0.0],
uv_scale: [1.0, 1.0],
uv_rotation: 0.0,
texture_transforms: [None; MATERIAL_TEXTURE_SLOTS],
sampler: [None; MATERIAL_TEXTURE_SLOTS],
ao_range: [0.0, 1.0],
metallic_range: [0.0, 1.0],
roughness_range: [0.0, 1.0],
shading_plugin: None,
plugin_params: PluginParams::default(),
plugin_textures: [None; MATERIAL_PLUGIN_MAX_TEXTURES],
reflectance: 0.5,
specular_factor: 1.0,
specular_colour: crate::colour::Colour::linear_rgb(1.0, 1.0, 1.0),
ior: 1.5,
clearcoat: 0.0,
clearcoat_roughness: 0.0,
sheen_colour: crate::colour::Colour::linear_rgb(0.0, 0.0, 0.0),
sheen_roughness: 0.0,
anisotropy: 0.0,
anisotropy_rotation: 0.0,
transmission: 0.0,
thickness: 0.0,
attenuation_colour: crate::colour::Colour::linear_rgb(1.0, 1.0, 1.0),
attenuation_distance: f32::MAX,
}
}
}
impl Material {
pub fn is_two_sided(&self) -> bool {
!matches!(self.backface_policy, BackfacePolicy::Cull)
}
pub fn with_uv_rotation(mut self, radians: f32) -> Self {
self.uv_rotation = radians;
self
}
pub fn with_texture_transform(mut self, slot: TextureSlot, transform: UvTransform) -> Self {
self.texture_transforms[slot as usize] = Some(transform);
self
}
pub fn with_sampler(mut self, slot: TextureSlot, sampler: SamplerKey) -> Self {
self.sampler[slot as usize] = Some(sampler);
self
}
pub fn texture(&self, slot: TextureSlot) -> Option<crate::ids::TextureId> {
match slot {
TextureSlot::Albedo => self.texture_id,
TextureSlot::Normal => self.normal_map_id,
TextureSlot::Ao => self.ao_map_id,
TextureSlot::MetallicRoughness => self.metallic_roughness_texture_id,
TextureSlot::Emissive => self.emissive_texture_id,
}
}
pub fn set_texture(&mut self, slot: TextureSlot, id: Option<crate::ids::TextureId>) {
let field = match slot {
TextureSlot::Albedo => &mut self.texture_id,
TextureSlot::Normal => &mut self.normal_map_id,
TextureSlot::Ao => &mut self.ao_map_id,
TextureSlot::MetallicRoughness => &mut self.metallic_roughness_texture_id,
TextureSlot::Emissive => &mut self.emissive_texture_id,
};
*field = id;
}
pub fn with_texture(mut self, slot: TextureSlot, id: crate::ids::TextureId) -> Self {
self.set_texture(slot, Some(id));
self
}
pub fn with_emissive_exposure_weight(mut self, weight: f32) -> Self {
self.emissive_exposure_weight = weight;
self
}
pub fn with_ior(mut self, ior: f32) -> Self {
self.ior = ior;
self.reflectance = ((ior - 1.0) / (ior + 1.0)).abs() / 0.4;
self
}
pub fn with_clearcoat(mut self, amount: f32, roughness: f32) -> Self {
self.clearcoat = amount;
self.clearcoat_roughness = roughness;
self
}
pub fn with_sheen(mut self, colour: crate::colour::Colour, roughness: f32) -> Self {
self.sheen_colour = colour;
self.sheen_roughness = roughness;
self
}
pub fn with_anisotropy(mut self, strength: f32, rotation: f32) -> Self {
self.anisotropy = strength;
self.anisotropy_rotation = rotation;
self
}
pub fn with_transmission(mut self, transmission: f32, thickness: f32) -> Self {
self.transmission = transmission;
self.thickness = thickness;
self
}
pub fn with_attenuation(mut self, colour: crate::colour::Colour, distance: f32) -> Self {
self.attenuation_colour = colour;
self.attenuation_distance = distance;
self
}
pub fn with_plugin(mut self, plugin: MaterialPluginId) -> Self {
self.shading_plugin = Some(plugin);
self
}
pub fn with_param(mut self, name: &str, value: impl Into<ParamValue>) -> Self {
self.plugin_params.set(name, value);
self
}
pub fn set_param(&mut self, name: &str, value: impl Into<ParamValue>) {
self.plugin_params.set(name, value);
}
pub fn param(&self, name: &str) -> Option<ParamValue> {
self.plugin_params.get(name)
}
pub fn with_plugin_texture(mut self, slot: usize, id: crate::ids::TextureId) -> Self {
self.plugin_textures[slot] = Some(id);
self
}
pub fn selected_sampler(&self) -> Option<SamplerKey> {
self.sampler.iter().flatten().next().copied()
}
pub fn effective_texture_transform(&self, slot: TextureSlot) -> UvTransform {
self.texture_transforms[slot as usize].unwrap_or(UvTransform {
offset: self.uv_offset,
scale: self.uv_scale,
rotation: self.uv_rotation,
uv_set: 0,
})
}
pub fn backface_needs_per_object(&self) -> bool {
matches!(
self.backface_policy,
BackfacePolicy::DifferentColour(_)
| BackfacePolicy::Tint(_)
| BackfacePolicy::Pattern(_)
)
}
pub fn is_blend(&self) -> bool {
matches!(
self.alpha_mode,
AlphaMode::Blend | AlphaMode::BlendPremultiplied
)
}
pub fn is_premultiplied(&self) -> bool {
matches!(self.alpha_mode, AlphaMode::BlendPremultiplied)
}
#[doc(hidden)]
pub fn emissive_nits(&self) -> [f32; 3] {
let e = self.emissive.to_linear_rgb();
[
e[0] * self.emissive_strength,
e[1] * self.emissive_strength,
e[2] * self.emissive_strength,
]
}
pub fn from_colour(colour: impl Into<crate::colour::Colour>) -> Self {
Self {
base_colour: colour.into(),
..Default::default()
}
}
pub fn emissive(colour: impl Into<crate::colour::Colour>, nits: f32) -> Self {
let colour = colour.into();
Self {
base_colour: colour,
emissive: colour,
emissive_strength: nits,
..Default::default()
}
}
pub fn pbr(
base_colour: impl Into<crate::colour::Colour>,
metallic: f32,
roughness: f32,
) -> Self {
Self {
base_colour: base_colour.into(),
shading_model: ShadingModel::Pbr,
metallic,
roughness,
..Default::default()
}
}
pub fn is_pbr(&self) -> bool {
matches!(self.shading_model, ShadingModel::Pbr)
}
pub fn is_flat(&self) -> bool {
matches!(self.shading_model, ShadingModel::Flat)
}
pub fn flat(base_colour: impl Into<crate::colour::Colour>) -> Self {
Self {
base_colour: base_colour.into(),
shading_model: ShadingModel::Flat,
..Default::default()
}
}
pub fn matcap_id(&self) -> Option<crate::ids::MatcapId> {
match self.shading_model {
ShadingModel::Matcap(id) => Some(id),
_ => None,
}
}
pub fn solid(colour: impl Into<crate::colour::Colour>) -> Self {
Self::from_colour(colour)
}
pub fn textured(texture_id: crate::ids::TextureId) -> Self {
Self {
texture_id: Some(texture_id),
..Default::default()
}
}
pub fn pbr_with_ao(
base_colour: impl Into<crate::colour::Colour>,
metallic: f32,
roughness: f32,
ao_map: Option<crate::ids::TextureId>,
) -> Self {
Self {
base_colour: base_colour.into(),
shading_model: ShadingModel::Pbr,
metallic,
roughness,
ao_map_id: ao_map,
..Default::default()
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::colour::Colour;
#[test]
fn with_ior_derives_reflectance() {
let m = Material::default().with_ior(1.5);
assert_eq!(m.ior, 1.5);
assert!((m.reflectance - Material::default().reflectance).abs() < 1e-6);
let m = Material::default().with_ior(2.4);
let f0 = 0.16 * m.reflectance * m.reflectance;
let expected = ((2.4f32 - 1.0) / (2.4 + 1.0)).powi(2);
assert!((f0 - expected).abs() < 1e-6, "{f0} vs {expected}");
}
#[cfg(feature = "serde")]
#[test]
fn emissive_exposure_weight_defaults_to_one_when_absent() {
let mut json =
serde_json::to_value(Material::default().with_emissive_exposure_weight(0.25)).unwrap();
assert_eq!(json["emissive_exposure_weight"], 0.25);
json.as_object_mut()
.unwrap()
.remove("emissive_exposure_weight");
let m: Material = serde_json::from_value(json).unwrap();
assert_eq!(m.emissive_exposure_weight, 1.0);
}
#[test]
fn texture_slots_list_in_index_order() {
for (i, slot) in TextureSlot::ALL.into_iter().enumerate() {
assert_eq!(slot.index(), i);
}
}
#[test]
fn texture_slots_build_what_they_require() {
use crate::data::texture::TextureData;
for slot in TextureSlot::ALL {
let req = slot.requirement();
let built = TextureData::for_slot(1, 1, vec![0u8; 4], slot);
assert_eq!(built.colour_space(), slot.colour_space(), "{slot:?}");
assert_eq!(built.role(), slot.role(), "{slot:?}");
let named = match req.constructor() {
"TextureData::srgb" => TextureData::srgb(1, 1, vec![0u8; 4]),
"TextureData::linear" => TextureData::linear(1, 1, vec![0u8; 4]),
"TextureData::normal_map" => TextureData::normal_map(1, 1, vec![0u8; 4]),
other => panic!("{slot:?} names an unknown constructor {other}"),
};
assert_eq!(named, built, "{slot:?}");
}
assert_eq!(TextureSlot::Albedo.colour_space(), ColourSpace::Srgb);
assert_eq!(TextureSlot::Normal.role(), TextureRole::NormalMap);
assert_eq!(TextureSlot::Ao.colour_space(), ColourSpace::Linear);
}
#[test]
fn texture_by_slot_sets_and_reads_one_field() {
use crate::ids::TextureId;
for (i, slot) in TextureSlot::ALL.into_iter().enumerate() {
let id = TextureId::from_raw(i as u64 + 1);
let m = Material::default().with_texture(slot, id);
for other in TextureSlot::ALL {
let expected = (other == slot).then_some(id);
assert_eq!(m.texture(other), expected, "{slot:?} set, {other:?} read");
}
let field = slot.requirement().field_name();
let direct = match field {
"Material::texture_id" => m.texture_id,
"Material::normal_map_id" => m.normal_map_id,
"Material::ao_map_id" => m.ao_map_id,
"Material::metallic_roughness_texture_id" => m.metallic_roughness_texture_id,
"Material::emissive_texture_id" => m.emissive_texture_id,
other => panic!("{slot:?} names an unknown field {other}"),
};
assert_eq!(direct, Some(id), "{slot:?}");
let mut cleared = m;
cleared.set_texture(slot, None);
assert_eq!(cleared.texture(slot), None);
}
}
#[test]
fn item_settings_defaults() {
let a = ItemSettings::default();
assert!(!a.hidden);
assert!(!a.unlit);
assert!((a.opacity - 1.0).abs() < 1e-6);
assert!(!a.wireframe);
assert!(!a.selected);
}
#[test]
fn item_settings_spread_syntax() {
let a = ItemSettings {
unlit: true,
..Default::default()
};
assert!(a.unlit);
assert!(!a.hidden);
assert!((a.opacity - 1.0).abs() < 1e-6);
}
#[test]
fn flat_constructor_and_helpers() {
let m = Material::flat(Colour::linear_rgb(0.4, 0.5, 0.6));
assert!(m.is_flat());
assert!(!m.is_pbr());
assert!(m.matcap_id().is_none());
assert!(matches!(m.shading_model, ShadingModel::Flat));
assert_eq!(
m.base_colour,
crate::colour::Colour::linear_rgb(0.4, 0.5, 0.6)
);
let p = Material::default();
assert!(!p.is_flat());
}
#[test]
fn default_values() {
let m = Material::default();
assert!((m.base_colour.to_linear_rgb()[0] - 0.7).abs() < 1e-6);
assert!((m.ambient - 0.15).abs() < 1e-6);
assert!((m.diffuse - 0.75).abs() < 1e-6);
assert!(!m.is_pbr());
assert!(m.texture_id.is_none());
assert!(m.normal_map_id.is_none());
assert!(m.ao_map_id.is_none());
assert!(m.matcap_id().is_none());
assert!(m.param_vis.is_none());
}
#[test]
fn from_colour_sets_base_colour() {
let m = Material::from_colour(Colour::linear_rgb(1.0, 0.0, 0.5));
assert!((m.base_colour.to_linear_rgb()[0] - 1.0).abs() < 1e-6);
assert!((m.base_colour.to_linear_rgb()[1]).abs() < 1e-6);
assert!((m.base_colour.to_linear_rgb()[2] - 0.5).abs() < 1e-6);
assert!((m.ambient - 0.15).abs() < 1e-6);
}
#[test]
fn pbr_constructor() {
let m = Material::pbr(Colour::linear_rgb(0.8, 0.2, 0.1), 0.9, 0.3);
assert!(m.is_pbr());
assert!((m.metallic - 0.9).abs() < 1e-6);
assert!((m.roughness - 0.3).abs() < 1e-6);
assert!((m.base_colour.to_linear_rgb()[0] - 0.8).abs() < 1e-6);
}
#[test]
fn is_two_sided_cull() {
let m = Material::default();
assert!(!m.is_two_sided());
}
#[test]
fn is_two_sided_identical() {
let m = Material {
backface_policy: BackfacePolicy::Identical,
..Default::default()
};
assert!(m.is_two_sided());
}
#[test]
fn is_two_sided_different_colour() {
let m = Material {
backface_policy: BackfacePolicy::DifferentColour(crate::colour::Colour::linear_rgb(
1.0, 0.0, 0.0,
)),
..Default::default()
};
assert!(m.is_two_sided());
}
#[test]
fn is_two_sided_tint() {
let m = Material {
backface_policy: BackfacePolicy::Tint(0.3),
..Default::default()
};
assert!(m.is_two_sided());
}
#[test]
fn is_two_sided_pattern() {
let m = Material {
backface_policy: BackfacePolicy::Pattern(PatternConfig {
pattern: BackfacePattern::Hatching,
colour: crate::colour::Colour::linear_rgb(0.5, 0.5, 0.5),
..Default::default()
}),
..Default::default()
};
assert!(m.is_two_sided());
}
#[test]
fn blend_modes_route_through_oit() {
let straight = Material {
alpha_mode: AlphaMode::Blend,
..Default::default()
};
assert!(straight.is_blend());
assert!(!straight.is_premultiplied());
let premult = Material {
alpha_mode: AlphaMode::BlendPremultiplied,
..Default::default()
};
assert!(premult.is_blend());
assert!(premult.is_premultiplied());
let opaque = Material::default();
assert!(!opaque.is_blend());
assert!(!opaque.is_premultiplied());
let mask = Material {
alpha_mode: AlphaMode::Mask(0.5),
..Default::default()
};
assert!(!mask.is_blend());
assert!(!mask.is_premultiplied());
}
#[test]
fn param_vis_default() {
let pv = ParamVis::default();
assert_eq!(pv.mode, ParamVisMode::Checker);
assert!((pv.scale - 8.0).abs() < 1e-6);
}
#[test]
fn solid_delegates_to_from_colour() {
let colour = [1.0_f32, 0.0, 0.5];
let a = Material::solid(Colour::from_linear_rgb_array(colour));
let b = Material::from_colour(Colour::from_linear_rgb_array(colour));
assert!((a.base_colour.to_linear_rgb()[0] - b.base_colour.to_linear_rgb()[0]).abs() < 1e-6);
assert!((a.base_colour.to_linear_rgb()[1] - b.base_colour.to_linear_rgb()[1]).abs() < 1e-6);
assert!((a.base_colour.to_linear_rgb()[2] - b.base_colour.to_linear_rgb()[2]).abs() < 1e-6);
assert_eq!(a.is_pbr(), b.is_pbr());
assert_eq!(a.texture_id, b.texture_id);
assert_eq!(a.ao_map_id, b.ao_map_id);
assert!((a.ambient - b.ambient).abs() < 1e-6);
}
#[test]
fn textured_sets_texture_id() {
let m = Material::textured(crate::ids::TextureId::from_raw(42));
assert_eq!(m.texture_id, Some(crate::ids::TextureId::from_raw(42)));
let def = Material::default();
assert!(
(m.base_colour.to_linear_rgb()[0] - def.base_colour.to_linear_rgb()[0]).abs() < 1e-6
);
assert!(!m.is_pbr());
}
#[test]
fn pbr_with_ao_sets_fields() {
let m = Material::pbr_with_ao(
Colour::linear_rgb(0.8, 0.2, 0.1),
0.9,
0.3,
Some(crate::ids::TextureId::from_raw(7)),
);
assert!(m.is_pbr());
assert!((m.metallic - 0.9).abs() < 1e-6);
assert!((m.roughness - 0.3).abs() < 1e-6);
assert_eq!(m.ao_map_id, Some(crate::ids::TextureId::from_raw(7)));
assert!((m.base_colour.to_linear_rgb()[0] - 0.8).abs() < 1e-6);
}
#[test]
fn pbr_with_ao_accepts_none() {
let m = Material::pbr_with_ao(Colour::linear_rgb(0.5, 0.5, 0.5), 0.0, 1.0, None);
assert_eq!(m.ao_map_id, None);
}
#[test]
fn channel_ranges_default_to_identity() {
let m = Material::default();
assert_eq!(m.ao_range, [0.0, 1.0]);
assert_eq!(m.metallic_range, [0.0, 1.0]);
assert_eq!(m.roughness_range, [0.0, 1.0]);
}
#[test]
fn channel_ranges_round_trip_with_spread() {
let m = Material {
ao_range: [0.4, 1.0],
metallic_range: [0.1, 0.9],
roughness_range: [0.2, 0.8],
..Default::default()
};
assert_eq!(m.ao_range, [0.4, 1.0]);
assert_eq!(m.metallic_range, [0.1, 0.9]);
assert_eq!(m.roughness_range, [0.2, 0.8]);
assert_eq!(m.uv_offset, [0.0, 0.0]);
assert_eq!(m.uv_scale, [1.0, 1.0]);
}
}