use std::cell::{Cell, RefMut};
use std::rc::Rc;
use crate::addons::camera_utils::frame_corners;
use crate::cameras::{PerspectiveCamera, StereoCamera};
use crate::materials::MeshBasicNodeMaterial;
use crate::math::{CoordinateSystem, Matrix3, Vector3, DEG2RAD};
use crate::nodes::node::SettableValue;
use crate::nodes::tsl::{max, texture_sample, uniform_settable, uv, vec4_join};
use crate::nodes::{NodeRef, Type};
use crate::objects::QuadMesh;
use crate::renderer::SceneRef;
use super::stereo_composite_pass::{AnaglyphEyes, CompositeState};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum AnaglyphAlgorithm {
True,
Grey,
Colour,
HalfColour,
#[default]
Dubois,
Optimised,
Compromise,
}
impl AnaglyphAlgorithm {
pub const ALL: [Self; 7] = [
Self::True,
Self::Grey,
Self::Colour,
Self::HalfColour,
Self::Dubois,
Self::Optimised,
Self::Compromise,
];
pub fn as_str(self) -> &'static str {
match self {
Self::True => "true",
Self::Grey => "grey",
Self::Colour => "colour",
Self::HalfColour => "halfColour",
Self::Dubois => "dubois",
Self::Optimised => "optimised",
Self::Compromise => "compromise",
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum AnaglyphColorMode {
#[default]
RedCyan,
MagentaCyan,
MagentaGreen,
}
impl AnaglyphColorMode {
pub const ALL: [Self; 3] = [Self::RedCyan, Self::MagentaCyan, Self::MagentaGreen];
pub fn as_str(self) -> &'static str {
match self {
Self::RedCyan => "redCyan",
Self::MagentaCyan => "magentaCyan",
Self::MagentaGreen => "magentaGreen",
}
}
}
const LUM: [f64; 3] = [0.299, 0.587, 0.114];
#[derive(Clone, Copy, Default)]
struct Spec {
r: Option<[f64; 3]>,
g: Option<[f64; 3]>,
b: Option<[f64; 3]>,
}
const fn r(r: [f64; 3]) -> Spec {
Spec {
r: Some(r),
g: None,
b: None,
}
}
impl Spec {
const fn g(self, g: [f64; 3]) -> Self {
Self { g: Some(g), ..self }
}
const fn b(self, b: [f64; 3]) -> Self {
Self { b: Some(b), ..self }
}
fn to_column_major(self) -> [f64; 9] {
let r = self.r.unwrap_or([0.0; 3]);
let g = self.g.unwrap_or([0.0; 3]);
let b = self.b.unwrap_or([0.0; 3]);
[
r[0], g[0], b[0], r[1], g[1], b[1], r[2], g[2], b[2], ]
}
}
const NONE: Spec = Spec {
r: None,
g: None,
b: None,
};
fn specs(algorithm: AnaglyphAlgorithm, color_mode: AnaglyphColorMode) -> (Spec, Spec) {
use AnaglyphAlgorithm as A;
use AnaglyphColorMode as M;
match (algorithm, color_mode) {
(A::True, M::RedCyan) => (r([1.0, 0.0, 0.0]), NONE.g(LUM).b(LUM)),
(A::True, M::MagentaCyan) => (
r([1.0, 0.0, 0.0]).b([0.0, 0.0, 0.5]),
NONE.g(LUM).b([0.0, 0.0, 0.5]),
),
(A::True, M::MagentaGreen) => (r([1.0, 0.0, 0.0]).b(LUM), NONE.g(LUM)),
(A::Grey, M::RedCyan) => (r(LUM), NONE.g(LUM).b(LUM)),
(A::Grey, M::MagentaCyan) => (
r(LUM).b([0.15, 0.29, 0.06]),
NONE.g(LUM).b([0.15, 0.29, 0.06]),
),
(A::Grey, M::MagentaGreen) => (r(LUM).b(LUM), NONE.g(LUM)),
(A::Colour, M::RedCyan) => (
r([1.0, 0.0, 0.0]),
NONE.g([0.0, 1.0, 0.0]).b([0.0, 0.0, 1.0]),
),
(A::Colour, M::MagentaCyan) => (
r([1.0, 0.0, 0.0]).b([0.0, 0.0, 0.5]),
NONE.g([0.0, 1.0, 0.0]).b([0.0, 0.0, 0.5]),
),
(A::Colour, M::MagentaGreen) => (
r([1.0, 0.0, 0.0]).b([0.0, 0.0, 1.0]),
NONE.g([0.0, 1.0, 0.0]),
),
(A::HalfColour, M::RedCyan) => (r(LUM), NONE.g([0.0, 1.0, 0.0]).b([0.0, 0.0, 1.0])),
(A::HalfColour, M::MagentaCyan) => (
r(LUM).b([0.15, 0.29, 0.06]),
NONE.g([0.0, 1.0, 0.0]).b([0.15, 0.29, 0.06]),
),
(A::HalfColour, M::MagentaGreen) => (r(LUM).b(LUM), NONE.g([0.0, 1.0, 0.0])),
(A::Dubois, M::RedCyan) => (
r([0.4561, 0.500484, 0.176381])
.g([-0.0400822, -0.0378246, -0.0157589])
.b([-0.0152161, -0.0205971, -0.00546856]),
r([-0.0434706, -0.0879388, -0.00155529])
.g([0.378476, 0.73364, -0.0184503])
.b([-0.0721527, -0.112961, 1.2264]),
),
(A::Dubois, M::MagentaCyan) => (
r([0.4561, 0.500484, 0.176381])
.g([-0.0400822, -0.0378246, -0.0157589])
.b([0.088, 0.088, -0.003]),
r([-0.0434706, -0.0879388, -0.00155529])
.g([0.378476, 0.73364, -0.0184503])
.b([0.088, 0.088, 0.613]),
),
(A::Dubois, M::MagentaGreen) => (
r([0.4561, 0.500484, 0.176381]).b([-0.0434706, -0.0879388, -0.00155529]),
NONE.g([0.378476 + 0.4561, 0.73364 + 0.500484, -0.0184503 + 0.176381]),
),
(A::Optimised, M::RedCyan) => (
r([0.0, 0.7, 0.3]),
NONE.g([0.0, 1.0, 0.0]).b([0.0, 0.0, 1.0]),
),
(A::Optimised, M::MagentaCyan) => (
r([0.0, 0.7, 0.3]).b([0.0, 0.0, 0.5]),
NONE.g([0.0, 1.0, 0.0]).b([0.0, 0.0, 0.5]),
),
(A::Optimised, M::MagentaGreen) => (
r([0.0, 0.7, 0.3]).b([0.0, 0.0, 1.0]),
NONE.g([0.0, 1.0, 0.0]),
),
(A::Compromise, M::RedCyan) => (
r([0.439, 0.447, 0.148]),
NONE.g([0.095, 0.934, 0.005]).b([0.018, 0.028, 1.057]),
),
(A::Compromise, M::MagentaCyan) => (
r([0.439, 0.447, 0.148]).b([0.009, 0.014, 0.074]),
NONE.g([0.095, 0.934, 0.005]).b([0.009, 0.014, 0.528]),
),
(A::Compromise, M::MagentaGreen) => (
r([0.439, 0.447, 0.148]).b([0.018, 0.028, 1.057]),
NONE.g([0.095 + 0.439, 0.934 + 0.447, 0.005 + 0.148]),
),
}
}
pub fn anaglyph_matrices(
algorithm: AnaglyphAlgorithm,
color_mode: AnaglyphColorMode,
) -> (Matrix3, Matrix3) {
let (left, right) = specs(algorithm, color_mode);
let matrix = |spec: Spec| {
let mut m = Matrix3::identity();
m.from_array(&spec.to_column_major(), 0);
m
};
(matrix(left), matrix(right))
}
fn mat3_values(m: &Matrix3) -> Vec<f64> {
m.to_padded_f32_array().iter().map(|&v| v as f64).collect()
}
pub fn anaglyph_pass(
scene: SceneRef,
camera: std::rc::Rc<std::cell::RefCell<PerspectiveCamera>>,
) -> AnaglyphPassNode {
AnaglyphPassNode::new(scene, camera)
}
pub struct AnaglyphPassNode {
state: Rc<CompositeState>,
algorithm: Cell<AnaglyphAlgorithm>,
color_mode: Cell<AnaglyphColorMode>,
color_matrices: Cell<(Matrix3, Matrix3)>,
color_matrix_left: SettableValue,
color_matrix_right: SettableValue,
}
impl AnaglyphPassNode {
pub const TYPE: &'static str = "AnaglyphPassNode";
pub fn new(
scene: SceneRef,
camera: std::rc::Rc<std::cell::RefCell<PerspectiveCamera>>,
) -> Self {
let algorithm = AnaglyphAlgorithm::Dubois;
let color_mode = AnaglyphColorMode::RedCyan;
let matrices = anaglyph_matrices(algorithm, color_mode);
let (left_node, left) = uniform_settable(Type::Mat3, mat3_values(&matrices.0));
let (right_node, right) = uniform_settable(Type::Mat3, mat3_values(&matrices.1));
let eyes = AnaglyphEyes {
eye_sep: Cell::new(0.064),
plane_distance: Cell::new(0.5),
};
let state = CompositeState::new(scene, camera, Some(eyes), |map_left, map_right| {
let mut material = MeshBasicNodeMaterial::new();
material.name = "Anaglyph";
material.fragment_node =
Some(anaglyph_node(map_left, map_right, left_node, right_node));
material
});
Self {
state,
algorithm: Cell::new(algorithm),
color_mode: Cell::new(color_mode),
color_matrices: Cell::new(matrices),
color_matrix_left: left,
color_matrix_right: right,
}
}
pub fn node(&self) -> NodeRef {
self.state.node()
}
pub fn stereo(&self) -> RefMut<'_, StereoCamera> {
self.state.stereo()
}
fn eyes(&self) -> &AnaglyphEyes {
self.state
.anaglyph()
.expect("three-rs: an AnaglyphPassNode's state carries its eyes")
}
pub fn eye_sep(&self) -> f64 {
self.eyes().eye_sep.get()
}
pub fn set_eye_sep(&self, value: f64) {
self.eyes().eye_sep.set(value);
}
pub fn plane_distance(&self) -> f64 {
self.eyes().plane_distance.get()
}
pub fn set_plane_distance(&self, value: f64) {
self.eyes().plane_distance.set(value);
}
pub fn algorithm(&self) -> AnaglyphAlgorithm {
self.algorithm.get()
}
pub fn set_algorithm(&self, value: AnaglyphAlgorithm) {
if self.algorithm.get() != value {
self.algorithm.set(value);
self.update_matrices();
}
}
pub fn color_mode(&self) -> AnaglyphColorMode {
self.color_mode.get()
}
pub fn set_color_mode(&self, value: AnaglyphColorMode) {
if self.color_mode.get() != value {
self.color_mode.set(value);
self.update_matrices();
}
}
pub fn color_matrix_left(&self) -> Matrix3 {
self.color_matrices.get().0
}
pub fn color_matrix_right(&self) -> Matrix3 {
self.color_matrices.get().1
}
fn update_matrices(&self) {
let matrices = anaglyph_matrices(self.algorithm.get(), self.color_mode.get());
self.color_matrix_left.set(mat3_values(&matrices.0));
self.color_matrix_right.set(mat3_values(&matrices.1));
self.color_matrices.set(matrices);
}
pub fn update_stereo_camera(&self, coordinate_system: CoordinateSystem) {
self.state.update_stereo_camera(coordinate_system);
}
#[doc(hidden)]
pub fn quad_material(&self) -> MeshBasicNodeMaterial {
let quad: std::cell::Ref<'_, QuadMesh> = self.state.quad();
quad.material.clone()
}
}
fn anaglyph_node(
map_left: &crate::textures::Texture,
map_right: &crate::textures::Texture,
color_matrix_left: NodeRef,
color_matrix_right: NodeRef,
) -> NodeRef {
let uv_node = uv();
let color_l = texture_sample(map_left, uv_node.clone());
let color_r = texture_sample(map_right, uv_node);
let color = color_matrix_left
.mul(color_l.rgb())
.add(color_matrix_right.mul(color_r.rgb()))
.clamp(0.0, 1.0);
vec4_join(vec![color, max(color_l.a(), color_r.a())])
}
pub(super) fn update_stereo_camera(
stereo: &mut StereoCamera,
camera: &PerspectiveCamera,
eye_sep: f64,
plane_distance: f64,
coordinate_system: CoordinateSystem,
) {
stereo.camera_l.coordinate_system = coordinate_system;
stereo.camera_r.coordinate_system = coordinate_system;
let (mut right, mut up, mut forward) = (Vector3::ZERO, Vector3::ZERO, Vector3::ZERO);
let (matrix_world, position) = {
let object = camera.node.borrow();
(object.matrix_world, object.position)
};
matrix_world.extract_basis(&mut right, &mut up, &mut forward);
right.normalize();
up.normalize();
forward.normalize();
let half_sep = eye_sep / 2.0;
let mut eye_l = position;
eye_l.add_scaled_vector(&right, -half_sep);
let mut eye_r = position;
eye_r.add_scaled_vector(&right, half_sep);
let mut screen_center = position;
screen_center.add_scaled_vector(&forward, -plane_distance);
let half_height = plane_distance * (DEG2RAD * camera.fov / 2.0).tan();
let half_width = half_height * camera.aspect;
let mut screen_bottom_left = screen_center;
screen_bottom_left
.add_scaled_vector(&right, -half_width)
.add_scaled_vector(&up, -half_height);
let mut screen_bottom_right = screen_center;
screen_bottom_right
.add_scaled_vector(&right, half_width)
.add_scaled_vector(&up, -half_height);
let mut screen_top_left = screen_center;
screen_top_left
.add_scaled_vector(&right, -half_width)
.add_scaled_vector(&up, half_height);
for (eye, position) in [(&mut stereo.camera_l, eye_l), (&mut stereo.camera_r, eye_r)] {
eye.node.borrow_mut().position = position;
eye.near = camera.near;
eye.far = camera.far;
frame_corners(
eye,
&screen_bottom_left,
&screen_bottom_right,
&screen_top_left,
true,
);
let matrix_world = {
let mut object = eye.node.borrow_mut();
let (position, quaternion, scale) = (object.position, object.quaternion, object.scale);
object.matrix_world.compose(&position, &quaternion, &scale);
object.matrix_world
};
eye.matrix_world_inverse = matrix_world;
eye.matrix_world_inverse.invert();
}
}