use crate::{
core::{
algebra::{Matrix4, Point3, Vector2, Vector3, Vector4},
inspect::{Inspect, PropertyInfo},
math::aabb::AxisAlignedBoundingBox,
math::{ray::Ray, Rect},
pool::Handle,
visitor::{Visit, VisitResult, Visitor},
},
resource::texture::{Texture, TextureError, TextureKind, TexturePixelKind, TextureWrapMode},
scene::{
base::{Base, BaseBuilder},
graph::Graph,
node::Node,
visibility::VisibilityCache,
},
};
use std::{
ops::{Deref, DerefMut},
sync::Arc,
};
use strum_macros::{AsRefStr, EnumString, EnumVariantNames};
#[derive(Inspect, Clone, Debug, PartialEq, Visit)]
pub struct PerspectiveProjection {
#[inspect(min_value = 0.0, max_value = 3.14159, step = 0.1)]
pub fov: f32,
#[inspect(min_value = 0.0, step = 0.1)]
pub z_near: f32,
#[inspect(min_value = 0.0, step = 0.1)]
pub z_far: f32,
}
impl Default for PerspectiveProjection {
fn default() -> Self {
Self {
fov: 75.0f32.to_radians(),
z_near: 0.025,
z_far: 2048.0,
}
}
}
impl PerspectiveProjection {
#[inline]
pub fn matrix(&self, frame_size: Vector2<f32>) -> Matrix4<f32> {
Matrix4::new_perspective(
(frame_size.x / frame_size.y).max(10.0 * f32::EPSILON),
self.fov,
self.z_near,
self.z_far,
)
}
}
#[derive(Inspect, Clone, Debug, PartialEq, Visit)]
pub struct OrthographicProjection {
#[inspect(min_value = 0.0, step = 0.1)]
pub z_near: f32,
#[inspect(min_value = 0.0, step = 0.1)]
pub z_far: f32,
#[inspect(step = 0.1)]
pub vertical_size: f32,
}
impl Default for OrthographicProjection {
fn default() -> Self {
Self {
z_near: 0.0,
z_far: 2048.0,
vertical_size: 5.0,
}
}
}
impl OrthographicProjection {
#[inline]
pub fn matrix(&self, frame_size: Vector2<f32>) -> Matrix4<f32> {
let aspect = (frame_size.x / frame_size.y).max(10.0 * f32::EPSILON);
let horizontal_size = aspect * self.vertical_size;
let left = -horizontal_size;
let top = self.vertical_size;
let right = horizontal_size;
let bottom = -self.vertical_size;
Matrix4::new_orthographic(left, right, bottom, top, self.z_near, self.z_far)
}
}
#[derive(Inspect, Clone, Debug, PartialEq, Visit, AsRefStr, EnumString, EnumVariantNames)]
pub enum Projection {
Perspective(PerspectiveProjection),
Orthographic(OrthographicProjection),
}
impl Projection {
#[inline]
#[must_use]
pub fn with_z_near(mut self, z_near: f32) -> Self {
match self {
Projection::Perspective(ref mut v) => v.z_near = z_near,
Projection::Orthographic(ref mut v) => v.z_near = z_near,
}
self
}
#[inline]
#[must_use]
pub fn with_z_far(mut self, z_far: f32) -> Self {
match self {
Projection::Perspective(ref mut v) => v.z_far = z_far,
Projection::Orthographic(ref mut v) => v.z_far = z_far,
}
self
}
#[inline]
pub fn set_z_near(&mut self, z_near: f32) {
match self {
Projection::Perspective(v) => v.z_near = z_near,
Projection::Orthographic(v) => v.z_near = z_near,
}
}
#[inline]
pub fn set_z_far(&mut self, z_far: f32) {
match self {
Projection::Perspective(v) => v.z_far = z_far,
Projection::Orthographic(v) => v.z_far = z_far,
}
}
#[inline]
pub fn z_near(&self) -> f32 {
match self {
Projection::Perspective(v) => v.z_near,
Projection::Orthographic(v) => v.z_near,
}
}
#[inline]
pub fn z_far(&self) -> f32 {
match self {
Projection::Perspective(v) => v.z_far,
Projection::Orthographic(v) => v.z_far,
}
}
#[inline]
pub fn matrix(&self, frame_size: Vector2<f32>) -> Matrix4<f32> {
match self {
Projection::Perspective(v) => v.matrix(frame_size),
Projection::Orthographic(v) => v.matrix(frame_size),
}
}
}
impl Default for Projection {
fn default() -> Self {
Self::Perspective(PerspectiveProjection::default())
}
}
#[derive(Visit, Copy, Clone, PartialEq, Debug, Inspect, AsRefStr, EnumString, EnumVariantNames)]
pub enum Exposure {
Auto {
#[inspect(min_value = 0.0, step = 0.1)]
key_value: f32,
#[inspect(min_value = 0.0, step = 0.1)]
min_luminance: f32,
#[inspect(min_value = 0.0, step = 0.1)]
max_luminance: f32,
},
Manual(f32),
}
impl Default for Exposure {
fn default() -> Self {
Self::Auto {
key_value: 0.01556,
min_luminance: 0.00778,
max_luminance: 64.0,
}
}
}
#[derive(Debug, Visit, Inspect)]
pub struct Camera {
base: Base,
#[visit(optional)] projection: Projection,
viewport: Rect<f32>,
#[visit(skip)]
#[inspect(skip)]
view_matrix: Matrix4<f32>,
#[visit(skip)]
#[inspect(skip)]
projection_matrix: Matrix4<f32>,
enabled: bool,
sky_box: Option<Box<SkyBox>>,
environment: Option<Texture>,
#[visit(optional)] exposure: Exposure,
#[visit(optional)] color_grading_lut: Option<ColorGradingLut>,
#[visit(optional)] color_grading_enabled: bool,
#[visit(skip)]
#[inspect(skip)]
pub visibility_cache: VisibilityCache,
}
impl Deref for Camera {
type Target = Base;
fn deref(&self) -> &Self::Target {
&self.base
}
}
impl DerefMut for Camera {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.base
}
}
impl Default for Camera {
fn default() -> Self {
CameraBuilder::new(BaseBuilder::new()).build_camera()
}
}
impl Camera {
#[inline]
pub fn calculate_matrices(&mut self, frame_size: Vector2<f32>) {
let pos = self.base.global_position();
let look = self.base.look_vector();
let up = self.base.up_vector();
self.view_matrix = Matrix4::look_at_rh(&Point3::from(pos), &Point3::from(pos + look), &up);
self.projection_matrix = self.projection.matrix(frame_size);
}
pub fn set_viewport(&mut self, viewport: Rect<f32>) -> &mut Self {
self.viewport = viewport;
self.viewport.position.x = self.viewport.position.x.clamp(0.0, 1.0);
self.viewport.position.y = self.viewport.position.y.clamp(0.0, 1.0);
self.viewport.size.x = self.viewport.size.x.clamp(0.0, 1.0);
self.viewport.size.y = self.viewport.size.y.clamp(0.0, 1.0);
self
}
pub fn viewport(&self) -> Rect<f32> {
self.viewport
}
#[inline]
pub fn viewport_pixels(&self, frame_size: Vector2<f32>) -> Rect<i32> {
Rect::new(
(self.viewport.x() * frame_size.x) as i32,
(self.viewport.y() * frame_size.y) as i32,
((self.viewport.w() * frame_size.x) as i32).max(1),
((self.viewport.h() * frame_size.y) as i32).max(1),
)
}
#[inline]
pub fn view_projection_matrix(&self) -> Matrix4<f32> {
self.projection_matrix * self.view_matrix
}
#[inline]
pub fn projection_matrix(&self) -> Matrix4<f32> {
self.projection_matrix
}
#[inline]
pub fn view_matrix(&self) -> Matrix4<f32> {
self.view_matrix
}
#[inline]
pub fn inv_view_matrix(&self) -> Option<Matrix4<f32>> {
self.view_matrix.try_inverse()
}
#[inline]
pub fn projection(&self) -> &Projection {
&self.projection
}
#[inline]
pub fn projection_value(&self) -> Projection {
self.projection.clone()
}
#[inline]
pub fn projection_mut(&mut self) -> &mut Projection {
&mut self.projection
}
#[inline]
pub fn set_projection(&mut self, projection: Projection) {
self.projection = projection;
}
#[inline]
pub fn is_enabled(&self) -> bool {
self.enabled
}
#[inline]
pub fn set_enabled(&mut self, enabled: bool) -> &mut Self {
self.enabled = enabled;
self
}
pub fn set_skybox(&mut self, skybox: Option<SkyBox>) -> &mut Self {
self.sky_box = skybox.map(Box::new);
self
}
pub fn skybox_mut(&mut self) -> Option<&mut SkyBox> {
self.sky_box.as_deref_mut()
}
pub fn skybox_ref(&self) -> Option<&SkyBox> {
self.sky_box.as_deref()
}
pub fn replace_skybox(&mut self, new: Option<Box<SkyBox>>) -> Option<Box<SkyBox>> {
std::mem::replace(&mut self.sky_box, new)
}
pub fn set_environment(&mut self, environment: Option<Texture>) -> &mut Self {
self.environment = environment;
self
}
pub fn environment_mut(&mut self) -> Option<&mut Texture> {
self.environment.as_mut()
}
pub fn environment_ref(&self) -> Option<&Texture> {
self.environment.as_ref()
}
pub fn environment_map(&self) -> Option<Texture> {
self.environment.clone()
}
#[inline]
pub fn local_bounding_box(&self) -> AxisAlignedBoundingBox {
self.base.local_bounding_box()
}
pub fn world_bounding_box(&self) -> AxisAlignedBoundingBox {
self.base.world_bounding_box()
}
pub fn make_ray(&self, screen_coord: Vector2<f32>, screen_size: Vector2<f32>) -> Ray {
let viewport = self.viewport_pixels(screen_size);
let nx = screen_coord.x / (viewport.w() as f32) * 2.0 - 1.0;
let ny = (viewport.h() as f32 - screen_coord.y) / (viewport.h() as f32) * 2.0 - 1.0;
let inv_view_proj = self
.view_projection_matrix()
.try_inverse()
.unwrap_or_default();
let near = inv_view_proj * Vector4::new(nx, ny, -1.0, 1.0);
let far = inv_view_proj * Vector4::new(nx, ny, 1.0, 1.0);
let begin = near.xyz().scale(1.0 / near.w);
let end = far.xyz().scale(1.0 / far.w);
Ray::from_two_points(begin, end)
}
pub fn project(
&self,
world_pos: Vector3<f32>,
screen_size: Vector2<f32>,
) -> Option<Vector2<f32>> {
let viewport = self.viewport_pixels(screen_size);
let proj = self.view_projection_matrix()
* Vector4::new(world_pos.x, world_pos.y, world_pos.z, 1.0);
if proj.w != 0.0 && proj.z >= 0.0 {
let k = (1.0 / proj.w) * 0.5;
Some(Vector2::new(
viewport.x() as f32 + viewport.w() as f32 * (proj.x * k + 0.5),
viewport.h() as f32
- (viewport.y() as f32 + viewport.h() as f32 * (proj.y * k + 0.5)),
))
} else {
None
}
}
pub fn raw_copy(&self) -> Self {
Self {
base: self.base.raw_copy(),
projection: self.projection.clone(),
viewport: self.viewport,
view_matrix: self.view_matrix,
projection_matrix: self.projection_matrix,
enabled: self.enabled,
sky_box: self.sky_box.clone(),
environment: self.environment.clone(),
exposure: self.exposure,
color_grading_lut: self.color_grading_lut.clone(),
color_grading_enabled: self.color_grading_enabled,
visibility_cache: Default::default(),
}
}
pub fn set_color_grading_map(&mut self, lut: Option<ColorGradingLut>) {
self.color_grading_lut = lut;
}
pub fn color_grading_lut(&self) -> Option<ColorGradingLut> {
self.color_grading_lut.clone()
}
pub fn color_grading_lut_ref(&self) -> Option<&ColorGradingLut> {
self.color_grading_lut.as_ref()
}
pub fn set_color_grading_enabled(&mut self, enable: bool) {
self.color_grading_enabled = enable;
}
pub fn color_grading_enabled(&self) -> bool {
self.color_grading_enabled
}
pub fn set_exposure(&mut self, exposure: Exposure) {
self.exposure = exposure;
}
pub fn exposure(&self) -> Exposure {
self.exposure
}
}
#[derive(Debug, thiserror::Error)]
pub enum ColorGradingLutCreationError {
#[error(
"There is not enough data in provided texture to build LUT. Required: {}, current: {}.",
required,
current
)]
NotEnoughData {
required: usize,
current: usize,
},
#[error("Pixel format is not supported. It must be either RGB8 or RGBA8, but texture has {0:?} pixel format")]
InvalidPixelFormat(TexturePixelKind),
#[error("Texture load error: {0:?}")]
Texture(Option<Arc<TextureError>>),
}
#[derive(Visit, Clone, Default, Debug, Inspect)]
pub struct ColorGradingLut {
#[visit(skip)]
lut: Option<Texture>,
#[inspect(skip)]
unwrapped_lut: Option<Texture>,
}
impl ColorGradingLut {
pub async fn new(unwrapped_lut: Texture) -> Result<Self, ColorGradingLutCreationError> {
match unwrapped_lut.await {
Ok(unwrapped_lut) => {
let data = unwrapped_lut.data_ref();
if data.pixel_kind() != TexturePixelKind::RGBA8
&& data.pixel_kind() != TexturePixelKind::RGB8
{
return Err(ColorGradingLutCreationError::InvalidPixelFormat(
data.pixel_kind(),
));
}
let bytes = data.data();
const RGBA8_SIZE: usize = 16 * 16 * 16 * 4;
const RGB8_SIZE: usize = 16 * 16 * 16 * 3;
if data.pixel_kind() == TexturePixelKind::RGBA8 {
if bytes.len() != RGBA8_SIZE {
return Err(ColorGradingLutCreationError::NotEnoughData {
required: RGBA8_SIZE,
current: bytes.len(),
});
}
} else if bytes.len() != RGB8_SIZE {
return Err(ColorGradingLutCreationError::NotEnoughData {
required: RGB8_SIZE,
current: bytes.len(),
});
}
let pixel_size = if data.pixel_kind() == TexturePixelKind::RGBA8 {
4
} else {
3
};
let mut lut_bytes = Vec::with_capacity(16 * 16 * 16 * 3);
for z in 0..16 {
for y in 0..16 {
for x in 0..16 {
let pixel_index = z * 16 + y * 16 * 16 + x;
let pixel_byte_pos = pixel_index * pixel_size;
lut_bytes.push(bytes[pixel_byte_pos]); lut_bytes.push(bytes[pixel_byte_pos + 1]); lut_bytes.push(bytes[pixel_byte_pos + 2]); }
}
}
let lut = Texture::from_bytes(
TextureKind::Volume {
width: 16,
height: 16,
depth: 16,
},
TexturePixelKind::RGB8,
lut_bytes,
false,
)
.unwrap();
let mut lut_ref = lut.data_ref();
lut_ref.set_s_wrap_mode(TextureWrapMode::ClampToEdge);
lut_ref.set_t_wrap_mode(TextureWrapMode::ClampToEdge);
drop(lut_ref);
drop(data);
Ok(Self {
lut: Some(lut),
unwrapped_lut: Some(unwrapped_lut),
})
}
Err(e) => Err(ColorGradingLutCreationError::Texture(e)),
}
}
pub fn unwrapped_lut(&self) -> Texture {
self.unwrapped_lut.clone().unwrap()
}
pub fn lut(&self) -> Texture {
self.lut.clone().unwrap()
}
pub fn lut_ref(&self) -> &Texture {
self.lut.as_ref().unwrap()
}
}
pub struct CameraBuilder {
base_builder: BaseBuilder,
fov: f32,
z_near: f32,
z_far: f32,
viewport: Rect<f32>,
enabled: bool,
skybox: Option<SkyBox>,
environment: Option<Texture>,
exposure: Exposure,
color_grading_lut: Option<ColorGradingLut>,
color_grading_enabled: bool,
projection: Projection,
}
impl CameraBuilder {
pub fn new(base_builder: BaseBuilder) -> Self {
Self {
enabled: true,
base_builder,
fov: 75.0f32.to_radians(),
z_near: 0.025,
z_far: 2048.0,
viewport: Rect::new(0.0, 0.0, 1.0, 1.0),
skybox: None,
environment: None,
exposure: Exposure::Manual(std::f32::consts::E),
color_grading_lut: None,
color_grading_enabled: false,
projection: Projection::default(),
}
}
pub fn with_fov(mut self, fov: f32) -> Self {
self.fov = fov;
self
}
pub fn with_z_near(mut self, z_near: f32) -> Self {
self.z_near = z_near;
self
}
pub fn with_z_far(mut self, z_far: f32) -> Self {
self.z_far = z_far;
self
}
pub fn with_viewport(mut self, viewport: Rect<f32>) -> Self {
self.viewport = viewport;
self
}
pub fn enabled(mut self, enabled: bool) -> Self {
self.enabled = enabled;
self
}
pub fn with_skybox(mut self, skybox: SkyBox) -> Self {
self.skybox = Some(skybox);
self
}
pub fn with_environment(mut self, environment: Texture) -> Self {
self.environment = Some(environment);
self
}
pub fn with_color_grading_lut(mut self, lut: ColorGradingLut) -> Self {
self.color_grading_lut = Some(lut);
self
}
pub fn with_color_grading_enabled(mut self, enabled: bool) -> Self {
self.color_grading_enabled = enabled;
self
}
pub fn with_exposure(mut self, exposure: Exposure) -> Self {
self.exposure = exposure;
self
}
pub fn with_projection(mut self, projection: Projection) -> Self {
self.projection = projection;
self
}
pub fn build_camera(self) -> Camera {
Camera {
enabled: self.enabled,
base: self.base_builder.build_base(),
projection: self.projection,
viewport: self.viewport,
view_matrix: Matrix4::identity(),
projection_matrix: Matrix4::identity(),
visibility_cache: Default::default(),
sky_box: self.skybox.map(Box::new),
environment: self.environment,
exposure: self.exposure,
color_grading_lut: self.color_grading_lut,
color_grading_enabled: self.color_grading_enabled,
}
}
pub fn build_node(self) -> Node {
Node::Camera(self.build_camera())
}
pub fn build(self, graph: &mut Graph) -> Handle<Node> {
graph.add_node(self.build_node())
}
}
pub struct SkyBoxBuilder {
pub front: Option<Texture>,
pub back: Option<Texture>,
pub left: Option<Texture>,
pub right: Option<Texture>,
pub top: Option<Texture>,
pub bottom: Option<Texture>,
}
impl SkyBoxBuilder {
pub fn with_front(mut self, texture: Texture) -> Self {
self.front = Some(texture);
self
}
pub fn with_back(mut self, texture: Texture) -> Self {
self.back = Some(texture);
self
}
pub fn with_left(mut self, texture: Texture) -> Self {
self.left = Some(texture);
self
}
pub fn with_right(mut self, texture: Texture) -> Self {
self.right = Some(texture);
self
}
pub fn with_top(mut self, texture: Texture) -> Self {
self.top = Some(texture);
self
}
pub fn with_bottom(mut self, texture: Texture) -> Self {
self.bottom = Some(texture);
self
}
pub fn build(self) -> Result<SkyBox, SkyBoxError> {
let mut skybox = SkyBox {
left: self.left,
right: self.right,
top: self.top,
bottom: self.bottom,
front: self.front,
back: self.back,
cubemap: None,
};
skybox.create_cubemap()?;
Ok(skybox)
}
}
#[derive(Debug, Clone, Default, Inspect)]
pub struct SkyBox {
pub(in crate) front: Option<Texture>,
pub(in crate) back: Option<Texture>,
pub(in crate) left: Option<Texture>,
pub(in crate) right: Option<Texture>,
pub(in crate) top: Option<Texture>,
pub(in crate) bottom: Option<Texture>,
#[inspect(skip)]
pub(in crate) cubemap: Option<Texture>,
}
#[derive(Debug)]
pub enum SkyBoxError {
UnsupportedTextureKind(TextureKind),
UnableToBuildCubeMap,
}
impl SkyBox {
pub fn cubemap(&self) -> Option<Texture> {
self.cubemap.clone()
}
pub fn cubemap_ref(&self) -> Option<&Texture> {
self.cubemap.as_ref()
}
pub fn create_cubemap(&mut self) -> Result<(), SkyBoxError> {
let (kind, pixel_kind, bytes_per_face) =
self.textures().iter().find(|face| face.is_some()).map_or(
(
TextureKind::Rectangle {
width: 1,
height: 1,
},
TexturePixelKind::R8,
1,
),
|face| {
let face = face.clone().unwrap();
let data = face.data_ref();
(
data.kind(),
data.pixel_kind(),
data.first_mip_level_data().len(),
)
},
);
let (width, height) = match kind {
TextureKind::Rectangle { width, height } => (width, height),
_ => return Err(SkyBoxError::UnsupportedTextureKind(kind)),
};
let mut data = Vec::<u8>::with_capacity(bytes_per_face * 6);
for face in self.textures().iter() {
if let Some(f) = face.clone() {
data.extend(f.data_ref().first_mip_level_data());
} else {
let black_face_data = vec![0; bytes_per_face];
data.extend(black_face_data);
}
}
self.cubemap = Some(
Texture::from_bytes(TextureKind::Cube { width, height }, pixel_kind, data, false)
.ok_or(SkyBoxError::UnableToBuildCubeMap)?,
);
Ok(())
}
pub fn textures(&self) -> [Option<Texture>; 6] {
[
self.left.clone(),
self.right.clone(),
self.top.clone(),
self.bottom.clone(),
self.front.clone(),
self.back.clone(),
]
}
pub fn left(&self) -> Option<Texture> {
self.left.clone()
}
pub fn right(&self) -> Option<Texture> {
self.right.clone()
}
pub fn top(&self) -> Option<Texture> {
self.top.clone()
}
pub fn bottom(&self) -> Option<Texture> {
self.bottom.clone()
}
pub fn front(&self) -> Option<Texture> {
self.front.clone()
}
pub fn back(&self) -> Option<Texture> {
self.back.clone()
}
}
impl Visit for SkyBox {
fn visit(&mut self, name: &str, visitor: &mut Visitor) -> VisitResult {
visitor.enter_region(name)?;
self.left.visit("Left", visitor)?;
self.right.visit("Right", visitor)?;
self.top.visit("Top", visitor)?;
self.bottom.visit("Bottom", visitor)?;
self.front.visit("Front", visitor)?;
self.back.visit("Back", visitor)?;
visitor.leave_region()
}
}