use std::cell::{Cell, OnceCell};
use std::rc::Rc;
use crate::materials::{MaterialKind, MeshBasicNodeMaterial};
use crate::math::Color;
use crate::nodes::tsl::{
block, camera_projection_matrix, camera_view_matrix, custom, float, mix, position_world,
screen_size, texture_uv, to_varying, uv, vec2, vec4_join,
};
use crate::nodes::{ContextValue, CustomNode, NodeBuilder, NodeRef, Type};
use crate::renderer::{CameraRef, PassNode, PassOptions, RenderObjectFunction, SceneRef};
use crate::textures::TextureFilter;
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct RetroPassOptions {
pub affine_distortion: Option<NodeRef>,
pub filter_textures: bool,
}
impl RetroPassOptions {
pub fn affine_distortion(mut self, node: impl Into<NodeRef>) -> Self {
self.affine_distortion = Some(node.into());
self
}
pub fn filter_textures(mut self, filter_textures: bool) -> Self {
self.filter_textures = filter_textures;
self
}
}
pub struct RetroPassNode {
pass: PassNode,
node: NodeRef,
function: Rc<RetroFunction>,
}
pub fn retro_pass(scene: SceneRef, camera: CameraRef, options: RetroPassOptions) -> RetroPassNode {
RetroPassNode::new(scene, camera, options)
}
impl RetroPassNode {
pub fn new(scene: SceneRef, camera: CameraRef, options: RetroPassOptions) -> Self {
let pass = PassNode::new_with_options(PassOptions {
min_filter: TextureFilter::Nearest,
mag_filter: TextureFilter::Nearest,
..PassOptions::default()
});
pass.set_scene(scene, camera);
pass.set_resolution_scale(0.25);
let function = Rc::new(RetroFunction {
affine_distortion: options.affine_distortion,
filter_textures: Cell::new(options.filter_textures),
id: next_id(),
});
pass.set_render_object_function(Some(function.clone()));
let node = custom(RetroTextureNode { pass: pass.clone() });
Self {
pass,
node,
function,
}
}
pub fn node(&self) -> NodeRef {
self.node.clone()
}
pub fn pass(&self) -> &PassNode {
&self.pass
}
pub fn set_filter_textures(&self, filter_textures: bool) {
self.function.filter_textures.set(filter_textures);
}
pub fn filter_textures(&self) -> bool {
self.function.filter_textures.get()
}
pub fn affine_distortion(&self) -> Option<NodeRef> {
self.function.affine_distortion.clone()
}
}
impl From<&RetroPassNode> for NodeRef {
fn from(retro: &RetroPassNode) -> NodeRef {
retro.node()
}
}
fn next_id() -> usize {
thread_local! { static NEXT: Cell<usize> = const { Cell::new(0) }; }
NEXT.with(|n| {
let id = n.get();
n.set(id + 1);
id
})
}
struct RetroTextureNode {
pass: PassNode,
}
impl CustomNode for RetroTextureNode {
fn type_name(&self) -> &'static str {
"PassTextureNode"
}
fn node_type(&self) -> Type {
Type::Vec4
}
fn setup(&self, builder: &NodeBuilder) -> NodeRef {
let coord = builder.context("getUV").unwrap_or_else(uv);
texture_uv(&self.pass.texture(), coord)
}
}
struct ClipSpaceRetro {
affine_uv: NodeRef,
w: NodeRef,
position: NodeRef,
}
fn clip_space_retro() -> Rc<ClipSpaceRetro> {
thread_local! { static CELL: OnceCell<Rc<ClipSpaceRetro>> = const { OnceCell::new() }; }
CELL.with(|c| {
c.get_or_init(|| {
let affine_uv = to_varying(None, vec2(0.0, 0.0));
let w = to_varying(None, float(0.0));
let default_position = camera_projection_matrix()
.mul(camera_view_matrix())
.mul(position_world());
let half_w = default_position.w().mul(2.0);
let rounded_position = default_position
.xy()
.div(half_w.clone())
.mul(screen_size().xy())
.round()
.div(screen_size().xy())
.mul(half_w);
let assign_affine_uv = affine_uv.assign(uv().mul(default_position.w()));
let assign_w = w.assign(default_position.w());
let position = block(
vec![assign_affine_uv, assign_w],
vec4_join(vec![rounded_position.xy(), default_position.zw()]),
);
Rc::new(ClipSpaceRetro {
affine_uv,
w,
position,
})
})
.clone()
})
}
pub(crate) fn is_node_material(material: &MeshBasicNodeMaterial) -> bool {
let m = material;
[
&m.color_node,
&m.opacity_node,
&m.alpha_test_node,
&m.emissive_node,
&m.mask_node,
&m.cast_shadow_node,
&m.received_shadow_position_node,
&m.specular_node,
&m.normal_node,
&m.position_node,
&m.scale_node,
&m.rotation_node,
&m.size_node,
&m.vertex_node,
&m.fragment_node,
&m.output_node,
&m.backdrop_node,
&m.backdrop_alpha_node,
&m.metalness_node,
&m.roughness_node,
&m.depth_node,
]
.iter()
.any(|slot| slot.is_some())
|| m.mrt_node.is_some()
|| m.context_overrides.is_some()
|| m.context_node.is_some()
|| m.lighting_model.is_some()
|| m.lights_node.is_some()
}
struct RetroFunction {
affine_distortion: Option<NodeRef>,
filter_textures: Cell<bool>,
id: usize,
}
impl RenderObjectFunction for RetroFunction {
fn material(&self, source: &MeshBasicNodeMaterial, background: bool) -> MeshBasicNodeMaterial {
let mut material = source.clone();
let basic = match source.kind {
MaterialKind::Basic => true,
MaterialKind::Phong
| MaterialKind::Lambert
| MaterialKind::Standard
| MaterialKind::Physical
| MaterialKind::Toon => false,
_ => return material,
};
if background {
return material;
}
if !basic {
if source.kind != MaterialKind::Phong {
let phong = MeshBasicNodeMaterial::phong(Color::new(1.0, 1.0, 1.0));
material.specular = phong.specular;
material.shininess = phong.shininess;
}
material.kind = MaterialKind::Phong;
material.lights = source.lights || !is_node_material(source);
}
if is_node_material(source) {
return material;
}
let clip = clip_space_retro();
material.vertex_node = Some(clip.position.clone());
material.color_node = None;
let mut context = ContextValue::new();
if let Some(affine) = &self.affine_distortion {
context = context.set(
"getUV",
mix(uv(), clip.affine_uv.div(clip.w.clone()), affine.clone()),
);
}
if !self.filter_textures.get() {
context = context.set("getTextureLevel", float(0.0));
}
material.context_node = Some(context);
material
}
fn variant(&self) -> u64 {
(self.id as u64) << 1 | u64::from(self.filter_textures.get())
}
}