From 1c47e5499e22e60d186d72b54f3e223343a0998b Mon Sep 17 00:00:00 2001 From: Laurent Valdes Date: Sat, 19 Apr 2025 21:12:52 +0200 Subject: [PATCH 01/28] fix(webgpu): implement canvas surface creation for WebAssembly target - Add SurfaceTarget::Canvas implementation for WebGPU surface creation\n- Enable wgsl feature in wgpu dependency\n- Fix shader source import using proper Cow::Borrowed syntax\n- Add necessary web-sys canvas features in Cargo.toml --- clickplanet-webapp/Cargo.toml | 6 +- .../src/app/components/create_sphere.rs | 62 ++++ .../src/app/components/globe.rs | 58 +++- .../src/app/components/globe.wgsl | 32 ++ .../src/app/components/setup_webgpu.rs | 296 ++++++++++++++++++ 5 files changed, 440 insertions(+), 14 deletions(-) create mode 100644 clickplanet-webapp/src/app/components/create_sphere.rs create mode 100644 clickplanet-webapp/src/app/components/globe.wgsl create mode 100644 clickplanet-webapp/src/app/components/setup_webgpu.rs diff --git a/clickplanet-webapp/Cargo.toml b/clickplanet-webapp/Cargo.toml index 4a14f42..bdc9be8 100644 --- a/clickplanet-webapp/Cargo.toml +++ b/clickplanet-webapp/Cargo.toml @@ -21,7 +21,7 @@ web-sys = { version = "0.3", features = [ "WebSocket", "MessageEvent", "CloseEvent", "ErrorEvent", "console", "Window", "Document", "Element", "HtmlElement", "Node", "BinaryType", "CanvasRenderingContext2d", "HtmlCanvasElement", "MouseEvent", "EventTarget", - "EventListener", "Event", "DomRect"] } + "EventListener", "Event", "DomRect", "GpuCanvasContext", "Navigator" ] } js-sys = "0.3" serde-wasm-bindgen = "0.6.5" serde.workspace = true @@ -55,6 +55,10 @@ dioxus-router = "0.6.3" console_log = "1.0.0" log = "0.4.21" +wgpu = { version = "25.0.0", features = ["webgl", "webgpu", "wgsl"], default-features = false } +bytemuck = { version = "1.14", features = ["derive"] } +raw-window-handle = "0.6.0" + # Enable/disable features based on target [target.'cfg(not(target_arch = "wasm32"))'.dependencies] reqwest = { version = "0.12.9", features = ["json"] } diff --git a/clickplanet-webapp/src/app/components/create_sphere.rs b/clickplanet-webapp/src/app/components/create_sphere.rs new file mode 100644 index 0000000..a43294f --- /dev/null +++ b/clickplanet-webapp/src/app/components/create_sphere.rs @@ -0,0 +1,62 @@ +use std::f32::consts::PI; +use bytemuck::{Pod, Zeroable}; + +/// Vertex data for the globe mesh +#[repr(C)] +#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)] +pub struct Vertex { + pub position: [f32; 3], + pub normal: [f32; 3], +} + +/// Create a UV sphere with the given radius and segment counts +pub fn create_sphere(radius: f32, latitude_segments: u32, longitude_segments: u32) -> (Vec, Vec) { + let mut vertices = Vec::new(); + let mut indices = Vec::new(); + + // Generate vertices + for lat in 0..=latitude_segments { + let theta = lat as f32 * PI / latitude_segments as f32; + let sin_theta = theta.sin(); + let cos_theta = theta.cos(); + + for lon in 0..=longitude_segments { + let phi = lon as f32 * 2.0 * PI / longitude_segments as f32; + let sin_phi = phi.sin(); + let cos_phi = phi.cos(); + + // Calculate vertex position + let x = cos_phi * sin_theta; + let y = cos_theta; + let z = sin_phi * sin_theta; + + // Position multiplied by radius + let position = [x * radius, y * radius, z * radius]; + + // Normal is just the normalized position for a sphere + let normal = [x, y, z]; + + vertices.push(Vertex { position, normal }); + } + } + + // Generate indices for triangle strips + for lat in 0..latitude_segments { + for lon in 0..longitude_segments { + let first = lat * (longitude_segments + 1) + lon; + let second = first + longitude_segments + 1; + + // First triangle + indices.push(first as u16); + indices.push(second as u16); + indices.push((first + 1) as u16); + + // Second triangle + indices.push(second as u16); + indices.push((second + 1) as u16); + indices.push((first + 1) as u16); + } + } + + (vertices, indices) +} diff --git a/clickplanet-webapp/src/app/components/globe.rs b/clickplanet-webapp/src/app/components/globe.rs index 1f9985e..af5f2c8 100644 --- a/clickplanet-webapp/src/app/components/globe.rs +++ b/clickplanet-webapp/src/app/components/globe.rs @@ -1,19 +1,51 @@ use dioxus::prelude::*; +use log::{debug, error}; +use web_sys::HtmlCanvasElement; +use wasm_bindgen::JsCast; +use wasm_bindgen_futures; +use crate::app::components::setup_webgpu::setup_webgpu; -// Updated for Dioxus 0.6.x compatibility -pub fn GlobeMock() -> Element { +#[component] +pub fn globe() -> Element { + let mut canvas_ref = use_signal(|| None::); + + use_effect(move || { + to_owned![canvas_ref]; + wasm_bindgen_futures::spawn_local(async move { + if let Some(canvas) = canvas_ref.read().clone() { + debug!("Canvas found - initializing WebGPU"); + // Hand off to setup_webgpu for real initialization + setup_webgpu(canvas).await; + } else { + error!("No canvas found for globe rendering"); + } + }); + + () + }); + rsx! { - div { - class: "globe-container", - style: "position: absolute; width: 100%; height: 100%; top: 0; left: 0; display: flex; justify-content: center; align-items: center; background-color: #1a1a2e;", - - div { - style: "text-align: center; color: white; padding: 20px; background-color: rgba(0,0,0,0.5); border-radius: 8px;", - h2 { "Globe Component" } - p { "This is a temporary placeholder while the interactive globe is being fixed." } - p { "The full interactive globe will be restored soon." } + div { + style: "width: 100%; height: 100%; overflow: hidden;", + canvas { + id: "globe-canvas", + style: "width: 100%; height: 100%; display: block; background-color: #001020;", + onmounted: move |_| { + debug!("Canvas mounted"); + let window = web_sys::window().expect("no global window"); + let document = window.document().expect("no document on window"); + if let Some(element) = document.get_element_by_id("globe-canvas") { + if let Some(canvas) = element.dyn_ref::() { + debug!("Canvas element captured"); + canvas_ref.set(Some(canvas.clone())); + } else { + error!("Failed to convert to HtmlCanvasElement"); + } + } else { + error!("Could not find canvas element with ID 'globe-canvas'"); + } + } } } } -} - +} \ No newline at end of file diff --git a/clickplanet-webapp/src/app/components/globe.wgsl b/clickplanet-webapp/src/app/components/globe.wgsl new file mode 100644 index 0000000..8746af7 --- /dev/null +++ b/clickplanet-webapp/src/app/components/globe.wgsl @@ -0,0 +1,32 @@ +struct Uniforms { + mvp: mat4x4; +}; + +@group(0) @binding(0) +var uniforms: Uniforms; + +struct VertexInput { + @location(0) position: vec3; + @location(1) normal: vec3; +}; + +struct VertexOutput { + @builtin(position) Position: vec4; + @location(0) v_normal: vec3; +}; + +@vertex +fn vs_main(input: VertexInput) -> VertexOutput { + var out: VertexOutput; + out.Position = uniforms.mvp * vec4(input.position, 1.0); + out.v_normal = input.normal; + return out; +} + +@fragment +fn fs_main(in: VertexOutput) -> @location(0) vec4 { + let light = normalize(vec3(1.0, 1.0, 1.0)); + let brightness = max(dot(in.v_normal, light), 0.0); + let color = vec3(0.2, 0.5, 1.0) * brightness + vec3(0.1); + return vec4(color, 1.0); +} diff --git a/clickplanet-webapp/src/app/components/setup_webgpu.rs b/clickplanet-webapp/src/app/components/setup_webgpu.rs new file mode 100644 index 0000000..0d7e18e --- /dev/null +++ b/clickplanet-webapp/src/app/components/setup_webgpu.rs @@ -0,0 +1,296 @@ +use wasm_bindgen::prelude::*; +use web_sys::HtmlCanvasElement; +use wgpu::SurfaceTarget; +use wgpu::util::DeviceExt; +use glam::{Mat4, Vec3}; +use std::cell::RefCell; +use std::rc::Rc; +use std::f32::consts::PI; +use log::{info, debug, error}; + +use crate::app::components::create_sphere::Vertex; + +/// Uniform buffer data for transformations +#[repr(C)] +#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)] +pub struct Uniforms { + pub mvp: [[f32; 4]; 4], +} + +/// Set up WebGPU and start the rendering loop +pub async fn setup_webgpu(canvas: HtmlCanvasElement) { + info!("Setting up WebGPU for globe rendering"); + let width = canvas.client_width() as u32; + let height = canvas.client_height() as u32; + + // Create WGPU instance + let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor { + backends: wgpu::Backends::all(), + flags: wgpu::InstanceFlags::default(), + backend_options: Default::default(), + }); + + debug!("Created WebGPU instance"); + + // For WebGPU in the browser, we need to create a surface from the canvas + // In wgpu 25.0, we use SurfaceTarget::Canvas + let surface_target = SurfaceTarget::Canvas(canvas.clone()); + let surface = instance + .create_surface(surface_target) + .expect("Failed to create surface from canvas"); + + // Request adapter + let adapter = instance.request_adapter(&wgpu::RequestAdapterOptions { + power_preference: wgpu::PowerPreference::default(), + compatible_surface: Some(&surface), + force_fallback_adapter: false, + }).await.expect("Failed to find appropriate adapter"); + + // Create device and queue + let (device, queue) = adapter.request_device( + &wgpu::DeviceDescriptor { + label: Some("Globe Device"), + required_features: wgpu::Features::empty(), + required_limits: wgpu::Limits::downlevel_webgl2_defaults(), + memory_hints: wgpu::MemoryHints::default(), + trace: wgpu::Trace::default(), + } + ).await.expect("Failed to create device"); + + // Get preferred format + let capabilities = surface.get_capabilities(&adapter); + let surface_format = capabilities.formats[0]; + + // Configure the surface + let config = wgpu::SurfaceConfiguration { + usage: wgpu::TextureUsages::RENDER_ATTACHMENT, + format: surface_format, + width, + height, + present_mode: wgpu::PresentMode::Fifo, + alpha_mode: wgpu::CompositeAlphaMode::Auto, + view_formats: vec![], + desired_maximum_frame_latency: 2, + }; + surface.configure(&device, &config); + + // Create sphere mesh + // let (vertices, indices) = create_sphere(1.0, 32, 32); + let vertices: Vec = Vec::new(); + let indices: Vec = Vec::new(); + + // Create vertex buffer + let vertex_buffer = device.create_buffer_init( + &wgpu::util::BufferInitDescriptor { + label: Some("Vertex Buffer"), + contents: bytemuck::cast_slice(&vertices), + usage: wgpu::BufferUsages::VERTEX, + } + ); + + // Create index buffer + let index_buffer = device.create_buffer_init( + &wgpu::util::BufferInitDescriptor { + label: Some("Index Buffer"), + contents: bytemuck::cast_slice(&indices), + usage: wgpu::BufferUsages::INDEX, + } + ); + let num_indices = indices.len() as u32; + + // Create uniform buffer for MVP matrix + let uniform_buffer = device.create_buffer_init( + &wgpu::util::BufferInitDescriptor { + label: Some("Uniform Buffer"), + contents: bytemuck::cast_slice(&[ + Uniforms { + mvp: Mat4::IDENTITY.to_cols_array_2d(), + } + ]), + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + } + ); + + // Create bind group layout + let bind_group_layout = device.create_bind_group_layout( + &wgpu::BindGroupLayoutDescriptor { + label: Some("Bind Group Layout"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::VERTEX, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }, + ], + } + ); + + // Create bind group + let bind_group = device.create_bind_group( + &wgpu::BindGroupDescriptor { + label: Some("Bind Group"), + layout: &bind_group_layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: uniform_buffer.as_entire_binding(), + }, + ], + } + ); + + // Create shader module + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("Globe Shader"), + source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(include_str!("globe.wgsl"))), + }); + + // Create render pipeline layout + let pipeline_layout = device.create_pipeline_layout( + &wgpu::PipelineLayoutDescriptor { + label: Some("Render Pipeline Layout"), + bind_group_layouts: &[&bind_group_layout], + push_constant_ranges: &[], + } + ); + + // Create render pipeline + let render_pipeline = device.create_render_pipeline( + &wgpu::RenderPipelineDescriptor { + cache: None, + label: Some("Render Pipeline"), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("vs_main"), + compilation_options: wgpu::PipelineCompilationOptions::default(), + buffers: &[ + wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::() as wgpu::BufferAddress, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &wgpu::vertex_attr_array![ + 0 => Float32x3, // position + 1 => Float32x3, // normal + ], + }, + ], + }, + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some("fs_main"), + compilation_options: wgpu::PipelineCompilationOptions::default(), + targets: &[Some(wgpu::ColorTargetState { + format: config.format, + blend: Some(wgpu::BlendState::REPLACE), + write_mask: wgpu::ColorWrites::ALL, + })], + }), + primitive: wgpu::PrimitiveState { + topology: wgpu::PrimitiveTopology::TriangleList, + strip_index_format: None, + front_face: wgpu::FrontFace::Ccw, + cull_mode: Some(wgpu::Face::Back), + unclipped_depth: false, + polygon_mode: wgpu::PolygonMode::Fill, + conservative: false, + }, + depth_stencil: None, + multisample: wgpu::MultisampleState { + count: 1, + mask: !0, + alpha_to_coverage_enabled: false, + }, + multiview: None, + } + ); + + // Animation loop variables + /*let animation = Rc::new(RefCell::new(None)); + let animation_clone = animation.clone(); + + // Define the animation function + *animation.borrow_mut() = Some(Closure::wrap(Box::new(move || { + // Update the rotation + let now = web_sys::window().unwrap().performance().unwrap().now(); + let rotation = now / 2000.0; // Full rotation every 2 seconds + + // Update MVP matrix - here we're just rotating around Y axis + let mvp = { + let model = Mat4::from_rotation_y(rotation as f32); + let view = Mat4::look_at_rh( + Vec3::new(0.0, 0.0, 2.5), // Eye position + Vec3::new(0.0, 0.0, 0.0), // Look at center + Vec3::new(0.0, 1.0, 0.0), // Up direction + ); + let proj = Mat4::perspective_rh( + PI / 4.0, // FOV + width as f32 / height as f32, // Aspect ratio + 0.1, // Near plane + 10.0, // Far plane + ); + (proj * view * model).to_cols_array_2d() + }; + + // Update uniform buffer + let uniforms = Uniforms { mvp }; + queue.write_buffer(&uniform_buffer, 0, bytemuck::cast_slice(&[uniforms])); + + // Render frame + match surface.get_current_texture() { + Ok(frame) => { + let view = frame.texture.create_view(&wgpu::TextureViewDescriptor::default()); + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None }); + { + let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("Render Pass"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &view, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color { + r: 0.0, + g: 0.0, + b: 0.1, + a: 1.0, + }), + store: wgpu::StoreOp::Store, + }, + })], + depth_stencil_attachment: None, + occlusion_query_set: None, + timestamp_writes: None, + }); + + render_pass.set_pipeline(&render_pipeline); + render_pass.set_bind_group(0, &bind_group, &[]); + render_pass.set_vertex_buffer(0, vertex_buffer.slice(..)); + render_pass.set_index_buffer(index_buffer.slice(..), wgpu::IndexFormat::Uint16); + render_pass.draw_indexed(0..num_indices, 0, 0..1); + } + + queue.submit(Some(encoder.finish())); + frame.present(); + } + Err(e) => { + error!("Failed to get current texture: {:?}", e); + } + } + + // Request next frame + web_sys::window() + .unwrap() + .request_animation_frame(animation_clone.borrow().as_ref().unwrap().as_ref().unchecked_ref()) + .unwrap(); + }) as Box)); + + // Start animation loop + web_sys::window() + .unwrap() + .request_animation_frame(animation_clone.borrow().as_ref().unwrap().as_ref().unchecked_ref()) + .unwrap();*/ +} From bb1ba4a45f7bde71a3f5a2cb68bb6080c52200af Mon Sep 17 00:00:00 2001 From: Laurent Valdes Date: Sat, 19 Apr 2025 21:18:19 +0200 Subject: [PATCH 02/28] feat(webgpu): implement animated Earth globe rendering - Add signal-based animation system with rotation control\n- Implement proper WebGPU rendering loop with Dioxus timing pattern\n- Configure depth testing and 3D rendering pipeline\n- Create animation loop with browser-friendly async yields\n- Add gloo-timers dependency for animation timing --- clickplanet-webapp/Cargo.toml | 3 +- .../src/app/components/globe.rs | 15 +- .../src/app/components/setup_webgpu.rs | 244 +++++++++++------- 3 files changed, 160 insertions(+), 102 deletions(-) diff --git a/clickplanet-webapp/Cargo.toml b/clickplanet-webapp/Cargo.toml index bdc9be8..4d2b8cb 100644 --- a/clickplanet-webapp/Cargo.toml +++ b/clickplanet-webapp/Cargo.toml @@ -58,6 +58,7 @@ log = "0.4.21" wgpu = { version = "25.0.0", features = ["webgl", "webgpu", "wgsl"], default-features = false } bytemuck = { version = "1.14", features = ["derive"] } raw-window-handle = "0.6.0" +gloo-timers = { version = "0.3.0", features = ["futures"] } # Enable/disable features based on target [target.'cfg(not(target_arch = "wasm32"))'.dependencies] @@ -74,4 +75,4 @@ console_log = "1.0.0" log = "0.4.22" wasm-bindgen-futures = "0.4.39" gloo-timers = "0.3.0" -lazy_static = "1.4.0" \ No newline at end of file +lazy_static = "1.4.0" diff --git a/clickplanet-webapp/src/app/components/globe.rs b/clickplanet-webapp/src/app/components/globe.rs index af5f2c8..c9b077d 100644 --- a/clickplanet-webapp/src/app/components/globe.rs +++ b/clickplanet-webapp/src/app/components/globe.rs @@ -1,21 +1,24 @@ use dioxus::prelude::*; -use log::{debug, error}; +use log::{debug, error, info}; use web_sys::HtmlCanvasElement; use wasm_bindgen::JsCast; use wasm_bindgen_futures; -use crate::app::components::setup_webgpu::setup_webgpu; +use crate::app::components::setup_webgpu::{setup_webgpu, use_animation_state}; #[component] pub fn globe() -> Element { let mut canvas_ref = use_signal(|| None::); + // Create animation state signal that will be used for rotation + let rotation = use_animation_state(); + use_effect(move || { - to_owned![canvas_ref]; + to_owned![canvas_ref, rotation]; wasm_bindgen_futures::spawn_local(async move { if let Some(canvas) = canvas_ref.read().clone() { - debug!("Canvas found - initializing WebGPU"); - // Hand off to setup_webgpu for real initialization - setup_webgpu(canvas).await; + info!("Canvas found - initializing WebGPU Earth rendering"); + // Hand off to setup_webgpu for real initialization with animation signal + setup_webgpu(canvas, rotation).await; } else { error!("No canvas found for globe rendering"); } diff --git a/clickplanet-webapp/src/app/components/setup_webgpu.rs b/clickplanet-webapp/src/app/components/setup_webgpu.rs index 0d7e18e..cb8aaf8 100644 --- a/clickplanet-webapp/src/app/components/setup_webgpu.rs +++ b/clickplanet-webapp/src/app/components/setup_webgpu.rs @@ -2,13 +2,15 @@ use wasm_bindgen::prelude::*; use web_sys::HtmlCanvasElement; use wgpu::SurfaceTarget; use wgpu::util::DeviceExt; -use glam::{Mat4, Vec3}; +use glam::{Mat4, Vec3, Quat}; use std::cell::RefCell; use std::rc::Rc; use std::f32::consts::PI; use log::{info, debug, error}; +use dioxus::prelude::*; +use wasm_bindgen_futures::spawn_local; -use crate::app::components::create_sphere::Vertex; +use crate::app::components::create_sphere::{Vertex, create_sphere}; /// Uniform buffer data for transformations #[repr(C)] @@ -17,8 +19,27 @@ pub struct Uniforms { pub mvp: [[f32; 4]; 4], } +/// Create a signal-based animation state for the globe +pub fn use_animation_state() -> Signal { + let rotation = use_signal(|| 0.0f32); + + use_effect(move || { + let mut rotation_state = rotation.clone(); + spawn_local(async move { + loop { + // Update rotation (in radians) + rotation_state.set(rotation_state() + 0.005); + // Yield to browser to avoid blocking the main thread + gloo_timers::future::TimeoutFuture::new(16).await; // ~60fps + } + }); + }); + + rotation +} + /// Set up WebGPU and start the rendering loop -pub async fn setup_webgpu(canvas: HtmlCanvasElement) { +pub async fn setup_webgpu(canvas: HtmlCanvasElement, rotation: Signal) { info!("Setting up WebGPU for globe rendering"); let width = canvas.client_width() as u32; let height = canvas.client_height() as u32; @@ -56,6 +77,8 @@ pub async fn setup_webgpu(canvas: HtmlCanvasElement) { trace: wgpu::Trace::default(), } ).await.expect("Failed to create device"); + + info!("Created device and queue"); // Get preferred format let capabilities = surface.get_capabilities(&adapter); @@ -74,10 +97,8 @@ pub async fn setup_webgpu(canvas: HtmlCanvasElement) { }; surface.configure(&device, &config); - // Create sphere mesh - // let (vertices, indices) = create_sphere(1.0, 32, 32); - let vertices: Vec = Vec::new(); - let indices: Vec = Vec::new(); + // Create Earth sphere mesh with proper dimensions + let (vertices, indices) = create_sphere(1.0, 64, 128); // Create vertex buffer let vertex_buffer = device.create_buffer_init( @@ -87,7 +108,7 @@ pub async fn setup_webgpu(canvas: HtmlCanvasElement) { usage: wgpu::BufferUsages::VERTEX, } ); - + // Create index buffer let index_buffer = device.create_buffer_init( &wgpu::util::BufferInitDescriptor { @@ -96,20 +117,23 @@ pub async fn setup_webgpu(canvas: HtmlCanvasElement) { usage: wgpu::BufferUsages::INDEX, } ); + let num_indices = indices.len() as u32; + + info!("Created mesh with {} vertices and {} indices", vertices.len(), indices.len()); - // Create uniform buffer for MVP matrix + // Create uniform buffer let uniform_buffer = device.create_buffer_init( &wgpu::util::BufferInitDescriptor { label: Some("Uniform Buffer"), - contents: bytemuck::cast_slice(&[ - Uniforms { - mvp: Mat4::IDENTITY.to_cols_array_2d(), - } - ]), + contents: bytemuck::cast_slice(&[Uniforms { + mvp: Mat4::IDENTITY.to_cols_array_2d(), + }]), usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, } ); + + info!("Created uniform buffer"); // Create bind group layout let bind_group_layout = device.create_bind_group_layout( @@ -173,10 +197,7 @@ pub async fn setup_webgpu(canvas: HtmlCanvasElement) { wgpu::VertexBufferLayout { array_stride: std::mem::size_of::() as wgpu::BufferAddress, step_mode: wgpu::VertexStepMode::Vertex, - attributes: &wgpu::vertex_attr_array![ - 0 => Float32x3, // position - 1 => Float32x3, // normal - ], + attributes: &wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3], }, ], }, @@ -185,7 +206,7 @@ pub async fn setup_webgpu(canvas: HtmlCanvasElement) { entry_point: Some("fs_main"), compilation_options: wgpu::PipelineCompilationOptions::default(), targets: &[Some(wgpu::ColorTargetState { - format: config.format, + format: surface_format, blend: Some(wgpu::BlendState::REPLACE), write_mask: wgpu::ColorWrites::ALL, })], @@ -195,11 +216,17 @@ pub async fn setup_webgpu(canvas: HtmlCanvasElement) { strip_index_format: None, front_face: wgpu::FrontFace::Ccw, cull_mode: Some(wgpu::Face::Back), - unclipped_depth: false, polygon_mode: wgpu::PolygonMode::Fill, + unclipped_depth: false, conservative: false, }, - depth_stencil: None, + depth_stencil: Some(wgpu::DepthStencilState { + format: wgpu::TextureFormat::Depth24Plus, + depth_write_enabled: true, + depth_compare: wgpu::CompareFunction::LessEqual, + stencil: wgpu::StencilState::default(), + bias: wgpu::DepthBiasState::default(), + }), multisample: wgpu::MultisampleState { count: 1, mask: !0, @@ -208,89 +235,116 @@ pub async fn setup_webgpu(canvas: HtmlCanvasElement) { multiview: None, } ); - - // Animation loop variables - /*let animation = Rc::new(RefCell::new(None)); - let animation_clone = animation.clone(); - // Define the animation function - *animation.borrow_mut() = Some(Closure::wrap(Box::new(move || { - // Update the rotation - let now = web_sys::window().unwrap().performance().unwrap().now(); - let rotation = now / 2000.0; // Full rotation every 2 seconds + info!("Created render pipeline"); - // Update MVP matrix - here we're just rotating around Y axis - let mvp = { - let model = Mat4::from_rotation_y(rotation as f32); + // Create depth texture + let depth_texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("Depth Texture"), + size: wgpu::Extent3d { + width, + height, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Depth24Plus, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT, + view_formats: &[], + }); + + let depth_view = depth_texture.create_view(&wgpu::TextureViewDescriptor::default()); + + // Start animation loop + spawn_local(async move { + loop { + // Get current rotation + let current_rotation = rotation(); + + // Create model-view-projection matrix + let model = Mat4::from_rotation_y(current_rotation); let view = Mat4::look_at_rh( - Vec3::new(0.0, 0.0, 2.5), // Eye position - Vec3::new(0.0, 0.0, 0.0), // Look at center - Vec3::new(0.0, 1.0, 0.0), // Up direction + Vec3::new(0.0, 0.0, 3.0), // Camera position + Vec3::new(0.0, 0.0, 0.0), // Look at center + Vec3::new(0.0, 1.0, 0.0), // Up vector ); - let proj = Mat4::perspective_rh( - PI / 4.0, // FOV - width as f32 / height as f32, // Aspect ratio - 0.1, // Near plane - 10.0, // Far plane + let aspect = width as f32 / height as f32; + let proj = Mat4::perspective_rh(45.0f32.to_radians(), aspect, 0.1, 100.0); + + let mvp = proj * view * model; + + // Update uniform buffer + queue.write_buffer( + &uniform_buffer, + 0, + bytemuck::cast_slice(&[Uniforms { + mvp: mvp.to_cols_array_2d(), + }]), ); - (proj * view * model).to_cols_array_2d() - }; - - // Update uniform buffer - let uniforms = Uniforms { mvp }; - queue.write_buffer(&uniform_buffer, 0, bytemuck::cast_slice(&[uniforms])); - - // Render frame - match surface.get_current_texture() { - Ok(frame) => { - let view = frame.texture.create_view(&wgpu::TextureViewDescriptor::default()); - let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None }); - { - let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { - label: Some("Render Pass"), - color_attachments: &[Some(wgpu::RenderPassColorAttachment { - view: &view, - resolve_target: None, - ops: wgpu::Operations { - load: wgpu::LoadOp::Clear(wgpu::Color { - r: 0.0, - g: 0.0, - b: 0.1, - a: 1.0, - }), - store: wgpu::StoreOp::Store, - }, - })], - depth_stencil_attachment: None, - occlusion_query_set: None, - timestamp_writes: None, + + // Get a frame + match surface.get_current_texture() { + Ok(frame) => { + let view = frame.texture.create_view(&wgpu::TextureViewDescriptor::default()); + + // Create command encoder + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("Render Encoder"), }); - render_pass.set_pipeline(&render_pipeline); - render_pass.set_bind_group(0, &bind_group, &[]); - render_pass.set_vertex_buffer(0, vertex_buffer.slice(..)); - render_pass.set_index_buffer(index_buffer.slice(..), wgpu::IndexFormat::Uint16); - render_pass.draw_indexed(0..num_indices, 0, 0..1); + // Create render pass + { + let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("Main Render Pass"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &view, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color { + r: 0.05, + g: 0.1, + b: 0.2, + a: 1.0, + }), + store: wgpu::StoreOp::Store, + }, + })], + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + view: &depth_view, + depth_ops: Some(wgpu::Operations { + load: wgpu::LoadOp::Clear(1.0), + store: wgpu::StoreOp::Store, + }), + stencil_ops: None, + }), + occlusion_query_set: None, + timestamp_writes: None, + }); + + // Set pipeline and bind groups + render_pass.set_pipeline(&render_pipeline); + render_pass.set_bind_group(0, &bind_group, &[]); + render_pass.set_vertex_buffer(0, vertex_buffer.slice(..)); + render_pass.set_index_buffer(index_buffer.slice(..), wgpu::IndexFormat::Uint16); + + // Draw the sphere + render_pass.draw_indexed(0..num_indices, 0, 0..1); + } + + // Submit commands + queue.submit(std::iter::once(encoder.finish())); + frame.present(); + }, + Err(e) => { + error!("Failed to get current texture: {:?}", e); } - - queue.submit(Some(encoder.finish())); - frame.present(); - } - Err(e) => { - error!("Failed to get current texture: {:?}", e); } + + // Yield to browser to avoid blocking the main thread + gloo_timers::future::TimeoutFuture::new(16).await; // ~60fps } - - // Request next frame - web_sys::window() - .unwrap() - .request_animation_frame(animation_clone.borrow().as_ref().unwrap().as_ref().unchecked_ref()) - .unwrap(); - }) as Box)); + }); - // Start animation loop - web_sys::window() - .unwrap() - .request_animation_frame(animation_clone.borrow().as_ref().unwrap().as_ref().unchecked_ref()) - .unwrap();*/ + info!("Started animation loop"); } From e7788c9bd48ade63de9fe99fb024a6cc36337ff0 Mon Sep 17 00:00:00 2001 From: Laurent Valdes Date: Sun, 20 Apr 2025 03:08:04 +0200 Subject: [PATCH 03/28] feat(earth): textured globe rendering with downscaled JPEG and WGSL shader --- .boa_history | 0 .windsurfrules | 11 +- Cargo.lock | 624 ++++++++++++++++-- clickplanet-client/Cargo.toml | 1 + .../__pycache__/download.cpython-311.pyc | Bin 0 -> 6113 bytes .../__pycache__/upload.cpython-311.pyc | Bin 0 -> 4982 bytes .../__pycache__/utils.cpython-311.pyc | Bin 0 -> 5725 bytes clickplanet-osm/project/metals.sbt | 8 + clickplanet-osm/project/project/metals.sbt | 8 + .../project/project/project/metals.sbt | 8 + clickplanet-webapp/Cargo.toml | 6 +- clickplanet-webapp/Dioxus.toml | 22 +- clickplanet-webapp/index.html | 14 +- clickplanet-webapp/rust-toolchain.toml | 3 + .../src/app/components/about.rs | 2 +- .../src/app/components/block_button.rs | 2 +- .../app/components/earth/animation_loop.rs | 121 ++++ .../components/{ => earth}/create_sphere.rs | 0 .../app/components/earth/earth_textured.wgsl | 48 ++ .../src/app/components/{ => earth}/globe.rs | 4 +- .../src/app/components/earth/mod.rs | 5 + .../src/app/components/earth/setup_webgpu.rs | 271 ++++++++ .../app/components/earth/shader_validation.rs | 57 ++ .../src/app/components/globe.wgsl | 32 - .../src/app/components/leaderboard.rs | 13 +- clickplanet-webapp/src/app/components/mod.rs | 12 + .../src/app/components/select_with_search.rs | 2 - .../src/app/components/settings.rs | 4 +- .../src/app/components/setup_webgpu.rs | 350 ---------- clickplanet-webapp/src/app/mod.rs | 3 + .../src/backends/http_backend.rs | 3 +- clickplanet-webapp/src/backends/mod.rs | 1 - clickplanet-webapp/src/main.rs | 101 +-- package-lock.json | 6 + 34 files changed, 1192 insertions(+), 550 deletions(-) create mode 100644 .boa_history create mode 100644 clickplanet-osm/download-job/__pycache__/download.cpython-311.pyc create mode 100644 clickplanet-osm/download-job/__pycache__/upload.cpython-311.pyc create mode 100644 clickplanet-osm/download-job/__pycache__/utils.cpython-311.pyc create mode 100644 clickplanet-osm/project/metals.sbt create mode 100644 clickplanet-osm/project/project/metals.sbt create mode 100644 clickplanet-osm/project/project/project/metals.sbt create mode 100644 clickplanet-webapp/rust-toolchain.toml create mode 100644 clickplanet-webapp/src/app/components/earth/animation_loop.rs rename clickplanet-webapp/src/app/components/{ => earth}/create_sphere.rs (100%) create mode 100644 clickplanet-webapp/src/app/components/earth/earth_textured.wgsl rename clickplanet-webapp/src/app/components/{ => earth}/globe.rs (93%) create mode 100644 clickplanet-webapp/src/app/components/earth/mod.rs create mode 100644 clickplanet-webapp/src/app/components/earth/setup_webgpu.rs create mode 100644 clickplanet-webapp/src/app/components/earth/shader_validation.rs delete mode 100644 clickplanet-webapp/src/app/components/globe.wgsl create mode 100644 clickplanet-webapp/src/app/components/mod.rs delete mode 100644 clickplanet-webapp/src/app/components/setup_webgpu.rs create mode 100644 clickplanet-webapp/src/app/mod.rs create mode 100644 package-lock.json diff --git a/.boa_history b/.boa_history new file mode 100644 index 0000000..e69de29 diff --git a/.windsurfrules b/.windsurfrules index b04d8b7..e42e214 100644 --- a/.windsurfrules +++ b/.windsurfrules @@ -46,14 +46,9 @@ Try to use trunk hot reload. It is does not work, instead of allocating a new po the frontend implementation is here: ./original-frontend the backend implementation is here: ./original-backend -The download/upload script should use the bucket that is listed in the gcloud storage ls command. -Do not modify production code for testing purposes, use environment variables instead. Pay attention to the environment variables you are using. -When designing the download/upload script, please take the size of the file in account (70 GB) and the nature of aria2. Which means, we should have enough place on the disk and the memory and we should write concurrently. -Also please when creating a download volume, think about deleting it after the operation. -Avoid using download-job/ directory for creating temporary files. -Do not use memory mount, since we are dealing with a 70 GB file. - Please read the documentation carefully. -Don't put fucking useless comments that are exact duplicates of the code. \ No newline at end of file +Don't put fucking useless comments that are exact duplicates of the code. + +Briefly explain what you are doing instead of just calling the tools. \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock index 8064d57..ddd2062 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -105,6 +105,18 @@ dependencies = [ "num-traits", ] +[[package]] +name = "arrayref" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" + +[[package]] +name = "arrayvec" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" + [[package]] name = "async-channel" version = "1.9.0" @@ -479,7 +491,7 @@ version = "0.69.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "271383c67ccabffb7381723dea0672a673f292304fcb45c01cc648c7a8d58088" dependencies = [ - "bitflags 2.6.0", + "bitflags 2.9.0", "cexpr", "clang-sys", "itertools", @@ -496,6 +508,21 @@ dependencies = [ "which", ] +[[package]] +name = "bit-set" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" + [[package]] name = "bitflags" version = "1.3.2" @@ -504,9 +531,24 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" -version = "2.6.0" +version = "2.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de" +checksum = "5c8214115b7bf84099f1309324e63141d4c5d7cc26862f97a0a857dbefe165bd" +dependencies = [ + "serde", +] + +[[package]] +name = "block-buffer" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0940dc441f31689269e10ac70eb1002a3a1d3ad1390e030043662eb7fe4688b" +dependencies = [ + "block-padding", + "byte-tools", + "byteorder", + "generic-array 0.12.4", +] [[package]] name = "block-buffer" @@ -514,7 +556,16 @@ version = "0.10.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" dependencies = [ - "generic-array", + "generic-array 0.14.7", +] + +[[package]] +name = "block-padding" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa79dedbb091f449f1f39e53edf88d5dbe95f895dae6135a8d7b881fb5af73f5" +dependencies = [ + "byte-tools", ] [[package]] @@ -586,11 +637,31 @@ version = "3.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c" +[[package]] +name = "byte-tools" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3b5ca7a04898ad4bcd41c90c5285445ff5b791899bb1b0abdd2a2aa791211d7" + [[package]] name = "bytemuck" -version = "1.20.0" +version = "1.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b37c88a63ffd85d15b406896cc343916d7cf57838a847b3a6f2ca5d39a5695a" +checksum = "b6b1fc10dbac614ebc03540c9dbd60e83887fda27794998c6528f1782047d540" +dependencies = [ + "bytemuck_derive", +] + +[[package]] +name = "bytemuck_derive" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ecc273b49b3205b83d648f0690daa588925572cc5063745bfe547fe7ec8e1a1" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] [[package]] name = "byteorder" @@ -639,6 +710,12 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" +[[package]] +name = "cfg_aliases" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" + [[package]] name = "chrono" version = "0.4.39" @@ -740,6 +817,7 @@ dependencies = [ "clickplanet-proto", "futures", "futures-util", + "imp", "prost", "rand 0.8.5", "rayon", @@ -849,6 +927,7 @@ dependencies = [ "anyhow", "async-trait", "base64 0.22.1", + "bytemuck", "clickplanet-proto", "console_log", "dioxus", @@ -867,6 +946,7 @@ dependencies = [ "log", "prost", "rand 0.8.5", + "raw-window-handle", "reqwest", "serde", "serde-wasm-bindgen 0.6.5", @@ -877,6 +957,7 @@ dependencies = [ "wasm-bindgen", "wasm-bindgen-futures", "web-sys", + "wgpu", ] [[package]] @@ -888,6 +969,17 @@ dependencies = [ "cc", ] +[[package]] +name = "codespan-reporting" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe6d2e5af09e8c8ad56c969f2157a3d4238cebc7c55f0a517728c38f7b200f81" +dependencies = [ + "serde", + "termcolor", + "unicode-width", +] + [[package]] name = "colorchoice" version = "1.0.3" @@ -1074,7 +1166,7 @@ version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" dependencies = [ - "generic-array", + "generic-array 0.14.7", "typenum", ] @@ -1087,7 +1179,7 @@ dependencies = [ "cfg-if", "cpufeatures", "curve25519-dalek-derive", - "digest", + "digest 0.10.7", "fiat-crypto", "rustc_version", "subtle", @@ -1241,13 +1333,22 @@ version = "0.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8" +[[package]] +name = "digest" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3d0c8c8752312f9713efd397ff63acb9f85585afbf179282e720e7704954dd5" +dependencies = [ + "generic-array 0.12.4", +] + [[package]] name = "digest" version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ - "block-buffer", + "block-buffer 0.10.4", "crypto-common", "subtle", ] @@ -1638,6 +1739,15 @@ dependencies = [ "serde_json", ] +[[package]] +name = "document-features" +version = "0.2.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95249b50c6c185bee49034bcb378a49dc2b5dff0be90ff6616d31d64febab05d" +dependencies = [ + "litrs", +] + [[package]] name = "dunce" version = "1.0.5" @@ -1661,7 +1771,7 @@ checksum = "4a3daa8e81a3963a60642bcc1f90a670680bd4a77535faa384e9d1c79d620871" dependencies = [ "curve25519-dalek", "ed25519", - "sha2", + "sha2 0.10.8", "signature", "subtle", ] @@ -1788,6 +1898,12 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "fake-simd" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e88a8acf291dafb59c2d96e8f59828f3838bb1a70398823ade51a84de6a6deed" + [[package]] name = "fallible-iterator" version = "0.2.0" @@ -1849,6 +1965,12 @@ version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + [[package]] name = "foreign-types" version = "0.3.2" @@ -1991,6 +2113,15 @@ dependencies = [ "tracing", ] +[[package]] +name = "generic-array" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffdf9f34f1447443d37393cc6c2b8313aebddcd96906caf34e54c68d8e57d7bd" +dependencies = [ + "typenum", +] + [[package]] name = "generic-array" version = "0.14.7" @@ -2056,6 +2187,17 @@ version = "0.31.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f" +[[package]] +name = "gl_generator" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a95dfc23a2b4a9a2f5ab41d194f8bfda3cabec42af4e39f08c339eb2a0c124d" +dependencies = [ + "khronos_api", + "log", + "xml-rs", +] + [[package]] name = "glam" version = "0.30.1" @@ -2272,6 +2414,27 @@ dependencies = [ "syn", ] +[[package]] +name = "glow" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5e5ea60d70410161c8bf5da3fdfeaa1c72ed2c15f8bbb9d19fe3a4fad085f08" +dependencies = [ + "js-sys", + "slotmap", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "glutin_wgl_sys" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c4ee00b289aba7a9e5306d57c2d05499b2e5dc427f84ac708bd2c090212cf3e" +dependencies = [ + "gl_generator", +] + [[package]] name = "h2" version = "0.4.7" @@ -2284,7 +2447,7 @@ dependencies = [ "futures-core", "futures-sink", "http 1.2.0", - "indexmap 2.7.0", + "indexmap 2.9.0", "slab", "tokio", "tokio-util", @@ -2293,12 +2456,13 @@ dependencies = [ [[package]] name = "half" -version = "2.4.1" +version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6dd08c532ae367adf81c312a4580bc67f1d0fe8bc9c460520283f4c0ff277888" +checksum = "459196ed295495a68f7d7fe1d84f6c4b7ff0e21fe3017b2f283c6fac3ad803c9" dependencies = [ "cfg-if", "crunchy", + "num-traits", ] [[package]] @@ -2327,6 +2491,9 @@ name = "hashbrown" version = "0.15.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bf151400ff0baff5465007dd2f3e717f3fe502074ca563069ce3a6629d07b289" +dependencies = [ + "foldhash", +] [[package]] name = "heapless" @@ -2362,13 +2529,19 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hexf-parse" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa686283ad6dd069f105e5ab091b04c62850d3e4cf5d67debad1933f55023df" + [[package]] name = "hmac" version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" dependencies = [ - "digest", + "digest 0.10.7", ] [[package]] @@ -2570,7 +2743,7 @@ dependencies = [ "iana-time-zone-haiku", "js-sys", "wasm-bindgen", - "windows-core", + "windows-core 0.52.0", ] [[package]] @@ -2737,6 +2910,18 @@ dependencies = [ "byteorder-lite", "num-traits", "png", + "zune-core", + "zune-jpeg", +] + +[[package]] +name = "imp" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "015f618e11715d4c739509a030fdac9278f2b036a74ca008889e95a9e186cc0e" +dependencies = [ + "arrayref", + "sha2 0.8.2", ] [[package]] @@ -2752,9 +2937,9 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.7.0" +version = "2.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62f822373a4fe84d4bb149bf54e584a7f4abec90e072ed49cda0edea5b95471f" +checksum = "cea70ddb795996207ad57735b50c5982d8844f38ba9ee5f1aedcfb708a2aa11e" dependencies = [ "equivalent", "hashbrown 0.15.2", @@ -2788,6 +2973,12 @@ version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d75a2a4b1b190afb6f5425f10f6a8f959d2ea0b9c2b1d79553551850539e4674" +[[package]] +name = "jni-sys" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130" + [[package]] name = "jobserver" version = "0.1.32" @@ -2813,9 +3004,26 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b750dcadc39a09dbadd74e118f6dd6598df77fa01df0cfcdc52c28dece74528a" dependencies = [ - "bitflags 2.6.0", + "bitflags 2.9.0", ] +[[package]] +name = "khronos-egl" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6aae1df220ece3c0ada96b8153459b67eebe9ae9212258bb0134ae60416fdf76" +dependencies = [ + "libc", + "libloading", + "pkg-config", +] + +[[package]] +name = "khronos_api" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc" + [[package]] name = "kv-log-macro" version = "1.0.7" @@ -2871,7 +3079,7 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d" dependencies = [ - "bitflags 2.6.0", + "bitflags 2.9.0", "libc", "redox_syscall 0.5.7", ] @@ -2888,6 +3096,12 @@ version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ee93343901ab17bd981295f2cf0026d4ad018c7c31ba84549a4ddbb47a45104" +[[package]] +name = "litrs" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ce301924b7887e9d637144fdade93f9dfff9b60981d4ac161db09720d39aa5" + [[package]] name = "lock_api" version = "0.4.12" @@ -2913,6 +3127,15 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b3bd0dd2cd90571056fdb71f6275fada10131182f84899f4b2a916e565d81d86" +[[package]] +name = "malloc_buf" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62bb907fe88d54d8d9ce32a3cceab4218ed2f6b7d35617cafe9adf84e43919cb" +dependencies = [ + "libc", +] + [[package]] name = "manganis" version = "0.6.2" @@ -2971,7 +3194,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" dependencies = [ "cfg-if", - "digest", + "digest 0.10.7", ] [[package]] @@ -3028,6 +3251,30 @@ version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "defc4c55412d89136f966bbb339008b474350e5e6e78d2714439c386b3137a03" +[[package]] +name = "naga" +version = "25.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b977c445f26e49757f9aca3631c3b8b836942cb278d69a92e7b80d3b24da632" +dependencies = [ + "arrayvec", + "bit-set", + "bitflags 2.9.0", + "cfg_aliases", + "codespan-reporting", + "half", + "hashbrown 0.15.2", + "hexf-parse", + "indexmap 2.9.0", + "log", + "num-traits", + "once_cell", + "rustc-hash", + "strum", + "thiserror 2.0.8", + "unicode-ident", +] + [[package]] name = "native-tls" version = "0.2.12" @@ -3045,6 +3292,15 @@ dependencies = [ "tempfile", ] +[[package]] +name = "ndk-sys" +version = "0.5.0+25.2.9519653" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c196769dd60fd4f363e11d948139556a344e79d451aeb2fa2fd040738ef7691" +dependencies = [ + "jni-sys", +] + [[package]] name = "nkeys" version = "0.3.2" @@ -3116,6 +3372,15 @@ dependencies = [ "libc", ] +[[package]] +name = "objc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "915b1b472bc21c53464d6c8461c9d3af805ba1ef837e1cac254428f4a77177b1" +dependencies = [ + "malloc_buf", +] + [[package]] name = "object" version = "0.36.5" @@ -3127,9 +3392,15 @@ dependencies = [ [[package]] name = "once_cell" -version = "1.20.2" +version = "1.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1261fe7e33c73b354eab43b1273a57c8f967d0391e80353e51f764ac02cf6775" +checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" + +[[package]] +name = "opaque-debug" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2839e79665f131bdb5782e51f2c6c9599c133c6098982a54c794358bf432529c" [[package]] name = "openssl" @@ -3137,7 +3408,7 @@ version = "0.10.70" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "61cfb4e166a8bb8c9b55c500bc2308550148ece889be90f609377e58140f42c6" dependencies = [ - "bitflags 2.6.0", + "bitflags 2.9.0", "cfg-if", "foreign-types", "libc", @@ -3369,7 +3640,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4c5cc86750666a3ed20bdaf5ca2a0344f9c67674cae0515bec2da16fbaa47db" dependencies = [ "fixedbitset", - "indexmap 2.7.0", + "indexmap 2.9.0", ] [[package]] @@ -3488,6 +3759,12 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "portable-atomic" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "350e9b48cbc6b0e028b0473b114454c6316e57336ee184ceab6e53f72c178b3e" + [[package]] name = "postgres" version = "0.19.9" @@ -3516,7 +3793,7 @@ dependencies = [ "md-5", "memchr", "rand 0.8.5", - "sha2", + "sha2 0.10.8", "stringprep", ] @@ -3597,6 +3874,12 @@ dependencies = [ "version_check", ] +[[package]] +name = "profiling" +version = "1.0.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afbdc74edc00b6f6a218ca6a5364d6226a259d4b8ea1af4a0ea063f27e179f4d" + [[package]] name = "prost" version = "0.13.4" @@ -3682,7 +3965,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "322330e133eab455718444b4e033ebfac7c6528972c784fcde28d2cc783c6257" dependencies = [ "anyhow", - "indexmap 2.7.0", + "indexmap 2.9.0", "log", "protobuf", "protobuf-support", @@ -3775,6 +4058,12 @@ dependencies = [ "getrandom 0.3.2", ] +[[package]] +name = "raw-window-handle" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" + [[package]] name = "rayon" version = "1.10.0" @@ -3829,7 +4118,7 @@ version = "0.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b6dfecf2c74bce2466cabf93f6664d6998a69eb21e39f4207930065b27b771f" dependencies = [ - "bitflags 2.6.0", + "bitflags 2.9.0", ] [[package]] @@ -3876,6 +4165,12 @@ version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" +[[package]] +name = "renderdoc-sys" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832" + [[package]] name = "reqwest" version = "0.12.9" @@ -3987,7 +4282,7 @@ version = "0.38.41" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d7f649912bc1495e167a6edee79151c84b1bad49748cb4f1f1167f459f6224f6" dependencies = [ - "bitflags 2.6.0", + "bitflags 2.9.0", "errno", "libc", "linux-raw-sys", @@ -4148,7 +4443,7 @@ version = "2.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" dependencies = [ - "bitflags 2.6.0", + "bitflags 2.9.0", "core-foundation 0.9.4", "core-foundation-sys", "libc", @@ -4161,7 +4456,7 @@ version = "3.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e1415a607e92bec364ea2cf9264646dcce0f91e6d65281bd6f2819cca3bf39c8" dependencies = [ - "bitflags 2.6.0", + "bitflags 2.9.0", "core-foundation 0.10.0", "core-foundation-sys", "libc", @@ -4320,7 +4615,7 @@ dependencies = [ "chrono", "hex", "indexmap 1.9.3", - "indexmap 2.7.0", + "indexmap 2.9.0", "serde", "serde_derive", "serde_json", @@ -4400,7 +4695,19 @@ checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba" dependencies = [ "cfg-if", "cpufeatures", - "digest", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a256f46ea78a0c0d9ff00077504903ac881a1dafdc20da66545699e7776b3e69" +dependencies = [ + "block-buffer 0.7.3", + "digest 0.8.1", + "fake-simd", + "opaque-debug", ] [[package]] @@ -4411,7 +4718,7 @@ checksum = "793db75ad2bcafc3ffa7c68b215fee268f537982cd901d132f89c6343f3a3dc8" dependencies = [ "cfg-if", "cpufeatures", - "digest", + "digest 0.10.7", ] [[package]] @@ -4456,7 +4763,7 @@ version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" dependencies = [ - "digest", + "digest 0.10.7", "rand_core 0.6.4", ] @@ -4564,6 +4871,12 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + [[package]] name = "stringprep" version = "0.1.5" @@ -4604,6 +4917,28 @@ dependencies = [ "syn", ] +[[package]] +name = "strum" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "rustversion", + "syn", +] + [[package]] name = "subtle" version = "2.6.1" @@ -4653,7 +4988,7 @@ version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c879d448e9d986b661742763247d3693ed13609438cf3d006f51f5368a5ba6b" dependencies = [ - "bitflags 2.6.0", + "bitflags 2.9.0", "core-foundation 0.9.4", "system-configuration-sys", ] @@ -4681,6 +5016,15 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + [[package]] name = "testcontainers" version = "0.23.1" @@ -5013,7 +5357,7 @@ version = "0.19.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" dependencies = [ - "indexmap 2.7.0", + "indexmap 2.9.0", "toml_datetime", "winnow", ] @@ -5090,7 +5434,7 @@ version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "403fa3b783d4b626a8ad51d766ab03cb6d2dbfc46b1c5d4448395e6628dc9697" dependencies = [ - "bitflags 2.6.0", + "bitflags 2.9.0", "bytes", "http 1.2.0", "http-body", @@ -5303,6 +5647,12 @@ version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493" +[[package]] +name = "unicode-width" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fc81956842c57dac11422a97c3b8195a1ff727f06e85c84ed2e8aa277c9a0fd" + [[package]] name = "unicode-xid" version = "0.2.6" @@ -5551,6 +5901,129 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "wgpu" +version = "25.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca6049eb2014a0e0d8689f9b787605dd71d5bbfdc74095ead499f3cff705c229" +dependencies = [ + "arrayvec", + "bitflags 2.9.0", + "cfg_aliases", + "document-features", + "hashbrown 0.15.2", + "js-sys", + "log", + "naga", + "parking_lot", + "portable-atomic", + "profiling", + "raw-window-handle", + "smallvec", + "static_assertions", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "wgpu-core", + "wgpu-hal", + "wgpu-types", +] + +[[package]] +name = "wgpu-core" +version = "25.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a19813e647da7aa3cdaa84f5846e2c64114970ea7c86b1e6aae8be08091f4bdc" +dependencies = [ + "arrayvec", + "bit-set", + "bit-vec", + "bitflags 2.9.0", + "cfg_aliases", + "document-features", + "hashbrown 0.15.2", + "indexmap 2.9.0", + "log", + "naga", + "once_cell", + "parking_lot", + "portable-atomic", + "profiling", + "raw-window-handle", + "rustc-hash", + "smallvec", + "thiserror 2.0.8", + "wgpu-core-deps-wasm", + "wgpu-core-deps-windows-linux-android", + "wgpu-hal", + "wgpu-types", +] + +[[package]] +name = "wgpu-core-deps-wasm" +version = "25.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eca8809ad123f6c7f2c5e01a2c7117c4fdfd02f70bd422ee2533f69dfa98756c" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-core-deps-windows-linux-android" +version = "25.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cba5fb5f7f9c98baa7c889d444f63ace25574833df56f5b817985f641af58e46" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-hal" +version = "25.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb7c4a1dc42ff14c23c9b11ebf1ee85cde661a9b1cf0392f79c1faca5bc559fb" +dependencies = [ + "arrayvec", + "bitflags 2.9.0", + "bytemuck", + "cfg-if", + "cfg_aliases", + "glow", + "glutin_wgl_sys", + "hashbrown 0.15.2", + "js-sys", + "khronos-egl", + "libloading", + "log", + "naga", + "ndk-sys", + "objc", + "parking_lot", + "portable-atomic", + "profiling", + "raw-window-handle", + "renderdoc-sys", + "thiserror 2.0.8", + "wasm-bindgen", + "web-sys", + "wgpu-types", + "windows", +] + +[[package]] +name = "wgpu-types" +version = "25.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2aa49460c2a8ee8edba3fca54325540d904dd85b2e086ada762767e17d06e8bc" +dependencies = [ + "bitflags 2.9.0", + "bytemuck", + "js-sys", + "log", + "thiserror 2.0.8", + "web-sys", +] + [[package]] name = "which" version = "4.4.2" @@ -5590,12 +6063,31 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +[[package]] +name = "winapi-util" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb" +dependencies = [ + "windows-sys 0.59.0", +] + [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" +[[package]] +name = "windows" +version = "0.58.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd04d41d93c4992d421894c18c8b43496aa748dd4c081bac0dc93eb0489272b6" +dependencies = [ + "windows-core 0.58.0", + "windows-targets 0.52.6", +] + [[package]] name = "windows-core" version = "0.52.0" @@ -5605,6 +6097,41 @@ dependencies = [ "windows-targets 0.52.6", ] +[[package]] +name = "windows-core" +version = "0.58.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ba6d44ec8c2591c134257ce647b7ea6b20335bf6379a27dac5f1641fcf59f99" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-result", + "windows-strings", + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-implement" +version = "0.58.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bbd5b46c938e506ecbce286b6628a02171d56153ba733b6c741fc627ec9579b" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-interface" +version = "0.58.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053c4c462dc91d3b1504c6fe5a726dd15e216ba718e84a0e46a88fbe5ded3515" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "windows-registry" version = "0.2.0" @@ -5798,7 +6325,7 @@ version = "0.39.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6f42320e61fe2cfd34354ecb597f86f413484a798ba44a8ca1165c58d42da6c1" dependencies = [ - "bitflags 2.6.0", + "bitflags 2.9.0", ] [[package]] @@ -5824,6 +6351,12 @@ dependencies = [ "rustix", ] +[[package]] +name = "xml-rs" +version = "0.8.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a62ce76d9b56901b19a74f19431b0d8b3bc7ca4ad685a746dfd78ca8f4fc6bda" + [[package]] name = "xxhash-rust" version = "0.8.13" @@ -5949,3 +6482,18 @@ dependencies = [ "quote", "syn", ] + +[[package]] +name = "zune-core" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f423a2c17029964870cfaabb1f13dfab7d092a62a29a89264f4d36990ca414a" + +[[package]] +name = "zune-jpeg" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99a5bab8d7dedf81405c4bb1f2b83ea057643d9cb28778cea9eecddeedd2e028" +dependencies = [ + "zune-core", +] diff --git a/clickplanet-client/Cargo.toml b/clickplanet-client/Cargo.toml index a4a104e..efe639f 100644 --- a/clickplanet-client/Cargo.toml +++ b/clickplanet-client/Cargo.toml @@ -27,5 +27,6 @@ serde_json.workspace = true tokio-retry.workspace = true futures-util = "0.3.31" rayon = "1.10.0" +imp = "0.1.0" # Additional dependencies specific to client diff --git a/clickplanet-osm/download-job/__pycache__/download.cpython-311.pyc b/clickplanet-osm/download-job/__pycache__/download.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5afe2abec02dea04a173a558fd66d84ae09cac56 GIT binary patch literal 6113 zcmb7IU2GFq7M`)k_V_2U6XzEK8DcizLSjOTfPn-;6MhN=O48jWw4{z_Y#jWzcg6%} z?NzkuLt62WT~#8xE!ymAm!_f*L4s9ZR-)auVx{eB9L)-Aq)14sKJey>tyHlud+r^3 z9EZSe?_8hzGk4B8_uT9AoqIp3t8-D1_&@(A_H8{y{R=lL$x^O7NkHWWB~SvLpvH}o z9;Zp$GHxNIb=*oyW}G3VZQKT>C1FoG#vMs^oJ~5%ok`cYE9oA0)0AL+hZ^??4A45k zA=uub$Lj?BoRrWL^zAYlzb(e5JV|-7Nw`eh%AL7 ziFo94CJ|1Fau3vDL`_#(N`@)|dZyBoW}`QAP2W(~Yoan@0*O*Oiz1?g>Oi&|eo{M- z8ES=by>m)!I9Oo%HKt#!WQ2!A%vnRj0Y74`-3+#t^SSoQQ6In}-n6c@n`{FPri<*M^AwiBMG+4ac80{a0YIG>$K&N5m%d$#hG;Hs4dyTvVda#YNkx61y?D2kdQe<0k> zS>?u6{n+dzt>61e-7T=(ZPR*rCdVvzD&MRwZ$aa>+3_Y=FmKD-bIg=!F`>R}*E>1e z!m62@A5pbD7QEFr)tca~o$(O$*1LH}&avRDj;YqxaBQf)sn!HvEl2cr%_=*dqep|# zSi6ga#_AqeSY_j?q*`rir9O9`_mPT5Ss9R<))=pvf*I@l)SyF z=~fC|$g|Jk(k$<&j?A&O+}7hS@2rkTKdRws?qoSs9W&KdslUi#G<6<)W1js5i#?=K zo2I9!tJd?>G#zXiQCg0PvK&vvxM(~fa#CCoiN{pDTvo!}Nc>q=lw|4gW{?-8b%z{J zis`KU_yM$)`d8B_8QfscDKQn3FDZ@Zz|G3QqQZ>lo?3f%M-?k~`iL@EJDR&Bh6NFE zsk96-vnc`mG{}=O>69ey2h>YmamyXwmJGEPyJc6cIw$ zCF!(F@kYv8C5Tr1Q<{H_-KNs9Ry{6?(n-RZ=ainKVNhGZvSOmltx=YY1aPdR z+J_N>5{A~=kLQBz2DUKqR5Y!#6%*eGGMP=qBVk$8T}YI(C`CBg1(B3CDU*oHx-F5O z2Do*BFeFRUaru&NlVlXn=r%A_8tKmAs}V6H$I~g@3NH}$?YdJ&;fRPWuDf88$*?>j zUX28ux)mEAW@0Rk&ftxrTO&z9ca+scO<4J6%!Pq<6LngY@Km@;Lf9wjO<*rTKDJFS&{4H}=wbpIw_I+CG{(_&^{QT_D zil_1VNwuwiaqM2#$3KCJnG2o)%`>2S28#aH*^}SExKnETTLsTW&2v%pTrB$A=l3iG z)W+`FS65m%t)+WGy2sx=^fmwYLu$)~LdylM<-+W-;-;++H|<*9w5zabx3+2byCbtl z=Z-$|wrJih3$HJGyH#&@v7_sEr+<6;H)lRP^RT0Dxub7sYoTMW*0HxlF%4S@nHws$ zZoHxVTKQG({oKRW-sRR_HFUVpI;gb{mMClU)|Jk#g;ze}|G+Osmih{TJz8MTQdkS@ zdl(p44h$3mhqb`rLg%2?IXKU(v~B*-t!^E?|H{{v&-Oya%!Rfwt!+$g8!L7O=H2)y zIe__hF3Rb>?opdxyFUs9a)CXmu_smbWYO!NmA_wcH-VbARRk{_e6atXf9dr*Eq7a> z3c0}Y8q2FJzvA|lDB9VFt$*rfyVl-QXb)-ap@L_Z=Gmosb`id_vhjQmspJIyP)gmf zMSeLraI}y5oE~b1;;Ys+O#58NTdZFl81x-)us&$8K_g;@D)0&3h9pd~0KGxwEIC>M zuoq|rUgVh?XKRL60*r#7$(pkO1xS}yaU_9=4FVDSO-HS3r$HFR!EE*0n@pU}+iGN( zp@QJd*#t)w64wO=tbI9E1FakdU%CYMC!SlN*KJd`Jro2K_9^U0ND}I<(5P3aU)_hL z2T&%ULO8Vs{?=NoMw6=j zeJ|p%?rJnV8x{(UIrc@`2dF+uVx}zyAY!;GZwmh$%sf;+3UOgB zaw(g-%n5M>r<}w!fMI~Z@_`8>2Vg8Gg|A>Rh8JOi?k?=s2^mB&i6=GO1vtTTZ=5@Y zM^;Wc1ZB+;1d%2tugN0Mjbe1-aGlGfr8q_-bDWqG%AZh?|abtfpHbSVJ%2ejGWIa0KC)81(=N zx==3^<#2{<3!SZO5WS(YsOC1%UBsS7aDfegaOkW%$x=)trI^m()j_X7uY}Kic|AW;%FE~V_l@ZMyS$8HEx)HtP$l1DhX2N-+E=QlnmROp zV0Nfvr+ixg*Xw$UzAdV6%bx-Z!taBB3>JJlHQ!Fvw-X0Z5Nw^h_wtf_XaC*(e>r#O zAT-Tf@QiAnQPndFA=iA<9ADa0D+vo;SA{hi;U`2Lf>*a|SlhokK%S z)MvYP3^}ZyZ}dR@^X-F;(D*Bl8(%n>A-CfTw-wjxXk{a#T;tdTJ47v{_c>_Hk}ITj zE?%B9ew|AfxT5nYp<{5g!uSvdr;ZN*sc_Oba)vo6BSzxUc!WDMdYTij;?`rU2hw8(QOQgEpl7b?@^x}MTq zO81XRUz$Ld#DxJ@x(t=OFo1L!EW1X^mzKnH;;a8Ept1+bo~pmV4ruIv$_|iVp4?mp>5-sMx1=SV!FLFTbMFML0Guvm z<#@ut2OF+R27chM7U8{YfC!FK$z3TqFA`5o=7+EcCo+f)p0Wp%X(5{s2hi*A0vkvA z6iCTR({zz?&XA`_xo5~zqdqIRhNUoJ5;JpkUYLhKzh Y9FRIV^vXw|$ zF|)cmC+i|gplL8oTCT)!J@8Z7BYEgc;V6Z^_EB;L5eo-_(ucgcxc8F2^!sL3t6kY9 z*V3`}o7wrd-^_f!-}jAw*W248LHgU%f3J`CNz&i(rJX`<;ovG19!a{S%SCBbWz*@+QA4wgtQbXcHzV+{eh@Y3o5bMuTq7~oOpMi)F&cx)9IDq&Smvwz zB@}|I46bb}Y=?Kfb+?COZcC4${)yMNrP#`D`{?`~C0p+5soEhLwL`X=^>nhswqmRK zFdUGq{Rk%QA&}FMN&SrTD zXIiV~ZW&g#td)#evJ8@#d17rCZUeE*_RN;)4H8oxF-SDvAaM%bh}=fCd@IWex8W;4 zsaT+)RwTTVU?o>qtbloAc;T91RcYC$@FikFN3Q0SIOFfTxTeiP{MX3 z>*;1kb`i~oQa8wC$&LV+LfXSNn67i~0JP)_U{_$f@0#X1l;(?ORVOQg3(2PiYlBp% zSuyAlsH;{gCjIY0hWHd_=UIKx%xT3es*jyl@D=?|aBJbPiZQ zLEY|O#4{+H7NEFV)@Mm7?u1O{D7Y6+#Q3bhEanVguVvF(#6FiPH7SQT^{^=*JM7{w zPt6kFQQU!4l%4=1aZYq?G(`u&$I$^Sd2=x|G2CBB0_cP7dGU}eGrOK+bQC&Gz{7qH z03PnE;suw*JGFe(L4G-GQoaC zQsd8**Y=dxcFcw{(^O{a%FOe`iP{q9g~gYrv`PisDYu2RnX|y9G7B6?Dd&f!M;S3e z86exq4(ak;>1pUOc(Es*C)-jjq!>4Kfj$Co^m?}YV15YnQ9HWpo2S#a8@O9B@Px6f zM{{=U7+O(-WzL=C($y;*9$b7!k9-7K1R(GC-g&@2I9TyD z-48J|W7Is0E|ATV_W)7o^YPVN4K*s@#UScx>y9Hh;N2-bkn2X#fM|=i&yo)|44^5B z%pe;0!UG$naTALM!66VDl!8gyPi)D#bd*gWFNS^W5?^_)2 zo%30@geVw-=iqS6XTQ>2>RmCM9y;xr@X-j+!$JGhmClG@3)r8!jMPW17pSl!&rk$a zD(r;8-W&z_%uyMj+e*nID8YV$re4M_6t&WtuFc(^a5q96)64}^z8? z^hfsfTYrA%FBkuG@vm<;GS`}!YxR})o0;p+G9T_`KCFL~ZDc-fW&i6L#)kK$kUG&ieHOe#e1eO6S6a!F&ywSN$?-<=Ofz|=&VSE+Hy1yDV;On$ zAPFWAyt(*!x)c5d882vgTPlWm5bT9P!hHlnK6NW%`Mwt%y>&c`ci)C$z}p^&gT7v} zBV9VgZ3Tin#g1pa?;gkAaA#8V@Kfb6?7$Pxn*j625kuNfVM{pfy--h3Ql99Vr4fy} zT%HF87xWJ1=f6Mj!T(R127+8Kd;-xXL_-~C!9RociE7P~A8%R)6DmUgu4s=NcDY(w zGbqN0ps#o#Q&k3$72f~Wjj}<(?Suc(h-HBLq8i)v*ZK8lCWqG_{=XY>9C&->VJ@dhimRs>8gugJbP67)Wa`zTF-MU_(G{`Z zg4hqsvfPs5HU8%-Bx?MxC6RjYx39?ZIIv(_#0F)uF9pT)sNBCV1;y+njtGiHc@jGw IBe?ee0asJQw*UYD literal 0 HcmV?d00001 diff --git a/clickplanet-osm/download-job/__pycache__/utils.cpython-311.pyc b/clickplanet-osm/download-job/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7293930ffd5090b658f9b661316abab93fcac951 GIT binary patch literal 5725 zcmbVPTWlN06`duAY5;Q3s)cr`&&s}2y6AK71Q1~N%0{j!WK+!u( zaYb4*s&+V>ot?RR=g!QzXYPFN^|}xw`49h^`Zv`6NnQ%cu~~UKXhG-(;!p%}6lY0L z5z2U4A{OImjaZE*j$q?yi`d|4P1uw6h@C-JUp`T;zH)1(HCep!hYqX(`o6p%-ej%SBEx zL)OSh&uioyC2|IF5y5S8bcvivE!*UrHyt~+(IxN6TSdwla|PBawpzDpr6Y0fy=K?{ zv@V_!d{{WIKyelSlLnuBz#JNt{}No%Kbn5Ep^=qh#4DO4=0Zbbg1^Ei1eUzM!!$G| z0n6+Zyre4|&L3$=9%#Z(4#x9@FHOW-6qWf<%tB0O;~rru+jXYxkz<$;oM~53NLnI z8hlNBl!5f@Y|Eqs?=1;-PUHpo3Y*|~sbx$|&A_armRKSly9{;-ynF=eAW_l;ThUV3 ziX*^?EreR7!0dwVm3Vn>HcEzr^%7r$@d#k0LqLsLwEprdiog9=j_ck}ymtrggtJ4r z%8u-txvGZj@DuFT@b1<4J=cR_1&^tCOv7VPdE%|nya$wnEvomZ<~^G2e~eu}AO3Jy z@ehC7e!ugZuKQh3g{7dbO6`e8YEd zYoSRsbWRJM%Qrx&;tLwSpx_Ipp5r%Kid!|@ zs^C^ry65#qAnyS8)4dcV%|uDJ&I= znWr4QkPRbHd76OY29k^VX3Tm9==+YP^o#{^HVGM_HIuYKjhQ%WrmQ1#2pk!YPLKnR zzZ#e1XzFtMrH~*2R=6$XGe(~T4uEw_O48{h3*HwOC9x5P&}|&?DbP`2`bu<`m8T_Q zHzPI?nccjhG`b~`*C`%@-e&kq?N9)4u>GUqPbzNLC^(?vfQAE5S%-ZNe;8IOyKW0m zKvr?LhP#zQ7JmdE$KY=!8fwOJR)7((oMs2`u(_OT=DAqZjb!`Q8%N3J$pQhdc`ASw zQ>v7=*UYnROUv`8P3iezFf3TI6{aqt;u zxstQS)*1*A_dyTA7*R?fP>hV)m@#&=(3dA$u>(Fi3V&%D3c!W0a(R9wvy{0xpfsHQ zYW&+h_xF8s;QoO}C*OK_@-6k`xOQ?}ePcpBlsQ9e?89&O_B9gK*}qpf_*2P9^@W8X$%MSe3wyw^y@ zNH3jL5WVy9B310GMKdew6UDkRRO$GOmJGF4$a;v$#vV&c7md*^WT7a;_NPcN+_Vq|?T(p+xDjU0Uu8g&u&F4Yq zqV;_%(VVZ%Q}gJm^*oxVn%tx56UCP#CN432J|JsmF7y0s`9KVAfawDh+v791+yQk# z*wn$KyZYk-n_yxPT?uou%n{HFXByGRCK6?WJ94Xpt0N=w$4!z40j_CGt^T6jN{*w!*rlUn%~Q67PJk=W9~^rhw!93!M;=F(guv5=Q4Zz9YHNZTh8SJ)z9gTuu)piQ^u z4`7Hzr%6z!+r^|T@(_w9APxYIHrQP}K}21^=b|jl$AS56aS1wgXXt8-pCxnCZN~JQ zuy~Tl;y5fBN{!T&?9COq4b(=$SU2V(LD;?lcOuH**CDyc9AlrCRBP-qbC)5@`>BK z+_uuS)V12Ex({pa!yCxrY+v_Otqd;>D|`CC9)tq2>KV{H1Bzz=x|T;)8}HRCo;KCf zrg_?+@}y?h^*3+Mt2M7`HLq?U>})rRYr*yE+UspMIzR3Fo#S?mS{=};1J{B%U-ild zOCPL$p!!-gUki-rZU5@jmjizu`P0aQdbM>xYaK8e*ZsS0xIc9(`-UG(Kml3xhc$m# z@rR-7x_6ZWGa#t+w`oRn`NNaK%4|&^Rsix3>+YHjM8O&qmt;LWOCF{6J>{);Nm=`z zO0ycxD&_JIkT$GD2UH{y=KswS41|uM?~b|p>#g5)?(aWn{rf>1)SF(?9Z|Tw#iG$X z)((NRNN&L*xm1c>q#y^XZW%tMTSnkNa7wQVhWdLa!xPcI!O79#==e}1q&s-wN?Zhd zS>Z+nm&MdP;EWu{c}Nos=h110{@6U1$1AyG8<&wh=1FvEgc1g#evga;-T>e;x)Uye za|ymnJOe`H%$I%&CCrneHZZ0zY$OyOM7gp~^2;Gt*7)U6Mb`M`kS}Zea>$!CemS&X zDb0^<&a5S8b6l(c+4-W% + ClickPlanet @@ -8,19 +9,6 @@ - - - - - - - - - - - - -
diff --git a/clickplanet-webapp/rust-toolchain.toml b/clickplanet-webapp/rust-toolchain.toml new file mode 100644 index 0000000..73cb934 --- /dev/null +++ b/clickplanet-webapp/rust-toolchain.toml @@ -0,0 +1,3 @@ +[toolchain] +channel = "stable" +components = ["rustfmt", "clippy"] diff --git a/clickplanet-webapp/src/app/components/about.rs b/clickplanet-webapp/src/app/components/about.rs index f333dd3..01297f8 100644 --- a/clickplanet-webapp/src/app/components/about.rs +++ b/clickplanet-webapp/src/app/components/about.rs @@ -12,7 +12,7 @@ pub fn About() -> Element { button_props: BlockButtonProps { on_click: Callback::new(|_| {}), text: "About".to_string(), - image_url: "/static/favicon.png".to_string(), + image_url: asset!("public/static/favicon.png").to_string(), class_name: Some("button-about".to_string()), }, close_button_text: Some("Back".to_string()), diff --git a/clickplanet-webapp/src/app/components/block_button.rs b/clickplanet-webapp/src/app/components/block_button.rs index 5c41b47..cdfc8bd 100644 --- a/clickplanet-webapp/src/app/components/block_button.rs +++ b/clickplanet-webapp/src/app/components/block_button.rs @@ -21,7 +21,7 @@ pub fn BlockButton(props: BlockButtonProps) -> Element { onclick: move |evt| props.on_click.call(evt), // Call the callback if !props.image_url.is_empty() { img { - src: format!("/public{}", props.image_url), + src: props.image_url, alt: props.text.clone(), class: "button-icon", style: "margin-right: 8px; width: 20px; height: 20px;" diff --git a/clickplanet-webapp/src/app/components/earth/animation_loop.rs b/clickplanet-webapp/src/app/components/earth/animation_loop.rs new file mode 100644 index 0000000..7d1d3e1 --- /dev/null +++ b/clickplanet-webapp/src/app/components/earth/animation_loop.rs @@ -0,0 +1,121 @@ +use dioxus::prelude::*; +use gloo_timers::future::TimeoutFuture; +use log::{debug, info}; +use wasm_bindgen_futures::spawn_local; +use glam::{Mat4, Vec3}; + +use crate::app::components::earth::setup_webgpu::{Uniforms, WebGpuContext}; + +pub struct RenderLoopContext { + pub webgpu_context: WebGpuContext, + pub rotation: Signal, +} + +pub fn start_animation(context: RenderLoopContext) { + info!("Starting WebGPU animation loop"); + let WebGpuContext { + device, + queue, + surface, + render_pipeline, + bind_group, + vertex_buffer, + index_buffer, + uniform_buffer, + depth_texture, + num_indices, + config, + } = context.webgpu_context; + let rotation = context.rotation; + let depth_view = depth_texture.create_view(&wgpu::TextureViewDescriptor::default()); + + // Extract dimensions + let width = config.width; + let height = config.height; + + spawn_local(async move { + loop { + let output = match surface.get_current_texture() { + Ok(texture) => texture, + Err(err) => { + debug!("Failed to get current texture: {:?}", err); + continue; + } + }; + + let texture_view = output.texture.create_view(&wgpu::TextureViewDescriptor::default()); + + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("Render Encoder"), + }); + + let rotation_angle = rotation(); + + let model = Mat4::from_rotation_y(rotation_angle); + let view_matrix = Mat4::look_at_rh( + Vec3::new(0.0, 0.0, 2.5), // camera position + Vec3::new(0.0, 0.0, 0.0), // target + Vec3::new(0.0, 1.0, 0.0), // up + ); + let aspect = width as f32 / height as f32; + let projection = Mat4::perspective_rh( + 45.0f32.to_radians(), + aspect, + 0.1, + 100.0, + ); + + let mvp = projection * view_matrix * model; + + // Update uniform buffer + queue.write_buffer( + &uniform_buffer, + 0, + bytemuck::cast_slice(&[Uniforms { mvp: mvp.to_cols_array_2d() }]), + ); + + // Begin render pass + { + let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("Render Pass"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &texture_view, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color { + r: 0.0, + g: 0.0, + b: 0.0, + a: 1.0, + }), + store: wgpu::StoreOp::Store, + }, + })], + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + view: &depth_view, + depth_ops: Some(wgpu::Operations { + load: wgpu::LoadOp::Clear(1.0), + store: wgpu::StoreOp::Store, + }), + stencil_ops: None, + }), + timestamp_writes: None, + occlusion_query_set: None, + }); + + render_pass.set_pipeline(&render_pipeline); + render_pass.set_bind_group(0, &bind_group, &[]); + render_pass.set_vertex_buffer(0, vertex_buffer.slice(..)); + render_pass.set_index_buffer(index_buffer.slice(..), wgpu::IndexFormat::Uint16); + render_pass.draw_indexed(0..num_indices, 0, 0..1); + } + + queue.submit(std::iter::once(encoder.finish())); + output.present(); + + TimeoutFuture::new(16).await; + } + }); + + info!("Started animation loop"); +} diff --git a/clickplanet-webapp/src/app/components/create_sphere.rs b/clickplanet-webapp/src/app/components/earth/create_sphere.rs similarity index 100% rename from clickplanet-webapp/src/app/components/create_sphere.rs rename to clickplanet-webapp/src/app/components/earth/create_sphere.rs diff --git a/clickplanet-webapp/src/app/components/earth/earth_textured.wgsl b/clickplanet-webapp/src/app/components/earth/earth_textured.wgsl new file mode 100644 index 0000000..3de7427 --- /dev/null +++ b/clickplanet-webapp/src/app/components/earth/earth_textured.wgsl @@ -0,0 +1,48 @@ +// Textured Earth Shader (WGSL) +const PI: f32 = 3.141592653589793; + +struct Uniforms { + mvp: mat4x4, +}; + +@group(0) @binding(0) +var uniforms: Uniforms; + +@group(0) @binding(1) +var earth_texture: texture_2d; + +@group(0) @binding(2) +var earth_sampler: sampler; + +struct VertexInput { + @location(0) position: vec3, + @location(1) normal: vec3, +}; + +struct VertexOutput { + @builtin(position) Position: vec4, + @location(0) v_uv: vec2, + @location(1) v_normal: vec3, +}; + +@vertex +fn vs_main(input: VertexInput) -> VertexOutput { + var out: VertexOutput; + out.Position = uniforms.mvp * vec4(input.position, 1.0); + // spherical UV calculation + let theta = acos(input.position.y); + let phi = atan2(input.position.z, input.position.x); + let u = phi / (2.0 * PI) + 0.5; + let v = theta / PI; + out.v_uv = vec2(u, v); + out.v_normal = input.normal; + return out; +} + +@fragment +fn fs_main(in: VertexOutput) -> @location(0) vec4 { + let color = textureSample(earth_texture, earth_sampler, in.v_uv); + let light_dir = normalize(vec3(1.0, 1.0, 1.0)); + let brightness = max(dot(in.v_normal, light_dir), 0.0); + return color * vec4(brightness, brightness, brightness, 1.0); +} diff --git a/clickplanet-webapp/src/app/components/globe.rs b/clickplanet-webapp/src/app/components/earth/globe.rs similarity index 93% rename from clickplanet-webapp/src/app/components/globe.rs rename to clickplanet-webapp/src/app/components/earth/globe.rs index c9b077d..15e53d8 100644 --- a/clickplanet-webapp/src/app/components/globe.rs +++ b/clickplanet-webapp/src/app/components/earth/globe.rs @@ -3,7 +3,7 @@ use log::{debug, error, info}; use web_sys::HtmlCanvasElement; use wasm_bindgen::JsCast; use wasm_bindgen_futures; -use crate::app::components::setup_webgpu::{setup_webgpu, use_animation_state}; +use crate::app::components::earth::setup_webgpu::{setup_scene, use_animation_state}; #[component] pub fn globe() -> Element { @@ -18,7 +18,7 @@ pub fn globe() -> Element { if let Some(canvas) = canvas_ref.read().clone() { info!("Canvas found - initializing WebGPU Earth rendering"); // Hand off to setup_webgpu for real initialization with animation signal - setup_webgpu(canvas, rotation).await; + setup_scene(canvas, rotation).await; } else { error!("No canvas found for globe rendering"); } diff --git a/clickplanet-webapp/src/app/components/earth/mod.rs b/clickplanet-webapp/src/app/components/earth/mod.rs new file mode 100644 index 0000000..2a16719 --- /dev/null +++ b/clickplanet-webapp/src/app/components/earth/mod.rs @@ -0,0 +1,5 @@ +pub mod globe; +mod create_sphere; +mod setup_webgpu; +mod animation_loop; +mod shader_validation; diff --git a/clickplanet-webapp/src/app/components/earth/setup_webgpu.rs b/clickplanet-webapp/src/app/components/earth/setup_webgpu.rs new file mode 100644 index 0000000..13bf70a --- /dev/null +++ b/clickplanet-webapp/src/app/components/earth/setup_webgpu.rs @@ -0,0 +1,271 @@ +use web_sys::HtmlCanvasElement; +use wgpu::util::DeviceExt; +use wgpu::SurfaceTarget; +use glam::Mat4; +use log::{debug, info}; +use dioxus::prelude::*; +use bytemuck::{Pod, Zeroable, cast_slice}; +use wasm_bindgen_futures::spawn_local; +use gloo_timers::future::TimeoutFuture; +use image::{GenericImageView, imageops::FilterType}; + +use crate::app::components::earth::create_sphere::{Vertex, create_sphere}; +use crate::app::components::earth::animation_loop::{start_animation, RenderLoopContext}; + +#[cfg(test)] +use crate::app::components::earth::shader_validation::validate_shader_code; + +#[repr(C)] +#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)] +pub struct Uniforms { + pub mvp: [[f32; 4]; 4], +} + +/// WebGPU rendering context containing all necessary components +pub struct WebGpuContext { + pub device: wgpu::Device, + pub queue: wgpu::Queue, + pub surface: wgpu::Surface<'static>, + pub vertex_buffer: wgpu::Buffer, + pub index_buffer: wgpu::Buffer, + pub uniform_buffer: wgpu::Buffer, + pub bind_group: wgpu::BindGroup, + pub render_pipeline: wgpu::RenderPipeline, + pub depth_texture: wgpu::Texture, + pub num_indices: u32, + pub config: wgpu::SurfaceConfiguration, +} + +/// Create a signal-based animation state for the globe +pub fn use_animation_state() -> Signal { + let rotation = use_signal(|| 0.0f32); + + use_effect(move || { + let mut rotation_state = rotation.clone(); + spawn_local(async move { + loop { + // Update rotation (in radians) + rotation_state.set(rotation_state() + 0.005); + // Yield to browser to avoid blocking the main thread + gloo_timers::future::TimeoutFuture::new(16).await; // ~60fps + } + }); + }); + + rotation +} + +/// Set up WebGPU and start the rendering loop +pub async fn setup_scene(canvas: HtmlCanvasElement, rotation: Signal) { + info!("Setting up WebGPU for globe rendering"); + let width = canvas.client_width() as u32; + let height = canvas.client_height() as u32; + + // Create WGPU instance first + let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor { + backends: wgpu::Backends::all(), + flags: wgpu::InstanceFlags::default(), + backend_options: Default::default(), + }); + + debug!("Created WebGPU instance"); + + // Create surface from canvas for WebGPU + let surface = instance + .create_surface(SurfaceTarget::Canvas(canvas.clone())) + .expect("Failed to create surface from canvas"); + + // Initialize full WebGPU context (adapter, device, surface config, pipeline, resources) + let context = create_render_pipeline(&instance, surface, width, height).await; + + // Start animation using TS-like startAnimation + start_animation(RenderLoopContext { webgpu_context: context, rotation }); + info!("Started animation loop"); +} + +/// Create WebGPU context: adapter, device, surface config, pipeline and resources +async fn create_render_pipeline( + instance: &wgpu::Instance, + surface: wgpu::Surface<'static>, + width: u32, + height: u32, +) -> WebGpuContext { + // Request adapter and create device/queue + let adapter = instance + .request_adapter(&wgpu::RequestAdapterOptions { + power_preference: wgpu::PowerPreference::default(), + compatible_surface: Some(&surface), + force_fallback_adapter: false, + }) + .await + .expect("Failed to find appropriate adapter"); + // Request device and queue + let (device, queue) = adapter.request_device( + &wgpu::DeviceDescriptor { + label: Some("Globe Device"), + required_features: wgpu::Features::empty(), + required_limits: wgpu::Limits::downlevel_webgl2_defaults(), + memory_hints: wgpu::MemoryHints::default(), + trace: wgpu::Trace::default(), + }, + ) + .await + .expect("Failed to create device"); + info!("Created adapter, device and queue"); + + // Configure the surface + let capabilities = surface.get_capabilities(&adapter); + let surface_format = capabilities.formats[0]; + let config = wgpu::SurfaceConfiguration { + usage: wgpu::TextureUsages::RENDER_ATTACHMENT, + format: surface_format, + width, + height, + present_mode: wgpu::PresentMode::Fifo, + alpha_mode: wgpu::CompositeAlphaMode::Auto, + view_formats: vec![], + desired_maximum_frame_latency: 2, + }; + surface.configure(&device, &config); + + // Create render pipeline and resources + // Mesh generation + let (vertices, indices) = create_sphere(1.0, 64, 128); + let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("Vertex Buffer"), + contents: bytemuck::cast_slice(&vertices), + usage: wgpu::BufferUsages::VERTEX, + }); + let index_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("Index Buffer"), + contents: bytemuck::cast_slice(&indices), + usage: wgpu::BufferUsages::INDEX, + }); + let num_indices = indices.len() as u32; + let uniform_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("Uniform Buffer"), + contents: bytemuck::cast_slice(&[Uniforms { mvp: Mat4::IDENTITY.to_cols_array_2d() }]), + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + }); + let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Bind Group Layout"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::VERTEX, + ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None }, + count: None, + }, + // earth texture binding + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { multisampled: false, view_dimension: wgpu::TextureViewDimension::D2, sample_type: wgpu::TextureSampleType::Float { filterable: true } }, + count: None, + }, + // sampler binding + wgpu::BindGroupLayoutEntry { + binding: 2, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }, + ], + }); + // Load and downscale earth image to fit device limits + let mut img = image::load_from_memory(include_bytes!("../../../../public/static/earth/3_no_ice_clouds_16k.jpg")).expect("Failed to load earth image"); + let max_dim = device.limits().max_texture_dimension_2d; + let (w, h) = img.dimensions(); + if w > max_dim || h > max_dim { + let aspect = w as f32 / h as f32; + let (new_w, new_h) = if w > h { + (max_dim, (max_dim as f32 / aspect) as u32) + } else { + ((max_dim as f32 * aspect) as u32, max_dim) + }; + img = img.resize(new_w, new_h, FilterType::Triangle); + } + let rgba = img.to_rgba8(); + let (tex_w, tex_h) = img.dimensions(); + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("Earth Texture"), + size: wgpu::Extent3d { width: tex_w, height: tex_h, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8UnormSrgb, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + queue.write_texture( + wgpu::ImageCopyTexture { texture: &texture, mip_level: 0, origin: Default::default(), aspect: wgpu::TextureAspect::All }, + &rgba, + wgpu::ImageDataLayout { offset: 0, bytes_per_row: Some(4 * tex_w), rows_per_image: Some(tex_h) }, + wgpu::Extent3d { width: tex_w, height: tex_h, depth_or_array_layers: 1 }, + ); + let texture_view = texture.create_view(&wgpu::TextureViewDescriptor::default()); + let sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("Earth Sampler"), + address_mode_u: wgpu::AddressMode::ClampToEdge, + address_mode_v: wgpu::AddressMode::ClampToEdge, + address_mode_w: wgpu::AddressMode::ClampToEdge, + mag_filter: wgpu::FilterMode::Linear, + min_filter: wgpu::FilterMode::Linear, + mipmap_filter: wgpu::FilterMode::Nearest, + ..Default::default() + }); + let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Bind Group"), + layout: &bind_group_layout, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: uniform_buffer.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(&texture_view) }, + wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::Sampler(&sampler) }, + ], + }); + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("Textured Earth Shader"), + source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(include_str!("earth_textured.wgsl"))), + }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("Render Pipeline Layout"), + bind_group_layouts: &[&bind_group_layout], + push_constant_ranges: &[], + }); + let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("Render Pipeline"), + layout: Some(&pipeline_layout), + cache: None, + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("vs_main"), + compilation_options: wgpu::PipelineCompilationOptions::default(), + buffers: &[wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::() as wgpu::BufferAddress, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3], + }], + }, + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some("fs_main"), + compilation_options: wgpu::PipelineCompilationOptions::default(), + targets: &[Some(wgpu::ColorTargetState { format: surface_format, blend: Some(wgpu::BlendState::REPLACE), write_mask: wgpu::ColorWrites::ALL })], + }), + primitive: wgpu::PrimitiveState::default(), + depth_stencil: Some(wgpu::DepthStencilState { format: wgpu::TextureFormat::Depth24Plus, depth_write_enabled: true, depth_compare: wgpu::CompareFunction::LessEqual, stencil: wgpu::StencilState::default(), bias: wgpu::DepthBiasState::default() }), + multisample: wgpu::MultisampleState::default(), + multiview: None, + }); + let depth_texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("Depth Texture"), + size: wgpu::Extent3d { width, height, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Depth24Plus, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT, + view_formats: &[], + }); + WebGpuContext { device, queue, surface, vertex_buffer, index_buffer, uniform_buffer, bind_group, render_pipeline, depth_texture, num_indices, config } +} diff --git a/clickplanet-webapp/src/app/components/earth/shader_validation.rs b/clickplanet-webapp/src/app/components/earth/shader_validation.rs new file mode 100644 index 0000000..542bf39 --- /dev/null +++ b/clickplanet-webapp/src/app/components/earth/shader_validation.rs @@ -0,0 +1,57 @@ +use log::info; + +/// Validates WGSL shader code by attempting to compile it +#[cfg(test)] +pub fn validate_shader_code(shader_source: &str) { + use wgpu::ShaderSource; + + // This function ensures the shader code is syntactically valid + // by attempting to create a shader module with it. + // It will panic if the shader has syntax errors. + + // Create a headless device for testing + pollster::block_on(async { + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::default()); + let adapter = instance + .request_adapter(&wgpu::RequestAdapterOptions { + power_preference: wgpu::PowerPreference::default(), + compatible_surface: None, + force_fallback_adapter: false, + }) + .await + .expect("Failed to find an appropriate adapter for shader testing"); + + let (device, _) = adapter + .request_device( + &wgpu::DeviceDescriptor { + label: Some("Test Device"), + features: wgpu::Features::empty(), + limits: wgpu::Limits::default(), + memory_hints: wgpu::MemoryHints::default(), + trace: wgpu::Trace::default(), + }, + ) + .await + .expect("Failed to create device for shader testing"); + + // Create shader module - this will validate the syntax + let _shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("Test Shader"), + source: ShaderSource::Wgsl(std::borrow::Cow::Borrowed(shader_source)), + }); + + // If we reach here without panicking, the shader is valid + println!("WGSL shader validation successful"); + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_globe_shader_validation() { + // This test validates that the globe.wgsl shader has valid syntax + validate_shader_code(include_str!("globe.wgsl")); + } +} diff --git a/clickplanet-webapp/src/app/components/globe.wgsl b/clickplanet-webapp/src/app/components/globe.wgsl deleted file mode 100644 index 8746af7..0000000 --- a/clickplanet-webapp/src/app/components/globe.wgsl +++ /dev/null @@ -1,32 +0,0 @@ -struct Uniforms { - mvp: mat4x4; -}; - -@group(0) @binding(0) -var uniforms: Uniforms; - -struct VertexInput { - @location(0) position: vec3; - @location(1) normal: vec3; -}; - -struct VertexOutput { - @builtin(position) Position: vec4; - @location(0) v_normal: vec3; -}; - -@vertex -fn vs_main(input: VertexInput) -> VertexOutput { - var out: VertexOutput; - out.Position = uniforms.mvp * vec4(input.position, 1.0); - out.v_normal = input.normal; - return out; -} - -@fragment -fn fs_main(in: VertexOutput) -> @location(0) vec4 { - let light = normalize(vec3(1.0, 1.0, 1.0)); - let brightness = max(dot(in.v_normal, light), 0.0); - let color = vec3(0.2, 0.5, 1.0) * brightness + vec3(0.1); - return vec4(color, 1.0); -} diff --git a/clickplanet-webapp/src/app/components/leaderboard.rs b/clickplanet-webapp/src/app/components/leaderboard.rs index 576089f..4947a51 100644 --- a/clickplanet-webapp/src/app/components/leaderboard.rs +++ b/clickplanet-webapp/src/app/components/leaderboard.rs @@ -1,4 +1,5 @@ use dioxus::prelude::*; + use crate::app::countries::Country; // Structure to store leaderboard entry data matching the TypeScript implementation @@ -19,11 +20,11 @@ pub struct LeaderboardProps { // Component for displaying the leaderboard #[component] -pub fn Leaderboard() -> Element { +pub fn Leaderboard(props: LeaderboardProps) -> Element { let mut is_open = use_signal(|| true); // Total number of tiles in the globe - matches the default in the TypeScript implementation - let total_tiles = 120000; // This would come from props.tiles_count in a real implementation + let total_tiles = props.tiles_count; // This would come from props.tiles_count in a real implementation // In a full implementation, this would be fetched from an API let entries = use_signal(|| { @@ -78,13 +79,15 @@ pub fn Leaderboard() -> Element { let toggle_leaderboard = move |_| { is_open.set(!is_open()); }; + + let folder = asset!("public/static"); rsx! { div { class: "leaderboard", div { class: "leaderboard-header", img { alt: "ClickPlanet logo", - src: "/public/static/favicon.png", + src: format!("{folder}/favicon.png"), width: "56px", height: "56px" } @@ -129,8 +132,8 @@ pub fn Leaderboard() -> Element { td { colspan: "3", img { class: "country-flag", - src: "/public/static/countries/svg/{entry.country.code.to_lowercase()}.svg", - alt: "{entry.country.name} flag", + src: format!("{folder}/countries/svg/{}.svg", entry.country.code.to_lowercase()), + alt: entry.country.name.as_str(), width: "20px", height: "auto", style: "margin-right: 8px;" diff --git a/clickplanet-webapp/src/app/components/mod.rs b/clickplanet-webapp/src/app/components/mod.rs new file mode 100644 index 0000000..df2c651 --- /dev/null +++ b/clickplanet-webapp/src/app/components/mod.rs @@ -0,0 +1,12 @@ +pub mod buy_me_a_coffee; +pub mod block_button; +pub mod close_button; +pub mod discord_button; +pub mod modal; +pub mod modal_manager; +pub mod on_load_modal; +pub mod select_with_search; +pub mod settings; +pub mod leaderboard; +pub mod about; +pub mod earth; diff --git a/clickplanet-webapp/src/app/components/select_with_search.rs b/clickplanet-webapp/src/app/components/select_with_search.rs index 88e880e..429e691 100644 --- a/clickplanet-webapp/src/app/components/select_with_search.rs +++ b/clickplanet-webapp/src/app/components/select_with_search.rs @@ -1,6 +1,4 @@ use dioxus::prelude::*; -use std::rc::Rc; -use dioxus::logger::tracing::event; /// Convert a country code (e.g., "us") to a flag emoji (e.g., "🇺🇸") fn get_flag_emoji(country_code: &str) -> String { diff --git a/clickplanet-webapp/src/app/components/settings.rs b/clickplanet-webapp/src/app/components/settings.rs index c97903b..995f16d 100644 --- a/clickplanet-webapp/src/app/components/settings.rs +++ b/clickplanet-webapp/src/app/components/settings.rs @@ -40,6 +40,8 @@ pub fn Settings(props: SettingsProps) -> Element { CountryValue { code: "gb".to_string(), name: "United Kingdom".to_string() }, ]; + let folder = asset!("public/static"); + rsx! { ModalManager { open_by_default: false, @@ -47,7 +49,7 @@ pub fn Settings(props: SettingsProps) -> Element { button_props: BlockButtonProps { on_click: Callback::new(|_| {}), text: country.name.clone(), - image_url: format!("/static/countries/svg/{}.svg", country.code.to_lowercase()), + image_url: format!("{}/countries/svg/{}.svg", folder, country.code.to_lowercase()), class_name: Some("button-settings".to_string()), }, close_button_text: None, diff --git a/clickplanet-webapp/src/app/components/setup_webgpu.rs b/clickplanet-webapp/src/app/components/setup_webgpu.rs deleted file mode 100644 index cb8aaf8..0000000 --- a/clickplanet-webapp/src/app/components/setup_webgpu.rs +++ /dev/null @@ -1,350 +0,0 @@ -use wasm_bindgen::prelude::*; -use web_sys::HtmlCanvasElement; -use wgpu::SurfaceTarget; -use wgpu::util::DeviceExt; -use glam::{Mat4, Vec3, Quat}; -use std::cell::RefCell; -use std::rc::Rc; -use std::f32::consts::PI; -use log::{info, debug, error}; -use dioxus::prelude::*; -use wasm_bindgen_futures::spawn_local; - -use crate::app::components::create_sphere::{Vertex, create_sphere}; - -/// Uniform buffer data for transformations -#[repr(C)] -#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)] -pub struct Uniforms { - pub mvp: [[f32; 4]; 4], -} - -/// Create a signal-based animation state for the globe -pub fn use_animation_state() -> Signal { - let rotation = use_signal(|| 0.0f32); - - use_effect(move || { - let mut rotation_state = rotation.clone(); - spawn_local(async move { - loop { - // Update rotation (in radians) - rotation_state.set(rotation_state() + 0.005); - // Yield to browser to avoid blocking the main thread - gloo_timers::future::TimeoutFuture::new(16).await; // ~60fps - } - }); - }); - - rotation -} - -/// Set up WebGPU and start the rendering loop -pub async fn setup_webgpu(canvas: HtmlCanvasElement, rotation: Signal) { - info!("Setting up WebGPU for globe rendering"); - let width = canvas.client_width() as u32; - let height = canvas.client_height() as u32; - - // Create WGPU instance - let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor { - backends: wgpu::Backends::all(), - flags: wgpu::InstanceFlags::default(), - backend_options: Default::default(), - }); - - debug!("Created WebGPU instance"); - - // For WebGPU in the browser, we need to create a surface from the canvas - // In wgpu 25.0, we use SurfaceTarget::Canvas - let surface_target = SurfaceTarget::Canvas(canvas.clone()); - let surface = instance - .create_surface(surface_target) - .expect("Failed to create surface from canvas"); - - // Request adapter - let adapter = instance.request_adapter(&wgpu::RequestAdapterOptions { - power_preference: wgpu::PowerPreference::default(), - compatible_surface: Some(&surface), - force_fallback_adapter: false, - }).await.expect("Failed to find appropriate adapter"); - - // Create device and queue - let (device, queue) = adapter.request_device( - &wgpu::DeviceDescriptor { - label: Some("Globe Device"), - required_features: wgpu::Features::empty(), - required_limits: wgpu::Limits::downlevel_webgl2_defaults(), - memory_hints: wgpu::MemoryHints::default(), - trace: wgpu::Trace::default(), - } - ).await.expect("Failed to create device"); - - info!("Created device and queue"); - - // Get preferred format - let capabilities = surface.get_capabilities(&adapter); - let surface_format = capabilities.formats[0]; - - // Configure the surface - let config = wgpu::SurfaceConfiguration { - usage: wgpu::TextureUsages::RENDER_ATTACHMENT, - format: surface_format, - width, - height, - present_mode: wgpu::PresentMode::Fifo, - alpha_mode: wgpu::CompositeAlphaMode::Auto, - view_formats: vec![], - desired_maximum_frame_latency: 2, - }; - surface.configure(&device, &config); - - // Create Earth sphere mesh with proper dimensions - let (vertices, indices) = create_sphere(1.0, 64, 128); - - // Create vertex buffer - let vertex_buffer = device.create_buffer_init( - &wgpu::util::BufferInitDescriptor { - label: Some("Vertex Buffer"), - contents: bytemuck::cast_slice(&vertices), - usage: wgpu::BufferUsages::VERTEX, - } - ); - - // Create index buffer - let index_buffer = device.create_buffer_init( - &wgpu::util::BufferInitDescriptor { - label: Some("Index Buffer"), - contents: bytemuck::cast_slice(&indices), - usage: wgpu::BufferUsages::INDEX, - } - ); - - let num_indices = indices.len() as u32; - - info!("Created mesh with {} vertices and {} indices", vertices.len(), indices.len()); - - // Create uniform buffer - let uniform_buffer = device.create_buffer_init( - &wgpu::util::BufferInitDescriptor { - label: Some("Uniform Buffer"), - contents: bytemuck::cast_slice(&[Uniforms { - mvp: Mat4::IDENTITY.to_cols_array_2d(), - }]), - usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, - } - ); - - info!("Created uniform buffer"); - - // Create bind group layout - let bind_group_layout = device.create_bind_group_layout( - &wgpu::BindGroupLayoutDescriptor { - label: Some("Bind Group Layout"), - entries: &[ - wgpu::BindGroupLayoutEntry { - binding: 0, - visibility: wgpu::ShaderStages::VERTEX, - ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Uniform, - has_dynamic_offset: false, - min_binding_size: None, - }, - count: None, - }, - ], - } - ); - - // Create bind group - let bind_group = device.create_bind_group( - &wgpu::BindGroupDescriptor { - label: Some("Bind Group"), - layout: &bind_group_layout, - entries: &[ - wgpu::BindGroupEntry { - binding: 0, - resource: uniform_buffer.as_entire_binding(), - }, - ], - } - ); - - // Create shader module - let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { - label: Some("Globe Shader"), - source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(include_str!("globe.wgsl"))), - }); - - // Create render pipeline layout - let pipeline_layout = device.create_pipeline_layout( - &wgpu::PipelineLayoutDescriptor { - label: Some("Render Pipeline Layout"), - bind_group_layouts: &[&bind_group_layout], - push_constant_ranges: &[], - } - ); - - // Create render pipeline - let render_pipeline = device.create_render_pipeline( - &wgpu::RenderPipelineDescriptor { - cache: None, - label: Some("Render Pipeline"), - layout: Some(&pipeline_layout), - vertex: wgpu::VertexState { - module: &shader, - entry_point: Some("vs_main"), - compilation_options: wgpu::PipelineCompilationOptions::default(), - buffers: &[ - wgpu::VertexBufferLayout { - array_stride: std::mem::size_of::() as wgpu::BufferAddress, - step_mode: wgpu::VertexStepMode::Vertex, - attributes: &wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3], - }, - ], - }, - fragment: Some(wgpu::FragmentState { - module: &shader, - entry_point: Some("fs_main"), - compilation_options: wgpu::PipelineCompilationOptions::default(), - targets: &[Some(wgpu::ColorTargetState { - format: surface_format, - blend: Some(wgpu::BlendState::REPLACE), - write_mask: wgpu::ColorWrites::ALL, - })], - }), - primitive: wgpu::PrimitiveState { - topology: wgpu::PrimitiveTopology::TriangleList, - strip_index_format: None, - front_face: wgpu::FrontFace::Ccw, - cull_mode: Some(wgpu::Face::Back), - polygon_mode: wgpu::PolygonMode::Fill, - unclipped_depth: false, - conservative: false, - }, - depth_stencil: Some(wgpu::DepthStencilState { - format: wgpu::TextureFormat::Depth24Plus, - depth_write_enabled: true, - depth_compare: wgpu::CompareFunction::LessEqual, - stencil: wgpu::StencilState::default(), - bias: wgpu::DepthBiasState::default(), - }), - multisample: wgpu::MultisampleState { - count: 1, - mask: !0, - alpha_to_coverage_enabled: false, - }, - multiview: None, - } - ); - - info!("Created render pipeline"); - - // Create depth texture - let depth_texture = device.create_texture(&wgpu::TextureDescriptor { - label: Some("Depth Texture"), - size: wgpu::Extent3d { - width, - height, - depth_or_array_layers: 1, - }, - mip_level_count: 1, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - format: wgpu::TextureFormat::Depth24Plus, - usage: wgpu::TextureUsages::RENDER_ATTACHMENT, - view_formats: &[], - }); - - let depth_view = depth_texture.create_view(&wgpu::TextureViewDescriptor::default()); - - // Start animation loop - spawn_local(async move { - loop { - // Get current rotation - let current_rotation = rotation(); - - // Create model-view-projection matrix - let model = Mat4::from_rotation_y(current_rotation); - let view = Mat4::look_at_rh( - Vec3::new(0.0, 0.0, 3.0), // Camera position - Vec3::new(0.0, 0.0, 0.0), // Look at center - Vec3::new(0.0, 1.0, 0.0), // Up vector - ); - let aspect = width as f32 / height as f32; - let proj = Mat4::perspective_rh(45.0f32.to_radians(), aspect, 0.1, 100.0); - - let mvp = proj * view * model; - - // Update uniform buffer - queue.write_buffer( - &uniform_buffer, - 0, - bytemuck::cast_slice(&[Uniforms { - mvp: mvp.to_cols_array_2d(), - }]), - ); - - // Get a frame - match surface.get_current_texture() { - Ok(frame) => { - let view = frame.texture.create_view(&wgpu::TextureViewDescriptor::default()); - - // Create command encoder - let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { - label: Some("Render Encoder"), - }); - - // Create render pass - { - let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { - label: Some("Main Render Pass"), - color_attachments: &[Some(wgpu::RenderPassColorAttachment { - view: &view, - resolve_target: None, - ops: wgpu::Operations { - load: wgpu::LoadOp::Clear(wgpu::Color { - r: 0.05, - g: 0.1, - b: 0.2, - a: 1.0, - }), - store: wgpu::StoreOp::Store, - }, - })], - depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { - view: &depth_view, - depth_ops: Some(wgpu::Operations { - load: wgpu::LoadOp::Clear(1.0), - store: wgpu::StoreOp::Store, - }), - stencil_ops: None, - }), - occlusion_query_set: None, - timestamp_writes: None, - }); - - // Set pipeline and bind groups - render_pass.set_pipeline(&render_pipeline); - render_pass.set_bind_group(0, &bind_group, &[]); - render_pass.set_vertex_buffer(0, vertex_buffer.slice(..)); - render_pass.set_index_buffer(index_buffer.slice(..), wgpu::IndexFormat::Uint16); - - // Draw the sphere - render_pass.draw_indexed(0..num_indices, 0, 0..1); - } - - // Submit commands - queue.submit(std::iter::once(encoder.finish())); - frame.present(); - }, - Err(e) => { - error!("Failed to get current texture: {:?}", e); - } - } - - // Yield to browser to avoid blocking the main thread - gloo_timers::future::TimeoutFuture::new(16).await; // ~60fps - } - }); - - info!("Started animation loop"); -} diff --git a/clickplanet-webapp/src/app/mod.rs b/clickplanet-webapp/src/app/mod.rs new file mode 100644 index 0000000..685b638 --- /dev/null +++ b/clickplanet-webapp/src/app/mod.rs @@ -0,0 +1,3 @@ +pub mod components; +pub mod countries; +pub mod viewer; diff --git a/clickplanet-webapp/src/backends/http_backend.rs b/clickplanet-webapp/src/backends/http_backend.rs index a5de5a6..3dd544a 100644 --- a/clickplanet-webapp/src/backends/http_backend.rs +++ b/clickplanet-webapp/src/backends/http_backend.rs @@ -5,13 +5,12 @@ use std::sync::{Arc, Mutex}; use crate::backends::backend::{Ownerships, OwnershipsGetter, TileClicker, Update, UpdatesListener}; use anyhow::Result; use base64::engine::general_purpose; -use clickplanet_proto::clicks::{BatchRequest, ClickRequest, OwnershipState}; +use clickplanet_proto::clicks::ClickRequest; use prost::Message; use uuid::Uuid; // WebAssembly compatible imports use gloo_net::http::Request; -use gloo::timers::callback::Timeout; use wasm_bindgen::prelude::*; use wasm_bindgen_futures::spawn_local; use web_sys::{MessageEvent, WebSocket}; diff --git a/clickplanet-webapp/src/backends/mod.rs b/clickplanet-webapp/src/backends/mod.rs index 30cd768..9ac3eb1 100644 --- a/clickplanet-webapp/src/backends/mod.rs +++ b/clickplanet-webapp/src/backends/mod.rs @@ -4,4 +4,3 @@ pub mod fake_backend; pub mod http_backend; // Re-export common types from backend -pub use backend::{TileClicker, Ownerships, OwnershipsGetter, Update, UpdatesListener}; diff --git a/clickplanet-webapp/src/main.rs b/clickplanet-webapp/src/main.rs index f1d3e59..3bb7f97 100644 --- a/clickplanet-webapp/src/main.rs +++ b/clickplanet-webapp/src/main.rs @@ -1,33 +1,13 @@ use dioxus::prelude::*; -use dioxus_web::launch; -use std::cell::RefCell; +use dioxus::document::Stylesheet; use crate::app::countries::Country; -mod app { - pub mod components { - pub mod buy_me_a_coffee; - pub mod block_button; - pub mod close_button; - pub mod discord_button; - pub mod modal; - pub mod modal_manager; - pub mod on_load_modal; - pub mod select_with_search; - pub mod globe; - pub mod settings; - pub mod leaderboard; - pub mod about; - } - pub mod countries; - pub mod viewer; -} - +mod app; mod backends; fn main() { console_log::init_with_level(log::Level::Debug).expect("Unable to initialize console_log"); - // Launch the web application launch(App); } @@ -40,70 +20,27 @@ enum Route { About {}, } -// App component takes no props now -// Commented out for now to fix compilation issues -/* -// Define a custom Link component for navigation -#[component] -fn Link(to: Route, children: Element) -> Element { - let onclick = move |_| { - APP_STATE.with(|state| { - if let Some(nav_fn) = state.navigate.borrow().as_ref() { - nav_fn(to.clone()) - } - }); - }; - - rsx! { - button { - class: "link-button", - onclick: onclick, - {children} - } - } -} - -// A simple state holder for app-wide state -thread_local! { - static APP_STATE: AppState = AppState::new(); -} - -struct AppState { - navigate: RefCell>>, -} -impl AppState { - fn new() -> Self { - Self { - navigate: RefCell::new(None), - } - } -} -*/ - -// Updated for Dioxus 0.6.x compatibility fn App() -> Element { let mut current_route = use_signal(|| Route::Home {}); - let mut navigate = move |route: Route| { + let navigate = move |route: Route| { current_route.set(route); }; - // Commented out for now to fix compilation issues - /* - // Store the navigation function in the app state for Link components - use_effect(move || { - APP_STATE.with(|state| { - *state.navigate.borrow_mut() = Some(Box::new(navigate.clone())); - }); - || {} - }); - */ - rsx! { - // Simplified to match original implementation without navigation bar + document::Link { rel: "icon", href: asset!("public/static/favicon.png") } + Stylesheet { href: asset!("public/styles/base.css") } + Stylesheet { href: asset!("public/styles/DiscordButton.css") } + Stylesheet { href: asset!("public/styles/BuyMeACoffee.css") } + Stylesheet { href: asset!("public/styles/Modal.css") } + Stylesheet { href: asset!("public/styles/CloseButton.css") } + Stylesheet { href: asset!("public/styles/SelectWithSearch.css") } + Stylesheet { href: asset!("public/styles/About.css") } + Stylesheet { href: asset!("public/styles/Leaderboard.css") } + Stylesheet { href: asset!("public/styles/Menu.css") } + Stylesheet { href: asset!("public/styles/rust-specific.css") } div { class: "content", - // Always show the HomeScreen as the original implementation does match current_route() { Route::Home {} => rsx! { HomeScreen {} }, Route::About {} => rsx! { AboutScreen {} }, @@ -129,7 +66,6 @@ fn HomeScreen() -> Element { rsx! { div { class: "container", - // Conditionally render the welcome modal if show_welcome_modal() { app::components::on_load_modal::OnLoadModal { title: "Dear earthlings".to_string(), @@ -138,7 +74,7 @@ fn HomeScreen() -> Element { div { class: "center-align", img { alt: "ClickPlanet logo", - src: "/static/logo.svg", + src: asset!("public/static/logo.svg"), width: "64px", height: "auto" } @@ -154,10 +90,8 @@ fn HomeScreen() -> Element { } } - // Main globe container - app::components::globe::GlobeMock {} + app::components::earth::globe::globe {} - // Menu with leaderboard and settings div { class: "menu", app::components::leaderboard::Leaderboard {} div { class: "menu-actions", @@ -175,15 +109,12 @@ fn HomeScreen() -> Element { } } -// Updated for Dioxus 0.6.x compatibility fn AboutScreen() -> Element { rsx! { div { class: "about-page", h1 { "About ClickPlanet" } p { "ClickPlanet is a real-time collaborative globe where players from around the world can claim hexagonal territories for their countries." } p { "This is a Rust/WebAssembly implementation of the original ClickPlanet game." } - // Link component commented out until fixed - // Link { to: Route::Home {}, "Return to the globe" } button { onclick: move |_| { // Manual navigation logic diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..83cb6e8 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,6 @@ +{ + "name": "clickplanet-client", + "lockfileVersion": 3, + "requires": true, + "packages": {} +} From 2d4f4bf4a43a08919cb3a62b1aa62721a0a17912 Mon Sep 17 00:00:00 2001 From: Laurent Valdes Date: Sun, 20 Apr 2025 03:13:03 +0200 Subject: [PATCH 04/28] chore: remove temp/build artifacts from repo and update .gitignore --- .boa_history | 0 .gitignore | 12 +++++++++++- .../__pycache__/download.cpython-311.pyc | Bin 6113 -> 0 bytes .../__pycache__/upload.cpython-311.pyc | Bin 4982 -> 0 bytes .../__pycache__/utils.cpython-311.pyc | Bin 5725 -> 0 bytes clickplanet-osm/project/metals.sbt | 8 -------- clickplanet-osm/project/project/metals.sbt | 8 -------- .../project/project/project/metals.sbt | 8 -------- package-lock.json | 6 ------ 9 files changed, 11 insertions(+), 31 deletions(-) delete mode 100644 .boa_history delete mode 100644 clickplanet-osm/download-job/__pycache__/download.cpython-311.pyc delete mode 100644 clickplanet-osm/download-job/__pycache__/upload.cpython-311.pyc delete mode 100644 clickplanet-osm/download-job/__pycache__/utils.cpython-311.pyc delete mode 100644 clickplanet-osm/project/metals.sbt delete mode 100644 clickplanet-osm/project/project/metals.sbt delete mode 100644 clickplanet-osm/project/project/project/metals.sbt delete mode 100644 package-lock.json diff --git a/.boa_history b/.boa_history deleted file mode 100644 index e69de29..0000000 diff --git a/.gitignore b/.gitignore index db10d8e..4ffd1bc 100644 --- a/.gitignore +++ b/.gitignore @@ -50,4 +50,14 @@ log4j.properties # Local utility scripts **/analyze-*.sh -**/cleanup-*.sh \ No newline at end of file +**/cleanup-*.sh + +# ignore boa history +.boa_history +# ignore Python bytecode and cache dirs +*.pyc +__pycache__/ +# ignore Metals build files +metals.sbt +# ignore npm lock file +package-lock.json \ No newline at end of file diff --git a/clickplanet-osm/download-job/__pycache__/download.cpython-311.pyc b/clickplanet-osm/download-job/__pycache__/download.cpython-311.pyc deleted file mode 100644 index 5afe2abec02dea04a173a558fd66d84ae09cac56..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6113 zcmb7IU2GFq7M`)k_V_2U6XzEK8DcizLSjOTfPn-;6MhN=O48jWw4{z_Y#jWzcg6%} z?NzkuLt62WT~#8xE!ymAm!_f*L4s9ZR-)auVx{eB9L)-Aq)14sKJey>tyHlud+r^3 z9EZSe?_8hzGk4B8_uT9AoqIp3t8-D1_&@(A_H8{y{R=lL$x^O7NkHWWB~SvLpvH}o z9;Zp$GHxNIb=*oyW}G3VZQKT>C1FoG#vMs^oJ~5%ok`cYE9oA0)0AL+hZ^??4A45k zA=uub$Lj?BoRrWL^zAYlzb(e5JV|-7Nw`eh%AL7 ziFo94CJ|1Fau3vDL`_#(N`@)|dZyBoW}`QAP2W(~Yoan@0*O*Oiz1?g>Oi&|eo{M- z8ES=by>m)!I9Oo%HKt#!WQ2!A%vnRj0Y74`-3+#t^SSoQQ6In}-n6c@n`{FPri<*M^AwiBMG+4ac80{a0YIG>$K&N5m%d$#hG;Hs4dyTvVda#YNkx61y?D2kdQe<0k> zS>?u6{n+dzt>61e-7T=(ZPR*rCdVvzD&MRwZ$aa>+3_Y=FmKD-bIg=!F`>R}*E>1e z!m62@A5pbD7QEFr)tca~o$(O$*1LH}&avRDj;YqxaBQf)sn!HvEl2cr%_=*dqep|# zSi6ga#_AqeSY_j?q*`rir9O9`_mPT5Ss9R<))=pvf*I@l)SyF z=~fC|$g|Jk(k$<&j?A&O+}7hS@2rkTKdRws?qoSs9W&KdslUi#G<6<)W1js5i#?=K zo2I9!tJd?>G#zXiQCg0PvK&vvxM(~fa#CCoiN{pDTvo!}Nc>q=lw|4gW{?-8b%z{J zis`KU_yM$)`d8B_8QfscDKQn3FDZ@Zz|G3QqQZ>lo?3f%M-?k~`iL@EJDR&Bh6NFE zsk96-vnc`mG{}=O>69ey2h>YmamyXwmJGEPyJc6cIw$ zCF!(F@kYv8C5Tr1Q<{H_-KNs9Ry{6?(n-RZ=ainKVNhGZvSOmltx=YY1aPdR z+J_N>5{A~=kLQBz2DUKqR5Y!#6%*eGGMP=qBVk$8T}YI(C`CBg1(B3CDU*oHx-F5O z2Do*BFeFRUaru&NlVlXn=r%A_8tKmAs}V6H$I~g@3NH}$?YdJ&;fRPWuDf88$*?>j zUX28ux)mEAW@0Rk&ftxrTO&z9ca+scO<4J6%!Pq<6LngY@Km@;Lf9wjO<*rTKDJFS&{4H}=wbpIw_I+CG{(_&^{QT_D zil_1VNwuwiaqM2#$3KCJnG2o)%`>2S28#aH*^}SExKnETTLsTW&2v%pTrB$A=l3iG z)W+`FS65m%t)+WGy2sx=^fmwYLu$)~LdylM<-+W-;-;++H|<*9w5zabx3+2byCbtl z=Z-$|wrJih3$HJGyH#&@v7_sEr+<6;H)lRP^RT0Dxub7sYoTMW*0HxlF%4S@nHws$ zZoHxVTKQG({oKRW-sRR_HFUVpI;gb{mMClU)|Jk#g;ze}|G+Osmih{TJz8MTQdkS@ zdl(p44h$3mhqb`rLg%2?IXKU(v~B*-t!^E?|H{{v&-Oya%!Rfwt!+$g8!L7O=H2)y zIe__hF3Rb>?opdxyFUs9a)CXmu_smbWYO!NmA_wcH-VbARRk{_e6atXf9dr*Eq7a> z3c0}Y8q2FJzvA|lDB9VFt$*rfyVl-QXb)-ap@L_Z=Gmosb`id_vhjQmspJIyP)gmf zMSeLraI}y5oE~b1;;Ys+O#58NTdZFl81x-)us&$8K_g;@D)0&3h9pd~0KGxwEIC>M zuoq|rUgVh?XKRL60*r#7$(pkO1xS}yaU_9=4FVDSO-HS3r$HFR!EE*0n@pU}+iGN( zp@QJd*#t)w64wO=tbI9E1FakdU%CYMC!SlN*KJd`Jro2K_9^U0ND}I<(5P3aU)_hL z2T&%ULO8Vs{?=NoMw6=j zeJ|p%?rJnV8x{(UIrc@`2dF+uVx}zyAY!;GZwmh$%sf;+3UOgB zaw(g-%n5M>r<}w!fMI~Z@_`8>2Vg8Gg|A>Rh8JOi?k?=s2^mB&i6=GO1vtTTZ=5@Y zM^;Wc1ZB+;1d%2tugN0Mjbe1-aGlGfr8q_-bDWqG%AZh?|abtfpHbSVJ%2ejGWIa0KC)81(=N zx==3^<#2{<3!SZO5WS(YsOC1%UBsS7aDfegaOkW%$x=)trI^m()j_X7uY}Kic|AW;%FE~V_l@ZMyS$8HEx)HtP$l1DhX2N-+E=QlnmROp zV0Nfvr+ixg*Xw$UzAdV6%bx-Z!taBB3>JJlHQ!Fvw-X0Z5Nw^h_wtf_XaC*(e>r#O zAT-Tf@QiAnQPndFA=iA<9ADa0D+vo;SA{hi;U`2Lf>*a|SlhokK%S z)MvYP3^}ZyZ}dR@^X-F;(D*Bl8(%n>A-CfTw-wjxXk{a#T;tdTJ47v{_c>_Hk}ITj zE?%B9ew|AfxT5nYp<{5g!uSvdr;ZN*sc_Oba)vo6BSzxUc!WDMdYTij;?`rU2hw8(QOQgEpl7b?@^x}MTq zO81XRUz$Ld#DxJ@x(t=OFo1L!EW1X^mzKnH;;a8Ept1+bo~pmV4ruIv$_|iVp4?mp>5-sMx1=SV!FLFTbMFML0Guvm z<#@ut2OF+R27chM7U8{YfC!FK$z3TqFA`5o=7+EcCo+f)p0Wp%X(5{s2hi*A0vkvA z6iCTR({zz?&XA`_xo5~zqdqIRhNUoJ5;JpkUYLhKzh Y9FRIV^vXw|$ zF|)cmC+i|gplL8oTCT)!J@8Z7BYEgc;V6Z^_EB;L5eo-_(ucgcxc8F2^!sL3t6kY9 z*V3`}o7wrd-^_f!-}jAw*W248LHgU%f3J`CNz&i(rJX`<;ovG19!a{S%SCBbWz*@+QA4wgtQbXcHzV+{eh@Y3o5bMuTq7~oOpMi)F&cx)9IDq&Smvwz zB@}|I46bb}Y=?Kfb+?COZcC4${)yMNrP#`D`{?`~C0p+5soEhLwL`X=^>nhswqmRK zFdUGq{Rk%QA&}FMN&SrTD zXIiV~ZW&g#td)#evJ8@#d17rCZUeE*_RN;)4H8oxF-SDvAaM%bh}=fCd@IWex8W;4 zsaT+)RwTTVU?o>qtbloAc;T91RcYC$@FikFN3Q0SIOFfTxTeiP{MX3 z>*;1kb`i~oQa8wC$&LV+LfXSNn67i~0JP)_U{_$f@0#X1l;(?ORVOQg3(2PiYlBp% zSuyAlsH;{gCjIY0hWHd_=UIKx%xT3es*jyl@D=?|aBJbPiZQ zLEY|O#4{+H7NEFV)@Mm7?u1O{D7Y6+#Q3bhEanVguVvF(#6FiPH7SQT^{^=*JM7{w zPt6kFQQU!4l%4=1aZYq?G(`u&$I$^Sd2=x|G2CBB0_cP7dGU}eGrOK+bQC&Gz{7qH z03PnE;suw*JGFe(L4G-GQoaC zQsd8**Y=dxcFcw{(^O{a%FOe`iP{q9g~gYrv`PisDYu2RnX|y9G7B6?Dd&f!M;S3e z86exq4(ak;>1pUOc(Es*C)-jjq!>4Kfj$Co^m?}YV15YnQ9HWpo2S#a8@O9B@Px6f zM{{=U7+O(-WzL=C($y;*9$b7!k9-7K1R(GC-g&@2I9TyD z-48J|W7Is0E|ATV_W)7o^YPVN4K*s@#UScx>y9Hh;N2-bkn2X#fM|=i&yo)|44^5B z%pe;0!UG$naTALM!66VDl!8gyPi)D#bd*gWFNS^W5?^_)2 zo%30@geVw-=iqS6XTQ>2>RmCM9y;xr@X-j+!$JGhmClG@3)r8!jMPW17pSl!&rk$a zD(r;8-W&z_%uyMj+e*nID8YV$re4M_6t&WtuFc(^a5q96)64}^z8? z^hfsfTYrA%FBkuG@vm<;GS`}!YxR})o0;p+G9T_`KCFL~ZDc-fW&i6L#)kK$kUG&ieHOe#e1eO6S6a!F&ywSN$?-<=Ofz|=&VSE+Hy1yDV;On$ zAPFWAyt(*!x)c5d882vgTPlWm5bT9P!hHlnK6NW%`Mwt%y>&c`ci)C$z}p^&gT7v} zBV9VgZ3Tin#g1pa?;gkAaA#8V@Kfb6?7$Pxn*j625kuNfVM{pfy--h3Ql99Vr4fy} zT%HF87xWJ1=f6Mj!T(R127+8Kd;-xXL_-~C!9RociE7P~A8%R)6DmUgu4s=NcDY(w zGbqN0ps#o#Q&k3$72f~Wjj}<(?Suc(h-HBLq8i)v*ZK8lCWqG_{=XY>9C&->VJ@dhimRs>8gugJbP67)Wa`zTF-MU_(G{`Z zg4hqsvfPs5HU8%-Bx?MxC6RjYx39?ZIIv(_#0F)uF9pT)sNBCV1;y+njtGiHc@jGw IBe?ee0asJQw*UYD diff --git a/clickplanet-osm/download-job/__pycache__/utils.cpython-311.pyc b/clickplanet-osm/download-job/__pycache__/utils.cpython-311.pyc deleted file mode 100644 index 7293930ffd5090b658f9b661316abab93fcac951..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 5725 zcmbVPTWlN06`duAY5;Q3s)cr`&&s}2y6AK71Q1~N%0{j!WK+!u( zaYb4*s&+V>ot?RR=g!QzXYPFN^|}xw`49h^`Zv`6NnQ%cu~~UKXhG-(;!p%}6lY0L z5z2U4A{OImjaZE*j$q?yi`d|4P1uw6h@C-JUp`T;zH)1(HCep!hYqX(`o6p%-ej%SBEx zL)OSh&uioyC2|IF5y5S8bcvivE!*UrHyt~+(IxN6TSdwla|PBawpzDpr6Y0fy=K?{ zv@V_!d{{WIKyelSlLnuBz#JNt{}No%Kbn5Ep^=qh#4DO4=0Zbbg1^Ei1eUzM!!$G| z0n6+Zyre4|&L3$=9%#Z(4#x9@FHOW-6qWf<%tB0O;~rru+jXYxkz<$;oM~53NLnI z8hlNBl!5f@Y|Eqs?=1;-PUHpo3Y*|~sbx$|&A_armRKSly9{;-ynF=eAW_l;ThUV3 ziX*^?EreR7!0dwVm3Vn>HcEzr^%7r$@d#k0LqLsLwEprdiog9=j_ck}ymtrggtJ4r z%8u-txvGZj@DuFT@b1<4J=cR_1&^tCOv7VPdE%|nya$wnEvomZ<~^G2e~eu}AO3Jy z@ehC7e!ugZuKQh3g{7dbO6`e8YEd zYoSRsbWRJM%Qrx&;tLwSpx_Ipp5r%Kid!|@ zs^C^ry65#qAnyS8)4dcV%|uDJ&I= znWr4QkPRbHd76OY29k^VX3Tm9==+YP^o#{^HVGM_HIuYKjhQ%WrmQ1#2pk!YPLKnR zzZ#e1XzFtMrH~*2R=6$XGe(~T4uEw_O48{h3*HwOC9x5P&}|&?DbP`2`bu<`m8T_Q zHzPI?nccjhG`b~`*C`%@-e&kq?N9)4u>GUqPbzNLC^(?vfQAE5S%-ZNe;8IOyKW0m zKvr?LhP#zQ7JmdE$KY=!8fwOJR)7((oMs2`u(_OT=DAqZjb!`Q8%N3J$pQhdc`ASw zQ>v7=*UYnROUv`8P3iezFf3TI6{aqt;u zxstQS)*1*A_dyTA7*R?fP>hV)m@#&=(3dA$u>(Fi3V&%D3c!W0a(R9wvy{0xpfsHQ zYW&+h_xF8s;QoO}C*OK_@-6k`xOQ?}ePcpBlsQ9e?89&O_B9gK*}qpf_*2P9^@W8X$%MSe3wyw^y@ zNH3jL5WVy9B310GMKdew6UDkRRO$GOmJGF4$a;v$#vV&c7md*^WT7a;_NPcN+_Vq|?T(p+xDjU0Uu8g&u&F4Yq zqV;_%(VVZ%Q}gJm^*oxVn%tx56UCP#CN432J|JsmF7y0s`9KVAfawDh+v791+yQk# z*wn$KyZYk-n_yxPT?uou%n{HFXByGRCK6?WJ94Xpt0N=w$4!z40j_CGt^T6jN{*w!*rlUn%~Q67PJk=W9~^rhw!93!M;=F(guv5=Q4Zz9YHNZTh8SJ)z9gTuu)piQ^u z4`7Hzr%6z!+r^|T@(_w9APxYIHrQP}K}21^=b|jl$AS56aS1wgXXt8-pCxnCZN~JQ zuy~Tl;y5fBN{!T&?9COq4b(=$SU2V(LD;?lcOuH**CDyc9AlrCRBP-qbC)5@`>BK z+_uuS)V12Ex({pa!yCxrY+v_Otqd;>D|`CC9)tq2>KV{H1Bzz=x|T;)8}HRCo;KCf zrg_?+@}y?h^*3+Mt2M7`HLq?U>})rRYr*yE+UspMIzR3Fo#S?mS{=};1J{B%U-ild zOCPL$p!!-gUki-rZU5@jmjizu`P0aQdbM>xYaK8e*ZsS0xIc9(`-UG(Kml3xhc$m# z@rR-7x_6ZWGa#t+w`oRn`NNaK%4|&^Rsix3>+YHjM8O&qmt;LWOCF{6J>{);Nm=`z zO0ycxD&_JIkT$GD2UH{y=KswS41|uM?~b|p>#g5)?(aWn{rf>1)SF(?9Z|Tw#iG$X z)((NRNN&L*xm1c>q#y^XZW%tMTSnkNa7wQVhWdLa!xPcI!O79#==e}1q&s-wN?Zhd zS>Z+nm&MdP;EWu{c}Nos=h110{@6U1$1AyG8<&wh=1FvEgc1g#evga;-T>e;x)Uye za|ymnJOe`H%$I%&CCrneHZZ0zY$OyOM7gp~^2;Gt*7)U6Mb`M`kS}Zea>$!CemS&X zDb0^<&a5S8b6l(c+4-W% Date: Mon, 21 Apr 2025 20:10:56 +0200 Subject: [PATCH 05/28] feat: add static file deployment to GCS bucket - Replace Python deployment script with Bash script - Move static assets from webapp to dedicated directory - Remove raphael.jpeg - Script configures GCS bucket with proper web settings - Set appropriate cache control headers --- clickplanet-static/deploy_static.sh | 80 ++++++++++++++++++ .../static/coordinates.json | 0 .../static/countries/atlas.json | 0 .../static/countries/atlas.png | Bin .../static/countries/countries.json | 0 .../static/countries/custom/xb.svg | 0 .../static/countries/png100px/ad.png | Bin .../static/countries/png100px/ae.png | Bin .../static/countries/png100px/af.png | Bin .../static/countries/png100px/ag.png | Bin .../static/countries/png100px/ai.png | Bin .../static/countries/png100px/al.png | Bin .../static/countries/png100px/am.png | Bin .../static/countries/png100px/ao.png | Bin .../static/countries/png100px/aq.png | Bin .../static/countries/png100px/ar.png | Bin .../static/countries/png100px/as.png | Bin .../static/countries/png100px/at.png | Bin .../static/countries/png100px/au.png | Bin .../static/countries/png100px/aw.png | Bin .../static/countries/png100px/ax.png | Bin .../static/countries/png100px/az.png | Bin .../static/countries/png100px/ba.png | Bin .../static/countries/png100px/bb.png | Bin .../static/countries/png100px/bd.png | Bin .../static/countries/png100px/be.png | Bin .../static/countries/png100px/bf.png | Bin .../static/countries/png100px/bg.png | Bin .../static/countries/png100px/bh.png | Bin .../static/countries/png100px/bi.png | Bin .../static/countries/png100px/bj.png | Bin .../static/countries/png100px/bl.png | Bin .../static/countries/png100px/bm.png | Bin .../static/countries/png100px/bn.png | Bin .../static/countries/png100px/bo.png | Bin .../static/countries/png100px/bq.png | Bin .../static/countries/png100px/br.png | Bin .../static/countries/png100px/bs.png | Bin .../static/countries/png100px/bt.png | Bin .../static/countries/png100px/bv.png | Bin .../static/countries/png100px/bw.png | Bin .../static/countries/png100px/by.png | Bin .../static/countries/png100px/bz.png | Bin .../static/countries/png100px/ca.png | Bin .../static/countries/png100px/cc.png | Bin .../static/countries/png100px/cd.png | Bin .../static/countries/png100px/cf.png | Bin .../static/countries/png100px/cg.png | Bin .../static/countries/png100px/ch.png | Bin .../static/countries/png100px/ci.png | Bin .../static/countries/png100px/ck.png | Bin .../static/countries/png100px/cl.png | Bin .../static/countries/png100px/cm.png | Bin .../static/countries/png100px/cn.png | Bin .../static/countries/png100px/co.png | Bin .../static/countries/png100px/cr.png | Bin .../static/countries/png100px/cu.png | Bin .../static/countries/png100px/cv.png | Bin .../static/countries/png100px/cw.png | Bin .../static/countries/png100px/cx.png | Bin .../static/countries/png100px/cy.png | Bin .../static/countries/png100px/cz.png | Bin .../static/countries/png100px/de.png | Bin .../static/countries/png100px/dj.png | Bin .../static/countries/png100px/dk.png | Bin .../static/countries/png100px/dm.png | Bin .../static/countries/png100px/do.png | Bin .../static/countries/png100px/dz.png | Bin .../static/countries/png100px/ec.png | Bin .../static/countries/png100px/ee.png | Bin .../static/countries/png100px/eg.png | Bin .../static/countries/png100px/eh.png | Bin .../static/countries/png100px/er.png | Bin .../static/countries/png100px/es.png | Bin .../static/countries/png100px/et.png | Bin .../static/countries/png100px/eu.png | Bin .../static/countries/png100px/fi.png | Bin .../static/countries/png100px/fj.png | Bin .../static/countries/png100px/fk.png | Bin .../static/countries/png100px/fm.png | Bin .../static/countries/png100px/fo.png | Bin .../static/countries/png100px/fr.png | Bin .../static/countries/png100px/ga.png | Bin .../static/countries/png100px/gb-eng.png | Bin .../static/countries/png100px/gb-nir.png | Bin .../static/countries/png100px/gb-sct.png | Bin .../static/countries/png100px/gb-wls.png | Bin .../static/countries/png100px/gb.png | Bin .../static/countries/png100px/gd.png | Bin .../static/countries/png100px/ge.png | Bin .../static/countries/png100px/gf.png | Bin .../static/countries/png100px/gg.png | Bin .../static/countries/png100px/gh.png | Bin .../static/countries/png100px/gi.png | Bin .../static/countries/png100px/gl.png | Bin .../static/countries/png100px/gm.png | Bin .../static/countries/png100px/gn.png | Bin .../static/countries/png100px/gp.png | Bin .../static/countries/png100px/gq.png | Bin .../static/countries/png100px/gr.png | Bin .../static/countries/png100px/gs.png | Bin .../static/countries/png100px/gt.png | Bin .../static/countries/png100px/gu.png | Bin .../static/countries/png100px/gw.png | Bin .../static/countries/png100px/gy.png | Bin .../static/countries/png100px/hk.png | Bin .../static/countries/png100px/hm.png | Bin .../static/countries/png100px/hn.png | Bin .../static/countries/png100px/hr.png | Bin .../static/countries/png100px/ht.png | Bin .../static/countries/png100px/hu.png | Bin .../static/countries/png100px/id.png | Bin .../static/countries/png100px/ie.png | Bin .../static/countries/png100px/il.png | Bin .../static/countries/png100px/im.png | Bin .../static/countries/png100px/in.png | Bin .../static/countries/png100px/io.png | Bin .../static/countries/png100px/iq.png | Bin .../static/countries/png100px/ir.png | Bin .../static/countries/png100px/is.png | Bin .../static/countries/png100px/it.png | Bin .../static/countries/png100px/je.png | Bin .../static/countries/png100px/jm.png | Bin .../static/countries/png100px/jo.png | Bin .../static/countries/png100px/jp.png | Bin .../static/countries/png100px/ke.png | Bin .../static/countries/png100px/kg.png | Bin .../static/countries/png100px/kh.png | Bin .../static/countries/png100px/ki.png | Bin .../static/countries/png100px/km.png | Bin .../static/countries/png100px/kn.png | Bin .../static/countries/png100px/kp.png | Bin .../static/countries/png100px/kr.png | Bin .../static/countries/png100px/kw.png | Bin .../static/countries/png100px/ky.png | Bin .../static/countries/png100px/kz.png | Bin .../static/countries/png100px/la.png | Bin .../static/countries/png100px/lb.png | Bin .../static/countries/png100px/lc.png | Bin .../static/countries/png100px/li.png | Bin .../static/countries/png100px/lk.png | Bin .../static/countries/png100px/lr.png | Bin .../static/countries/png100px/ls.png | Bin .../static/countries/png100px/lt.png | Bin .../static/countries/png100px/lu.png | Bin .../static/countries/png100px/lv.png | Bin .../static/countries/png100px/ly.png | Bin .../static/countries/png100px/ma.png | Bin .../static/countries/png100px/mc.png | Bin .../static/countries/png100px/md.png | Bin .../static/countries/png100px/me.png | Bin .../static/countries/png100px/mf.png | Bin .../static/countries/png100px/mg.png | Bin .../static/countries/png100px/mh.png | Bin .../static/countries/png100px/mk.png | Bin .../static/countries/png100px/ml.png | Bin .../static/countries/png100px/mm.png | Bin .../static/countries/png100px/mn.png | Bin .../static/countries/png100px/mo.png | Bin .../static/countries/png100px/mp.png | Bin .../static/countries/png100px/mq.png | Bin .../static/countries/png100px/mr.png | Bin .../static/countries/png100px/ms.png | Bin .../static/countries/png100px/mt.png | Bin .../static/countries/png100px/mu.png | Bin .../static/countries/png100px/mv.png | Bin .../static/countries/png100px/mw.png | Bin .../static/countries/png100px/mx.png | Bin .../static/countries/png100px/my.png | Bin .../static/countries/png100px/mz.png | Bin .../static/countries/png100px/na.png | Bin .../static/countries/png100px/nc.png | Bin .../static/countries/png100px/ne.png | Bin .../static/countries/png100px/nf.png | Bin .../static/countries/png100px/ng.png | Bin .../static/countries/png100px/ni.png | Bin .../static/countries/png100px/nl.png | Bin .../static/countries/png100px/no.png | Bin .../static/countries/png100px/np.png | Bin .../static/countries/png100px/nr.png | Bin .../static/countries/png100px/nu.png | Bin .../static/countries/png100px/nz.png | Bin .../static/countries/png100px/om.png | Bin .../static/countries/png100px/pa.png | Bin .../static/countries/png100px/pe.png | Bin .../static/countries/png100px/pf.png | Bin .../static/countries/png100px/pg.png | Bin .../static/countries/png100px/ph.png | Bin .../static/countries/png100px/pk.png | Bin .../static/countries/png100px/pl.png | Bin .../static/countries/png100px/pm.png | Bin .../static/countries/png100px/pn.png | Bin .../static/countries/png100px/pr.png | Bin .../static/countries/png100px/ps.png | Bin .../static/countries/png100px/pt.png | Bin .../static/countries/png100px/pw.png | Bin .../static/countries/png100px/py.png | Bin .../static/countries/png100px/qa.png | Bin .../static/countries/png100px/re.png | Bin .../static/countries/png100px/ro.png | Bin .../static/countries/png100px/rs.png | Bin .../static/countries/png100px/ru.png | Bin .../static/countries/png100px/rw.png | Bin .../static/countries/png100px/sa.png | Bin .../static/countries/png100px/sb.png | Bin .../static/countries/png100px/sc.png | Bin .../static/countries/png100px/sd.png | Bin .../static/countries/png100px/se.png | Bin .../static/countries/png100px/sg.png | Bin .../static/countries/png100px/sh.png | Bin .../static/countries/png100px/si.png | Bin .../static/countries/png100px/sj.png | Bin .../static/countries/png100px/sk.png | Bin .../static/countries/png100px/sl.png | Bin .../static/countries/png100px/sm.png | Bin .../static/countries/png100px/sn.png | Bin .../static/countries/png100px/so.png | Bin .../static/countries/png100px/sr.png | Bin .../static/countries/png100px/ss.png | Bin .../static/countries/png100px/st.png | Bin .../static/countries/png100px/sv.png | Bin .../static/countries/png100px/sx.png | Bin .../static/countries/png100px/sy.png | Bin .../static/countries/png100px/sz.png | Bin .../static/countries/png100px/tc.png | Bin .../static/countries/png100px/td.png | Bin .../static/countries/png100px/tf.png | Bin .../static/countries/png100px/tg.png | Bin .../static/countries/png100px/th.png | Bin .../static/countries/png100px/tj.png | Bin .../static/countries/png100px/tk.png | Bin .../static/countries/png100px/tl.png | Bin .../static/countries/png100px/tm.png | Bin .../static/countries/png100px/tn.png | Bin .../static/countries/png100px/to.png | Bin .../static/countries/png100px/tr.png | Bin .../static/countries/png100px/tt.png | Bin .../static/countries/png100px/tv.png | Bin .../static/countries/png100px/tw.png | Bin .../static/countries/png100px/tz.png | Bin .../static/countries/png100px/ua.png | Bin .../static/countries/png100px/ug.png | Bin .../static/countries/png100px/um.png | Bin .../static/countries/png100px/us.png | Bin .../static/countries/png100px/uy.png | Bin .../static/countries/png100px/uz.png | Bin .../static/countries/png100px/va.png | Bin .../static/countries/png100px/vc.png | Bin .../static/countries/png100px/ve.png | Bin .../static/countries/png100px/vg.png | Bin .../static/countries/png100px/vi.png | Bin .../static/countries/png100px/vn.png | Bin .../static/countries/png100px/vu.png | Bin .../static/countries/png100px/wf.png | Bin .../static/countries/png100px/ws.png | Bin .../static/countries/png100px/xb.png | Bin .../static/countries/png100px/xk.png | Bin .../static/countries/png100px/ye.png | Bin .../static/countries/png100px/yt.png | Bin .../static/countries/png100px/za.png | Bin .../static/countries/png100px/zm.png | Bin .../static/countries/png100px/zw.png | Bin .../static/countries/svg/ad.svg | 0 .../static/countries/svg/ae.svg | 0 .../static/countries/svg/af.svg | 0 .../static/countries/svg/ag.svg | 0 .../static/countries/svg/ai.svg | 0 .../static/countries/svg/al.svg | 0 .../static/countries/svg/am.svg | 0 .../static/countries/svg/ao.svg | 0 .../static/countries/svg/aq.svg | 0 .../static/countries/svg/ar.svg | 0 .../static/countries/svg/as.svg | 0 .../static/countries/svg/at.svg | 0 .../static/countries/svg/au.svg | 0 .../static/countries/svg/aw.svg | 0 .../static/countries/svg/ax.svg | 0 .../static/countries/svg/az.svg | 0 .../static/countries/svg/ba.svg | 0 .../static/countries/svg/bb.svg | 0 .../static/countries/svg/bd.svg | 0 .../static/countries/svg/be.svg | 0 .../static/countries/svg/bf.svg | 0 .../static/countries/svg/bg.svg | 0 .../static/countries/svg/bh.svg | 0 .../static/countries/svg/bi.svg | 0 .../static/countries/svg/bj.svg | 0 .../static/countries/svg/bl.svg | 0 .../static/countries/svg/bm.svg | 0 .../static/countries/svg/bn.svg | 0 .../static/countries/svg/bo.svg | 0 .../static/countries/svg/bq.svg | 0 .../static/countries/svg/br.svg | 0 .../static/countries/svg/bs.svg | 0 .../static/countries/svg/bt.svg | 0 .../static/countries/svg/bv.svg | 0 .../static/countries/svg/bw.svg | 0 .../static/countries/svg/by.svg | 0 .../static/countries/svg/bz.svg | 0 .../static/countries/svg/ca.svg | 0 .../static/countries/svg/cc.svg | 0 .../static/countries/svg/cd.svg | 0 .../static/countries/svg/cf.svg | 0 .../static/countries/svg/cg.svg | 0 .../static/countries/svg/ch.svg | 0 .../static/countries/svg/ci.svg | 0 .../static/countries/svg/ck.svg | 0 .../static/countries/svg/cl.svg | 0 .../static/countries/svg/cm.svg | 0 .../static/countries/svg/cn.svg | 0 .../static/countries/svg/co.svg | 0 .../static/countries/svg/cr.svg | 0 .../static/countries/svg/cu.svg | 0 .../static/countries/svg/cv.svg | 0 .../static/countries/svg/cw.svg | 0 .../static/countries/svg/cx.svg | 0 .../static/countries/svg/cy.svg | 0 .../static/countries/svg/cz.svg | 0 .../static/countries/svg/de.svg | 0 .../static/countries/svg/dj.svg | 0 .../static/countries/svg/dk.svg | 0 .../static/countries/svg/dm.svg | 0 .../static/countries/svg/do.svg | 0 .../static/countries/svg/dz.svg | 0 .../static/countries/svg/ec.svg | 0 .../static/countries/svg/ee.svg | 0 .../static/countries/svg/eg.svg | 0 .../static/countries/svg/eh.svg | 0 .../static/countries/svg/er.svg | 0 .../static/countries/svg/es.svg | 0 .../static/countries/svg/et.svg | 0 .../static/countries/svg/eu.svg | 0 .../static/countries/svg/fi.svg | 0 .../static/countries/svg/fj.svg | 0 .../static/countries/svg/fk.svg | 0 .../static/countries/svg/fm.svg | 0 .../static/countries/svg/fo.svg | 0 .../static/countries/svg/fr.svg | 0 .../static/countries/svg/ga.svg | 0 .../static/countries/svg/gb-eng.svg | 0 .../static/countries/svg/gb-nir.svg | 0 .../static/countries/svg/gb-sct.svg | 0 .../static/countries/svg/gb-wls.svg | 0 .../static/countries/svg/gb.svg | 0 .../static/countries/svg/gd.svg | 0 .../static/countries/svg/ge.svg | 0 .../static/countries/svg/gf.svg | 0 .../static/countries/svg/gg.svg | 0 .../static/countries/svg/gh.svg | 0 .../static/countries/svg/gi.svg | 0 .../static/countries/svg/gl.svg | 0 .../static/countries/svg/gm.svg | 0 .../static/countries/svg/gn.svg | 0 .../static/countries/svg/gp.svg | 0 .../static/countries/svg/gq.svg | 0 .../static/countries/svg/gr.svg | 0 .../static/countries/svg/gs.svg | 0 .../static/countries/svg/gt.svg | 0 .../static/countries/svg/gu.svg | 0 .../static/countries/svg/gw.svg | 0 .../static/countries/svg/gy.svg | 0 .../static/countries/svg/hk.svg | 0 .../static/countries/svg/hm.svg | 0 .../static/countries/svg/hn.svg | 0 .../static/countries/svg/hr.svg | 0 .../static/countries/svg/ht.svg | 0 .../static/countries/svg/hu.svg | 0 .../static/countries/svg/id.svg | 0 .../static/countries/svg/ie.svg | 0 .../static/countries/svg/il.svg | 0 .../static/countries/svg/im.svg | 0 .../static/countries/svg/in.svg | 0 .../static/countries/svg/io.svg | 0 .../static/countries/svg/iq.svg | 0 .../static/countries/svg/ir.svg | 0 .../static/countries/svg/is.svg | 0 .../static/countries/svg/it.svg | 0 .../static/countries/svg/je.svg | 0 .../static/countries/svg/jm.svg | 0 .../static/countries/svg/jo.svg | 0 .../static/countries/svg/jp.svg | 0 .../static/countries/svg/ke.svg | 0 .../static/countries/svg/kg.svg | 0 .../static/countries/svg/kh.svg | 0 .../static/countries/svg/ki.svg | 0 .../static/countries/svg/km.svg | 0 .../static/countries/svg/kn.svg | 0 .../static/countries/svg/kp.svg | 0 .../static/countries/svg/kr.svg | 0 .../static/countries/svg/kw.svg | 0 .../static/countries/svg/ky.svg | 0 .../static/countries/svg/kz.svg | 0 .../static/countries/svg/la.svg | 0 .../static/countries/svg/lb.svg | 0 .../static/countries/svg/lc.svg | 0 .../static/countries/svg/li.svg | 0 .../static/countries/svg/lk.svg | 0 .../static/countries/svg/lr.svg | 0 .../static/countries/svg/ls.svg | 0 .../static/countries/svg/lt.svg | 0 .../static/countries/svg/lu.svg | 0 .../static/countries/svg/lv.svg | 0 .../static/countries/svg/ly.svg | 0 .../static/countries/svg/ma.svg | 0 .../static/countries/svg/mc.svg | 0 .../static/countries/svg/md.svg | 0 .../static/countries/svg/me.svg | 0 .../static/countries/svg/mf.svg | 0 .../static/countries/svg/mg.svg | 0 .../static/countries/svg/mh.svg | 0 .../static/countries/svg/mk.svg | 0 .../static/countries/svg/ml.svg | 0 .../static/countries/svg/mm.svg | 0 .../static/countries/svg/mn.svg | 0 .../static/countries/svg/mo.svg | 0 .../static/countries/svg/mp.svg | 0 .../static/countries/svg/mq.svg | 0 .../static/countries/svg/mr.svg | 0 .../static/countries/svg/ms.svg | 0 .../static/countries/svg/mt.svg | 0 .../static/countries/svg/mu.svg | 0 .../static/countries/svg/mv.svg | 0 .../static/countries/svg/mw.svg | 0 .../static/countries/svg/mx.svg | 0 .../static/countries/svg/my.svg | 0 .../static/countries/svg/mz.svg | 0 .../static/countries/svg/na.svg | 0 .../static/countries/svg/nc.svg | 0 .../static/countries/svg/ne.svg | 0 .../static/countries/svg/nf.svg | 0 .../static/countries/svg/ng.svg | 0 .../static/countries/svg/ni.svg | 0 .../static/countries/svg/nl.svg | 0 .../static/countries/svg/no.svg | 0 .../static/countries/svg/np.svg | 0 .../static/countries/svg/nr.svg | 0 .../static/countries/svg/nu.svg | 0 .../static/countries/svg/nz.svg | 0 .../static/countries/svg/om.svg | 0 .../static/countries/svg/pa.svg | 0 .../static/countries/svg/pe.svg | 0 .../static/countries/svg/pf.svg | 0 .../static/countries/svg/pg.svg | 0 .../static/countries/svg/ph.svg | 0 .../static/countries/svg/pk.svg | 0 .../static/countries/svg/pl.svg | 0 .../static/countries/svg/pm.svg | 0 .../static/countries/svg/pn.svg | 0 .../static/countries/svg/pr.svg | 0 .../static/countries/svg/ps.svg | 0 .../static/countries/svg/pt.svg | 0 .../static/countries/svg/pw.svg | 0 .../static/countries/svg/py.svg | 0 .../static/countries/svg/qa.svg | 0 .../static/countries/svg/re.svg | 0 .../static/countries/svg/ro.svg | 0 .../static/countries/svg/rs.svg | 0 .../static/countries/svg/ru.svg | 0 .../static/countries/svg/rw.svg | 0 .../static/countries/svg/sa.svg | 0 .../static/countries/svg/sb.svg | 0 .../static/countries/svg/sc.svg | 0 .../static/countries/svg/sd.svg | 0 .../static/countries/svg/se.svg | 0 .../static/countries/svg/sg.svg | 0 .../static/countries/svg/sh.svg | 0 .../static/countries/svg/si.svg | 0 .../static/countries/svg/sj.svg | 0 .../static/countries/svg/sk.svg | 0 .../static/countries/svg/sl.svg | 0 .../static/countries/svg/sm.svg | 0 .../static/countries/svg/sn.svg | 0 .../static/countries/svg/so.svg | 0 .../static/countries/svg/sr.svg | 0 .../static/countries/svg/ss.svg | 0 .../static/countries/svg/st.svg | 0 .../static/countries/svg/sv.svg | 0 .../static/countries/svg/sx.svg | 0 .../static/countries/svg/sy.svg | 0 .../static/countries/svg/sz.svg | 0 .../static/countries/svg/tc.svg | 0 .../static/countries/svg/td.svg | 0 .../static/countries/svg/tf.svg | 0 .../static/countries/svg/tg.svg | 0 .../static/countries/svg/th.svg | 0 .../static/countries/svg/tj.svg | 0 .../static/countries/svg/tk.svg | 0 .../static/countries/svg/tl.svg | 0 .../static/countries/svg/tm.svg | 0 .../static/countries/svg/tn.svg | 0 .../static/countries/svg/to.svg | 0 .../static/countries/svg/tr.svg | 0 .../static/countries/svg/tt.svg | 0 .../static/countries/svg/tv.svg | 0 .../static/countries/svg/tw.svg | 0 .../static/countries/svg/tz.svg | 0 .../static/countries/svg/ua.svg | 0 .../static/countries/svg/ug.svg | 0 .../static/countries/svg/um.svg | 0 .../static/countries/svg/us.svg | 0 .../static/countries/svg/uy.svg | 0 .../static/countries/svg/uz.svg | 0 .../static/countries/svg/va.svg | 0 .../static/countries/svg/vc.svg | 0 .../static/countries/svg/ve.svg | 0 .../static/countries/svg/vg.svg | 0 .../static/countries/svg/vi.svg | 0 .../static/countries/svg/vn.svg | 0 .../static/countries/svg/vu.svg | 0 .../static/countries/svg/wf.svg | 0 .../static/countries/svg/ws.svg | 0 .../static/countries/svg/xb.svg | 0 .../static/countries/svg/xk.svg | 0 .../static/countries/svg/ye.svg | 0 .../static/countries/svg/yt.svg | 0 .../static/countries/svg/za.svg | 0 .../static/countries/svg/zm.svg | 0 .../static/countries/svg/zw.svg | 0 .../static/discord.svg | 0 .../static/earth/2k_earth_specular_map.png | Bin .../static/earth/3_no_ice_clouds_16k.jpg | Bin .../static/favicon.png | Bin .../static/logo.svg | 0 .../static/og-image.png | Bin clickplanet-webapp/public/static/raphael.jpeg | Bin 38334 -> 0 bytes 525 files changed, 80 insertions(+) create mode 100755 clickplanet-static/deploy_static.sh rename {clickplanet-webapp/public => clickplanet-static}/static/coordinates.json (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/atlas.json (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/atlas.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/countries.json (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/custom/xb.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ad.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ae.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/af.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ag.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ai.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/al.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/am.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ao.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/aq.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ar.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/as.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/at.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/au.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/aw.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ax.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/az.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ba.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/bb.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/bd.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/be.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/bf.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/bg.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/bh.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/bi.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/bj.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/bl.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/bm.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/bn.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/bo.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/bq.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/br.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/bs.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/bt.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/bv.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/bw.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/by.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/bz.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ca.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/cc.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/cd.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/cf.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/cg.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ch.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ci.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ck.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/cl.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/cm.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/cn.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/co.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/cr.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/cu.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/cv.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/cw.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/cx.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/cy.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/cz.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/de.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/dj.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/dk.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/dm.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/do.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/dz.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ec.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ee.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/eg.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/eh.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/er.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/es.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/et.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/eu.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/fi.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/fj.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/fk.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/fm.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/fo.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/fr.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ga.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/gb-eng.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/gb-nir.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/gb-sct.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/gb-wls.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/gb.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/gd.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ge.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/gf.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/gg.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/gh.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/gi.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/gl.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/gm.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/gn.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/gp.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/gq.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/gr.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/gs.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/gt.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/gu.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/gw.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/gy.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/hk.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/hm.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/hn.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/hr.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ht.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/hu.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/id.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ie.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/il.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/im.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/in.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/io.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/iq.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ir.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/is.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/it.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/je.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/jm.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/jo.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/jp.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ke.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/kg.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/kh.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ki.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/km.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/kn.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/kp.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/kr.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/kw.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ky.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/kz.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/la.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/lb.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/lc.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/li.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/lk.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/lr.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ls.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/lt.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/lu.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/lv.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ly.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ma.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/mc.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/md.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/me.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/mf.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/mg.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/mh.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/mk.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ml.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/mm.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/mn.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/mo.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/mp.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/mq.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/mr.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ms.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/mt.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/mu.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/mv.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/mw.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/mx.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/my.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/mz.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/na.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/nc.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ne.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/nf.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ng.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ni.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/nl.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/no.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/np.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/nr.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/nu.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/nz.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/om.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/pa.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/pe.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/pf.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/pg.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ph.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/pk.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/pl.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/pm.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/pn.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/pr.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ps.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/pt.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/pw.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/py.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/qa.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/re.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ro.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/rs.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ru.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/rw.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/sa.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/sb.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/sc.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/sd.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/se.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/sg.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/sh.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/si.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/sj.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/sk.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/sl.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/sm.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/sn.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/so.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/sr.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ss.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/st.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/sv.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/sx.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/sy.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/sz.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/tc.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/td.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/tf.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/tg.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/th.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/tj.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/tk.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/tl.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/tm.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/tn.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/to.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/tr.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/tt.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/tv.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/tw.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/tz.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ua.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ug.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/um.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/us.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/uy.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/uz.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/va.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/vc.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ve.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/vg.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/vi.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/vn.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/vu.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/wf.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ws.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/xb.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/xk.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/ye.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/yt.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/za.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/zm.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/png100px/zw.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ad.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ae.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/af.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ag.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ai.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/al.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/am.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ao.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/aq.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ar.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/as.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/at.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/au.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/aw.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ax.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/az.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ba.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/bb.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/bd.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/be.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/bf.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/bg.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/bh.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/bi.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/bj.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/bl.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/bm.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/bn.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/bo.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/bq.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/br.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/bs.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/bt.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/bv.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/bw.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/by.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/bz.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ca.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/cc.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/cd.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/cf.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/cg.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ch.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ci.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ck.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/cl.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/cm.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/cn.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/co.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/cr.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/cu.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/cv.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/cw.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/cx.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/cy.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/cz.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/de.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/dj.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/dk.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/dm.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/do.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/dz.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ec.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ee.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/eg.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/eh.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/er.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/es.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/et.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/eu.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/fi.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/fj.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/fk.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/fm.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/fo.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/fr.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ga.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/gb-eng.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/gb-nir.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/gb-sct.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/gb-wls.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/gb.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/gd.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ge.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/gf.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/gg.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/gh.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/gi.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/gl.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/gm.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/gn.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/gp.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/gq.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/gr.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/gs.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/gt.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/gu.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/gw.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/gy.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/hk.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/hm.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/hn.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/hr.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ht.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/hu.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/id.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ie.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/il.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/im.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/in.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/io.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/iq.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ir.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/is.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/it.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/je.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/jm.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/jo.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/jp.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ke.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/kg.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/kh.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ki.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/km.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/kn.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/kp.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/kr.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/kw.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ky.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/kz.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/la.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/lb.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/lc.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/li.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/lk.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/lr.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ls.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/lt.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/lu.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/lv.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ly.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ma.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/mc.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/md.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/me.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/mf.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/mg.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/mh.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/mk.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ml.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/mm.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/mn.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/mo.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/mp.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/mq.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/mr.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ms.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/mt.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/mu.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/mv.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/mw.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/mx.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/my.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/mz.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/na.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/nc.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ne.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/nf.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ng.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ni.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/nl.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/no.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/np.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/nr.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/nu.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/nz.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/om.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/pa.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/pe.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/pf.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/pg.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ph.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/pk.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/pl.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/pm.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/pn.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/pr.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ps.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/pt.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/pw.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/py.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/qa.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/re.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ro.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/rs.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ru.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/rw.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/sa.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/sb.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/sc.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/sd.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/se.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/sg.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/sh.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/si.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/sj.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/sk.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/sl.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/sm.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/sn.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/so.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/sr.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ss.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/st.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/sv.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/sx.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/sy.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/sz.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/tc.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/td.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/tf.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/tg.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/th.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/tj.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/tk.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/tl.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/tm.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/tn.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/to.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/tr.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/tt.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/tv.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/tw.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/tz.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ua.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ug.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/um.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/us.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/uy.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/uz.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/va.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/vc.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ve.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/vg.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/vi.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/vn.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/vu.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/wf.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ws.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/xb.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/xk.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/ye.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/yt.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/za.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/zm.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/countries/svg/zw.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/discord.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/earth/2k_earth_specular_map.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/earth/3_no_ice_clouds_16k.jpg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/favicon.png (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/logo.svg (100%) rename {clickplanet-webapp/public => clickplanet-static}/static/og-image.png (100%) delete mode 100644 clickplanet-webapp/public/static/raphael.jpeg diff --git a/clickplanet-static/deploy_static.sh b/clickplanet-static/deploy_static.sh new file mode 100755 index 0000000..dc7219e --- /dev/null +++ b/clickplanet-static/deploy_static.sh @@ -0,0 +1,80 @@ +#!/bin/bash +# +# Move static assets into clickplanet-static/ then deploy to GCS via gcloud CLI. +# Usage: +# ./deploy_static.sh +# or set GCS_BUCKET env var. +# + +set -e + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +LOCAL_SRC="$SCRIPT_DIR/static" +WEBAPP_SRC="$(cd "$SCRIPT_DIR/../clickplanet-webapp/public" && pwd)/static" + +move_static() { + if [ -d "$LOCAL_SRC" ]; then + echo "Using existing static in $LOCAL_SRC" + elif [ -d "$WEBAPP_SRC" ]; then + echo "Moving static files: $WEBAPP_SRC -> $SCRIPT_DIR" + mv "$WEBAPP_SRC" "$LOCAL_SRC" + else + echo "No static found in '$LOCAL_SRC' or '$WEBAPP_SRC'" + exit 1 + fi +} + +deploy() { + local bucket="$1" + + echo "Using bucket 'gs://$bucket'" + + # Configure bucket for website hosting + echo "Configuring bucket for static website hosting" + gcloud storage buckets update "gs://$bucket" \ + --web-main-page-suffix=index.html \ + --web-error-page=404.html + + # Make bucket contents publicly readable + echo "Setting public read access" + gcloud storage buckets add-iam-policy-binding "gs://$bucket" \ + --member=allUsers \ + --role=roles/storage.objectViewer + + # Upload files + echo "Uploading files from $LOCAL_SRC to gs://$bucket/" + + # First clean the bucket to avoid old files + echo "Cleaning existing files in the bucket..." + gcloud storage objects list "gs://$bucket/" | grep -v "^gs://$bucket/$" | xargs -r gcloud storage rm 2>/dev/null || true + + # Use the proper recursive upload with gcloud CLI + echo "Uploading all files and directories recursively" + + # Simply use the recursive upload with appropriate cache-control + echo "Uploading all files with appropriate cache-control" + # First remove .DS_Store files + find "$LOCAL_SRC" -name ".DS_Store" -type f -delete + + # Upload everything recursively + gcloud storage cp "$LOCAL_SRC" "gs://$bucket" --recursive \ + --cache-control="public, max-age=3600" + + if [ $? -ne 0 ]; then + echo "Failed to upload files" + exit 1 + fi + + echo "Successfully deployed static assets to gs://$bucket/" + echo "Website URL: https://storage.googleapis.com/$bucket/index.html" +} + +# Main +BUCKET=${1:-$GCS_BUCKET} +if [ -z "$BUCKET" ]; then + echo "Usage: ./deploy_static.sh or set GCS_BUCKET env var." + exit 1 +fi + +move_static +deploy "$BUCKET" diff --git a/clickplanet-webapp/public/static/coordinates.json b/clickplanet-static/static/coordinates.json similarity index 100% rename from clickplanet-webapp/public/static/coordinates.json rename to clickplanet-static/static/coordinates.json diff --git a/clickplanet-webapp/public/static/countries/atlas.json b/clickplanet-static/static/countries/atlas.json similarity index 100% rename from clickplanet-webapp/public/static/countries/atlas.json rename to clickplanet-static/static/countries/atlas.json diff --git a/clickplanet-webapp/public/static/countries/atlas.png b/clickplanet-static/static/countries/atlas.png similarity index 100% rename from clickplanet-webapp/public/static/countries/atlas.png rename to clickplanet-static/static/countries/atlas.png diff --git a/clickplanet-webapp/public/static/countries/countries.json b/clickplanet-static/static/countries/countries.json similarity index 100% rename from clickplanet-webapp/public/static/countries/countries.json rename to clickplanet-static/static/countries/countries.json diff --git a/clickplanet-webapp/public/static/countries/custom/xb.svg b/clickplanet-static/static/countries/custom/xb.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/custom/xb.svg rename to clickplanet-static/static/countries/custom/xb.svg diff --git a/clickplanet-webapp/public/static/countries/png100px/ad.png b/clickplanet-static/static/countries/png100px/ad.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ad.png rename to clickplanet-static/static/countries/png100px/ad.png diff --git a/clickplanet-webapp/public/static/countries/png100px/ae.png b/clickplanet-static/static/countries/png100px/ae.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ae.png rename to clickplanet-static/static/countries/png100px/ae.png diff --git a/clickplanet-webapp/public/static/countries/png100px/af.png b/clickplanet-static/static/countries/png100px/af.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/af.png rename to clickplanet-static/static/countries/png100px/af.png diff --git a/clickplanet-webapp/public/static/countries/png100px/ag.png b/clickplanet-static/static/countries/png100px/ag.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ag.png rename to clickplanet-static/static/countries/png100px/ag.png diff --git a/clickplanet-webapp/public/static/countries/png100px/ai.png b/clickplanet-static/static/countries/png100px/ai.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ai.png rename to clickplanet-static/static/countries/png100px/ai.png diff --git a/clickplanet-webapp/public/static/countries/png100px/al.png b/clickplanet-static/static/countries/png100px/al.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/al.png rename to clickplanet-static/static/countries/png100px/al.png diff --git a/clickplanet-webapp/public/static/countries/png100px/am.png b/clickplanet-static/static/countries/png100px/am.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/am.png rename to clickplanet-static/static/countries/png100px/am.png diff --git a/clickplanet-webapp/public/static/countries/png100px/ao.png b/clickplanet-static/static/countries/png100px/ao.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ao.png rename to clickplanet-static/static/countries/png100px/ao.png diff --git a/clickplanet-webapp/public/static/countries/png100px/aq.png b/clickplanet-static/static/countries/png100px/aq.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/aq.png rename to clickplanet-static/static/countries/png100px/aq.png diff --git a/clickplanet-webapp/public/static/countries/png100px/ar.png b/clickplanet-static/static/countries/png100px/ar.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ar.png rename to clickplanet-static/static/countries/png100px/ar.png diff --git a/clickplanet-webapp/public/static/countries/png100px/as.png b/clickplanet-static/static/countries/png100px/as.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/as.png rename to clickplanet-static/static/countries/png100px/as.png diff --git a/clickplanet-webapp/public/static/countries/png100px/at.png b/clickplanet-static/static/countries/png100px/at.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/at.png rename to clickplanet-static/static/countries/png100px/at.png diff --git a/clickplanet-webapp/public/static/countries/png100px/au.png b/clickplanet-static/static/countries/png100px/au.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/au.png rename to clickplanet-static/static/countries/png100px/au.png diff --git a/clickplanet-webapp/public/static/countries/png100px/aw.png b/clickplanet-static/static/countries/png100px/aw.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/aw.png rename to clickplanet-static/static/countries/png100px/aw.png diff --git a/clickplanet-webapp/public/static/countries/png100px/ax.png b/clickplanet-static/static/countries/png100px/ax.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ax.png rename to clickplanet-static/static/countries/png100px/ax.png diff --git a/clickplanet-webapp/public/static/countries/png100px/az.png b/clickplanet-static/static/countries/png100px/az.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/az.png rename to clickplanet-static/static/countries/png100px/az.png diff --git a/clickplanet-webapp/public/static/countries/png100px/ba.png b/clickplanet-static/static/countries/png100px/ba.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ba.png rename to clickplanet-static/static/countries/png100px/ba.png diff --git a/clickplanet-webapp/public/static/countries/png100px/bb.png b/clickplanet-static/static/countries/png100px/bb.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/bb.png rename to clickplanet-static/static/countries/png100px/bb.png diff --git a/clickplanet-webapp/public/static/countries/png100px/bd.png b/clickplanet-static/static/countries/png100px/bd.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/bd.png rename to clickplanet-static/static/countries/png100px/bd.png diff --git a/clickplanet-webapp/public/static/countries/png100px/be.png b/clickplanet-static/static/countries/png100px/be.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/be.png rename to clickplanet-static/static/countries/png100px/be.png diff --git a/clickplanet-webapp/public/static/countries/png100px/bf.png b/clickplanet-static/static/countries/png100px/bf.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/bf.png rename to clickplanet-static/static/countries/png100px/bf.png diff --git a/clickplanet-webapp/public/static/countries/png100px/bg.png b/clickplanet-static/static/countries/png100px/bg.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/bg.png rename to clickplanet-static/static/countries/png100px/bg.png diff --git a/clickplanet-webapp/public/static/countries/png100px/bh.png b/clickplanet-static/static/countries/png100px/bh.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/bh.png rename to clickplanet-static/static/countries/png100px/bh.png diff --git a/clickplanet-webapp/public/static/countries/png100px/bi.png b/clickplanet-static/static/countries/png100px/bi.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/bi.png rename to clickplanet-static/static/countries/png100px/bi.png diff --git a/clickplanet-webapp/public/static/countries/png100px/bj.png b/clickplanet-static/static/countries/png100px/bj.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/bj.png rename to clickplanet-static/static/countries/png100px/bj.png diff --git a/clickplanet-webapp/public/static/countries/png100px/bl.png b/clickplanet-static/static/countries/png100px/bl.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/bl.png rename to clickplanet-static/static/countries/png100px/bl.png diff --git a/clickplanet-webapp/public/static/countries/png100px/bm.png b/clickplanet-static/static/countries/png100px/bm.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/bm.png rename to clickplanet-static/static/countries/png100px/bm.png diff --git a/clickplanet-webapp/public/static/countries/png100px/bn.png b/clickplanet-static/static/countries/png100px/bn.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/bn.png rename to clickplanet-static/static/countries/png100px/bn.png diff --git a/clickplanet-webapp/public/static/countries/png100px/bo.png b/clickplanet-static/static/countries/png100px/bo.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/bo.png rename to clickplanet-static/static/countries/png100px/bo.png diff --git a/clickplanet-webapp/public/static/countries/png100px/bq.png b/clickplanet-static/static/countries/png100px/bq.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/bq.png rename to clickplanet-static/static/countries/png100px/bq.png diff --git a/clickplanet-webapp/public/static/countries/png100px/br.png b/clickplanet-static/static/countries/png100px/br.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/br.png rename to clickplanet-static/static/countries/png100px/br.png diff --git a/clickplanet-webapp/public/static/countries/png100px/bs.png b/clickplanet-static/static/countries/png100px/bs.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/bs.png rename to clickplanet-static/static/countries/png100px/bs.png diff --git a/clickplanet-webapp/public/static/countries/png100px/bt.png b/clickplanet-static/static/countries/png100px/bt.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/bt.png rename to clickplanet-static/static/countries/png100px/bt.png diff --git a/clickplanet-webapp/public/static/countries/png100px/bv.png b/clickplanet-static/static/countries/png100px/bv.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/bv.png rename to clickplanet-static/static/countries/png100px/bv.png diff --git a/clickplanet-webapp/public/static/countries/png100px/bw.png b/clickplanet-static/static/countries/png100px/bw.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/bw.png rename to clickplanet-static/static/countries/png100px/bw.png diff --git a/clickplanet-webapp/public/static/countries/png100px/by.png b/clickplanet-static/static/countries/png100px/by.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/by.png rename to clickplanet-static/static/countries/png100px/by.png diff --git a/clickplanet-webapp/public/static/countries/png100px/bz.png b/clickplanet-static/static/countries/png100px/bz.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/bz.png rename to clickplanet-static/static/countries/png100px/bz.png diff --git a/clickplanet-webapp/public/static/countries/png100px/ca.png b/clickplanet-static/static/countries/png100px/ca.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ca.png rename to clickplanet-static/static/countries/png100px/ca.png diff --git a/clickplanet-webapp/public/static/countries/png100px/cc.png b/clickplanet-static/static/countries/png100px/cc.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/cc.png rename to clickplanet-static/static/countries/png100px/cc.png diff --git a/clickplanet-webapp/public/static/countries/png100px/cd.png b/clickplanet-static/static/countries/png100px/cd.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/cd.png rename to clickplanet-static/static/countries/png100px/cd.png diff --git a/clickplanet-webapp/public/static/countries/png100px/cf.png b/clickplanet-static/static/countries/png100px/cf.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/cf.png rename to clickplanet-static/static/countries/png100px/cf.png diff --git a/clickplanet-webapp/public/static/countries/png100px/cg.png b/clickplanet-static/static/countries/png100px/cg.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/cg.png rename to clickplanet-static/static/countries/png100px/cg.png diff --git a/clickplanet-webapp/public/static/countries/png100px/ch.png b/clickplanet-static/static/countries/png100px/ch.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ch.png rename to clickplanet-static/static/countries/png100px/ch.png diff --git a/clickplanet-webapp/public/static/countries/png100px/ci.png b/clickplanet-static/static/countries/png100px/ci.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ci.png rename to clickplanet-static/static/countries/png100px/ci.png diff --git a/clickplanet-webapp/public/static/countries/png100px/ck.png b/clickplanet-static/static/countries/png100px/ck.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ck.png rename to clickplanet-static/static/countries/png100px/ck.png diff --git a/clickplanet-webapp/public/static/countries/png100px/cl.png b/clickplanet-static/static/countries/png100px/cl.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/cl.png rename to clickplanet-static/static/countries/png100px/cl.png diff --git a/clickplanet-webapp/public/static/countries/png100px/cm.png b/clickplanet-static/static/countries/png100px/cm.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/cm.png rename to clickplanet-static/static/countries/png100px/cm.png diff --git a/clickplanet-webapp/public/static/countries/png100px/cn.png b/clickplanet-static/static/countries/png100px/cn.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/cn.png rename to clickplanet-static/static/countries/png100px/cn.png diff --git a/clickplanet-webapp/public/static/countries/png100px/co.png b/clickplanet-static/static/countries/png100px/co.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/co.png rename to clickplanet-static/static/countries/png100px/co.png diff --git a/clickplanet-webapp/public/static/countries/png100px/cr.png b/clickplanet-static/static/countries/png100px/cr.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/cr.png rename to clickplanet-static/static/countries/png100px/cr.png diff --git a/clickplanet-webapp/public/static/countries/png100px/cu.png b/clickplanet-static/static/countries/png100px/cu.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/cu.png rename to clickplanet-static/static/countries/png100px/cu.png diff --git a/clickplanet-webapp/public/static/countries/png100px/cv.png b/clickplanet-static/static/countries/png100px/cv.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/cv.png rename to clickplanet-static/static/countries/png100px/cv.png diff --git a/clickplanet-webapp/public/static/countries/png100px/cw.png b/clickplanet-static/static/countries/png100px/cw.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/cw.png rename to clickplanet-static/static/countries/png100px/cw.png diff --git a/clickplanet-webapp/public/static/countries/png100px/cx.png b/clickplanet-static/static/countries/png100px/cx.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/cx.png rename to clickplanet-static/static/countries/png100px/cx.png diff --git a/clickplanet-webapp/public/static/countries/png100px/cy.png b/clickplanet-static/static/countries/png100px/cy.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/cy.png rename to clickplanet-static/static/countries/png100px/cy.png diff --git a/clickplanet-webapp/public/static/countries/png100px/cz.png b/clickplanet-static/static/countries/png100px/cz.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/cz.png rename to clickplanet-static/static/countries/png100px/cz.png diff --git a/clickplanet-webapp/public/static/countries/png100px/de.png b/clickplanet-static/static/countries/png100px/de.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/de.png rename to clickplanet-static/static/countries/png100px/de.png diff --git a/clickplanet-webapp/public/static/countries/png100px/dj.png b/clickplanet-static/static/countries/png100px/dj.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/dj.png rename to clickplanet-static/static/countries/png100px/dj.png diff --git a/clickplanet-webapp/public/static/countries/png100px/dk.png b/clickplanet-static/static/countries/png100px/dk.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/dk.png rename to clickplanet-static/static/countries/png100px/dk.png diff --git a/clickplanet-webapp/public/static/countries/png100px/dm.png b/clickplanet-static/static/countries/png100px/dm.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/dm.png rename to clickplanet-static/static/countries/png100px/dm.png diff --git a/clickplanet-webapp/public/static/countries/png100px/do.png b/clickplanet-static/static/countries/png100px/do.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/do.png rename to clickplanet-static/static/countries/png100px/do.png diff --git a/clickplanet-webapp/public/static/countries/png100px/dz.png b/clickplanet-static/static/countries/png100px/dz.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/dz.png rename to clickplanet-static/static/countries/png100px/dz.png diff --git a/clickplanet-webapp/public/static/countries/png100px/ec.png b/clickplanet-static/static/countries/png100px/ec.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ec.png rename to clickplanet-static/static/countries/png100px/ec.png diff --git a/clickplanet-webapp/public/static/countries/png100px/ee.png b/clickplanet-static/static/countries/png100px/ee.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ee.png rename to clickplanet-static/static/countries/png100px/ee.png diff --git a/clickplanet-webapp/public/static/countries/png100px/eg.png b/clickplanet-static/static/countries/png100px/eg.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/eg.png rename to clickplanet-static/static/countries/png100px/eg.png diff --git a/clickplanet-webapp/public/static/countries/png100px/eh.png b/clickplanet-static/static/countries/png100px/eh.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/eh.png rename to clickplanet-static/static/countries/png100px/eh.png diff --git a/clickplanet-webapp/public/static/countries/png100px/er.png b/clickplanet-static/static/countries/png100px/er.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/er.png rename to clickplanet-static/static/countries/png100px/er.png diff --git a/clickplanet-webapp/public/static/countries/png100px/es.png b/clickplanet-static/static/countries/png100px/es.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/es.png rename to clickplanet-static/static/countries/png100px/es.png diff --git a/clickplanet-webapp/public/static/countries/png100px/et.png b/clickplanet-static/static/countries/png100px/et.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/et.png rename to clickplanet-static/static/countries/png100px/et.png diff --git a/clickplanet-webapp/public/static/countries/png100px/eu.png b/clickplanet-static/static/countries/png100px/eu.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/eu.png rename to clickplanet-static/static/countries/png100px/eu.png diff --git a/clickplanet-webapp/public/static/countries/png100px/fi.png b/clickplanet-static/static/countries/png100px/fi.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/fi.png rename to clickplanet-static/static/countries/png100px/fi.png diff --git a/clickplanet-webapp/public/static/countries/png100px/fj.png b/clickplanet-static/static/countries/png100px/fj.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/fj.png rename to clickplanet-static/static/countries/png100px/fj.png diff --git a/clickplanet-webapp/public/static/countries/png100px/fk.png b/clickplanet-static/static/countries/png100px/fk.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/fk.png rename to clickplanet-static/static/countries/png100px/fk.png diff --git a/clickplanet-webapp/public/static/countries/png100px/fm.png b/clickplanet-static/static/countries/png100px/fm.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/fm.png rename to clickplanet-static/static/countries/png100px/fm.png diff --git a/clickplanet-webapp/public/static/countries/png100px/fo.png b/clickplanet-static/static/countries/png100px/fo.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/fo.png rename to clickplanet-static/static/countries/png100px/fo.png diff --git a/clickplanet-webapp/public/static/countries/png100px/fr.png b/clickplanet-static/static/countries/png100px/fr.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/fr.png rename to clickplanet-static/static/countries/png100px/fr.png diff --git a/clickplanet-webapp/public/static/countries/png100px/ga.png b/clickplanet-static/static/countries/png100px/ga.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ga.png rename to clickplanet-static/static/countries/png100px/ga.png diff --git a/clickplanet-webapp/public/static/countries/png100px/gb-eng.png b/clickplanet-static/static/countries/png100px/gb-eng.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/gb-eng.png rename to clickplanet-static/static/countries/png100px/gb-eng.png diff --git a/clickplanet-webapp/public/static/countries/png100px/gb-nir.png b/clickplanet-static/static/countries/png100px/gb-nir.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/gb-nir.png rename to clickplanet-static/static/countries/png100px/gb-nir.png diff --git a/clickplanet-webapp/public/static/countries/png100px/gb-sct.png b/clickplanet-static/static/countries/png100px/gb-sct.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/gb-sct.png rename to clickplanet-static/static/countries/png100px/gb-sct.png diff --git a/clickplanet-webapp/public/static/countries/png100px/gb-wls.png b/clickplanet-static/static/countries/png100px/gb-wls.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/gb-wls.png rename to clickplanet-static/static/countries/png100px/gb-wls.png diff --git a/clickplanet-webapp/public/static/countries/png100px/gb.png b/clickplanet-static/static/countries/png100px/gb.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/gb.png rename to clickplanet-static/static/countries/png100px/gb.png diff --git a/clickplanet-webapp/public/static/countries/png100px/gd.png b/clickplanet-static/static/countries/png100px/gd.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/gd.png rename to clickplanet-static/static/countries/png100px/gd.png diff --git a/clickplanet-webapp/public/static/countries/png100px/ge.png b/clickplanet-static/static/countries/png100px/ge.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ge.png rename to clickplanet-static/static/countries/png100px/ge.png diff --git a/clickplanet-webapp/public/static/countries/png100px/gf.png b/clickplanet-static/static/countries/png100px/gf.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/gf.png rename to clickplanet-static/static/countries/png100px/gf.png diff --git a/clickplanet-webapp/public/static/countries/png100px/gg.png b/clickplanet-static/static/countries/png100px/gg.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/gg.png rename to clickplanet-static/static/countries/png100px/gg.png diff --git a/clickplanet-webapp/public/static/countries/png100px/gh.png b/clickplanet-static/static/countries/png100px/gh.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/gh.png rename to clickplanet-static/static/countries/png100px/gh.png diff --git a/clickplanet-webapp/public/static/countries/png100px/gi.png b/clickplanet-static/static/countries/png100px/gi.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/gi.png rename to clickplanet-static/static/countries/png100px/gi.png diff --git a/clickplanet-webapp/public/static/countries/png100px/gl.png b/clickplanet-static/static/countries/png100px/gl.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/gl.png rename to clickplanet-static/static/countries/png100px/gl.png diff --git a/clickplanet-webapp/public/static/countries/png100px/gm.png b/clickplanet-static/static/countries/png100px/gm.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/gm.png rename to clickplanet-static/static/countries/png100px/gm.png diff --git a/clickplanet-webapp/public/static/countries/png100px/gn.png b/clickplanet-static/static/countries/png100px/gn.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/gn.png rename to clickplanet-static/static/countries/png100px/gn.png diff --git a/clickplanet-webapp/public/static/countries/png100px/gp.png b/clickplanet-static/static/countries/png100px/gp.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/gp.png rename to clickplanet-static/static/countries/png100px/gp.png diff --git a/clickplanet-webapp/public/static/countries/png100px/gq.png b/clickplanet-static/static/countries/png100px/gq.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/gq.png rename to clickplanet-static/static/countries/png100px/gq.png diff --git a/clickplanet-webapp/public/static/countries/png100px/gr.png b/clickplanet-static/static/countries/png100px/gr.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/gr.png rename to clickplanet-static/static/countries/png100px/gr.png diff --git a/clickplanet-webapp/public/static/countries/png100px/gs.png b/clickplanet-static/static/countries/png100px/gs.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/gs.png rename to clickplanet-static/static/countries/png100px/gs.png diff --git a/clickplanet-webapp/public/static/countries/png100px/gt.png b/clickplanet-static/static/countries/png100px/gt.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/gt.png rename to clickplanet-static/static/countries/png100px/gt.png diff --git a/clickplanet-webapp/public/static/countries/png100px/gu.png b/clickplanet-static/static/countries/png100px/gu.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/gu.png rename to clickplanet-static/static/countries/png100px/gu.png diff --git a/clickplanet-webapp/public/static/countries/png100px/gw.png b/clickplanet-static/static/countries/png100px/gw.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/gw.png rename to clickplanet-static/static/countries/png100px/gw.png diff --git a/clickplanet-webapp/public/static/countries/png100px/gy.png b/clickplanet-static/static/countries/png100px/gy.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/gy.png rename to clickplanet-static/static/countries/png100px/gy.png diff --git a/clickplanet-webapp/public/static/countries/png100px/hk.png b/clickplanet-static/static/countries/png100px/hk.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/hk.png rename to clickplanet-static/static/countries/png100px/hk.png diff --git a/clickplanet-webapp/public/static/countries/png100px/hm.png b/clickplanet-static/static/countries/png100px/hm.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/hm.png rename to clickplanet-static/static/countries/png100px/hm.png diff --git a/clickplanet-webapp/public/static/countries/png100px/hn.png b/clickplanet-static/static/countries/png100px/hn.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/hn.png rename to clickplanet-static/static/countries/png100px/hn.png diff --git a/clickplanet-webapp/public/static/countries/png100px/hr.png b/clickplanet-static/static/countries/png100px/hr.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/hr.png rename to clickplanet-static/static/countries/png100px/hr.png diff --git a/clickplanet-webapp/public/static/countries/png100px/ht.png b/clickplanet-static/static/countries/png100px/ht.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ht.png rename to clickplanet-static/static/countries/png100px/ht.png diff --git a/clickplanet-webapp/public/static/countries/png100px/hu.png b/clickplanet-static/static/countries/png100px/hu.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/hu.png rename to clickplanet-static/static/countries/png100px/hu.png diff --git a/clickplanet-webapp/public/static/countries/png100px/id.png b/clickplanet-static/static/countries/png100px/id.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/id.png rename to clickplanet-static/static/countries/png100px/id.png diff --git a/clickplanet-webapp/public/static/countries/png100px/ie.png b/clickplanet-static/static/countries/png100px/ie.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ie.png rename to clickplanet-static/static/countries/png100px/ie.png diff --git a/clickplanet-webapp/public/static/countries/png100px/il.png b/clickplanet-static/static/countries/png100px/il.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/il.png rename to clickplanet-static/static/countries/png100px/il.png diff --git a/clickplanet-webapp/public/static/countries/png100px/im.png b/clickplanet-static/static/countries/png100px/im.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/im.png rename to clickplanet-static/static/countries/png100px/im.png diff --git a/clickplanet-webapp/public/static/countries/png100px/in.png b/clickplanet-static/static/countries/png100px/in.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/in.png rename to clickplanet-static/static/countries/png100px/in.png diff --git a/clickplanet-webapp/public/static/countries/png100px/io.png b/clickplanet-static/static/countries/png100px/io.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/io.png rename to clickplanet-static/static/countries/png100px/io.png diff --git a/clickplanet-webapp/public/static/countries/png100px/iq.png b/clickplanet-static/static/countries/png100px/iq.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/iq.png rename to clickplanet-static/static/countries/png100px/iq.png diff --git a/clickplanet-webapp/public/static/countries/png100px/ir.png b/clickplanet-static/static/countries/png100px/ir.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ir.png rename to clickplanet-static/static/countries/png100px/ir.png diff --git a/clickplanet-webapp/public/static/countries/png100px/is.png b/clickplanet-static/static/countries/png100px/is.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/is.png rename to clickplanet-static/static/countries/png100px/is.png diff --git a/clickplanet-webapp/public/static/countries/png100px/it.png b/clickplanet-static/static/countries/png100px/it.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/it.png rename to clickplanet-static/static/countries/png100px/it.png diff --git a/clickplanet-webapp/public/static/countries/png100px/je.png b/clickplanet-static/static/countries/png100px/je.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/je.png rename to clickplanet-static/static/countries/png100px/je.png diff --git a/clickplanet-webapp/public/static/countries/png100px/jm.png b/clickplanet-static/static/countries/png100px/jm.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/jm.png rename to clickplanet-static/static/countries/png100px/jm.png diff --git a/clickplanet-webapp/public/static/countries/png100px/jo.png b/clickplanet-static/static/countries/png100px/jo.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/jo.png rename to clickplanet-static/static/countries/png100px/jo.png diff --git a/clickplanet-webapp/public/static/countries/png100px/jp.png b/clickplanet-static/static/countries/png100px/jp.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/jp.png rename to clickplanet-static/static/countries/png100px/jp.png diff --git a/clickplanet-webapp/public/static/countries/png100px/ke.png b/clickplanet-static/static/countries/png100px/ke.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ke.png rename to clickplanet-static/static/countries/png100px/ke.png diff --git a/clickplanet-webapp/public/static/countries/png100px/kg.png b/clickplanet-static/static/countries/png100px/kg.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/kg.png rename to clickplanet-static/static/countries/png100px/kg.png diff --git a/clickplanet-webapp/public/static/countries/png100px/kh.png b/clickplanet-static/static/countries/png100px/kh.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/kh.png rename to clickplanet-static/static/countries/png100px/kh.png diff --git a/clickplanet-webapp/public/static/countries/png100px/ki.png b/clickplanet-static/static/countries/png100px/ki.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ki.png rename to clickplanet-static/static/countries/png100px/ki.png diff --git a/clickplanet-webapp/public/static/countries/png100px/km.png b/clickplanet-static/static/countries/png100px/km.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/km.png rename to clickplanet-static/static/countries/png100px/km.png diff --git a/clickplanet-webapp/public/static/countries/png100px/kn.png b/clickplanet-static/static/countries/png100px/kn.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/kn.png rename to clickplanet-static/static/countries/png100px/kn.png diff --git a/clickplanet-webapp/public/static/countries/png100px/kp.png b/clickplanet-static/static/countries/png100px/kp.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/kp.png rename to clickplanet-static/static/countries/png100px/kp.png diff --git a/clickplanet-webapp/public/static/countries/png100px/kr.png b/clickplanet-static/static/countries/png100px/kr.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/kr.png rename to clickplanet-static/static/countries/png100px/kr.png diff --git a/clickplanet-webapp/public/static/countries/png100px/kw.png b/clickplanet-static/static/countries/png100px/kw.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/kw.png rename to clickplanet-static/static/countries/png100px/kw.png diff --git a/clickplanet-webapp/public/static/countries/png100px/ky.png b/clickplanet-static/static/countries/png100px/ky.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ky.png rename to clickplanet-static/static/countries/png100px/ky.png diff --git a/clickplanet-webapp/public/static/countries/png100px/kz.png b/clickplanet-static/static/countries/png100px/kz.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/kz.png rename to clickplanet-static/static/countries/png100px/kz.png diff --git a/clickplanet-webapp/public/static/countries/png100px/la.png b/clickplanet-static/static/countries/png100px/la.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/la.png rename to clickplanet-static/static/countries/png100px/la.png diff --git a/clickplanet-webapp/public/static/countries/png100px/lb.png b/clickplanet-static/static/countries/png100px/lb.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/lb.png rename to clickplanet-static/static/countries/png100px/lb.png diff --git a/clickplanet-webapp/public/static/countries/png100px/lc.png b/clickplanet-static/static/countries/png100px/lc.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/lc.png rename to clickplanet-static/static/countries/png100px/lc.png diff --git a/clickplanet-webapp/public/static/countries/png100px/li.png b/clickplanet-static/static/countries/png100px/li.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/li.png rename to clickplanet-static/static/countries/png100px/li.png diff --git a/clickplanet-webapp/public/static/countries/png100px/lk.png b/clickplanet-static/static/countries/png100px/lk.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/lk.png rename to clickplanet-static/static/countries/png100px/lk.png diff --git a/clickplanet-webapp/public/static/countries/png100px/lr.png b/clickplanet-static/static/countries/png100px/lr.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/lr.png rename to clickplanet-static/static/countries/png100px/lr.png diff --git a/clickplanet-webapp/public/static/countries/png100px/ls.png b/clickplanet-static/static/countries/png100px/ls.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ls.png rename to clickplanet-static/static/countries/png100px/ls.png diff --git a/clickplanet-webapp/public/static/countries/png100px/lt.png b/clickplanet-static/static/countries/png100px/lt.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/lt.png rename to clickplanet-static/static/countries/png100px/lt.png diff --git a/clickplanet-webapp/public/static/countries/png100px/lu.png b/clickplanet-static/static/countries/png100px/lu.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/lu.png rename to clickplanet-static/static/countries/png100px/lu.png diff --git a/clickplanet-webapp/public/static/countries/png100px/lv.png b/clickplanet-static/static/countries/png100px/lv.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/lv.png rename to clickplanet-static/static/countries/png100px/lv.png diff --git a/clickplanet-webapp/public/static/countries/png100px/ly.png b/clickplanet-static/static/countries/png100px/ly.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ly.png rename to clickplanet-static/static/countries/png100px/ly.png diff --git a/clickplanet-webapp/public/static/countries/png100px/ma.png b/clickplanet-static/static/countries/png100px/ma.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ma.png rename to clickplanet-static/static/countries/png100px/ma.png diff --git a/clickplanet-webapp/public/static/countries/png100px/mc.png b/clickplanet-static/static/countries/png100px/mc.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/mc.png rename to clickplanet-static/static/countries/png100px/mc.png diff --git a/clickplanet-webapp/public/static/countries/png100px/md.png b/clickplanet-static/static/countries/png100px/md.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/md.png rename to clickplanet-static/static/countries/png100px/md.png diff --git a/clickplanet-webapp/public/static/countries/png100px/me.png b/clickplanet-static/static/countries/png100px/me.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/me.png rename to clickplanet-static/static/countries/png100px/me.png diff --git a/clickplanet-webapp/public/static/countries/png100px/mf.png b/clickplanet-static/static/countries/png100px/mf.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/mf.png rename to clickplanet-static/static/countries/png100px/mf.png diff --git a/clickplanet-webapp/public/static/countries/png100px/mg.png b/clickplanet-static/static/countries/png100px/mg.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/mg.png rename to clickplanet-static/static/countries/png100px/mg.png diff --git a/clickplanet-webapp/public/static/countries/png100px/mh.png b/clickplanet-static/static/countries/png100px/mh.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/mh.png rename to clickplanet-static/static/countries/png100px/mh.png diff --git a/clickplanet-webapp/public/static/countries/png100px/mk.png b/clickplanet-static/static/countries/png100px/mk.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/mk.png rename to clickplanet-static/static/countries/png100px/mk.png diff --git a/clickplanet-webapp/public/static/countries/png100px/ml.png b/clickplanet-static/static/countries/png100px/ml.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ml.png rename to clickplanet-static/static/countries/png100px/ml.png diff --git a/clickplanet-webapp/public/static/countries/png100px/mm.png b/clickplanet-static/static/countries/png100px/mm.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/mm.png rename to clickplanet-static/static/countries/png100px/mm.png diff --git a/clickplanet-webapp/public/static/countries/png100px/mn.png b/clickplanet-static/static/countries/png100px/mn.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/mn.png rename to clickplanet-static/static/countries/png100px/mn.png diff --git a/clickplanet-webapp/public/static/countries/png100px/mo.png b/clickplanet-static/static/countries/png100px/mo.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/mo.png rename to clickplanet-static/static/countries/png100px/mo.png diff --git a/clickplanet-webapp/public/static/countries/png100px/mp.png b/clickplanet-static/static/countries/png100px/mp.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/mp.png rename to clickplanet-static/static/countries/png100px/mp.png diff --git a/clickplanet-webapp/public/static/countries/png100px/mq.png b/clickplanet-static/static/countries/png100px/mq.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/mq.png rename to clickplanet-static/static/countries/png100px/mq.png diff --git a/clickplanet-webapp/public/static/countries/png100px/mr.png b/clickplanet-static/static/countries/png100px/mr.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/mr.png rename to clickplanet-static/static/countries/png100px/mr.png diff --git a/clickplanet-webapp/public/static/countries/png100px/ms.png b/clickplanet-static/static/countries/png100px/ms.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ms.png rename to clickplanet-static/static/countries/png100px/ms.png diff --git a/clickplanet-webapp/public/static/countries/png100px/mt.png b/clickplanet-static/static/countries/png100px/mt.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/mt.png rename to clickplanet-static/static/countries/png100px/mt.png diff --git a/clickplanet-webapp/public/static/countries/png100px/mu.png b/clickplanet-static/static/countries/png100px/mu.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/mu.png rename to clickplanet-static/static/countries/png100px/mu.png diff --git a/clickplanet-webapp/public/static/countries/png100px/mv.png b/clickplanet-static/static/countries/png100px/mv.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/mv.png rename to clickplanet-static/static/countries/png100px/mv.png diff --git a/clickplanet-webapp/public/static/countries/png100px/mw.png b/clickplanet-static/static/countries/png100px/mw.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/mw.png rename to clickplanet-static/static/countries/png100px/mw.png diff --git a/clickplanet-webapp/public/static/countries/png100px/mx.png b/clickplanet-static/static/countries/png100px/mx.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/mx.png rename to clickplanet-static/static/countries/png100px/mx.png diff --git a/clickplanet-webapp/public/static/countries/png100px/my.png b/clickplanet-static/static/countries/png100px/my.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/my.png rename to clickplanet-static/static/countries/png100px/my.png diff --git a/clickplanet-webapp/public/static/countries/png100px/mz.png b/clickplanet-static/static/countries/png100px/mz.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/mz.png rename to clickplanet-static/static/countries/png100px/mz.png diff --git a/clickplanet-webapp/public/static/countries/png100px/na.png b/clickplanet-static/static/countries/png100px/na.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/na.png rename to clickplanet-static/static/countries/png100px/na.png diff --git a/clickplanet-webapp/public/static/countries/png100px/nc.png b/clickplanet-static/static/countries/png100px/nc.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/nc.png rename to clickplanet-static/static/countries/png100px/nc.png diff --git a/clickplanet-webapp/public/static/countries/png100px/ne.png b/clickplanet-static/static/countries/png100px/ne.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ne.png rename to clickplanet-static/static/countries/png100px/ne.png diff --git a/clickplanet-webapp/public/static/countries/png100px/nf.png b/clickplanet-static/static/countries/png100px/nf.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/nf.png rename to clickplanet-static/static/countries/png100px/nf.png diff --git a/clickplanet-webapp/public/static/countries/png100px/ng.png b/clickplanet-static/static/countries/png100px/ng.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ng.png rename to clickplanet-static/static/countries/png100px/ng.png diff --git a/clickplanet-webapp/public/static/countries/png100px/ni.png b/clickplanet-static/static/countries/png100px/ni.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ni.png rename to clickplanet-static/static/countries/png100px/ni.png diff --git a/clickplanet-webapp/public/static/countries/png100px/nl.png b/clickplanet-static/static/countries/png100px/nl.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/nl.png rename to clickplanet-static/static/countries/png100px/nl.png diff --git a/clickplanet-webapp/public/static/countries/png100px/no.png b/clickplanet-static/static/countries/png100px/no.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/no.png rename to clickplanet-static/static/countries/png100px/no.png diff --git a/clickplanet-webapp/public/static/countries/png100px/np.png b/clickplanet-static/static/countries/png100px/np.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/np.png rename to clickplanet-static/static/countries/png100px/np.png diff --git a/clickplanet-webapp/public/static/countries/png100px/nr.png b/clickplanet-static/static/countries/png100px/nr.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/nr.png rename to clickplanet-static/static/countries/png100px/nr.png diff --git a/clickplanet-webapp/public/static/countries/png100px/nu.png b/clickplanet-static/static/countries/png100px/nu.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/nu.png rename to clickplanet-static/static/countries/png100px/nu.png diff --git a/clickplanet-webapp/public/static/countries/png100px/nz.png b/clickplanet-static/static/countries/png100px/nz.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/nz.png rename to clickplanet-static/static/countries/png100px/nz.png diff --git a/clickplanet-webapp/public/static/countries/png100px/om.png b/clickplanet-static/static/countries/png100px/om.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/om.png rename to clickplanet-static/static/countries/png100px/om.png diff --git a/clickplanet-webapp/public/static/countries/png100px/pa.png b/clickplanet-static/static/countries/png100px/pa.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/pa.png rename to clickplanet-static/static/countries/png100px/pa.png diff --git a/clickplanet-webapp/public/static/countries/png100px/pe.png b/clickplanet-static/static/countries/png100px/pe.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/pe.png rename to clickplanet-static/static/countries/png100px/pe.png diff --git a/clickplanet-webapp/public/static/countries/png100px/pf.png b/clickplanet-static/static/countries/png100px/pf.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/pf.png rename to clickplanet-static/static/countries/png100px/pf.png diff --git a/clickplanet-webapp/public/static/countries/png100px/pg.png b/clickplanet-static/static/countries/png100px/pg.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/pg.png rename to clickplanet-static/static/countries/png100px/pg.png diff --git a/clickplanet-webapp/public/static/countries/png100px/ph.png b/clickplanet-static/static/countries/png100px/ph.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ph.png rename to clickplanet-static/static/countries/png100px/ph.png diff --git a/clickplanet-webapp/public/static/countries/png100px/pk.png b/clickplanet-static/static/countries/png100px/pk.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/pk.png rename to clickplanet-static/static/countries/png100px/pk.png diff --git a/clickplanet-webapp/public/static/countries/png100px/pl.png b/clickplanet-static/static/countries/png100px/pl.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/pl.png rename to clickplanet-static/static/countries/png100px/pl.png diff --git a/clickplanet-webapp/public/static/countries/png100px/pm.png b/clickplanet-static/static/countries/png100px/pm.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/pm.png rename to clickplanet-static/static/countries/png100px/pm.png diff --git a/clickplanet-webapp/public/static/countries/png100px/pn.png b/clickplanet-static/static/countries/png100px/pn.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/pn.png rename to clickplanet-static/static/countries/png100px/pn.png diff --git a/clickplanet-webapp/public/static/countries/png100px/pr.png b/clickplanet-static/static/countries/png100px/pr.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/pr.png rename to clickplanet-static/static/countries/png100px/pr.png diff --git a/clickplanet-webapp/public/static/countries/png100px/ps.png b/clickplanet-static/static/countries/png100px/ps.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ps.png rename to clickplanet-static/static/countries/png100px/ps.png diff --git a/clickplanet-webapp/public/static/countries/png100px/pt.png b/clickplanet-static/static/countries/png100px/pt.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/pt.png rename to clickplanet-static/static/countries/png100px/pt.png diff --git a/clickplanet-webapp/public/static/countries/png100px/pw.png b/clickplanet-static/static/countries/png100px/pw.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/pw.png rename to clickplanet-static/static/countries/png100px/pw.png diff --git a/clickplanet-webapp/public/static/countries/png100px/py.png b/clickplanet-static/static/countries/png100px/py.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/py.png rename to clickplanet-static/static/countries/png100px/py.png diff --git a/clickplanet-webapp/public/static/countries/png100px/qa.png b/clickplanet-static/static/countries/png100px/qa.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/qa.png rename to clickplanet-static/static/countries/png100px/qa.png diff --git a/clickplanet-webapp/public/static/countries/png100px/re.png b/clickplanet-static/static/countries/png100px/re.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/re.png rename to clickplanet-static/static/countries/png100px/re.png diff --git a/clickplanet-webapp/public/static/countries/png100px/ro.png b/clickplanet-static/static/countries/png100px/ro.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ro.png rename to clickplanet-static/static/countries/png100px/ro.png diff --git a/clickplanet-webapp/public/static/countries/png100px/rs.png b/clickplanet-static/static/countries/png100px/rs.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/rs.png rename to clickplanet-static/static/countries/png100px/rs.png diff --git a/clickplanet-webapp/public/static/countries/png100px/ru.png b/clickplanet-static/static/countries/png100px/ru.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ru.png rename to clickplanet-static/static/countries/png100px/ru.png diff --git a/clickplanet-webapp/public/static/countries/png100px/rw.png b/clickplanet-static/static/countries/png100px/rw.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/rw.png rename to clickplanet-static/static/countries/png100px/rw.png diff --git a/clickplanet-webapp/public/static/countries/png100px/sa.png b/clickplanet-static/static/countries/png100px/sa.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/sa.png rename to clickplanet-static/static/countries/png100px/sa.png diff --git a/clickplanet-webapp/public/static/countries/png100px/sb.png b/clickplanet-static/static/countries/png100px/sb.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/sb.png rename to clickplanet-static/static/countries/png100px/sb.png diff --git a/clickplanet-webapp/public/static/countries/png100px/sc.png b/clickplanet-static/static/countries/png100px/sc.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/sc.png rename to clickplanet-static/static/countries/png100px/sc.png diff --git a/clickplanet-webapp/public/static/countries/png100px/sd.png b/clickplanet-static/static/countries/png100px/sd.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/sd.png rename to clickplanet-static/static/countries/png100px/sd.png diff --git a/clickplanet-webapp/public/static/countries/png100px/se.png b/clickplanet-static/static/countries/png100px/se.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/se.png rename to clickplanet-static/static/countries/png100px/se.png diff --git a/clickplanet-webapp/public/static/countries/png100px/sg.png b/clickplanet-static/static/countries/png100px/sg.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/sg.png rename to clickplanet-static/static/countries/png100px/sg.png diff --git a/clickplanet-webapp/public/static/countries/png100px/sh.png b/clickplanet-static/static/countries/png100px/sh.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/sh.png rename to clickplanet-static/static/countries/png100px/sh.png diff --git a/clickplanet-webapp/public/static/countries/png100px/si.png b/clickplanet-static/static/countries/png100px/si.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/si.png rename to clickplanet-static/static/countries/png100px/si.png diff --git a/clickplanet-webapp/public/static/countries/png100px/sj.png b/clickplanet-static/static/countries/png100px/sj.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/sj.png rename to clickplanet-static/static/countries/png100px/sj.png diff --git a/clickplanet-webapp/public/static/countries/png100px/sk.png b/clickplanet-static/static/countries/png100px/sk.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/sk.png rename to clickplanet-static/static/countries/png100px/sk.png diff --git a/clickplanet-webapp/public/static/countries/png100px/sl.png b/clickplanet-static/static/countries/png100px/sl.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/sl.png rename to clickplanet-static/static/countries/png100px/sl.png diff --git a/clickplanet-webapp/public/static/countries/png100px/sm.png b/clickplanet-static/static/countries/png100px/sm.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/sm.png rename to clickplanet-static/static/countries/png100px/sm.png diff --git a/clickplanet-webapp/public/static/countries/png100px/sn.png b/clickplanet-static/static/countries/png100px/sn.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/sn.png rename to clickplanet-static/static/countries/png100px/sn.png diff --git a/clickplanet-webapp/public/static/countries/png100px/so.png b/clickplanet-static/static/countries/png100px/so.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/so.png rename to clickplanet-static/static/countries/png100px/so.png diff --git a/clickplanet-webapp/public/static/countries/png100px/sr.png b/clickplanet-static/static/countries/png100px/sr.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/sr.png rename to clickplanet-static/static/countries/png100px/sr.png diff --git a/clickplanet-webapp/public/static/countries/png100px/ss.png b/clickplanet-static/static/countries/png100px/ss.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ss.png rename to clickplanet-static/static/countries/png100px/ss.png diff --git a/clickplanet-webapp/public/static/countries/png100px/st.png b/clickplanet-static/static/countries/png100px/st.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/st.png rename to clickplanet-static/static/countries/png100px/st.png diff --git a/clickplanet-webapp/public/static/countries/png100px/sv.png b/clickplanet-static/static/countries/png100px/sv.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/sv.png rename to clickplanet-static/static/countries/png100px/sv.png diff --git a/clickplanet-webapp/public/static/countries/png100px/sx.png b/clickplanet-static/static/countries/png100px/sx.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/sx.png rename to clickplanet-static/static/countries/png100px/sx.png diff --git a/clickplanet-webapp/public/static/countries/png100px/sy.png b/clickplanet-static/static/countries/png100px/sy.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/sy.png rename to clickplanet-static/static/countries/png100px/sy.png diff --git a/clickplanet-webapp/public/static/countries/png100px/sz.png b/clickplanet-static/static/countries/png100px/sz.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/sz.png rename to clickplanet-static/static/countries/png100px/sz.png diff --git a/clickplanet-webapp/public/static/countries/png100px/tc.png b/clickplanet-static/static/countries/png100px/tc.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/tc.png rename to clickplanet-static/static/countries/png100px/tc.png diff --git a/clickplanet-webapp/public/static/countries/png100px/td.png b/clickplanet-static/static/countries/png100px/td.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/td.png rename to clickplanet-static/static/countries/png100px/td.png diff --git a/clickplanet-webapp/public/static/countries/png100px/tf.png b/clickplanet-static/static/countries/png100px/tf.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/tf.png rename to clickplanet-static/static/countries/png100px/tf.png diff --git a/clickplanet-webapp/public/static/countries/png100px/tg.png b/clickplanet-static/static/countries/png100px/tg.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/tg.png rename to clickplanet-static/static/countries/png100px/tg.png diff --git a/clickplanet-webapp/public/static/countries/png100px/th.png b/clickplanet-static/static/countries/png100px/th.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/th.png rename to clickplanet-static/static/countries/png100px/th.png diff --git a/clickplanet-webapp/public/static/countries/png100px/tj.png b/clickplanet-static/static/countries/png100px/tj.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/tj.png rename to clickplanet-static/static/countries/png100px/tj.png diff --git a/clickplanet-webapp/public/static/countries/png100px/tk.png b/clickplanet-static/static/countries/png100px/tk.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/tk.png rename to clickplanet-static/static/countries/png100px/tk.png diff --git a/clickplanet-webapp/public/static/countries/png100px/tl.png b/clickplanet-static/static/countries/png100px/tl.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/tl.png rename to clickplanet-static/static/countries/png100px/tl.png diff --git a/clickplanet-webapp/public/static/countries/png100px/tm.png b/clickplanet-static/static/countries/png100px/tm.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/tm.png rename to clickplanet-static/static/countries/png100px/tm.png diff --git a/clickplanet-webapp/public/static/countries/png100px/tn.png b/clickplanet-static/static/countries/png100px/tn.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/tn.png rename to clickplanet-static/static/countries/png100px/tn.png diff --git a/clickplanet-webapp/public/static/countries/png100px/to.png b/clickplanet-static/static/countries/png100px/to.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/to.png rename to clickplanet-static/static/countries/png100px/to.png diff --git a/clickplanet-webapp/public/static/countries/png100px/tr.png b/clickplanet-static/static/countries/png100px/tr.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/tr.png rename to clickplanet-static/static/countries/png100px/tr.png diff --git a/clickplanet-webapp/public/static/countries/png100px/tt.png b/clickplanet-static/static/countries/png100px/tt.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/tt.png rename to clickplanet-static/static/countries/png100px/tt.png diff --git a/clickplanet-webapp/public/static/countries/png100px/tv.png b/clickplanet-static/static/countries/png100px/tv.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/tv.png rename to clickplanet-static/static/countries/png100px/tv.png diff --git a/clickplanet-webapp/public/static/countries/png100px/tw.png b/clickplanet-static/static/countries/png100px/tw.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/tw.png rename to clickplanet-static/static/countries/png100px/tw.png diff --git a/clickplanet-webapp/public/static/countries/png100px/tz.png b/clickplanet-static/static/countries/png100px/tz.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/tz.png rename to clickplanet-static/static/countries/png100px/tz.png diff --git a/clickplanet-webapp/public/static/countries/png100px/ua.png b/clickplanet-static/static/countries/png100px/ua.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ua.png rename to clickplanet-static/static/countries/png100px/ua.png diff --git a/clickplanet-webapp/public/static/countries/png100px/ug.png b/clickplanet-static/static/countries/png100px/ug.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ug.png rename to clickplanet-static/static/countries/png100px/ug.png diff --git a/clickplanet-webapp/public/static/countries/png100px/um.png b/clickplanet-static/static/countries/png100px/um.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/um.png rename to clickplanet-static/static/countries/png100px/um.png diff --git a/clickplanet-webapp/public/static/countries/png100px/us.png b/clickplanet-static/static/countries/png100px/us.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/us.png rename to clickplanet-static/static/countries/png100px/us.png diff --git a/clickplanet-webapp/public/static/countries/png100px/uy.png b/clickplanet-static/static/countries/png100px/uy.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/uy.png rename to clickplanet-static/static/countries/png100px/uy.png diff --git a/clickplanet-webapp/public/static/countries/png100px/uz.png b/clickplanet-static/static/countries/png100px/uz.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/uz.png rename to clickplanet-static/static/countries/png100px/uz.png diff --git a/clickplanet-webapp/public/static/countries/png100px/va.png b/clickplanet-static/static/countries/png100px/va.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/va.png rename to clickplanet-static/static/countries/png100px/va.png diff --git a/clickplanet-webapp/public/static/countries/png100px/vc.png b/clickplanet-static/static/countries/png100px/vc.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/vc.png rename to clickplanet-static/static/countries/png100px/vc.png diff --git a/clickplanet-webapp/public/static/countries/png100px/ve.png b/clickplanet-static/static/countries/png100px/ve.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ve.png rename to clickplanet-static/static/countries/png100px/ve.png diff --git a/clickplanet-webapp/public/static/countries/png100px/vg.png b/clickplanet-static/static/countries/png100px/vg.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/vg.png rename to clickplanet-static/static/countries/png100px/vg.png diff --git a/clickplanet-webapp/public/static/countries/png100px/vi.png b/clickplanet-static/static/countries/png100px/vi.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/vi.png rename to clickplanet-static/static/countries/png100px/vi.png diff --git a/clickplanet-webapp/public/static/countries/png100px/vn.png b/clickplanet-static/static/countries/png100px/vn.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/vn.png rename to clickplanet-static/static/countries/png100px/vn.png diff --git a/clickplanet-webapp/public/static/countries/png100px/vu.png b/clickplanet-static/static/countries/png100px/vu.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/vu.png rename to clickplanet-static/static/countries/png100px/vu.png diff --git a/clickplanet-webapp/public/static/countries/png100px/wf.png b/clickplanet-static/static/countries/png100px/wf.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/wf.png rename to clickplanet-static/static/countries/png100px/wf.png diff --git a/clickplanet-webapp/public/static/countries/png100px/ws.png b/clickplanet-static/static/countries/png100px/ws.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ws.png rename to clickplanet-static/static/countries/png100px/ws.png diff --git a/clickplanet-webapp/public/static/countries/png100px/xb.png b/clickplanet-static/static/countries/png100px/xb.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/xb.png rename to clickplanet-static/static/countries/png100px/xb.png diff --git a/clickplanet-webapp/public/static/countries/png100px/xk.png b/clickplanet-static/static/countries/png100px/xk.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/xk.png rename to clickplanet-static/static/countries/png100px/xk.png diff --git a/clickplanet-webapp/public/static/countries/png100px/ye.png b/clickplanet-static/static/countries/png100px/ye.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/ye.png rename to clickplanet-static/static/countries/png100px/ye.png diff --git a/clickplanet-webapp/public/static/countries/png100px/yt.png b/clickplanet-static/static/countries/png100px/yt.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/yt.png rename to clickplanet-static/static/countries/png100px/yt.png diff --git a/clickplanet-webapp/public/static/countries/png100px/za.png b/clickplanet-static/static/countries/png100px/za.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/za.png rename to clickplanet-static/static/countries/png100px/za.png diff --git a/clickplanet-webapp/public/static/countries/png100px/zm.png b/clickplanet-static/static/countries/png100px/zm.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/zm.png rename to clickplanet-static/static/countries/png100px/zm.png diff --git a/clickplanet-webapp/public/static/countries/png100px/zw.png b/clickplanet-static/static/countries/png100px/zw.png similarity index 100% rename from clickplanet-webapp/public/static/countries/png100px/zw.png rename to clickplanet-static/static/countries/png100px/zw.png diff --git a/clickplanet-webapp/public/static/countries/svg/ad.svg b/clickplanet-static/static/countries/svg/ad.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ad.svg rename to clickplanet-static/static/countries/svg/ad.svg diff --git a/clickplanet-webapp/public/static/countries/svg/ae.svg b/clickplanet-static/static/countries/svg/ae.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ae.svg rename to clickplanet-static/static/countries/svg/ae.svg diff --git a/clickplanet-webapp/public/static/countries/svg/af.svg b/clickplanet-static/static/countries/svg/af.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/af.svg rename to clickplanet-static/static/countries/svg/af.svg diff --git a/clickplanet-webapp/public/static/countries/svg/ag.svg b/clickplanet-static/static/countries/svg/ag.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ag.svg rename to clickplanet-static/static/countries/svg/ag.svg diff --git a/clickplanet-webapp/public/static/countries/svg/ai.svg b/clickplanet-static/static/countries/svg/ai.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ai.svg rename to clickplanet-static/static/countries/svg/ai.svg diff --git a/clickplanet-webapp/public/static/countries/svg/al.svg b/clickplanet-static/static/countries/svg/al.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/al.svg rename to clickplanet-static/static/countries/svg/al.svg diff --git a/clickplanet-webapp/public/static/countries/svg/am.svg b/clickplanet-static/static/countries/svg/am.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/am.svg rename to clickplanet-static/static/countries/svg/am.svg diff --git a/clickplanet-webapp/public/static/countries/svg/ao.svg b/clickplanet-static/static/countries/svg/ao.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ao.svg rename to clickplanet-static/static/countries/svg/ao.svg diff --git a/clickplanet-webapp/public/static/countries/svg/aq.svg b/clickplanet-static/static/countries/svg/aq.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/aq.svg rename to clickplanet-static/static/countries/svg/aq.svg diff --git a/clickplanet-webapp/public/static/countries/svg/ar.svg b/clickplanet-static/static/countries/svg/ar.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ar.svg rename to clickplanet-static/static/countries/svg/ar.svg diff --git a/clickplanet-webapp/public/static/countries/svg/as.svg b/clickplanet-static/static/countries/svg/as.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/as.svg rename to clickplanet-static/static/countries/svg/as.svg diff --git a/clickplanet-webapp/public/static/countries/svg/at.svg b/clickplanet-static/static/countries/svg/at.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/at.svg rename to clickplanet-static/static/countries/svg/at.svg diff --git a/clickplanet-webapp/public/static/countries/svg/au.svg b/clickplanet-static/static/countries/svg/au.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/au.svg rename to clickplanet-static/static/countries/svg/au.svg diff --git a/clickplanet-webapp/public/static/countries/svg/aw.svg b/clickplanet-static/static/countries/svg/aw.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/aw.svg rename to clickplanet-static/static/countries/svg/aw.svg diff --git a/clickplanet-webapp/public/static/countries/svg/ax.svg b/clickplanet-static/static/countries/svg/ax.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ax.svg rename to clickplanet-static/static/countries/svg/ax.svg diff --git a/clickplanet-webapp/public/static/countries/svg/az.svg b/clickplanet-static/static/countries/svg/az.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/az.svg rename to clickplanet-static/static/countries/svg/az.svg diff --git a/clickplanet-webapp/public/static/countries/svg/ba.svg b/clickplanet-static/static/countries/svg/ba.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ba.svg rename to clickplanet-static/static/countries/svg/ba.svg diff --git a/clickplanet-webapp/public/static/countries/svg/bb.svg b/clickplanet-static/static/countries/svg/bb.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/bb.svg rename to clickplanet-static/static/countries/svg/bb.svg diff --git a/clickplanet-webapp/public/static/countries/svg/bd.svg b/clickplanet-static/static/countries/svg/bd.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/bd.svg rename to clickplanet-static/static/countries/svg/bd.svg diff --git a/clickplanet-webapp/public/static/countries/svg/be.svg b/clickplanet-static/static/countries/svg/be.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/be.svg rename to clickplanet-static/static/countries/svg/be.svg diff --git a/clickplanet-webapp/public/static/countries/svg/bf.svg b/clickplanet-static/static/countries/svg/bf.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/bf.svg rename to clickplanet-static/static/countries/svg/bf.svg diff --git a/clickplanet-webapp/public/static/countries/svg/bg.svg b/clickplanet-static/static/countries/svg/bg.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/bg.svg rename to clickplanet-static/static/countries/svg/bg.svg diff --git a/clickplanet-webapp/public/static/countries/svg/bh.svg b/clickplanet-static/static/countries/svg/bh.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/bh.svg rename to clickplanet-static/static/countries/svg/bh.svg diff --git a/clickplanet-webapp/public/static/countries/svg/bi.svg b/clickplanet-static/static/countries/svg/bi.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/bi.svg rename to clickplanet-static/static/countries/svg/bi.svg diff --git a/clickplanet-webapp/public/static/countries/svg/bj.svg b/clickplanet-static/static/countries/svg/bj.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/bj.svg rename to clickplanet-static/static/countries/svg/bj.svg diff --git a/clickplanet-webapp/public/static/countries/svg/bl.svg b/clickplanet-static/static/countries/svg/bl.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/bl.svg rename to clickplanet-static/static/countries/svg/bl.svg diff --git a/clickplanet-webapp/public/static/countries/svg/bm.svg b/clickplanet-static/static/countries/svg/bm.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/bm.svg rename to clickplanet-static/static/countries/svg/bm.svg diff --git a/clickplanet-webapp/public/static/countries/svg/bn.svg b/clickplanet-static/static/countries/svg/bn.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/bn.svg rename to clickplanet-static/static/countries/svg/bn.svg diff --git a/clickplanet-webapp/public/static/countries/svg/bo.svg b/clickplanet-static/static/countries/svg/bo.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/bo.svg rename to clickplanet-static/static/countries/svg/bo.svg diff --git a/clickplanet-webapp/public/static/countries/svg/bq.svg b/clickplanet-static/static/countries/svg/bq.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/bq.svg rename to clickplanet-static/static/countries/svg/bq.svg diff --git a/clickplanet-webapp/public/static/countries/svg/br.svg b/clickplanet-static/static/countries/svg/br.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/br.svg rename to clickplanet-static/static/countries/svg/br.svg diff --git a/clickplanet-webapp/public/static/countries/svg/bs.svg b/clickplanet-static/static/countries/svg/bs.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/bs.svg rename to clickplanet-static/static/countries/svg/bs.svg diff --git a/clickplanet-webapp/public/static/countries/svg/bt.svg b/clickplanet-static/static/countries/svg/bt.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/bt.svg rename to clickplanet-static/static/countries/svg/bt.svg diff --git a/clickplanet-webapp/public/static/countries/svg/bv.svg b/clickplanet-static/static/countries/svg/bv.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/bv.svg rename to clickplanet-static/static/countries/svg/bv.svg diff --git a/clickplanet-webapp/public/static/countries/svg/bw.svg b/clickplanet-static/static/countries/svg/bw.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/bw.svg rename to clickplanet-static/static/countries/svg/bw.svg diff --git a/clickplanet-webapp/public/static/countries/svg/by.svg b/clickplanet-static/static/countries/svg/by.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/by.svg rename to clickplanet-static/static/countries/svg/by.svg diff --git a/clickplanet-webapp/public/static/countries/svg/bz.svg b/clickplanet-static/static/countries/svg/bz.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/bz.svg rename to clickplanet-static/static/countries/svg/bz.svg diff --git a/clickplanet-webapp/public/static/countries/svg/ca.svg b/clickplanet-static/static/countries/svg/ca.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ca.svg rename to clickplanet-static/static/countries/svg/ca.svg diff --git a/clickplanet-webapp/public/static/countries/svg/cc.svg b/clickplanet-static/static/countries/svg/cc.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/cc.svg rename to clickplanet-static/static/countries/svg/cc.svg diff --git a/clickplanet-webapp/public/static/countries/svg/cd.svg b/clickplanet-static/static/countries/svg/cd.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/cd.svg rename to clickplanet-static/static/countries/svg/cd.svg diff --git a/clickplanet-webapp/public/static/countries/svg/cf.svg b/clickplanet-static/static/countries/svg/cf.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/cf.svg rename to clickplanet-static/static/countries/svg/cf.svg diff --git a/clickplanet-webapp/public/static/countries/svg/cg.svg b/clickplanet-static/static/countries/svg/cg.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/cg.svg rename to clickplanet-static/static/countries/svg/cg.svg diff --git a/clickplanet-webapp/public/static/countries/svg/ch.svg b/clickplanet-static/static/countries/svg/ch.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ch.svg rename to clickplanet-static/static/countries/svg/ch.svg diff --git a/clickplanet-webapp/public/static/countries/svg/ci.svg b/clickplanet-static/static/countries/svg/ci.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ci.svg rename to clickplanet-static/static/countries/svg/ci.svg diff --git a/clickplanet-webapp/public/static/countries/svg/ck.svg b/clickplanet-static/static/countries/svg/ck.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ck.svg rename to clickplanet-static/static/countries/svg/ck.svg diff --git a/clickplanet-webapp/public/static/countries/svg/cl.svg b/clickplanet-static/static/countries/svg/cl.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/cl.svg rename to clickplanet-static/static/countries/svg/cl.svg diff --git a/clickplanet-webapp/public/static/countries/svg/cm.svg b/clickplanet-static/static/countries/svg/cm.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/cm.svg rename to clickplanet-static/static/countries/svg/cm.svg diff --git a/clickplanet-webapp/public/static/countries/svg/cn.svg b/clickplanet-static/static/countries/svg/cn.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/cn.svg rename to clickplanet-static/static/countries/svg/cn.svg diff --git a/clickplanet-webapp/public/static/countries/svg/co.svg b/clickplanet-static/static/countries/svg/co.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/co.svg rename to clickplanet-static/static/countries/svg/co.svg diff --git a/clickplanet-webapp/public/static/countries/svg/cr.svg b/clickplanet-static/static/countries/svg/cr.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/cr.svg rename to clickplanet-static/static/countries/svg/cr.svg diff --git a/clickplanet-webapp/public/static/countries/svg/cu.svg b/clickplanet-static/static/countries/svg/cu.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/cu.svg rename to clickplanet-static/static/countries/svg/cu.svg diff --git a/clickplanet-webapp/public/static/countries/svg/cv.svg b/clickplanet-static/static/countries/svg/cv.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/cv.svg rename to clickplanet-static/static/countries/svg/cv.svg diff --git a/clickplanet-webapp/public/static/countries/svg/cw.svg b/clickplanet-static/static/countries/svg/cw.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/cw.svg rename to clickplanet-static/static/countries/svg/cw.svg diff --git a/clickplanet-webapp/public/static/countries/svg/cx.svg b/clickplanet-static/static/countries/svg/cx.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/cx.svg rename to clickplanet-static/static/countries/svg/cx.svg diff --git a/clickplanet-webapp/public/static/countries/svg/cy.svg b/clickplanet-static/static/countries/svg/cy.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/cy.svg rename to clickplanet-static/static/countries/svg/cy.svg diff --git a/clickplanet-webapp/public/static/countries/svg/cz.svg b/clickplanet-static/static/countries/svg/cz.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/cz.svg rename to clickplanet-static/static/countries/svg/cz.svg diff --git a/clickplanet-webapp/public/static/countries/svg/de.svg b/clickplanet-static/static/countries/svg/de.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/de.svg rename to clickplanet-static/static/countries/svg/de.svg diff --git a/clickplanet-webapp/public/static/countries/svg/dj.svg b/clickplanet-static/static/countries/svg/dj.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/dj.svg rename to clickplanet-static/static/countries/svg/dj.svg diff --git a/clickplanet-webapp/public/static/countries/svg/dk.svg b/clickplanet-static/static/countries/svg/dk.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/dk.svg rename to clickplanet-static/static/countries/svg/dk.svg diff --git a/clickplanet-webapp/public/static/countries/svg/dm.svg b/clickplanet-static/static/countries/svg/dm.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/dm.svg rename to clickplanet-static/static/countries/svg/dm.svg diff --git a/clickplanet-webapp/public/static/countries/svg/do.svg b/clickplanet-static/static/countries/svg/do.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/do.svg rename to clickplanet-static/static/countries/svg/do.svg diff --git a/clickplanet-webapp/public/static/countries/svg/dz.svg b/clickplanet-static/static/countries/svg/dz.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/dz.svg rename to clickplanet-static/static/countries/svg/dz.svg diff --git a/clickplanet-webapp/public/static/countries/svg/ec.svg b/clickplanet-static/static/countries/svg/ec.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ec.svg rename to clickplanet-static/static/countries/svg/ec.svg diff --git a/clickplanet-webapp/public/static/countries/svg/ee.svg b/clickplanet-static/static/countries/svg/ee.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ee.svg rename to clickplanet-static/static/countries/svg/ee.svg diff --git a/clickplanet-webapp/public/static/countries/svg/eg.svg b/clickplanet-static/static/countries/svg/eg.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/eg.svg rename to clickplanet-static/static/countries/svg/eg.svg diff --git a/clickplanet-webapp/public/static/countries/svg/eh.svg b/clickplanet-static/static/countries/svg/eh.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/eh.svg rename to clickplanet-static/static/countries/svg/eh.svg diff --git a/clickplanet-webapp/public/static/countries/svg/er.svg b/clickplanet-static/static/countries/svg/er.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/er.svg rename to clickplanet-static/static/countries/svg/er.svg diff --git a/clickplanet-webapp/public/static/countries/svg/es.svg b/clickplanet-static/static/countries/svg/es.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/es.svg rename to clickplanet-static/static/countries/svg/es.svg diff --git a/clickplanet-webapp/public/static/countries/svg/et.svg b/clickplanet-static/static/countries/svg/et.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/et.svg rename to clickplanet-static/static/countries/svg/et.svg diff --git a/clickplanet-webapp/public/static/countries/svg/eu.svg b/clickplanet-static/static/countries/svg/eu.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/eu.svg rename to clickplanet-static/static/countries/svg/eu.svg diff --git a/clickplanet-webapp/public/static/countries/svg/fi.svg b/clickplanet-static/static/countries/svg/fi.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/fi.svg rename to clickplanet-static/static/countries/svg/fi.svg diff --git a/clickplanet-webapp/public/static/countries/svg/fj.svg b/clickplanet-static/static/countries/svg/fj.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/fj.svg rename to clickplanet-static/static/countries/svg/fj.svg diff --git a/clickplanet-webapp/public/static/countries/svg/fk.svg b/clickplanet-static/static/countries/svg/fk.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/fk.svg rename to clickplanet-static/static/countries/svg/fk.svg diff --git a/clickplanet-webapp/public/static/countries/svg/fm.svg b/clickplanet-static/static/countries/svg/fm.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/fm.svg rename to clickplanet-static/static/countries/svg/fm.svg diff --git a/clickplanet-webapp/public/static/countries/svg/fo.svg b/clickplanet-static/static/countries/svg/fo.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/fo.svg rename to clickplanet-static/static/countries/svg/fo.svg diff --git a/clickplanet-webapp/public/static/countries/svg/fr.svg b/clickplanet-static/static/countries/svg/fr.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/fr.svg rename to clickplanet-static/static/countries/svg/fr.svg diff --git a/clickplanet-webapp/public/static/countries/svg/ga.svg b/clickplanet-static/static/countries/svg/ga.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ga.svg rename to clickplanet-static/static/countries/svg/ga.svg diff --git a/clickplanet-webapp/public/static/countries/svg/gb-eng.svg b/clickplanet-static/static/countries/svg/gb-eng.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/gb-eng.svg rename to clickplanet-static/static/countries/svg/gb-eng.svg diff --git a/clickplanet-webapp/public/static/countries/svg/gb-nir.svg b/clickplanet-static/static/countries/svg/gb-nir.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/gb-nir.svg rename to clickplanet-static/static/countries/svg/gb-nir.svg diff --git a/clickplanet-webapp/public/static/countries/svg/gb-sct.svg b/clickplanet-static/static/countries/svg/gb-sct.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/gb-sct.svg rename to clickplanet-static/static/countries/svg/gb-sct.svg diff --git a/clickplanet-webapp/public/static/countries/svg/gb-wls.svg b/clickplanet-static/static/countries/svg/gb-wls.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/gb-wls.svg rename to clickplanet-static/static/countries/svg/gb-wls.svg diff --git a/clickplanet-webapp/public/static/countries/svg/gb.svg b/clickplanet-static/static/countries/svg/gb.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/gb.svg rename to clickplanet-static/static/countries/svg/gb.svg diff --git a/clickplanet-webapp/public/static/countries/svg/gd.svg b/clickplanet-static/static/countries/svg/gd.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/gd.svg rename to clickplanet-static/static/countries/svg/gd.svg diff --git a/clickplanet-webapp/public/static/countries/svg/ge.svg b/clickplanet-static/static/countries/svg/ge.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ge.svg rename to clickplanet-static/static/countries/svg/ge.svg diff --git a/clickplanet-webapp/public/static/countries/svg/gf.svg b/clickplanet-static/static/countries/svg/gf.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/gf.svg rename to clickplanet-static/static/countries/svg/gf.svg diff --git a/clickplanet-webapp/public/static/countries/svg/gg.svg b/clickplanet-static/static/countries/svg/gg.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/gg.svg rename to clickplanet-static/static/countries/svg/gg.svg diff --git a/clickplanet-webapp/public/static/countries/svg/gh.svg b/clickplanet-static/static/countries/svg/gh.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/gh.svg rename to clickplanet-static/static/countries/svg/gh.svg diff --git a/clickplanet-webapp/public/static/countries/svg/gi.svg b/clickplanet-static/static/countries/svg/gi.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/gi.svg rename to clickplanet-static/static/countries/svg/gi.svg diff --git a/clickplanet-webapp/public/static/countries/svg/gl.svg b/clickplanet-static/static/countries/svg/gl.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/gl.svg rename to clickplanet-static/static/countries/svg/gl.svg diff --git a/clickplanet-webapp/public/static/countries/svg/gm.svg b/clickplanet-static/static/countries/svg/gm.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/gm.svg rename to clickplanet-static/static/countries/svg/gm.svg diff --git a/clickplanet-webapp/public/static/countries/svg/gn.svg b/clickplanet-static/static/countries/svg/gn.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/gn.svg rename to clickplanet-static/static/countries/svg/gn.svg diff --git a/clickplanet-webapp/public/static/countries/svg/gp.svg b/clickplanet-static/static/countries/svg/gp.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/gp.svg rename to clickplanet-static/static/countries/svg/gp.svg diff --git a/clickplanet-webapp/public/static/countries/svg/gq.svg b/clickplanet-static/static/countries/svg/gq.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/gq.svg rename to clickplanet-static/static/countries/svg/gq.svg diff --git a/clickplanet-webapp/public/static/countries/svg/gr.svg b/clickplanet-static/static/countries/svg/gr.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/gr.svg rename to clickplanet-static/static/countries/svg/gr.svg diff --git a/clickplanet-webapp/public/static/countries/svg/gs.svg b/clickplanet-static/static/countries/svg/gs.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/gs.svg rename to clickplanet-static/static/countries/svg/gs.svg diff --git a/clickplanet-webapp/public/static/countries/svg/gt.svg b/clickplanet-static/static/countries/svg/gt.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/gt.svg rename to clickplanet-static/static/countries/svg/gt.svg diff --git a/clickplanet-webapp/public/static/countries/svg/gu.svg b/clickplanet-static/static/countries/svg/gu.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/gu.svg rename to clickplanet-static/static/countries/svg/gu.svg diff --git a/clickplanet-webapp/public/static/countries/svg/gw.svg b/clickplanet-static/static/countries/svg/gw.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/gw.svg rename to clickplanet-static/static/countries/svg/gw.svg diff --git a/clickplanet-webapp/public/static/countries/svg/gy.svg b/clickplanet-static/static/countries/svg/gy.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/gy.svg rename to clickplanet-static/static/countries/svg/gy.svg diff --git a/clickplanet-webapp/public/static/countries/svg/hk.svg b/clickplanet-static/static/countries/svg/hk.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/hk.svg rename to clickplanet-static/static/countries/svg/hk.svg diff --git a/clickplanet-webapp/public/static/countries/svg/hm.svg b/clickplanet-static/static/countries/svg/hm.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/hm.svg rename to clickplanet-static/static/countries/svg/hm.svg diff --git a/clickplanet-webapp/public/static/countries/svg/hn.svg b/clickplanet-static/static/countries/svg/hn.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/hn.svg rename to clickplanet-static/static/countries/svg/hn.svg diff --git a/clickplanet-webapp/public/static/countries/svg/hr.svg b/clickplanet-static/static/countries/svg/hr.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/hr.svg rename to clickplanet-static/static/countries/svg/hr.svg diff --git a/clickplanet-webapp/public/static/countries/svg/ht.svg b/clickplanet-static/static/countries/svg/ht.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ht.svg rename to clickplanet-static/static/countries/svg/ht.svg diff --git a/clickplanet-webapp/public/static/countries/svg/hu.svg b/clickplanet-static/static/countries/svg/hu.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/hu.svg rename to clickplanet-static/static/countries/svg/hu.svg diff --git a/clickplanet-webapp/public/static/countries/svg/id.svg b/clickplanet-static/static/countries/svg/id.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/id.svg rename to clickplanet-static/static/countries/svg/id.svg diff --git a/clickplanet-webapp/public/static/countries/svg/ie.svg b/clickplanet-static/static/countries/svg/ie.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ie.svg rename to clickplanet-static/static/countries/svg/ie.svg diff --git a/clickplanet-webapp/public/static/countries/svg/il.svg b/clickplanet-static/static/countries/svg/il.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/il.svg rename to clickplanet-static/static/countries/svg/il.svg diff --git a/clickplanet-webapp/public/static/countries/svg/im.svg b/clickplanet-static/static/countries/svg/im.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/im.svg rename to clickplanet-static/static/countries/svg/im.svg diff --git a/clickplanet-webapp/public/static/countries/svg/in.svg b/clickplanet-static/static/countries/svg/in.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/in.svg rename to clickplanet-static/static/countries/svg/in.svg diff --git a/clickplanet-webapp/public/static/countries/svg/io.svg b/clickplanet-static/static/countries/svg/io.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/io.svg rename to clickplanet-static/static/countries/svg/io.svg diff --git a/clickplanet-webapp/public/static/countries/svg/iq.svg b/clickplanet-static/static/countries/svg/iq.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/iq.svg rename to clickplanet-static/static/countries/svg/iq.svg diff --git a/clickplanet-webapp/public/static/countries/svg/ir.svg b/clickplanet-static/static/countries/svg/ir.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ir.svg rename to clickplanet-static/static/countries/svg/ir.svg diff --git a/clickplanet-webapp/public/static/countries/svg/is.svg b/clickplanet-static/static/countries/svg/is.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/is.svg rename to clickplanet-static/static/countries/svg/is.svg diff --git a/clickplanet-webapp/public/static/countries/svg/it.svg b/clickplanet-static/static/countries/svg/it.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/it.svg rename to clickplanet-static/static/countries/svg/it.svg diff --git a/clickplanet-webapp/public/static/countries/svg/je.svg b/clickplanet-static/static/countries/svg/je.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/je.svg rename to clickplanet-static/static/countries/svg/je.svg diff --git a/clickplanet-webapp/public/static/countries/svg/jm.svg b/clickplanet-static/static/countries/svg/jm.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/jm.svg rename to clickplanet-static/static/countries/svg/jm.svg diff --git a/clickplanet-webapp/public/static/countries/svg/jo.svg b/clickplanet-static/static/countries/svg/jo.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/jo.svg rename to clickplanet-static/static/countries/svg/jo.svg diff --git a/clickplanet-webapp/public/static/countries/svg/jp.svg b/clickplanet-static/static/countries/svg/jp.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/jp.svg rename to clickplanet-static/static/countries/svg/jp.svg diff --git a/clickplanet-webapp/public/static/countries/svg/ke.svg b/clickplanet-static/static/countries/svg/ke.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ke.svg rename to clickplanet-static/static/countries/svg/ke.svg diff --git a/clickplanet-webapp/public/static/countries/svg/kg.svg b/clickplanet-static/static/countries/svg/kg.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/kg.svg rename to clickplanet-static/static/countries/svg/kg.svg diff --git a/clickplanet-webapp/public/static/countries/svg/kh.svg b/clickplanet-static/static/countries/svg/kh.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/kh.svg rename to clickplanet-static/static/countries/svg/kh.svg diff --git a/clickplanet-webapp/public/static/countries/svg/ki.svg b/clickplanet-static/static/countries/svg/ki.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ki.svg rename to clickplanet-static/static/countries/svg/ki.svg diff --git a/clickplanet-webapp/public/static/countries/svg/km.svg b/clickplanet-static/static/countries/svg/km.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/km.svg rename to clickplanet-static/static/countries/svg/km.svg diff --git a/clickplanet-webapp/public/static/countries/svg/kn.svg b/clickplanet-static/static/countries/svg/kn.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/kn.svg rename to clickplanet-static/static/countries/svg/kn.svg diff --git a/clickplanet-webapp/public/static/countries/svg/kp.svg b/clickplanet-static/static/countries/svg/kp.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/kp.svg rename to clickplanet-static/static/countries/svg/kp.svg diff --git a/clickplanet-webapp/public/static/countries/svg/kr.svg b/clickplanet-static/static/countries/svg/kr.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/kr.svg rename to clickplanet-static/static/countries/svg/kr.svg diff --git a/clickplanet-webapp/public/static/countries/svg/kw.svg b/clickplanet-static/static/countries/svg/kw.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/kw.svg rename to clickplanet-static/static/countries/svg/kw.svg diff --git a/clickplanet-webapp/public/static/countries/svg/ky.svg b/clickplanet-static/static/countries/svg/ky.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ky.svg rename to clickplanet-static/static/countries/svg/ky.svg diff --git a/clickplanet-webapp/public/static/countries/svg/kz.svg b/clickplanet-static/static/countries/svg/kz.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/kz.svg rename to clickplanet-static/static/countries/svg/kz.svg diff --git a/clickplanet-webapp/public/static/countries/svg/la.svg b/clickplanet-static/static/countries/svg/la.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/la.svg rename to clickplanet-static/static/countries/svg/la.svg diff --git a/clickplanet-webapp/public/static/countries/svg/lb.svg b/clickplanet-static/static/countries/svg/lb.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/lb.svg rename to clickplanet-static/static/countries/svg/lb.svg diff --git a/clickplanet-webapp/public/static/countries/svg/lc.svg b/clickplanet-static/static/countries/svg/lc.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/lc.svg rename to clickplanet-static/static/countries/svg/lc.svg diff --git a/clickplanet-webapp/public/static/countries/svg/li.svg b/clickplanet-static/static/countries/svg/li.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/li.svg rename to clickplanet-static/static/countries/svg/li.svg diff --git a/clickplanet-webapp/public/static/countries/svg/lk.svg b/clickplanet-static/static/countries/svg/lk.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/lk.svg rename to clickplanet-static/static/countries/svg/lk.svg diff --git a/clickplanet-webapp/public/static/countries/svg/lr.svg b/clickplanet-static/static/countries/svg/lr.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/lr.svg rename to clickplanet-static/static/countries/svg/lr.svg diff --git a/clickplanet-webapp/public/static/countries/svg/ls.svg b/clickplanet-static/static/countries/svg/ls.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ls.svg rename to clickplanet-static/static/countries/svg/ls.svg diff --git a/clickplanet-webapp/public/static/countries/svg/lt.svg b/clickplanet-static/static/countries/svg/lt.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/lt.svg rename to clickplanet-static/static/countries/svg/lt.svg diff --git a/clickplanet-webapp/public/static/countries/svg/lu.svg b/clickplanet-static/static/countries/svg/lu.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/lu.svg rename to clickplanet-static/static/countries/svg/lu.svg diff --git a/clickplanet-webapp/public/static/countries/svg/lv.svg b/clickplanet-static/static/countries/svg/lv.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/lv.svg rename to clickplanet-static/static/countries/svg/lv.svg diff --git a/clickplanet-webapp/public/static/countries/svg/ly.svg b/clickplanet-static/static/countries/svg/ly.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ly.svg rename to clickplanet-static/static/countries/svg/ly.svg diff --git a/clickplanet-webapp/public/static/countries/svg/ma.svg b/clickplanet-static/static/countries/svg/ma.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ma.svg rename to clickplanet-static/static/countries/svg/ma.svg diff --git a/clickplanet-webapp/public/static/countries/svg/mc.svg b/clickplanet-static/static/countries/svg/mc.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/mc.svg rename to clickplanet-static/static/countries/svg/mc.svg diff --git a/clickplanet-webapp/public/static/countries/svg/md.svg b/clickplanet-static/static/countries/svg/md.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/md.svg rename to clickplanet-static/static/countries/svg/md.svg diff --git a/clickplanet-webapp/public/static/countries/svg/me.svg b/clickplanet-static/static/countries/svg/me.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/me.svg rename to clickplanet-static/static/countries/svg/me.svg diff --git a/clickplanet-webapp/public/static/countries/svg/mf.svg b/clickplanet-static/static/countries/svg/mf.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/mf.svg rename to clickplanet-static/static/countries/svg/mf.svg diff --git a/clickplanet-webapp/public/static/countries/svg/mg.svg b/clickplanet-static/static/countries/svg/mg.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/mg.svg rename to clickplanet-static/static/countries/svg/mg.svg diff --git a/clickplanet-webapp/public/static/countries/svg/mh.svg b/clickplanet-static/static/countries/svg/mh.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/mh.svg rename to clickplanet-static/static/countries/svg/mh.svg diff --git a/clickplanet-webapp/public/static/countries/svg/mk.svg b/clickplanet-static/static/countries/svg/mk.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/mk.svg rename to clickplanet-static/static/countries/svg/mk.svg diff --git a/clickplanet-webapp/public/static/countries/svg/ml.svg b/clickplanet-static/static/countries/svg/ml.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ml.svg rename to clickplanet-static/static/countries/svg/ml.svg diff --git a/clickplanet-webapp/public/static/countries/svg/mm.svg b/clickplanet-static/static/countries/svg/mm.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/mm.svg rename to clickplanet-static/static/countries/svg/mm.svg diff --git a/clickplanet-webapp/public/static/countries/svg/mn.svg b/clickplanet-static/static/countries/svg/mn.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/mn.svg rename to clickplanet-static/static/countries/svg/mn.svg diff --git a/clickplanet-webapp/public/static/countries/svg/mo.svg b/clickplanet-static/static/countries/svg/mo.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/mo.svg rename to clickplanet-static/static/countries/svg/mo.svg diff --git a/clickplanet-webapp/public/static/countries/svg/mp.svg b/clickplanet-static/static/countries/svg/mp.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/mp.svg rename to clickplanet-static/static/countries/svg/mp.svg diff --git a/clickplanet-webapp/public/static/countries/svg/mq.svg b/clickplanet-static/static/countries/svg/mq.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/mq.svg rename to clickplanet-static/static/countries/svg/mq.svg diff --git a/clickplanet-webapp/public/static/countries/svg/mr.svg b/clickplanet-static/static/countries/svg/mr.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/mr.svg rename to clickplanet-static/static/countries/svg/mr.svg diff --git a/clickplanet-webapp/public/static/countries/svg/ms.svg b/clickplanet-static/static/countries/svg/ms.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ms.svg rename to clickplanet-static/static/countries/svg/ms.svg diff --git a/clickplanet-webapp/public/static/countries/svg/mt.svg b/clickplanet-static/static/countries/svg/mt.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/mt.svg rename to clickplanet-static/static/countries/svg/mt.svg diff --git a/clickplanet-webapp/public/static/countries/svg/mu.svg b/clickplanet-static/static/countries/svg/mu.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/mu.svg rename to clickplanet-static/static/countries/svg/mu.svg diff --git a/clickplanet-webapp/public/static/countries/svg/mv.svg b/clickplanet-static/static/countries/svg/mv.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/mv.svg rename to clickplanet-static/static/countries/svg/mv.svg diff --git a/clickplanet-webapp/public/static/countries/svg/mw.svg b/clickplanet-static/static/countries/svg/mw.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/mw.svg rename to clickplanet-static/static/countries/svg/mw.svg diff --git a/clickplanet-webapp/public/static/countries/svg/mx.svg b/clickplanet-static/static/countries/svg/mx.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/mx.svg rename to clickplanet-static/static/countries/svg/mx.svg diff --git a/clickplanet-webapp/public/static/countries/svg/my.svg b/clickplanet-static/static/countries/svg/my.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/my.svg rename to clickplanet-static/static/countries/svg/my.svg diff --git a/clickplanet-webapp/public/static/countries/svg/mz.svg b/clickplanet-static/static/countries/svg/mz.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/mz.svg rename to clickplanet-static/static/countries/svg/mz.svg diff --git a/clickplanet-webapp/public/static/countries/svg/na.svg b/clickplanet-static/static/countries/svg/na.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/na.svg rename to clickplanet-static/static/countries/svg/na.svg diff --git a/clickplanet-webapp/public/static/countries/svg/nc.svg b/clickplanet-static/static/countries/svg/nc.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/nc.svg rename to clickplanet-static/static/countries/svg/nc.svg diff --git a/clickplanet-webapp/public/static/countries/svg/ne.svg b/clickplanet-static/static/countries/svg/ne.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ne.svg rename to clickplanet-static/static/countries/svg/ne.svg diff --git a/clickplanet-webapp/public/static/countries/svg/nf.svg b/clickplanet-static/static/countries/svg/nf.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/nf.svg rename to clickplanet-static/static/countries/svg/nf.svg diff --git a/clickplanet-webapp/public/static/countries/svg/ng.svg b/clickplanet-static/static/countries/svg/ng.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ng.svg rename to clickplanet-static/static/countries/svg/ng.svg diff --git a/clickplanet-webapp/public/static/countries/svg/ni.svg b/clickplanet-static/static/countries/svg/ni.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ni.svg rename to clickplanet-static/static/countries/svg/ni.svg diff --git a/clickplanet-webapp/public/static/countries/svg/nl.svg b/clickplanet-static/static/countries/svg/nl.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/nl.svg rename to clickplanet-static/static/countries/svg/nl.svg diff --git a/clickplanet-webapp/public/static/countries/svg/no.svg b/clickplanet-static/static/countries/svg/no.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/no.svg rename to clickplanet-static/static/countries/svg/no.svg diff --git a/clickplanet-webapp/public/static/countries/svg/np.svg b/clickplanet-static/static/countries/svg/np.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/np.svg rename to clickplanet-static/static/countries/svg/np.svg diff --git a/clickplanet-webapp/public/static/countries/svg/nr.svg b/clickplanet-static/static/countries/svg/nr.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/nr.svg rename to clickplanet-static/static/countries/svg/nr.svg diff --git a/clickplanet-webapp/public/static/countries/svg/nu.svg b/clickplanet-static/static/countries/svg/nu.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/nu.svg rename to clickplanet-static/static/countries/svg/nu.svg diff --git a/clickplanet-webapp/public/static/countries/svg/nz.svg b/clickplanet-static/static/countries/svg/nz.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/nz.svg rename to clickplanet-static/static/countries/svg/nz.svg diff --git a/clickplanet-webapp/public/static/countries/svg/om.svg b/clickplanet-static/static/countries/svg/om.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/om.svg rename to clickplanet-static/static/countries/svg/om.svg diff --git a/clickplanet-webapp/public/static/countries/svg/pa.svg b/clickplanet-static/static/countries/svg/pa.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/pa.svg rename to clickplanet-static/static/countries/svg/pa.svg diff --git a/clickplanet-webapp/public/static/countries/svg/pe.svg b/clickplanet-static/static/countries/svg/pe.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/pe.svg rename to clickplanet-static/static/countries/svg/pe.svg diff --git a/clickplanet-webapp/public/static/countries/svg/pf.svg b/clickplanet-static/static/countries/svg/pf.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/pf.svg rename to clickplanet-static/static/countries/svg/pf.svg diff --git a/clickplanet-webapp/public/static/countries/svg/pg.svg b/clickplanet-static/static/countries/svg/pg.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/pg.svg rename to clickplanet-static/static/countries/svg/pg.svg diff --git a/clickplanet-webapp/public/static/countries/svg/ph.svg b/clickplanet-static/static/countries/svg/ph.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ph.svg rename to clickplanet-static/static/countries/svg/ph.svg diff --git a/clickplanet-webapp/public/static/countries/svg/pk.svg b/clickplanet-static/static/countries/svg/pk.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/pk.svg rename to clickplanet-static/static/countries/svg/pk.svg diff --git a/clickplanet-webapp/public/static/countries/svg/pl.svg b/clickplanet-static/static/countries/svg/pl.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/pl.svg rename to clickplanet-static/static/countries/svg/pl.svg diff --git a/clickplanet-webapp/public/static/countries/svg/pm.svg b/clickplanet-static/static/countries/svg/pm.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/pm.svg rename to clickplanet-static/static/countries/svg/pm.svg diff --git a/clickplanet-webapp/public/static/countries/svg/pn.svg b/clickplanet-static/static/countries/svg/pn.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/pn.svg rename to clickplanet-static/static/countries/svg/pn.svg diff --git a/clickplanet-webapp/public/static/countries/svg/pr.svg b/clickplanet-static/static/countries/svg/pr.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/pr.svg rename to clickplanet-static/static/countries/svg/pr.svg diff --git a/clickplanet-webapp/public/static/countries/svg/ps.svg b/clickplanet-static/static/countries/svg/ps.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ps.svg rename to clickplanet-static/static/countries/svg/ps.svg diff --git a/clickplanet-webapp/public/static/countries/svg/pt.svg b/clickplanet-static/static/countries/svg/pt.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/pt.svg rename to clickplanet-static/static/countries/svg/pt.svg diff --git a/clickplanet-webapp/public/static/countries/svg/pw.svg b/clickplanet-static/static/countries/svg/pw.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/pw.svg rename to clickplanet-static/static/countries/svg/pw.svg diff --git a/clickplanet-webapp/public/static/countries/svg/py.svg b/clickplanet-static/static/countries/svg/py.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/py.svg rename to clickplanet-static/static/countries/svg/py.svg diff --git a/clickplanet-webapp/public/static/countries/svg/qa.svg b/clickplanet-static/static/countries/svg/qa.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/qa.svg rename to clickplanet-static/static/countries/svg/qa.svg diff --git a/clickplanet-webapp/public/static/countries/svg/re.svg b/clickplanet-static/static/countries/svg/re.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/re.svg rename to clickplanet-static/static/countries/svg/re.svg diff --git a/clickplanet-webapp/public/static/countries/svg/ro.svg b/clickplanet-static/static/countries/svg/ro.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ro.svg rename to clickplanet-static/static/countries/svg/ro.svg diff --git a/clickplanet-webapp/public/static/countries/svg/rs.svg b/clickplanet-static/static/countries/svg/rs.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/rs.svg rename to clickplanet-static/static/countries/svg/rs.svg diff --git a/clickplanet-webapp/public/static/countries/svg/ru.svg b/clickplanet-static/static/countries/svg/ru.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ru.svg rename to clickplanet-static/static/countries/svg/ru.svg diff --git a/clickplanet-webapp/public/static/countries/svg/rw.svg b/clickplanet-static/static/countries/svg/rw.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/rw.svg rename to clickplanet-static/static/countries/svg/rw.svg diff --git a/clickplanet-webapp/public/static/countries/svg/sa.svg b/clickplanet-static/static/countries/svg/sa.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/sa.svg rename to clickplanet-static/static/countries/svg/sa.svg diff --git a/clickplanet-webapp/public/static/countries/svg/sb.svg b/clickplanet-static/static/countries/svg/sb.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/sb.svg rename to clickplanet-static/static/countries/svg/sb.svg diff --git a/clickplanet-webapp/public/static/countries/svg/sc.svg b/clickplanet-static/static/countries/svg/sc.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/sc.svg rename to clickplanet-static/static/countries/svg/sc.svg diff --git a/clickplanet-webapp/public/static/countries/svg/sd.svg b/clickplanet-static/static/countries/svg/sd.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/sd.svg rename to clickplanet-static/static/countries/svg/sd.svg diff --git a/clickplanet-webapp/public/static/countries/svg/se.svg b/clickplanet-static/static/countries/svg/se.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/se.svg rename to clickplanet-static/static/countries/svg/se.svg diff --git a/clickplanet-webapp/public/static/countries/svg/sg.svg b/clickplanet-static/static/countries/svg/sg.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/sg.svg rename to clickplanet-static/static/countries/svg/sg.svg diff --git a/clickplanet-webapp/public/static/countries/svg/sh.svg b/clickplanet-static/static/countries/svg/sh.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/sh.svg rename to clickplanet-static/static/countries/svg/sh.svg diff --git a/clickplanet-webapp/public/static/countries/svg/si.svg b/clickplanet-static/static/countries/svg/si.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/si.svg rename to clickplanet-static/static/countries/svg/si.svg diff --git a/clickplanet-webapp/public/static/countries/svg/sj.svg b/clickplanet-static/static/countries/svg/sj.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/sj.svg rename to clickplanet-static/static/countries/svg/sj.svg diff --git a/clickplanet-webapp/public/static/countries/svg/sk.svg b/clickplanet-static/static/countries/svg/sk.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/sk.svg rename to clickplanet-static/static/countries/svg/sk.svg diff --git a/clickplanet-webapp/public/static/countries/svg/sl.svg b/clickplanet-static/static/countries/svg/sl.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/sl.svg rename to clickplanet-static/static/countries/svg/sl.svg diff --git a/clickplanet-webapp/public/static/countries/svg/sm.svg b/clickplanet-static/static/countries/svg/sm.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/sm.svg rename to clickplanet-static/static/countries/svg/sm.svg diff --git a/clickplanet-webapp/public/static/countries/svg/sn.svg b/clickplanet-static/static/countries/svg/sn.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/sn.svg rename to clickplanet-static/static/countries/svg/sn.svg diff --git a/clickplanet-webapp/public/static/countries/svg/so.svg b/clickplanet-static/static/countries/svg/so.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/so.svg rename to clickplanet-static/static/countries/svg/so.svg diff --git a/clickplanet-webapp/public/static/countries/svg/sr.svg b/clickplanet-static/static/countries/svg/sr.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/sr.svg rename to clickplanet-static/static/countries/svg/sr.svg diff --git a/clickplanet-webapp/public/static/countries/svg/ss.svg b/clickplanet-static/static/countries/svg/ss.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ss.svg rename to clickplanet-static/static/countries/svg/ss.svg diff --git a/clickplanet-webapp/public/static/countries/svg/st.svg b/clickplanet-static/static/countries/svg/st.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/st.svg rename to clickplanet-static/static/countries/svg/st.svg diff --git a/clickplanet-webapp/public/static/countries/svg/sv.svg b/clickplanet-static/static/countries/svg/sv.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/sv.svg rename to clickplanet-static/static/countries/svg/sv.svg diff --git a/clickplanet-webapp/public/static/countries/svg/sx.svg b/clickplanet-static/static/countries/svg/sx.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/sx.svg rename to clickplanet-static/static/countries/svg/sx.svg diff --git a/clickplanet-webapp/public/static/countries/svg/sy.svg b/clickplanet-static/static/countries/svg/sy.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/sy.svg rename to clickplanet-static/static/countries/svg/sy.svg diff --git a/clickplanet-webapp/public/static/countries/svg/sz.svg b/clickplanet-static/static/countries/svg/sz.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/sz.svg rename to clickplanet-static/static/countries/svg/sz.svg diff --git a/clickplanet-webapp/public/static/countries/svg/tc.svg b/clickplanet-static/static/countries/svg/tc.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/tc.svg rename to clickplanet-static/static/countries/svg/tc.svg diff --git a/clickplanet-webapp/public/static/countries/svg/td.svg b/clickplanet-static/static/countries/svg/td.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/td.svg rename to clickplanet-static/static/countries/svg/td.svg diff --git a/clickplanet-webapp/public/static/countries/svg/tf.svg b/clickplanet-static/static/countries/svg/tf.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/tf.svg rename to clickplanet-static/static/countries/svg/tf.svg diff --git a/clickplanet-webapp/public/static/countries/svg/tg.svg b/clickplanet-static/static/countries/svg/tg.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/tg.svg rename to clickplanet-static/static/countries/svg/tg.svg diff --git a/clickplanet-webapp/public/static/countries/svg/th.svg b/clickplanet-static/static/countries/svg/th.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/th.svg rename to clickplanet-static/static/countries/svg/th.svg diff --git a/clickplanet-webapp/public/static/countries/svg/tj.svg b/clickplanet-static/static/countries/svg/tj.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/tj.svg rename to clickplanet-static/static/countries/svg/tj.svg diff --git a/clickplanet-webapp/public/static/countries/svg/tk.svg b/clickplanet-static/static/countries/svg/tk.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/tk.svg rename to clickplanet-static/static/countries/svg/tk.svg diff --git a/clickplanet-webapp/public/static/countries/svg/tl.svg b/clickplanet-static/static/countries/svg/tl.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/tl.svg rename to clickplanet-static/static/countries/svg/tl.svg diff --git a/clickplanet-webapp/public/static/countries/svg/tm.svg b/clickplanet-static/static/countries/svg/tm.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/tm.svg rename to clickplanet-static/static/countries/svg/tm.svg diff --git a/clickplanet-webapp/public/static/countries/svg/tn.svg b/clickplanet-static/static/countries/svg/tn.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/tn.svg rename to clickplanet-static/static/countries/svg/tn.svg diff --git a/clickplanet-webapp/public/static/countries/svg/to.svg b/clickplanet-static/static/countries/svg/to.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/to.svg rename to clickplanet-static/static/countries/svg/to.svg diff --git a/clickplanet-webapp/public/static/countries/svg/tr.svg b/clickplanet-static/static/countries/svg/tr.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/tr.svg rename to clickplanet-static/static/countries/svg/tr.svg diff --git a/clickplanet-webapp/public/static/countries/svg/tt.svg b/clickplanet-static/static/countries/svg/tt.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/tt.svg rename to clickplanet-static/static/countries/svg/tt.svg diff --git a/clickplanet-webapp/public/static/countries/svg/tv.svg b/clickplanet-static/static/countries/svg/tv.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/tv.svg rename to clickplanet-static/static/countries/svg/tv.svg diff --git a/clickplanet-webapp/public/static/countries/svg/tw.svg b/clickplanet-static/static/countries/svg/tw.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/tw.svg rename to clickplanet-static/static/countries/svg/tw.svg diff --git a/clickplanet-webapp/public/static/countries/svg/tz.svg b/clickplanet-static/static/countries/svg/tz.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/tz.svg rename to clickplanet-static/static/countries/svg/tz.svg diff --git a/clickplanet-webapp/public/static/countries/svg/ua.svg b/clickplanet-static/static/countries/svg/ua.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ua.svg rename to clickplanet-static/static/countries/svg/ua.svg diff --git a/clickplanet-webapp/public/static/countries/svg/ug.svg b/clickplanet-static/static/countries/svg/ug.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ug.svg rename to clickplanet-static/static/countries/svg/ug.svg diff --git a/clickplanet-webapp/public/static/countries/svg/um.svg b/clickplanet-static/static/countries/svg/um.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/um.svg rename to clickplanet-static/static/countries/svg/um.svg diff --git a/clickplanet-webapp/public/static/countries/svg/us.svg b/clickplanet-static/static/countries/svg/us.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/us.svg rename to clickplanet-static/static/countries/svg/us.svg diff --git a/clickplanet-webapp/public/static/countries/svg/uy.svg b/clickplanet-static/static/countries/svg/uy.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/uy.svg rename to clickplanet-static/static/countries/svg/uy.svg diff --git a/clickplanet-webapp/public/static/countries/svg/uz.svg b/clickplanet-static/static/countries/svg/uz.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/uz.svg rename to clickplanet-static/static/countries/svg/uz.svg diff --git a/clickplanet-webapp/public/static/countries/svg/va.svg b/clickplanet-static/static/countries/svg/va.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/va.svg rename to clickplanet-static/static/countries/svg/va.svg diff --git a/clickplanet-webapp/public/static/countries/svg/vc.svg b/clickplanet-static/static/countries/svg/vc.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/vc.svg rename to clickplanet-static/static/countries/svg/vc.svg diff --git a/clickplanet-webapp/public/static/countries/svg/ve.svg b/clickplanet-static/static/countries/svg/ve.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ve.svg rename to clickplanet-static/static/countries/svg/ve.svg diff --git a/clickplanet-webapp/public/static/countries/svg/vg.svg b/clickplanet-static/static/countries/svg/vg.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/vg.svg rename to clickplanet-static/static/countries/svg/vg.svg diff --git a/clickplanet-webapp/public/static/countries/svg/vi.svg b/clickplanet-static/static/countries/svg/vi.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/vi.svg rename to clickplanet-static/static/countries/svg/vi.svg diff --git a/clickplanet-webapp/public/static/countries/svg/vn.svg b/clickplanet-static/static/countries/svg/vn.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/vn.svg rename to clickplanet-static/static/countries/svg/vn.svg diff --git a/clickplanet-webapp/public/static/countries/svg/vu.svg b/clickplanet-static/static/countries/svg/vu.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/vu.svg rename to clickplanet-static/static/countries/svg/vu.svg diff --git a/clickplanet-webapp/public/static/countries/svg/wf.svg b/clickplanet-static/static/countries/svg/wf.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/wf.svg rename to clickplanet-static/static/countries/svg/wf.svg diff --git a/clickplanet-webapp/public/static/countries/svg/ws.svg b/clickplanet-static/static/countries/svg/ws.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ws.svg rename to clickplanet-static/static/countries/svg/ws.svg diff --git a/clickplanet-webapp/public/static/countries/svg/xb.svg b/clickplanet-static/static/countries/svg/xb.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/xb.svg rename to clickplanet-static/static/countries/svg/xb.svg diff --git a/clickplanet-webapp/public/static/countries/svg/xk.svg b/clickplanet-static/static/countries/svg/xk.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/xk.svg rename to clickplanet-static/static/countries/svg/xk.svg diff --git a/clickplanet-webapp/public/static/countries/svg/ye.svg b/clickplanet-static/static/countries/svg/ye.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/ye.svg rename to clickplanet-static/static/countries/svg/ye.svg diff --git a/clickplanet-webapp/public/static/countries/svg/yt.svg b/clickplanet-static/static/countries/svg/yt.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/yt.svg rename to clickplanet-static/static/countries/svg/yt.svg diff --git a/clickplanet-webapp/public/static/countries/svg/za.svg b/clickplanet-static/static/countries/svg/za.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/za.svg rename to clickplanet-static/static/countries/svg/za.svg diff --git a/clickplanet-webapp/public/static/countries/svg/zm.svg b/clickplanet-static/static/countries/svg/zm.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/zm.svg rename to clickplanet-static/static/countries/svg/zm.svg diff --git a/clickplanet-webapp/public/static/countries/svg/zw.svg b/clickplanet-static/static/countries/svg/zw.svg similarity index 100% rename from clickplanet-webapp/public/static/countries/svg/zw.svg rename to clickplanet-static/static/countries/svg/zw.svg diff --git a/clickplanet-webapp/public/static/discord.svg b/clickplanet-static/static/discord.svg similarity index 100% rename from clickplanet-webapp/public/static/discord.svg rename to clickplanet-static/static/discord.svg diff --git a/clickplanet-webapp/public/static/earth/2k_earth_specular_map.png b/clickplanet-static/static/earth/2k_earth_specular_map.png similarity index 100% rename from clickplanet-webapp/public/static/earth/2k_earth_specular_map.png rename to clickplanet-static/static/earth/2k_earth_specular_map.png diff --git a/clickplanet-webapp/public/static/earth/3_no_ice_clouds_16k.jpg b/clickplanet-static/static/earth/3_no_ice_clouds_16k.jpg similarity index 100% rename from clickplanet-webapp/public/static/earth/3_no_ice_clouds_16k.jpg rename to clickplanet-static/static/earth/3_no_ice_clouds_16k.jpg diff --git a/clickplanet-webapp/public/static/favicon.png b/clickplanet-static/static/favicon.png similarity index 100% rename from clickplanet-webapp/public/static/favicon.png rename to clickplanet-static/static/favicon.png diff --git a/clickplanet-webapp/public/static/logo.svg b/clickplanet-static/static/logo.svg similarity index 100% rename from clickplanet-webapp/public/static/logo.svg rename to clickplanet-static/static/logo.svg diff --git a/clickplanet-webapp/public/static/og-image.png b/clickplanet-static/static/og-image.png similarity index 100% rename from clickplanet-webapp/public/static/og-image.png rename to clickplanet-static/static/og-image.png diff --git a/clickplanet-webapp/public/static/raphael.jpeg b/clickplanet-webapp/public/static/raphael.jpeg deleted file mode 100644 index 63ccf58bf2c11630b461a59b30a95722d20f0137..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 38334 zcmb@tWl)^Y_NY5Rkc6N?f(HohG7L@#Ay|OmIzw<7BtUSB0l|X}Zoz`fV1pAZFu2U% z1b4`wVUS#Q)v0s$-oO97Rj2B7_lK_PetSK&x~qHjTK)c=`TGk%uKrT(B>)Ep0KmD+ zfWPwqCBOqh!ux~-5AGA)CnkRIkc^I;jFgm&nTD2UVj^VW+2r2sP_HmD)HS^fI3ova2)1+ZdYKih;gmb=eM z11#W9M{gRTe(;@tBDvgABRDKRL<#IG~u z2OWZlkDB=!)ZS(_a}^owEj9@f6Wu@)+w|7&g|ZBfQL5_4M>Humg=qoK>rR7ZrxR9CNux@(bo8*qkTA~M!|2W zK(CCA={pWnSGe@%(Tp9&^7O5c1er?RTLff2&OZCoq#??e{(^f?T%g-R7fSV1o&!~eEj9x?yqL}>+=5nmTne3R_b032 z!(18+TblEYF~?PBhik=bXe-wsDT(F)WG5Oyfo$1-xCKiIbB$WiL!>Nrxlt7Nyo|c4R}0iWS__eS)h#;r^3_ppc9;ApRt% z29;h+I=03@KRJg7u5W5S6Fj@VP0#W>IzBMHp4>7W&DzXxO?jN6%c%BI>M6yl<`;Ow zIF+}sPQ_G}eb!2VpyA~oQtif*r5vIAbyB^a zUEn=9dkl5JRpCS-2Mh^mN-l zP5^z>j~2-(T>A$Bp#RG`Ga+(2^8U)@Z4+>W=02qc#AS1&{OmGIi#fLKFhnEA4g_qU zNd)<=eub$vNH~Tj>H>vZY|}(4Ma-&2V(P!IrRbN9>>A1zr<^ZYjBlKH7M)(c%b}cQ zY>JR+gOFMKo@exPP5=Iz-U&!`i*aU)n&PJ8+$0vO4}@zFIzg?{@?YEfQ3DodKy z@2rLslri$>>%WSbAn>QP)R*IF&*)ufgO9MI-DRJqc%s^qupUuNU}N=ho3G#EDtr&q zEe|_{Dp_U2p>3NjDe~vN#D4*1oizVVfZG-)7xQ~(RAoJgj(c&-u8Wjy%IgmpA6+rj zFYD$$YJHkM~ZRkyg_#g^l%6#B|{%Wv13@HcKRM z`=z?^cEr>VDe6>|v(@lE-L*;~-(GL_ z`eNZq7S&%h@?Ri$V8r-_lyBj&JgnJH)|EFwv9%_3A2me7S#X*OxyYDAA&?!Tjp`Rd z871@m@;}_Hb9%J(a_$?MVC6fcR3^)>_d1YOCG|hH-H#@f5u{Gf!G%L7K}}bTfqQbk zSBvdF^2K9Iy0>17EgL=-1{>0KmuJ5-A!xGcwKh3<7@{5pO*=AZP}y#x^x8V*2w>6f zr1~#JOndRhk}I|=CfEl-aONED(1_?u9jKeLgEpeJ-d(r1FgU&`kwEcARZ+FuRl%zR zFD&vrfwHbQsm>*1<1rUk!Ab~ZRc(#dEvRqhLN-Bn^~`-ah1f#T-uQ&f%}!SNFF>=@ zZzqV+8zTfYKM8bG>^j&=DIBP;^f1qxl)nFt4MyiBbDOax-#@>$M`rO~c>1zOp$P4b z8%*yWGhyLxE@)|Q`!$;k-7wu*WayK8{ zU;#M_-!2%&3{rmhby%+j1@OK|Lje?0v-NI}u9 zC~yigIPvE%KzX7pOY!Bk@6Pjp^aY&`l3}e5jU4}7L6B!gicro%pI0Yb)@!(AslGCp z_o8HYbmYy&v~&7j0P|k}X{G}4kt|Eqz?Xtg;~S0R>!)ykn4@NvqFsu%Zy`T*rT@}a zCstdV%vkRB^?%@EAdhA)wKEQ;zchLGg4d?{5Caj$^rw!!W=YKyyV!TqOBOD-$y#yD z)3){P(kFZ88e8Xw>8qMECSGI`k-W{V`vBLrje&5Q-kDgZk)y+d-0%%&&RMQC8SKDPGqXHuqDv1={k~eG9@1Q2f0nHcR zAscfp6Kno1?WQpj0-=Hhrbt{*UemnE?DL)TMlJ+?R7u_+RYFzuA&KMt zX6HP!TXWtm$gJ8%`Xf3f25NQ2!$QHaAM`1C$LqnOzA?1!fOlR>0(%DYpt`Olq>ur5UyQjso`K@LCRe0!95K{C4z?Wha)v^4^&3mMzpw)H-7=6ZNZPvkmH*)KTtX#h!M^`tV={Kc1vPF!v{kauE`h;WXJ3^IQi1bkZ+DJQvfD4jo8`3&)r+5> z3QEa$>y(CPZfj0P|6(}#c^`%&Qi9iy@5SQ&aqeh{nqItng^)5t z`jEOTJIPF=lKKqB5XGR#=_45933ZoYbn!T54nTCB`R1X91)EZQFA$B>>!$_9PIWuw zb0k4NG1#2q@Ml3}PyQVgM;)cJS{6_lLfXLsGa5dhi0$Dky6Uo#>U-2OhoNzwpY-&* zgwI@D_vfxHL&Ev;MhlUFmEnSO=9_15KWdp^kXC_wKt9^2pddT8;5vY`u|5x6*&cY7 zU&BS&A|H!Rfq9%~{8{P?yz#rd@C5aVP+b~rpKh%nKvMD@RP`d+nFaHjv9XsE{EqeS za_DXSb2Lwab9Q`{I{t$bfW!D{ePLO7>sEWLsuF7LHy)LGHbPEPF`clivUjcBaDvT+ zGq++#Jzxu1&52F(zAN#I968wo*J(24kBcP0`CeKCPiXA~m#^>!-vXggB|H%aa zFp~`i(f$bh3viQ2o`VE8Ejyc7sEH>&jCRWlU{SnG8UKTIncg;7TQ;|*Yv3w*idMhi z418A)F&2oF@|<$*tI{uIP=JcWJ{WPnJZ6_Ac8_E{ie_ z4lm~h`7cW6N2bo}%TI1&>?f{T-3R@f{(UpB%XU3ozHU4xF1C zjr^nmTr+%|a6`BSS<7+LsOJj~fz()_C6Zd4TQthkrqWkHkJz0xYESaEyS+#v1Z?je zAJHEa@tW6;K!@?9-5Ss$ffozc#T^eQt+b8eUb)oRP05GNu_$g2p9ZqdfBkO`K%oy| zG=}B%ZwQ$MnW)<45y8`V-l=Wze3g&GY^;DZS7{BIz!5=6$0xJ*1=|7L1F_JCw@^(rp$420zw9Rqiv_!2{)km_3b#L zf6@Q|;mNakG474q_6#S?&>eZPQS`t;mTY@e(1WzT+Z?B?zW~~HdNgbL*7#mmdmz){ z*plG#$#GS2m{+ipT&JSzi?z_rdBb`)rX15hZx0P$P*UJ zM=t#FTe7d4oZS4)jE*aA=|2tqpX}m0J_0_|Fk?`P2Mfo6QYdYCT)NLp~dw zKeXc~H{UBL);w+;lMa+lKFijGOquoHpQ9*PXStYvU z$?6W<@q9B~=ES0-_PQmSm_`Cni=;L7eg1;z{LwYJl*E$LTb~a7##7lh|5Oif22f>n zKiFvKEYKqU)UecSWqIcG60EII3dUrfq8LO54Ec0Sj6^pFk!AwmLyatb*iE!s4sZy0 zFLAFG8r|=il@?PN=U0@lt6$}o=B|`@%5qaa^*{jcc$S`b*$3WcBPSd8* zrM}N)Z^1R&%i5(twbZx}0c#mLYOfufml=i@)O>Z92`m$sTr+EJ0tXvuF!|S_YBHDv z8x}=gp2NM@px}n1zVt=6suLj7pZEVof@h4#4n9Yu_77qyv^jEwigUJZxJaQNDh05z zw`Da0d+w(*u=^MUsL!@n<7?6xj2M)n=4|ys(E~OKp7jezoOZE;D_MbRNFv@o>~APw zTuOd?(yFcaV`s4O8wN5WZCEk_hUSd)d6 zeKc%5C$O<3&}eE0o8Q!ed)Me*9nR#7SyxUj6X9y&br$6)+)p8UtLGLP_+AOmMpx z4)1&1fLMy2EX$bH#UE;N1fjZ3Y^#j&bW60Eog1@2G4C=c_t-_ZoZZZ<={VA*tR?$C zX<9{yfby1^sUa5(=GTEOJF%!ry&7cYgagNtKxxoQO5l2=!B@)&h}*bB;8xtBtx#sPj?r%gQ&C2$Vf4SWe<0t|EPx~6ShAn>G zRKP2JPkRD-?BwcF44?MZ_hB{J5*>pyH4@KGE(4L#Sn-j$BJUVO&_`?klg|3n6b;Vo z%!HXGfx_en)^F4>RXerwNq3sD^xxQEr_qAt5+MsFCpl?4^hbp5rX1ybg>}v=O=jD9 z7az@wFikbFn8p~kZ0^3fHR;Wh8#1a*k05h{4UYZE+TdO}c;#ukmwjI15Lz3m5W4Ng z-1}q4d*gL*+zJ5j1m))97pyXHguOf5MX^t}Y#B4wB~INfwbyPmpAH3+L1reUGhW6T zChTNEvwULCM$)GAdU>|7*IGFtT(}BKn<6_Yuk2j;HK>OYrc)E@;jjAz!y?2PdSK4V z4X!Bmq=X&`5_qUGL@O|UENcF2W4_EO=EOR2{8%gy`4x$r6ev9xYpda`J!mMHQ}ro{ zhKg;Q5IpU3^^@a9XT>xc!?V7X%L$Yvw;d!Vc9=5RJ$Q=&W>uXeBn?+T7mEX$ab$QHgac zuTd+A->xu1Y#)P97Nh*LA2>Q<&b2Fn;t7mQBzq>t`Pm#O)r&ASuMzKPy1_pU=yA@$7Ilqix)wxgCP=P8!I|kC8yYP;i(j%$W~_ISKfnC1M0eIhj}6c)moMfCAQk5*w)~bwAGD~qp5@Ck)|L?1fo4WwuTGBw&yWRm|2&|<7aJ=xh>lI>4x5GyEG!#xgM z*84i|tkyp+(8QIFk^&}YT5%3}q$cpxgRJd*tid7$5uQDJ8pt?VQuV$yt4<%tKQZyGW zW|zhnv<3saXWI2=7M_B$$?{GwS?9n$Bkk}W@t;f6Bm*VGR?x)Qp0u6KZ)bGr7;J#R z+RvpU7f-EqXaq1yRD+nf-M!YDVZ}Nhnkf``{fh<|tae#nZvI(X<8q7Y}Xd+gCt>o!^>;U-vd zD#CB=>rJsxI8`ffHV5`XJ1@S2afo~hdiTRJ3n+^APm#2%9}#;uqI(*o06UetZevsd zxe9kfpSLGC3R-6nNGN9+kAR*eNZE!5QM5efijoo@SxI|jzV1kR#+kpquqA}6mOCBG zZMCvp1B&|OhgBZUJol`!FJ{k=LDr=+Sied*3e7k&T}(x@NdbG@EqB~EE0Fl1L%%f` z8hcG*8N%Y-TK%r1=BplVF$f~&#DbJeL=ayjKJc5&u{jicggVEk!s(AHML1^$>nA0b z+*<<@T`E1xEh`1zE#t>2Zv}zeu`aMqD>CBg)zD>3o#tK^) zuV#a$C-1N~3Yb77mcitAn*K3IE4G+0Cpgi-;Y?~NM4L3uRX__EqDXKuxbInZ+TXr^ z4LkQbi@A0SNYS|3k#N0?3gDoM)MVEN?OxXoxE2nS_)Pf5In;9{iWpQ#bd8R9PJY&P ztW95^mrO!E+;(h(B&b!^A`4`8fP%oOd9Vj?fME@+DVA^2Q-ge@0+&I_VKTCOPy+r( zta~k&r(uU#l4!IqQcq{1SsE43HAe-9GHY&@-&IQ+Qv9d zY#U9EdfbrVLwlcQTUcx(oy^XHttY)tj2(p_rrkVGA~$K0 z5>+S)r}`u`n6K8Mf(biy2^3bH6V5j1AP;-GIo6(ZiY_OP4ZjfU4f;)GZwrOeLTH^` zQH5Q(Q9aYy$F@HkYo2ZR0$ZPyCJYbyllKGbHP`l-gfg-1Ojq+t!ug)6ClWhzBUl<9 zvuICj;E7t%v^7fih?_;+V9E&%Ty1wQ2?Rst$E5ps6X*VIqN z6rTt`d-I%-MjZJ5E~H9y7lys-`WJxx3#blTC$}&sE%JW!^CQC^`KB)GXs%+8VpP1@ zGsVAvsq865H-V_vA&Hg+3cP*c8^)MhZ3~r416YQ^RxLQF36h1lItZ|5N5b zoymX&8Sh{f()iit65MEDmXr%=Xnh@7#z8j?ChWKo$&e5T=I%Gbymb7x>_V(1_w!HF($lv7MAj>? zmgrga@CSlu%~`^wSr7*>gSM8Sd69RphTnJhz0flr+lfY{K2MmAu%8zKTJOw)6?|#n zJ1`VjaJbM?WmlJqJ41;jC*D)8ryLlIh;4s=D?TLV9yDR=~lQv$z|rc5{E z-)7*kGK2Qk{zN!&NWBx9L&P@FASMZ-fGA#cDdYpzc=trovG zIGcAt;)Z{Exb^mx(Sz-$7N#rW-4h-!T;G?Z4adgBYRc^u0W(mFi!$`m1c zK0Ii*t9J3$B|r_L;ZvT0XMm<`ku@^UGR=-PY;Q2B@sik{(~qP*3jTo|pfjBFpLcW) zXdCyNJ*3ieH*OXPR`JxWAa>d8GKM}_m6d}U@)l_IZlWDS3Tjjf{vXf*Gu#8)IH3y+9;uEeD{QqWVVDK`WNsvluull zGiTmQK+l>geFAT-r0Oirsa)z_z1u8b{kuyNcQ}7t#p8QQ#mp(T9Rw+&84}l8YTZBk zo4`gF=6?aKtCf507d3`KstiHb_|wPe zUHy%cyTo9Gg6Fi)=ra*kXZ~(WaJX8k)i9|0-H_Hm(^rdb^4_NZ@$)2k?6xG zRy)z?_ZW$Ua((YtO1g}cedXGX+cH$W+#bT}W?HQKt(GSnm^P#9;JFczRht(S~(NRxOMWx#+&mvHou9VmucuZq<6CWc)0vazMmXpE3Dk zgHHg~N5u~M&$6>?=&Nm0=V3-uww4*RGO<@;lA8pbP^|$pJjcpVkf4C!HuEn$-5ID*_ejR zq=E8#Kk87|LARzM@Qqr0$%|cd-M)f8%$W<4Jk#Md+OUmhIlcjBU}UqhJ}edKOy;Jr zN;4xWa4~jWE##xkmu08^Xd?5cJ@z}o>;l+ezXMm=K!DXnzo4@71OS{oU$#BqM3r?BE==4r_;$CF)7auH9dZZ7| zJ+}jbM;&9qpKm|3(LAz#v+I-f!7#1~DO9j0_p}bOCpg_0Nxm zUUV*K@XX!0g!|P-mRO#|F?nZy>51?q5>eb)o2QSG6X$+xfP3l~E4uS+VXr#>HAydp zk#3XtlhAq@5}E~0AF-PEHQAjC#p^itr#OSH?^_L}7qjaCkHz`N9V@=Yz^nA$O!dEM z%#Y$*2{JSKecLZR$}C~V02jpHNA8;bz}xsb{5hk?V#`7QOMaygB391*^1iRJ)tB&B z`R*?mmIiVns+2@c>cZ~4289&iPRFzp z4Yf4_)0qaLZv8T4SIj6hmYO(^MhS!UPC;<`)4g5 zUg3I$TjZLcD5}QDUg8trQ?5)jcll$}DwH0wtDgYv{9S6N6NZFkZmPMV9%fL>CvUdt zoih!xFdfyytvWB2i>}Ku3En8%YX%#%h|BMn)O$iyyP1mQqpT4gMAR$sr8mkB#qMn7 zcr!Q8yDW^mJ|Aqyd?&|7wtRSV%@UFu^9}g;rO01Etk%#5g%?asa)<_gIJUvDHy!XO zn5DIp;YJAe2BT1YNdSpoOy+kpYBeK_oRDEB-<@m7kSSEK^_>?Z5if8mB`YQEby9or zB|hYt{dyv;@`r^pB8I)~0zPu4Tgy|Ng(+OtL27Qo}RX^p#wOSo8EXO=O#8a%C@&fj$3yPpXQGvSBk<-8}|TBT^}h#H#{fkGf{`Klc8`Uj$a!nKiA$vT#u3hEt8oiH%eM;7?hS5<}GCc zv~mI(!uY^07w(`cu;Q;O&e>X>`H7q%iPc~gcC*aSBoEJxaO*$0lDut9Lt>plO^b=v7jSSs3kO#a*Q5i53*L`T0eK&*9&f*`kY+x=KR{$ zUs;En-lwfJYP}t06!UeOLCX6(c#s%e89;}r6;x36*UoQrjIin{?UhXVGfY<)Mxe@0 z6Xw(B#78$9Ht+_~)mgKO(IzDG?vv1TdFCIvkz{d90u^)++g(UMo@dMUQw?<4 zcUWh5fVmDJsI3>WlXk4Uy5vi(J3W1Cf{pA-!Ioe3$qTW=W)X*)acPbz`)l*sPU0?e&a*4MT@jqxeJcjhdI`CbqRKbx^%5BKgr%J6KzIuE6VaL}F&rLSK}+w0duI(&3G=V zL_@N5&0t1~4IA=(9scMM!`C6_{iF3Gt5UMwsz&x!hM6l{=uAyYLnzB=xQss7BtpkG zX}@&a50^{qn58Jj&PXU=wb_(%P)iE2{1;Gc9Ajr8^uaV%BNEu6KiAW5(>~WcBG~?k z{NnXvql5y~%=_gGQ#3ef-9otOmy4E^7XBZra-^fpPsvU}PW;9oscDyqG8}YC_jI}#ME(WrWPa$^UyN~m%#dju5{H8fPj2$MO-p6FE=!e| zBQu>YY~O%+=@I_IEnQCUq#!!76yW{~@cc}UBTPH~I`{74gDCFx23|H`W?a5Vk#dM0 zSj5`Q682P>^i(Ve3PK=Ss*;T}%WGMK?yC{5b5~% z&I8{)7=b1i9X%h++6B9MSu~?kdS`=Dajzd%f|5>*Hp%351FS$-208PHPtk1OBA1I< zVt>WH?9!%<4RKAHSZ|E9TAZ<3n7M4#GD^?cK}1h?{}>(&yo8d;cZR69X`Yf(py#24anma+Ye3cWuYbC< zrD9sm^Kygq5OIgBsg=@OCX1M$B6g>C9e-55N0b_)W}9Gl%Ye~ohg?b8IHBr6p7pu( zybKXR68DP|dQ@qs>9LBUWKG#yDgocfhouP9n>IG|cj&_7J-9Az?(>gw5Ln&=Zn|Q7 zv+xPDaMzw;ez2&XlS=da;df%H@uS=*-Mtq?7hPP)p`zcrt%tRFf3DP*d*;lrZduy~^W!cW7H>zL>QSl?xQk`+#8lhi zkn8yfW#vJ*s;R^4unLOTH^AJoDZIUMUe%p?y!n|je!R+8GodYvPAw1hCvw@y5H6b0 zk=U;5n(|MF^Z>ygOPuhzz42SYyc8aZ4&LIfpYWhhm+0+~;~s`a8EBGRG}q)-@F7RC z*W;rl{iSw=kVLGmf7Q@Q?`4BT^0HFHK(ZlP<|`|MEqL(VXR}}5CJQrp{_t>V$~6RJFOD+iFCor4r9!CCP=Ny#N9!4cTmb2NCXmCr z23dLETwt$^(rz9Pi^H|S;jPZu5W)1^QKD0Qow>|J)QqLcYDdIbiq4|N_;ut+YMQHT zVO^d^cd@($F2K}C(RZ-U$hfv|uufkZ*Wz1bQpy_3^WsDN96OTilBa{`9KpZjR4MG* z`q^Y6?4k$8UOdZ3j`IwRzlxotTwhFkkas-ql2{05HPu~0RmSK<=EYgqT2i$Au+53? zF1U1LrnykP9+U4?2(n?;PI-E4?V_o4A)zJUxZYp9z%$7eu87Jx@5sOO){dgzT>Si{ zr&^cS)FEK09T+e0Q{9$oHaR}g%hxOSv|fspO=sAO8;Wol*u9m32o?P6X#Lf&FS>+U8u$-nIJXc z{z1Ox%l@KW_p-s^+F1j;6IZ7-y~^Urba$HBRpn@jB&+29ZV#AY0H+w!T2oSE{rL-W zky(-0O*^6?X-q{!TJ~0L6JHK2b!z#z<@(xwptLO|af&g`F?q=7OInD?K=TrDHk<=< zOg%|)VcJDI!^z}Q*aFKjuV~}jI*{0``fZ_1T3TgV42{pauwC7jm)T=y!XhK+_}r?S zLt;t3#R#2hy~`18L}op{DtX@RYka9SE@2JnVZeQ+0i>=$h*a2M#o%A=EXyTS-Vu6s zJR*HA`Is}}_1IFO3whsXXNexS-X7LVeC)TiViA>vARcMFNdo-sXDH6-?|@+lY zb+$>m**ZjJ6#npG+l?ugk0-neUYQ@9M`rHdndyQ&GY&6pb68(#SDO9!$LLt1qBtTb zvhNcOS?p4oeDZ3YDvF4qPMVzV%_;H$iP>vGccllv)9HWk=^GAyt-TQrmHw>wXoe*w zH3oEEc247JBF4X)!|HYl3jjZk`t}zPe(o?CRrcHD)9zt;BdQnQ=G_nzAwU_C85DGP z^U5F2wXwd=iI4>4o#xx$ny5sV6HZ*&vFtbvO!N4WbRAP~=%pyJ{o1%aR2DxS(bLjq zvezhcU%ietT&QTEZhKn0Vrm2@cJiJDsE>YaBF47~>t8TUf9RqA?V`Q1m?n2%MV~Z7 z$KoJw2ao8X9;jnHx^Cz^hwX_@yomOcd&4zD2~R%s+IJjNi8OGGdz2R_5bd zZ9I}#=zeIOhG2R)*W3Pm;_%NK@b8I&JKUc7?JHn1n@etw@GT}E5l_;$b}UclR~ z`!y?9qdQsk?z&ilQ=GUdF8K|&&Qg9A8BW+GVyZYcXO};ZKQs18p!uMt?5Fn} zJLE1Er!dg>5OvSW0+Ru-LoZh&nNPWM953p|wW8ltV0&Z{vscHyMqT4seO>YsBjq}U znYGcvqbu@Why%T++9Fpy95%%jVjX(*Lu;v zb#4rwUlgzF|MBx-kjU<4F{{3^x_=iMP!E}1(Hap@FLOF=$P#zcR=(0|k%Up3-eOXo zf18h_o^5qNKxL)_OZfO5g}KrLIgxlU|jNpbh*Nl@S{HHP{qouBFnVTJC~`B&_9l_|jtAyxkgi z!-$4~)p|!@3bWMZ7x8*B#2(v_i!U(+*f6^_NMhcN7PETs>rD}d1u78E)Ly`2a;;hH zY&3SOCBA%W7<|aQV!<8>0-wPwRuxa5co;S&o8@c%ijt$ujdECcO@5O#&F5*r*U+bj z55C`TClLKrzlQsWyVrmy4^P~O(`T3N3#~k=;7Q7||s{17Yo%t{(2p?Rj5lQ_TU?2FK{h5W#uqaJh5-IRmdJwmu-eD;>_yi8tg ze_XjbK#J}(w;I^G8!1ogLzY2iQkKzO#$3o$n@7iLg+v{PX#w`Y~7HwhS_ zJ+c|Qai6bPkoya0Xz;hNES15;6VCHVi#A-qiBn%L7f@q=;|P8a6aVU1-1^G6PLdk+ z4E+5#;F#&-t0$*+7Zsh&F}r~$lJc+N>fX;D(7v=TZg3s`fZ4m$kjy5{eDE^-oCYQE z>iS7BtdC52I>}CFh55VwZiGeIqjS~I!C&6Za3rK3k@CEK!w_REQZj2WRW|9wKlMiO z<@-mtOmZrSJ|VtxH1#VyR6Q|CD1XaQ>JR;Aztlw0^ken;+Ya@no8Ukgf435A6i5YfzPO_?8{tU zcoPHR0zrJ|h+9V$4Qkc;zLC4vVofd8*BW%L2txhaNw#<^&l!fa$A_@eeR60~bPXJ|KmQ0$LK2dX=&oOQNYXUxYB%&TNSlVToUlt+LI zI|UT5z^*&Yg+j}&!Ic~u4->%TE#2iab_*|t%El-K-$bU17>nD@9r7(;>C`|=8;=nGrfy(abA!z0#P$So|t33cJ32p3Y{Tu=}Ee26vj?<6dQ_X_;&xODQYl2Jh}~tTca~ zH;$XT!%0+x$=D!rL)0Sdc4LIDvZb}?y_Vb)#T}r$dREgEo}Z+nv!tQ!v{$u_75x@% z0`%uft?W$Byp51ed&%j1fWu8|tk9s}-Fqt^2r_K5%%kjX)${KSTKxs!>`KC>o6a;a z`Gy0Jo|c#K<>m9)v+&3eE5RGO-b5mv^86&BU&6Rffy!{8UbGGps>JI7h2rX^fT}rM ztaRqY#aazdMXzsiS0DV<5=CM1tZ6fqTckZ8Dc{a@%|qclq+MP~2y>!VulxG^@G4f~lW0@q)?D|r&%6!$ytqdpwV@7k4< z7`cxi+LP~dDgNNo;YA-(vq#si_OwM6L^h@rsB4!BI&aK{PEra-aySk-fWcy}Eswy5 z^P4Ti1Ai(V1C!LD0)u<=kfuL`D&H8zRD!JmQ z4tU2?eS}{FSk~s%y0>}rRSG0wUa=7;{Ka`aHvJqV8N^D0lnq7U@ulMbk+Ev9EFif&gzd$u{ps?obEV|kxLi8IvT#Z|j*1L}HQyhv+YgEIP}_tkM)FE%h*9n0;JL<60g zMkdmlUt(xq^5KwuyWJ>}P}HL$q7jbG-nB}|xG_WhaGpia8sisg;EXW{KerT}6eZ|$ z+7WA8`IW=M6Ak2jQW^}(tp+vE5LL`L^LuA}?5(v(YN{9vjGz{g(mKIQ5&v9UUT9-` zn~F8hMERGO&r|!zz9Athe%1inpl@X;3l<&pa4KteW%GIg4n5$ru7B^0!$hS))i=W) zpw}e#(xrcag5@>H(o{vhxrUo}H*x!6q zx=0Q^rf8b1+(^g!e*kenj=wh=zDpOJt1pb?@w3=A2Pm&Gve{)kycU*9Gw86IRD)9w z=v%D|Wvz48gsUfI3ApK~2FI?T?QYz44!GD}eALD1$x@wS9TBq-MSueV={s&(tJ={L zD#7d&jHUo)j?>f*#OUo6OfDr~WZ58W!x-uvM>6kA%4pTfbquw4%&T=wb&2l2&<}fv z!A)*ATlOrPhhlF~uSe(je11zGBY~=y6k9>VFL z8Co_qiwGnC04xGaGUFwzZGTbr7C)%#0{hgOS)SUy^z&(TPbswQaJtCkG5wul@W^4&#&Bt(}j2rW8ZW9uQd>k87 zKZwM|%cn?d9YE5K!%D%RcmRspWDT;#gKt|6HVW(P=J?PKUL}=_e3m{gU6dX_k_|ZS zN370Uv#~OAGVq^``7L)>Mo}>>R-F;U;i->}Vh{XqH#WHF_BKoO&>xR`br79J^%RXA zXm#svu)dq)RM;^&3JrXMj?<`EJpmVHDKHVB$4-Hz)q)v%3im4{f_jBmN8AwaMgpQ& z?4N8snt)gjsN}-JUy`*a3yJl!p;f!dGn6eEy$zKv;zZdcfIsv902Pj)Ye@rxJuzUQ zsf-4Je#-9N8GKc9_~yKy84LLU5Es&ifyjtV zT^L_d!iF^KD`7S0S2Y0KA+``}y1?Md{Yv)?{0A|bb2(bCfdJs!?p(ERCbY8$9JAV^ z)mxRWmd5+Q4+mYVz(&T5@8~fx({X)5I|`3_^YOGzK+LW+FI#x~aUj8~C}UyeQgQi9 zvCbzlo2!)AT-7WyqGy9D%vhJ!(O+?^O9%cPU;&kUL?RaZ`)o1+2oa%S5AzH0S$(ES}Avxpq2IPur%%I z&$oTdyTBY43vztzYG|q4mjN01%lh$nN>>E|*ga)wqP~xE?5DI{5TFMhr@bjA1ePyi zLEXxHb+CH#s_A-u0QXthY6B1P^te1Y5aHiZFUTyjmdVFTK0`(0SQ(=4j!|iPIX*e? zK0=-U0PMS}49-<49G^9nbol2h%U_l=5{fZz4_UgGVKfwZLrjL)0c%f2762}awxJ+G z28b;gU~NvyutG;_eOrzhTNc8nn8f<*K<9nI0iggJ1Xlnl>lDKr&Ca`q5Zln-js%LL zSMFA#Rn}|?sdH*wY|qF$_^%E07&pIJYYA4@sZ57?i9?SqgQki9<8 z8AooTbG$9GQ&aLP^)qYjQ1sdk3iX3}1MWVqv$5Bzg*%Dr9mM-#g=2ar)vUei>I^7Wb=cQZwgylDjH<8KM_Ximqg}>V z8IP7ZKZg{FpU81m{{Yaa%>p9BkU`}$&MqOo{JUuQ=56)S!qJBkyE11=v6lSLD(7;D zvj+~#-kQ5LL&I79_isu|1yP{S8GDc5L&a}nYQ>Bj6V{trI@L?3#6$F}*2JupV71>@ zFU39vQaM?$K{59gh?KXW;e!UA)*WqT^gU~44d_2;jszPpIbdH>=i26Es!kJ!x17qw z#!OmlaSE_!8#e*t&vh1iE~naWOTN9t18}cWKH!jSf^`H84D|^N9#~1PvI=DBFASx6 z2T#N(IxB7jR}EVS9_LX49-TlXgUr4%jI{j%69Gh>+2J8i-ezAGxoeAqkA%6IMJ6aq z-usrCvM&{k-a^af4;SrKYfL(V)oXf0@vo`hWr^+UUcf(eDgoAk?HAG0Z)dMWR>ko(VF22(&>@(nrFIC69ZK|sY=6K6%_@R> zPRg;YQ6Da<#oWy`%&(BwRQ~`enUeHzxfjbWTxzoUV1=I}K4IV`NEKCaYV%#{w5Mj? z(4c9cssM}%l6y{@8Uh_A{{V{mqWddVolW#poku0aTgO^7 zV~s{rs_m3Gh^XPwC5RzbN#!%VCvi2p{Yr+7W_Rl{a#bfAz+InhIMw1%_WB^a*a~`u zBTJfIx^8uQv|XxAO5m@s0f64X9TaRhJ))Ijy>z~SB&S}meT0a1q<^`PrKmb}H9d9H zlkS!pH3lUBh&1j6kbyR(B~;gpsTWHdL}1b5OOEX;)NE^d7HfXQJJBhxLUfC=0|-Ry7;o+N zu}^4#>jlM_t+0BBRCBN5_1ZvFUF)Cm)$e_8OWFp*4bixOMo_}U^=T^!V*!IudWjW? zg5ZL)eqrMNKV4Jot!%NJ9Vu1Xx8N?J9wp@*3SG-XQwSfU(!wbzJ;HsK5n^eFt?VP# z+aqFnp2S^2=voTTOtvqNAq=*Kw9|c*O6>AhNFb+;(e~v_s;;1I1bxfF)%=ZgPDkX( z22aT{GR`LlpU8|J0}lyV>7r$GRbsR9_vSj{W#r0ux~hqey;VJ`=#|vPr^{(RI_XCN znYW-}Zm=D*YhIxB7uj!RMu_{0w#tCTmNT{ncKpP;A@mt2!-Rm<0 z7d`mVCH4aAC2td<5P`UyQOUX+rE(P zEI>LPx!#h%q;r>x1~cy&nVoA+!lWACWgAh{lDdFtRmVj99SEzq90&^RlM40)3057e zskS*Pg1Y)3mo5dPO^j%~S_PfMR%&G>L!l$DV3zeSx0xJ`*R~hOGIO5`hQ+{J^Qxp} z{ED#_u1`GT@O6n+B2_vlAOgys{?cDdENO>Ou8Vf$ohZ}J{a)55^z5Lk5Z(6)o77+D zzQhiyKLtaAafJfDHh<$p2v+@x)EX5b$2X1T7|a7x>g2=C6Az>=&s;aR?MxR85^Wc zZ5^5a0Gu?GnAsq(Zt}!x-8RFZjVrXw4ig^;Uz=S6Kja|_;&L3R!Qm;!M8{BzSu>#R z5}4aOV5Z{8r84_-C@gCP#V_XHq*cEmex6b zx9@a|R9sb^3v8XMfX=(^7|ZOL*YzBu_q!Z)q_bGmfJJ&zI+!S`%L-bJ^(MHMDU4#S z%PS!cVmz&Zh4&X?7TNpN&#RdOC4^$yahth@AWh4(! zun_wdg9hSyjqUpPX6#fAFB5C6w7#207N00~YDe3WbaB0XPmi`SZP*lttr_YpZ4c<(V%0J&>e+gq*V8=4G!UwHfyR#4%=*&V%i3vKEe07~+Sq6xe&}TShgdCY8~_NTX`|S;hQ*%ij|Qx>0LYfDH!R(wGPe0BFBzdIWocJa8|U zAa$y`2Wepf56+JL#$UTzno%}%<)>W+U$B?yTQ@{4qI)SlBM3}iXOFYReJ*QMV^k;^ z3IiDw+5r_Zuajxe9n#7^sX~lG%GV+TZ=;IHry$fcSol@k<%K5~uI?2n2SFCTxiwa7 z$1A$p9aL<)rPkZh%L}sKQ6}oP*Rca7*eklxR&H)h*#n!;$Fm>hHG_-I*KEe+)uuLG zR?jOE_15D~kXyH2tlc|AJ~sn(>>((ipG!d@d37I5r>QmRb0S}KHrLo;p)N)J&_rt}EfqV`X=sdMUa^#d&}J)+qAfNl~5Z$ZNtSc%x_ zqlVvR)s?WYh24FErpYAhWP+qd(#7`J+VfSkdhO`7+tEAt>tz}}n$UElc=3*M zZ^;Pif!6%m1-P|^XossKg4L;Itqf-%Qp8JY?zp!zMjk{<3;=63M-> z3Tsa+?V#=zPir2v)pd^c+J4cbA%|8{!I%{VOE4r6=xJeaL!)ckO{&D!!}UJHGjv|v z*U^cfaS&UT;A(0iTqo|`*_zsK1q$`Xa8kDf-&j9Tdki}(8*%=z7f;kS4@MTPL}evl z(8!{`n#f#zDfdl`gVEK-eB0f)wkEFj-^v7zV_Qsn9+~b z*Br}e^=$yg!wf>?;_L{E5O4_KF`y+6YB9YeC&?9x^QYgu* zT0*ER*?yW^bfF*ZtbtvqQp#L(x~_)3l2obctZPBrK^&Fu-C7EJPTf}b>=*HSf1{yb1tr?%{_E6N6oKkk4CD;r~O(}w!a){vAz8_VA#I0Fod%n z${!cx7f?8#l2>@c&r9ND9XchEEMX6&t@{S775t7~fSJ|*06MqPTuQgAzX5dBS)^74 zLGU$9EU0yXeQ8Vd)IW{0gGju9I^Ad!py`om3yOk_TkH)6fM?tNqIyyR*#t5<)1OE? zRy7~+U(h>HJDQU~6Fac4O|5O$)F33{iTc|1=s^+c1^%001}{#{)Ld$Y!Z2RIF|BnL zmsZNI&D~91q0VZa+zGM_~66k_#5_0Em#MzZ&bQ5yW&c(`Ll= zmrrFY4SH)xdNF}&=o-zed%M)}4ylc_vm5QZ9CW`M)%aTqw&OPs@;esJH<=E#WeXr- zYIS6QuELaR{?pDUs=W$(G(Z+sPh5|1u>>DfKdY1K6B^(rtuX+0+w=w^Cey2*u@ce| zDoqQn^-B5jk${S&vTc1d@`VAy!sA;S{{Wql1)p*E0W2Fp_S2#g0iXLb6ex2?$ivC+rUn?b6}I@nw$QS7#= z4-ziON9-#-4QjC}2C?iF3_j%+Auyrs({5|j$g6c^p#_%u#k5^&)QX9WLuDczKAVh*;^>g;euxaK}5VSXP&$MQDu&Bk+Kmlu$&rEaDWwnFTxNEUL{EtnM_vZ54M z>Q!f~jmB~;1EQmrYFuji*1ONB8Udr@An4Dv7RMcHZ@%{=U18rEnpR~+#`~+Zgp2LA zN|Up$u!dj&gzh%=wGz)tNzgsWsZf*F2VIsxeQW_Y>f#FUqjw=TBKkT6rjj14q$pQT z#j%y#(BQpAg_!4ct1I+r;?Z;S8`dd5m8MqBi`+oIZJ9W6&Q9y zeY+vfd@d1lYWpJRD$WO%&s0X~(=BdS;7v}_5|oRKzwDc1xehubj;y50yYT#@edQMy zMOniamzF5Qmhf#w>iH@jlsNZel;5T$zu|ZtpZZ4qT(^{oPlT1Cw9}M})KrC6g9=yd zW=($P0I{2#ho|uQX6X7)s<*Y?#qn0w9%VLw!M*8 zinckw4v9^kr-ZsU<%%^>i0NgGwU$XGb%bx#cPVCuzSTEWk24fl^61N0Gjb_GqlXbV z<^ob@KlUSYlCn!h)DKd2{{T^Oxi*LDU$ESw+uHdmT5VBY9U^hecRL$X${?|7IW=T5 zQum}edtj8FF+yI$Zz-{^$&=Jyv`y1XbdO51DShm|WcWtyM{T?$dc8izI6u;d^6-cA zH4#Q04^l$ZQg2L3Y`C=l0PGi)xRuJZ%8EIoZgA}znI%k9QQ@oiUQa}pbCY^buE;^F zjM9?+Oe*x)-<+~iAzj#@D7S=(xbsONrNUHCR!Gx_{{Ut$EN$@-y7e|&%$h!Crgb|a zs@r%&p1Ua~wEHh3j5Lwzw0b9xc5S!r&9jZf-|+IMe`uko%a7;VZzQEQ_L(t(J^4kt zPK5l5dsWpkP)eIZ-4WeTlS_1XW~Y}L9Awr}C^kYXgfzHOXlPA5CYe9wkzP_0mQ-Sx z^%CLWf>~|Rzm*Ixc5afaTN}JLQC{9fFF9@YM5M8%l_X~-8$EGWdLXTNDZzgR$;wPw ze$3q-Qxs&yCHdCd$t!PY_K$L+~n?OUDy864PMr6g*dfzV+{&kM;!X&fkpAd zAt%a}HRjBdzYL#>u}OEKr{R!BIh7(Xj}c$xlAmZKm+r+D_;$~iq`Ch99tSyPtRhy@ zMShi<9QCEPJ(4O4n@77Xl(D9{d>)Hw6w;#ON=u({YCuZ=0665>^z_)0TAEF9ctW*-YH6%AMaL5GZ_4c@ z?n*5>c|_M_?53G3=7}V*vW!I7-=@!Kl794vwwi=lEOOAJ#89;OUv$52$k`V5MGkFn zZrrrsOP5(!i#DaYZ!g&0D4CMaVxAwG8hP-~R||$HN&acJ$yak7HzeZ~-1O?E%Ziqq zy|SP1CGi?P7+Q@?~el$u?lik6Hfzw^nRB?aGVRL?}+_+y09S>Y-_(wn~z5B&0FQNKb} z-J+aWyS3k?rH9ROi&;3>uQkP#;#!SKb{nf)G{%}u*Y^}$c;`0gQ-e1(ZLv$sBepy& zA>rYh+q@ z%d8fcsP$7WJPD*+TQaGl+3tV&c}K1(_?2YzrClnET#Zw1iEdoGNVK>c)G1V9(bRur zQ&~73=~5gtmJ4-$-VD+((<-T(P@={8W|8Jo%l1Q1O4!#Zxbx$zqtSUxUzCw4N#(Ma11Q@MzDCRR z$1-OI>0Kjq_+=&0U;I8gyBQ_iV;hWBmzO8NtWv9J+@dKi8Ed+xRq#hqI=4^w7v&sm zYq2i~&nb`Cl)s@;E5{;hm%+6=gh=C}O?_D97FSG{^xyj|b;=t{BeAJ+n7hUQ0D`+b zrb;Z^*)l12BE88)yfF#>Nxukal%@P3F7nGDmwd9{>O`NJ3O(e5ix=dY9;5E< z5}RB_vND(HR>^8ejMs*T4-!VA?YsW~Lfq~!R{A7|9@I~7cHh&2x?BGMZrP8euC64L z6S66GPRSclFJ?|;X1fr6Mfnzdw8+JA%N(ojl8QE`ix;~#KHG^x>nPRc(~})Ka)01+ zmz)Yx;KCaE7yJg|th#IKY?YPSvTdPz*&la9uhlY98uHP1h|LlFi*1seiF+^Z*`}Js zIe$DM-w{2oktn}3H{{iqh+93{&$2E3u@xhnng0NDA5FibA5$2{o8jQzMJpV!gpDW4 zkEw|gM(=$801S`hTvIHJQ+DNTiQPpiMy%H|bcNwG$xqC!bl1=6Nf%j{Pj%8S{#!#s z99dV}qnDP1^0=W%lYZC~eC3KikaA;!yk(zv2%Nq4uiv>HD9bMdAh=x+{{VJR#@5ed zQaxP~>Bmb7T)$J5|pDae4eXL~V{2Nyy=}1-5+f;IgB=C$C5~C~5N-L*7O%>CD zWf*xIk}fh#$z2;mXqB-I2z8QG#1RkKHeY>7D6iYOt0mf^DJOw`ImlW`^39374fnfj zl%L%*YUV?I>jE>`Q2m&qkL07AAt5V0*;|~wqE2q2mv@$Z&R!hdBve}4-drNLjc*-Q zmh~X-!{AiQjIZcp>3fzuml-KP2zRKXHQASh{fcuhOIaqEqdQU|zEsNGxXLz9k?2YPt&nX)|_|>?+QQ6|s zk#V%vebMW?Swe)lX869JyXmW`E>ulvKJab-0FzBDHxz2m%A|ZYigmULzvNOQs|NPX zT?wzo{HU_8-TvgS?qk~UhbP2@ktts;hRMl^5@Hd$$0)TP%Nb?Ow*LUjDLPAYitT6GhiM^TvXk z4O{lMW^(@2T6s5437CQQ7UL8Q;mlcD`U+ZpQGX3Ky^7UL_bjn=WSbpD;B_MPbtNV_Y3aB@cVwfZtvZCf zvU1Ua*IH@HOT8g4iO`%GT3X9@hlkSxwmB(U{{YC!=#f8qNZ0ph-yUJ6=4Hx6wB)lAI=T(%>PA+j7flaSQ&M}LTW#AuCPbwqhd+j_iW=~7l@Z1p8Em4W zG|3^wtc^oX)PIUXo}#u&F-qJ`Z7oRUN%B-Mnx;1KL)Ox?;_%AWlblyK$#9=XX_|r^ zFSQW;tkm~t)|+_SPxxeFo@Xm&tk>$BOWu|UUTskcc|!5S7OWOmDB4>5JCh}$60Y2` z*w~^{=;ZiC{;3p;mk4uWlMw!f*(!KF38)HN9tEwU{#K*qJ{Y5Vc@^sNe4mCLBDcbgP{q6U_lyK-%sbd!6l`;Z@cn_t}8ou|jK>czTV7{3oW zN!AIw!;t)RZH@G)T_MY+!)hssAIC&sbX@+^f~g6}vZAVr%!f%u8*e=}^+oh-+b#=; z^Jl4lB5f9y1t|`=9u5pET{Sv1GQ6@8=9wu!*FC7&;aI5LyEZ%iq;0o+rfk*CaU*8y zufyy{_sp=qhxBKW$(F{-W9XMleK*<$)1N@FsP2H_*u6S_TF z>6Bp9KbjEI7w%c14}HwkUL(;(Kej`aUQxb1jmf+T#~YorFT+H>%Lrw@lvH>{o8`;k zwn}p0EEUD{$mp>#eK?6t9CYKQE~vhiIvRajIOxtg(M*~p9};8+Szb{E*(@5KB^qRG zm$MY3b|V3t|ol)7YiMV7i> z)kE^SGf^5t>HJ`1qwJd?(JJpGD3-f3HE3Fq#G)_4w#B5M9Ur*twtE{P$95#$7~si0 zN~a}{b|u~BT|asf5WcGD=yEJ&4EC`qDzn#-)inCoT-i<1DC46Tq-mk`i}NH)#?)<3 zD1u*nnFlYm`boj?_!!TZFT%>1t2g9tu*-Z2C4Ld|;?k2@_Aoa1EiYtx-7aKbZW0@P zH2W(O6Bk6^R+-O7(yy-Al#WY9biU(E;J&d`_VxDq9g0L4`sl?zWo&=^P@g-J5_}_Mn`O@yHQ|tCe+eTa@M94hf5Pc=Nk^90c-P9g}Mfv8;NC_-p+A3-EGfb=>+? za9px%gQ)jsqc6#FY>Pr!QAgX;3(}RMO6f(2vWclLLgDqlrHr-Pql?Ne0-VZy9jwsR zS;DbGC3MHpj+&ZPh@xhr^54-FS!{~(>}~gUHpP{allMZB<}6cd6GU3fmJ9qOuj#yL?41LX5~eEyq6++Gvwcn;XKvE?K#%S9ccK8yj+VT4r8&+ns7iYH&jCps4 zFTzV{t9Aoap+-Q?eCe-kJ$VuE@QEBpok`#z-;__qYzov>u7CVXQ z7HJ}xXjXYR!Z6HzY>_dGqDJ05I3s>&)a9h@7aTUzMD`(gzw9mOb=kBii|~?zC97C$ zlNp}KzK?1U=-By2<;-%0ZzlaO-J*JJJ;QTW+7_F|vP#Mm==#xe=chR`)uFCNkkfR; zg-E7`pKKz^mU=dEkzLy|{sssyvA|Zoha?}pz_>{};GOpS zjkjVL(i7<;Xz2~USx!b7B?pN!GA{aXpGsxhG1n3jydw;_v_2n2(Z2+>2CK0ee2Ypv zv@%3Z9?myncgiBHNzJ8iCztfj#q@}xH1vE$c`Pc z#p&I0dgB)d&y-0@wyp-}6-kqD)NrM0kCxrW@hZro=eY?;X^3a3;WF8+CC1{HNf8xx zStDQ4@AnmWrf-fmx+OTQO%^(x}W5}#XKr}Qq2;>z#S zc5MnXOD@=!uj|eMX}Nq^kcp}5|;@k zPD?IQY^%9+NQZ{#f?PbZP+l7~9F?_!{KtgH6t`O=sWc>)<6P1tq=`0QjEiIXQ4QP} zW%PX)mGoa`Hd#$%wsBoKF{y;c_n&t}GMCWChRt^C>>YKX`#M5?BE+u**K4C@l6y$+ zMJ4#>G>!B~cfsk9hxKXxo+b+W#V zKZc9MIYlIdWr{H|*<`5lt=E=C&JHjlw*E!MlEBNMGOsLh^646nz?%9IrKr3iKdPC* z&(oHe@zSgPjlV{wtmR56n!3`>v7XD3w;xL2ZQ(NtsQKE97AV3i@_UIQQDTW*s8L)Z zZ@iyIx}#6_9A8(`x?`WN#*+GT(7>xZ2OrLuoR6FnT3QU z>ccl)8I)RV{{Y&3D5$1-i9J8Mutm-(ztuwCsW(MC+h?U&d>djm)_Qz4qVgsC4m?VS z2A##&uL+yDl42L-nq$E5HqnJpHjYKUFCvhQV#i$@T`tSKj!7-Gk~WqWN~|K=wq$NN zVrg)C;*3PK6A>Ju$Goa3@h-+`B(1;LjH78*7~+KAN;IE|o8cDrq7rGURK+x3bW_SI z@nl;3yXevw{V$^&JEhZ8_WEsf_eGLSisZPK*wPVF*uyCFl8;1;v;gS5q=}8iFY+WMzH%v_wFQwAyQY{;dWVCK*|>+98CV8<5tWptM6c2D5`CMxBaNXm23XQEz) z_!U3PKc-R>8bq|^!3iz|{klGt_4CrGh0uM!rXxSVDAtwdAoHaU=Qvk;o&=%!gvJLTMv~?o05^6cpn{>%P5-L2h zv15+WElZYz$GlD2a*X1TmlHhwJRDia(am*#UA_h}YUqFb=l8^J57PNW z+<0u^^pKfs-CUKqzMHsXx{TNPDqoRkb8=rEWdcx$ID@|j=ka%G~Bs|Z3& z@R!#=*_unt2tWLgzluCt5@u@#=hmY5Tn)b%Gex=-qxT`{%bNaEC#S8tlgEaIsTL(7 z^rw#o&2x5&Q}0I2NI0`}B&g%?JGD7{A<9^a;S#c|1v*1LMNy2gwo)Mo=W4U!7i9jQ zS4wteCSuW^e4bH%MiJwpQ4_X16jlr6v6%W;;<=U)v2h5bX-CY2mPIF($jptbbVbrA zW5|ukx{%(a6q*~+oqIDFqh_O{ZK)!W{{T~<+L~UduIAb4%`O$2cWu-~YQbNWR9!Oa z{{ZGvE?JxZ00!y2bo8SvrPC=H8jU1XTQL(`Ri6>>HgVS-DU`C0w8}8Y;hD;PJe(J_ z%u$4|qD}P4OO|@MJR_VKW_TTxqT{FKih7jfzm`rq`Wi38+f2PJ1e#`68WLPs{0?3i z+b)M*ZFJ#087ZQQV~M>(5;tkf_+w5rBxX$u)~s73C-Ad`btC#&yIVp~n&qW|X-@uY z6X&HhXQD;8Ob%}$1z;8n=q*71M*cSIxMp-m`G^UZZxE8TFu{12iIAUkt8BpNkNw8R)Xdfv&1oju_D>xSO>3>}>dm)BdA=o3w#ZmN!= z?`O`^gkvF6RAFHc9djS$7pCl{tNt$eE0f_HAnsCj&8bnA%B&%~E;i`5(YolHFs(6B zrsr~#RFdK(b!!q-*xFq^zMgB?X~ogYF-){(MiOPwnH1!TO*7W4=9gqtIWfsY#_i5d5V=OE2NITdX)pQTUBHX}>*>Osw@hG-5|MDWqnR ziC0RLZ{PkV`TeMJ9Od^*r7<1`(M-eb+{wkI((H;)Yj2V<)AYt4blBVzZDkqfhFa-s zgFJNP^&OoTT`fMCZj82Fx6=1Ciiq2NDH$mi`RM4=(u!_UnpiaPov8IGX}jfc$MW?f zHO5bfbEPF5G-^&x_eg57XY+&jE#ykE^m~@wm{~aKmzBZCB$8b+G+ZtdUC~<5a;_&4 zM_!#G^r|=BB95NAn&%~`rdP@@Q$l~hx3?GWdL)iYlV9#-o|!MIicL77%_>NupG@@I zw~m+O%30{zX|mTOer2k6DkCXH?0AGw;i%T{>F`M}vU&RHl8w4(aB|&~JQlFdI&jJ` z(;1v4($ec=W!@0!if=l4LW+xcJrch#W0JT{c0MXHo%%>u?knS^xfw(3UT}+Tu8pID zhOpU#Zw0KliP`&<$5<*x76%zY9*N2b^lG>Jo|=*VzJ!%`MM|uDlo@{wHwg~!S5MoM zX07STa;5&&wmXsW6N8*;lu|b7-mE*aD_c5^8?|H0!L}`@(&p(KbolPimW5p@GM`FC zp@`$9r0tj&bz*Mbt6r7;BWbJsa%I6MC}u3FDr*d`>!-I$N1mP;n4B1qRP5m47;P80 zyR!?cvm--R&zGl}Nzz1I*RENSnK-W{>a4fvoJmJkRV1xHC|?bwbv((k8f%28#feE4 zIXo7M@>0%vEZM<(S!&N0z~#wAqg*oAE2SAJSjwh(Ee%d8L!ZcslRjs_w+VRcZ1|{2 zS95Nt@RXkq{fyH6#|TQ)aO6Lf>ONWj08{bW&sF~bLc&A;0H)G<9}2mX?vIi1P|fT3xu5dI@cTqXB)ucyOZI5J}=BX6VhoKia^W#JyeV{P<#KkGH)a9?3cuDBbA zZ@LV{{I2W6D^l_H$lTJBO9o6y+b`QD{{Z5JXhTnvoC#S`Zr2B`rc&sal8O|wl|;Le zjMh`ZYKv#2X|9`#M(^T^e4eB@>OnR=UxaQfQTV9I#XLW!2=&W85n6D^mTGD@lA{?( zc1TjyYe{%7Us2Auk7A&{UYGe|zEJAohX`U#(n8kP&x9z&8(J>?D8@>ogN`tcc^Z8l zF3U%DUt+DY(#_;)5%XrnerF?g+^j+(+VlG5;FKkpHA(p!ioGYt(T=p%dU}hseJz){ zm@|_L2a?|&3`EBxvAHvR(_ar3M^8=(C@Q37`dSAfM6wOwJdC zdLwLU;M=I)(ML`Z98}{4S(6-==|z6G-1H-MqqpF2_ZTcVZH=CV38!y9^ve&fCh!?n?*@UkaZEpW}$=&{*WDn$v81+uo1h|}!ohNN*Mde37h zed5d)E|#y7*wba1MRfAYlPMRu7dZ~vqPOx^hMb!1ctX_p%}Za=&`O5T_1r75tUYq7FU)^ZXT^nL3ln_5LuHq zNA8oTFAK@Fzf51Lk55r7p~^YaEf-j2r)Z|Eve506V}iPJUG%=bTkMaU@rty&Kw5e* zNkw5I)AUOY`!PYix{K|8P4$(DqjS!a?chsOI(?)zs&OZ^RdR;k1Mrzh!=g-AR9s9p z?+mP>ou+a&QmdgS%jt38_8pV27#wDWvR4Mj2I!}iM(E&hkeYZ!TSJRqvniR%Ty(Y1 zO!CiLFx3xXS`dGC8?(QLzax3Jj8AC+3YU``4fB+qDdho z#SJ0eUv^a)SSzJw?$K?hV~S%^BP6(V&7|YmF(u4c>Ftvi{?3_c@>5wKiY?_5k?JZX zK9?qmY(7`R!Ofe#DozmaD~gly%7R8`L-{b7dfKik_(FATVvA{4OWphp%ZQg|>2ldk zme)tPeo;eDEZV#F8bf!=FN#MkmOhW7)Vq?zVq-e9=h+KQHM5yWo~r)<;{)Y)Pjuu; zR`*HNNxslkA9g6umCHS8DUMnmxSMrhD6BT6HNoFr7aCwHRwEQyo)rKUzp~3ySivv=xn+z{>eBC-zSd>lLS--j_?HM%J zF&opk&MPR4pDcHH5)<=;N-o<-p|o*!H=cMXZE!2iydE73a%~sNDlJgmr6Zf6$GR$5 zHx`S$r-5B6c`h!~Wut3F#bKM98;S0iqb_Wz@KU)>PZ37%i*7OJXsQt$Q=(dWH>p1e zTi?oq@LsLXUSwe;mwvSt%4Ma8(QoC73E^dwi)$r5M@jVKu*PvrrVc|;_i zre>s9I&RSoNxO{IKW0xwa}33hno3G*Y`vKDpWPh5x=U6k&C^SI#G-H0#IG?YEjHt* zxkl)`_cYR8rmaz2V!#TW$y@Tug(1gEPIK`R{vu8qZQ?N(q)juj zqNu7X2%%ds!WV^>Zj!nj(&r;6N|mv$Osv_8WR+L3V;*`^ctutQ%%073vT%=)!gnX`PIvdqYW72>>q%B5iaeh(rD~CdjVUz7BGflkjR7##iW~rjH2^HgjIZ zWsk_yc5{QAx4^Mn8x~V5^qk;+qq%W?E2DU!yDen0s+wjUvA+!Gmx0^NSn*vF)4kHe zBc!GKpD#|SEXYxh+MZaoHq;@(DNR(S$Z54u(^gJRdbK2yBcHYeoR!N`Rc4e|=}ouc z9}y(ei)M^v=Yv^0-B^AR1-l!qlT(-JR81*yCuq^sSL16nw9>@0W}MrpMbal5#G`D4 zo2`=jiAVJ6M$;wUT2Bnonn|XqlhJX+vY6p4>S?iRLlcG?7OKB=eBC8!@^4YNO;bZk zN|_{xMXW_D6u3xn(`NOlVsGu{{4>@2H{`>*$tgIkjd#lz%9hGRx2@IP8=rU6611|4 zcxdz`#zvM*#PtMJBix_38=>^$SWb_Y`AWV)O3&4t&NqU;eUElDX%t`ok^<4YBaQx{Yk&zn@eukYXp2n(`02>lCRv?hTOcG zGplKhEN+hk({$j?DP7v8YiSxbR|=$$nwr@qY*f?J znLRd=Pbik3WHo#tQL%DuZKHIZB#Av8S;J27kxqN#;z&zdL5=(_u79PQHByUca^G!s z@L?v8QtfuI%ZI6U@>6wO+9@WiWm6qy%15~3`IZq^b%uP(UYDCAHQZFPnHJdGacoI8 zdbv00WueA@az!$w7B$@3kgeeMDI+sQBl5PmOH8`E2U*L{jBvQW~mq#Vl$Rv zku68eo(Czql(-`ZyPSokLX2rf7{2z+eM)kY;r66y>F!Om+FGRTq;zlYG$UE0Si_!)5kF#@isfT%EbzKA%&w4+ zmP(!@UXfBsuOdz2B=r;Y>F|kaHJNc^?F$jqQV*2vvKo{7qVUnDsM6cymAj15 zJr@+OE8NtC-`GdWXUtB`)0gl$Tcn4YsNiX}TS!xU6KR}oE@OtD3DY%J)->Wg92i1+ zT9Q@5HtXO204Rw^Rx@QzN-}7;Q=Xu1Vb+n!9w7cj$b3F{=JYhL@7x@+5rNymzB>e4F6zGB(;wYYg$Ax z<6c=wx<+0fVWhAq!;;$VY?ikPIz+3oI7_Sc?lh5o*-DhGZ8T*bsa1~OB{@1rpsZxa zsg22T!MWNQj*qzud^1v8yj7xa%uKp;NhvIv5KAagd_`Rn)UQn%v!w3YY;wB0cr@X7 zZC|+ro)T=Elxu3ER!J?b;R@15nrj?x7deg%Ng?BgY0CXKL$`^eQ%k`6II~Yty~JE? zV}o}JSZI`Nmug%RZQD`7ULrjHlm7sz2jw&?<0+07sS;^ispL+LR#@nkQlXbdQa9-~ ztBNAEu2tW;3!S6HMNXCAxVIfcX0ALw%(T$$B3Y)HPDpdNO(rh_-TVtll2zcOsJ<^5rt>D4K$xN z#ME+^400_dQ*Dfuwp&>(tn+4h9p;V)7L|D^6iTqn)gsjy!AV-^=__O!H88T#H7dd) z?$d)b)LT}B=Sim2Nwt|8k)H2UCzP^AGnGbEX)8iXS=*XsqurRIa`$;EX___VG7VK# z8i>@}Y)w85JymL|#i+8RsGL>pVuFzh?yZqeKB{AlVYE%em2#Dh`w#yBjnNIfxR56Y z<%y+qZg@##ZNm?PQ#gvv62r@}tTx86c6jN*h>g*{4W_tg+3_u3X&H8xfl4hRnoTom z%uuZ%liZt)hxfsSX)?y1aAB^k=Ej=iqp0DJ zDID5HPBVQUM2J(xl2^+{rM@DO2A$LhJIy*gz2ux7J=i3iZ*E&QJPHhj@e=16X?7=3 z#FkA+ZflcdrfIb4r@yR_c#oQD|w#;>tpC<|`s!sHNhJKhSAPk^cbQj+<|BJFYYPQx+ELWMyQU zZtQZr(k(69iOQ1A7>cdD5nC%HqSD3_Db^7O<(i7Sp8IKrLIGYPBO-$!(D6~P(o2s zVE@_x2mt~C0Y3o$0PZaz&L`xE^F<%XN9Tz1qxk~r5gf5%Y5xGGmRQ7=X2&MW8!w!4 z$|gL@U+CLOTQX+92)it@%hi@yW$?wFuMCWoztA?4wq?rX>2PCZmNs6~EWJ?-jx2=K zm)`Vd%G;zO#?IpSuZIl#Se^ac`8!oDSl;ZjxgFjZueSp zNO=d4b32aXxb8dHrbj6piSflg*%5ZH?e!Tuoh}X0EQ67M3L?l)k4-yO_Oi;NKQ8xV z%NV6{NJu>WV0>HeRoEP|-v^6fJbK{e5{lMoD)|NokoGMHDF6 z_|L>n93cT>KN;FMlwGS9wTSubUckjG-j1Ug7_FM?u_lvyk>{St$SnTguspKG%e z`=j+biPEiC8T%U(KPd8!cC>}2imfb-AC&y5q0xiThAs5-r(aX3{@ShB#xnM_g{Ct2 z^vpvRkrz@T?R`A%=J=vshRJb47Ua2f{`AGAtPbP!r0OhwUldEw(Dk9MYp^Q{C<~E>29?z2yXqG0KPlVu@ zmgF%Za$9Ri$LL&oXk4%ARg%Q1jZ>};0*NnUC8#?)PSdpQI}X#ej?rS&7lCoX4%q!{ zs;0%pWArpMFAR&}da_c|5g%L^lMWYl#p~;J5b`cLOVdSa&f?i@?i(3GA?92nn=s(7 zEM7joSXm`cjz!?Eb~nWsV{Y`wLCw*R3WEDA&ki{>*A`zSV_rAYWAT4)EG-g)Tqo#E z_E!g_Em1|7-+^lf_4}D3I1N+O{b@Z=(8sC}wBDgN6hk6<>80Yn|mL079EaJf;cMgzxRNBxQ}o>P(i9n50@RCv-Z6fU_H}(zg(w|AT&Ln> zWS^DvvSp4nY|YimZjj_y#KkLISI3Oav?ei0#o9a8MdX$?yrLaM;o{6)Y?rbUY?%KWxAhV+)6?{9Gs<7lRz!x)|r-oILZ zJDZcSulpNEo>pHt`WC4%!SYG6Fyk-kR~7NO{-RTU%S)B~F!jmB9f<5jE_3ztd`HmT z{A-RsUpn?=^jM)|$0hY&1THxK8Yr$2GWyhHMbVjxA|@G$p1z(>zp;)tAu3x$NTGhx zU52#vkyM|tf*;=qnAPbr%R*x3dQ4=zk9pVk>&06jsc?yn7IhXmBz?lnLU+Pb9%Jnk z>{Bf=Z@Bl8JxFT3Y!J76Q4a%RO`Qz-TRxP1NKv9MQXDM$qJ0SZT0XWbMEvo~5AW4V z*@_)8)7pK=zQRI8vZ(kTNwIYp(~=qz@2VVGG|=3ahDS4ANX7Y05Hm&ijGf$mDt zB~R1Dsyjj%4P1;S98?lA2^6VG(_`L{SvQ z22&b(nIyK!OS>-E_+^#9TO0oX9w^1#2uw^uWEiB*sU1wRR7ov1Hc9sv44G9@_3+EE z_~3g?PfB!0G54eHi1MMyy)lz@7p11sGG)HY*vBd&?Qz2CiRlPhNa;FC)82Vft;%XB zo>wnrGZeVu@-D*C7NR0sZ%vsSz2~2L_TegIW}ggRMug~3NJK=&HdxtZ8CQMf^X_9} zn6;1j2yxP4ViPQ}k4Y3x7Rf=PjM4WZ%Q4TrYCcH#8X7yHNQ{wXmRcJUBDBtwPZ5?D zhuhmjWF1RTM0{zXp~OjvNKui}&YdA^CHX{Mp{pm3(VGa>dyB~naYRV%qKX#Z7P}B) zM50P5nZ7mmh~nbu`%#OLi{pQ6=%hrC;d@*q*pH1$2x!TMGe%r8gZ44tl)RYnC?YW= zy9swA`{nRqcDB(&f|90Z`0pFF;P|){{{WGn;kfsR;@6ewW5(v`82&ndqEL!DDT`OZ z3-HSO7&g}2RFyHs<9&>IRJ$|kjJ%?M3m#7h%kW%ZVpt~=$Log^$mqw7K~ma6((d0i z_)jHvMYdvHw#J2~tZ-gXn?iPEl54sevRET8D4)cy;!7N(<$h3uo1|jIvBtKRkli6l zrOJiPxWHY6yK30`K{#h#Yv%M zk@v{^G~MGhzV zA!PpmqLO@9=(xQhZ!hb6#o6f%3L}CX8t#Z?ei`R$^IwADm(QUOC5uUEqEN9n0W|*r G5C7RClpeVN From 2512d3e0211be04326d3160bf16bed861c3b4bb6 Mon Sep 17 00:00:00 2001 From: Laurent Valdes Date: Mon, 21 Apr 2025 21:59:12 +0200 Subject: [PATCH 06/28] feat: use static files from gcs bucket --- clickplanet-webapp/Dioxus.toml | 14 ++------------ clickplanet-webapp/public/static/favicon.png | Bin 0 -> 1913 bytes .../src/app/components/earth/setup_webgpu.rs | 8 ++++++-- .../src/app/components/leaderboard.rs | 11 +++-------- .../src/app/components/settings.rs | 4 +--- clickplanet-webapp/src/main.rs | 2 +- 6 files changed, 13 insertions(+), 26 deletions(-) create mode 100644 clickplanet-webapp/public/static/favicon.png diff --git a/clickplanet-webapp/Dioxus.toml b/clickplanet-webapp/Dioxus.toml index e828210..8a71c0e 100644 --- a/clickplanet-webapp/Dioxus.toml +++ b/clickplanet-webapp/Dioxus.toml @@ -12,19 +12,9 @@ script = [] [web.resource] script = [] -[[web.resource.copy-dir]] -src = "public/static" -dest = "static" -[[web.resource.copy-dir]] -src = "public/styles" -dest = "styles" [web.resource.dev] script = [] -[[web.resource.dev.copy-dir]] -src = "public/static" -dest = "static" -[[web.resource.dev.copy-dir]] -src = "public/styles" -dest = "styles" +level = "z" +debug = false \ No newline at end of file diff --git a/clickplanet-webapp/public/static/favicon.png b/clickplanet-webapp/public/static/favicon.png new file mode 100644 index 0000000000000000000000000000000000000000..6b8eff1847a7447943f3034f39cf32953cd83967 GIT binary patch literal 1913 zcmV-<2Zs2GP)C0003sP)t-s00019 zm+M`e>|C4c|NsA7oa|C4c|NsA>)oB0!|6Q8vpwwqzpX*(m?4Q$U|NsC0|No!Q zX#fBJU7YNo)M%g6Xra|;pwwue&tP4g?EnA&|NsA=)Ms6t?EnA&T%7Fx|No%WX#fBJ z|NsC0|NsC0|5}>rU7YM)oa|o}*>bMKrq^-t`RQ${%edc;@Am%r{q@`L#>3>G zt=fIz^3c`nz0c~j*XH`5#q`PNs)xUtz2cY0-TAZ7_KUdkd#>+ssP1Q??SYj~JOBUy zJake{Qve{}fPkRCKp@}mVDAubK;O?G5bwW$e_s&KppcMXzrQe_aA03hFt3n*Pe3rw zudkqRP!R9$zmQN+Kz4m zG?01gZiI}NY%Y%CfkdrO1Tn5o`8be#aE*+CgjJv-RN;c;t-NXZI2FW&KFJ69Ny;Nd z7=R&+Umo>afMn*3l-`ZPQJx=xd40zPapu(Y^*BZ%UG)@L;wzx{v+5;S4=ee`c3)m>QOIygP;C_UT(>4%hKeUp0z)h^Cooxk z$gn4%JBes^Lm~5fUl1u?ZePh4v_9rAxpCBQ)tH2{O!khu?v~ z3}t#rjtp@dYR;r8;7Z6MLtF!>700xV)a%tolT84fCqumM)h6#5UXixbJHK+H-8Vpo zUQr-JEW!mXI*Kl+QtMuQgX7C`mLM;o$M(3ouv-nPun0kJLJ!X|y^SDkx6-3Zk*5Sn z{)=?{U7$n<++_oR^4J3aCoq7)Na1i?s1F`Oj38JpV-KJk769)M+F*t{Cjifx$W_D! zz&(U>gLg3-KnA#nP&RD>n)BHZ@#?{wADEy)gZsd9K*H`t4-Bx)bV9rfkk)ucax5@* zBznaREi8_?1hALUEFhs}&@xg12pQrQAfaVYY?`tFI}xqJf1C%7rJjBdK<@d6(*G$d zM6h{$xN&&=ZIhD#>_coL;I(9@IZA)azGUO5ognb*?`pP7tS!5?N z}rlP>#!)m=(iYECmh~qzY(66$Vw1WM(+gMu0|C;0CrsW-1e- zj#sh@kH~R5Ke7{2=xEj3Hfcyu|!0OSi)(z_fBawG>GW!Z_*r7@zOuks&5ZIe=<1!CoIbf9 zIDAZvT^~sW?q5?A(67IUk>v^LlbJA)=a zKAE}Rzh<5h1S3HGF*1F}PAyD_{8uWqG#uJrd37TRhyBuN00000NkvXXu0mjf7hJo= literal 0 HcmV?d00001 diff --git a/clickplanet-webapp/src/app/components/earth/setup_webgpu.rs b/clickplanet-webapp/src/app/components/earth/setup_webgpu.rs index 13bf70a..57df381 100644 --- a/clickplanet-webapp/src/app/components/earth/setup_webgpu.rs +++ b/clickplanet-webapp/src/app/components/earth/setup_webgpu.rs @@ -172,8 +172,12 @@ async fn create_render_pipeline( }, ], }); - // Load and downscale earth image to fit device limits - let mut img = image::load_from_memory(include_bytes!("../../../../public/static/earth/3_no_ice_clouds_16k.jpg")).expect("Failed to load earth image"); + // Fetch and downscale earth image via asset API + let image_url = format!("{}/earth/3_no_ice_clouds_16k.jpg", env!("CITYWARS_STATIC_SITE")); + let resp = Request::get(&image_url) + .send().await.expect("Failed to fetch earth image"); + let data = resp.binary().await.expect("Failed to read earth image bytes"); + let mut img = image::load_from_memory(&data).expect("Failed to decode earth image"); let max_dim = device.limits().max_texture_dimension_2d; let (w, h) = img.dimensions(); if w > max_dim || h > max_dim { diff --git a/clickplanet-webapp/src/app/components/leaderboard.rs b/clickplanet-webapp/src/app/components/leaderboard.rs index 4947a51..5e3df5a 100644 --- a/clickplanet-webapp/src/app/components/leaderboard.rs +++ b/clickplanet-webapp/src/app/components/leaderboard.rs @@ -18,15 +18,12 @@ pub struct LeaderboardProps { pub tiles_count: u32, } -// Component for displaying the leaderboard #[component] pub fn Leaderboard(props: LeaderboardProps) -> Element { let mut is_open = use_signal(|| true); - // Total number of tiles in the globe - matches the default in the TypeScript implementation - let total_tiles = props.tiles_count; // This would come from props.tiles_count in a real implementation + let total_tiles = props.tiles_count; - // In a full implementation, this would be fetched from an API let entries = use_signal(|| { let mut mock_data = vec![ LeaderboardEntry { @@ -80,14 +77,12 @@ pub fn Leaderboard(props: LeaderboardProps) -> Element { is_open.set(!is_open()); }; - let folder = asset!("public/static"); - rsx! { div { class: "leaderboard", div { class: "leaderboard-header", img { alt: "ClickPlanet logo", - src: format!("{folder}/favicon.png"), + src: format!("{}/favicon.png", env!("CITYWARS_STATIC_SITE")), width: "56px", height: "56px" } @@ -132,7 +127,7 @@ pub fn Leaderboard(props: LeaderboardProps) -> Element { td { colspan: "3", img { class: "country-flag", - src: format!("{folder}/countries/svg/{}.svg", entry.country.code.to_lowercase()), + src: format!("{}/countries/svg/{}.svg", env!("CITYWARS_STATIC_SITE"), entry.country.code.to_lowercase()), alt: entry.country.name.as_str(), width: "20px", height: "auto", diff --git a/clickplanet-webapp/src/app/components/settings.rs b/clickplanet-webapp/src/app/components/settings.rs index 995f16d..4e03f4f 100644 --- a/clickplanet-webapp/src/app/components/settings.rs +++ b/clickplanet-webapp/src/app/components/settings.rs @@ -40,8 +40,6 @@ pub fn Settings(props: SettingsProps) -> Element { CountryValue { code: "gb".to_string(), name: "United Kingdom".to_string() }, ]; - let folder = asset!("public/static"); - rsx! { ModalManager { open_by_default: false, @@ -49,7 +47,7 @@ pub fn Settings(props: SettingsProps) -> Element { button_props: BlockButtonProps { on_click: Callback::new(|_| {}), text: country.name.clone(), - image_url: format!("{}/countries/svg/{}.svg", folder, country.code.to_lowercase()), + image_url: format!("{}/countries/svg/{}.svg", env!("CITYWARS_STATIC_SITE"), country.code.to_lowercase()), class_name: Some("button-settings".to_string()), }, close_button_text: None, diff --git a/clickplanet-webapp/src/main.rs b/clickplanet-webapp/src/main.rs index 3bb7f97..6aef1a9 100644 --- a/clickplanet-webapp/src/main.rs +++ b/clickplanet-webapp/src/main.rs @@ -74,7 +74,7 @@ fn HomeScreen() -> Element { div { class: "center-align", img { alt: "ClickPlanet logo", - src: asset!("public/static/logo.svg"), + src: format!("{}/favicon.png", env!("CITYWARS_STATIC_SITE")), width: "64px", height: "auto" } From 1f0bafe2d7ec657807a4e86baf0e8a307edbcf5b Mon Sep 17 00:00:00 2001 From: Laurent Valdes Date: Mon, 5 May 2025 14:56:29 +0200 Subject: [PATCH 07/28] fix(webgpu): update API calls for canvas surface creation and rendering - Update wgpu API calls to match v25.0.0 including texture handling - Add proper routing with Dioxus router for better navigation - Fix environment variable handling for static assets - Improve debugging and code documentation --- .devcontainer/.devcontainer.json | 11 +++ .windsurfrules | 11 ++- .../src/app/components/buy_me_a_coffee.rs | 1 + .../src/app/components/discord_button.rs | 1 + .../app/components/earth/animation_loop.rs | 2 + .../src/app/components/earth/create_sphere.rs | 3 +- .../src/app/components/earth/setup_webgpu.rs | 16 +++-- .../app/components/earth/shader_validation.rs | 1 - .../src/app/components/modal.rs | 1 + .../src/app/components/on_load_modal.rs | 1 + .../src/backends/http_backend.rs | 5 +- clickplanet-webapp/src/main.rs | 69 ++++++++++++------- 12 files changed, 88 insertions(+), 34 deletions(-) create mode 100644 .devcontainer/.devcontainer.json diff --git a/.devcontainer/.devcontainer.json b/.devcontainer/.devcontainer.json new file mode 100644 index 0000000..47b7061 --- /dev/null +++ b/.devcontainer/.devcontainer.json @@ -0,0 +1,11 @@ +{ + "name": "Rust Development Environment", + "image": "mcr.microsoft.com/devcontainers/rust:latest", + "customizations": { + "vscode": { + "extensions": [ + "rust-lang.rust-analyzer" + ] + } + } +} \ No newline at end of file diff --git a/.windsurfrules b/.windsurfrules index e42e214..a1a68f9 100644 --- a/.windsurfrules +++ b/.windsurfrules @@ -41,7 +41,10 @@ And finally: Always use the edit tool. If it does not work, read the file first Make sure we use conventional commits Do not use interactive rebase (you are an LLM). If a git MCP server does rebases, use it. -Try to use trunk hot reload. It is does not work, instead of allocating a new port, kill the older trunk instances. +Try to use dioxus hot reload. It is does not work, instead of allocating a new port, use or kill the older dioxus instances. If it is just for building, just use cargo check or cargo compile. +Do not use docker build when building locally. + +CITYWARS_STATIC_SITE="https://storage.googleapis.com/lv-project-313715-clickwars-static/static" is the right environnement variable to place in front of RUSTFLAGS="--cfg=web_sys_unstable_apis" cargo build --target wasm32-unknown-unknown or dx serve command. the frontend implementation is here: ./original-frontend the backend implementation is here: ./original-backend @@ -51,4 +54,8 @@ Please read the documentation carefully. Don't put fucking useless comments that are exact duplicates of the code. -Briefly explain what you are doing instead of just calling the tools. \ No newline at end of file +Briefly explain what you are doing instead of just calling the tools. + +When compiling the webapp, the chain should be wasm, and not local machine one. + +When you launch a command use the Windsurf terminal API so that I can kill or stop a process by myself. \ No newline at end of file diff --git a/clickplanet-webapp/src/app/components/buy_me_a_coffee.rs b/clickplanet-webapp/src/app/components/buy_me_a_coffee.rs index a403d11..0c457ab 100644 --- a/clickplanet-webapp/src/app/components/buy_me_a_coffee.rs +++ b/clickplanet-webapp/src/app/components/buy_me_a_coffee.rs @@ -1,6 +1,7 @@ use dioxus::prelude::*; // In Dioxus 0.6.x, components are defined as regular functions +#[allow(non_snake_case)] pub fn BuyMeACoffee() -> Element { rsx!( a { diff --git a/clickplanet-webapp/src/app/components/discord_button.rs b/clickplanet-webapp/src/app/components/discord_button.rs index 2099abe..6f7e47b 100644 --- a/clickplanet-webapp/src/app/components/discord_button.rs +++ b/clickplanet-webapp/src/app/components/discord_button.rs @@ -8,6 +8,7 @@ pub struct DiscordButtonProps { } // Updated for Dioxus 0.6.x compatibility +#[allow(non_snake_case)] pub fn DiscordButton(props: DiscordButtonProps) -> Element { let message = props .message diff --git a/clickplanet-webapp/src/app/components/earth/animation_loop.rs b/clickplanet-webapp/src/app/components/earth/animation_loop.rs index 7d1d3e1..6ff0423 100644 --- a/clickplanet-webapp/src/app/components/earth/animation_loop.rs +++ b/clickplanet-webapp/src/app/components/earth/animation_loop.rs @@ -6,11 +6,13 @@ use glam::{Mat4, Vec3}; use crate::app::components::earth::setup_webgpu::{Uniforms, WebGpuContext}; +#[allow(dead_code)] pub struct RenderLoopContext { pub webgpu_context: WebGpuContext, pub rotation: Signal, } +#[allow(dead_code)] pub fn start_animation(context: RenderLoopContext) { info!("Starting WebGPU animation loop"); let WebGpuContext { diff --git a/clickplanet-webapp/src/app/components/earth/create_sphere.rs b/clickplanet-webapp/src/app/components/earth/create_sphere.rs index a43294f..46e8569 100644 --- a/clickplanet-webapp/src/app/components/earth/create_sphere.rs +++ b/clickplanet-webapp/src/app/components/earth/create_sphere.rs @@ -1,15 +1,16 @@ use std::f32::consts::PI; -use bytemuck::{Pod, Zeroable}; /// Vertex data for the globe mesh #[repr(C)] #[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)] +#[allow(dead_code)] pub struct Vertex { pub position: [f32; 3], pub normal: [f32; 3], } /// Create a UV sphere with the given radius and segment counts +#[allow(dead_code)] pub fn create_sphere(radius: f32, latitude_segments: u32, longitude_segments: u32) -> (Vec, Vec) { let mut vertices = Vec::new(); let mut indices = Vec::new(); diff --git a/clickplanet-webapp/src/app/components/earth/setup_webgpu.rs b/clickplanet-webapp/src/app/components/earth/setup_webgpu.rs index 57df381..0209de1 100644 --- a/clickplanet-webapp/src/app/components/earth/setup_webgpu.rs +++ b/clickplanet-webapp/src/app/components/earth/setup_webgpu.rs @@ -4,9 +4,8 @@ use wgpu::SurfaceTarget; use glam::Mat4; use log::{debug, info}; use dioxus::prelude::*; -use bytemuck::{Pod, Zeroable, cast_slice}; use wasm_bindgen_futures::spawn_local; -use gloo_timers::future::TimeoutFuture; +use gloo_net::http::Request; use image::{GenericImageView, imageops::FilterType}; use crate::app::components::earth::create_sphere::{Vertex, create_sphere}; @@ -17,11 +16,13 @@ use crate::app::components::earth::shader_validation::validate_shader_code; #[repr(C)] #[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)] +#[allow(dead_code)] pub struct Uniforms { pub mvp: [[f32; 4]; 4], } /// WebGPU rendering context containing all necessary components +#[allow(dead_code)] pub struct WebGpuContext { pub device: wgpu::Device, pub queue: wgpu::Queue, @@ -37,6 +38,7 @@ pub struct WebGpuContext { } /// Create a signal-based animation state for the globe +#[allow(dead_code)] pub fn use_animation_state() -> Signal { let rotation = use_signal(|| 0.0f32); @@ -56,6 +58,7 @@ pub fn use_animation_state() -> Signal { } /// Set up WebGPU and start the rendering loop +#[allow(dead_code)] pub async fn setup_scene(canvas: HtmlCanvasElement, rotation: Signal) { info!("Setting up WebGPU for globe rendering"); let width = canvas.client_width() as u32; @@ -84,6 +87,7 @@ pub async fn setup_scene(canvas: HtmlCanvasElement, rotation: Signal) { } /// Create WebGPU context: adapter, device, surface config, pipeline and resources +#[allow(dead_code)] async fn create_render_pipeline( instance: &wgpu::Instance, surface: wgpu::Surface<'static>, @@ -172,10 +176,12 @@ async fn create_render_pipeline( }, ], }); - // Fetch and downscale earth image via asset API let image_url = format!("{}/earth/3_no_ice_clouds_16k.jpg", env!("CITYWARS_STATIC_SITE")); + debug!("Attempting to fetch earth image from URL: {}", image_url); + let resp = Request::get(&image_url) .send().await.expect("Failed to fetch earth image"); + let data = resp.binary().await.expect("Failed to read earth image bytes"); let mut img = image::load_from_memory(&data).expect("Failed to decode earth image"); let max_dim = device.limits().max_texture_dimension_2d; @@ -202,9 +208,9 @@ async fn create_render_pipeline( view_formats: &[], }); queue.write_texture( - wgpu::ImageCopyTexture { texture: &texture, mip_level: 0, origin: Default::default(), aspect: wgpu::TextureAspect::All }, + wgpu::TexelCopyTextureInfo { texture: &texture, mip_level: 0, origin: Default::default(), aspect: wgpu::TextureAspect::All }, &rgba, - wgpu::ImageDataLayout { offset: 0, bytes_per_row: Some(4 * tex_w), rows_per_image: Some(tex_h) }, + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(4 * tex_w), rows_per_image: Some(tex_h) }, wgpu::Extent3d { width: tex_w, height: tex_h, depth_or_array_layers: 1 }, ); let texture_view = texture.create_view(&wgpu::TextureViewDescriptor::default()); diff --git a/clickplanet-webapp/src/app/components/earth/shader_validation.rs b/clickplanet-webapp/src/app/components/earth/shader_validation.rs index 542bf39..e56d291 100644 --- a/clickplanet-webapp/src/app/components/earth/shader_validation.rs +++ b/clickplanet-webapp/src/app/components/earth/shader_validation.rs @@ -1,4 +1,3 @@ -use log::info; /// Validates WGSL shader code by attempting to compile it #[cfg(test)] diff --git a/clickplanet-webapp/src/app/components/modal.rs b/clickplanet-webapp/src/app/components/modal.rs index 865f8ee..c0a11b5 100644 --- a/clickplanet-webapp/src/app/components/modal.rs +++ b/clickplanet-webapp/src/app/components/modal.rs @@ -11,6 +11,7 @@ pub struct ModalProps { pub close_button_text: Option, // Optional text for the close button } +#[allow(non_snake_case)] pub fn Modal(props: ModalProps) -> Element { rsx!( div { diff --git a/clickplanet-webapp/src/app/components/on_load_modal.rs b/clickplanet-webapp/src/app/components/on_load_modal.rs index 65e7b8a..b6bd2c9 100644 --- a/clickplanet-webapp/src/app/components/on_load_modal.rs +++ b/clickplanet-webapp/src/app/components/on_load_modal.rs @@ -10,6 +10,7 @@ pub struct OnLoadModalProps { } // Updated for Dioxus 0.6.x compatibility +#[allow(non_snake_case)] pub fn OnLoadModal(props: OnLoadModalProps) -> Element { let mut is_open = use_signal(|| true); // Local state to track modal visibility diff --git a/clickplanet-webapp/src/backends/http_backend.rs b/clickplanet-webapp/src/backends/http_backend.rs index 3dd544a..07f6b11 100644 --- a/clickplanet-webapp/src/backends/http_backend.rs +++ b/clickplanet-webapp/src/backends/http_backend.rs @@ -84,7 +84,7 @@ pub struct HTTPBackend { #[allow(dead_code)] impl HTTPBackend { - pub fn new(client: ClickServiceClient, batch_update_duration_ms: u64) -> Self { + pub fn new(client: ClickServiceClient, _batch_update_duration_ms: u64) -> Self { // Create a simplified version without the problematic timer let backend = Self { client, @@ -143,7 +143,7 @@ impl OwnershipsGetter for HTTPBackend { // Move the callback into an Arc once, outside the loop let callback = std::sync::Arc::new(callback); - for i in (1..max_index).step_by(batch_size) { + for _i in (1..max_index).step_by(batch_size) { // Clone the Arc for this iteration let callback_ref = callback.clone(); @@ -220,6 +220,7 @@ impl UpdatesListener for HTTPBackend { // WebAssembly-compatible WebSocket initialization +#[allow(dead_code)] fn init_websocket(url: &str, mut callback: Box)>) -> WebSocket { // Added 'mut' keyword to the callback parameter to fix mutable borrow error let ws = WebSocket::new(url).unwrap(); diff --git a/clickplanet-webapp/src/main.rs b/clickplanet-webapp/src/main.rs index 6aef1a9..4365d85 100644 --- a/clickplanet-webapp/src/main.rs +++ b/clickplanet-webapp/src/main.rs @@ -6,27 +6,26 @@ mod app; mod backends; fn main() { - console_log::init_with_level(log::Level::Debug).expect("Unable to initialize console_log"); + console_log::init_with_level(log::Level::Info).expect("Unable to initialize console_log"); launch(App); - } -// Define app routes -#[derive(Clone, PartialEq)] +// Define app routes with Routable trait +#[derive(Routable, Clone, PartialEq)] enum Route { + #[route("/")] Home {}, - About {}, + + // Fallback route for when no other routes match + #[route("/:..segments")] + NotFound { segments: Vec }, } - +// Root app component that sets up the router +#[allow(non_snake_case)] fn App() -> Element { - let mut current_route = use_signal(|| Route::Home {}); - - let navigate = move |route: Route| { - current_route.set(route); - }; rsx! { document::Link { rel: "icon", href: asset!("public/static/favicon.png") } @@ -39,18 +38,18 @@ fn App() -> Element { Stylesheet { href: asset!("public/styles/About.css") } Stylesheet { href: asset!("public/styles/Leaderboard.css") } Stylesheet { href: asset!("public/styles/Menu.css") } + Stylesheet { href: asset!("public/styles/rust-specific.css") } div { class: "content", - match current_route() { - Route::Home {} => rsx! { HomeScreen {} }, - Route::About {} => rsx! { AboutScreen {} }, - } + // Router uses the Route enum to handle URL-based routing + Router:: {} } } } -// Updated for Dioxus 0.6.x compatibility -fn HomeScreen() -> Element { +// Home component with the globe and main UI +#[component] +fn Home() -> Element { let mut show_welcome_modal = use_signal(|| true); // Manage country state here, similar to the original TypeScript implementation @@ -90,7 +89,7 @@ fn HomeScreen() -> Element { } } - app::components::earth::globe::globe {} + // app::components::earth::globe::globe {} div { class: "menu", app::components::leaderboard::Leaderboard {} @@ -109,19 +108,43 @@ fn HomeScreen() -> Element { } } -fn AboutScreen() -> Element { +#[component] +fn About() -> Element { rsx! { div { class: "about-page", h1 { "About ClickPlanet" } p { "ClickPlanet is a real-time collaborative globe where players from around the world can claim hexagonal territories for their countries." } p { "This is a Rust/WebAssembly implementation of the original ClickPlanet game." } button { - onclick: move |_| { - // Manual navigation logic - // Would normally use Link component - }, + onclick: move |_| { router().push(Route::Home {}); }, "Return to the globe" } + + + } + } +} + + +// 404 Not Found component +#[component] +fn NotFound(segments: Vec) -> Element { + let url_path = if segments.is_empty() { + "/".to_string() + } else { + format!("/{}", segments.join("/")) + }; + + rsx! { + div { class: "not-found", + h1 { "Page Not Found" } + p { "The page you're looking for doesn't exist." } + p { + "Requested URL: {url_path}" + } + Link { to: Route::Home {}, + button { "Return Home" } + } } } } From a7f642201613d5504278ce4668251d75c29653d8 Mon Sep 17 00:00:00 2001 From: Laurent Valdes Date: Mon, 5 May 2025 15:50:59 +0200 Subject: [PATCH 08/28] fix(webapp): proper Three.js integration with wasm-bindgen --- .windsurfrules | 6 +- Cargo.lock | 1 + clickplanet-webapp/Cargo.toml | 2 + clickplanet-webapp/public/js/OrbitControls.js | 1860 ++ clickplanet-webapp/public/js/three.module.js | 18021 ++++++++++++++++ .../src/app/components/earth/globe.rs | 53 +- .../src/app/components/earth/mod.rs | 6 +- .../app/components/earth/three_js/bindings.rs | 155 + .../app/components/earth/three_js/globe.rs | 279 + .../src/app/components/earth/three_js/mod.rs | 66 + .../earth/{ => wgpu}/animation_loop.rs | 2 +- .../earth/{ => wgpu}/create_sphere.rs | 0 .../earth/{ => wgpu}/earth_textured.wgsl | 0 .../src/app/components/earth/wgpu/mod.rs | 9 + .../earth/{ => wgpu}/setup_webgpu.rs | 4 +- .../earth/{ => wgpu}/shader_validation.rs | 0 clickplanet-webapp/src/main.rs | 2 +- 17 files changed, 20411 insertions(+), 55 deletions(-) create mode 100644 clickplanet-webapp/public/js/OrbitControls.js create mode 100644 clickplanet-webapp/public/js/three.module.js create mode 100644 clickplanet-webapp/src/app/components/earth/three_js/bindings.rs create mode 100644 clickplanet-webapp/src/app/components/earth/three_js/globe.rs create mode 100644 clickplanet-webapp/src/app/components/earth/three_js/mod.rs rename clickplanet-webapp/src/app/components/earth/{ => wgpu}/animation_loop.rs (98%) rename clickplanet-webapp/src/app/components/earth/{ => wgpu}/create_sphere.rs (100%) rename clickplanet-webapp/src/app/components/earth/{ => wgpu}/earth_textured.wgsl (100%) create mode 100644 clickplanet-webapp/src/app/components/earth/wgpu/mod.rs rename clickplanet-webapp/src/app/components/earth/{ => wgpu}/setup_webgpu.rs (98%) rename clickplanet-webapp/src/app/components/earth/{ => wgpu}/shader_validation.rs (100%) diff --git a/.windsurfrules b/.windsurfrules index a1a68f9..ec4656a 100644 --- a/.windsurfrules +++ b/.windsurfrules @@ -58,4 +58,8 @@ Briefly explain what you are doing instead of just calling the tools. When compiling the webapp, the chain should be wasm, and not local machine one. -When you launch a command use the Windsurf terminal API so that I can kill or stop a process by myself. \ No newline at end of file +When you launch a command use the Windsurf terminal API so that I can kill or stop a process by myself. + +When downloading a caego or js or sbt dependency, check the latest one using your browser tools, before guessing. Your memory is not up to date. + +When I say, read the public docs, or review the public docs, you have to do it and use the fucking documentation or the source code of the project. \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock index ddd2062..095b317 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -940,6 +940,7 @@ dependencies = [ "gloo", "gloo-net 0.6.0", "gloo-timers", + "gloo-utils", "image", "js-sys", "lazy_static", diff --git a/clickplanet-webapp/Cargo.toml b/clickplanet-webapp/Cargo.toml index 3e2f099..840acef 100644 --- a/clickplanet-webapp/Cargo.toml +++ b/clickplanet-webapp/Cargo.toml @@ -61,6 +61,8 @@ wgpu = { version = "25.0.0", features = ["webgl", "webgpu", "wgsl"], default-fea bytemuck = { version = "1.14", features = ["derive"] } raw-window-handle = "0.6.0" gloo-timers = { version = "0.3.0", features = ["futures"] } +gloo-utils = "0.2.0" + # Enable/disable features based on target [target.'cfg(not(target_arch = "wasm32"))'.dependencies] diff --git a/clickplanet-webapp/public/js/OrbitControls.js b/clickplanet-webapp/public/js/OrbitControls.js new file mode 100644 index 0000000..eea2670 --- /dev/null +++ b/clickplanet-webapp/public/js/OrbitControls.js @@ -0,0 +1,1860 @@ +import { + Controls, + MOUSE, + Quaternion, + Spherical, + TOUCH, + Vector2, + Vector3, + Plane, + Ray, + MathUtils +} from 'three'; + +/** + * Fires when the camera has been transformed by the controls. + * + * @event OrbitControls#change + * @type {Object} + */ +const _changeEvent = { type: 'change' }; + +/** + * Fires when an interaction was initiated. + * + * @event OrbitControls#start + * @type {Object} + */ +const _startEvent = { type: 'start' }; + +/** + * Fires when an interaction has finished. + * + * @event OrbitControls#end + * @type {Object} + */ +const _endEvent = { type: 'end' }; + +const _ray = new Ray(); +const _plane = new Plane(); +const _TILT_LIMIT = Math.cos( 70 * MathUtils.DEG2RAD ); + +const _v = new Vector3(); +const _twoPI = 2 * Math.PI; + +const _STATE = { + NONE: - 1, + ROTATE: 0, + DOLLY: 1, + PAN: 2, + TOUCH_ROTATE: 3, + TOUCH_PAN: 4, + TOUCH_DOLLY_PAN: 5, + TOUCH_DOLLY_ROTATE: 6 +}; +const _EPS = 0.000001; + + +/** + * Orbit controls allow the camera to orbit around a target. + * + * OrbitControls performs orbiting, dollying (zooming), and panning. Unlike {@link TrackballControls}, + * it maintains the "up" direction `object.up` (+Y by default). + * + * - Orbit: Left mouse / touch: one-finger move. + * - Zoom: Middle mouse, or mousewheel / touch: two-finger spread or squish. + * - Pan: Right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move. + * + * ```js + * const controls = new OrbitControls( camera, renderer.domElement ); + * + * // controls.update() must be called after any manual changes to the camera's transform + * camera.position.set( 0, 20, 100 ); + * controls.update(); + * + * function animate() { + * + * // required if controls.enableDamping or controls.autoRotate are set to true + * controls.update(); + * + * renderer.render( scene, camera ); + * + * } + * ``` + * + * @augments Controls + * @three_import import { OrbitControls } from 'three/addons/controls/OrbitControls.js'; + */ +class OrbitControls extends Controls { + + /** + * Constructs a new controls instance. + * + * @param {Object3D} object - The object that is managed by the controls. + * @param {?HTMLDOMElement} domElement - The HTML element used for event listeners. + */ + constructor( object, domElement = null ) { + + super( object, domElement ); + + this.state = _STATE.NONE; + + /** + * The focus point of the controls, the `object` orbits around this. + * It can be updated manually at any point to change the focus of the controls. + * + * @type {Vector3} + */ + this.target = new Vector3(); + + /** + * The focus point of the `minTargetRadius` and `maxTargetRadius` limits. + * It can be updated manually at any point to change the center of interest + * for the `target`. + * + * @type {Vector3} + */ + this.cursor = new Vector3(); + + /** + * How far you can dolly in (perspective camera only). + * + * @type {number} + * @default 0 + */ + this.minDistance = 0; + + /** + * How far you can dolly out (perspective camera only). + * + * @type {number} + * @default Infinity + */ + this.maxDistance = Infinity; + + /** + * How far you can zoom in (orthographic camera only). + * + * @type {number} + * @default 0 + */ + this.minZoom = 0; + + /** + * How far you can zoom out (orthographic camera only). + * + * @type {number} + * @default Infinity + */ + this.maxZoom = Infinity; + + /** + * How close you can get the target to the 3D `cursor`. + * + * @type {number} + * @default 0 + */ + this.minTargetRadius = 0; + + /** + * How far you can move the target from the 3D `cursor`. + * + * @type {number} + * @default Infinity + */ + this.maxTargetRadius = Infinity; + + /** + * How far you can orbit vertically, lower limit. Range is `[0, Math.PI]` radians. + * + * @type {number} + * @default 0 + */ + this.minPolarAngle = 0; + + /** + * How far you can orbit vertically, upper limit. Range is `[0, Math.PI]` radians. + * + * @type {number} + * @default Math.PI + */ + this.maxPolarAngle = Math.PI; + + /** + * How far you can orbit horizontally, lower limit. If set, the interval `[ min, max ]` + * must be a sub-interval of `[ - 2 PI, 2 PI ]`, with `( max - min < 2 PI )`. + * + * @type {number} + * @default -Infinity + */ + this.minAzimuthAngle = - Infinity; + + /** + * How far you can orbit horizontally, upper limit. If set, the interval `[ min, max ]` + * must be a sub-interval of `[ - 2 PI, 2 PI ]`, with `( max - min < 2 PI )`. + * + * @type {number} + * @default -Infinity + */ + this.maxAzimuthAngle = Infinity; + + /** + * Set to `true` to enable damping (inertia), which can be used to give a sense of weight + * to the controls. Note that if this is enabled, you must call `update()` in your animation + * loop. + * + * @type {boolean} + * @default false + */ + this.enableDamping = false; + + /** + * The damping inertia used if `enableDamping` is set to `true`. + * + * Note that for this to work, you must call `update()` in your animation loop. + * + * @type {number} + * @default 0.05 + */ + this.dampingFactor = 0.05; + + /** + * Enable or disable zooming (dollying) of the camera. + * + * @type {boolean} + * @default true + */ + this.enableZoom = true; + + /** + * Speed of zooming / dollying. + * + * @type {number} + * @default 1 + */ + this.zoomSpeed = 1.0; + + /** + * Enable or disable horizontal and vertical rotation of the camera. + * + * Note that it is possible to disable a single axis by setting the min and max of the + * `minPolarAngle` or `minAzimuthAngle` to the same value, which will cause the vertical + * or horizontal rotation to be fixed at that value. + * + * @type {boolean} + * @default true + */ + this.enableRotate = true; + + /** + * Speed of rotation. + * + * @type {number} + * @default 1 + */ + this.rotateSpeed = 1.0; + + /** + * How fast to rotate the camera when the keyboard is used. + * + * @type {number} + * @default 1 + */ + this.keyRotateSpeed = 1.0; + + /** + * Enable or disable camera panning. + * + * @type {boolean} + * @default true + */ + this.enablePan = true; + + /** + * Speed of panning. + * + * @type {number} + * @default 1 + */ + this.panSpeed = 1.0; + + /** + * Defines how the camera's position is translated when panning. If `true`, the camera pans + * in screen space. Otherwise, the camera pans in the plane orthogonal to the camera's up + * direction. + * + * @type {boolean} + * @default true + */ + this.screenSpacePanning = true; + + /** + * How fast to pan the camera when the keyboard is used in + * pixels per keypress. + * + * @type {number} + * @default 7 + */ + this.keyPanSpeed = 7.0; + + /** + * Setting this property to `true` allows to zoom to the cursor's position. + * + * @type {boolean} + * @default false + */ + this.zoomToCursor = false; + + /** + * Set to true to automatically rotate around the target + * + * Note that if this is enabled, you must call `update()` in your animation loop. + * If you want the auto-rotate speed to be independent of the frame rate (the refresh + * rate of the display), you must pass the time `deltaTime`, in seconds, to `update()`. + * + * @type {boolean} + * @default false + */ + this.autoRotate = false; + + /** + * How fast to rotate around the target if `autoRotate` is `true`. The default equates to 30 seconds + * per orbit at 60fps. + * + * Note that if `autoRotate` is enabled, you must call `update()` in your animation loop. + * + * @type {number} + * @default 2 + */ + this.autoRotateSpeed = 2.0; + + /** + * This object contains references to the keycodes for controlling camera panning. + * + * ```js + * controls.keys = { + * LEFT: 'ArrowLeft', //left arrow + * UP: 'ArrowUp', // up arrow + * RIGHT: 'ArrowRight', // right arrow + * BOTTOM: 'ArrowDown' // down arrow + * } + * ``` + * @type {Object} + */ + this.keys = { LEFT: 'ArrowLeft', UP: 'ArrowUp', RIGHT: 'ArrowRight', BOTTOM: 'ArrowDown' }; + + /** + * This object contains references to the mouse actions used by the controls. + * + * ```js + * controls.mouseButtons = { + * LEFT: THREE.MOUSE.ROTATE, + * MIDDLE: THREE.MOUSE.DOLLY, + * RIGHT: THREE.MOUSE.PAN + * } + * ``` + * @type {Object} + */ + this.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN }; + + /** + * This object contains references to the touch actions used by the controls. + * + * ```js + * controls.mouseButtons = { + * ONE: THREE.TOUCH.ROTATE, + * TWO: THREE.TOUCH.DOLLY_PAN + * } + * ``` + * @type {Object} + */ + this.touches = { ONE: TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN }; + + /** + * Used internally by `saveState()` and `reset()`. + * + * @type {Vector3} + */ + this.target0 = this.target.clone(); + + /** + * Used internally by `saveState()` and `reset()`. + * + * @type {Vector3} + */ + this.position0 = this.object.position.clone(); + + /** + * Used internally by `saveState()` and `reset()`. + * + * @type {number} + */ + this.zoom0 = this.object.zoom; + + // the target DOM element for key events + this._domElementKeyEvents = null; + + // internals + + this._lastPosition = new Vector3(); + this._lastQuaternion = new Quaternion(); + this._lastTargetPosition = new Vector3(); + + // so camera.up is the orbit axis + this._quat = new Quaternion().setFromUnitVectors( object.up, new Vector3( 0, 1, 0 ) ); + this._quatInverse = this._quat.clone().invert(); + + // current position in spherical coordinates + this._spherical = new Spherical(); + this._sphericalDelta = new Spherical(); + + this._scale = 1; + this._panOffset = new Vector3(); + + this._rotateStart = new Vector2(); + this._rotateEnd = new Vector2(); + this._rotateDelta = new Vector2(); + + this._panStart = new Vector2(); + this._panEnd = new Vector2(); + this._panDelta = new Vector2(); + + this._dollyStart = new Vector2(); + this._dollyEnd = new Vector2(); + this._dollyDelta = new Vector2(); + + this._dollyDirection = new Vector3(); + this._mouse = new Vector2(); + this._performCursorZoom = false; + + this._pointers = []; + this._pointerPositions = {}; + + this._controlActive = false; + + // event listeners + + this._onPointerMove = onPointerMove.bind( this ); + this._onPointerDown = onPointerDown.bind( this ); + this._onPointerUp = onPointerUp.bind( this ); + this._onContextMenu = onContextMenu.bind( this ); + this._onMouseWheel = onMouseWheel.bind( this ); + this._onKeyDown = onKeyDown.bind( this ); + + this._onTouchStart = onTouchStart.bind( this ); + this._onTouchMove = onTouchMove.bind( this ); + + this._onMouseDown = onMouseDown.bind( this ); + this._onMouseMove = onMouseMove.bind( this ); + + this._interceptControlDown = interceptControlDown.bind( this ); + this._interceptControlUp = interceptControlUp.bind( this ); + + // + + if ( this.domElement !== null ) { + + this.connect( this.domElement ); + + } + + this.update(); + + } + + connect( element ) { + + super.connect( element ); + + this.domElement.addEventListener( 'pointerdown', this._onPointerDown ); + this.domElement.addEventListener( 'pointercancel', this._onPointerUp ); + + this.domElement.addEventListener( 'contextmenu', this._onContextMenu ); + this.domElement.addEventListener( 'wheel', this._onMouseWheel, { passive: false } ); + + const document = this.domElement.getRootNode(); // offscreen canvas compatibility + document.addEventListener( 'keydown', this._interceptControlDown, { passive: true, capture: true } ); + + this.domElement.style.touchAction = 'none'; // disable touch scroll + + } + + disconnect() { + + this.domElement.removeEventListener( 'pointerdown', this._onPointerDown ); + this.domElement.removeEventListener( 'pointermove', this._onPointerMove ); + this.domElement.removeEventListener( 'pointerup', this._onPointerUp ); + this.domElement.removeEventListener( 'pointercancel', this._onPointerUp ); + + this.domElement.removeEventListener( 'wheel', this._onMouseWheel ); + this.domElement.removeEventListener( 'contextmenu', this._onContextMenu ); + + this.stopListenToKeyEvents(); + + const document = this.domElement.getRootNode(); // offscreen canvas compatibility + document.removeEventListener( 'keydown', this._interceptControlDown, { capture: true } ); + + this.domElement.style.touchAction = 'auto'; + + } + + dispose() { + + this.disconnect(); + + } + + /** + * Get the current vertical rotation, in radians. + * + * @return {number} The current vertical rotation, in radians. + */ + getPolarAngle() { + + return this._spherical.phi; + + } + + /** + * Get the current horizontal rotation, in radians. + * + * @return {number} The current horizontal rotation, in radians. + */ + getAzimuthalAngle() { + + return this._spherical.theta; + + } + + /** + * Returns the distance from the camera to the target. + * + * @return {number} The distance from the camera to the target. + */ + getDistance() { + + return this.object.position.distanceTo( this.target ); + + } + + /** + * Adds key event listeners to the given DOM element. + * `window` is a recommended argument for using this method. + * + * @param {HTMLDOMElement} domElement - The DOM element + */ + listenToKeyEvents( domElement ) { + + domElement.addEventListener( 'keydown', this._onKeyDown ); + this._domElementKeyEvents = domElement; + + } + + /** + * Removes the key event listener previously defined with `listenToKeyEvents()`. + */ + stopListenToKeyEvents() { + + if ( this._domElementKeyEvents !== null ) { + + this._domElementKeyEvents.removeEventListener( 'keydown', this._onKeyDown ); + this._domElementKeyEvents = null; + + } + + } + + /** + * Save the current state of the controls. This can later be recovered with `reset()`. + */ + saveState() { + + this.target0.copy( this.target ); + this.position0.copy( this.object.position ); + this.zoom0 = this.object.zoom; + + } + + /** + * Reset the controls to their state from either the last time the `saveState()` + * was called, or the initial state. + */ + reset() { + + this.target.copy( this.target0 ); + this.object.position.copy( this.position0 ); + this.object.zoom = this.zoom0; + + this.object.updateProjectionMatrix(); + this.dispatchEvent( _changeEvent ); + + this.update(); + + this.state = _STATE.NONE; + + } + + update( deltaTime = null ) { + + const position = this.object.position; + + _v.copy( position ).sub( this.target ); + + // rotate offset to "y-axis-is-up" space + _v.applyQuaternion( this._quat ); + + // angle from z-axis around y-axis + this._spherical.setFromVector3( _v ); + + if ( this.autoRotate && this.state === _STATE.NONE ) { + + this._rotateLeft( this._getAutoRotationAngle( deltaTime ) ); + + } + + if ( this.enableDamping ) { + + this._spherical.theta += this._sphericalDelta.theta * this.dampingFactor; + this._spherical.phi += this._sphericalDelta.phi * this.dampingFactor; + + } else { + + this._spherical.theta += this._sphericalDelta.theta; + this._spherical.phi += this._sphericalDelta.phi; + + } + + // restrict theta to be between desired limits + + let min = this.minAzimuthAngle; + let max = this.maxAzimuthAngle; + + if ( isFinite( min ) && isFinite( max ) ) { + + if ( min < - Math.PI ) min += _twoPI; else if ( min > Math.PI ) min -= _twoPI; + + if ( max < - Math.PI ) max += _twoPI; else if ( max > Math.PI ) max -= _twoPI; + + if ( min <= max ) { + + this._spherical.theta = Math.max( min, Math.min( max, this._spherical.theta ) ); + + } else { + + this._spherical.theta = ( this._spherical.theta > ( min + max ) / 2 ) ? + Math.max( min, this._spherical.theta ) : + Math.min( max, this._spherical.theta ); + + } + + } + + // restrict phi to be between desired limits + this._spherical.phi = Math.max( this.minPolarAngle, Math.min( this.maxPolarAngle, this._spherical.phi ) ); + + this._spherical.makeSafe(); + + + // move target to panned location + + if ( this.enableDamping === true ) { + + this.target.addScaledVector( this._panOffset, this.dampingFactor ); + + } else { + + this.target.add( this._panOffset ); + + } + + // Limit the target distance from the cursor to create a sphere around the center of interest + this.target.sub( this.cursor ); + this.target.clampLength( this.minTargetRadius, this.maxTargetRadius ); + this.target.add( this.cursor ); + + let zoomChanged = false; + // adjust the camera position based on zoom only if we're not zooming to the cursor or if it's an ortho camera + // we adjust zoom later in these cases + if ( this.zoomToCursor && this._performCursorZoom || this.object.isOrthographicCamera ) { + + this._spherical.radius = this._clampDistance( this._spherical.radius ); + + } else { + + const prevRadius = this._spherical.radius; + this._spherical.radius = this._clampDistance( this._spherical.radius * this._scale ); + zoomChanged = prevRadius != this._spherical.radius; + + } + + _v.setFromSpherical( this._spherical ); + + // rotate offset back to "camera-up-vector-is-up" space + _v.applyQuaternion( this._quatInverse ); + + position.copy( this.target ).add( _v ); + + this.object.lookAt( this.target ); + + if ( this.enableDamping === true ) { + + this._sphericalDelta.theta *= ( 1 - this.dampingFactor ); + this._sphericalDelta.phi *= ( 1 - this.dampingFactor ); + + this._panOffset.multiplyScalar( 1 - this.dampingFactor ); + + } else { + + this._sphericalDelta.set( 0, 0, 0 ); + + this._panOffset.set( 0, 0, 0 ); + + } + + // adjust camera position + if ( this.zoomToCursor && this._performCursorZoom ) { + + let newRadius = null; + if ( this.object.isPerspectiveCamera ) { + + // move the camera down the pointer ray + // this method avoids floating point error + const prevRadius = _v.length(); + newRadius = this._clampDistance( prevRadius * this._scale ); + + const radiusDelta = prevRadius - newRadius; + this.object.position.addScaledVector( this._dollyDirection, radiusDelta ); + this.object.updateMatrixWorld(); + + zoomChanged = !! radiusDelta; + + } else if ( this.object.isOrthographicCamera ) { + + // adjust the ortho camera position based on zoom changes + const mouseBefore = new Vector3( this._mouse.x, this._mouse.y, 0 ); + mouseBefore.unproject( this.object ); + + const prevZoom = this.object.zoom; + this.object.zoom = Math.max( this.minZoom, Math.min( this.maxZoom, this.object.zoom / this._scale ) ); + this.object.updateProjectionMatrix(); + + zoomChanged = prevZoom !== this.object.zoom; + + const mouseAfter = new Vector3( this._mouse.x, this._mouse.y, 0 ); + mouseAfter.unproject( this.object ); + + this.object.position.sub( mouseAfter ).add( mouseBefore ); + this.object.updateMatrixWorld(); + + newRadius = _v.length(); + + } else { + + console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled.' ); + this.zoomToCursor = false; + + } + + // handle the placement of the target + if ( newRadius !== null ) { + + if ( this.screenSpacePanning ) { + + // position the orbit target in front of the new camera position + this.target.set( 0, 0, - 1 ) + .transformDirection( this.object.matrix ) + .multiplyScalar( newRadius ) + .add( this.object.position ); + + } else { + + // get the ray and translation plane to compute target + _ray.origin.copy( this.object.position ); + _ray.direction.set( 0, 0, - 1 ).transformDirection( this.object.matrix ); + + // if the camera is 20 degrees above the horizon then don't adjust the focus target to avoid + // extremely large values + if ( Math.abs( this.object.up.dot( _ray.direction ) ) < _TILT_LIMIT ) { + + this.object.lookAt( this.target ); + + } else { + + _plane.setFromNormalAndCoplanarPoint( this.object.up, this.target ); + _ray.intersectPlane( _plane, this.target ); + + } + + } + + } + + } else if ( this.object.isOrthographicCamera ) { + + const prevZoom = this.object.zoom; + this.object.zoom = Math.max( this.minZoom, Math.min( this.maxZoom, this.object.zoom / this._scale ) ); + + if ( prevZoom !== this.object.zoom ) { + + this.object.updateProjectionMatrix(); + zoomChanged = true; + + } + + } + + this._scale = 1; + this._performCursorZoom = false; + + // update condition is: + // min(camera displacement, camera rotation in radians)^2 > EPS + // using small-angle approximation cos(x/2) = 1 - x^2 / 8 + + if ( zoomChanged || + this._lastPosition.distanceToSquared( this.object.position ) > _EPS || + 8 * ( 1 - this._lastQuaternion.dot( this.object.quaternion ) ) > _EPS || + this._lastTargetPosition.distanceToSquared( this.target ) > _EPS ) { + + this.dispatchEvent( _changeEvent ); + + this._lastPosition.copy( this.object.position ); + this._lastQuaternion.copy( this.object.quaternion ); + this._lastTargetPosition.copy( this.target ); + + return true; + + } + + return false; + + } + + _getAutoRotationAngle( deltaTime ) { + + if ( deltaTime !== null ) { + + return ( _twoPI / 60 * this.autoRotateSpeed ) * deltaTime; + + } else { + + return _twoPI / 60 / 60 * this.autoRotateSpeed; + + } + + } + + _getZoomScale( delta ) { + + const normalizedDelta = Math.abs( delta * 0.01 ); + return Math.pow( 0.95, this.zoomSpeed * normalizedDelta ); + + } + + _rotateLeft( angle ) { + + this._sphericalDelta.theta -= angle; + + } + + _rotateUp( angle ) { + + this._sphericalDelta.phi -= angle; + + } + + _panLeft( distance, objectMatrix ) { + + _v.setFromMatrixColumn( objectMatrix, 0 ); // get X column of objectMatrix + _v.multiplyScalar( - distance ); + + this._panOffset.add( _v ); + + } + + _panUp( distance, objectMatrix ) { + + if ( this.screenSpacePanning === true ) { + + _v.setFromMatrixColumn( objectMatrix, 1 ); + + } else { + + _v.setFromMatrixColumn( objectMatrix, 0 ); + _v.crossVectors( this.object.up, _v ); + + } + + _v.multiplyScalar( distance ); + + this._panOffset.add( _v ); + + } + + // deltaX and deltaY are in pixels; right and down are positive + _pan( deltaX, deltaY ) { + + const element = this.domElement; + + if ( this.object.isPerspectiveCamera ) { + + // perspective + const position = this.object.position; + _v.copy( position ).sub( this.target ); + let targetDistance = _v.length(); + + // half of the fov is center to top of screen + targetDistance *= Math.tan( ( this.object.fov / 2 ) * Math.PI / 180.0 ); + + // we use only clientHeight here so aspect ratio does not distort speed + this._panLeft( 2 * deltaX * targetDistance / element.clientHeight, this.object.matrix ); + this._panUp( 2 * deltaY * targetDistance / element.clientHeight, this.object.matrix ); + + } else if ( this.object.isOrthographicCamera ) { + + // orthographic + this._panLeft( deltaX * ( this.object.right - this.object.left ) / this.object.zoom / element.clientWidth, this.object.matrix ); + this._panUp( deltaY * ( this.object.top - this.object.bottom ) / this.object.zoom / element.clientHeight, this.object.matrix ); + + } else { + + // camera neither orthographic nor perspective + console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' ); + this.enablePan = false; + + } + + } + + _dollyOut( dollyScale ) { + + if ( this.object.isPerspectiveCamera || this.object.isOrthographicCamera ) { + + this._scale /= dollyScale; + + } else { + + console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' ); + this.enableZoom = false; + + } + + } + + _dollyIn( dollyScale ) { + + if ( this.object.isPerspectiveCamera || this.object.isOrthographicCamera ) { + + this._scale *= dollyScale; + + } else { + + console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' ); + this.enableZoom = false; + + } + + } + + _updateZoomParameters( x, y ) { + + if ( ! this.zoomToCursor ) { + + return; + + } + + this._performCursorZoom = true; + + const rect = this.domElement.getBoundingClientRect(); + const dx = x - rect.left; + const dy = y - rect.top; + const w = rect.width; + const h = rect.height; + + this._mouse.x = ( dx / w ) * 2 - 1; + this._mouse.y = - ( dy / h ) * 2 + 1; + + this._dollyDirection.set( this._mouse.x, this._mouse.y, 1 ).unproject( this.object ).sub( this.object.position ).normalize(); + + } + + _clampDistance( dist ) { + + return Math.max( this.minDistance, Math.min( this.maxDistance, dist ) ); + + } + + // + // event callbacks - update the object state + // + + _handleMouseDownRotate( event ) { + + this._rotateStart.set( event.clientX, event.clientY ); + + } + + _handleMouseDownDolly( event ) { + + this._updateZoomParameters( event.clientX, event.clientX ); + this._dollyStart.set( event.clientX, event.clientY ); + + } + + _handleMouseDownPan( event ) { + + this._panStart.set( event.clientX, event.clientY ); + + } + + _handleMouseMoveRotate( event ) { + + this._rotateEnd.set( event.clientX, event.clientY ); + + this._rotateDelta.subVectors( this._rotateEnd, this._rotateStart ).multiplyScalar( this.rotateSpeed ); + + const element = this.domElement; + + this._rotateLeft( _twoPI * this._rotateDelta.x / element.clientHeight ); // yes, height + + this._rotateUp( _twoPI * this._rotateDelta.y / element.clientHeight ); + + this._rotateStart.copy( this._rotateEnd ); + + this.update(); + + } + + _handleMouseMoveDolly( event ) { + + this._dollyEnd.set( event.clientX, event.clientY ); + + this._dollyDelta.subVectors( this._dollyEnd, this._dollyStart ); + + if ( this._dollyDelta.y > 0 ) { + + this._dollyOut( this._getZoomScale( this._dollyDelta.y ) ); + + } else if ( this._dollyDelta.y < 0 ) { + + this._dollyIn( this._getZoomScale( this._dollyDelta.y ) ); + + } + + this._dollyStart.copy( this._dollyEnd ); + + this.update(); + + } + + _handleMouseMovePan( event ) { + + this._panEnd.set( event.clientX, event.clientY ); + + this._panDelta.subVectors( this._panEnd, this._panStart ).multiplyScalar( this.panSpeed ); + + this._pan( this._panDelta.x, this._panDelta.y ); + + this._panStart.copy( this._panEnd ); + + this.update(); + + } + + _handleMouseWheel( event ) { + + this._updateZoomParameters( event.clientX, event.clientY ); + + if ( event.deltaY < 0 ) { + + this._dollyIn( this._getZoomScale( event.deltaY ) ); + + } else if ( event.deltaY > 0 ) { + + this._dollyOut( this._getZoomScale( event.deltaY ) ); + + } + + this.update(); + + } + + _handleKeyDown( event ) { + + let needsUpdate = false; + + switch ( event.code ) { + + case this.keys.UP: + + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + + if ( this.enableRotate ) { + + this._rotateUp( _twoPI * this.keyRotateSpeed / this.domElement.clientHeight ); + + } + + } else { + + if ( this.enablePan ) { + + this._pan( 0, this.keyPanSpeed ); + + } + + } + + needsUpdate = true; + break; + + case this.keys.BOTTOM: + + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + + if ( this.enableRotate ) { + + this._rotateUp( - _twoPI * this.keyRotateSpeed / this.domElement.clientHeight ); + + } + + } else { + + if ( this.enablePan ) { + + this._pan( 0, - this.keyPanSpeed ); + + } + + } + + needsUpdate = true; + break; + + case this.keys.LEFT: + + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + + if ( this.enableRotate ) { + + this._rotateLeft( _twoPI * this.keyRotateSpeed / this.domElement.clientHeight ); + + } + + } else { + + if ( this.enablePan ) { + + this._pan( this.keyPanSpeed, 0 ); + + } + + } + + needsUpdate = true; + break; + + case this.keys.RIGHT: + + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + + if ( this.enableRotate ) { + + this._rotateLeft( - _twoPI * this.keyRotateSpeed / this.domElement.clientHeight ); + + } + + } else { + + if ( this.enablePan ) { + + this._pan( - this.keyPanSpeed, 0 ); + + } + + } + + needsUpdate = true; + break; + + } + + if ( needsUpdate ) { + + // prevent the browser from scrolling on cursor keys + event.preventDefault(); + + this.update(); + + } + + + } + + _handleTouchStartRotate( event ) { + + if ( this._pointers.length === 1 ) { + + this._rotateStart.set( event.pageX, event.pageY ); + + } else { + + const position = this._getSecondPointerPosition( event ); + + const x = 0.5 * ( event.pageX + position.x ); + const y = 0.5 * ( event.pageY + position.y ); + + this._rotateStart.set( x, y ); + + } + + } + + _handleTouchStartPan( event ) { + + if ( this._pointers.length === 1 ) { + + this._panStart.set( event.pageX, event.pageY ); + + } else { + + const position = this._getSecondPointerPosition( event ); + + const x = 0.5 * ( event.pageX + position.x ); + const y = 0.5 * ( event.pageY + position.y ); + + this._panStart.set( x, y ); + + } + + } + + _handleTouchStartDolly( event ) { + + const position = this._getSecondPointerPosition( event ); + + const dx = event.pageX - position.x; + const dy = event.pageY - position.y; + + const distance = Math.sqrt( dx * dx + dy * dy ); + + this._dollyStart.set( 0, distance ); + + } + + _handleTouchStartDollyPan( event ) { + + if ( this.enableZoom ) this._handleTouchStartDolly( event ); + + if ( this.enablePan ) this._handleTouchStartPan( event ); + + } + + _handleTouchStartDollyRotate( event ) { + + if ( this.enableZoom ) this._handleTouchStartDolly( event ); + + if ( this.enableRotate ) this._handleTouchStartRotate( event ); + + } + + _handleTouchMoveRotate( event ) { + + if ( this._pointers.length == 1 ) { + + this._rotateEnd.set( event.pageX, event.pageY ); + + } else { + + const position = this._getSecondPointerPosition( event ); + + const x = 0.5 * ( event.pageX + position.x ); + const y = 0.5 * ( event.pageY + position.y ); + + this._rotateEnd.set( x, y ); + + } + + this._rotateDelta.subVectors( this._rotateEnd, this._rotateStart ).multiplyScalar( this.rotateSpeed ); + + const element = this.domElement; + + this._rotateLeft( _twoPI * this._rotateDelta.x / element.clientHeight ); // yes, height + + this._rotateUp( _twoPI * this._rotateDelta.y / element.clientHeight ); + + this._rotateStart.copy( this._rotateEnd ); + + } + + _handleTouchMovePan( event ) { + + if ( this._pointers.length === 1 ) { + + this._panEnd.set( event.pageX, event.pageY ); + + } else { + + const position = this._getSecondPointerPosition( event ); + + const x = 0.5 * ( event.pageX + position.x ); + const y = 0.5 * ( event.pageY + position.y ); + + this._panEnd.set( x, y ); + + } + + this._panDelta.subVectors( this._panEnd, this._panStart ).multiplyScalar( this.panSpeed ); + + this._pan( this._panDelta.x, this._panDelta.y ); + + this._panStart.copy( this._panEnd ); + + } + + _handleTouchMoveDolly( event ) { + + const position = this._getSecondPointerPosition( event ); + + const dx = event.pageX - position.x; + const dy = event.pageY - position.y; + + const distance = Math.sqrt( dx * dx + dy * dy ); + + this._dollyEnd.set( 0, distance ); + + this._dollyDelta.set( 0, Math.pow( this._dollyEnd.y / this._dollyStart.y, this.zoomSpeed ) ); + + this._dollyOut( this._dollyDelta.y ); + + this._dollyStart.copy( this._dollyEnd ); + + const centerX = ( event.pageX + position.x ) * 0.5; + const centerY = ( event.pageY + position.y ) * 0.5; + + this._updateZoomParameters( centerX, centerY ); + + } + + _handleTouchMoveDollyPan( event ) { + + if ( this.enableZoom ) this._handleTouchMoveDolly( event ); + + if ( this.enablePan ) this._handleTouchMovePan( event ); + + } + + _handleTouchMoveDollyRotate( event ) { + + if ( this.enableZoom ) this._handleTouchMoveDolly( event ); + + if ( this.enableRotate ) this._handleTouchMoveRotate( event ); + + } + + // pointers + + _addPointer( event ) { + + this._pointers.push( event.pointerId ); + + } + + _removePointer( event ) { + + delete this._pointerPositions[ event.pointerId ]; + + for ( let i = 0; i < this._pointers.length; i ++ ) { + + if ( this._pointers[ i ] == event.pointerId ) { + + this._pointers.splice( i, 1 ); + return; + + } + + } + + } + + _isTrackingPointer( event ) { + + for ( let i = 0; i < this._pointers.length; i ++ ) { + + if ( this._pointers[ i ] == event.pointerId ) return true; + + } + + return false; + + } + + _trackPointer( event ) { + + let position = this._pointerPositions[ event.pointerId ]; + + if ( position === undefined ) { + + position = new Vector2(); + this._pointerPositions[ event.pointerId ] = position; + + } + + position.set( event.pageX, event.pageY ); + + } + + _getSecondPointerPosition( event ) { + + const pointerId = ( event.pointerId === this._pointers[ 0 ] ) ? this._pointers[ 1 ] : this._pointers[ 0 ]; + + return this._pointerPositions[ pointerId ]; + + } + + // + + _customWheelEvent( event ) { + + const mode = event.deltaMode; + + // minimal wheel event altered to meet delta-zoom demand + const newEvent = { + clientX: event.clientX, + clientY: event.clientY, + deltaY: event.deltaY, + }; + + switch ( mode ) { + + case 1: // LINE_MODE + newEvent.deltaY *= 16; + break; + + case 2: // PAGE_MODE + newEvent.deltaY *= 100; + break; + + } + + // detect if event was triggered by pinching + if ( event.ctrlKey && ! this._controlActive ) { + + newEvent.deltaY *= 10; + + } + + return newEvent; + + } + +} + +function onPointerDown( event ) { + + if ( this.enabled === false ) return; + + if ( this._pointers.length === 0 ) { + + this.domElement.setPointerCapture( event.pointerId ); + + this.domElement.addEventListener( 'pointermove', this._onPointerMove ); + this.domElement.addEventListener( 'pointerup', this._onPointerUp ); + + } + + // + + if ( this._isTrackingPointer( event ) ) return; + + // + + this._addPointer( event ); + + if ( event.pointerType === 'touch' ) { + + this._onTouchStart( event ); + + } else { + + this._onMouseDown( event ); + + } + +} + +function onPointerMove( event ) { + + if ( this.enabled === false ) return; + + if ( event.pointerType === 'touch' ) { + + this._onTouchMove( event ); + + } else { + + this._onMouseMove( event ); + + } + +} + +function onPointerUp( event ) { + + this._removePointer( event ); + + switch ( this._pointers.length ) { + + case 0: + + this.domElement.releasePointerCapture( event.pointerId ); + + this.domElement.removeEventListener( 'pointermove', this._onPointerMove ); + this.domElement.removeEventListener( 'pointerup', this._onPointerUp ); + + this.dispatchEvent( _endEvent ); + + this.state = _STATE.NONE; + + break; + + case 1: + + const pointerId = this._pointers[ 0 ]; + const position = this._pointerPositions[ pointerId ]; + + // minimal placeholder event - allows state correction on pointer-up + this._onTouchStart( { pointerId: pointerId, pageX: position.x, pageY: position.y } ); + + break; + + } + +} + +function onMouseDown( event ) { + + let mouseAction; + + switch ( event.button ) { + + case 0: + + mouseAction = this.mouseButtons.LEFT; + break; + + case 1: + + mouseAction = this.mouseButtons.MIDDLE; + break; + + case 2: + + mouseAction = this.mouseButtons.RIGHT; + break; + + default: + + mouseAction = - 1; + + } + + switch ( mouseAction ) { + + case MOUSE.DOLLY: + + if ( this.enableZoom === false ) return; + + this._handleMouseDownDolly( event ); + + this.state = _STATE.DOLLY; + + break; + + case MOUSE.ROTATE: + + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + + if ( this.enablePan === false ) return; + + this._handleMouseDownPan( event ); + + this.state = _STATE.PAN; + + } else { + + if ( this.enableRotate === false ) return; + + this._handleMouseDownRotate( event ); + + this.state = _STATE.ROTATE; + + } + + break; + + case MOUSE.PAN: + + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + + if ( this.enableRotate === false ) return; + + this._handleMouseDownRotate( event ); + + this.state = _STATE.ROTATE; + + } else { + + if ( this.enablePan === false ) return; + + this._handleMouseDownPan( event ); + + this.state = _STATE.PAN; + + } + + break; + + default: + + this.state = _STATE.NONE; + + } + + if ( this.state !== _STATE.NONE ) { + + this.dispatchEvent( _startEvent ); + + } + +} + +function onMouseMove( event ) { + + switch ( this.state ) { + + case _STATE.ROTATE: + + if ( this.enableRotate === false ) return; + + this._handleMouseMoveRotate( event ); + + break; + + case _STATE.DOLLY: + + if ( this.enableZoom === false ) return; + + this._handleMouseMoveDolly( event ); + + break; + + case _STATE.PAN: + + if ( this.enablePan === false ) return; + + this._handleMouseMovePan( event ); + + break; + + } + +} + +function onMouseWheel( event ) { + + if ( this.enabled === false || this.enableZoom === false || this.state !== _STATE.NONE ) return; + + event.preventDefault(); + + this.dispatchEvent( _startEvent ); + + this._handleMouseWheel( this._customWheelEvent( event ) ); + + this.dispatchEvent( _endEvent ); + +} + +function onKeyDown( event ) { + + if ( this.enabled === false ) return; + + this._handleKeyDown( event ); + +} + +function onTouchStart( event ) { + + this._trackPointer( event ); + + switch ( this._pointers.length ) { + + case 1: + + switch ( this.touches.ONE ) { + + case TOUCH.ROTATE: + + if ( this.enableRotate === false ) return; + + this._handleTouchStartRotate( event ); + + this.state = _STATE.TOUCH_ROTATE; + + break; + + case TOUCH.PAN: + + if ( this.enablePan === false ) return; + + this._handleTouchStartPan( event ); + + this.state = _STATE.TOUCH_PAN; + + break; + + default: + + this.state = _STATE.NONE; + + } + + break; + + case 2: + + switch ( this.touches.TWO ) { + + case TOUCH.DOLLY_PAN: + + if ( this.enableZoom === false && this.enablePan === false ) return; + + this._handleTouchStartDollyPan( event ); + + this.state = _STATE.TOUCH_DOLLY_PAN; + + break; + + case TOUCH.DOLLY_ROTATE: + + if ( this.enableZoom === false && this.enableRotate === false ) return; + + this._handleTouchStartDollyRotate( event ); + + this.state = _STATE.TOUCH_DOLLY_ROTATE; + + break; + + default: + + this.state = _STATE.NONE; + + } + + break; + + default: + + this.state = _STATE.NONE; + + } + + if ( this.state !== _STATE.NONE ) { + + this.dispatchEvent( _startEvent ); + + } + +} + +function onTouchMove( event ) { + + this._trackPointer( event ); + + switch ( this.state ) { + + case _STATE.TOUCH_ROTATE: + + if ( this.enableRotate === false ) return; + + this._handleTouchMoveRotate( event ); + + this.update(); + + break; + + case _STATE.TOUCH_PAN: + + if ( this.enablePan === false ) return; + + this._handleTouchMovePan( event ); + + this.update(); + + break; + + case _STATE.TOUCH_DOLLY_PAN: + + if ( this.enableZoom === false && this.enablePan === false ) return; + + this._handleTouchMoveDollyPan( event ); + + this.update(); + + break; + + case _STATE.TOUCH_DOLLY_ROTATE: + + if ( this.enableZoom === false && this.enableRotate === false ) return; + + this._handleTouchMoveDollyRotate( event ); + + this.update(); + + break; + + default: + + this.state = _STATE.NONE; + + } + +} + +function onContextMenu( event ) { + + if ( this.enabled === false ) return; + + event.preventDefault(); + +} + +function interceptControlDown( event ) { + + if ( event.key === 'Control' ) { + + this._controlActive = true; + + const document = this.domElement.getRootNode(); // offscreen canvas compatibility + + document.addEventListener( 'keyup', this._interceptControlUp, { passive: true, capture: true } ); + + } + +} + +function interceptControlUp( event ) { + + if ( event.key === 'Control' ) { + + this._controlActive = false; + + const document = this.domElement.getRootNode(); // offscreen canvas compatibility + + document.removeEventListener( 'keyup', this._interceptControlUp, { passive: true, capture: true } ); + + } + +} + +export { OrbitControls }; diff --git a/clickplanet-webapp/public/js/three.module.js b/clickplanet-webapp/public/js/three.module.js new file mode 100644 index 0000000..5a4f327 --- /dev/null +++ b/clickplanet-webapp/public/js/three.module.js @@ -0,0 +1,18021 @@ +/** + * @license + * Copyright 2010-2025 Three.js Authors + * SPDX-License-Identifier: MIT + */ +import { Matrix3, Vector2, Color, mergeUniforms, Vector3, CubeUVReflectionMapping, Mesh, BoxGeometry, ShaderMaterial, BackSide, cloneUniforms, Euler, Matrix4, ColorManagement, SRGBTransfer, PlaneGeometry, FrontSide, getUnlitUniformColorSpace, IntType, HalfFloatType, UnsignedByteType, FloatType, RGBAFormat, Plane, EquirectangularReflectionMapping, EquirectangularRefractionMapping, WebGLCubeRenderTarget, CubeReflectionMapping, CubeRefractionMapping, OrthographicCamera, PerspectiveCamera, NoToneMapping, MeshBasicMaterial, NoBlending, WebGLRenderTarget, BufferGeometry, BufferAttribute, LinearSRGBColorSpace, LinearFilter, warnOnce, Uint32BufferAttribute, Uint16BufferAttribute, arrayNeedsUint32, Vector4, DataArrayTexture, CubeTexture, Data3DTexture, LessEqualCompare, DepthTexture, Texture, GLSL3, PCFShadowMap, PCFSoftShadowMap, VSMShadowMap, CustomToneMapping, NeutralToneMapping, AgXToneMapping, ACESFilmicToneMapping, CineonToneMapping, ReinhardToneMapping, LinearToneMapping, LinearTransfer, AddOperation, MixOperation, MultiplyOperation, UniformsUtils, DoubleSide, NormalBlending, TangentSpaceNormalMap, ObjectSpaceNormalMap, Layers, Frustum, MeshDepthMaterial, RGBADepthPacking, MeshDistanceMaterial, NearestFilter, LessEqualDepth, ReverseSubtractEquation, SubtractEquation, AddEquation, OneMinusConstantAlphaFactor, ConstantAlphaFactor, OneMinusConstantColorFactor, ConstantColorFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, DstAlphaFactor, DstColorFactor, SrcAlphaSaturateFactor, SrcAlphaFactor, SrcColorFactor, OneFactor, ZeroFactor, NotEqualDepth, GreaterDepth, GreaterEqualDepth, EqualDepth, LessDepth, AlwaysDepth, NeverDepth, CullFaceNone, CullFaceBack, CullFaceFront, CustomBlending, MultiplyBlending, SubtractiveBlending, AdditiveBlending, MinEquation, MaxEquation, MirroredRepeatWrapping, ClampToEdgeWrapping, RepeatWrapping, LinearMipmapLinearFilter, LinearMipmapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NotEqualCompare, GreaterCompare, GreaterEqualCompare, EqualCompare, LessCompare, AlwaysCompare, NeverCompare, NoColorSpace, DepthStencilFormat, getByteLength, DepthFormat, UnsignedIntType, UnsignedInt248Type, UnsignedShortType, createElementNS, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedInt5999Type, ByteType, ShortType, AlphaFormat, RGBFormat, RedFormat, RedIntegerFormat, RGFormat, RGIntegerFormat, RGBAIntegerFormat, RGB_S3TC_DXT1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGB_PVRTC_4BPPV1_Format, RGB_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_PVRTC_2BPPV1_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGBA_ETC2_EAC_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_10x10_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_BPTC_Format, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RED_RGTC1_Format, SIGNED_RED_RGTC1_Format, RED_GREEN_RGTC2_Format, SIGNED_RED_GREEN_RGTC2_Format, EventDispatcher, ArrayCamera, WebXRController, RAD2DEG, createCanvasElement, SRGBColorSpace, REVISION, toNormalizedProjectionMatrix, toReversedProjectionMatrix, probeAsync, WebGLCoordinateSystem } from './three.core.js'; +export { AdditiveAnimationBlendMode, AlwaysStencilFunc, AmbientLight, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BasicDepthPacking, BasicShadowMap, BatchedMesh, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxHelper, BufferGeometryLoader, Cache, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CircleGeometry, Clock, ColorKeyframeTrack, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, Controls, CubeCamera, CubeTextureLoader, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceFrontBack, Curve, CurvePath, CylinderGeometry, Cylindrical, DataTexture, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthArrayTexture, DetachedBindMode, DirectionalLight, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, EqualStencilFunc, ExtrudeGeometry, FileLoader, Float16BufferAttribute, Float32BufferAttribute, Fog, FogExp2, FramebufferTexture, FrustumArray, GLBufferAttribute, GLSL1, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HemisphereLight, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InterpolationSamplingMode, InterpolationSamplingType, InvertStencilOp, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, Line, Line3, LineBasicMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineLoop, LineSegments, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, Loader, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, Material, MaterialLoader, MathUtils, Matrix2, MeshLambertMaterial, MeshMatcapMaterial, MeshNormalMaterial, MeshPhongMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NeverStencilFunc, NormalAnimationBlendMode, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, ObjectLoader, OctahedronGeometry, Path, PlaneHelper, PointLight, PointLightHelper, Points, PointsMaterial, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RGBDepthPacking, RGBIntegerFormat, RGDepthPacking, RawShaderMaterial, Ray, Raycaster, RectAreaLight, RenderTarget, RenderTarget3D, RenderTargetArray, ReplaceStencilOp, RingGeometry, Scene, ShadowMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, Skeleton, SkeletonHelper, SkinnedMesh, Source, Sphere, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SpotLight, SpotLightHelper, Sprite, SpriteMaterial, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, TOUCH, TetrahedronGeometry, TextureLoader, TextureUtils, TimestampQuery, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, UVMapping, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGPUCoordinateSystem, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroSlopeEnding, ZeroStencilOp } from './three.core.js'; + +function WebGLAnimation() { + + let context = null; + let isAnimating = false; + let animationLoop = null; + let requestId = null; + + function onAnimationFrame( time, frame ) { + + animationLoop( time, frame ); + + requestId = context.requestAnimationFrame( onAnimationFrame ); + + } + + return { + + start: function () { + + if ( isAnimating === true ) return; + if ( animationLoop === null ) return; + + requestId = context.requestAnimationFrame( onAnimationFrame ); + + isAnimating = true; + + }, + + stop: function () { + + context.cancelAnimationFrame( requestId ); + + isAnimating = false; + + }, + + setAnimationLoop: function ( callback ) { + + animationLoop = callback; + + }, + + setContext: function ( value ) { + + context = value; + + } + + }; + +} + +function WebGLAttributes( gl ) { + + const buffers = new WeakMap(); + + function createBuffer( attribute, bufferType ) { + + const array = attribute.array; + const usage = attribute.usage; + const size = array.byteLength; + + const buffer = gl.createBuffer(); + + gl.bindBuffer( bufferType, buffer ); + gl.bufferData( bufferType, array, usage ); + + attribute.onUploadCallback(); + + let type; + + if ( array instanceof Float32Array ) { + + type = gl.FLOAT; + + } else if ( array instanceof Uint16Array ) { + + if ( attribute.isFloat16BufferAttribute ) { + + type = gl.HALF_FLOAT; + + } else { + + type = gl.UNSIGNED_SHORT; + + } + + } else if ( array instanceof Int16Array ) { + + type = gl.SHORT; + + } else if ( array instanceof Uint32Array ) { + + type = gl.UNSIGNED_INT; + + } else if ( array instanceof Int32Array ) { + + type = gl.INT; + + } else if ( array instanceof Int8Array ) { + + type = gl.BYTE; + + } else if ( array instanceof Uint8Array ) { + + type = gl.UNSIGNED_BYTE; + + } else if ( array instanceof Uint8ClampedArray ) { + + type = gl.UNSIGNED_BYTE; + + } else { + + throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array ); + + } + + return { + buffer: buffer, + type: type, + bytesPerElement: array.BYTES_PER_ELEMENT, + version: attribute.version, + size: size + }; + + } + + function updateBuffer( buffer, attribute, bufferType ) { + + const array = attribute.array; + const updateRanges = attribute.updateRanges; + + gl.bindBuffer( bufferType, buffer ); + + if ( updateRanges.length === 0 ) { + + // Not using update ranges + gl.bufferSubData( bufferType, 0, array ); + + } else { + + // Before applying update ranges, we merge any adjacent / overlapping + // ranges to reduce load on `gl.bufferSubData`. Empirically, this has led + // to performance improvements for applications which make heavy use of + // update ranges. Likely due to GPU command overhead. + // + // Note that to reduce garbage collection between frames, we merge the + // update ranges in-place. This is safe because this method will clear the + // update ranges once updated. + + updateRanges.sort( ( a, b ) => a.start - b.start ); + + // To merge the update ranges in-place, we work from left to right in the + // existing updateRanges array, merging ranges. This may result in a final + // array which is smaller than the original. This index tracks the last + // index representing a merged range, any data after this index can be + // trimmed once the merge algorithm is completed. + let mergeIndex = 0; + + for ( let i = 1; i < updateRanges.length; i ++ ) { + + const previousRange = updateRanges[ mergeIndex ]; + const range = updateRanges[ i ]; + + // We add one here to merge adjacent ranges. This is safe because ranges + // operate over positive integers. + if ( range.start <= previousRange.start + previousRange.count + 1 ) { + + previousRange.count = Math.max( + previousRange.count, + range.start + range.count - previousRange.start + ); + + } else { + + ++ mergeIndex; + updateRanges[ mergeIndex ] = range; + + } + + } + + // Trim the array to only contain the merged ranges. + updateRanges.length = mergeIndex + 1; + + for ( let i = 0, l = updateRanges.length; i < l; i ++ ) { + + const range = updateRanges[ i ]; + + gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT, + array, range.start, range.count ); + + } + + attribute.clearUpdateRanges(); + + } + + attribute.onUploadCallback(); + + } + + // + + function get( attribute ) { + + if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data; + + return buffers.get( attribute ); + + } + + function remove( attribute ) { + + if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data; + + const data = buffers.get( attribute ); + + if ( data ) { + + gl.deleteBuffer( data.buffer ); + + buffers.delete( attribute ); + + } + + } + + function update( attribute, bufferType ) { + + if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data; + + if ( attribute.isGLBufferAttribute ) { + + const cached = buffers.get( attribute ); + + if ( ! cached || cached.version < attribute.version ) { + + buffers.set( attribute, { + buffer: attribute.buffer, + type: attribute.type, + bytesPerElement: attribute.elementSize, + version: attribute.version + } ); + + } + + return; + + } + + const data = buffers.get( attribute ); + + if ( data === undefined ) { + + buffers.set( attribute, createBuffer( attribute, bufferType ) ); + + } else if ( data.version < attribute.version ) { + + if ( data.size !== attribute.array.byteLength ) { + + throw new Error( 'THREE.WebGLAttributes: The size of the buffer attribute\'s array buffer does not match the original size. Resizing buffer attributes is not supported.' ); + + } + + updateBuffer( data.buffer, attribute, bufferType ); + + data.version = attribute.version; + + } + + } + + return { + + get: get, + remove: remove, + update: update + + }; + +} + +var alphahash_fragment = "#ifdef USE_ALPHAHASH\n\tif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif"; + +var alphahash_pars_fragment = "#ifdef USE_ALPHAHASH\n\tconst float ALPHA_HASH_SCALE = 0.05;\n\tfloat hash2D( vec2 value ) {\n\t\treturn fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );\n\t}\n\tfloat hash3D( vec3 value ) {\n\t\treturn hash2D( vec2( hash2D( value.xy ), value.z ) );\n\t}\n\tfloat getAlphaHashThreshold( vec3 position ) {\n\t\tfloat maxDeriv = max(\n\t\t\tlength( dFdx( position.xyz ) ),\n\t\t\tlength( dFdy( position.xyz ) )\n\t\t);\n\t\tfloat pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );\n\t\tvec2 pixScales = vec2(\n\t\t\texp2( floor( log2( pixScale ) ) ),\n\t\t\texp2( ceil( log2( pixScale ) ) )\n\t\t);\n\t\tvec2 alpha = vec2(\n\t\t\thash3D( floor( pixScales.x * position.xyz ) ),\n\t\t\thash3D( floor( pixScales.y * position.xyz ) )\n\t\t);\n\t\tfloat lerpFactor = fract( log2( pixScale ) );\n\t\tfloat x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;\n\t\tfloat a = min( lerpFactor, 1.0 - lerpFactor );\n\t\tvec3 cases = vec3(\n\t\t\tx * x / ( 2.0 * a * ( 1.0 - a ) ),\n\t\t\t( x - 0.5 * a ) / ( 1.0 - a ),\n\t\t\t1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )\n\t\t);\n\t\tfloat threshold = ( x < ( 1.0 - a ) )\n\t\t\t? ( ( x < a ) ? cases.x : cases.y )\n\t\t\t: cases.z;\n\t\treturn clamp( threshold , 1.0e-6, 1.0 );\n\t}\n#endif"; + +var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif"; + +var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif"; + +var alphatest_fragment = "#ifdef USE_ALPHATEST\n\t#ifdef ALPHA_TO_COVERAGE\n\tdiffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );\n\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\tif ( diffuseColor.a < alphaTest ) discard;\n\t#endif\n#endif"; + +var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif"; + +var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_CLEARCOAT ) \n\t\tclearcoatSpecularIndirect *= ambientOcclusion;\n\t#endif\n\t#if defined( USE_SHEEN ) \n\t\tsheenSpecularIndirect *= ambientOcclusion;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometryNormal, geometryViewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif"; + +var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif"; + +var batching_pars_vertex = "#ifdef USE_BATCHING\n\t#if ! defined( GL_ANGLE_multi_draw )\n\t#define gl_DrawID _gl_DrawID\n\tuniform int _gl_DrawID;\n\t#endif\n\tuniform highp sampler2D batchingTexture;\n\tuniform highp usampler2D batchingIdTexture;\n\tmat4 getBatchingMatrix( const in float i ) {\n\t\tint size = textureSize( batchingTexture, 0 ).x;\n\t\tint j = int( i ) * 4;\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\tvec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n\tfloat getIndirectIndex( const in int i ) {\n\t\tint size = textureSize( batchingIdTexture, 0 ).x;\n\t\tint x = i % size;\n\t\tint y = i / size;\n\t\treturn float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r );\n\t}\n#endif\n#ifdef USE_BATCHING_COLOR\n\tuniform sampler2D batchingColorTexture;\n\tvec3 getBatchingColor( const in float i ) {\n\t\tint size = textureSize( batchingColorTexture, 0 ).x;\n\t\tint j = int( i );\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\treturn texelFetch( batchingColorTexture, ivec2( x, y ), 0 ).rgb;\n\t}\n#endif"; + +var batching_vertex = "#ifdef USE_BATCHING\n\tmat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );\n#endif"; + +var begin_vertex = "vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n\tvPosition = vec3( position );\n#endif"; + +var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif"; + +var bsdfs = "float G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n} // validated"; + +var iridescence_fragment = "#ifdef USE_IRIDESCENCE\n\tconst mat3 XYZ_TO_REC709 = mat3(\n\t\t 3.2404542, -0.9692660, 0.0556434,\n\t\t-1.5371385, 1.8760108, -0.2040259,\n\t\t-0.4985314, 0.0415560, 1.0572252\n\t);\n\tvec3 Fresnel0ToIor( vec3 fresnel0 ) {\n\t\tvec3 sqrtF0 = sqrt( fresnel0 );\n\t\treturn ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );\n\t}\n\tvec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );\n\t}\n\tfloat IorToFresnel0( float transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));\n\t}\n\tvec3 evalSensitivity( float OPD, vec3 shift ) {\n\t\tfloat phase = 2.0 * PI * OPD * 1.0e-9;\n\t\tvec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );\n\t\tvec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );\n\t\tvec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );\n\t\tvec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );\n\t\txyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );\n\t\txyz /= 1.0685e-7;\n\t\tvec3 rgb = XYZ_TO_REC709 * xyz;\n\t\treturn rgb;\n\t}\n\tvec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {\n\t\tvec3 I;\n\t\tfloat iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );\n\t\tfloat sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );\n\t\tfloat cosTheta2Sq = 1.0 - sinTheta2Sq;\n\t\tif ( cosTheta2Sq < 0.0 ) {\n\t\t\treturn vec3( 1.0 );\n\t\t}\n\t\tfloat cosTheta2 = sqrt( cosTheta2Sq );\n\t\tfloat R0 = IorToFresnel0( iridescenceIOR, outsideIOR );\n\t\tfloat R12 = F_Schlick( R0, 1.0, cosTheta1 );\n\t\tfloat T121 = 1.0 - R12;\n\t\tfloat phi12 = 0.0;\n\t\tif ( iridescenceIOR < outsideIOR ) phi12 = PI;\n\t\tfloat phi21 = PI - phi12;\n\t\tvec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) );\t\tvec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );\n\t\tvec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );\n\t\tvec3 phi23 = vec3( 0.0 );\n\t\tif ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;\n\t\tif ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;\n\t\tif ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;\n\t\tfloat OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;\n\t\tvec3 phi = vec3( phi21 ) + phi23;\n\t\tvec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );\n\t\tvec3 r123 = sqrt( R123 );\n\t\tvec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );\n\t\tvec3 C0 = R12 + Rs;\n\t\tI = C0;\n\t\tvec3 Cm = Rs - T121;\n\t\tfor ( int m = 1; m <= 2; ++ m ) {\n\t\t\tCm *= r123;\n\t\t\tvec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );\n\t\t\tI += Cm * Sm;\n\t\t}\n\t\treturn max( I, vec3( 0.0 ) );\n\t}\n#endif"; + +var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vBumpMapUv );\n\t\tvec2 dSTdy = dFdy( vBumpMapUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );\n\t\tvec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif"; + +var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#ifdef ALPHA_TO_COVERAGE\n\t\tfloat distanceToPlane, distanceGradient;\n\t\tfloat clipOpacity = 1.0;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\tclipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\tif ( clipOpacity == 0.0 ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tfloat unionClipOpacity = 1.0;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\t\tunionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tclipOpacity *= 1.0 - unionClipOpacity;\n\t\t#endif\n\t\tdiffuseColor.a *= clipOpacity;\n\t\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tbool clipped = true;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tif ( clipped ) discard;\n\t\t#endif\n\t#endif\n#endif"; + +var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif"; + +var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif"; + +var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif"; + +var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif"; + +var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif"; + +var color_pars_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvarying vec3 vColor;\n#endif"; + +var color_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif\n#ifdef USE_BATCHING_COLOR\n\tvec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) );\n\tvColor.xyz *= batchingColor.xyz;\n#endif"; + +var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\n#ifdef USE_ALPHAHASH\n\tvarying vec3 vPosition;\n#endif\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}\nvec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n} // validated"; + +var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\thighp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\n\t}\n\t#define cubeUV_r0 1.0\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= cubeUV_r1 ) {\n\t\t\tmip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n\t\t} else if ( roughness >= cubeUV_r4 ) {\n\t\t\tmip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n\t\t} else if ( roughness >= cubeUV_r5 ) {\n\t\t\tmip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n\t\t} else if ( roughness >= cubeUV_r6 ) {\n\t\t\tmip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif"; + +var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = objectTangent;\n#endif\n#ifdef USE_BATCHING\n\tmat3 bm = mat3( batchingMatrix );\n\ttransformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );\n\ttransformedNormal = bm * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = bm * transformedTangent;\n\t#endif\n#endif\n#ifdef USE_INSTANCING\n\tmat3 im = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );\n\ttransformedNormal = im * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = im * transformedTangent;\n\t#endif\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\ttransformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif"; + +var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif"; + +var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif"; + +var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE_EMISSIVE\n\t\temissiveColor = sRGBTransferEOTF( emissiveColor );\n\t#endif\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif"; + +var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif"; + +var colorspace_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );"; + +var colorspace_pars_fragment = "vec4 LinearTransferOETF( in vec4 value ) {\n\treturn value;\n}\nvec4 sRGBTransferEOTF( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 sRGBTransferOETF( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}"; + +var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif"; + +var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform mat3 envMapRotation;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif"; + +var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif"; + +var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif"; + +var envmap_vertex = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif"; + +var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif"; + +var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif"; + +var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif"; + +var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif"; + +var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\tvec2 fw = fwidth( coord ) * 0.5;\n\t\treturn mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n\t#endif\n}"; + +var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif"; + +var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;"; + +var lights_lambert_pars_fragment = "varying vec3 vViewPosition;\nstruct LambertMaterial {\n\tvec3 diffuseColor;\n\tfloat specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Lambert\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Lambert"; + +var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\n#if defined( USE_LIGHT_PROBES )\n\tuniform vec3 lightProbe[ 9 ];\n#endif\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif ( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif"; + +var envmap_physical_pars_fragment = "#ifdef USE_ENVMAP\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\t#ifdef USE_ANISOTROPY\n\t\tvec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {\n\t\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\t\tvec3 bentNormal = cross( bitangent, viewDir );\n\t\t\t\tbentNormal = normalize( cross( bentNormal, bitangent ) );\n\t\t\t\tbentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );\n\t\t\t\treturn getIBLRadiance( viewDir, bentNormal, roughness );\n\t\t\t#else\n\t\t\t\treturn vec3( 0.0 );\n\t\t\t#endif\n\t\t}\n\t#endif\n#endif"; + +var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;"; + +var lights_toon_pars_fragment = "varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon"; + +var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;"; + +var lights_phong_pars_fragment = "varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong"; + +var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\tmaterial.ior = ior;\n\t#ifdef USE_SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULAR_COLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;\n\t\t#endif\n\t\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_DISPERSION\n\tmaterial.dispersion = dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\t#ifdef USE_ANISOTROPYMAP\n\t\tmat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );\n\t\tvec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;\n\t\tvec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;\n\t#else\n\t\tvec2 anisotropyV = anisotropyVector;\n\t#endif\n\tmaterial.anisotropy = length( anisotropyV );\n\tif( material.anisotropy == 0.0 ) {\n\t\tanisotropyV = vec2( 1.0, 0.0 );\n\t} else {\n\t\tanisotropyV /= material.anisotropy;\n\t\tmaterial.anisotropy = saturate( material.anisotropy );\n\t}\n\tmaterial.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );\n\tmaterial.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;\n\tmaterial.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;\n#endif"; + +var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\tfloat dispersion;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat anisotropy;\n\t\tfloat alphaT;\n\t\tvec3 anisotropyT;\n\t\tvec3 anisotropyB;\n\t#endif\n};\nvec3 clearcoatSpecularDirect = vec3( 0.0 );\nvec3 clearcoatSpecularIndirect = vec3( 0.0 );\nvec3 sheenSpecularDirect = vec3( 0.0 );\nvec3 sheenSpecularIndirect = vec3(0.0 );\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\n#ifdef USE_ANISOTROPY\n\tfloat V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {\n\t\tfloat gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );\n\t\tfloat gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );\n\t\tfloat v = 0.5 / ( gv + gl );\n\t\treturn saturate(v);\n\t}\n\tfloat D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {\n\t\tfloat a2 = alphaT * alphaB;\n\t\thighp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );\n\t\thighp float v2 = dot( v, v );\n\t\tfloat w2 = a2 / v2;\n\t\treturn RECIPROCAL_PI * a2 * pow2 ( w2 );\n\t}\n#endif\n#ifdef USE_CLEARCOAT\n\tvec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {\n\t\tvec3 f0 = material.clearcoatF0;\n\t\tfloat f90 = material.clearcoatF90;\n\t\tfloat roughness = material.clearcoatRoughness;\n\t\tfloat alpha = pow2( roughness );\n\t\tvec3 halfDir = normalize( lightDir + viewDir );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\t\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\t\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t\treturn F * ( V * D );\n\t}\n#endif\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n\tvec3 f0 = material.specularColor;\n\tfloat f90 = material.specularF90;\n\tfloat roughness = material.roughness;\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t#ifdef USE_IRIDESCENCE\n\t\tF = mix( F, material.iridescenceFresnel, material.iridescence );\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat dotTL = dot( material.anisotropyT, lightDir );\n\t\tfloat dotTV = dot( material.anisotropyT, viewDir );\n\t\tfloat dotTH = dot( material.anisotropyT, halfDir );\n\t\tfloat dotBL = dot( material.anisotropyB, lightDir );\n\t\tfloat dotBV = dot( material.anisotropyB, viewDir );\n\t\tfloat dotBH = dot( material.anisotropyB, halfDir );\n\t\tfloat V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );\n\t\tfloat D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );\n\t#else\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t#endif\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometryNormal;\n\t\tvec3 viewDir = geometryViewDir;\n\t\tvec3 position = geometryPosition;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\t#endif\n\tvec3 totalScattering = singleScattering + multiScattering;\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}"; + +var lights_fragment_begin = "\nvec3 geometryPosition = - vViewPosition;\nvec3 geometryNormal = normal;\nvec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\nvec3 geometryClearcoatNormal = vec3( 0.0 );\n#ifdef USE_CLEARCOAT\n\tgeometryClearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometryViewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tmaterial.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n\t}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometryPosition, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometryPosition, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#if defined( USE_LIGHT_PROBES )\n\t\tirradiance += getLightProbeIrradiance( lightProbe, geometryNormal );\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif"; + +var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometryNormal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\t#ifdef USE_ANISOTROPY\n\t\tradiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );\n\t#else\n\t\tradiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif"; + +var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif"; + +var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF )\n\tgl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif"; + +var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif"; + +var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif"; + +var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\tvFragDepth = 1.0 + gl_Position.w;\n\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif"; + +var map_fragment = "#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif"; + +var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif"; + +var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t#if defined( USE_POINTS_UV )\n\t\tvec2 uv = vUv;\n\t#else\n\t\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif"; + +var map_particle_pars_fragment = "#if defined( USE_POINTS_UV )\n\tvarying vec2 vUv;\n#else\n\t#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t\tuniform mat3 uvTransform;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif"; + +var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif"; + +var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif"; + +var morphinstance_vertex = "#ifdef USE_INSTANCING_MORPH\n\tfloat morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\tfloat morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tmorphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;\n\t}\n#endif"; + +var morphcolor_vertex = "#if defined( USE_MORPHCOLORS )\n\tvColor *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t#if defined( USE_COLOR_ALPHA )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n\t\t#elif defined( USE_COLOR )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n\t\t#endif\n\t}\n#endif"; + +var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif"; + +var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\t#ifndef USE_INSTANCING_MORPH\n\t\tuniform float morphTargetBaseInfluence;\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t#endif\n\tuniform sampler2DArray morphTargetsTexture;\n\tuniform ivec2 morphTargetsTextureSize;\n\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t}\n#endif"; + +var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif"; + +var normal_fragment_begin = "float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = dFdx( vViewPosition );\n\tvec3 fdy = dFdy( vViewPosition );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal *= faceDirection;\n\t#endif\n#endif\n#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn = getTangentFrame( - vViewPosition, normal,\n\t\t#if defined( USE_NORMALMAP )\n\t\t\tvNormalMapUv\n\t\t#elif defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tvClearcoatNormalMapUv\n\t\t#else\n\t\t\tvUv\n\t\t#endif\n\t\t);\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn[0] *= faceDirection;\n\t\ttbn[1] *= faceDirection;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn2[0] *= faceDirection;\n\t\ttbn2[1] *= faceDirection;\n\t#endif\n#endif\nvec3 nonPerturbedNormal = normal;"; + +var normal_fragment_maps = "#ifdef USE_NORMALMAP_OBJECTSPACE\n\tnormal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( USE_NORMALMAP_TANGENTSPACE )\n\tvec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\tnormal = normalize( tbn * mapN );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif"; + +var normal_pars_fragment = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif"; + +var normal_pars_vertex = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif"; + +var normal_vertex = "#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif"; + +var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef USE_NORMALMAP_OBJECTSPACE\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )\n\tmat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( uv.st );\n\t\tvec2 st1 = dFdy( uv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );\n\t\treturn mat3( T * scale, B * scale, N );\n\t}\n#endif"; + +var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif"; + +var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\tclearcoatNormal = normalize( tbn2 * clearcoatMapN );\n#endif"; + +var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif"; + +var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif"; + +var opaque_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );"; + +var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.;\nconst float Inv255 = 1. / 255.;\nconst vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );\nconst vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );\nconst vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );\nconst vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );\nvec4 packDepthToRGBA( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec4( 0., 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec4( 1., 1., 1., 1. );\n\tfloat vuf;\n\tfloat af = modf( v * PackFactors.a, vuf );\n\tfloat bf = modf( vuf * ShiftRight8, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );\n}\nvec3 packDepthToRGB( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec3( 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec3( 1., 1., 1. );\n\tfloat vuf;\n\tfloat bf = modf( v * PackFactors.b, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec3( vuf * Inv255, gf * PackUpscale, bf );\n}\nvec2 packDepthToRG( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec2( 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec2( 1., 1. );\n\tfloat vuf;\n\tfloat gf = modf( v * 256., vuf );\n\treturn vec2( vuf * Inv255, gf );\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors4 );\n}\nfloat unpackRGBToDepth( const in vec3 v ) {\n\treturn dot( v, UnpackFactors3 );\n}\nfloat unpackRGToDepth( const in vec2 v ) {\n\treturn v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;\n}\nvec4 pack2HalfToRGBA( const in vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( const in vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn depth * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * depth - far );\n}"; + +var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif"; + +var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_BATCHING\n\tmvPosition = batchingMatrix * mvPosition;\n#endif\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;"; + +var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif"; + +var dithering_pars_fragment = "#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif"; + +var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif"; + +var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif"; + +var shadowmap_pars_fragment = "#if NUM_SPOT_LIGHT_COORDS > 0\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n\tuniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\t\n\t\tfloat lightToPositionLength = length( lightToPosition );\n\t\tif ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) {\n\t\t\tfloat dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\t\tdp += shadowBias;\n\t\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\t\tshadow = (\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t\t) * ( 1.0 / 9.0 );\n\t\t\t#else\n\t\t\t\tshadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t\t#endif\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n#endif"; + +var shadowmap_pars_vertex = "#if NUM_SPOT_LIGHT_COORDS > 0\n\tuniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif"; + +var shadowmap_vertex = "#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\tvec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if NUM_SPOT_LIGHT_COORDS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition;\n\t\t#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t\tshadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n\t\t#endif\n\t\tvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n#endif"; + +var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}"; + +var skinbase_vertex = "#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif"; + +var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tint size = textureSize( boneTexture, 0 ).x;\n\t\tint j = int( i ) * 4;\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\tvec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n#endif"; + +var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif"; + +var skinnormal_vertex = "#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif"; + +var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif"; + +var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif"; + +var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif"; + +var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn saturate( toneMappingExposure * color );\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 CineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.6605, - 0.1246, - 0.0182 ),\n\tvec3( - 0.5876, 1.1329, - 0.1006 ),\n\tvec3( - 0.0728, - 0.0083, 1.1187 )\n);\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n\tvec3( 0.6274, 0.0691, 0.0164 ),\n\tvec3( 0.3293, 0.9195, 0.0880 ),\n\tvec3( 0.0433, 0.0113, 0.8956 )\n);\nvec3 agxDefaultContrastApprox( vec3 x ) {\n\tvec3 x2 = x * x;\n\tvec3 x4 = x2 * x2;\n\treturn + 15.5 * x4 * x2\n\t\t- 40.14 * x4 * x\n\t\t+ 31.96 * x4\n\t\t- 6.868 * x2 * x\n\t\t+ 0.4298 * x2\n\t\t+ 0.1191 * x\n\t\t- 0.00232;\n}\nvec3 AgXToneMapping( vec3 color ) {\n\tconst mat3 AgXInsetMatrix = mat3(\n\t\tvec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n\t\tvec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n\t\tvec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n\t);\n\tconst mat3 AgXOutsetMatrix = mat3(\n\t\tvec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n\t\tvec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n\t\tvec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n\t);\n\tconst float AgxMinEv = - 12.47393;\tconst float AgxMaxEv = 4.026069;\n\tcolor *= toneMappingExposure;\n\tcolor = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n\tcolor = AgXInsetMatrix * color;\n\tcolor = max( color, 1e-10 );\tcolor = log2( color );\n\tcolor = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n\tcolor = clamp( color, 0.0, 1.0 );\n\tcolor = agxDefaultContrastApprox( color );\n\tcolor = AgXOutsetMatrix * color;\n\tcolor = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n\tcolor = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n\tcolor = clamp( color, 0.0, 1.0 );\n\treturn color;\n}\nvec3 NeutralToneMapping( vec3 color ) {\n\tconst float StartCompression = 0.8 - 0.04;\n\tconst float Desaturation = 0.15;\n\tcolor *= toneMappingExposure;\n\tfloat x = min( color.r, min( color.g, color.b ) );\n\tfloat offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n\tcolor -= offset;\n\tfloat peak = max( color.r, max( color.g, color.b ) );\n\tif ( peak < StartCompression ) return color;\n\tfloat d = 1. - StartCompression;\n\tfloat newPeak = 1. - d * d / ( peak + d - StartCompression );\n\tcolor *= newPeak / peak;\n\tfloat g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );\n\treturn mix( color, vec3( newPeak ), g );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }"; + +var transmission_fragment = "#ifdef USE_TRANSMISSION\n\tmaterial.transmission = transmission;\n\tmaterial.transmissionAlpha = 1.0;\n\tmaterial.thickness = thickness;\n\tmaterial.attenuationDistance = attenuationDistance;\n\tmaterial.attenuationColor = attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tmaterial.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmitted = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );\n#endif"; + +var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tfloat w0( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );\n\t}\n\tfloat w1( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );\n\t}\n\tfloat w2( float a ){\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );\n\t}\n\tfloat w3( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * a );\n\t}\n\tfloat g0( float a ) {\n\t\treturn w0( a ) + w1( a );\n\t}\n\tfloat g1( float a ) {\n\t\treturn w2( a ) + w3( a );\n\t}\n\tfloat h0( float a ) {\n\t\treturn - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );\n\t}\n\tfloat h1( float a ) {\n\t\treturn 1.0 + w3( a ) / ( w2( a ) + w3( a ) );\n\t}\n\tvec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {\n\t\tuv = uv * texelSize.zw + 0.5;\n\t\tvec2 iuv = floor( uv );\n\t\tvec2 fuv = fract( uv );\n\t\tfloat g0x = g0( fuv.x );\n\t\tfloat g1x = g1( fuv.x );\n\t\tfloat h0x = h0( fuv.x );\n\t\tfloat h1x = h1( fuv.x );\n\t\tfloat h0y = h0( fuv.y );\n\t\tfloat h1y = h1( fuv.y );\n\t\tvec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\treturn g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +\n\t\t\tg1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );\n\t}\n\tvec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {\n\t\tvec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );\n\t\tvec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );\n\t\tvec2 fLodSizeInv = 1.0 / fLodSize;\n\t\tvec2 cLodSizeInv = 1.0 / cLodSize;\n\t\tvec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );\n\t\tvec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );\n\t\treturn mix( fSample, cSample, fract( lod ) );\n\t}\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\treturn textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );\n\t}\n\tvec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn vec3( 1.0 );\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec4 transmittedLight;\n\t\tvec3 transmittance;\n\t\t#ifdef USE_DISPERSION\n\t\t\tfloat halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;\n\t\t\tvec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );\n\t\t\tfor ( int i = 0; i < 3; i ++ ) {\n\t\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );\n\t\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\t\trefractionCoords += 1.0;\n\t\t\t\trefractionCoords /= 2.0;\n\t\t\t\tvec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );\n\t\t\t\ttransmittedLight[ i ] = transmissionSample[ i ];\n\t\t\t\ttransmittedLight.a += transmissionSample.a;\n\t\t\t\ttransmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];\n\t\t\t}\n\t\t\ttransmittedLight.a /= 3.0;\n\t\t#else\n\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\trefractionCoords += 1.0;\n\t\t\trefractionCoords /= 2.0;\n\t\t\ttransmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\t\ttransmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\t#endif\n\t\tvec3 attenuatedColor = transmittance * transmittedLight.rgb;\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\tfloat transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );\n\t}\n#endif"; + +var uv_pars_fragment = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif"; + +var uv_pars_vertex = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tuniform mat3 mapTransform;\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform mat3 alphaMapTransform;\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tuniform mat3 lightMapTransform;\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tuniform mat3 aoMapTransform;\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tuniform mat3 bumpMapTransform;\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tuniform mat3 normalMapTransform;\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tuniform mat3 displacementMapTransform;\n\tvarying vec2 vDisplacementMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tuniform mat3 emissiveMapTransform;\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tuniform mat3 metalnessMapTransform;\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tuniform mat3 roughnessMapTransform;\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tuniform mat3 anisotropyMapTransform;\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tuniform mat3 clearcoatMapTransform;\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform mat3 clearcoatNormalMapTransform;\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform mat3 clearcoatRoughnessMapTransform;\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tuniform mat3 sheenColorMapTransform;\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tuniform mat3 sheenRoughnessMapTransform;\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tuniform mat3 iridescenceMapTransform;\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform mat3 iridescenceThicknessMapTransform;\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tuniform mat3 specularMapTransform;\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tuniform mat3 specularColorMapTransform;\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tuniform mat3 specularIntensityMapTransform;\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif"; + +var uv_vertex = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvUv = vec3( uv, 1 ).xy;\n#endif\n#ifdef USE_MAP\n\tvMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ALPHAMAP\n\tvAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_LIGHTMAP\n\tvLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_AOMAP\n\tvAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_BUMPMAP\n\tvBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_NORMALMAP\n\tvNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tvDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_METALNESSMAP\n\tvMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULARMAP\n\tvSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tvTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_THICKNESSMAP\n\tvThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;\n#endif"; + +var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_BATCHING\n\t\tworldPosition = batchingMatrix * worldPosition;\n\t#endif\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif"; + +const vertex$h = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}"; + +const fragment$h = "uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\ttexColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include \n\t#include \n}"; + +const vertex$g = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}"; + +const fragment$g = "#ifdef ENVMAP_TYPE_CUBE\n\tuniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n\tuniform sampler2D envMap;\n#endif\nuniform float flipEnvMap;\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nuniform mat3 backgroundRotation;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );\n\t#else\n\t\tvec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include \n\t#include \n}"; + +const vertex$f = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}"; + +const fragment$f = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = texColor;\n\tgl_FragColor.a *= opacity;\n\t#include \n\t#include \n}"; + +const vertex$e = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvHighPrecisionZW = gl_Position.zw;\n}"; + +const fragment$e = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#elif DEPTH_PACKING == 3202\n\t\tgl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );\n\t#elif DEPTH_PACKING == 3203\n\t\tgl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );\n\t#endif\n}"; + +const vertex$d = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvWorldPosition = worldPosition.xyz;\n}"; + +const fragment$d = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main () {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}"; + +const vertex$c = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}"; + +const fragment$c = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include \n\t#include \n}"; + +const vertex$b = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const fragment$b = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$a = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const fragment$a = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$9 = "#define LAMBERT\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const fragment$9 = "#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$8 = "#define MATCAP\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n}"; + +const fragment$8 = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}"; + +const fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}"; + +const vertex$6 = "#define PHONG\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const fragment$6 = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}"; + +const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define USE_SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef USE_SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULAR_COLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_DISPERSION\n\tuniform float dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\tuniform vec2 anisotropyVector;\n\t#ifdef USE_ANISOTROPYMAP\n\t\tuniform sampler2D anisotropyMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include \n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}"; + +const fragment$4 = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$3 = "uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \n#include \n#ifdef USE_POINTS_UV\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif\nvoid main() {\n\t#ifdef USE_POINTS_UV\n\t\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const fragment$3 = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const vertex$2 = "#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const fragment$2 = "uniform vec3 color;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include \n\t#include \n\t#include \n}"; + +const vertex$1 = "uniform float rotation;\nuniform vec2 center;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 mvPosition = modelViewMatrix[ 3 ];\n\tvec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include \n\t#include \n\t#include \n}"; + +const fragment$1 = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n}"; + +const ShaderChunk = { + alphahash_fragment: alphahash_fragment, + alphahash_pars_fragment: alphahash_pars_fragment, + alphamap_fragment: alphamap_fragment, + alphamap_pars_fragment: alphamap_pars_fragment, + alphatest_fragment: alphatest_fragment, + alphatest_pars_fragment: alphatest_pars_fragment, + aomap_fragment: aomap_fragment, + aomap_pars_fragment: aomap_pars_fragment, + batching_pars_vertex: batching_pars_vertex, + batching_vertex: batching_vertex, + begin_vertex: begin_vertex, + beginnormal_vertex: beginnormal_vertex, + bsdfs: bsdfs, + iridescence_fragment: iridescence_fragment, + bumpmap_pars_fragment: bumpmap_pars_fragment, + clipping_planes_fragment: clipping_planes_fragment, + clipping_planes_pars_fragment: clipping_planes_pars_fragment, + clipping_planes_pars_vertex: clipping_planes_pars_vertex, + clipping_planes_vertex: clipping_planes_vertex, + color_fragment: color_fragment, + color_pars_fragment: color_pars_fragment, + color_pars_vertex: color_pars_vertex, + color_vertex: color_vertex, + common: common, + cube_uv_reflection_fragment: cube_uv_reflection_fragment, + defaultnormal_vertex: defaultnormal_vertex, + displacementmap_pars_vertex: displacementmap_pars_vertex, + displacementmap_vertex: displacementmap_vertex, + emissivemap_fragment: emissivemap_fragment, + emissivemap_pars_fragment: emissivemap_pars_fragment, + colorspace_fragment: colorspace_fragment, + colorspace_pars_fragment: colorspace_pars_fragment, + envmap_fragment: envmap_fragment, + envmap_common_pars_fragment: envmap_common_pars_fragment, + envmap_pars_fragment: envmap_pars_fragment, + envmap_pars_vertex: envmap_pars_vertex, + envmap_physical_pars_fragment: envmap_physical_pars_fragment, + envmap_vertex: envmap_vertex, + fog_vertex: fog_vertex, + fog_pars_vertex: fog_pars_vertex, + fog_fragment: fog_fragment, + fog_pars_fragment: fog_pars_fragment, + gradientmap_pars_fragment: gradientmap_pars_fragment, + lightmap_pars_fragment: lightmap_pars_fragment, + lights_lambert_fragment: lights_lambert_fragment, + lights_lambert_pars_fragment: lights_lambert_pars_fragment, + lights_pars_begin: lights_pars_begin, + lights_toon_fragment: lights_toon_fragment, + lights_toon_pars_fragment: lights_toon_pars_fragment, + lights_phong_fragment: lights_phong_fragment, + lights_phong_pars_fragment: lights_phong_pars_fragment, + lights_physical_fragment: lights_physical_fragment, + lights_physical_pars_fragment: lights_physical_pars_fragment, + lights_fragment_begin: lights_fragment_begin, + lights_fragment_maps: lights_fragment_maps, + lights_fragment_end: lights_fragment_end, + logdepthbuf_fragment: logdepthbuf_fragment, + logdepthbuf_pars_fragment: logdepthbuf_pars_fragment, + logdepthbuf_pars_vertex: logdepthbuf_pars_vertex, + logdepthbuf_vertex: logdepthbuf_vertex, + map_fragment: map_fragment, + map_pars_fragment: map_pars_fragment, + map_particle_fragment: map_particle_fragment, + map_particle_pars_fragment: map_particle_pars_fragment, + metalnessmap_fragment: metalnessmap_fragment, + metalnessmap_pars_fragment: metalnessmap_pars_fragment, + morphinstance_vertex: morphinstance_vertex, + morphcolor_vertex: morphcolor_vertex, + morphnormal_vertex: morphnormal_vertex, + morphtarget_pars_vertex: morphtarget_pars_vertex, + morphtarget_vertex: morphtarget_vertex, + normal_fragment_begin: normal_fragment_begin, + normal_fragment_maps: normal_fragment_maps, + normal_pars_fragment: normal_pars_fragment, + normal_pars_vertex: normal_pars_vertex, + normal_vertex: normal_vertex, + normalmap_pars_fragment: normalmap_pars_fragment, + clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin, + clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps, + clearcoat_pars_fragment: clearcoat_pars_fragment, + iridescence_pars_fragment: iridescence_pars_fragment, + opaque_fragment: opaque_fragment, + packing: packing, + premultiplied_alpha_fragment: premultiplied_alpha_fragment, + project_vertex: project_vertex, + dithering_fragment: dithering_fragment, + dithering_pars_fragment: dithering_pars_fragment, + roughnessmap_fragment: roughnessmap_fragment, + roughnessmap_pars_fragment: roughnessmap_pars_fragment, + shadowmap_pars_fragment: shadowmap_pars_fragment, + shadowmap_pars_vertex: shadowmap_pars_vertex, + shadowmap_vertex: shadowmap_vertex, + shadowmask_pars_fragment: shadowmask_pars_fragment, + skinbase_vertex: skinbase_vertex, + skinning_pars_vertex: skinning_pars_vertex, + skinning_vertex: skinning_vertex, + skinnormal_vertex: skinnormal_vertex, + specularmap_fragment: specularmap_fragment, + specularmap_pars_fragment: specularmap_pars_fragment, + tonemapping_fragment: tonemapping_fragment, + tonemapping_pars_fragment: tonemapping_pars_fragment, + transmission_fragment: transmission_fragment, + transmission_pars_fragment: transmission_pars_fragment, + uv_pars_fragment: uv_pars_fragment, + uv_pars_vertex: uv_pars_vertex, + uv_vertex: uv_vertex, + worldpos_vertex: worldpos_vertex, + + background_vert: vertex$h, + background_frag: fragment$h, + backgroundCube_vert: vertex$g, + backgroundCube_frag: fragment$g, + cube_vert: vertex$f, + cube_frag: fragment$f, + depth_vert: vertex$e, + depth_frag: fragment$e, + distanceRGBA_vert: vertex$d, + distanceRGBA_frag: fragment$d, + equirect_vert: vertex$c, + equirect_frag: fragment$c, + linedashed_vert: vertex$b, + linedashed_frag: fragment$b, + meshbasic_vert: vertex$a, + meshbasic_frag: fragment$a, + meshlambert_vert: vertex$9, + meshlambert_frag: fragment$9, + meshmatcap_vert: vertex$8, + meshmatcap_frag: fragment$8, + meshnormal_vert: vertex$7, + meshnormal_frag: fragment$7, + meshphong_vert: vertex$6, + meshphong_frag: fragment$6, + meshphysical_vert: vertex$5, + meshphysical_frag: fragment$5, + meshtoon_vert: vertex$4, + meshtoon_frag: fragment$4, + points_vert: vertex$3, + points_frag: fragment$3, + shadow_vert: vertex$2, + shadow_frag: fragment$2, + sprite_vert: vertex$1, + sprite_frag: fragment$1 +}; + +// Uniforms library for shared webgl shaders +const UniformsLib = { + + common: { + + diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) }, + opacity: { value: 1.0 }, + + map: { value: null }, + mapTransform: { value: /*@__PURE__*/ new Matrix3() }, + + alphaMap: { value: null }, + alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + + alphaTest: { value: 0 } + + }, + + specularmap: { + + specularMap: { value: null }, + specularMapTransform: { value: /*@__PURE__*/ new Matrix3() } + + }, + + envmap: { + + envMap: { value: null }, + envMapRotation: { value: /*@__PURE__*/ new Matrix3() }, + flipEnvMap: { value: -1 }, + reflectivity: { value: 1.0 }, // basic, lambert, phong + ior: { value: 1.5 }, // physical + refractionRatio: { value: 0.98 }, // basic, lambert, phong + + }, + + aomap: { + + aoMap: { value: null }, + aoMapIntensity: { value: 1 }, + aoMapTransform: { value: /*@__PURE__*/ new Matrix3() } + + }, + + lightmap: { + + lightMap: { value: null }, + lightMapIntensity: { value: 1 }, + lightMapTransform: { value: /*@__PURE__*/ new Matrix3() } + + }, + + bumpmap: { + + bumpMap: { value: null }, + bumpMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + bumpScale: { value: 1 } + + }, + + normalmap: { + + normalMap: { value: null }, + normalMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) } + + }, + + displacementmap: { + + displacementMap: { value: null }, + displacementMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + displacementScale: { value: 1 }, + displacementBias: { value: 0 } + + }, + + emissivemap: { + + emissiveMap: { value: null }, + emissiveMapTransform: { value: /*@__PURE__*/ new Matrix3() } + + }, + + metalnessmap: { + + metalnessMap: { value: null }, + metalnessMapTransform: { value: /*@__PURE__*/ new Matrix3() } + + }, + + roughnessmap: { + + roughnessMap: { value: null }, + roughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() } + + }, + + gradientmap: { + + gradientMap: { value: null } + + }, + + fog: { + + fogDensity: { value: 0.00025 }, + fogNear: { value: 1 }, + fogFar: { value: 2000 }, + fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) } + + }, + + lights: { + + ambientLightColor: { value: [] }, + + lightProbe: { value: [] }, + + directionalLights: { value: [], properties: { + direction: {}, + color: {} + } }, + + directionalLightShadows: { value: [], properties: { + shadowIntensity: 1, + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, + + directionalShadowMap: { value: [] }, + directionalShadowMatrix: { value: [] }, + + spotLights: { value: [], properties: { + color: {}, + position: {}, + direction: {}, + distance: {}, + coneCos: {}, + penumbraCos: {}, + decay: {} + } }, + + spotLightShadows: { value: [], properties: { + shadowIntensity: 1, + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, + + spotLightMap: { value: [] }, + spotShadowMap: { value: [] }, + spotLightMatrix: { value: [] }, + + pointLights: { value: [], properties: { + color: {}, + position: {}, + decay: {}, + distance: {} + } }, + + pointLightShadows: { value: [], properties: { + shadowIntensity: 1, + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {}, + shadowCameraNear: {}, + shadowCameraFar: {} + } }, + + pointShadowMap: { value: [] }, + pointShadowMatrix: { value: [] }, + + hemisphereLights: { value: [], properties: { + direction: {}, + skyColor: {}, + groundColor: {} + } }, + + // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src + rectAreaLights: { value: [], properties: { + color: {}, + position: {}, + width: {}, + height: {} + } }, + + ltc_1: { value: null }, + ltc_2: { value: null } + + }, + + points: { + + diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) }, + opacity: { value: 1.0 }, + size: { value: 1.0 }, + scale: { value: 1.0 }, + map: { value: null }, + alphaMap: { value: null }, + alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + alphaTest: { value: 0 }, + uvTransform: { value: /*@__PURE__*/ new Matrix3() } + + }, + + sprite: { + + diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) }, + opacity: { value: 1.0 }, + center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) }, + rotation: { value: 0.0 }, + map: { value: null }, + mapTransform: { value: /*@__PURE__*/ new Matrix3() }, + alphaMap: { value: null }, + alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + alphaTest: { value: 0 } + + } + +}; + +const ShaderLib = { + + basic: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.fog + ] ), + + vertexShader: ShaderChunk.meshbasic_vert, + fragmentShader: ShaderChunk.meshbasic_frag + + }, + + lambert: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) } + } + ] ), + + vertexShader: ShaderChunk.meshlambert_vert, + fragmentShader: ShaderChunk.meshlambert_frag + + }, + + phong: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }, + specular: { value: /*@__PURE__*/ new Color( 0x111111 ) }, + shininess: { value: 30 } + } + ] ), + + vertexShader: ShaderChunk.meshphong_vert, + fragmentShader: ShaderChunk.meshphong_frag + + }, + + standard: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.roughnessmap, + UniformsLib.metalnessmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }, + roughness: { value: 1.0 }, + metalness: { value: 0.0 }, + envMapIntensity: { value: 1 } + } + ] ), + + vertexShader: ShaderChunk.meshphysical_vert, + fragmentShader: ShaderChunk.meshphysical_frag + + }, + + toon: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.gradientmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) } + } + ] ), + + vertexShader: ShaderChunk.meshtoon_vert, + fragmentShader: ShaderChunk.meshtoon_frag + + }, + + matcap: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.fog, + { + matcap: { value: null } + } + ] ), + + vertexShader: ShaderChunk.meshmatcap_vert, + fragmentShader: ShaderChunk.meshmatcap_frag + + }, + + points: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.points, + UniformsLib.fog + ] ), + + vertexShader: ShaderChunk.points_vert, + fragmentShader: ShaderChunk.points_frag + + }, + + dashed: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.fog, + { + scale: { value: 1 }, + dashSize: { value: 1 }, + totalSize: { value: 2 } + } + ] ), + + vertexShader: ShaderChunk.linedashed_vert, + fragmentShader: ShaderChunk.linedashed_frag + + }, + + depth: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.displacementmap + ] ), + + vertexShader: ShaderChunk.depth_vert, + fragmentShader: ShaderChunk.depth_frag + + }, + + normal: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + { + opacity: { value: 1.0 } + } + ] ), + + vertexShader: ShaderChunk.meshnormal_vert, + fragmentShader: ShaderChunk.meshnormal_frag + + }, + + sprite: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.sprite, + UniformsLib.fog + ] ), + + vertexShader: ShaderChunk.sprite_vert, + fragmentShader: ShaderChunk.sprite_frag + + }, + + background: { + + uniforms: { + uvTransform: { value: /*@__PURE__*/ new Matrix3() }, + t2D: { value: null }, + backgroundIntensity: { value: 1 } + }, + + vertexShader: ShaderChunk.background_vert, + fragmentShader: ShaderChunk.background_frag + + }, + + backgroundCube: { + + uniforms: { + envMap: { value: null }, + flipEnvMap: { value: -1 }, + backgroundBlurriness: { value: 0 }, + backgroundIntensity: { value: 1 }, + backgroundRotation: { value: /*@__PURE__*/ new Matrix3() } + }, + + vertexShader: ShaderChunk.backgroundCube_vert, + fragmentShader: ShaderChunk.backgroundCube_frag + + }, + + cube: { + + uniforms: { + tCube: { value: null }, + tFlip: { value: -1 }, + opacity: { value: 1.0 } + }, + + vertexShader: ShaderChunk.cube_vert, + fragmentShader: ShaderChunk.cube_frag + + }, + + equirect: { + + uniforms: { + tEquirect: { value: null }, + }, + + vertexShader: ShaderChunk.equirect_vert, + fragmentShader: ShaderChunk.equirect_frag + + }, + + distanceRGBA: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.common, + UniformsLib.displacementmap, + { + referencePosition: { value: /*@__PURE__*/ new Vector3() }, + nearDistance: { value: 1 }, + farDistance: { value: 1000 } + } + ] ), + + vertexShader: ShaderChunk.distanceRGBA_vert, + fragmentShader: ShaderChunk.distanceRGBA_frag + + }, + + shadow: { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + UniformsLib.lights, + UniformsLib.fog, + { + color: { value: /*@__PURE__*/ new Color( 0x00000 ) }, + opacity: { value: 1.0 } + }, + ] ), + + vertexShader: ShaderChunk.shadow_vert, + fragmentShader: ShaderChunk.shadow_frag + + } + +}; + +ShaderLib.physical = { + + uniforms: /*@__PURE__*/ mergeUniforms( [ + ShaderLib.standard.uniforms, + { + clearcoat: { value: 0 }, + clearcoatMap: { value: null }, + clearcoatMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + clearcoatNormalMap: { value: null }, + clearcoatNormalMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }, + clearcoatRoughness: { value: 0 }, + clearcoatRoughnessMap: { value: null }, + clearcoatRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + dispersion: { value: 0 }, + iridescence: { value: 0 }, + iridescenceMap: { value: null }, + iridescenceMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + iridescenceIOR: { value: 1.3 }, + iridescenceThicknessMinimum: { value: 100 }, + iridescenceThicknessMaximum: { value: 400 }, + iridescenceThicknessMap: { value: null }, + iridescenceThicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + sheen: { value: 0 }, + sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) }, + sheenColorMap: { value: null }, + sheenColorMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + sheenRoughness: { value: 1 }, + sheenRoughnessMap: { value: null }, + sheenRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + transmission: { value: 0 }, + transmissionMap: { value: null }, + transmissionMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() }, + transmissionSamplerMap: { value: null }, + thickness: { value: 0 }, + thicknessMap: { value: null }, + thicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + attenuationDistance: { value: 0 }, + attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) }, + specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) }, + specularColorMap: { value: null }, + specularColorMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + specularIntensity: { value: 1 }, + specularIntensityMap: { value: null }, + specularIntensityMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + anisotropyVector: { value: /*@__PURE__*/ new Vector2() }, + anisotropyMap: { value: null }, + anisotropyMapTransform: { value: /*@__PURE__*/ new Matrix3() }, + } + ] ), + + vertexShader: ShaderChunk.meshphysical_vert, + fragmentShader: ShaderChunk.meshphysical_frag + +}; + +const _rgb = { r: 0, b: 0, g: 0 }; +const _e1$1 = /*@__PURE__*/ new Euler(); +const _m1$1 = /*@__PURE__*/ new Matrix4(); + +function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) { + + const clearColor = new Color( 0x000000 ); + let clearAlpha = alpha === true ? 0 : 1; + + let planeMesh; + let boxMesh; + + let currentBackground = null; + let currentBackgroundVersion = 0; + let currentTonemapping = null; + + function getBackground( scene ) { + + let background = scene.isScene === true ? scene.background : null; + + if ( background && background.isTexture ) { + + const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background + background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background ); + + } + + return background; + + } + + function render( scene ) { + + let forceClear = false; + const background = getBackground( scene ); + + if ( background === null ) { + + setClear( clearColor, clearAlpha ); + + } else if ( background && background.isColor ) { + + setClear( background, 1 ); + forceClear = true; + + } + + const environmentBlendMode = renderer.xr.getEnvironmentBlendMode(); + + if ( environmentBlendMode === 'additive' ) { + + state.buffers.color.setClear( 0, 0, 0, 1, premultipliedAlpha ); + + } else if ( environmentBlendMode === 'alpha-blend' ) { + + state.buffers.color.setClear( 0, 0, 0, 0, premultipliedAlpha ); + + } + + if ( renderer.autoClear || forceClear ) { + + // buffers might not be writable which is required to ensure a correct clear + + state.buffers.depth.setTest( true ); + state.buffers.depth.setMask( true ); + state.buffers.color.setMask( true ); + + renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil ); + + } + + } + + function addToRenderList( renderList, scene ) { + + const background = getBackground( scene ); + + if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) { + + if ( boxMesh === undefined ) { + + boxMesh = new Mesh( + new BoxGeometry( 1, 1, 1 ), + new ShaderMaterial( { + name: 'BackgroundCubeMaterial', + uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ), + vertexShader: ShaderLib.backgroundCube.vertexShader, + fragmentShader: ShaderLib.backgroundCube.fragmentShader, + side: BackSide, + depthTest: false, + depthWrite: false, + fog: false, + allowOverride: false + } ) + ); + + boxMesh.geometry.deleteAttribute( 'normal' ); + boxMesh.geometry.deleteAttribute( 'uv' ); + + boxMesh.onBeforeRender = function ( renderer, scene, camera ) { + + this.matrixWorld.copyPosition( camera.matrixWorld ); + + }; + + // add "envMap" material property so the renderer can evaluate it like for built-in materials + Object.defineProperty( boxMesh.material, 'envMap', { + + get: function () { + + return this.uniforms.envMap.value; + + } + + } ); + + objects.update( boxMesh ); + + } + + _e1$1.copy( scene.backgroundRotation ); + + // accommodate left-handed frame + _e1$1.x *= -1; _e1$1.y *= -1; _e1$1.z *= -1; + + if ( background.isCubeTexture && background.isRenderTargetTexture === false ) { + + // environment maps which are not cube render targets or PMREMs follow a different convention + _e1$1.y *= -1; + _e1$1.z *= -1; + + } + + boxMesh.material.uniforms.envMap.value = background; + boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? -1 : 1; + boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness; + boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity; + boxMesh.material.uniforms.backgroundRotation.value.setFromMatrix4( _m1$1.makeRotationFromEuler( _e1$1 ) ); + boxMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer; + + if ( currentBackground !== background || + currentBackgroundVersion !== background.version || + currentTonemapping !== renderer.toneMapping ) { + + boxMesh.material.needsUpdate = true; + + currentBackground = background; + currentBackgroundVersion = background.version; + currentTonemapping = renderer.toneMapping; + + } + + boxMesh.layers.enableAll(); + + // push to the pre-sorted opaque render list + renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null ); + + } else if ( background && background.isTexture ) { + + if ( planeMesh === undefined ) { + + planeMesh = new Mesh( + new PlaneGeometry( 2, 2 ), + new ShaderMaterial( { + name: 'BackgroundMaterial', + uniforms: cloneUniforms( ShaderLib.background.uniforms ), + vertexShader: ShaderLib.background.vertexShader, + fragmentShader: ShaderLib.background.fragmentShader, + side: FrontSide, + depthTest: false, + depthWrite: false, + fog: false, + allowOverride: false + } ) + ); + + planeMesh.geometry.deleteAttribute( 'normal' ); + + // add "map" material property so the renderer can evaluate it like for built-in materials + Object.defineProperty( planeMesh.material, 'map', { + + get: function () { + + return this.uniforms.t2D.value; + + } + + } ); + + objects.update( planeMesh ); + + } + + planeMesh.material.uniforms.t2D.value = background; + planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity; + planeMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer; + + if ( background.matrixAutoUpdate === true ) { + + background.updateMatrix(); + + } + + planeMesh.material.uniforms.uvTransform.value.copy( background.matrix ); + + if ( currentBackground !== background || + currentBackgroundVersion !== background.version || + currentTonemapping !== renderer.toneMapping ) { + + planeMesh.material.needsUpdate = true; + + currentBackground = background; + currentBackgroundVersion = background.version; + currentTonemapping = renderer.toneMapping; + + } + + planeMesh.layers.enableAll(); + + // push to the pre-sorted opaque render list + renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null ); + + } + + } + + function setClear( color, alpha ) { + + color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) ); + + state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha ); + + } + + function dispose() { + + if ( boxMesh !== undefined ) { + + boxMesh.geometry.dispose(); + boxMesh.material.dispose(); + + boxMesh = undefined; + + } + + if ( planeMesh !== undefined ) { + + planeMesh.geometry.dispose(); + planeMesh.material.dispose(); + + planeMesh = undefined; + + } + + } + + return { + + getClearColor: function () { + + return clearColor; + + }, + setClearColor: function ( color, alpha = 1 ) { + + clearColor.set( color ); + clearAlpha = alpha; + setClear( clearColor, clearAlpha ); + + }, + getClearAlpha: function () { + + return clearAlpha; + + }, + setClearAlpha: function ( alpha ) { + + clearAlpha = alpha; + setClear( clearColor, clearAlpha ); + + }, + render: render, + addToRenderList: addToRenderList, + dispose: dispose + + }; + +} + +function WebGLBindingStates( gl, attributes ) { + + const maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS ); + + const bindingStates = {}; + + const defaultState = createBindingState( null ); + let currentState = defaultState; + let forceUpdate = false; + + function setup( object, material, program, geometry, index ) { + + let updateBuffers = false; + + const state = getBindingState( geometry, program, material ); + + if ( currentState !== state ) { + + currentState = state; + bindVertexArrayObject( currentState.object ); + + } + + updateBuffers = needsUpdate( object, geometry, program, index ); + + if ( updateBuffers ) saveCache( object, geometry, program, index ); + + if ( index !== null ) { + + attributes.update( index, gl.ELEMENT_ARRAY_BUFFER ); + + } + + if ( updateBuffers || forceUpdate ) { + + forceUpdate = false; + + setupVertexAttributes( object, material, program, geometry ); + + if ( index !== null ) { + + gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer ); + + } + + } + + } + + function createVertexArrayObject() { + + return gl.createVertexArray(); + + } + + function bindVertexArrayObject( vao ) { + + return gl.bindVertexArray( vao ); + + } + + function deleteVertexArrayObject( vao ) { + + return gl.deleteVertexArray( vao ); + + } + + function getBindingState( geometry, program, material ) { + + const wireframe = ( material.wireframe === true ); + + let programMap = bindingStates[ geometry.id ]; + + if ( programMap === undefined ) { + + programMap = {}; + bindingStates[ geometry.id ] = programMap; + + } + + let stateMap = programMap[ program.id ]; + + if ( stateMap === undefined ) { + + stateMap = {}; + programMap[ program.id ] = stateMap; + + } + + let state = stateMap[ wireframe ]; + + if ( state === undefined ) { + + state = createBindingState( createVertexArrayObject() ); + stateMap[ wireframe ] = state; + + } + + return state; + + } + + function createBindingState( vao ) { + + const newAttributes = []; + const enabledAttributes = []; + const attributeDivisors = []; + + for ( let i = 0; i < maxVertexAttributes; i ++ ) { + + newAttributes[ i ] = 0; + enabledAttributes[ i ] = 0; + attributeDivisors[ i ] = 0; + + } + + return { + + // for backward compatibility on non-VAO support browser + geometry: null, + program: null, + wireframe: false, + + newAttributes: newAttributes, + enabledAttributes: enabledAttributes, + attributeDivisors: attributeDivisors, + object: vao, + attributes: {}, + index: null + + }; + + } + + function needsUpdate( object, geometry, program, index ) { + + const cachedAttributes = currentState.attributes; + const geometryAttributes = geometry.attributes; + + let attributesNum = 0; + + const programAttributes = program.getAttributes(); + + for ( const name in programAttributes ) { + + const programAttribute = programAttributes[ name ]; + + if ( programAttribute.location >= 0 ) { + + const cachedAttribute = cachedAttributes[ name ]; + let geometryAttribute = geometryAttributes[ name ]; + + if ( geometryAttribute === undefined ) { + + if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix; + if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor; + + } + + if ( cachedAttribute === undefined ) return true; + + if ( cachedAttribute.attribute !== geometryAttribute ) return true; + + if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true; + + attributesNum ++; + + } + + } + + if ( currentState.attributesNum !== attributesNum ) return true; + + if ( currentState.index !== index ) return true; + + return false; + + } + + function saveCache( object, geometry, program, index ) { + + const cache = {}; + const attributes = geometry.attributes; + let attributesNum = 0; + + const programAttributes = program.getAttributes(); + + for ( const name in programAttributes ) { + + const programAttribute = programAttributes[ name ]; + + if ( programAttribute.location >= 0 ) { + + let attribute = attributes[ name ]; + + if ( attribute === undefined ) { + + if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix; + if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor; + + } + + const data = {}; + data.attribute = attribute; + + if ( attribute && attribute.data ) { + + data.data = attribute.data; + + } + + cache[ name ] = data; + + attributesNum ++; + + } + + } + + currentState.attributes = cache; + currentState.attributesNum = attributesNum; + + currentState.index = index; + + } + + function initAttributes() { + + const newAttributes = currentState.newAttributes; + + for ( let i = 0, il = newAttributes.length; i < il; i ++ ) { + + newAttributes[ i ] = 0; + + } + + } + + function enableAttribute( attribute ) { + + enableAttributeAndDivisor( attribute, 0 ); + + } + + function enableAttributeAndDivisor( attribute, meshPerAttribute ) { + + const newAttributes = currentState.newAttributes; + const enabledAttributes = currentState.enabledAttributes; + const attributeDivisors = currentState.attributeDivisors; + + newAttributes[ attribute ] = 1; + + if ( enabledAttributes[ attribute ] === 0 ) { + + gl.enableVertexAttribArray( attribute ); + enabledAttributes[ attribute ] = 1; + + } + + if ( attributeDivisors[ attribute ] !== meshPerAttribute ) { + + gl.vertexAttribDivisor( attribute, meshPerAttribute ); + attributeDivisors[ attribute ] = meshPerAttribute; + + } + + } + + function disableUnusedAttributes() { + + const newAttributes = currentState.newAttributes; + const enabledAttributes = currentState.enabledAttributes; + + for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) { + + if ( enabledAttributes[ i ] !== newAttributes[ i ] ) { + + gl.disableVertexAttribArray( i ); + enabledAttributes[ i ] = 0; + + } + + } + + } + + function vertexAttribPointer( index, size, type, normalized, stride, offset, integer ) { + + if ( integer === true ) { + + gl.vertexAttribIPointer( index, size, type, stride, offset ); + + } else { + + gl.vertexAttribPointer( index, size, type, normalized, stride, offset ); + + } + + } + + function setupVertexAttributes( object, material, program, geometry ) { + + initAttributes(); + + const geometryAttributes = geometry.attributes; + + const programAttributes = program.getAttributes(); + + const materialDefaultAttributeValues = material.defaultAttributeValues; + + for ( const name in programAttributes ) { + + const programAttribute = programAttributes[ name ]; + + if ( programAttribute.location >= 0 ) { + + let geometryAttribute = geometryAttributes[ name ]; + + if ( geometryAttribute === undefined ) { + + if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix; + if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor; + + } + + if ( geometryAttribute !== undefined ) { + + const normalized = geometryAttribute.normalized; + const size = geometryAttribute.itemSize; + + const attribute = attributes.get( geometryAttribute ); + + // TODO Attribute may not be available on context restore + + if ( attribute === undefined ) continue; + + const buffer = attribute.buffer; + const type = attribute.type; + const bytesPerElement = attribute.bytesPerElement; + + // check for integer attributes + + const integer = ( type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType ); + + if ( geometryAttribute.isInterleavedBufferAttribute ) { + + const data = geometryAttribute.data; + const stride = data.stride; + const offset = geometryAttribute.offset; + + if ( data.isInstancedInterleavedBuffer ) { + + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { + + enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute ); + + } + + if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) { + + geometry._maxInstanceCount = data.meshPerAttribute * data.count; + + } + + } else { + + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { + + enableAttribute( programAttribute.location + i ); + + } + + } + + gl.bindBuffer( gl.ARRAY_BUFFER, buffer ); + + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { + + vertexAttribPointer( + programAttribute.location + i, + size / programAttribute.locationSize, + type, + normalized, + stride * bytesPerElement, + ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement, + integer + ); + + } + + } else { + + if ( geometryAttribute.isInstancedBufferAttribute ) { + + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { + + enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute ); + + } + + if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) { + + geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count; + + } + + } else { + + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { + + enableAttribute( programAttribute.location + i ); + + } + + } + + gl.bindBuffer( gl.ARRAY_BUFFER, buffer ); + + for ( let i = 0; i < programAttribute.locationSize; i ++ ) { + + vertexAttribPointer( + programAttribute.location + i, + size / programAttribute.locationSize, + type, + normalized, + size * bytesPerElement, + ( size / programAttribute.locationSize ) * i * bytesPerElement, + integer + ); + + } + + } + + } else if ( materialDefaultAttributeValues !== undefined ) { + + const value = materialDefaultAttributeValues[ name ]; + + if ( value !== undefined ) { + + switch ( value.length ) { + + case 2: + gl.vertexAttrib2fv( programAttribute.location, value ); + break; + + case 3: + gl.vertexAttrib3fv( programAttribute.location, value ); + break; + + case 4: + gl.vertexAttrib4fv( programAttribute.location, value ); + break; + + default: + gl.vertexAttrib1fv( programAttribute.location, value ); + + } + + } + + } + + } + + } + + disableUnusedAttributes(); + + } + + function dispose() { + + reset(); + + for ( const geometryId in bindingStates ) { + + const programMap = bindingStates[ geometryId ]; + + for ( const programId in programMap ) { + + const stateMap = programMap[ programId ]; + + for ( const wireframe in stateMap ) { + + deleteVertexArrayObject( stateMap[ wireframe ].object ); + + delete stateMap[ wireframe ]; + + } + + delete programMap[ programId ]; + + } + + delete bindingStates[ geometryId ]; + + } + + } + + function releaseStatesOfGeometry( geometry ) { + + if ( bindingStates[ geometry.id ] === undefined ) return; + + const programMap = bindingStates[ geometry.id ]; + + for ( const programId in programMap ) { + + const stateMap = programMap[ programId ]; + + for ( const wireframe in stateMap ) { + + deleteVertexArrayObject( stateMap[ wireframe ].object ); + + delete stateMap[ wireframe ]; + + } + + delete programMap[ programId ]; + + } + + delete bindingStates[ geometry.id ]; + + } + + function releaseStatesOfProgram( program ) { + + for ( const geometryId in bindingStates ) { + + const programMap = bindingStates[ geometryId ]; + + if ( programMap[ program.id ] === undefined ) continue; + + const stateMap = programMap[ program.id ]; + + for ( const wireframe in stateMap ) { + + deleteVertexArrayObject( stateMap[ wireframe ].object ); + + delete stateMap[ wireframe ]; + + } + + delete programMap[ program.id ]; + + } + + } + + function reset() { + + resetDefaultState(); + forceUpdate = true; + + if ( currentState === defaultState ) return; + + currentState = defaultState; + bindVertexArrayObject( currentState.object ); + + } + + // for backward-compatibility + + function resetDefaultState() { + + defaultState.geometry = null; + defaultState.program = null; + defaultState.wireframe = false; + + } + + return { + + setup: setup, + reset: reset, + resetDefaultState: resetDefaultState, + dispose: dispose, + releaseStatesOfGeometry: releaseStatesOfGeometry, + releaseStatesOfProgram: releaseStatesOfProgram, + + initAttributes: initAttributes, + enableAttribute: enableAttribute, + disableUnusedAttributes: disableUnusedAttributes + + }; + +} + +function WebGLBufferRenderer( gl, extensions, info ) { + + let mode; + + function setMode( value ) { + + mode = value; + + } + + function render( start, count ) { + + gl.drawArrays( mode, start, count ); + + info.update( count, mode, 1 ); + + } + + function renderInstances( start, count, primcount ) { + + if ( primcount === 0 ) return; + + gl.drawArraysInstanced( mode, start, count, primcount ); + + info.update( count, mode, primcount ); + + } + + function renderMultiDraw( starts, counts, drawCount ) { + + if ( drawCount === 0 ) return; + + const extension = extensions.get( 'WEBGL_multi_draw' ); + extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount ); + + let elementCount = 0; + for ( let i = 0; i < drawCount; i ++ ) { + + elementCount += counts[ i ]; + + } + + info.update( elementCount, mode, 1 ); + + } + + function renderMultiDrawInstances( starts, counts, drawCount, primcount ) { + + if ( drawCount === 0 ) return; + + const extension = extensions.get( 'WEBGL_multi_draw' ); + + if ( extension === null ) { + + for ( let i = 0; i < starts.length; i ++ ) { + + renderInstances( starts[ i ], counts[ i ], primcount[ i ] ); + + } + + } else { + + extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount ); + + let elementCount = 0; + for ( let i = 0; i < drawCount; i ++ ) { + + elementCount += counts[ i ] * primcount[ i ]; + + } + + info.update( elementCount, mode, 1 ); + + } + + } + + // + + this.setMode = setMode; + this.render = render; + this.renderInstances = renderInstances; + this.renderMultiDraw = renderMultiDraw; + this.renderMultiDrawInstances = renderMultiDrawInstances; + +} + +function WebGLCapabilities( gl, extensions, parameters, utils ) { + + let maxAnisotropy; + + function getMaxAnisotropy() { + + if ( maxAnisotropy !== undefined ) return maxAnisotropy; + + if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) { + + const extension = extensions.get( 'EXT_texture_filter_anisotropic' ); + + maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT ); + + } else { + + maxAnisotropy = 0; + + } + + return maxAnisotropy; + + } + + function textureFormatReadable( textureFormat ) { + + if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) { + + return false; + + } + + return true; + + } + + function textureTypeReadable( textureType ) { + + const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) ); + + if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // Edge and Chrome Mac < 52 (#9513) + textureType !== FloatType && ! halfFloatSupportedByExt ) { + + return false; + + } + + return true; + + } + + function getMaxPrecision( precision ) { + + if ( precision === 'highp' ) { + + if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 && + gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) { + + return 'highp'; + + } + + precision = 'mediump'; + + } + + if ( precision === 'mediump' ) { + + if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 && + gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) { + + return 'mediump'; + + } + + } + + return 'lowp'; + + } + + let precision = parameters.precision !== undefined ? parameters.precision : 'highp'; + const maxPrecision = getMaxPrecision( precision ); + + if ( maxPrecision !== precision ) { + + console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' ); + precision = maxPrecision; + + } + + const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true; + const reverseDepthBuffer = parameters.reverseDepthBuffer === true && extensions.has( 'EXT_clip_control' ); + + const maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS ); + const maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ); + const maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE ); + const maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE ); + + const maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS ); + const maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS ); + const maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS ); + const maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS ); + + const vertexTextures = maxVertexTextures > 0; + + const maxSamples = gl.getParameter( gl.MAX_SAMPLES ); + + return { + + isWebGL2: true, // keeping this for backwards compatibility + + getMaxAnisotropy: getMaxAnisotropy, + getMaxPrecision: getMaxPrecision, + + textureFormatReadable: textureFormatReadable, + textureTypeReadable: textureTypeReadable, + + precision: precision, + logarithmicDepthBuffer: logarithmicDepthBuffer, + reverseDepthBuffer: reverseDepthBuffer, + + maxTextures: maxTextures, + maxVertexTextures: maxVertexTextures, + maxTextureSize: maxTextureSize, + maxCubemapSize: maxCubemapSize, + + maxAttributes: maxAttributes, + maxVertexUniforms: maxVertexUniforms, + maxVaryings: maxVaryings, + maxFragmentUniforms: maxFragmentUniforms, + + vertexTextures: vertexTextures, + + maxSamples: maxSamples + + }; + +} + +function WebGLClipping( properties ) { + + const scope = this; + + let globalState = null, + numGlobalPlanes = 0, + localClippingEnabled = false, + renderingShadows = false; + + const plane = new Plane(), + viewNormalMatrix = new Matrix3(), + + uniform = { value: null, needsUpdate: false }; + + this.uniform = uniform; + this.numPlanes = 0; + this.numIntersection = 0; + + this.init = function ( planes, enableLocalClipping ) { + + const enabled = + planes.length !== 0 || + enableLocalClipping || + // enable state of previous frame - the clipping code has to + // run another frame in order to reset the state: + numGlobalPlanes !== 0 || + localClippingEnabled; + + localClippingEnabled = enableLocalClipping; + + numGlobalPlanes = planes.length; + + return enabled; + + }; + + this.beginShadows = function () { + + renderingShadows = true; + projectPlanes( null ); + + }; + + this.endShadows = function () { + + renderingShadows = false; + + }; + + this.setGlobalState = function ( planes, camera ) { + + globalState = projectPlanes( planes, camera, 0 ); + + }; + + this.setState = function ( material, camera, useCache ) { + + const planes = material.clippingPlanes, + clipIntersection = material.clipIntersection, + clipShadows = material.clipShadows; + + const materialProperties = properties.get( material ); + + if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) { + + // there's no local clipping + + if ( renderingShadows ) { + + // there's no global clipping + + projectPlanes( null ); + + } else { + + resetGlobalState(); + + } + + } else { + + const nGlobal = renderingShadows ? 0 : numGlobalPlanes, + lGlobal = nGlobal * 4; + + let dstArray = materialProperties.clippingState || null; + + uniform.value = dstArray; // ensure unique state + + dstArray = projectPlanes( planes, camera, lGlobal, useCache ); + + for ( let i = 0; i !== lGlobal; ++ i ) { + + dstArray[ i ] = globalState[ i ]; + + } + + materialProperties.clippingState = dstArray; + this.numIntersection = clipIntersection ? this.numPlanes : 0; + this.numPlanes += nGlobal; + + } + + + }; + + function resetGlobalState() { + + if ( uniform.value !== globalState ) { + + uniform.value = globalState; + uniform.needsUpdate = numGlobalPlanes > 0; + + } + + scope.numPlanes = numGlobalPlanes; + scope.numIntersection = 0; + + } + + function projectPlanes( planes, camera, dstOffset, skipTransform ) { + + const nPlanes = planes !== null ? planes.length : 0; + let dstArray = null; + + if ( nPlanes !== 0 ) { + + dstArray = uniform.value; + + if ( skipTransform !== true || dstArray === null ) { + + const flatSize = dstOffset + nPlanes * 4, + viewMatrix = camera.matrixWorldInverse; + + viewNormalMatrix.getNormalMatrix( viewMatrix ); + + if ( dstArray === null || dstArray.length < flatSize ) { + + dstArray = new Float32Array( flatSize ); + + } + + for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) { + + plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix ); + + plane.normal.toArray( dstArray, i4 ); + dstArray[ i4 + 3 ] = plane.constant; + + } + + } + + uniform.value = dstArray; + uniform.needsUpdate = true; + + } + + scope.numPlanes = nPlanes; + scope.numIntersection = 0; + + return dstArray; + + } + +} + +function WebGLCubeMaps( renderer ) { + + let cubemaps = new WeakMap(); + + function mapTextureMapping( texture, mapping ) { + + if ( mapping === EquirectangularReflectionMapping ) { + + texture.mapping = CubeReflectionMapping; + + } else if ( mapping === EquirectangularRefractionMapping ) { + + texture.mapping = CubeRefractionMapping; + + } + + return texture; + + } + + function get( texture ) { + + if ( texture && texture.isTexture ) { + + const mapping = texture.mapping; + + if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) { + + if ( cubemaps.has( texture ) ) { + + const cubemap = cubemaps.get( texture ).texture; + return mapTextureMapping( cubemap, texture.mapping ); + + } else { + + const image = texture.image; + + if ( image && image.height > 0 ) { + + const renderTarget = new WebGLCubeRenderTarget( image.height ); + renderTarget.fromEquirectangularTexture( renderer, texture ); + cubemaps.set( texture, renderTarget ); + + texture.addEventListener( 'dispose', onTextureDispose ); + + return mapTextureMapping( renderTarget.texture, texture.mapping ); + + } else { + + // image not yet ready. try the conversion next frame + + return null; + + } + + } + + } + + } + + return texture; + + } + + function onTextureDispose( event ) { + + const texture = event.target; + + texture.removeEventListener( 'dispose', onTextureDispose ); + + const cubemap = cubemaps.get( texture ); + + if ( cubemap !== undefined ) { + + cubemaps.delete( texture ); + cubemap.dispose(); + + } + + } + + function dispose() { + + cubemaps = new WeakMap(); + + } + + return { + get: get, + dispose: dispose + }; + +} + +const LOD_MIN = 4; + +// The standard deviations (radians) associated with the extra mips. These are +// chosen to approximate a Trowbridge-Reitz distribution function times the +// geometric shadowing function. These sigma values squared must match the +// variance #defines in cube_uv_reflection_fragment.glsl.js. +const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ]; + +// The maximum length of the blur for loop. Smaller sigmas will use fewer +// samples and exit early, but not recompile the shader. +const MAX_SAMPLES = 20; + +const _flatCamera = /*@__PURE__*/ new OrthographicCamera(); +const _clearColor = /*@__PURE__*/ new Color(); +let _oldTarget = null; +let _oldActiveCubeFace = 0; +let _oldActiveMipmapLevel = 0; +let _oldXrEnabled = false; + +// Golden Ratio +const PHI = ( 1 + Math.sqrt( 5 ) ) / 2; +const INV_PHI = 1 / PHI; + +// Vertices of a dodecahedron (except the opposites, which represent the +// same axis), used as axis directions evenly spread on a sphere. +const _axisDirections = [ + /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ), + /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ), + /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ), + /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ), + /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ), + /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ), + /*@__PURE__*/ new Vector3( -1, 1, -1 ), + /*@__PURE__*/ new Vector3( 1, 1, -1 ), + /*@__PURE__*/ new Vector3( -1, 1, 1 ), + /*@__PURE__*/ new Vector3( 1, 1, 1 ) ]; + +const _origin = /*@__PURE__*/ new Vector3(); + +/** + * This class generates a Prefiltered, Mipmapped Radiance Environment Map + * (PMREM) from a cubeMap environment texture. This allows different levels of + * blur to be quickly accessed based on material roughness. It is packed into a + * special CubeUV format that allows us to perform custom interpolation so that + * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap + * chain, it only goes down to the LOD_MIN level (above), and then creates extra + * even more filtered 'mips' at the same LOD_MIN resolution, associated with + * higher roughness levels. In this way we maintain resolution to smoothly + * interpolate diffuse lighting while limiting sampling computation. + * + * Paper: Fast, Accurate Image-Based Lighting: + * {@link https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view} +*/ +class PMREMGenerator { + + /** + * Constructs a new PMREM generator. + * + * @param {WebGLRenderer} renderer - The renderer. + */ + constructor( renderer ) { + + this._renderer = renderer; + this._pingPongRenderTarget = null; + + this._lodMax = 0; + this._cubeSize = 0; + this._lodPlanes = []; + this._sizeLods = []; + this._sigmas = []; + + this._blurMaterial = null; + this._cubemapMaterial = null; + this._equirectMaterial = null; + + this._compileMaterial( this._blurMaterial ); + + } + + /** + * Generates a PMREM from a supplied Scene, which can be faster than using an + * image if networking bandwidth is low. Optional sigma specifies a blur radius + * in radians to be applied to the scene before PMREM generation. Optional near + * and far planes ensure the scene is rendered in its entirety. + * + * @param {Scene} scene - The scene to be captured. + * @param {number} [sigma=0] - The blur radius in radians. + * @param {number} [near=0.1] - The near plane distance. + * @param {number} [far=100] - The far plane distance. + * @param {Object} [options={}] - The configuration options. + * @param {number} [options.size=256] - The texture size of the PMREM. + * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene. + * @return {WebGLRenderTarget} The resulting PMREM. + */ + fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) { + + const { + size = 256, + position = _origin, + } = options; + + _oldTarget = this._renderer.getRenderTarget(); + _oldActiveCubeFace = this._renderer.getActiveCubeFace(); + _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel(); + _oldXrEnabled = this._renderer.xr.enabled; + + this._renderer.xr.enabled = false; + + this._setSize( size ); + + const cubeUVRenderTarget = this._allocateTargets(); + cubeUVRenderTarget.depthBuffer = true; + + this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ); + + if ( sigma > 0 ) { + + this._blur( cubeUVRenderTarget, 0, 0, sigma ); + + } + + this._applyPMREM( cubeUVRenderTarget ); + this._cleanup( cubeUVRenderTarget ); + + return cubeUVRenderTarget; + + } + + /** + * Generates a PMREM from an equirectangular texture, which can be either LDR + * or HDR. The ideal input image size is 1k (1024 x 512), + * as this matches best with the 256 x 256 cubemap output. + * + * @param {Texture} equirectangular - The equirectangular texture to be converted. + * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use. + * @return {WebGLRenderTarget} The resulting PMREM. + */ + fromEquirectangular( equirectangular, renderTarget = null ) { + + return this._fromTexture( equirectangular, renderTarget ); + + } + + /** + * Generates a PMREM from an cubemap texture, which can be either LDR + * or HDR. The ideal input cube size is 256 x 256, + * as this matches best with the 256 x 256 cubemap output. + * + * @param {Texture} cubemap - The cubemap texture to be converted. + * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use. + * @return {WebGLRenderTarget} The resulting PMREM. + */ + fromCubemap( cubemap, renderTarget = null ) { + + return this._fromTexture( cubemap, renderTarget ); + + } + + /** + * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during + * your texture's network fetch for increased concurrency. + */ + compileCubemapShader() { + + if ( this._cubemapMaterial === null ) { + + this._cubemapMaterial = _getCubemapMaterial(); + this._compileMaterial( this._cubemapMaterial ); + + } + + } + + /** + * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during + * your texture's network fetch for increased concurrency. + */ + compileEquirectangularShader() { + + if ( this._equirectMaterial === null ) { + + this._equirectMaterial = _getEquirectMaterial(); + this._compileMaterial( this._equirectMaterial ); + + } + + } + + /** + * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class, + * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on + * one of them will cause any others to also become unusable. + */ + dispose() { + + this._dispose(); + + if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose(); + if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose(); + + } + + // private interface + + _setSize( cubeSize ) { + + this._lodMax = Math.floor( Math.log2( cubeSize ) ); + this._cubeSize = Math.pow( 2, this._lodMax ); + + } + + _dispose() { + + if ( this._blurMaterial !== null ) this._blurMaterial.dispose(); + + if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose(); + + for ( let i = 0; i < this._lodPlanes.length; i ++ ) { + + this._lodPlanes[ i ].dispose(); + + } + + } + + _cleanup( outputTarget ) { + + this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel ); + this._renderer.xr.enabled = _oldXrEnabled; + + outputTarget.scissorTest = false; + _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height ); + + } + + _fromTexture( texture, renderTarget ) { + + if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) { + + this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) ); + + } else { // Equirectangular + + this._setSize( texture.image.width / 4 ); + + } + + _oldTarget = this._renderer.getRenderTarget(); + _oldActiveCubeFace = this._renderer.getActiveCubeFace(); + _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel(); + _oldXrEnabled = this._renderer.xr.enabled; + + this._renderer.xr.enabled = false; + + const cubeUVRenderTarget = renderTarget || this._allocateTargets(); + this._textureToCubeUV( texture, cubeUVRenderTarget ); + this._applyPMREM( cubeUVRenderTarget ); + this._cleanup( cubeUVRenderTarget ); + + return cubeUVRenderTarget; + + } + + _allocateTargets() { + + const width = 3 * Math.max( this._cubeSize, 16 * 7 ); + const height = 4 * this._cubeSize; + + const params = { + magFilter: LinearFilter, + minFilter: LinearFilter, + generateMipmaps: false, + type: HalfFloatType, + format: RGBAFormat, + colorSpace: LinearSRGBColorSpace, + depthBuffer: false + }; + + const cubeUVRenderTarget = _createRenderTarget( width, height, params ); + + if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) { + + if ( this._pingPongRenderTarget !== null ) { + + this._dispose(); + + } + + this._pingPongRenderTarget = _createRenderTarget( width, height, params ); + + const { _lodMax } = this; + ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) ); + + this._blurMaterial = _getBlurShader( _lodMax, width, height ); + + } + + return cubeUVRenderTarget; + + } + + _compileMaterial( material ) { + + const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material ); + this._renderer.compile( tmpMesh, _flatCamera ); + + } + + _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) { + + const fov = 90; + const aspect = 1; + const cubeCamera = new PerspectiveCamera( fov, aspect, near, far ); + const upSign = [ 1, -1, 1, 1, 1, 1 ]; + const forwardSign = [ 1, 1, 1, -1, -1, -1 ]; + const renderer = this._renderer; + + const originalAutoClear = renderer.autoClear; + const toneMapping = renderer.toneMapping; + renderer.getClearColor( _clearColor ); + + renderer.toneMapping = NoToneMapping; + renderer.autoClear = false; + + const backgroundMaterial = new MeshBasicMaterial( { + name: 'PMREM.Background', + side: BackSide, + depthWrite: false, + depthTest: false, + } ); + + const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial ); + + let useSolidColor = false; + const background = scene.background; + + if ( background ) { + + if ( background.isColor ) { + + backgroundMaterial.color.copy( background ); + scene.background = null; + useSolidColor = true; + + } + + } else { + + backgroundMaterial.color.copy( _clearColor ); + useSolidColor = true; + + } + + for ( let i = 0; i < 6; i ++ ) { + + const col = i % 3; + + if ( col === 0 ) { + + cubeCamera.up.set( 0, upSign[ i ], 0 ); + cubeCamera.position.set( position.x, position.y, position.z ); + cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z ); + + } else if ( col === 1 ) { + + cubeCamera.up.set( 0, 0, upSign[ i ] ); + cubeCamera.position.set( position.x, position.y, position.z ); + cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z ); + + + } else { + + cubeCamera.up.set( 0, upSign[ i ], 0 ); + cubeCamera.position.set( position.x, position.y, position.z ); + cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] ); + + } + + const size = this._cubeSize; + + _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size ); + + renderer.setRenderTarget( cubeUVRenderTarget ); + + if ( useSolidColor ) { + + renderer.render( backgroundBox, cubeCamera ); + + } + + renderer.render( scene, cubeCamera ); + + } + + backgroundBox.geometry.dispose(); + backgroundBox.material.dispose(); + + renderer.toneMapping = toneMapping; + renderer.autoClear = originalAutoClear; + scene.background = background; + + } + + _textureToCubeUV( texture, cubeUVRenderTarget ) { + + const renderer = this._renderer; + + const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ); + + if ( isCubeTexture ) { + + if ( this._cubemapMaterial === null ) { + + this._cubemapMaterial = _getCubemapMaterial(); + + } + + this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? -1 : 1; + + } else { + + if ( this._equirectMaterial === null ) { + + this._equirectMaterial = _getEquirectMaterial(); + + } + + } + + const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial; + const mesh = new Mesh( this._lodPlanes[ 0 ], material ); + + const uniforms = material.uniforms; + + uniforms[ 'envMap' ].value = texture; + + const size = this._cubeSize; + + _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size ); + + renderer.setRenderTarget( cubeUVRenderTarget ); + renderer.render( mesh, _flatCamera ); + + } + + _applyPMREM( cubeUVRenderTarget ) { + + const renderer = this._renderer; + const autoClear = renderer.autoClear; + renderer.autoClear = false; + const n = this._lodPlanes.length; + + for ( let i = 1; i < n; i ++ ) { + + const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] ); + + const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ]; + + this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis ); + + } + + renderer.autoClear = autoClear; + + } + + /** + * This is a two-pass Gaussian blur for a cubemap. Normally this is done + * vertically and horizontally, but this breaks down on a cube. Here we apply + * the blur latitudinally (around the poles), and then longitudinally (towards + * the poles) to approximate the orthogonally-separable blur. It is least + * accurate at the poles, but still does a decent job. + * + * @private + * @param {WebGLRenderTarget} cubeUVRenderTarget + * @param {number} lodIn + * @param {number} lodOut + * @param {number} sigma + * @param {Vector3} [poleAxis] + */ + _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) { + + const pingPongRenderTarget = this._pingPongRenderTarget; + + this._halfBlur( + cubeUVRenderTarget, + pingPongRenderTarget, + lodIn, + lodOut, + sigma, + 'latitudinal', + poleAxis ); + + this._halfBlur( + pingPongRenderTarget, + cubeUVRenderTarget, + lodOut, + lodOut, + sigma, + 'longitudinal', + poleAxis ); + + } + + _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) { + + const renderer = this._renderer; + const blurMaterial = this._blurMaterial; + + if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) { + + console.error( + 'blur direction must be either latitudinal or longitudinal!' ); + + } + + // Number of standard deviations at which to cut off the discrete approximation. + const STANDARD_DEVIATIONS = 3; + + const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial ); + const blurUniforms = blurMaterial.uniforms; + + const pixels = this._sizeLods[ lodIn ] - 1; + const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 ); + const sigmaPixels = sigmaRadians / radiansPerPixel; + const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES; + + if ( samples > MAX_SAMPLES ) { + + console.warn( `sigmaRadians, ${ + sigmaRadians}, is too large and will clip, as it requested ${ + samples} samples when the maximum is set to ${MAX_SAMPLES}` ); + + } + + const weights = []; + let sum = 0; + + for ( let i = 0; i < MAX_SAMPLES; ++ i ) { + + const x = i / sigmaPixels; + const weight = Math.exp( - x * x / 2 ); + weights.push( weight ); + + if ( i === 0 ) { + + sum += weight; + + } else if ( i < samples ) { + + sum += 2 * weight; + + } + + } + + for ( let i = 0; i < weights.length; i ++ ) { + + weights[ i ] = weights[ i ] / sum; + + } + + blurUniforms[ 'envMap' ].value = targetIn.texture; + blurUniforms[ 'samples' ].value = samples; + blurUniforms[ 'weights' ].value = weights; + blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal'; + + if ( poleAxis ) { + + blurUniforms[ 'poleAxis' ].value = poleAxis; + + } + + const { _lodMax } = this; + blurUniforms[ 'dTheta' ].value = radiansPerPixel; + blurUniforms[ 'mipInt' ].value = _lodMax - lodIn; + + const outputSize = this._sizeLods[ lodOut ]; + const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 ); + const y = 4 * ( this._cubeSize - outputSize ); + + _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize ); + renderer.setRenderTarget( targetOut ); + renderer.render( blurMesh, _flatCamera ); + + } + +} + + + +function _createPlanes( lodMax ) { + + const lodPlanes = []; + const sizeLods = []; + const sigmas = []; + + let lod = lodMax; + + const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length; + + for ( let i = 0; i < totalLods; i ++ ) { + + const sizeLod = Math.pow( 2, lod ); + sizeLods.push( sizeLod ); + let sigma = 1.0 / sizeLod; + + if ( i > lodMax - LOD_MIN ) { + + sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ]; + + } else if ( i === 0 ) { + + sigma = 0; + + } + + sigmas.push( sigma ); + + const texelSize = 1.0 / ( sizeLod - 2 ); + const min = - texelSize; + const max = 1 + texelSize; + const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ]; + + const cubeFaces = 6; + const vertices = 6; + const positionSize = 3; + const uvSize = 2; + const faceIndexSize = 1; + + const position = new Float32Array( positionSize * vertices * cubeFaces ); + const uv = new Float32Array( uvSize * vertices * cubeFaces ); + const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces ); + + for ( let face = 0; face < cubeFaces; face ++ ) { + + const x = ( face % 3 ) * 2 / 3 - 1; + const y = face > 2 ? 0 : -1; + const coordinates = [ + x, y, 0, + x + 2 / 3, y, 0, + x + 2 / 3, y + 1, 0, + x, y, 0, + x + 2 / 3, y + 1, 0, + x, y + 1, 0 + ]; + position.set( coordinates, positionSize * vertices * face ); + uv.set( uv1, uvSize * vertices * face ); + const fill = [ face, face, face, face, face, face ]; + faceIndex.set( fill, faceIndexSize * vertices * face ); + + } + + const planes = new BufferGeometry(); + planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) ); + planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) ); + planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) ); + lodPlanes.push( planes ); + + if ( lod > LOD_MIN ) { + + lod --; + + } + + } + + return { lodPlanes, sizeLods, sigmas }; + +} + +function _createRenderTarget( width, height, params ) { + + const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params ); + cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping; + cubeUVRenderTarget.texture.name = 'PMREM.cubeUv'; + cubeUVRenderTarget.scissorTest = true; + return cubeUVRenderTarget; + +} + +function _setViewport( target, x, y, width, height ) { + + target.viewport.set( x, y, width, height ); + target.scissor.set( x, y, width, height ); + +} + +function _getBlurShader( lodMax, width, height ) { + + const weights = new Float32Array( MAX_SAMPLES ); + const poleAxis = new Vector3( 0, 1, 0 ); + const shaderMaterial = new ShaderMaterial( { + + name: 'SphericalGaussianBlur', + + defines: { + 'n': MAX_SAMPLES, + 'CUBEUV_TEXEL_WIDTH': 1.0 / width, + 'CUBEUV_TEXEL_HEIGHT': 1.0 / height, + 'CUBEUV_MAX_MIP': `${lodMax}.0`, + }, + + uniforms: { + 'envMap': { value: null }, + 'samples': { value: 1 }, + 'weights': { value: weights }, + 'latitudinal': { value: false }, + 'dTheta': { value: 0 }, + 'mipInt': { value: 0 }, + 'poleAxis': { value: poleAxis } + }, + + vertexShader: _getCommonVertexShader(), + + fragmentShader: /* glsl */` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + uniform int samples; + uniform float weights[ n ]; + uniform bool latitudinal; + uniform float dTheta; + uniform float mipInt; + uniform vec3 poleAxis; + + #define ENVMAP_TYPE_CUBE_UV + #include + + vec3 getSample( float theta, vec3 axis ) { + + float cosTheta = cos( theta ); + // Rodrigues' axis-angle rotation + vec3 sampleDirection = vOutputDirection * cosTheta + + cross( axis, vOutputDirection ) * sin( theta ) + + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); + + return bilinearCubeUV( envMap, sampleDirection, mipInt ); + + } + + void main() { + + vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); + + if ( all( equal( axis, vec3( 0.0 ) ) ) ) { + + axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); + + } + + axis = normalize( axis ); + + gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); + + for ( int i = 1; i < n; i++ ) { + + if ( i >= samples ) { + + break; + + } + + float theta = dTheta * float( i ); + gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); + gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); + + } + + } + `, + + blending: NoBlending, + depthTest: false, + depthWrite: false + + } ); + + return shaderMaterial; + +} + +function _getEquirectMaterial() { + + return new ShaderMaterial( { + + name: 'EquirectangularToCubeUV', + + uniforms: { + 'envMap': { value: null } + }, + + vertexShader: _getCommonVertexShader(), + + fragmentShader: /* glsl */` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + + #include + + void main() { + + vec3 outputDirection = normalize( vOutputDirection ); + vec2 uv = equirectUv( outputDirection ); + + gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); + + } + `, + + blending: NoBlending, + depthTest: false, + depthWrite: false + + } ); + +} + +function _getCubemapMaterial() { + + return new ShaderMaterial( { + + name: 'CubemapToCubeUV', + + uniforms: { + 'envMap': { value: null }, + 'flipEnvMap': { value: -1 } + }, + + vertexShader: _getCommonVertexShader(), + + fragmentShader: /* glsl */` + + precision mediump float; + precision mediump int; + + uniform float flipEnvMap; + + varying vec3 vOutputDirection; + + uniform samplerCube envMap; + + void main() { + + gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); + + } + `, + + blending: NoBlending, + depthTest: false, + depthWrite: false + + } ); + +} + +function _getCommonVertexShader() { + + return /* glsl */` + + precision mediump float; + precision mediump int; + + attribute float faceIndex; + + varying vec3 vOutputDirection; + + // RH coordinate system; PMREM face-indexing convention + vec3 getDirection( vec2 uv, float face ) { + + uv = 2.0 * uv - 1.0; + + vec3 direction = vec3( uv, 1.0 ); + + if ( face == 0.0 ) { + + direction = direction.zyx; // ( 1, v, u ) pos x + + } else if ( face == 1.0 ) { + + direction = direction.xzy; + direction.xz *= -1.0; // ( -u, 1, -v ) pos y + + } else if ( face == 2.0 ) { + + direction.x *= -1.0; // ( -u, v, 1 ) pos z + + } else if ( face == 3.0 ) { + + direction = direction.zyx; + direction.xz *= -1.0; // ( -1, v, -u ) neg x + + } else if ( face == 4.0 ) { + + direction = direction.xzy; + direction.xy *= -1.0; // ( -u, -1, v ) neg y + + } else if ( face == 5.0 ) { + + direction.z *= -1.0; // ( u, v, -1 ) neg z + + } + + return direction; + + } + + void main() { + + vOutputDirection = getDirection( uv, faceIndex ); + gl_Position = vec4( position, 1.0 ); + + } + `; + +} + +function WebGLCubeUVMaps( renderer ) { + + let cubeUVmaps = new WeakMap(); + + let pmremGenerator = null; + + function get( texture ) { + + if ( texture && texture.isTexture ) { + + const mapping = texture.mapping; + + const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ); + const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping ); + + // equirect/cube map to cubeUV conversion + + if ( isEquirectMap || isCubeMap ) { + + let renderTarget = cubeUVmaps.get( texture ); + + const currentPMREMVersion = renderTarget !== undefined ? renderTarget.texture.pmremVersion : 0; + + if ( texture.isRenderTargetTexture && texture.pmremVersion !== currentPMREMVersion ) { + + if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer ); + + renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget ); + renderTarget.texture.pmremVersion = texture.pmremVersion; + + cubeUVmaps.set( texture, renderTarget ); + + return renderTarget.texture; + + } else { + + if ( renderTarget !== undefined ) { + + return renderTarget.texture; + + } else { + + const image = texture.image; + + if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) { + + if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer ); + + renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture ); + renderTarget.texture.pmremVersion = texture.pmremVersion; + + cubeUVmaps.set( texture, renderTarget ); + + texture.addEventListener( 'dispose', onTextureDispose ); + + return renderTarget.texture; + + } else { + + // image not yet ready. try the conversion next frame + + return null; + + } + + } + + } + + } + + } + + return texture; + + } + + function isCubeTextureComplete( image ) { + + let count = 0; + const length = 6; + + for ( let i = 0; i < length; i ++ ) { + + if ( image[ i ] !== undefined ) count ++; + + } + + return count === length; + + + } + + function onTextureDispose( event ) { + + const texture = event.target; + + texture.removeEventListener( 'dispose', onTextureDispose ); + + const cubemapUV = cubeUVmaps.get( texture ); + + if ( cubemapUV !== undefined ) { + + cubeUVmaps.delete( texture ); + cubemapUV.dispose(); + + } + + } + + function dispose() { + + cubeUVmaps = new WeakMap(); + + if ( pmremGenerator !== null ) { + + pmremGenerator.dispose(); + pmremGenerator = null; + + } + + } + + return { + get: get, + dispose: dispose + }; + +} + +function WebGLExtensions( gl ) { + + const extensions = {}; + + function getExtension( name ) { + + if ( extensions[ name ] !== undefined ) { + + return extensions[ name ]; + + } + + let extension; + + switch ( name ) { + + case 'WEBGL_depth_texture': + extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' ); + break; + + case 'EXT_texture_filter_anisotropic': + extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' ); + break; + + case 'WEBGL_compressed_texture_s3tc': + extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' ); + break; + + case 'WEBGL_compressed_texture_pvrtc': + extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' ); + break; + + default: + extension = gl.getExtension( name ); + + } + + extensions[ name ] = extension; + + return extension; + + } + + return { + + has: function ( name ) { + + return getExtension( name ) !== null; + + }, + + init: function () { + + getExtension( 'EXT_color_buffer_float' ); + getExtension( 'WEBGL_clip_cull_distance' ); + getExtension( 'OES_texture_float_linear' ); + getExtension( 'EXT_color_buffer_half_float' ); + getExtension( 'WEBGL_multisampled_render_to_texture' ); + getExtension( 'WEBGL_render_shared_exponent' ); + + }, + + get: function ( name ) { + + const extension = getExtension( name ); + + if ( extension === null ) { + + warnOnce( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' ); + + } + + return extension; + + } + + }; + +} + +function WebGLGeometries( gl, attributes, info, bindingStates ) { + + const geometries = {}; + const wireframeAttributes = new WeakMap(); + + function onGeometryDispose( event ) { + + const geometry = event.target; + + if ( geometry.index !== null ) { + + attributes.remove( geometry.index ); + + } + + for ( const name in geometry.attributes ) { + + attributes.remove( geometry.attributes[ name ] ); + + } + + geometry.removeEventListener( 'dispose', onGeometryDispose ); + + delete geometries[ geometry.id ]; + + const attribute = wireframeAttributes.get( geometry ); + + if ( attribute ) { + + attributes.remove( attribute ); + wireframeAttributes.delete( geometry ); + + } + + bindingStates.releaseStatesOfGeometry( geometry ); + + if ( geometry.isInstancedBufferGeometry === true ) { + + delete geometry._maxInstanceCount; + + } + + // + + info.memory.geometries --; + + } + + function get( object, geometry ) { + + if ( geometries[ geometry.id ] === true ) return geometry; + + geometry.addEventListener( 'dispose', onGeometryDispose ); + + geometries[ geometry.id ] = true; + + info.memory.geometries ++; + + return geometry; + + } + + function update( geometry ) { + + const geometryAttributes = geometry.attributes; + + // Updating index buffer in VAO now. See WebGLBindingStates. + + for ( const name in geometryAttributes ) { + + attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER ); + + } + + } + + function updateWireframeAttribute( geometry ) { + + const indices = []; + + const geometryIndex = geometry.index; + const geometryPosition = geometry.attributes.position; + let version = 0; + + if ( geometryIndex !== null ) { + + const array = geometryIndex.array; + version = geometryIndex.version; + + for ( let i = 0, l = array.length; i < l; i += 3 ) { + + const a = array[ i + 0 ]; + const b = array[ i + 1 ]; + const c = array[ i + 2 ]; + + indices.push( a, b, b, c, c, a ); + + } + + } else if ( geometryPosition !== undefined ) { + + const array = geometryPosition.array; + version = geometryPosition.version; + + for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) { + + const a = i + 0; + const b = i + 1; + const c = i + 2; + + indices.push( a, b, b, c, c, a ); + + } + + } else { + + return; + + } + + const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 ); + attribute.version = version; + + // Updating index buffer in VAO now. See WebGLBindingStates + + // + + const previousAttribute = wireframeAttributes.get( geometry ); + + if ( previousAttribute ) attributes.remove( previousAttribute ); + + // + + wireframeAttributes.set( geometry, attribute ); + + } + + function getWireframeAttribute( geometry ) { + + const currentAttribute = wireframeAttributes.get( geometry ); + + if ( currentAttribute ) { + + const geometryIndex = geometry.index; + + if ( geometryIndex !== null ) { + + // if the attribute is obsolete, create a new one + + if ( currentAttribute.version < geometryIndex.version ) { + + updateWireframeAttribute( geometry ); + + } + + } + + } else { + + updateWireframeAttribute( geometry ); + + } + + return wireframeAttributes.get( geometry ); + + } + + return { + + get: get, + update: update, + + getWireframeAttribute: getWireframeAttribute + + }; + +} + +function WebGLIndexedBufferRenderer( gl, extensions, info ) { + + let mode; + + function setMode( value ) { + + mode = value; + + } + + let type, bytesPerElement; + + function setIndex( value ) { + + type = value.type; + bytesPerElement = value.bytesPerElement; + + } + + function render( start, count ) { + + gl.drawElements( mode, count, type, start * bytesPerElement ); + + info.update( count, mode, 1 ); + + } + + function renderInstances( start, count, primcount ) { + + if ( primcount === 0 ) return; + + gl.drawElementsInstanced( mode, count, type, start * bytesPerElement, primcount ); + + info.update( count, mode, primcount ); + + } + + function renderMultiDraw( starts, counts, drawCount ) { + + if ( drawCount === 0 ) return; + + const extension = extensions.get( 'WEBGL_multi_draw' ); + extension.multiDrawElementsWEBGL( mode, counts, 0, type, starts, 0, drawCount ); + + let elementCount = 0; + for ( let i = 0; i < drawCount; i ++ ) { + + elementCount += counts[ i ]; + + } + + info.update( elementCount, mode, 1 ); + + + } + + function renderMultiDrawInstances( starts, counts, drawCount, primcount ) { + + if ( drawCount === 0 ) return; + + const extension = extensions.get( 'WEBGL_multi_draw' ); + + if ( extension === null ) { + + for ( let i = 0; i < starts.length; i ++ ) { + + renderInstances( starts[ i ] / bytesPerElement, counts[ i ], primcount[ i ] ); + + } + + } else { + + extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, type, starts, 0, primcount, 0, drawCount ); + + let elementCount = 0; + for ( let i = 0; i < drawCount; i ++ ) { + + elementCount += counts[ i ] * primcount[ i ]; + + } + + info.update( elementCount, mode, 1 ); + + } + + } + + // + + this.setMode = setMode; + this.setIndex = setIndex; + this.render = render; + this.renderInstances = renderInstances; + this.renderMultiDraw = renderMultiDraw; + this.renderMultiDrawInstances = renderMultiDrawInstances; + +} + +function WebGLInfo( gl ) { + + const memory = { + geometries: 0, + textures: 0 + }; + + const render = { + frame: 0, + calls: 0, + triangles: 0, + points: 0, + lines: 0 + }; + + function update( count, mode, instanceCount ) { + + render.calls ++; + + switch ( mode ) { + + case gl.TRIANGLES: + render.triangles += instanceCount * ( count / 3 ); + break; + + case gl.LINES: + render.lines += instanceCount * ( count / 2 ); + break; + + case gl.LINE_STRIP: + render.lines += instanceCount * ( count - 1 ); + break; + + case gl.LINE_LOOP: + render.lines += instanceCount * count; + break; + + case gl.POINTS: + render.points += instanceCount * count; + break; + + default: + console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode ); + break; + + } + + } + + function reset() { + + render.calls = 0; + render.triangles = 0; + render.points = 0; + render.lines = 0; + + } + + return { + memory: memory, + render: render, + programs: null, + autoReset: true, + reset: reset, + update: update + }; + +} + +function WebGLMorphtargets( gl, capabilities, textures ) { + + const morphTextures = new WeakMap(); + const morph = new Vector4(); + + function update( object, geometry, program ) { + + const objectInfluences = object.morphTargetInfluences; + + // the following encodes morph targets into an array of data textures. Each layer represents a single morph target. + + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0; + + let entry = morphTextures.get( geometry ); + + if ( entry === undefined || entry.count !== morphTargetsCount ) { + + if ( entry !== undefined ) entry.texture.dispose(); + + const hasMorphPosition = geometry.morphAttributes.position !== undefined; + const hasMorphNormals = geometry.morphAttributes.normal !== undefined; + const hasMorphColors = geometry.morphAttributes.color !== undefined; + + const morphTargets = geometry.morphAttributes.position || []; + const morphNormals = geometry.morphAttributes.normal || []; + const morphColors = geometry.morphAttributes.color || []; + + let vertexDataCount = 0; + + if ( hasMorphPosition === true ) vertexDataCount = 1; + if ( hasMorphNormals === true ) vertexDataCount = 2; + if ( hasMorphColors === true ) vertexDataCount = 3; + + let width = geometry.attributes.position.count * vertexDataCount; + let height = 1; + + if ( width > capabilities.maxTextureSize ) { + + height = Math.ceil( width / capabilities.maxTextureSize ); + width = capabilities.maxTextureSize; + + } + + const buffer = new Float32Array( width * height * 4 * morphTargetsCount ); + + const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount ); + texture.type = FloatType; + texture.needsUpdate = true; + + // fill buffer + + const vertexDataStride = vertexDataCount * 4; + + for ( let i = 0; i < morphTargetsCount; i ++ ) { + + const morphTarget = morphTargets[ i ]; + const morphNormal = morphNormals[ i ]; + const morphColor = morphColors[ i ]; + + const offset = width * height * 4 * i; + + for ( let j = 0; j < morphTarget.count; j ++ ) { + + const stride = j * vertexDataStride; + + if ( hasMorphPosition === true ) { + + morph.fromBufferAttribute( morphTarget, j ); + + buffer[ offset + stride + 0 ] = morph.x; + buffer[ offset + stride + 1 ] = morph.y; + buffer[ offset + stride + 2 ] = morph.z; + buffer[ offset + stride + 3 ] = 0; + + } + + if ( hasMorphNormals === true ) { + + morph.fromBufferAttribute( morphNormal, j ); + + buffer[ offset + stride + 4 ] = morph.x; + buffer[ offset + stride + 5 ] = morph.y; + buffer[ offset + stride + 6 ] = morph.z; + buffer[ offset + stride + 7 ] = 0; + + } + + if ( hasMorphColors === true ) { + + morph.fromBufferAttribute( morphColor, j ); + + buffer[ offset + stride + 8 ] = morph.x; + buffer[ offset + stride + 9 ] = morph.y; + buffer[ offset + stride + 10 ] = morph.z; + buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1; + + } + + } + + } + + entry = { + count: morphTargetsCount, + texture: texture, + size: new Vector2( width, height ) + }; + + morphTextures.set( geometry, entry ); + + function disposeTexture() { + + texture.dispose(); + + morphTextures.delete( geometry ); + + geometry.removeEventListener( 'dispose', disposeTexture ); + + } + + geometry.addEventListener( 'dispose', disposeTexture ); + + } + + // + if ( object.isInstancedMesh === true && object.morphTexture !== null ) { + + program.getUniforms().setValue( gl, 'morphTexture', object.morphTexture, textures ); + + } else { + + let morphInfluencesSum = 0; + + for ( let i = 0; i < objectInfluences.length; i ++ ) { + + morphInfluencesSum += objectInfluences[ i ]; + + } + + const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; + + + program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence ); + program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences ); + + } + + program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures ); + program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size ); + + } + + return { + + update: update + + }; + +} + +function WebGLObjects( gl, geometries, attributes, info ) { + + let updateMap = new WeakMap(); + + function update( object ) { + + const frame = info.render.frame; + + const geometry = object.geometry; + const buffergeometry = geometries.get( object, geometry ); + + // Update once per frame + + if ( updateMap.get( buffergeometry ) !== frame ) { + + geometries.update( buffergeometry ); + + updateMap.set( buffergeometry, frame ); + + } + + if ( object.isInstancedMesh ) { + + if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) { + + object.addEventListener( 'dispose', onInstancedMeshDispose ); + + } + + if ( updateMap.get( object ) !== frame ) { + + attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER ); + + if ( object.instanceColor !== null ) { + + attributes.update( object.instanceColor, gl.ARRAY_BUFFER ); + + } + + updateMap.set( object, frame ); + + } + + } + + if ( object.isSkinnedMesh ) { + + const skeleton = object.skeleton; + + if ( updateMap.get( skeleton ) !== frame ) { + + skeleton.update(); + + updateMap.set( skeleton, frame ); + + } + + } + + return buffergeometry; + + } + + function dispose() { + + updateMap = new WeakMap(); + + } + + function onInstancedMeshDispose( event ) { + + const instancedMesh = event.target; + + instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose ); + + attributes.remove( instancedMesh.instanceMatrix ); + + if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor ); + + } + + return { + + update: update, + dispose: dispose + + }; + +} + +/** + * Uniforms of a program. + * Those form a tree structure with a special top-level container for the root, + * which you get by calling 'new WebGLUniforms( gl, program )'. + * + * + * Properties of inner nodes including the top-level container: + * + * .seq - array of nested uniforms + * .map - nested uniforms by name + * + * + * Methods of all nodes except the top-level container: + * + * .setValue( gl, value, [textures] ) + * + * uploads a uniform value(s) + * the 'textures' parameter is needed for sampler uniforms + * + * + * Static methods of the top-level container (textures factorizations): + * + * .upload( gl, seq, values, textures ) + * + * sets uniforms in 'seq' to 'values[id].value' + * + * .seqWithValue( seq, values ) : filteredSeq + * + * filters 'seq' entries with corresponding entry in values + * + * + * Methods of the top-level container (textures factorizations): + * + * .setValue( gl, name, value, textures ) + * + * sets uniform with name 'name' to 'value' + * + * .setOptional( gl, obj, prop ) + * + * like .set for an optional property of the object + * + */ + + +const emptyTexture = /*@__PURE__*/ new Texture(); + +const emptyShadowTexture = /*@__PURE__*/ new DepthTexture( 1, 1 ); + +const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture(); +const empty3dTexture = /*@__PURE__*/ new Data3DTexture(); +const emptyCubeTexture = /*@__PURE__*/ new CubeTexture(); + +// --- Utilities --- + +// Array Caches (provide typed arrays for temporary by size) + +const arrayCacheF32 = []; +const arrayCacheI32 = []; + +// Float32Array caches used for uploading Matrix uniforms + +const mat4array = new Float32Array( 16 ); +const mat3array = new Float32Array( 9 ); +const mat2array = new Float32Array( 4 ); + +// Flattening for arrays of vectors and matrices + +function flatten( array, nBlocks, blockSize ) { + + const firstElem = array[ 0 ]; + + if ( firstElem <= 0 || firstElem > 0 ) return array; + // unoptimized: ! isNaN( firstElem ) + // see http://jacksondunstan.com/articles/983 + + const n = nBlocks * blockSize; + let r = arrayCacheF32[ n ]; + + if ( r === undefined ) { + + r = new Float32Array( n ); + arrayCacheF32[ n ] = r; + + } + + if ( nBlocks !== 0 ) { + + firstElem.toArray( r, 0 ); + + for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) { + + offset += blockSize; + array[ i ].toArray( r, offset ); + + } + + } + + return r; + +} + +function arraysEqual( a, b ) { + + if ( a.length !== b.length ) return false; + + for ( let i = 0, l = a.length; i < l; i ++ ) { + + if ( a[ i ] !== b[ i ] ) return false; + + } + + return true; + +} + +function copyArray( a, b ) { + + for ( let i = 0, l = b.length; i < l; i ++ ) { + + a[ i ] = b[ i ]; + + } + +} + +// Texture unit allocation + +function allocTexUnits( textures, n ) { + + let r = arrayCacheI32[ n ]; + + if ( r === undefined ) { + + r = new Int32Array( n ); + arrayCacheI32[ n ] = r; + + } + + for ( let i = 0; i !== n; ++ i ) { + + r[ i ] = textures.allocateTextureUnit(); + + } + + return r; + +} + +// --- Setters --- + +// Note: Defining these methods externally, because they come in a bunch +// and this way their names minify. + +// Single scalar + +function setValueV1f( gl, v ) { + + const cache = this.cache; + + if ( cache[ 0 ] === v ) return; + + gl.uniform1f( this.addr, v ); + + cache[ 0 ] = v; + +} + +// Single float vector (from flat array or THREE.VectorN) + +function setValueV2f( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) { + + gl.uniform2f( this.addr, v.x, v.y ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform2fv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +function setValueV3f( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) { + + gl.uniform3f( this.addr, v.x, v.y, v.z ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; + + } + + } else if ( v.r !== undefined ) { + + if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) { + + gl.uniform3f( this.addr, v.r, v.g, v.b ); + + cache[ 0 ] = v.r; + cache[ 1 ] = v.g; + cache[ 2 ] = v.b; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform3fv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +function setValueV4f( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) { + + gl.uniform4f( this.addr, v.x, v.y, v.z, v.w ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; + cache[ 3 ] = v.w; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform4fv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +// Single matrix (from flat array or THREE.MatrixN) + +function setValueM2( gl, v ) { + + const cache = this.cache; + const elements = v.elements; + + if ( elements === undefined ) { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniformMatrix2fv( this.addr, false, v ); + + copyArray( cache, v ); + + } else { + + if ( arraysEqual( cache, elements ) ) return; + + mat2array.set( elements ); + + gl.uniformMatrix2fv( this.addr, false, mat2array ); + + copyArray( cache, elements ); + + } + +} + +function setValueM3( gl, v ) { + + const cache = this.cache; + const elements = v.elements; + + if ( elements === undefined ) { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniformMatrix3fv( this.addr, false, v ); + + copyArray( cache, v ); + + } else { + + if ( arraysEqual( cache, elements ) ) return; + + mat3array.set( elements ); + + gl.uniformMatrix3fv( this.addr, false, mat3array ); + + copyArray( cache, elements ); + + } + +} + +function setValueM4( gl, v ) { + + const cache = this.cache; + const elements = v.elements; + + if ( elements === undefined ) { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniformMatrix4fv( this.addr, false, v ); + + copyArray( cache, v ); + + } else { + + if ( arraysEqual( cache, elements ) ) return; + + mat4array.set( elements ); + + gl.uniformMatrix4fv( this.addr, false, mat4array ); + + copyArray( cache, elements ); + + } + +} + +// Single integer / boolean + +function setValueV1i( gl, v ) { + + const cache = this.cache; + + if ( cache[ 0 ] === v ) return; + + gl.uniform1i( this.addr, v ); + + cache[ 0 ] = v; + +} + +// Single integer / boolean vector (from flat array or THREE.VectorN) + +function setValueV2i( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) { + + gl.uniform2i( this.addr, v.x, v.y ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform2iv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +function setValueV3i( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) { + + gl.uniform3i( this.addr, v.x, v.y, v.z ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform3iv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +function setValueV4i( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) { + + gl.uniform4i( this.addr, v.x, v.y, v.z, v.w ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; + cache[ 3 ] = v.w; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform4iv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +// Single unsigned integer + +function setValueV1ui( gl, v ) { + + const cache = this.cache; + + if ( cache[ 0 ] === v ) return; + + gl.uniform1ui( this.addr, v ); + + cache[ 0 ] = v; + +} + +// Single unsigned integer vector (from flat array or THREE.VectorN) + +function setValueV2ui( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) { + + gl.uniform2ui( this.addr, v.x, v.y ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform2uiv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +function setValueV3ui( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) { + + gl.uniform3ui( this.addr, v.x, v.y, v.z ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform3uiv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + +function setValueV4ui( gl, v ) { + + const cache = this.cache; + + if ( v.x !== undefined ) { + + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) { + + gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w ); + + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; + cache[ 3 ] = v.w; + + } + + } else { + + if ( arraysEqual( cache, v ) ) return; + + gl.uniform4uiv( this.addr, v ); + + copyArray( cache, v ); + + } + +} + + +// Single texture (2D / Cube) + +function setValueT1( gl, v, textures ) { + + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + + if ( cache[ 0 ] !== unit ) { + + gl.uniform1i( this.addr, unit ); + cache[ 0 ] = unit; + + } + + let emptyTexture2D; + + if ( this.type === gl.SAMPLER_2D_SHADOW ) { + + emptyShadowTexture.compareFunction = LessEqualCompare; // #28670 + emptyTexture2D = emptyShadowTexture; + + } else { + + emptyTexture2D = emptyTexture; + + } + + textures.setTexture2D( v || emptyTexture2D, unit ); + +} + +function setValueT3D1( gl, v, textures ) { + + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + + if ( cache[ 0 ] !== unit ) { + + gl.uniform1i( this.addr, unit ); + cache[ 0 ] = unit; + + } + + textures.setTexture3D( v || empty3dTexture, unit ); + +} + +function setValueT6( gl, v, textures ) { + + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + + if ( cache[ 0 ] !== unit ) { + + gl.uniform1i( this.addr, unit ); + cache[ 0 ] = unit; + + } + + textures.setTextureCube( v || emptyCubeTexture, unit ); + +} + +function setValueT2DArray1( gl, v, textures ) { + + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + + if ( cache[ 0 ] !== unit ) { + + gl.uniform1i( this.addr, unit ); + cache[ 0 ] = unit; + + } + + textures.setTexture2DArray( v || emptyArrayTexture, unit ); + +} + +// Helper to pick the right setter for the singular case + +function getSingularSetter( type ) { + + switch ( type ) { + + case 0x1406: return setValueV1f; // FLOAT + case 0x8b50: return setValueV2f; // _VEC2 + case 0x8b51: return setValueV3f; // _VEC3 + case 0x8b52: return setValueV4f; // _VEC4 + + case 0x8b5a: return setValueM2; // _MAT2 + case 0x8b5b: return setValueM3; // _MAT3 + case 0x8b5c: return setValueM4; // _MAT4 + + case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL + case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2 + case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3 + case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4 + + case 0x1405: return setValueV1ui; // UINT + case 0x8dc6: return setValueV2ui; // _VEC2 + case 0x8dc7: return setValueV3ui; // _VEC3 + case 0x8dc8: return setValueV4ui; // _VEC4 + + case 0x8b5e: // SAMPLER_2D + case 0x8d66: // SAMPLER_EXTERNAL_OES + case 0x8dca: // INT_SAMPLER_2D + case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D + case 0x8b62: // SAMPLER_2D_SHADOW + return setValueT1; + + case 0x8b5f: // SAMPLER_3D + case 0x8dcb: // INT_SAMPLER_3D + case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D + return setValueT3D1; + + case 0x8b60: // SAMPLER_CUBE + case 0x8dcc: // INT_SAMPLER_CUBE + case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE + case 0x8dc5: // SAMPLER_CUBE_SHADOW + return setValueT6; + + case 0x8dc1: // SAMPLER_2D_ARRAY + case 0x8dcf: // INT_SAMPLER_2D_ARRAY + case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY + case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW + return setValueT2DArray1; + + } + +} + + +// Array of scalars + +function setValueV1fArray( gl, v ) { + + gl.uniform1fv( this.addr, v ); + +} + +// Array of vectors (from flat array or array of THREE.VectorN) + +function setValueV2fArray( gl, v ) { + + const data = flatten( v, this.size, 2 ); + + gl.uniform2fv( this.addr, data ); + +} + +function setValueV3fArray( gl, v ) { + + const data = flatten( v, this.size, 3 ); + + gl.uniform3fv( this.addr, data ); + +} + +function setValueV4fArray( gl, v ) { + + const data = flatten( v, this.size, 4 ); + + gl.uniform4fv( this.addr, data ); + +} + +// Array of matrices (from flat array or array of THREE.MatrixN) + +function setValueM2Array( gl, v ) { + + const data = flatten( v, this.size, 4 ); + + gl.uniformMatrix2fv( this.addr, false, data ); + +} + +function setValueM3Array( gl, v ) { + + const data = flatten( v, this.size, 9 ); + + gl.uniformMatrix3fv( this.addr, false, data ); + +} + +function setValueM4Array( gl, v ) { + + const data = flatten( v, this.size, 16 ); + + gl.uniformMatrix4fv( this.addr, false, data ); + +} + +// Array of integer / boolean + +function setValueV1iArray( gl, v ) { + + gl.uniform1iv( this.addr, v ); + +} + +// Array of integer / boolean vectors (from flat array) + +function setValueV2iArray( gl, v ) { + + gl.uniform2iv( this.addr, v ); + +} + +function setValueV3iArray( gl, v ) { + + gl.uniform3iv( this.addr, v ); + +} + +function setValueV4iArray( gl, v ) { + + gl.uniform4iv( this.addr, v ); + +} + +// Array of unsigned integer + +function setValueV1uiArray( gl, v ) { + + gl.uniform1uiv( this.addr, v ); + +} + +// Array of unsigned integer vectors (from flat array) + +function setValueV2uiArray( gl, v ) { + + gl.uniform2uiv( this.addr, v ); + +} + +function setValueV3uiArray( gl, v ) { + + gl.uniform3uiv( this.addr, v ); + +} + +function setValueV4uiArray( gl, v ) { + + gl.uniform4uiv( this.addr, v ); + +} + + +// Array of textures (2D / 3D / Cube / 2DArray) + +function setValueT1Array( gl, v, textures ) { + + const cache = this.cache; + + const n = v.length; + + const units = allocTexUnits( textures, n ); + + if ( ! arraysEqual( cache, units ) ) { + + gl.uniform1iv( this.addr, units ); + + copyArray( cache, units ); + + } + + for ( let i = 0; i !== n; ++ i ) { + + textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] ); + + } + +} + +function setValueT3DArray( gl, v, textures ) { + + const cache = this.cache; + + const n = v.length; + + const units = allocTexUnits( textures, n ); + + if ( ! arraysEqual( cache, units ) ) { + + gl.uniform1iv( this.addr, units ); + + copyArray( cache, units ); + + } + + for ( let i = 0; i !== n; ++ i ) { + + textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] ); + + } + +} + +function setValueT6Array( gl, v, textures ) { + + const cache = this.cache; + + const n = v.length; + + const units = allocTexUnits( textures, n ); + + if ( ! arraysEqual( cache, units ) ) { + + gl.uniform1iv( this.addr, units ); + + copyArray( cache, units ); + + } + + for ( let i = 0; i !== n; ++ i ) { + + textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] ); + + } + +} + +function setValueT2DArrayArray( gl, v, textures ) { + + const cache = this.cache; + + const n = v.length; + + const units = allocTexUnits( textures, n ); + + if ( ! arraysEqual( cache, units ) ) { + + gl.uniform1iv( this.addr, units ); + + copyArray( cache, units ); + + } + + for ( let i = 0; i !== n; ++ i ) { + + textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] ); + + } + +} + + +// Helper to pick the right setter for a pure (bottom-level) array + +function getPureArraySetter( type ) { + + switch ( type ) { + + case 0x1406: return setValueV1fArray; // FLOAT + case 0x8b50: return setValueV2fArray; // _VEC2 + case 0x8b51: return setValueV3fArray; // _VEC3 + case 0x8b52: return setValueV4fArray; // _VEC4 + + case 0x8b5a: return setValueM2Array; // _MAT2 + case 0x8b5b: return setValueM3Array; // _MAT3 + case 0x8b5c: return setValueM4Array; // _MAT4 + + case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL + case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2 + case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3 + case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4 + + case 0x1405: return setValueV1uiArray; // UINT + case 0x8dc6: return setValueV2uiArray; // _VEC2 + case 0x8dc7: return setValueV3uiArray; // _VEC3 + case 0x8dc8: return setValueV4uiArray; // _VEC4 + + case 0x8b5e: // SAMPLER_2D + case 0x8d66: // SAMPLER_EXTERNAL_OES + case 0x8dca: // INT_SAMPLER_2D + case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D + case 0x8b62: // SAMPLER_2D_SHADOW + return setValueT1Array; + + case 0x8b5f: // SAMPLER_3D + case 0x8dcb: // INT_SAMPLER_3D + case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D + return setValueT3DArray; + + case 0x8b60: // SAMPLER_CUBE + case 0x8dcc: // INT_SAMPLER_CUBE + case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE + case 0x8dc5: // SAMPLER_CUBE_SHADOW + return setValueT6Array; + + case 0x8dc1: // SAMPLER_2D_ARRAY + case 0x8dcf: // INT_SAMPLER_2D_ARRAY + case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY + case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW + return setValueT2DArrayArray; + + } + +} + +// --- Uniform Classes --- + +class SingleUniform { + + constructor( id, activeInfo, addr ) { + + this.id = id; + this.addr = addr; + this.cache = []; + this.type = activeInfo.type; + this.setValue = getSingularSetter( activeInfo.type ); + + // this.path = activeInfo.name; // DEBUG + + } + +} + +class PureArrayUniform { + + constructor( id, activeInfo, addr ) { + + this.id = id; + this.addr = addr; + this.cache = []; + this.type = activeInfo.type; + this.size = activeInfo.size; + this.setValue = getPureArraySetter( activeInfo.type ); + + // this.path = activeInfo.name; // DEBUG + + } + +} + +class StructuredUniform { + + constructor( id ) { + + this.id = id; + + this.seq = []; + this.map = {}; + + } + + setValue( gl, value, textures ) { + + const seq = this.seq; + + for ( let i = 0, n = seq.length; i !== n; ++ i ) { + + const u = seq[ i ]; + u.setValue( gl, value[ u.id ], textures ); + + } + + } + +} + +// --- Top-level --- + +// Parser - builds up the property tree from the path strings + +const RePathPart = /(\w+)(\])?(\[|\.)?/g; + +// extracts +// - the identifier (member name or array index) +// - followed by an optional right bracket (found when array index) +// - followed by an optional left bracket or dot (type of subscript) +// +// Note: These portions can be read in a non-overlapping fashion and +// allow straightforward parsing of the hierarchy that WebGL encodes +// in the uniform names. + +function addUniform( container, uniformObject ) { + + container.seq.push( uniformObject ); + container.map[ uniformObject.id ] = uniformObject; + +} + +function parseUniform( activeInfo, addr, container ) { + + const path = activeInfo.name, + pathLength = path.length; + + // reset RegExp object, because of the early exit of a previous run + RePathPart.lastIndex = 0; + + while ( true ) { + + const match = RePathPart.exec( path ), + matchEnd = RePathPart.lastIndex; + + let id = match[ 1 ]; + const idIsIndex = match[ 2 ] === ']', + subscript = match[ 3 ]; + + if ( idIsIndex ) id = id | 0; // convert to integer + + if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) { + + // bare name or "pure" bottom-level array "[0]" suffix + + addUniform( container, subscript === undefined ? + new SingleUniform( id, activeInfo, addr ) : + new PureArrayUniform( id, activeInfo, addr ) ); + + break; + + } else { + + // step into inner node / create it in case it doesn't exist + + const map = container.map; + let next = map[ id ]; + + if ( next === undefined ) { + + next = new StructuredUniform( id ); + addUniform( container, next ); + + } + + container = next; + + } + + } + +} + +// Root Container + +class WebGLUniforms { + + constructor( gl, program ) { + + this.seq = []; + this.map = {}; + + const n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS ); + + for ( let i = 0; i < n; ++ i ) { + + const info = gl.getActiveUniform( program, i ), + addr = gl.getUniformLocation( program, info.name ); + + parseUniform( info, addr, this ); + + } + + } + + setValue( gl, name, value, textures ) { + + const u = this.map[ name ]; + + if ( u !== undefined ) u.setValue( gl, value, textures ); + + } + + setOptional( gl, object, name ) { + + const v = object[ name ]; + + if ( v !== undefined ) this.setValue( gl, name, v ); + + } + + static upload( gl, seq, values, textures ) { + + for ( let i = 0, n = seq.length; i !== n; ++ i ) { + + const u = seq[ i ], + v = values[ u.id ]; + + if ( v.needsUpdate !== false ) { + + // note: always updating when .needsUpdate is undefined + u.setValue( gl, v.value, textures ); + + } + + } + + } + + static seqWithValue( seq, values ) { + + const r = []; + + for ( let i = 0, n = seq.length; i !== n; ++ i ) { + + const u = seq[ i ]; + if ( u.id in values ) r.push( u ); + + } + + return r; + + } + +} + +function WebGLShader( gl, type, string ) { + + const shader = gl.createShader( type ); + + gl.shaderSource( shader, string ); + gl.compileShader( shader ); + + return shader; + +} + +// From https://www.khronos.org/registry/webgl/extensions/KHR_parallel_shader_compile/ +const COMPLETION_STATUS_KHR = 0x91B1; + +let programIdCount = 0; + +function handleSource( string, errorLine ) { + + const lines = string.split( '\n' ); + const lines2 = []; + + const from = Math.max( errorLine - 6, 0 ); + const to = Math.min( errorLine + 6, lines.length ); + + for ( let i = from; i < to; i ++ ) { + + const line = i + 1; + lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` ); + + } + + return lines2.join( '\n' ); + +} + +const _m0 = /*@__PURE__*/ new Matrix3(); + +function getEncodingComponents( colorSpace ) { + + ColorManagement._getMatrix( _m0, ColorManagement.workingColorSpace, colorSpace ); + + const encodingMatrix = `mat3( ${ _m0.elements.map( ( v ) => v.toFixed( 4 ) ) } )`; + + switch ( ColorManagement.getTransfer( colorSpace ) ) { + + case LinearTransfer: + return [ encodingMatrix, 'LinearTransferOETF' ]; + + case SRGBTransfer: + return [ encodingMatrix, 'sRGBTransferOETF' ]; + + default: + console.warn( 'THREE.WebGLProgram: Unsupported color space: ', colorSpace ); + return [ encodingMatrix, 'LinearTransferOETF' ]; + + } + +} + +function getShaderErrors( gl, shader, type ) { + + const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS ); + const errors = gl.getShaderInfoLog( shader ).trim(); + + if ( status && errors === '' ) return ''; + + const errorMatches = /ERROR: 0:(\d+)/.exec( errors ); + if ( errorMatches ) { + + // --enable-privileged-webgl-extension + // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) ); + + const errorLine = parseInt( errorMatches[ 1 ] ); + return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine ); + + } else { + + return errors; + + } + +} + +function getTexelEncodingFunction( functionName, colorSpace ) { + + const components = getEncodingComponents( colorSpace ); + + return [ + + `vec4 ${functionName}( vec4 value ) {`, + + ` return ${components[ 1 ]}( vec4( value.rgb * ${components[ 0 ]}, value.a ) );`, + + '}', + + ].join( '\n' ); + +} + +function getToneMappingFunction( functionName, toneMapping ) { + + let toneMappingName; + + switch ( toneMapping ) { + + case LinearToneMapping: + toneMappingName = 'Linear'; + break; + + case ReinhardToneMapping: + toneMappingName = 'Reinhard'; + break; + + case CineonToneMapping: + toneMappingName = 'Cineon'; + break; + + case ACESFilmicToneMapping: + toneMappingName = 'ACESFilmic'; + break; + + case AgXToneMapping: + toneMappingName = 'AgX'; + break; + + case NeutralToneMapping: + toneMappingName = 'Neutral'; + break; + + case CustomToneMapping: + toneMappingName = 'Custom'; + break; + + default: + console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping ); + toneMappingName = 'Linear'; + + } + + return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }'; + +} + +const _v0 = /*@__PURE__*/ new Vector3(); + +function getLuminanceFunction() { + + ColorManagement.getLuminanceCoefficients( _v0 ); + + const r = _v0.x.toFixed( 4 ); + const g = _v0.y.toFixed( 4 ); + const b = _v0.z.toFixed( 4 ); + + return [ + + 'float luminance( const in vec3 rgb ) {', + + ` const vec3 weights = vec3( ${ r }, ${ g }, ${ b } );`, + + ' return dot( weights, rgb );', + + '}' + + ].join( '\n' ); + +} + +function generateVertexExtensions( parameters ) { + + const chunks = [ + parameters.extensionClipCullDistance ? '#extension GL_ANGLE_clip_cull_distance : require' : '', + parameters.extensionMultiDraw ? '#extension GL_ANGLE_multi_draw : require' : '', + ]; + + return chunks.filter( filterEmptyLine ).join( '\n' ); + +} + +function generateDefines( defines ) { + + const chunks = []; + + for ( const name in defines ) { + + const value = defines[ name ]; + + if ( value === false ) continue; + + chunks.push( '#define ' + name + ' ' + value ); + + } + + return chunks.join( '\n' ); + +} + +function fetchAttributeLocations( gl, program ) { + + const attributes = {}; + + const n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES ); + + for ( let i = 0; i < n; i ++ ) { + + const info = gl.getActiveAttrib( program, i ); + const name = info.name; + + let locationSize = 1; + if ( info.type === gl.FLOAT_MAT2 ) locationSize = 2; + if ( info.type === gl.FLOAT_MAT3 ) locationSize = 3; + if ( info.type === gl.FLOAT_MAT4 ) locationSize = 4; + + // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i ); + + attributes[ name ] = { + type: info.type, + location: gl.getAttribLocation( program, name ), + locationSize: locationSize + }; + + } + + return attributes; + +} + +function filterEmptyLine( string ) { + + return string !== ''; + +} + +function replaceLightNums( string, parameters ) { + + const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps; + + return string + .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights ) + .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights ) + .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps ) + .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords ) + .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights ) + .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights ) + .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights ) + .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows ) + .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps ) + .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows ) + .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows ); + +} + +function replaceClippingPlaneNums( string, parameters ) { + + return string + .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes ) + .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) ); + +} + +// Resolve Includes + +const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm; + +function resolveIncludes( string ) { + + return string.replace( includePattern, includeReplacer ); + +} + +const shaderChunkMap = new Map(); + +function includeReplacer( match, include ) { + + let string = ShaderChunk[ include ]; + + if ( string === undefined ) { + + const newInclude = shaderChunkMap.get( include ); + + if ( newInclude !== undefined ) { + + string = ShaderChunk[ newInclude ]; + console.warn( 'THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude ); + + } else { + + throw new Error( 'Can not resolve #include <' + include + '>' ); + + } + + } + + return resolveIncludes( string ); + +} + +// Unroll Loops + +const unrollLoopPattern = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g; + +function unrollLoops( string ) { + + return string.replace( unrollLoopPattern, loopReplacer ); + +} + +function loopReplacer( match, start, end, snippet ) { + + let string = ''; + + for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) { + + string += snippet + .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' ) + .replace( /UNROLLED_LOOP_INDEX/g, i ); + + } + + return string; + +} + +// + +function generatePrecision( parameters ) { + + let precisionstring = `precision ${parameters.precision} float; + precision ${parameters.precision} int; + precision ${parameters.precision} sampler2D; + precision ${parameters.precision} samplerCube; + precision ${parameters.precision} sampler3D; + precision ${parameters.precision} sampler2DArray; + precision ${parameters.precision} sampler2DShadow; + precision ${parameters.precision} samplerCubeShadow; + precision ${parameters.precision} sampler2DArrayShadow; + precision ${parameters.precision} isampler2D; + precision ${parameters.precision} isampler3D; + precision ${parameters.precision} isamplerCube; + precision ${parameters.precision} isampler2DArray; + precision ${parameters.precision} usampler2D; + precision ${parameters.precision} usampler3D; + precision ${parameters.precision} usamplerCube; + precision ${parameters.precision} usampler2DArray; + `; + + if ( parameters.precision === 'highp' ) { + + precisionstring += '\n#define HIGH_PRECISION'; + + } else if ( parameters.precision === 'mediump' ) { + + precisionstring += '\n#define MEDIUM_PRECISION'; + + } else if ( parameters.precision === 'lowp' ) { + + precisionstring += '\n#define LOW_PRECISION'; + + } + + return precisionstring; + +} + +function generateShadowMapTypeDefine( parameters ) { + + let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC'; + + if ( parameters.shadowMapType === PCFShadowMap ) { + + shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF'; + + } else if ( parameters.shadowMapType === PCFSoftShadowMap ) { + + shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT'; + + } else if ( parameters.shadowMapType === VSMShadowMap ) { + + shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM'; + + } + + return shadowMapTypeDefine; + +} + +function generateEnvMapTypeDefine( parameters ) { + + let envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; + + if ( parameters.envMap ) { + + switch ( parameters.envMapMode ) { + + case CubeReflectionMapping: + case CubeRefractionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; + break; + + case CubeUVReflectionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV'; + break; + + } + + } + + return envMapTypeDefine; + +} + +function generateEnvMapModeDefine( parameters ) { + + let envMapModeDefine = 'ENVMAP_MODE_REFLECTION'; + + if ( parameters.envMap ) { + + switch ( parameters.envMapMode ) { + + case CubeRefractionMapping: + + envMapModeDefine = 'ENVMAP_MODE_REFRACTION'; + break; + + } + + } + + return envMapModeDefine; + +} + +function generateEnvMapBlendingDefine( parameters ) { + + let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE'; + + if ( parameters.envMap ) { + + switch ( parameters.combine ) { + + case MultiplyOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; + break; + + case MixOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_MIX'; + break; + + case AddOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_ADD'; + break; + + } + + } + + return envMapBlendingDefine; + +} + +function generateCubeUVSize( parameters ) { + + const imageHeight = parameters.envMapCubeUVHeight; + + if ( imageHeight === null ) return null; + + const maxMip = Math.log2( imageHeight ) - 2; + + const texelHeight = 1.0 / imageHeight; + + const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) ); + + return { texelWidth, texelHeight, maxMip }; + +} + +function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) { + + // TODO Send this event to Three.js DevTools + // console.log( 'WebGLProgram', cacheKey ); + + const gl = renderer.getContext(); + + const defines = parameters.defines; + + let vertexShader = parameters.vertexShader; + let fragmentShader = parameters.fragmentShader; + + const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters ); + const envMapTypeDefine = generateEnvMapTypeDefine( parameters ); + const envMapModeDefine = generateEnvMapModeDefine( parameters ); + const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters ); + const envMapCubeUVSize = generateCubeUVSize( parameters ); + + const customVertexExtensions = generateVertexExtensions( parameters ); + + const customDefines = generateDefines( defines ); + + const program = gl.createProgram(); + + let prefixVertex, prefixFragment; + let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : ''; + + if ( parameters.isRawShaderMaterial ) { + + prefixVertex = [ + + '#define SHADER_TYPE ' + parameters.shaderType, + '#define SHADER_NAME ' + parameters.shaderName, + + customDefines + + ].filter( filterEmptyLine ).join( '\n' ); + + if ( prefixVertex.length > 0 ) { + + prefixVertex += '\n'; + + } + + prefixFragment = [ + + '#define SHADER_TYPE ' + parameters.shaderType, + '#define SHADER_NAME ' + parameters.shaderName, + + customDefines + + ].filter( filterEmptyLine ).join( '\n' ); + + if ( prefixFragment.length > 0 ) { + + prefixFragment += '\n'; + + } + + } else { + + prefixVertex = [ + + generatePrecision( parameters ), + + '#define SHADER_TYPE ' + parameters.shaderType, + '#define SHADER_NAME ' + parameters.shaderName, + + customDefines, + + parameters.extensionClipCullDistance ? '#define USE_CLIP_DISTANCE' : '', + parameters.batching ? '#define USE_BATCHING' : '', + parameters.batchingColor ? '#define USE_BATCHING_COLOR' : '', + parameters.instancing ? '#define USE_INSTANCING' : '', + parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '', + parameters.instancingMorph ? '#define USE_INSTANCING_MORPH' : '', + + parameters.useFog && parameters.fog ? '#define USE_FOG' : '', + parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', + + parameters.map ? '#define USE_MAP' : '', + parameters.envMap ? '#define USE_ENVMAP' : '', + parameters.envMap ? '#define ' + envMapModeDefine : '', + parameters.lightMap ? '#define USE_LIGHTMAP' : '', + parameters.aoMap ? '#define USE_AOMAP' : '', + parameters.bumpMap ? '#define USE_BUMPMAP' : '', + parameters.normalMap ? '#define USE_NORMALMAP' : '', + parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '', + parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '', + parameters.displacementMap ? '#define USE_DISPLACEMENTMAP' : '', + parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', + + parameters.anisotropy ? '#define USE_ANISOTROPY' : '', + parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '', + + parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', + parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', + parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', + + parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '', + parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '', + + parameters.specularMap ? '#define USE_SPECULARMAP' : '', + parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '', + parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '', + + parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', + parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', + parameters.alphaMap ? '#define USE_ALPHAMAP' : '', + parameters.alphaHash ? '#define USE_ALPHAHASH' : '', + + parameters.transmission ? '#define USE_TRANSMISSION' : '', + parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', + parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', + + parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '', + parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '', + + // + + parameters.mapUv ? '#define MAP_UV ' + parameters.mapUv : '', + parameters.alphaMapUv ? '#define ALPHAMAP_UV ' + parameters.alphaMapUv : '', + parameters.lightMapUv ? '#define LIGHTMAP_UV ' + parameters.lightMapUv : '', + parameters.aoMapUv ? '#define AOMAP_UV ' + parameters.aoMapUv : '', + parameters.emissiveMapUv ? '#define EMISSIVEMAP_UV ' + parameters.emissiveMapUv : '', + parameters.bumpMapUv ? '#define BUMPMAP_UV ' + parameters.bumpMapUv : '', + parameters.normalMapUv ? '#define NORMALMAP_UV ' + parameters.normalMapUv : '', + parameters.displacementMapUv ? '#define DISPLACEMENTMAP_UV ' + parameters.displacementMapUv : '', + + parameters.metalnessMapUv ? '#define METALNESSMAP_UV ' + parameters.metalnessMapUv : '', + parameters.roughnessMapUv ? '#define ROUGHNESSMAP_UV ' + parameters.roughnessMapUv : '', + + parameters.anisotropyMapUv ? '#define ANISOTROPYMAP_UV ' + parameters.anisotropyMapUv : '', + + parameters.clearcoatMapUv ? '#define CLEARCOATMAP_UV ' + parameters.clearcoatMapUv : '', + parameters.clearcoatNormalMapUv ? '#define CLEARCOAT_NORMALMAP_UV ' + parameters.clearcoatNormalMapUv : '', + parameters.clearcoatRoughnessMapUv ? '#define CLEARCOAT_ROUGHNESSMAP_UV ' + parameters.clearcoatRoughnessMapUv : '', + + parameters.iridescenceMapUv ? '#define IRIDESCENCEMAP_UV ' + parameters.iridescenceMapUv : '', + parameters.iridescenceThicknessMapUv ? '#define IRIDESCENCE_THICKNESSMAP_UV ' + parameters.iridescenceThicknessMapUv : '', + + parameters.sheenColorMapUv ? '#define SHEEN_COLORMAP_UV ' + parameters.sheenColorMapUv : '', + parameters.sheenRoughnessMapUv ? '#define SHEEN_ROUGHNESSMAP_UV ' + parameters.sheenRoughnessMapUv : '', + + parameters.specularMapUv ? '#define SPECULARMAP_UV ' + parameters.specularMapUv : '', + parameters.specularColorMapUv ? '#define SPECULAR_COLORMAP_UV ' + parameters.specularColorMapUv : '', + parameters.specularIntensityMapUv ? '#define SPECULAR_INTENSITYMAP_UV ' + parameters.specularIntensityMapUv : '', + + parameters.transmissionMapUv ? '#define TRANSMISSIONMAP_UV ' + parameters.transmissionMapUv : '', + parameters.thicknessMapUv ? '#define THICKNESSMAP_UV ' + parameters.thicknessMapUv : '', + + // + + parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '', + parameters.vertexColors ? '#define USE_COLOR' : '', + parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', + parameters.vertexUv1s ? '#define USE_UV1' : '', + parameters.vertexUv2s ? '#define USE_UV2' : '', + parameters.vertexUv3s ? '#define USE_UV3' : '', + + parameters.pointsUvs ? '#define USE_POINTS_UV' : '', + + parameters.flatShading ? '#define FLAT_SHADED' : '', + + parameters.skinning ? '#define USE_SKINNING' : '', + + parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', + parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', + ( parameters.morphColors ) ? '#define USE_MORPHCOLORS' : '', + ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '', + ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '', + parameters.doubleSided ? '#define DOUBLE_SIDED' : '', + parameters.flipSided ? '#define FLIP_SIDED' : '', + + parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', + parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', + + parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', + + parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '', + + parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', + parameters.reverseDepthBuffer ? '#define USE_REVERSEDEPTHBUF' : '', + + 'uniform mat4 modelMatrix;', + 'uniform mat4 modelViewMatrix;', + 'uniform mat4 projectionMatrix;', + 'uniform mat4 viewMatrix;', + 'uniform mat3 normalMatrix;', + 'uniform vec3 cameraPosition;', + 'uniform bool isOrthographic;', + + '#ifdef USE_INSTANCING', + + ' attribute mat4 instanceMatrix;', + + '#endif', + + '#ifdef USE_INSTANCING_COLOR', + + ' attribute vec3 instanceColor;', + + '#endif', + + '#ifdef USE_INSTANCING_MORPH', + + ' uniform sampler2D morphTexture;', + + '#endif', + + 'attribute vec3 position;', + 'attribute vec3 normal;', + 'attribute vec2 uv;', + + '#ifdef USE_UV1', + + ' attribute vec2 uv1;', + + '#endif', + + '#ifdef USE_UV2', + + ' attribute vec2 uv2;', + + '#endif', + + '#ifdef USE_UV3', + + ' attribute vec2 uv3;', + + '#endif', + + '#ifdef USE_TANGENT', + + ' attribute vec4 tangent;', + + '#endif', + + '#if defined( USE_COLOR_ALPHA )', + + ' attribute vec4 color;', + + '#elif defined( USE_COLOR )', + + ' attribute vec3 color;', + + '#endif', + + '#ifdef USE_SKINNING', + + ' attribute vec4 skinIndex;', + ' attribute vec4 skinWeight;', + + '#endif', + + '\n' + + ].filter( filterEmptyLine ).join( '\n' ); + + prefixFragment = [ + + generatePrecision( parameters ), + + '#define SHADER_TYPE ' + parameters.shaderType, + '#define SHADER_NAME ' + parameters.shaderName, + + customDefines, + + parameters.useFog && parameters.fog ? '#define USE_FOG' : '', + parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', + + parameters.alphaToCoverage ? '#define ALPHA_TO_COVERAGE' : '', + parameters.map ? '#define USE_MAP' : '', + parameters.matcap ? '#define USE_MATCAP' : '', + parameters.envMap ? '#define USE_ENVMAP' : '', + parameters.envMap ? '#define ' + envMapTypeDefine : '', + parameters.envMap ? '#define ' + envMapModeDefine : '', + parameters.envMap ? '#define ' + envMapBlendingDefine : '', + envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '', + envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '', + envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '', + parameters.lightMap ? '#define USE_LIGHTMAP' : '', + parameters.aoMap ? '#define USE_AOMAP' : '', + parameters.bumpMap ? '#define USE_BUMPMAP' : '', + parameters.normalMap ? '#define USE_NORMALMAP' : '', + parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '', + parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '', + parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', + + parameters.anisotropy ? '#define USE_ANISOTROPY' : '', + parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '', + + parameters.clearcoat ? '#define USE_CLEARCOAT' : '', + parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', + parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', + parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', + + parameters.dispersion ? '#define USE_DISPERSION' : '', + + parameters.iridescence ? '#define USE_IRIDESCENCE' : '', + parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '', + parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '', + + parameters.specularMap ? '#define USE_SPECULARMAP' : '', + parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '', + parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '', + + parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', + parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', + + parameters.alphaMap ? '#define USE_ALPHAMAP' : '', + parameters.alphaTest ? '#define USE_ALPHATEST' : '', + parameters.alphaHash ? '#define USE_ALPHAHASH' : '', + + parameters.sheen ? '#define USE_SHEEN' : '', + parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '', + parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '', + + parameters.transmission ? '#define USE_TRANSMISSION' : '', + parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', + parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', + + parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '', + parameters.vertexColors || parameters.instancingColor || parameters.batchingColor ? '#define USE_COLOR' : '', + parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', + parameters.vertexUv1s ? '#define USE_UV1' : '', + parameters.vertexUv2s ? '#define USE_UV2' : '', + parameters.vertexUv3s ? '#define USE_UV3' : '', + + parameters.pointsUvs ? '#define USE_POINTS_UV' : '', + + parameters.gradientMap ? '#define USE_GRADIENTMAP' : '', + + parameters.flatShading ? '#define FLAT_SHADED' : '', + + parameters.doubleSided ? '#define DOUBLE_SIDED' : '', + parameters.flipSided ? '#define FLIP_SIDED' : '', + + parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', + parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', + + parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '', + + parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '', + + parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '', + parameters.decodeVideoTextureEmissive ? '#define DECODE_VIDEO_TEXTURE_EMISSIVE' : '', + + parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', + parameters.reverseDepthBuffer ? '#define USE_REVERSEDEPTHBUF' : '', + + 'uniform mat4 viewMatrix;', + 'uniform vec3 cameraPosition;', + 'uniform bool isOrthographic;', + + ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '', + ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below + ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '', + + parameters.dithering ? '#define DITHERING' : '', + parameters.opaque ? '#define OPAQUE' : '', + + ShaderChunk[ 'colorspace_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below + getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputColorSpace ), + getLuminanceFunction(), + + parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', + + '\n' + + ].filter( filterEmptyLine ).join( '\n' ); + + } + + vertexShader = resolveIncludes( vertexShader ); + vertexShader = replaceLightNums( vertexShader, parameters ); + vertexShader = replaceClippingPlaneNums( vertexShader, parameters ); + + fragmentShader = resolveIncludes( fragmentShader ); + fragmentShader = replaceLightNums( fragmentShader, parameters ); + fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters ); + + vertexShader = unrollLoops( vertexShader ); + fragmentShader = unrollLoops( fragmentShader ); + + if ( parameters.isRawShaderMaterial !== true ) { + + // GLSL 3.0 conversion for built-in materials and ShaderMaterial + + versionString = '#version 300 es\n'; + + prefixVertex = [ + customVertexExtensions, + '#define attribute in', + '#define varying out', + '#define texture2D texture' + ].join( '\n' ) + '\n' + prefixVertex; + + prefixFragment = [ + '#define varying in', + ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;', + ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor', + '#define gl_FragDepthEXT gl_FragDepth', + '#define texture2D texture', + '#define textureCube texture', + '#define texture2DProj textureProj', + '#define texture2DLodEXT textureLod', + '#define texture2DProjLodEXT textureProjLod', + '#define textureCubeLodEXT textureLod', + '#define texture2DGradEXT textureGrad', + '#define texture2DProjGradEXT textureProjGrad', + '#define textureCubeGradEXT textureGrad' + ].join( '\n' ) + '\n' + prefixFragment; + + } + + const vertexGlsl = versionString + prefixVertex + vertexShader; + const fragmentGlsl = versionString + prefixFragment + fragmentShader; + + // console.log( '*VERTEX*', vertexGlsl ); + // console.log( '*FRAGMENT*', fragmentGlsl ); + + const glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl ); + const glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl ); + + gl.attachShader( program, glVertexShader ); + gl.attachShader( program, glFragmentShader ); + + // Force a particular attribute to index 0. + + if ( parameters.index0AttributeName !== undefined ) { + + gl.bindAttribLocation( program, 0, parameters.index0AttributeName ); + + } else if ( parameters.morphTargets === true ) { + + // programs with morphTargets displace position out of attribute 0 + gl.bindAttribLocation( program, 0, 'position' ); + + } + + gl.linkProgram( program ); + + function onFirstUse( self ) { + + // check for link errors + if ( renderer.debug.checkShaderErrors ) { + + const programLog = gl.getProgramInfoLog( program ).trim(); + const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim(); + const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim(); + + let runnable = true; + let haveDiagnostics = true; + + if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) { + + runnable = false; + + if ( typeof renderer.debug.onShaderError === 'function' ) { + + renderer.debug.onShaderError( gl, program, glVertexShader, glFragmentShader ); + + } else { + + // default error reporting + + const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' ); + const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' ); + + console.error( + 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' + + 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' + + 'Material Name: ' + self.name + '\n' + + 'Material Type: ' + self.type + '\n\n' + + 'Program Info Log: ' + programLog + '\n' + + vertexErrors + '\n' + + fragmentErrors + ); + + } + + } else if ( programLog !== '' ) { + + console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog ); + + } else if ( vertexLog === '' || fragmentLog === '' ) { + + haveDiagnostics = false; + + } + + if ( haveDiagnostics ) { + + self.diagnostics = { + + runnable: runnable, + + programLog: programLog, + + vertexShader: { + + log: vertexLog, + prefix: prefixVertex + + }, + + fragmentShader: { + + log: fragmentLog, + prefix: prefixFragment + + } + + }; + + } + + } + + // Clean up + + // Crashes in iOS9 and iOS10. #18402 + // gl.detachShader( program, glVertexShader ); + // gl.detachShader( program, glFragmentShader ); + + gl.deleteShader( glVertexShader ); + gl.deleteShader( glFragmentShader ); + + cachedUniforms = new WebGLUniforms( gl, program ); + cachedAttributes = fetchAttributeLocations( gl, program ); + + } + + // set up caching for uniform locations + + let cachedUniforms; + + this.getUniforms = function () { + + if ( cachedUniforms === undefined ) { + + // Populates cachedUniforms and cachedAttributes + onFirstUse( this ); + + } + + return cachedUniforms; + + }; + + // set up caching for attribute locations + + let cachedAttributes; + + this.getAttributes = function () { + + if ( cachedAttributes === undefined ) { + + // Populates cachedAttributes and cachedUniforms + onFirstUse( this ); + + } + + return cachedAttributes; + + }; + + // indicate when the program is ready to be used. if the KHR_parallel_shader_compile extension isn't supported, + // flag the program as ready immediately. It may cause a stall when it's first used. + + let programReady = ( parameters.rendererExtensionParallelShaderCompile === false ); + + this.isReady = function () { + + if ( programReady === false ) { + + programReady = gl.getProgramParameter( program, COMPLETION_STATUS_KHR ); + + } + + return programReady; + + }; + + // free resource + + this.destroy = function () { + + bindingStates.releaseStatesOfProgram( this ); + + gl.deleteProgram( program ); + this.program = undefined; + + }; + + // + + this.type = parameters.shaderType; + this.name = parameters.shaderName; + this.id = programIdCount ++; + this.cacheKey = cacheKey; + this.usedTimes = 1; + this.program = program; + this.vertexShader = glVertexShader; + this.fragmentShader = glFragmentShader; + + return this; + +} + +let _id = 0; + +class WebGLShaderCache { + + constructor() { + + this.shaderCache = new Map(); + this.materialCache = new Map(); + + } + + update( material ) { + + const vertexShader = material.vertexShader; + const fragmentShader = material.fragmentShader; + + const vertexShaderStage = this._getShaderStage( vertexShader ); + const fragmentShaderStage = this._getShaderStage( fragmentShader ); + + const materialShaders = this._getShaderCacheForMaterial( material ); + + if ( materialShaders.has( vertexShaderStage ) === false ) { + + materialShaders.add( vertexShaderStage ); + vertexShaderStage.usedTimes ++; + + } + + if ( materialShaders.has( fragmentShaderStage ) === false ) { + + materialShaders.add( fragmentShaderStage ); + fragmentShaderStage.usedTimes ++; + + } + + return this; + + } + + remove( material ) { + + const materialShaders = this.materialCache.get( material ); + + for ( const shaderStage of materialShaders ) { + + shaderStage.usedTimes --; + + if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code ); + + } + + this.materialCache.delete( material ); + + return this; + + } + + getVertexShaderID( material ) { + + return this._getShaderStage( material.vertexShader ).id; + + } + + getFragmentShaderID( material ) { + + return this._getShaderStage( material.fragmentShader ).id; + + } + + dispose() { + + this.shaderCache.clear(); + this.materialCache.clear(); + + } + + _getShaderCacheForMaterial( material ) { + + const cache = this.materialCache; + let set = cache.get( material ); + + if ( set === undefined ) { + + set = new Set(); + cache.set( material, set ); + + } + + return set; + + } + + _getShaderStage( code ) { + + const cache = this.shaderCache; + let stage = cache.get( code ); + + if ( stage === undefined ) { + + stage = new WebGLShaderStage( code ); + cache.set( code, stage ); + + } + + return stage; + + } + +} + +class WebGLShaderStage { + + constructor( code ) { + + this.id = _id ++; + + this.code = code; + this.usedTimes = 0; + + } + +} + +function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) { + + const _programLayers = new Layers(); + const _customShaders = new WebGLShaderCache(); + const _activeChannels = new Set(); + const programs = []; + + const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer; + const SUPPORTS_VERTEX_TEXTURES = capabilities.vertexTextures; + + let precision = capabilities.precision; + + const shaderIDs = { + MeshDepthMaterial: 'depth', + MeshDistanceMaterial: 'distanceRGBA', + MeshNormalMaterial: 'normal', + MeshBasicMaterial: 'basic', + MeshLambertMaterial: 'lambert', + MeshPhongMaterial: 'phong', + MeshToonMaterial: 'toon', + MeshStandardMaterial: 'physical', + MeshPhysicalMaterial: 'physical', + MeshMatcapMaterial: 'matcap', + LineBasicMaterial: 'basic', + LineDashedMaterial: 'dashed', + PointsMaterial: 'points', + ShadowMaterial: 'shadow', + SpriteMaterial: 'sprite' + }; + + function getChannel( value ) { + + _activeChannels.add( value ); + + if ( value === 0 ) return 'uv'; + + return `uv${ value }`; + + } + + function getParameters( material, lights, shadows, scene, object ) { + + const fog = scene.fog; + const geometry = object.geometry; + const environment = material.isMeshStandardMaterial ? scene.environment : null; + + const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment ); + const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null; + + const shaderID = shaderIDs[ material.type ]; + + // heuristics to create shader parameters according to lights in the scene + // (not to blow over maxLights budget) + + if ( material.precision !== null ) { + + precision = capabilities.getMaxPrecision( material.precision ); + + if ( precision !== material.precision ) { + + console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' ); + + } + + } + + // + + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0; + + let morphTextureStride = 0; + + if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1; + if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2; + if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3; + + // + + let vertexShader, fragmentShader; + let customVertexShaderID, customFragmentShaderID; + + if ( shaderID ) { + + const shader = ShaderLib[ shaderID ]; + + vertexShader = shader.vertexShader; + fragmentShader = shader.fragmentShader; + + } else { + + vertexShader = material.vertexShader; + fragmentShader = material.fragmentShader; + + _customShaders.update( material ); + + customVertexShaderID = _customShaders.getVertexShaderID( material ); + customFragmentShaderID = _customShaders.getFragmentShaderID( material ); + + } + + const currentRenderTarget = renderer.getRenderTarget(); + const reverseDepthBuffer = renderer.state.buffers.depth.getReversed(); + + const IS_INSTANCEDMESH = object.isInstancedMesh === true; + const IS_BATCHEDMESH = object.isBatchedMesh === true; + + const HAS_MAP = !! material.map; + const HAS_MATCAP = !! material.matcap; + const HAS_ENVMAP = !! envMap; + const HAS_AOMAP = !! material.aoMap; + const HAS_LIGHTMAP = !! material.lightMap; + const HAS_BUMPMAP = !! material.bumpMap; + const HAS_NORMALMAP = !! material.normalMap; + const HAS_DISPLACEMENTMAP = !! material.displacementMap; + const HAS_EMISSIVEMAP = !! material.emissiveMap; + + const HAS_METALNESSMAP = !! material.metalnessMap; + const HAS_ROUGHNESSMAP = !! material.roughnessMap; + + const HAS_ANISOTROPY = material.anisotropy > 0; + const HAS_CLEARCOAT = material.clearcoat > 0; + const HAS_DISPERSION = material.dispersion > 0; + const HAS_IRIDESCENCE = material.iridescence > 0; + const HAS_SHEEN = material.sheen > 0; + const HAS_TRANSMISSION = material.transmission > 0; + + const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !! material.anisotropyMap; + + const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !! material.clearcoatMap; + const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !! material.clearcoatNormalMap; + const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !! material.clearcoatRoughnessMap; + + const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !! material.iridescenceMap; + const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !! material.iridescenceThicknessMap; + + const HAS_SHEEN_COLORMAP = HAS_SHEEN && !! material.sheenColorMap; + const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !! material.sheenRoughnessMap; + + const HAS_SPECULARMAP = !! material.specularMap; + const HAS_SPECULAR_COLORMAP = !! material.specularColorMap; + const HAS_SPECULAR_INTENSITYMAP = !! material.specularIntensityMap; + + const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !! material.transmissionMap; + const HAS_THICKNESSMAP = HAS_TRANSMISSION && !! material.thicknessMap; + + const HAS_GRADIENTMAP = !! material.gradientMap; + + const HAS_ALPHAMAP = !! material.alphaMap; + + const HAS_ALPHATEST = material.alphaTest > 0; + + const HAS_ALPHAHASH = !! material.alphaHash; + + const HAS_EXTENSIONS = !! material.extensions; + + let toneMapping = NoToneMapping; + + if ( material.toneMapped ) { + + if ( currentRenderTarget === null || currentRenderTarget.isXRRenderTarget === true ) { + + toneMapping = renderer.toneMapping; + + } + + } + + const parameters = { + + shaderID: shaderID, + shaderType: material.type, + shaderName: material.name, + + vertexShader: vertexShader, + fragmentShader: fragmentShader, + defines: material.defines, + + customVertexShaderID: customVertexShaderID, + customFragmentShaderID: customFragmentShaderID, + + isRawShaderMaterial: material.isRawShaderMaterial === true, + glslVersion: material.glslVersion, + + precision: precision, + + batching: IS_BATCHEDMESH, + batchingColor: IS_BATCHEDMESH && object._colorsTexture !== null, + instancing: IS_INSTANCEDMESH, + instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null, + instancingMorph: IS_INSTANCEDMESH && object.morphTexture !== null, + + supportsVertexTextures: SUPPORTS_VERTEX_TEXTURES, + outputColorSpace: ( currentRenderTarget === null ) ? renderer.outputColorSpace : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace ), + alphaToCoverage: !! material.alphaToCoverage, + + map: HAS_MAP, + matcap: HAS_MATCAP, + envMap: HAS_ENVMAP, + envMapMode: HAS_ENVMAP && envMap.mapping, + envMapCubeUVHeight: envMapCubeUVHeight, + aoMap: HAS_AOMAP, + lightMap: HAS_LIGHTMAP, + bumpMap: HAS_BUMPMAP, + normalMap: HAS_NORMALMAP, + displacementMap: SUPPORTS_VERTEX_TEXTURES && HAS_DISPLACEMENTMAP, + emissiveMap: HAS_EMISSIVEMAP, + + normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap, + normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap, + + metalnessMap: HAS_METALNESSMAP, + roughnessMap: HAS_ROUGHNESSMAP, + + anisotropy: HAS_ANISOTROPY, + anisotropyMap: HAS_ANISOTROPYMAP, + + clearcoat: HAS_CLEARCOAT, + clearcoatMap: HAS_CLEARCOATMAP, + clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP, + clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP, + + dispersion: HAS_DISPERSION, + + iridescence: HAS_IRIDESCENCE, + iridescenceMap: HAS_IRIDESCENCEMAP, + iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP, + + sheen: HAS_SHEEN, + sheenColorMap: HAS_SHEEN_COLORMAP, + sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP, + + specularMap: HAS_SPECULARMAP, + specularColorMap: HAS_SPECULAR_COLORMAP, + specularIntensityMap: HAS_SPECULAR_INTENSITYMAP, + + transmission: HAS_TRANSMISSION, + transmissionMap: HAS_TRANSMISSIONMAP, + thicknessMap: HAS_THICKNESSMAP, + + gradientMap: HAS_GRADIENTMAP, + + opaque: material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false, + + alphaMap: HAS_ALPHAMAP, + alphaTest: HAS_ALPHATEST, + alphaHash: HAS_ALPHAHASH, + + combine: material.combine, + + // + + mapUv: HAS_MAP && getChannel( material.map.channel ), + aoMapUv: HAS_AOMAP && getChannel( material.aoMap.channel ), + lightMapUv: HAS_LIGHTMAP && getChannel( material.lightMap.channel ), + bumpMapUv: HAS_BUMPMAP && getChannel( material.bumpMap.channel ), + normalMapUv: HAS_NORMALMAP && getChannel( material.normalMap.channel ), + displacementMapUv: HAS_DISPLACEMENTMAP && getChannel( material.displacementMap.channel ), + emissiveMapUv: HAS_EMISSIVEMAP && getChannel( material.emissiveMap.channel ), + + metalnessMapUv: HAS_METALNESSMAP && getChannel( material.metalnessMap.channel ), + roughnessMapUv: HAS_ROUGHNESSMAP && getChannel( material.roughnessMap.channel ), + + anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel( material.anisotropyMap.channel ), + + clearcoatMapUv: HAS_CLEARCOATMAP && getChannel( material.clearcoatMap.channel ), + clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel( material.clearcoatNormalMap.channel ), + clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel( material.clearcoatRoughnessMap.channel ), + + iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel( material.iridescenceMap.channel ), + iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel( material.iridescenceThicknessMap.channel ), + + sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel( material.sheenColorMap.channel ), + sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel( material.sheenRoughnessMap.channel ), + + specularMapUv: HAS_SPECULARMAP && getChannel( material.specularMap.channel ), + specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel( material.specularColorMap.channel ), + specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel( material.specularIntensityMap.channel ), + + transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel( material.transmissionMap.channel ), + thicknessMapUv: HAS_THICKNESSMAP && getChannel( material.thicknessMap.channel ), + + alphaMapUv: HAS_ALPHAMAP && getChannel( material.alphaMap.channel ), + + // + + vertexTangents: !! geometry.attributes.tangent && ( HAS_NORMALMAP || HAS_ANISOTROPY ), + vertexColors: material.vertexColors, + vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4, + + pointsUvs: object.isPoints === true && !! geometry.attributes.uv && ( HAS_MAP || HAS_ALPHAMAP ), + + fog: !! fog, + useFog: material.fog === true, + fogExp2: ( !! fog && fog.isFogExp2 ), + + flatShading: material.flatShading === true, + + sizeAttenuation: material.sizeAttenuation === true, + logarithmicDepthBuffer: logarithmicDepthBuffer, + reverseDepthBuffer: reverseDepthBuffer, + + skinning: object.isSkinnedMesh === true, + + morphTargets: geometry.morphAttributes.position !== undefined, + morphNormals: geometry.morphAttributes.normal !== undefined, + morphColors: geometry.morphAttributes.color !== undefined, + morphTargetsCount: morphTargetsCount, + morphTextureStride: morphTextureStride, + + numDirLights: lights.directional.length, + numPointLights: lights.point.length, + numSpotLights: lights.spot.length, + numSpotLightMaps: lights.spotLightMap.length, + numRectAreaLights: lights.rectArea.length, + numHemiLights: lights.hemi.length, + + numDirLightShadows: lights.directionalShadowMap.length, + numPointLightShadows: lights.pointShadowMap.length, + numSpotLightShadows: lights.spotShadowMap.length, + numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps, + + numLightProbes: lights.numLightProbes, + + numClippingPlanes: clipping.numPlanes, + numClipIntersection: clipping.numIntersection, + + dithering: material.dithering, + + shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0, + shadowMapType: renderer.shadowMap.type, + + toneMapping: toneMapping, + + decodeVideoTexture: HAS_MAP && ( material.map.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.map.colorSpace ) === SRGBTransfer ), + decodeVideoTextureEmissive: HAS_EMISSIVEMAP && ( material.emissiveMap.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.emissiveMap.colorSpace ) === SRGBTransfer ), + + premultipliedAlpha: material.premultipliedAlpha, + + doubleSided: material.side === DoubleSide, + flipSided: material.side === BackSide, + + useDepthPacking: material.depthPacking >= 0, + depthPacking: material.depthPacking || 0, + + index0AttributeName: material.index0AttributeName, + + extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance === true && extensions.has( 'WEBGL_clip_cull_distance' ), + extensionMultiDraw: ( HAS_EXTENSIONS && material.extensions.multiDraw === true || IS_BATCHEDMESH ) && extensions.has( 'WEBGL_multi_draw' ), + + rendererExtensionParallelShaderCompile: extensions.has( 'KHR_parallel_shader_compile' ), + + customProgramCacheKey: material.customProgramCacheKey() + + }; + + // the usage of getChannel() determines the active texture channels for this shader + + parameters.vertexUv1s = _activeChannels.has( 1 ); + parameters.vertexUv2s = _activeChannels.has( 2 ); + parameters.vertexUv3s = _activeChannels.has( 3 ); + + _activeChannels.clear(); + + return parameters; + + } + + function getProgramCacheKey( parameters ) { + + const array = []; + + if ( parameters.shaderID ) { + + array.push( parameters.shaderID ); + + } else { + + array.push( parameters.customVertexShaderID ); + array.push( parameters.customFragmentShaderID ); + + } + + if ( parameters.defines !== undefined ) { + + for ( const name in parameters.defines ) { + + array.push( name ); + array.push( parameters.defines[ name ] ); + + } + + } + + if ( parameters.isRawShaderMaterial === false ) { + + getProgramCacheKeyParameters( array, parameters ); + getProgramCacheKeyBooleans( array, parameters ); + array.push( renderer.outputColorSpace ); + + } + + array.push( parameters.customProgramCacheKey ); + + return array.join(); + + } + + function getProgramCacheKeyParameters( array, parameters ) { + + array.push( parameters.precision ); + array.push( parameters.outputColorSpace ); + array.push( parameters.envMapMode ); + array.push( parameters.envMapCubeUVHeight ); + array.push( parameters.mapUv ); + array.push( parameters.alphaMapUv ); + array.push( parameters.lightMapUv ); + array.push( parameters.aoMapUv ); + array.push( parameters.bumpMapUv ); + array.push( parameters.normalMapUv ); + array.push( parameters.displacementMapUv ); + array.push( parameters.emissiveMapUv ); + array.push( parameters.metalnessMapUv ); + array.push( parameters.roughnessMapUv ); + array.push( parameters.anisotropyMapUv ); + array.push( parameters.clearcoatMapUv ); + array.push( parameters.clearcoatNormalMapUv ); + array.push( parameters.clearcoatRoughnessMapUv ); + array.push( parameters.iridescenceMapUv ); + array.push( parameters.iridescenceThicknessMapUv ); + array.push( parameters.sheenColorMapUv ); + array.push( parameters.sheenRoughnessMapUv ); + array.push( parameters.specularMapUv ); + array.push( parameters.specularColorMapUv ); + array.push( parameters.specularIntensityMapUv ); + array.push( parameters.transmissionMapUv ); + array.push( parameters.thicknessMapUv ); + array.push( parameters.combine ); + array.push( parameters.fogExp2 ); + array.push( parameters.sizeAttenuation ); + array.push( parameters.morphTargetsCount ); + array.push( parameters.morphAttributeCount ); + array.push( parameters.numDirLights ); + array.push( parameters.numPointLights ); + array.push( parameters.numSpotLights ); + array.push( parameters.numSpotLightMaps ); + array.push( parameters.numHemiLights ); + array.push( parameters.numRectAreaLights ); + array.push( parameters.numDirLightShadows ); + array.push( parameters.numPointLightShadows ); + array.push( parameters.numSpotLightShadows ); + array.push( parameters.numSpotLightShadowsWithMaps ); + array.push( parameters.numLightProbes ); + array.push( parameters.shadowMapType ); + array.push( parameters.toneMapping ); + array.push( parameters.numClippingPlanes ); + array.push( parameters.numClipIntersection ); + array.push( parameters.depthPacking ); + + } + + function getProgramCacheKeyBooleans( array, parameters ) { + + _programLayers.disableAll(); + + if ( parameters.supportsVertexTextures ) + _programLayers.enable( 0 ); + if ( parameters.instancing ) + _programLayers.enable( 1 ); + if ( parameters.instancingColor ) + _programLayers.enable( 2 ); + if ( parameters.instancingMorph ) + _programLayers.enable( 3 ); + if ( parameters.matcap ) + _programLayers.enable( 4 ); + if ( parameters.envMap ) + _programLayers.enable( 5 ); + if ( parameters.normalMapObjectSpace ) + _programLayers.enable( 6 ); + if ( parameters.normalMapTangentSpace ) + _programLayers.enable( 7 ); + if ( parameters.clearcoat ) + _programLayers.enable( 8 ); + if ( parameters.iridescence ) + _programLayers.enable( 9 ); + if ( parameters.alphaTest ) + _programLayers.enable( 10 ); + if ( parameters.vertexColors ) + _programLayers.enable( 11 ); + if ( parameters.vertexAlphas ) + _programLayers.enable( 12 ); + if ( parameters.vertexUv1s ) + _programLayers.enable( 13 ); + if ( parameters.vertexUv2s ) + _programLayers.enable( 14 ); + if ( parameters.vertexUv3s ) + _programLayers.enable( 15 ); + if ( parameters.vertexTangents ) + _programLayers.enable( 16 ); + if ( parameters.anisotropy ) + _programLayers.enable( 17 ); + if ( parameters.alphaHash ) + _programLayers.enable( 18 ); + if ( parameters.batching ) + _programLayers.enable( 19 ); + if ( parameters.dispersion ) + _programLayers.enable( 20 ); + if ( parameters.batchingColor ) + _programLayers.enable( 21 ); + + array.push( _programLayers.mask ); + _programLayers.disableAll(); + + if ( parameters.fog ) + _programLayers.enable( 0 ); + if ( parameters.useFog ) + _programLayers.enable( 1 ); + if ( parameters.flatShading ) + _programLayers.enable( 2 ); + if ( parameters.logarithmicDepthBuffer ) + _programLayers.enable( 3 ); + if ( parameters.reverseDepthBuffer ) + _programLayers.enable( 4 ); + if ( parameters.skinning ) + _programLayers.enable( 5 ); + if ( parameters.morphTargets ) + _programLayers.enable( 6 ); + if ( parameters.morphNormals ) + _programLayers.enable( 7 ); + if ( parameters.morphColors ) + _programLayers.enable( 8 ); + if ( parameters.premultipliedAlpha ) + _programLayers.enable( 9 ); + if ( parameters.shadowMapEnabled ) + _programLayers.enable( 10 ); + if ( parameters.doubleSided ) + _programLayers.enable( 11 ); + if ( parameters.flipSided ) + _programLayers.enable( 12 ); + if ( parameters.useDepthPacking ) + _programLayers.enable( 13 ); + if ( parameters.dithering ) + _programLayers.enable( 14 ); + if ( parameters.transmission ) + _programLayers.enable( 15 ); + if ( parameters.sheen ) + _programLayers.enable( 16 ); + if ( parameters.opaque ) + _programLayers.enable( 17 ); + if ( parameters.pointsUvs ) + _programLayers.enable( 18 ); + if ( parameters.decodeVideoTexture ) + _programLayers.enable( 19 ); + if ( parameters.decodeVideoTextureEmissive ) + _programLayers.enable( 20 ); + if ( parameters.alphaToCoverage ) + _programLayers.enable( 21 ); + + array.push( _programLayers.mask ); + + } + + function getUniforms( material ) { + + const shaderID = shaderIDs[ material.type ]; + let uniforms; + + if ( shaderID ) { + + const shader = ShaderLib[ shaderID ]; + uniforms = UniformsUtils.clone( shader.uniforms ); + + } else { + + uniforms = material.uniforms; + + } + + return uniforms; + + } + + function acquireProgram( parameters, cacheKey ) { + + let program; + + // Check if code has been already compiled + for ( let p = 0, pl = programs.length; p < pl; p ++ ) { + + const preexistingProgram = programs[ p ]; + + if ( preexistingProgram.cacheKey === cacheKey ) { + + program = preexistingProgram; + ++ program.usedTimes; + + break; + + } + + } + + if ( program === undefined ) { + + program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates ); + programs.push( program ); + + } + + return program; + + } + + function releaseProgram( program ) { + + if ( -- program.usedTimes === 0 ) { + + // Remove from unordered set + const i = programs.indexOf( program ); + programs[ i ] = programs[ programs.length - 1 ]; + programs.pop(); + + // Free WebGL resources + program.destroy(); + + } + + } + + function releaseShaderCache( material ) { + + _customShaders.remove( material ); + + } + + function dispose() { + + _customShaders.dispose(); + + } + + return { + getParameters: getParameters, + getProgramCacheKey: getProgramCacheKey, + getUniforms: getUniforms, + acquireProgram: acquireProgram, + releaseProgram: releaseProgram, + releaseShaderCache: releaseShaderCache, + // Exposed for resource monitoring & error feedback via renderer.info: + programs: programs, + dispose: dispose + }; + +} + +function WebGLProperties() { + + let properties = new WeakMap(); + + function has( object ) { + + return properties.has( object ); + + } + + function get( object ) { + + let map = properties.get( object ); + + if ( map === undefined ) { + + map = {}; + properties.set( object, map ); + + } + + return map; + + } + + function remove( object ) { + + properties.delete( object ); + + } + + function update( object, key, value ) { + + properties.get( object )[ key ] = value; + + } + + function dispose() { + + properties = new WeakMap(); + + } + + return { + has: has, + get: get, + remove: remove, + update: update, + dispose: dispose + }; + +} + +function painterSortStable( a, b ) { + + if ( a.groupOrder !== b.groupOrder ) { + + return a.groupOrder - b.groupOrder; + + } else if ( a.renderOrder !== b.renderOrder ) { + + return a.renderOrder - b.renderOrder; + + } else if ( a.material.id !== b.material.id ) { + + return a.material.id - b.material.id; + + } else if ( a.z !== b.z ) { + + return a.z - b.z; + + } else { + + return a.id - b.id; + + } + +} + +function reversePainterSortStable( a, b ) { + + if ( a.groupOrder !== b.groupOrder ) { + + return a.groupOrder - b.groupOrder; + + } else if ( a.renderOrder !== b.renderOrder ) { + + return a.renderOrder - b.renderOrder; + + } else if ( a.z !== b.z ) { + + return b.z - a.z; + + } else { + + return a.id - b.id; + + } + +} + + +function WebGLRenderList() { + + const renderItems = []; + let renderItemsIndex = 0; + + const opaque = []; + const transmissive = []; + const transparent = []; + + function init() { + + renderItemsIndex = 0; + + opaque.length = 0; + transmissive.length = 0; + transparent.length = 0; + + } + + function getNextRenderItem( object, geometry, material, groupOrder, z, group ) { + + let renderItem = renderItems[ renderItemsIndex ]; + + if ( renderItem === undefined ) { + + renderItem = { + id: object.id, + object: object, + geometry: geometry, + material: material, + groupOrder: groupOrder, + renderOrder: object.renderOrder, + z: z, + group: group + }; + + renderItems[ renderItemsIndex ] = renderItem; + + } else { + + renderItem.id = object.id; + renderItem.object = object; + renderItem.geometry = geometry; + renderItem.material = material; + renderItem.groupOrder = groupOrder; + renderItem.renderOrder = object.renderOrder; + renderItem.z = z; + renderItem.group = group; + + } + + renderItemsIndex ++; + + return renderItem; + + } + + function push( object, geometry, material, groupOrder, z, group ) { + + const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group ); + + if ( material.transmission > 0.0 ) { + + transmissive.push( renderItem ); + + } else if ( material.transparent === true ) { + + transparent.push( renderItem ); + + } else { + + opaque.push( renderItem ); + + } + + } + + function unshift( object, geometry, material, groupOrder, z, group ) { + + const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group ); + + if ( material.transmission > 0.0 ) { + + transmissive.unshift( renderItem ); + + } else if ( material.transparent === true ) { + + transparent.unshift( renderItem ); + + } else { + + opaque.unshift( renderItem ); + + } + + } + + function sort( customOpaqueSort, customTransparentSort ) { + + if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable ); + if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable ); + if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable ); + + } + + function finish() { + + // Clear references from inactive renderItems in the list + + for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) { + + const renderItem = renderItems[ i ]; + + if ( renderItem.id === null ) break; + + renderItem.id = null; + renderItem.object = null; + renderItem.geometry = null; + renderItem.material = null; + renderItem.group = null; + + } + + } + + return { + + opaque: opaque, + transmissive: transmissive, + transparent: transparent, + + init: init, + push: push, + unshift: unshift, + finish: finish, + + sort: sort + }; + +} + +function WebGLRenderLists() { + + let lists = new WeakMap(); + + function get( scene, renderCallDepth ) { + + const listArray = lists.get( scene ); + let list; + + if ( listArray === undefined ) { + + list = new WebGLRenderList(); + lists.set( scene, [ list ] ); + + } else { + + if ( renderCallDepth >= listArray.length ) { + + list = new WebGLRenderList(); + listArray.push( list ); + + } else { + + list = listArray[ renderCallDepth ]; + + } + + } + + return list; + + } + + function dispose() { + + lists = new WeakMap(); + + } + + return { + get: get, + dispose: dispose + }; + +} + +function UniformsCache() { + + const lights = {}; + + return { + + get: function ( light ) { + + if ( lights[ light.id ] !== undefined ) { + + return lights[ light.id ]; + + } + + let uniforms; + + switch ( light.type ) { + + case 'DirectionalLight': + uniforms = { + direction: new Vector3(), + color: new Color() + }; + break; + + case 'SpotLight': + uniforms = { + position: new Vector3(), + direction: new Vector3(), + color: new Color(), + distance: 0, + coneCos: 0, + penumbraCos: 0, + decay: 0 + }; + break; + + case 'PointLight': + uniforms = { + position: new Vector3(), + color: new Color(), + distance: 0, + decay: 0 + }; + break; + + case 'HemisphereLight': + uniforms = { + direction: new Vector3(), + skyColor: new Color(), + groundColor: new Color() + }; + break; + + case 'RectAreaLight': + uniforms = { + color: new Color(), + position: new Vector3(), + halfWidth: new Vector3(), + halfHeight: new Vector3() + }; + break; + + } + + lights[ light.id ] = uniforms; + + return uniforms; + + } + + }; + +} + +function ShadowUniformsCache() { + + const lights = {}; + + return { + + get: function ( light ) { + + if ( lights[ light.id ] !== undefined ) { + + return lights[ light.id ]; + + } + + let uniforms; + + switch ( light.type ) { + + case 'DirectionalLight': + uniforms = { + shadowIntensity: 1, + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2() + }; + break; + + case 'SpotLight': + uniforms = { + shadowIntensity: 1, + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2() + }; + break; + + case 'PointLight': + uniforms = { + shadowIntensity: 1, + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2(), + shadowCameraNear: 1, + shadowCameraFar: 1000 + }; + break; + + // TODO (abelnation): set RectAreaLight shadow uniforms + + } + + lights[ light.id ] = uniforms; + + return uniforms; + + } + + }; + +} + + + +let nextVersion = 0; + +function shadowCastingAndTexturingLightsFirst( lightA, lightB ) { + + return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 ); + +} + +function WebGLLights( extensions ) { + + const cache = new UniformsCache(); + + const shadowCache = ShadowUniformsCache(); + + const state = { + + version: 0, + + hash: { + directionalLength: -1, + pointLength: -1, + spotLength: -1, + rectAreaLength: -1, + hemiLength: -1, + + numDirectionalShadows: -1, + numPointShadows: -1, + numSpotShadows: -1, + numSpotMaps: -1, + + numLightProbes: -1 + }, + + ambient: [ 0, 0, 0 ], + probe: [], + directional: [], + directionalShadow: [], + directionalShadowMap: [], + directionalShadowMatrix: [], + spot: [], + spotLightMap: [], + spotShadow: [], + spotShadowMap: [], + spotLightMatrix: [], + rectArea: [], + rectAreaLTC1: null, + rectAreaLTC2: null, + point: [], + pointShadow: [], + pointShadowMap: [], + pointShadowMatrix: [], + hemi: [], + numSpotLightShadowsWithMaps: 0, + numLightProbes: 0 + + }; + + for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() ); + + const vector3 = new Vector3(); + const matrix4 = new Matrix4(); + const matrix42 = new Matrix4(); + + function setup( lights ) { + + let r = 0, g = 0, b = 0; + + for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 ); + + let directionalLength = 0; + let pointLength = 0; + let spotLength = 0; + let rectAreaLength = 0; + let hemiLength = 0; + + let numDirectionalShadows = 0; + let numPointShadows = 0; + let numSpotShadows = 0; + let numSpotMaps = 0; + let numSpotShadowsWithMaps = 0; + + let numLightProbes = 0; + + // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ] + lights.sort( shadowCastingAndTexturingLightsFirst ); + + for ( let i = 0, l = lights.length; i < l; i ++ ) { + + const light = lights[ i ]; + + const color = light.color; + const intensity = light.intensity; + const distance = light.distance; + + const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null; + + if ( light.isAmbientLight ) { + + r += color.r * intensity; + g += color.g * intensity; + b += color.b * intensity; + + } else if ( light.isLightProbe ) { + + for ( let j = 0; j < 9; j ++ ) { + + state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity ); + + } + + numLightProbes ++; + + } else if ( light.isDirectionalLight ) { + + const uniforms = cache.get( light ); + + uniforms.color.copy( light.color ).multiplyScalar( light.intensity ); + + if ( light.castShadow ) { + + const shadow = light.shadow; + + const shadowUniforms = shadowCache.get( light ); + + shadowUniforms.shadowIntensity = shadow.intensity; + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + + state.directionalShadow[ directionalLength ] = shadowUniforms; + state.directionalShadowMap[ directionalLength ] = shadowMap; + state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix; + + numDirectionalShadows ++; + + } + + state.directional[ directionalLength ] = uniforms; + + directionalLength ++; + + } else if ( light.isSpotLight ) { + + const uniforms = cache.get( light ); + + uniforms.position.setFromMatrixPosition( light.matrixWorld ); + + uniforms.color.copy( color ).multiplyScalar( intensity ); + uniforms.distance = distance; + + uniforms.coneCos = Math.cos( light.angle ); + uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) ); + uniforms.decay = light.decay; + + state.spot[ spotLength ] = uniforms; + + const shadow = light.shadow; + + if ( light.map ) { + + state.spotLightMap[ numSpotMaps ] = light.map; + numSpotMaps ++; + + // make sure the lightMatrix is up to date + // TODO : do it if required only + shadow.updateMatrices( light ); + + if ( light.castShadow ) numSpotShadowsWithMaps ++; + + } + + state.spotLightMatrix[ spotLength ] = shadow.matrix; + + if ( light.castShadow ) { + + const shadowUniforms = shadowCache.get( light ); + + shadowUniforms.shadowIntensity = shadow.intensity; + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + + state.spotShadow[ spotLength ] = shadowUniforms; + state.spotShadowMap[ spotLength ] = shadowMap; + + numSpotShadows ++; + + } + + spotLength ++; + + } else if ( light.isRectAreaLight ) { + + const uniforms = cache.get( light ); + + uniforms.color.copy( color ).multiplyScalar( intensity ); + + uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 ); + uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 ); + + state.rectArea[ rectAreaLength ] = uniforms; + + rectAreaLength ++; + + } else if ( light.isPointLight ) { + + const uniforms = cache.get( light ); + + uniforms.color.copy( light.color ).multiplyScalar( light.intensity ); + uniforms.distance = light.distance; + uniforms.decay = light.decay; + + if ( light.castShadow ) { + + const shadow = light.shadow; + + const shadowUniforms = shadowCache.get( light ); + + shadowUniforms.shadowIntensity = shadow.intensity; + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + shadowUniforms.shadowCameraNear = shadow.camera.near; + shadowUniforms.shadowCameraFar = shadow.camera.far; + + state.pointShadow[ pointLength ] = shadowUniforms; + state.pointShadowMap[ pointLength ] = shadowMap; + state.pointShadowMatrix[ pointLength ] = light.shadow.matrix; + + numPointShadows ++; + + } + + state.point[ pointLength ] = uniforms; + + pointLength ++; + + } else if ( light.isHemisphereLight ) { + + const uniforms = cache.get( light ); + + uniforms.skyColor.copy( light.color ).multiplyScalar( intensity ); + uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity ); + + state.hemi[ hemiLength ] = uniforms; + + hemiLength ++; + + } + + } + + if ( rectAreaLength > 0 ) { + + if ( extensions.has( 'OES_texture_float_linear' ) === true ) { + + state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1; + state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2; + + } else { + + state.rectAreaLTC1 = UniformsLib.LTC_HALF_1; + state.rectAreaLTC2 = UniformsLib.LTC_HALF_2; + + } + + } + + state.ambient[ 0 ] = r; + state.ambient[ 1 ] = g; + state.ambient[ 2 ] = b; + + const hash = state.hash; + + if ( hash.directionalLength !== directionalLength || + hash.pointLength !== pointLength || + hash.spotLength !== spotLength || + hash.rectAreaLength !== rectAreaLength || + hash.hemiLength !== hemiLength || + hash.numDirectionalShadows !== numDirectionalShadows || + hash.numPointShadows !== numPointShadows || + hash.numSpotShadows !== numSpotShadows || + hash.numSpotMaps !== numSpotMaps || + hash.numLightProbes !== numLightProbes ) { + + state.directional.length = directionalLength; + state.spot.length = spotLength; + state.rectArea.length = rectAreaLength; + state.point.length = pointLength; + state.hemi.length = hemiLength; + + state.directionalShadow.length = numDirectionalShadows; + state.directionalShadowMap.length = numDirectionalShadows; + state.pointShadow.length = numPointShadows; + state.pointShadowMap.length = numPointShadows; + state.spotShadow.length = numSpotShadows; + state.spotShadowMap.length = numSpotShadows; + state.directionalShadowMatrix.length = numDirectionalShadows; + state.pointShadowMatrix.length = numPointShadows; + state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps; + state.spotLightMap.length = numSpotMaps; + state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps; + state.numLightProbes = numLightProbes; + + hash.directionalLength = directionalLength; + hash.pointLength = pointLength; + hash.spotLength = spotLength; + hash.rectAreaLength = rectAreaLength; + hash.hemiLength = hemiLength; + + hash.numDirectionalShadows = numDirectionalShadows; + hash.numPointShadows = numPointShadows; + hash.numSpotShadows = numSpotShadows; + hash.numSpotMaps = numSpotMaps; + + hash.numLightProbes = numLightProbes; + + state.version = nextVersion ++; + + } + + } + + function setupView( lights, camera ) { + + let directionalLength = 0; + let pointLength = 0; + let spotLength = 0; + let rectAreaLength = 0; + let hemiLength = 0; + + const viewMatrix = camera.matrixWorldInverse; + + for ( let i = 0, l = lights.length; i < l; i ++ ) { + + const light = lights[ i ]; + + if ( light.isDirectionalLight ) { + + const uniforms = state.directional[ directionalLength ]; + + uniforms.direction.setFromMatrixPosition( light.matrixWorld ); + vector3.setFromMatrixPosition( light.target.matrixWorld ); + uniforms.direction.sub( vector3 ); + uniforms.direction.transformDirection( viewMatrix ); + + directionalLength ++; + + } else if ( light.isSpotLight ) { + + const uniforms = state.spot[ spotLength ]; + + uniforms.position.setFromMatrixPosition( light.matrixWorld ); + uniforms.position.applyMatrix4( viewMatrix ); + + uniforms.direction.setFromMatrixPosition( light.matrixWorld ); + vector3.setFromMatrixPosition( light.target.matrixWorld ); + uniforms.direction.sub( vector3 ); + uniforms.direction.transformDirection( viewMatrix ); + + spotLength ++; + + } else if ( light.isRectAreaLight ) { + + const uniforms = state.rectArea[ rectAreaLength ]; + + uniforms.position.setFromMatrixPosition( light.matrixWorld ); + uniforms.position.applyMatrix4( viewMatrix ); + + // extract local rotation of light to derive width/height half vectors + matrix42.identity(); + matrix4.copy( light.matrixWorld ); + matrix4.premultiply( viewMatrix ); + matrix42.extractRotation( matrix4 ); + + uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 ); + uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 ); + + uniforms.halfWidth.applyMatrix4( matrix42 ); + uniforms.halfHeight.applyMatrix4( matrix42 ); + + rectAreaLength ++; + + } else if ( light.isPointLight ) { + + const uniforms = state.point[ pointLength ]; + + uniforms.position.setFromMatrixPosition( light.matrixWorld ); + uniforms.position.applyMatrix4( viewMatrix ); + + pointLength ++; + + } else if ( light.isHemisphereLight ) { + + const uniforms = state.hemi[ hemiLength ]; + + uniforms.direction.setFromMatrixPosition( light.matrixWorld ); + uniforms.direction.transformDirection( viewMatrix ); + + hemiLength ++; + + } + + } + + } + + return { + setup: setup, + setupView: setupView, + state: state + }; + +} + +function WebGLRenderState( extensions ) { + + const lights = new WebGLLights( extensions ); + + const lightsArray = []; + const shadowsArray = []; + + function init( camera ) { + + state.camera = camera; + + lightsArray.length = 0; + shadowsArray.length = 0; + + } + + function pushLight( light ) { + + lightsArray.push( light ); + + } + + function pushShadow( shadowLight ) { + + shadowsArray.push( shadowLight ); + + } + + function setupLights() { + + lights.setup( lightsArray ); + + } + + function setupLightsView( camera ) { + + lights.setupView( lightsArray, camera ); + + } + + const state = { + lightsArray: lightsArray, + shadowsArray: shadowsArray, + + camera: null, + + lights: lights, + + transmissionRenderTarget: {} + }; + + return { + init: init, + state: state, + setupLights: setupLights, + setupLightsView: setupLightsView, + + pushLight: pushLight, + pushShadow: pushShadow + }; + +} + +function WebGLRenderStates( extensions ) { + + let renderStates = new WeakMap(); + + function get( scene, renderCallDepth = 0 ) { + + const renderStateArray = renderStates.get( scene ); + let renderState; + + if ( renderStateArray === undefined ) { + + renderState = new WebGLRenderState( extensions ); + renderStates.set( scene, [ renderState ] ); + + } else { + + if ( renderCallDepth >= renderStateArray.length ) { + + renderState = new WebGLRenderState( extensions ); + renderStateArray.push( renderState ); + + } else { + + renderState = renderStateArray[ renderCallDepth ]; + + } + + } + + return renderState; + + } + + function dispose() { + + renderStates = new WeakMap(); + + } + + return { + get: get, + dispose: dispose + }; + +} + +const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}"; + +const fragment = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include \nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}"; + +function WebGLShadowMap( renderer, objects, capabilities ) { + + let _frustum = new Frustum(); + + const _shadowMapSize = new Vector2(), + _viewportSize = new Vector2(), + + _viewport = new Vector4(), + + _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ), + _distanceMaterial = new MeshDistanceMaterial(), + + _materialCache = {}, + + _maxTextureSize = capabilities.maxTextureSize; + + const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide }; + + const shadowMaterialVertical = new ShaderMaterial( { + defines: { + VSM_SAMPLES: 8 + }, + uniforms: { + shadow_pass: { value: null }, + resolution: { value: new Vector2() }, + radius: { value: 4.0 } + }, + + vertexShader: vertex, + fragmentShader: fragment + + } ); + + const shadowMaterialHorizontal = shadowMaterialVertical.clone(); + shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1; + + const fullScreenTri = new BufferGeometry(); + fullScreenTri.setAttribute( + 'position', + new BufferAttribute( + new Float32Array( [ -1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5 ] ), + 3 + ) + ); + + const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical ); + + const scope = this; + + this.enabled = false; + + this.autoUpdate = true; + this.needsUpdate = false; + + this.type = PCFShadowMap; + let _previousType = this.type; + + this.render = function ( lights, scene, camera ) { + + if ( scope.enabled === false ) return; + if ( scope.autoUpdate === false && scope.needsUpdate === false ) return; + + if ( lights.length === 0 ) return; + + const currentRenderTarget = renderer.getRenderTarget(); + const activeCubeFace = renderer.getActiveCubeFace(); + const activeMipmapLevel = renderer.getActiveMipmapLevel(); + + const _state = renderer.state; + + // Set GL state for depth map. + _state.setBlending( NoBlending ); + _state.buffers.color.setClear( 1, 1, 1, 1 ); + _state.buffers.depth.setTest( true ); + _state.setScissorTest( false ); + + // check for shadow map type changes + + const toVSM = ( _previousType !== VSMShadowMap && this.type === VSMShadowMap ); + const fromVSM = ( _previousType === VSMShadowMap && this.type !== VSMShadowMap ); + + // render depth map + + for ( let i = 0, il = lights.length; i < il; i ++ ) { + + const light = lights[ i ]; + const shadow = light.shadow; + + if ( shadow === undefined ) { + + console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' ); + continue; + + } + + if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue; + + _shadowMapSize.copy( shadow.mapSize ); + + const shadowFrameExtents = shadow.getFrameExtents(); + + _shadowMapSize.multiply( shadowFrameExtents ); + + _viewportSize.copy( shadow.mapSize ); + + if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) { + + if ( _shadowMapSize.x > _maxTextureSize ) { + + _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x ); + _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x; + shadow.mapSize.x = _viewportSize.x; + + } + + if ( _shadowMapSize.y > _maxTextureSize ) { + + _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y ); + _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y; + shadow.mapSize.y = _viewportSize.y; + + } + + } + + if ( shadow.map === null || toVSM === true || fromVSM === true ) { + + const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {}; + + if ( shadow.map !== null ) { + + shadow.map.dispose(); + + } + + shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars ); + shadow.map.texture.name = light.name + '.shadowMap'; + + shadow.camera.updateProjectionMatrix(); + + } + + renderer.setRenderTarget( shadow.map ); + renderer.clear(); + + const viewportCount = shadow.getViewportCount(); + + for ( let vp = 0; vp < viewportCount; vp ++ ) { + + const viewport = shadow.getViewport( vp ); + + _viewport.set( + _viewportSize.x * viewport.x, + _viewportSize.y * viewport.y, + _viewportSize.x * viewport.z, + _viewportSize.y * viewport.w + ); + + _state.viewport( _viewport ); + + shadow.updateMatrices( light, vp ); + + _frustum = shadow.getFrustum(); + + renderObject( scene, camera, shadow.camera, light, this.type ); + + } + + // do blur pass for VSM + + if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) { + + VSMPass( shadow, camera ); + + } + + shadow.needsUpdate = false; + + } + + _previousType = this.type; + + scope.needsUpdate = false; + + renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel ); + + }; + + function VSMPass( shadow, camera ) { + + const geometry = objects.update( fullScreenMesh ); + + if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) { + + shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples; + shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples; + + shadowMaterialVertical.needsUpdate = true; + shadowMaterialHorizontal.needsUpdate = true; + + } + + if ( shadow.mapPass === null ) { + + shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y ); + + } + + // vertical pass + + shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture; + shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize; + shadowMaterialVertical.uniforms.radius.value = shadow.radius; + renderer.setRenderTarget( shadow.mapPass ); + renderer.clear(); + renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null ); + + // horizontal pass + + shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture; + shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize; + shadowMaterialHorizontal.uniforms.radius.value = shadow.radius; + renderer.setRenderTarget( shadow.map ); + renderer.clear(); + renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null ); + + } + + function getDepthMaterial( object, material, light, type ) { + + let result = null; + + const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial; + + if ( customMaterial !== undefined ) { + + result = customMaterial; + + } else { + + result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial; + + if ( ( renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) || + ( material.displacementMap && material.displacementScale !== 0 ) || + ( material.alphaMap && material.alphaTest > 0 ) || + ( material.map && material.alphaTest > 0 ) || + ( material.alphaToCoverage === true ) ) { + + // in this case we need a unique material instance reflecting the + // appropriate state + + const keyA = result.uuid, keyB = material.uuid; + + let materialsForVariant = _materialCache[ keyA ]; + + if ( materialsForVariant === undefined ) { + + materialsForVariant = {}; + _materialCache[ keyA ] = materialsForVariant; + + } + + let cachedMaterial = materialsForVariant[ keyB ]; + + if ( cachedMaterial === undefined ) { + + cachedMaterial = result.clone(); + materialsForVariant[ keyB ] = cachedMaterial; + material.addEventListener( 'dispose', onMaterialDispose ); + + } + + result = cachedMaterial; + + } + + } + + result.visible = material.visible; + result.wireframe = material.wireframe; + + if ( type === VSMShadowMap ) { + + result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side; + + } else { + + result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ]; + + } + + result.alphaMap = material.alphaMap; + result.alphaTest = ( material.alphaToCoverage === true ) ? 0.5 : material.alphaTest; // approximate alphaToCoverage by using a fixed alphaTest value + result.map = material.map; + + result.clipShadows = material.clipShadows; + result.clippingPlanes = material.clippingPlanes; + result.clipIntersection = material.clipIntersection; + + result.displacementMap = material.displacementMap; + result.displacementScale = material.displacementScale; + result.displacementBias = material.displacementBias; + + result.wireframeLinewidth = material.wireframeLinewidth; + result.linewidth = material.linewidth; + + if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) { + + const materialProperties = renderer.properties.get( result ); + materialProperties.light = light; + + } + + return result; + + } + + function renderObject( object, camera, shadowCamera, light, type ) { + + if ( object.visible === false ) return; + + const visible = object.layers.test( camera.layers ); + + if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) { + + if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) { + + object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld ); + + const geometry = objects.update( object ); + const material = object.material; + + if ( Array.isArray( material ) ) { + + const groups = geometry.groups; + + for ( let k = 0, kl = groups.length; k < kl; k ++ ) { + + const group = groups[ k ]; + const groupMaterial = material[ group.materialIndex ]; + + if ( groupMaterial && groupMaterial.visible ) { + + const depthMaterial = getDepthMaterial( object, groupMaterial, light, type ); + + object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group ); + + renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group ); + + object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group ); + + } + + } + + } else if ( material.visible ) { + + const depthMaterial = getDepthMaterial( object, material, light, type ); + + object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null ); + + renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null ); + + object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null ); + + } + + } + + } + + const children = object.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + renderObject( children[ i ], camera, shadowCamera, light, type ); + + } + + } + + function onMaterialDispose( event ) { + + const material = event.target; + + material.removeEventListener( 'dispose', onMaterialDispose ); + + // make sure to remove the unique distance/depth materials used for shadow map rendering + + for ( const id in _materialCache ) { + + const cache = _materialCache[ id ]; + + const uuid = event.target.uuid; + + if ( uuid in cache ) { + + const shadowMaterial = cache[ uuid ]; + shadowMaterial.dispose(); + delete cache[ uuid ]; + + } + + } + + } + +} + +const reversedFuncs = { + [ NeverDepth ]: AlwaysDepth, + [ LessDepth ]: GreaterDepth, + [ EqualDepth ]: NotEqualDepth, + [ LessEqualDepth ]: GreaterEqualDepth, + + [ AlwaysDepth ]: NeverDepth, + [ GreaterDepth ]: LessDepth, + [ NotEqualDepth ]: EqualDepth, + [ GreaterEqualDepth ]: LessEqualDepth, +}; + +function WebGLState( gl, extensions ) { + + function ColorBuffer() { + + let locked = false; + + const color = new Vector4(); + let currentColorMask = null; + const currentColorClear = new Vector4( 0, 0, 0, 0 ); + + return { + + setMask: function ( colorMask ) { + + if ( currentColorMask !== colorMask && ! locked ) { + + gl.colorMask( colorMask, colorMask, colorMask, colorMask ); + currentColorMask = colorMask; + + } + + }, + + setLocked: function ( lock ) { + + locked = lock; + + }, + + setClear: function ( r, g, b, a, premultipliedAlpha ) { + + if ( premultipliedAlpha === true ) { + + r *= a; g *= a; b *= a; + + } + + color.set( r, g, b, a ); + + if ( currentColorClear.equals( color ) === false ) { + + gl.clearColor( r, g, b, a ); + currentColorClear.copy( color ); + + } + + }, + + reset: function () { + + locked = false; + + currentColorMask = null; + currentColorClear.set( -1, 0, 0, 0 ); // set to invalid state + + } + + }; + + } + + function DepthBuffer() { + + let locked = false; + + let currentReversed = false; + let currentDepthMask = null; + let currentDepthFunc = null; + let currentDepthClear = null; + + return { + + setReversed: function ( reversed ) { + + if ( currentReversed !== reversed ) { + + const ext = extensions.get( 'EXT_clip_control' ); + + if ( reversed ) { + + ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.ZERO_TO_ONE_EXT ); + + } else { + + ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.NEGATIVE_ONE_TO_ONE_EXT ); + + } + + currentReversed = reversed; + + const oldDepth = currentDepthClear; + currentDepthClear = null; + this.setClear( oldDepth ); + + } + + }, + + getReversed: function () { + + return currentReversed; + + }, + + setTest: function ( depthTest ) { + + if ( depthTest ) { + + enable( gl.DEPTH_TEST ); + + } else { + + disable( gl.DEPTH_TEST ); + + } + + }, + + setMask: function ( depthMask ) { + + if ( currentDepthMask !== depthMask && ! locked ) { + + gl.depthMask( depthMask ); + currentDepthMask = depthMask; + + } + + }, + + setFunc: function ( depthFunc ) { + + if ( currentReversed ) depthFunc = reversedFuncs[ depthFunc ]; + + if ( currentDepthFunc !== depthFunc ) { + + switch ( depthFunc ) { + + case NeverDepth: + + gl.depthFunc( gl.NEVER ); + break; + + case AlwaysDepth: + + gl.depthFunc( gl.ALWAYS ); + break; + + case LessDepth: + + gl.depthFunc( gl.LESS ); + break; + + case LessEqualDepth: + + gl.depthFunc( gl.LEQUAL ); + break; + + case EqualDepth: + + gl.depthFunc( gl.EQUAL ); + break; + + case GreaterEqualDepth: + + gl.depthFunc( gl.GEQUAL ); + break; + + case GreaterDepth: + + gl.depthFunc( gl.GREATER ); + break; + + case NotEqualDepth: + + gl.depthFunc( gl.NOTEQUAL ); + break; + + default: + + gl.depthFunc( gl.LEQUAL ); + + } + + currentDepthFunc = depthFunc; + + } + + }, + + setLocked: function ( lock ) { + + locked = lock; + + }, + + setClear: function ( depth ) { + + if ( currentDepthClear !== depth ) { + + if ( currentReversed ) { + + depth = 1 - depth; + + } + + gl.clearDepth( depth ); + currentDepthClear = depth; + + } + + }, + + reset: function () { + + locked = false; + + currentDepthMask = null; + currentDepthFunc = null; + currentDepthClear = null; + currentReversed = false; + + } + + }; + + } + + function StencilBuffer() { + + let locked = false; + + let currentStencilMask = null; + let currentStencilFunc = null; + let currentStencilRef = null; + let currentStencilFuncMask = null; + let currentStencilFail = null; + let currentStencilZFail = null; + let currentStencilZPass = null; + let currentStencilClear = null; + + return { + + setTest: function ( stencilTest ) { + + if ( ! locked ) { + + if ( stencilTest ) { + + enable( gl.STENCIL_TEST ); + + } else { + + disable( gl.STENCIL_TEST ); + + } + + } + + }, + + setMask: function ( stencilMask ) { + + if ( currentStencilMask !== stencilMask && ! locked ) { + + gl.stencilMask( stencilMask ); + currentStencilMask = stencilMask; + + } + + }, + + setFunc: function ( stencilFunc, stencilRef, stencilMask ) { + + if ( currentStencilFunc !== stencilFunc || + currentStencilRef !== stencilRef || + currentStencilFuncMask !== stencilMask ) { + + gl.stencilFunc( stencilFunc, stencilRef, stencilMask ); + + currentStencilFunc = stencilFunc; + currentStencilRef = stencilRef; + currentStencilFuncMask = stencilMask; + + } + + }, + + setOp: function ( stencilFail, stencilZFail, stencilZPass ) { + + if ( currentStencilFail !== stencilFail || + currentStencilZFail !== stencilZFail || + currentStencilZPass !== stencilZPass ) { + + gl.stencilOp( stencilFail, stencilZFail, stencilZPass ); + + currentStencilFail = stencilFail; + currentStencilZFail = stencilZFail; + currentStencilZPass = stencilZPass; + + } + + }, + + setLocked: function ( lock ) { + + locked = lock; + + }, + + setClear: function ( stencil ) { + + if ( currentStencilClear !== stencil ) { + + gl.clearStencil( stencil ); + currentStencilClear = stencil; + + } + + }, + + reset: function () { + + locked = false; + + currentStencilMask = null; + currentStencilFunc = null; + currentStencilRef = null; + currentStencilFuncMask = null; + currentStencilFail = null; + currentStencilZFail = null; + currentStencilZPass = null; + currentStencilClear = null; + + } + + }; + + } + + // + + const colorBuffer = new ColorBuffer(); + const depthBuffer = new DepthBuffer(); + const stencilBuffer = new StencilBuffer(); + + const uboBindings = new WeakMap(); + const uboProgramMap = new WeakMap(); + + let enabledCapabilities = {}; + + let currentBoundFramebuffers = {}; + let currentDrawbuffers = new WeakMap(); + let defaultDrawbuffers = []; + + let currentProgram = null; + + let currentBlendingEnabled = false; + let currentBlending = null; + let currentBlendEquation = null; + let currentBlendSrc = null; + let currentBlendDst = null; + let currentBlendEquationAlpha = null; + let currentBlendSrcAlpha = null; + let currentBlendDstAlpha = null; + let currentBlendColor = new Color( 0, 0, 0 ); + let currentBlendAlpha = 0; + let currentPremultipledAlpha = false; + + let currentFlipSided = null; + let currentCullFace = null; + + let currentLineWidth = null; + + let currentPolygonOffsetFactor = null; + let currentPolygonOffsetUnits = null; + + const maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS ); + + let lineWidthAvailable = false; + let version = 0; + const glVersion = gl.getParameter( gl.VERSION ); + + if ( glVersion.indexOf( 'WebGL' ) !== -1 ) { + + version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] ); + lineWidthAvailable = ( version >= 1.0 ); + + } else if ( glVersion.indexOf( 'OpenGL ES' ) !== -1 ) { + + version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] ); + lineWidthAvailable = ( version >= 2.0 ); + + } + + let currentTextureSlot = null; + let currentBoundTextures = {}; + + const scissorParam = gl.getParameter( gl.SCISSOR_BOX ); + const viewportParam = gl.getParameter( gl.VIEWPORT ); + + const currentScissor = new Vector4().fromArray( scissorParam ); + const currentViewport = new Vector4().fromArray( viewportParam ); + + function createTexture( type, target, count, dimensions ) { + + const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4. + const texture = gl.createTexture(); + + gl.bindTexture( type, texture ); + gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST ); + gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST ); + + for ( let i = 0; i < count; i ++ ) { + + if ( type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY ) { + + gl.texImage3D( target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data ); + + } else { + + gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data ); + + } + + } + + return texture; + + } + + const emptyTextures = {}; + emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 ); + emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 ); + emptyTextures[ gl.TEXTURE_2D_ARRAY ] = createTexture( gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1 ); + emptyTextures[ gl.TEXTURE_3D ] = createTexture( gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1 ); + + // init + + colorBuffer.setClear( 0, 0, 0, 1 ); + depthBuffer.setClear( 1 ); + stencilBuffer.setClear( 0 ); + + enable( gl.DEPTH_TEST ); + depthBuffer.setFunc( LessEqualDepth ); + + setFlipSided( false ); + setCullFace( CullFaceBack ); + enable( gl.CULL_FACE ); + + setBlending( NoBlending ); + + // + + function enable( id ) { + + if ( enabledCapabilities[ id ] !== true ) { + + gl.enable( id ); + enabledCapabilities[ id ] = true; + + } + + } + + function disable( id ) { + + if ( enabledCapabilities[ id ] !== false ) { + + gl.disable( id ); + enabledCapabilities[ id ] = false; + + } + + } + + function bindFramebuffer( target, framebuffer ) { + + if ( currentBoundFramebuffers[ target ] !== framebuffer ) { + + gl.bindFramebuffer( target, framebuffer ); + + currentBoundFramebuffers[ target ] = framebuffer; + + // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER + + if ( target === gl.DRAW_FRAMEBUFFER ) { + + currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer; + + } + + if ( target === gl.FRAMEBUFFER ) { + + currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer; + + } + + return true; + + } + + return false; + + } + + function drawBuffers( renderTarget, framebuffer ) { + + let drawBuffers = defaultDrawbuffers; + + let needsUpdate = false; + + if ( renderTarget ) { + + drawBuffers = currentDrawbuffers.get( framebuffer ); + + if ( drawBuffers === undefined ) { + + drawBuffers = []; + currentDrawbuffers.set( framebuffer, drawBuffers ); + + } + + const textures = renderTarget.textures; + + if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) { + + for ( let i = 0, il = textures.length; i < il; i ++ ) { + + drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i; + + } + + drawBuffers.length = textures.length; + + needsUpdate = true; + + } + + } else { + + if ( drawBuffers[ 0 ] !== gl.BACK ) { + + drawBuffers[ 0 ] = gl.BACK; + + needsUpdate = true; + + } + + } + + if ( needsUpdate ) { + + gl.drawBuffers( drawBuffers ); + + } + + } + + function useProgram( program ) { + + if ( currentProgram !== program ) { + + gl.useProgram( program ); + + currentProgram = program; + + return true; + + } + + return false; + + } + + const equationToGL = { + [ AddEquation ]: gl.FUNC_ADD, + [ SubtractEquation ]: gl.FUNC_SUBTRACT, + [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT + }; + + equationToGL[ MinEquation ] = gl.MIN; + equationToGL[ MaxEquation ] = gl.MAX; + + const factorToGL = { + [ ZeroFactor ]: gl.ZERO, + [ OneFactor ]: gl.ONE, + [ SrcColorFactor ]: gl.SRC_COLOR, + [ SrcAlphaFactor ]: gl.SRC_ALPHA, + [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE, + [ DstColorFactor ]: gl.DST_COLOR, + [ DstAlphaFactor ]: gl.DST_ALPHA, + [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR, + [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA, + [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR, + [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA, + [ ConstantColorFactor ]: gl.CONSTANT_COLOR, + [ OneMinusConstantColorFactor ]: gl.ONE_MINUS_CONSTANT_COLOR, + [ ConstantAlphaFactor ]: gl.CONSTANT_ALPHA, + [ OneMinusConstantAlphaFactor ]: gl.ONE_MINUS_CONSTANT_ALPHA + }; + + function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, blendColor, blendAlpha, premultipliedAlpha ) { + + if ( blending === NoBlending ) { + + if ( currentBlendingEnabled === true ) { + + disable( gl.BLEND ); + currentBlendingEnabled = false; + + } + + return; + + } + + if ( currentBlendingEnabled === false ) { + + enable( gl.BLEND ); + currentBlendingEnabled = true; + + } + + if ( blending !== CustomBlending ) { + + if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) { + + if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) { + + gl.blendEquation( gl.FUNC_ADD ); + + currentBlendEquation = AddEquation; + currentBlendEquationAlpha = AddEquation; + + } + + if ( premultipliedAlpha ) { + + switch ( blending ) { + + case NormalBlending: + gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); + break; + + case AdditiveBlending: + gl.blendFunc( gl.ONE, gl.ONE ); + break; + + case SubtractiveBlending: + gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE ); + break; + + case MultiplyBlending: + gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA ); + break; + + default: + console.error( 'THREE.WebGLState: Invalid blending: ', blending ); + break; + + } + + } else { + + switch ( blending ) { + + case NormalBlending: + gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); + break; + + case AdditiveBlending: + gl.blendFunc( gl.SRC_ALPHA, gl.ONE ); + break; + + case SubtractiveBlending: + gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE ); + break; + + case MultiplyBlending: + gl.blendFunc( gl.ZERO, gl.SRC_COLOR ); + break; + + default: + console.error( 'THREE.WebGLState: Invalid blending: ', blending ); + break; + + } + + } + + currentBlendSrc = null; + currentBlendDst = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; + currentBlendColor.set( 0, 0, 0 ); + currentBlendAlpha = 0; + + currentBlending = blending; + currentPremultipledAlpha = premultipliedAlpha; + + } + + return; + + } + + // custom blending + + blendEquationAlpha = blendEquationAlpha || blendEquation; + blendSrcAlpha = blendSrcAlpha || blendSrc; + blendDstAlpha = blendDstAlpha || blendDst; + + if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) { + + gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] ); + + currentBlendEquation = blendEquation; + currentBlendEquationAlpha = blendEquationAlpha; + + } + + if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) { + + gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] ); + + currentBlendSrc = blendSrc; + currentBlendDst = blendDst; + currentBlendSrcAlpha = blendSrcAlpha; + currentBlendDstAlpha = blendDstAlpha; + + } + + if ( blendColor.equals( currentBlendColor ) === false || blendAlpha !== currentBlendAlpha ) { + + gl.blendColor( blendColor.r, blendColor.g, blendColor.b, blendAlpha ); + + currentBlendColor.copy( blendColor ); + currentBlendAlpha = blendAlpha; + + } + + currentBlending = blending; + currentPremultipledAlpha = false; + + } + + function setMaterial( material, frontFaceCW ) { + + material.side === DoubleSide + ? disable( gl.CULL_FACE ) + : enable( gl.CULL_FACE ); + + let flipSided = ( material.side === BackSide ); + if ( frontFaceCW ) flipSided = ! flipSided; + + setFlipSided( flipSided ); + + ( material.blending === NormalBlending && material.transparent === false ) + ? setBlending( NoBlending ) + : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.blendColor, material.blendAlpha, material.premultipliedAlpha ); + + depthBuffer.setFunc( material.depthFunc ); + depthBuffer.setTest( material.depthTest ); + depthBuffer.setMask( material.depthWrite ); + colorBuffer.setMask( material.colorWrite ); + + const stencilWrite = material.stencilWrite; + stencilBuffer.setTest( stencilWrite ); + if ( stencilWrite ) { + + stencilBuffer.setMask( material.stencilWriteMask ); + stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask ); + stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass ); + + } + + setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); + + material.alphaToCoverage === true + ? enable( gl.SAMPLE_ALPHA_TO_COVERAGE ) + : disable( gl.SAMPLE_ALPHA_TO_COVERAGE ); + + } + + // + + function setFlipSided( flipSided ) { + + if ( currentFlipSided !== flipSided ) { + + if ( flipSided ) { + + gl.frontFace( gl.CW ); + + } else { + + gl.frontFace( gl.CCW ); + + } + + currentFlipSided = flipSided; + + } + + } + + function setCullFace( cullFace ) { + + if ( cullFace !== CullFaceNone ) { + + enable( gl.CULL_FACE ); + + if ( cullFace !== currentCullFace ) { + + if ( cullFace === CullFaceBack ) { + + gl.cullFace( gl.BACK ); + + } else if ( cullFace === CullFaceFront ) { + + gl.cullFace( gl.FRONT ); + + } else { + + gl.cullFace( gl.FRONT_AND_BACK ); + + } + + } + + } else { + + disable( gl.CULL_FACE ); + + } + + currentCullFace = cullFace; + + } + + function setLineWidth( width ) { + + if ( width !== currentLineWidth ) { + + if ( lineWidthAvailable ) gl.lineWidth( width ); + + currentLineWidth = width; + + } + + } + + function setPolygonOffset( polygonOffset, factor, units ) { + + if ( polygonOffset ) { + + enable( gl.POLYGON_OFFSET_FILL ); + + if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) { + + gl.polygonOffset( factor, units ); + + currentPolygonOffsetFactor = factor; + currentPolygonOffsetUnits = units; + + } + + } else { + + disable( gl.POLYGON_OFFSET_FILL ); + + } + + } + + function setScissorTest( scissorTest ) { + + if ( scissorTest ) { + + enable( gl.SCISSOR_TEST ); + + } else { + + disable( gl.SCISSOR_TEST ); + + } + + } + + // texture + + function activeTexture( webglSlot ) { + + if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1; + + if ( currentTextureSlot !== webglSlot ) { + + gl.activeTexture( webglSlot ); + currentTextureSlot = webglSlot; + + } + + } + + function bindTexture( webglType, webglTexture, webglSlot ) { + + if ( webglSlot === undefined ) { + + if ( currentTextureSlot === null ) { + + webglSlot = gl.TEXTURE0 + maxTextures - 1; + + } else { + + webglSlot = currentTextureSlot; + + } + + } + + let boundTexture = currentBoundTextures[ webglSlot ]; + + if ( boundTexture === undefined ) { + + boundTexture = { type: undefined, texture: undefined }; + currentBoundTextures[ webglSlot ] = boundTexture; + + } + + if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) { + + if ( currentTextureSlot !== webglSlot ) { + + gl.activeTexture( webglSlot ); + currentTextureSlot = webglSlot; + + } + + gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] ); + + boundTexture.type = webglType; + boundTexture.texture = webglTexture; + + } + + } + + function unbindTexture() { + + const boundTexture = currentBoundTextures[ currentTextureSlot ]; + + if ( boundTexture !== undefined && boundTexture.type !== undefined ) { + + gl.bindTexture( boundTexture.type, null ); + + boundTexture.type = undefined; + boundTexture.texture = undefined; + + } + + } + + function compressedTexImage2D() { + + try { + + gl.compressedTexImage2D( ...arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function compressedTexImage3D() { + + try { + + gl.compressedTexImage3D( ...arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function texSubImage2D() { + + try { + + gl.texSubImage2D( ...arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function texSubImage3D() { + + try { + + gl.texSubImage3D( ...arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function compressedTexSubImage2D() { + + try { + + gl.compressedTexSubImage2D( ...arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function compressedTexSubImage3D() { + + try { + + gl.compressedTexSubImage3D( ...arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function texStorage2D() { + + try { + + gl.texStorage2D( ...arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function texStorage3D() { + + try { + + gl.texStorage3D( ...arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function texImage2D() { + + try { + + gl.texImage2D( ...arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + function texImage3D() { + + try { + + gl.texImage3D( ...arguments ); + + } catch ( error ) { + + console.error( 'THREE.WebGLState:', error ); + + } + + } + + // + + function scissor( scissor ) { + + if ( currentScissor.equals( scissor ) === false ) { + + gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w ); + currentScissor.copy( scissor ); + + } + + } + + function viewport( viewport ) { + + if ( currentViewport.equals( viewport ) === false ) { + + gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w ); + currentViewport.copy( viewport ); + + } + + } + + function updateUBOMapping( uniformsGroup, program ) { + + let mapping = uboProgramMap.get( program ); + + if ( mapping === undefined ) { + + mapping = new WeakMap(); + + uboProgramMap.set( program, mapping ); + + } + + let blockIndex = mapping.get( uniformsGroup ); + + if ( blockIndex === undefined ) { + + blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name ); + + mapping.set( uniformsGroup, blockIndex ); + + } + + } + + function uniformBlockBinding( uniformsGroup, program ) { + + const mapping = uboProgramMap.get( program ); + const blockIndex = mapping.get( uniformsGroup ); + + if ( uboBindings.get( program ) !== blockIndex ) { + + // bind shader specific block index to global block point + gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex ); + + uboBindings.set( program, blockIndex ); + + } + + } + + // + + function reset() { + + // reset state + + gl.disable( gl.BLEND ); + gl.disable( gl.CULL_FACE ); + gl.disable( gl.DEPTH_TEST ); + gl.disable( gl.POLYGON_OFFSET_FILL ); + gl.disable( gl.SCISSOR_TEST ); + gl.disable( gl.STENCIL_TEST ); + gl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE ); + + gl.blendEquation( gl.FUNC_ADD ); + gl.blendFunc( gl.ONE, gl.ZERO ); + gl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO ); + gl.blendColor( 0, 0, 0, 0 ); + + gl.colorMask( true, true, true, true ); + gl.clearColor( 0, 0, 0, 0 ); + + gl.depthMask( true ); + gl.depthFunc( gl.LESS ); + + depthBuffer.setReversed( false ); + + gl.clearDepth( 1 ); + + gl.stencilMask( 0xffffffff ); + gl.stencilFunc( gl.ALWAYS, 0, 0xffffffff ); + gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP ); + gl.clearStencil( 0 ); + + gl.cullFace( gl.BACK ); + gl.frontFace( gl.CCW ); + + gl.polygonOffset( 0, 0 ); + + gl.activeTexture( gl.TEXTURE0 ); + + gl.bindFramebuffer( gl.FRAMEBUFFER, null ); + gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null ); + gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null ); + + gl.useProgram( null ); + + gl.lineWidth( 1 ); + + gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height ); + gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height ); + + // reset internals + + enabledCapabilities = {}; + + currentTextureSlot = null; + currentBoundTextures = {}; + + currentBoundFramebuffers = {}; + currentDrawbuffers = new WeakMap(); + defaultDrawbuffers = []; + + currentProgram = null; + + currentBlendingEnabled = false; + currentBlending = null; + currentBlendEquation = null; + currentBlendSrc = null; + currentBlendDst = null; + currentBlendEquationAlpha = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; + currentBlendColor = new Color( 0, 0, 0 ); + currentBlendAlpha = 0; + currentPremultipledAlpha = false; + + currentFlipSided = null; + currentCullFace = null; + + currentLineWidth = null; + + currentPolygonOffsetFactor = null; + currentPolygonOffsetUnits = null; + + currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height ); + currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height ); + + colorBuffer.reset(); + depthBuffer.reset(); + stencilBuffer.reset(); + + } + + return { + + buffers: { + color: colorBuffer, + depth: depthBuffer, + stencil: stencilBuffer + }, + + enable: enable, + disable: disable, + + bindFramebuffer: bindFramebuffer, + drawBuffers: drawBuffers, + + useProgram: useProgram, + + setBlending: setBlending, + setMaterial: setMaterial, + + setFlipSided: setFlipSided, + setCullFace: setCullFace, + + setLineWidth: setLineWidth, + setPolygonOffset: setPolygonOffset, + + setScissorTest: setScissorTest, + + activeTexture: activeTexture, + bindTexture: bindTexture, + unbindTexture: unbindTexture, + compressedTexImage2D: compressedTexImage2D, + compressedTexImage3D: compressedTexImage3D, + texImage2D: texImage2D, + texImage3D: texImage3D, + + updateUBOMapping: updateUBOMapping, + uniformBlockBinding: uniformBlockBinding, + + texStorage2D: texStorage2D, + texStorage3D: texStorage3D, + texSubImage2D: texSubImage2D, + texSubImage3D: texSubImage3D, + compressedTexSubImage2D: compressedTexSubImage2D, + compressedTexSubImage3D: compressedTexSubImage3D, + + scissor: scissor, + viewport: viewport, + + reset: reset + + }; + +} + +function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) { + + const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null; + const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent ); + + const _imageDimensions = new Vector2(); + const _videoTextures = new WeakMap(); + let _canvas; + + const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source + + // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas, + // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")! + // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d). + + let useOffscreenCanvas = false; + + try { + + useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' + // eslint-disable-next-line compat/compat + && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null; + + } catch ( err ) { + + // Ignore any errors + + } + + function createCanvas( width, height ) { + + // Use OffscreenCanvas when available. Specially needed in web workers + + return useOffscreenCanvas ? + // eslint-disable-next-line compat/compat + new OffscreenCanvas( width, height ) : createElementNS( 'canvas' ); + + } + + function resizeImage( image, needsNewCanvas, maxSize ) { + + let scale = 1; + + const dimensions = getDimensions( image ); + + // handle case if texture exceeds max size + + if ( dimensions.width > maxSize || dimensions.height > maxSize ) { + + scale = maxSize / Math.max( dimensions.width, dimensions.height ); + + } + + // only perform resize if necessary + + if ( scale < 1 ) { + + // only perform resize for certain image types + + if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) || + ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) || + ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) || + ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) ) { + + const width = Math.floor( scale * dimensions.width ); + const height = Math.floor( scale * dimensions.height ); + + if ( _canvas === undefined ) _canvas = createCanvas( width, height ); + + // cube textures can't reuse the same canvas + + const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas; + + canvas.width = width; + canvas.height = height; + + const context = canvas.getContext( '2d' ); + context.drawImage( image, 0, 0, width, height ); + + console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + dimensions.width + 'x' + dimensions.height + ') to (' + width + 'x' + height + ').' ); + + return canvas; + + } else { + + if ( 'data' in image ) { + + console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + dimensions.width + 'x' + dimensions.height + ').' ); + + } + + return image; + + } + + } + + return image; + + } + + function textureNeedsGenerateMipmaps( texture ) { + + return texture.generateMipmaps; + + } + + function generateMipmap( target ) { + + _gl.generateMipmap( target ); + + } + + function getTargetType( texture ) { + + if ( texture.isWebGLCubeRenderTarget ) return _gl.TEXTURE_CUBE_MAP; + if ( texture.isWebGL3DRenderTarget ) return _gl.TEXTURE_3D; + if ( texture.isWebGLArrayRenderTarget || texture.isCompressedArrayTexture ) return _gl.TEXTURE_2D_ARRAY; + return _gl.TEXTURE_2D; + + } + + function getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) { + + if ( internalFormatName !== null ) { + + if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ]; + + console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' ); + + } + + let internalFormat = glFormat; + + if ( glFormat === _gl.RED ) { + + if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F; + if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F; + if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8; + + } + + if ( glFormat === _gl.RED_INTEGER ) { + + if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8UI; + if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.R16UI; + if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.R32UI; + if ( glType === _gl.BYTE ) internalFormat = _gl.R8I; + if ( glType === _gl.SHORT ) internalFormat = _gl.R16I; + if ( glType === _gl.INT ) internalFormat = _gl.R32I; + + } + + if ( glFormat === _gl.RG ) { + + if ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F; + if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F; + if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8; + + } + + if ( glFormat === _gl.RG_INTEGER ) { + + if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8UI; + if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RG16UI; + if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RG32UI; + if ( glType === _gl.BYTE ) internalFormat = _gl.RG8I; + if ( glType === _gl.SHORT ) internalFormat = _gl.RG16I; + if ( glType === _gl.INT ) internalFormat = _gl.RG32I; + + } + + if ( glFormat === _gl.RGB_INTEGER ) { + + if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGB8UI; + if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGB16UI; + if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGB32UI; + if ( glType === _gl.BYTE ) internalFormat = _gl.RGB8I; + if ( glType === _gl.SHORT ) internalFormat = _gl.RGB16I; + if ( glType === _gl.INT ) internalFormat = _gl.RGB32I; + + } + + if ( glFormat === _gl.RGBA_INTEGER ) { + + if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGBA8UI; + if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGBA16UI; + if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGBA32UI; + if ( glType === _gl.BYTE ) internalFormat = _gl.RGBA8I; + if ( glType === _gl.SHORT ) internalFormat = _gl.RGBA16I; + if ( glType === _gl.INT ) internalFormat = _gl.RGBA32I; + + } + + if ( glFormat === _gl.RGB ) { + + if ( glType === _gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = _gl.RGB9_E5; + + } + + if ( glFormat === _gl.RGBA ) { + + const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace ); + + if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F; + if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F; + if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8; + if ( glType === _gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = _gl.RGBA4; + if ( glType === _gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = _gl.RGB5_A1; + + } + + if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F || + internalFormat === _gl.RG16F || internalFormat === _gl.RG32F || + internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) { + + extensions.get( 'EXT_color_buffer_float' ); + + } + + return internalFormat; + + } + + function getInternalDepthFormat( useStencil, depthType ) { + + let glInternalFormat; + if ( useStencil ) { + + if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) { + + glInternalFormat = _gl.DEPTH24_STENCIL8; + + } else if ( depthType === FloatType ) { + + glInternalFormat = _gl.DEPTH32F_STENCIL8; + + } else if ( depthType === UnsignedShortType ) { + + glInternalFormat = _gl.DEPTH24_STENCIL8; + console.warn( 'DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.' ); + + } + + } else { + + if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) { + + glInternalFormat = _gl.DEPTH_COMPONENT24; + + } else if ( depthType === FloatType ) { + + glInternalFormat = _gl.DEPTH_COMPONENT32F; + + } else if ( depthType === UnsignedShortType ) { + + glInternalFormat = _gl.DEPTH_COMPONENT16; + + } + + } + + return glInternalFormat; + + } + + function getMipLevels( texture, image ) { + + if ( textureNeedsGenerateMipmaps( texture ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) { + + return Math.log2( Math.max( image.width, image.height ) ) + 1; + + } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) { + + // user-defined mipmaps + + return texture.mipmaps.length; + + } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) { + + return image.mipmaps.length; + + } else { + + // texture without mipmaps (only base level) + + return 1; + + } + + } + + // + + function onTextureDispose( event ) { + + const texture = event.target; + + texture.removeEventListener( 'dispose', onTextureDispose ); + + deallocateTexture( texture ); + + if ( texture.isVideoTexture ) { + + _videoTextures.delete( texture ); + + } + + } + + function onRenderTargetDispose( event ) { + + const renderTarget = event.target; + + renderTarget.removeEventListener( 'dispose', onRenderTargetDispose ); + + deallocateRenderTarget( renderTarget ); + + } + + // + + function deallocateTexture( texture ) { + + const textureProperties = properties.get( texture ); + + if ( textureProperties.__webglInit === undefined ) return; + + // check if it's necessary to remove the WebGLTexture object + + const source = texture.source; + const webglTextures = _sources.get( source ); + + if ( webglTextures ) { + + const webglTexture = webglTextures[ textureProperties.__cacheKey ]; + webglTexture.usedTimes --; + + // the WebGLTexture object is not used anymore, remove it + + if ( webglTexture.usedTimes === 0 ) { + + deleteTexture( texture ); + + } + + // remove the weak map entry if no WebGLTexture uses the source anymore + + if ( Object.keys( webglTextures ).length === 0 ) { + + _sources.delete( source ); + + } + + } + + properties.remove( texture ); + + } + + function deleteTexture( texture ) { + + const textureProperties = properties.get( texture ); + _gl.deleteTexture( textureProperties.__webglTexture ); + + const source = texture.source; + const webglTextures = _sources.get( source ); + delete webglTextures[ textureProperties.__cacheKey ]; + + info.memory.textures --; + + } + + function deallocateRenderTarget( renderTarget ) { + + const renderTargetProperties = properties.get( renderTarget ); + + if ( renderTarget.depthTexture ) { + + renderTarget.depthTexture.dispose(); + + properties.remove( renderTarget.depthTexture ); + + } + + if ( renderTarget.isWebGLCubeRenderTarget ) { + + for ( let i = 0; i < 6; i ++ ) { + + if ( Array.isArray( renderTargetProperties.__webglFramebuffer[ i ] ) ) { + + for ( let level = 0; level < renderTargetProperties.__webglFramebuffer[ i ].length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ][ level ] ); + + } else { + + _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] ); + + } + + if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] ); + + } + + } else { + + if ( Array.isArray( renderTargetProperties.__webglFramebuffer ) ) { + + for ( let level = 0; level < renderTargetProperties.__webglFramebuffer.length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ level ] ); + + } else { + + _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer ); + + } + + if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer ); + if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer ); + + if ( renderTargetProperties.__webglColorRenderbuffer ) { + + for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) { + + if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + } + + } + + if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer ); + + } + + const textures = renderTarget.textures; + + for ( let i = 0, il = textures.length; i < il; i ++ ) { + + const attachmentProperties = properties.get( textures[ i ] ); + + if ( attachmentProperties.__webglTexture ) { + + _gl.deleteTexture( attachmentProperties.__webglTexture ); + + info.memory.textures --; + + } + + properties.remove( textures[ i ] ); + + } + + properties.remove( renderTarget ); + + } + + // + + let textureUnits = 0; + + function resetTextureUnits() { + + textureUnits = 0; + + } + + function allocateTextureUnit() { + + const textureUnit = textureUnits; + + if ( textureUnit >= capabilities.maxTextures ) { + + console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures ); + + } + + textureUnits += 1; + + return textureUnit; + + } + + function getTextureCacheKey( texture ) { + + const array = []; + + array.push( texture.wrapS ); + array.push( texture.wrapT ); + array.push( texture.wrapR || 0 ); + array.push( texture.magFilter ); + array.push( texture.minFilter ); + array.push( texture.anisotropy ); + array.push( texture.internalFormat ); + array.push( texture.format ); + array.push( texture.type ); + array.push( texture.generateMipmaps ); + array.push( texture.premultiplyAlpha ); + array.push( texture.flipY ); + array.push( texture.unpackAlignment ); + array.push( texture.colorSpace ); + + return array.join(); + + } + + // + + function setTexture2D( texture, slot ) { + + const textureProperties = properties.get( texture ); + + if ( texture.isVideoTexture ) updateVideoTexture( texture ); + + if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) { + + const image = texture.image; + + if ( image === null ) { + + console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' ); + + } else if ( image.complete === false ) { + + console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' ); + + } else { + + uploadTexture( textureProperties, texture, slot ); + return; + + } + + } + + state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot ); + + } + + function setTexture2DArray( texture, slot ) { + + const textureProperties = properties.get( texture ); + + if ( texture.version > 0 && textureProperties.__version !== texture.version ) { + + uploadTexture( textureProperties, texture, slot ); + return; + + } + + state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot ); + + } + + function setTexture3D( texture, slot ) { + + const textureProperties = properties.get( texture ); + + if ( texture.version > 0 && textureProperties.__version !== texture.version ) { + + uploadTexture( textureProperties, texture, slot ); + return; + + } + + state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot ); + + } + + function setTextureCube( texture, slot ) { + + const textureProperties = properties.get( texture ); + + if ( texture.version > 0 && textureProperties.__version !== texture.version ) { + + uploadCubeTexture( textureProperties, texture, slot ); + return; + + } + + state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot ); + + } + + const wrappingToGL = { + [ RepeatWrapping ]: _gl.REPEAT, + [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE, + [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT + }; + + const filterToGL = { + [ NearestFilter ]: _gl.NEAREST, + [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST, + [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR, + + [ LinearFilter ]: _gl.LINEAR, + [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST, + [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR + }; + + const compareToGL = { + [ NeverCompare ]: _gl.NEVER, + [ AlwaysCompare ]: _gl.ALWAYS, + [ LessCompare ]: _gl.LESS, + [ LessEqualCompare ]: _gl.LEQUAL, + [ EqualCompare ]: _gl.EQUAL, + [ GreaterEqualCompare ]: _gl.GEQUAL, + [ GreaterCompare ]: _gl.GREATER, + [ NotEqualCompare ]: _gl.NOTEQUAL + }; + + function setTextureParameters( textureType, texture ) { + + if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false && + ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter || + texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter ) ) { + + console.warn( 'THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.' ); + + } + + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] ); + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] ); + + if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) { + + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] ); + + } + + _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] ); + _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] ); + + if ( texture.compareFunction ) { + + _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE ); + _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] ); + + } + + if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) { + + if ( texture.magFilter === NearestFilter ) return; + if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return; + if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension + + if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) { + + const extension = extensions.get( 'EXT_texture_filter_anisotropic' ); + _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) ); + properties.get( texture ).__currentAnisotropy = texture.anisotropy; + + } + + } + + } + + function initTexture( textureProperties, texture ) { + + let forceUpload = false; + + if ( textureProperties.__webglInit === undefined ) { + + textureProperties.__webglInit = true; + + texture.addEventListener( 'dispose', onTextureDispose ); + + } + + // create Source <-> WebGLTextures mapping if necessary + + const source = texture.source; + let webglTextures = _sources.get( source ); + + if ( webglTextures === undefined ) { + + webglTextures = {}; + _sources.set( source, webglTextures ); + + } + + // check if there is already a WebGLTexture object for the given texture parameters + + const textureCacheKey = getTextureCacheKey( texture ); + + if ( textureCacheKey !== textureProperties.__cacheKey ) { + + // if not, create a new instance of WebGLTexture + + if ( webglTextures[ textureCacheKey ] === undefined ) { + + // create new entry + + webglTextures[ textureCacheKey ] = { + texture: _gl.createTexture(), + usedTimes: 0 + }; + + info.memory.textures ++; + + // when a new instance of WebGLTexture was created, a texture upload is required + // even if the image contents are identical + + forceUpload = true; + + } + + webglTextures[ textureCacheKey ].usedTimes ++; + + // every time the texture cache key changes, it's necessary to check if an instance of + // WebGLTexture can be deleted in order to avoid a memory leak. + + const webglTexture = webglTextures[ textureProperties.__cacheKey ]; + + if ( webglTexture !== undefined ) { + + webglTextures[ textureProperties.__cacheKey ].usedTimes --; + + if ( webglTexture.usedTimes === 0 ) { + + deleteTexture( texture ); + + } + + } + + // store references to cache key and WebGLTexture object + + textureProperties.__cacheKey = textureCacheKey; + textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture; + + } + + return forceUpload; + + } + + function uploadTexture( textureProperties, texture, slot ) { + + let textureType = _gl.TEXTURE_2D; + + if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = _gl.TEXTURE_2D_ARRAY; + if ( texture.isData3DTexture ) textureType = _gl.TEXTURE_3D; + + const forceUpload = initTexture( textureProperties, texture ); + const source = texture.source; + + state.bindTexture( textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot ); + + const sourceProperties = properties.get( source ); + + if ( source.version !== sourceProperties.__version || forceUpload === true ) { + + state.activeTexture( _gl.TEXTURE0 + slot ); + + const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace ); + const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace ); + const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL; + + _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); + _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha ); + _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment ); + _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion ); + + let image = resizeImage( texture.image, false, capabilities.maxTextureSize ); + image = verifyColorSpace( texture, image ); + + const glFormat = utils.convert( texture.format, texture.colorSpace ); + + const glType = utils.convert( texture.type ); + let glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture ); + + setTextureParameters( textureType, texture ); + + let mipmap; + const mipmaps = texture.mipmaps; + + const useTexStorage = ( texture.isVideoTexture !== true ); + const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true ); + const dataReady = source.dataReady; + const levels = getMipLevels( texture, image ); + + if ( texture.isDepthTexture ) { + + glInternalFormat = getInternalDepthFormat( texture.format === DepthStencilFormat, texture.type ); + + // + + if ( allocateMemory ) { + + if ( useTexStorage ) { + + state.texStorage2D( _gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height ); + + } else { + + state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null ); + + } + + } + + } else if ( texture.isDataTexture ) { + + // use manually created mipmaps if available + // if there are no manual mipmaps + // set 0 level mipmap and then use GL to generate other mipmap levels + + if ( mipmaps.length > 0 ) { + + if ( useTexStorage && allocateMemory ) { + + state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height ); + + } + + for ( let i = 0, il = mipmaps.length; i < il; i ++ ) { + + mipmap = mipmaps[ i ]; + + if ( useTexStorage ) { + + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); + + } + + } else { + + state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + + } + + } + + texture.generateMipmaps = false; + + } else { + + if ( useTexStorage ) { + + if ( allocateMemory ) { + + state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height ); + + } + + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data ); + + } + + } else { + + state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data ); + + } + + } + + } else if ( texture.isCompressedTexture ) { + + if ( texture.isCompressedArrayTexture ) { + + if ( useTexStorage && allocateMemory ) { + + state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth ); + + } + + for ( let i = 0, il = mipmaps.length; i < il; i ++ ) { + + mipmap = mipmaps[ i ]; + + if ( texture.format !== RGBAFormat ) { + + if ( glFormat !== null ) { + + if ( useTexStorage ) { + + if ( dataReady ) { + + if ( texture.layerUpdates.size > 0 ) { + + const layerByteLength = getByteLength( mipmap.width, mipmap.height, texture.format, texture.type ); + + for ( const layerIndex of texture.layerUpdates ) { + + const layerData = mipmap.data.subarray( + layerIndex * layerByteLength / mipmap.data.BYTES_PER_ELEMENT, + ( layerIndex + 1 ) * layerByteLength / mipmap.data.BYTES_PER_ELEMENT + ); + state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, layerIndex, mipmap.width, mipmap.height, 1, glFormat, layerData ); + + } + + texture.clearLayerUpdates(); + + } else { + + state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data ); + + } + + } + + } else { + + state.compressedTexImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 ); + + } + + } else { + + console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' ); + + } + + } else { + + if ( useTexStorage ) { + + if ( dataReady ) { + + state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data ); + + } + + } else { + + state.texImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data ); + + } + + } + + } + + } else { + + if ( useTexStorage && allocateMemory ) { + + state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height ); + + } + + for ( let i = 0, il = mipmaps.length; i < il; i ++ ) { + + mipmap = mipmaps[ i ]; + + if ( texture.format !== RGBAFormat ) { + + if ( glFormat !== null ) { + + if ( useTexStorage ) { + + if ( dataReady ) { + + state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data ); + + } + + } else { + + state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data ); + + } + + } else { + + console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' ); + + } + + } else { + + if ( useTexStorage ) { + + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); + + } + + } else { + + state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + + } + + } + + } + + } + + } else if ( texture.isDataArrayTexture ) { + + if ( useTexStorage ) { + + if ( allocateMemory ) { + + state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth ); + + } + + if ( dataReady ) { + + if ( texture.layerUpdates.size > 0 ) { + + const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type ); + + for ( const layerIndex of texture.layerUpdates ) { + + const layerData = image.data.subarray( + layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT, + ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT + ); + state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData ); + + } + + texture.clearLayerUpdates(); + + } else { + + state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data ); + + } + + } + + } else { + + state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data ); + + } + + } else if ( texture.isData3DTexture ) { + + if ( useTexStorage ) { + + if ( allocateMemory ) { + + state.texStorage3D( _gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth ); + + } + + if ( dataReady ) { + + state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data ); + + } + + } else { + + state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data ); + + } + + } else if ( texture.isFramebufferTexture ) { + + if ( allocateMemory ) { + + if ( useTexStorage ) { + + state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height ); + + } else { + + let width = image.width, height = image.height; + + for ( let i = 0; i < levels; i ++ ) { + + state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null ); + + width >>= 1; + height >>= 1; + + } + + } + + } + + } else { + + // regular Texture (image, video, canvas) + + // use manually created mipmaps if available + // if there are no manual mipmaps + // set 0 level mipmap and then use GL to generate other mipmap levels + + if ( mipmaps.length > 0 ) { + + if ( useTexStorage && allocateMemory ) { + + const dimensions = getDimensions( mipmaps[ 0 ] ); + + state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height ); + + } + + for ( let i = 0, il = mipmaps.length; i < il; i ++ ) { + + mipmap = mipmaps[ i ]; + + if ( useTexStorage ) { + + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap ); + + } + + } else { + + state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap ); + + } + + } + + texture.generateMipmaps = false; + + } else { + + if ( useTexStorage ) { + + if ( allocateMemory ) { + + const dimensions = getDimensions( image ); + + state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height ); + + } + + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image ); + + } + + } else { + + state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image ); + + } + + } + + } + + if ( textureNeedsGenerateMipmaps( texture ) ) { + + generateMipmap( textureType ); + + } + + sourceProperties.__version = source.version; + + if ( texture.onUpdate ) texture.onUpdate( texture ); + + } + + textureProperties.__version = texture.version; + + } + + function uploadCubeTexture( textureProperties, texture, slot ) { + + if ( texture.image.length !== 6 ) return; + + const forceUpload = initTexture( textureProperties, texture ); + const source = texture.source; + + state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot ); + + const sourceProperties = properties.get( source ); + + if ( source.version !== sourceProperties.__version || forceUpload === true ) { + + state.activeTexture( _gl.TEXTURE0 + slot ); + + const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace ); + const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace ); + const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL; + + _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); + _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha ); + _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment ); + _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion ); + + const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture ); + const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture ); + + const cubeImage = []; + + for ( let i = 0; i < 6; i ++ ) { + + if ( ! isCompressed && ! isDataTexture ) { + + cubeImage[ i ] = resizeImage( texture.image[ i ], true, capabilities.maxCubemapSize ); + + } else { + + cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ]; + + } + + cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] ); + + } + + const image = cubeImage[ 0 ], + glFormat = utils.convert( texture.format, texture.colorSpace ), + glType = utils.convert( texture.type ), + glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace ); + + const useTexStorage = ( texture.isVideoTexture !== true ); + const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true ); + const dataReady = source.dataReady; + let levels = getMipLevels( texture, image ); + + setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture ); + + let mipmaps; + + if ( isCompressed ) { + + if ( useTexStorage && allocateMemory ) { + + state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height ); + + } + + for ( let i = 0; i < 6; i ++ ) { + + mipmaps = cubeImage[ i ].mipmaps; + + for ( let j = 0; j < mipmaps.length; j ++ ) { + + const mipmap = mipmaps[ j ]; + + if ( texture.format !== RGBAFormat ) { + + if ( glFormat !== null ) { + + if ( useTexStorage ) { + + if ( dataReady ) { + + state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data ); + + } + + } else { + + state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data ); + + } + + } else { + + console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' ); + + } + + } else { + + if ( useTexStorage ) { + + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data ); + + } + + } else { + + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + + } + + } + + } + + } + + } else { + + mipmaps = texture.mipmaps; + + if ( useTexStorage && allocateMemory ) { + + // TODO: Uniformly handle mipmap definitions + // Normal textures and compressed cube textures define base level + mips with their mipmap array + // Uncompressed cube textures use their mipmap array only for mips (no base level) + + if ( mipmaps.length > 0 ) levels ++; + + const dimensions = getDimensions( cubeImage[ 0 ] ); + + state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, dimensions.width, dimensions.height ); + + } + + for ( let i = 0; i < 6; i ++ ) { + + if ( isDataTexture ) { + + if ( useTexStorage ) { + + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data ); + + } + + } else { + + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data ); + + } + + for ( let j = 0; j < mipmaps.length; j ++ ) { + + const mipmap = mipmaps[ j ]; + const mipmapImage = mipmap.image[ i ].image; + + if ( useTexStorage ) { + + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data ); + + } + + } else { + + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data ); + + } + + } + + } else { + + if ( useTexStorage ) { + + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] ); + + } + + } else { + + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] ); + + } + + for ( let j = 0; j < mipmaps.length; j ++ ) { + + const mipmap = mipmaps[ j ]; + + if ( useTexStorage ) { + + if ( dataReady ) { + + state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] ); + + } + + } else { + + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] ); + + } + + } + + } + + } + + } + + if ( textureNeedsGenerateMipmaps( texture ) ) { + + // We assume images for cube map have the same size. + generateMipmap( _gl.TEXTURE_CUBE_MAP ); + + } + + sourceProperties.__version = source.version; + + if ( texture.onUpdate ) texture.onUpdate( texture ); + + } + + textureProperties.__version = texture.version; + + } + + // Render targets + + // Setup storage for target texture and bind it to correct framebuffer + function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget, level ) { + + const glFormat = utils.convert( texture.format, texture.colorSpace ); + const glType = utils.convert( texture.type ); + const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace ); + const renderTargetProperties = properties.get( renderTarget ); + const textureProperties = properties.get( texture ); + + textureProperties.__renderTarget = renderTarget; + + if ( ! renderTargetProperties.__hasExternalTextures ) { + + const width = Math.max( 1, renderTarget.width >> level ); + const height = Math.max( 1, renderTarget.height >> level ); + + if ( textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY ) { + + state.texImage3D( textureTarget, level, glInternalFormat, width, height, renderTarget.depth, 0, glFormat, glType, null ); + + } else { + + state.texImage2D( textureTarget, level, glInternalFormat, width, height, 0, glFormat, glType, null ); + + } + + } + + state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + + if ( useMultisampledRTT( renderTarget ) ) { + + multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, 0, getRenderTargetSamples( renderTarget ) ); + + } else if ( textureTarget === _gl.TEXTURE_2D || ( textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ) ) { // see #24753 + + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, level ); + + } + + state.bindFramebuffer( _gl.FRAMEBUFFER, null ); + + } + + // Setup storage for internal depth/stencil buffers and bind to correct framebuffer + function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) { + + _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer ); + + if ( renderTarget.depthBuffer ) { + + // retrieve the depth attachment types + const depthTexture = renderTarget.depthTexture; + const depthType = depthTexture && depthTexture.isDepthTexture ? depthTexture.type : null; + const glInternalFormat = getInternalDepthFormat( renderTarget.stencilBuffer, depthType ); + const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + + // set up the attachment + const samples = getRenderTargetSamples( renderTarget ); + const isUseMultisampledRTT = useMultisampledRTT( renderTarget ); + if ( isUseMultisampledRTT ) { + + multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + + } else if ( isMultisample ) { + + _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + + } else { + + _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height ); + + } + + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer ); + + } else { + + const textures = renderTarget.textures; + + for ( let i = 0; i < textures.length; i ++ ) { + + const texture = textures[ i ]; + + const glFormat = utils.convert( texture.format, texture.colorSpace ); + const glType = utils.convert( texture.type ); + const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace ); + const samples = getRenderTargetSamples( renderTarget ); + + if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) { + + _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + + } else if ( useMultisampledRTT( renderTarget ) ) { + + multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + + } else { + + _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height ); + + } + + } + + } + + _gl.bindRenderbuffer( _gl.RENDERBUFFER, null ); + + } + + // Setup resources for a Depth Texture for a FBO (needs an extension) + function setupDepthTexture( framebuffer, renderTarget ) { + + const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget ); + if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' ); + + state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + + if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) { + + throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' ); + + } + + const textureProperties = properties.get( renderTarget.depthTexture ); + textureProperties.__renderTarget = renderTarget; + + // upload an empty depth texture with framebuffer size + if ( ! textureProperties.__webglTexture || + renderTarget.depthTexture.image.width !== renderTarget.width || + renderTarget.depthTexture.image.height !== renderTarget.height ) { + + renderTarget.depthTexture.image.width = renderTarget.width; + renderTarget.depthTexture.image.height = renderTarget.height; + renderTarget.depthTexture.needsUpdate = true; + + } + + setTexture2D( renderTarget.depthTexture, 0 ); + + const webglDepthTexture = textureProperties.__webglTexture; + const samples = getRenderTargetSamples( renderTarget ); + + if ( renderTarget.depthTexture.format === DepthFormat ) { + + if ( useMultisampledRTT( renderTarget ) ) { + + multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples ); + + } else { + + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 ); + + } + + } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) { + + if ( useMultisampledRTT( renderTarget ) ) { + + multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples ); + + } else { + + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 ); + + } + + } else { + + throw new Error( 'Unknown depthTexture format' ); + + } + + } + + // Setup GL resources for a non-texture depth buffer + function setupDepthRenderbuffer( renderTarget ) { + + const renderTargetProperties = properties.get( renderTarget ); + const isCube = ( renderTarget.isWebGLCubeRenderTarget === true ); + + // if the bound depth texture has changed + if ( renderTargetProperties.__boundDepthTexture !== renderTarget.depthTexture ) { + + // fire the dispose event to get rid of stored state associated with the previously bound depth buffer + const depthTexture = renderTarget.depthTexture; + if ( renderTargetProperties.__depthDisposeCallback ) { + + renderTargetProperties.__depthDisposeCallback(); + + } + + // set up dispose listeners to track when the currently attached buffer is implicitly unbound + if ( depthTexture ) { + + const disposeEvent = () => { + + delete renderTargetProperties.__boundDepthTexture; + delete renderTargetProperties.__depthDisposeCallback; + depthTexture.removeEventListener( 'dispose', disposeEvent ); + + }; + + depthTexture.addEventListener( 'dispose', disposeEvent ); + renderTargetProperties.__depthDisposeCallback = disposeEvent; + + } + + renderTargetProperties.__boundDepthTexture = depthTexture; + + } + + if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) { + + if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' ); + + const mipmaps = renderTarget.texture.mipmaps; + + if ( mipmaps && mipmaps.length > 0 ) { + + setupDepthTexture( renderTargetProperties.__webglFramebuffer[ 0 ], renderTarget ); + + } else { + + setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget ); + + } + + } else { + + if ( isCube ) { + + renderTargetProperties.__webglDepthbuffer = []; + + for ( let i = 0; i < 6; i ++ ) { + + state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] ); + + if ( renderTargetProperties.__webglDepthbuffer[ i ] === undefined ) { + + renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer(); + setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false ); + + } else { + + // attach buffer if it's been created already + const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const renderbuffer = renderTargetProperties.__webglDepthbuffer[ i ]; + _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer ); + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer ); + + } + + } + + } else { + + const mipmaps = renderTarget.texture.mipmaps; + + if ( mipmaps && mipmaps.length > 0 ) { + + state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ 0 ] ); + + } else { + + state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer ); + + } + + if ( renderTargetProperties.__webglDepthbuffer === undefined ) { + + renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false ); + + } else { + + // attach buffer if it's been created already + const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const renderbuffer = renderTargetProperties.__webglDepthbuffer; + _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer ); + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer ); + + } + + } + + } + + state.bindFramebuffer( _gl.FRAMEBUFFER, null ); + + } + + // rebind framebuffer with external textures + function rebindTextures( renderTarget, colorTexture, depthTexture ) { + + const renderTargetProperties = properties.get( renderTarget ); + + if ( colorTexture !== undefined ) { + + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, 0 ); + + } + + if ( depthTexture !== undefined ) { + + setupDepthRenderbuffer( renderTarget ); + + } + + } + + // Set up GL resources for the render target + function setupRenderTarget( renderTarget ) { + + const texture = renderTarget.texture; + + const renderTargetProperties = properties.get( renderTarget ); + const textureProperties = properties.get( texture ); + + renderTarget.addEventListener( 'dispose', onRenderTargetDispose ); + + const textures = renderTarget.textures; + + const isCube = ( renderTarget.isWebGLCubeRenderTarget === true ); + const isMultipleRenderTargets = ( textures.length > 1 ); + + if ( ! isMultipleRenderTargets ) { + + if ( textureProperties.__webglTexture === undefined ) { + + textureProperties.__webglTexture = _gl.createTexture(); + + } + + textureProperties.__version = texture.version; + info.memory.textures ++; + + } + + // Setup framebuffer + + if ( isCube ) { + + renderTargetProperties.__webglFramebuffer = []; + + for ( let i = 0; i < 6; i ++ ) { + + if ( texture.mipmaps && texture.mipmaps.length > 0 ) { + + renderTargetProperties.__webglFramebuffer[ i ] = []; + + for ( let level = 0; level < texture.mipmaps.length; level ++ ) { + + renderTargetProperties.__webglFramebuffer[ i ][ level ] = _gl.createFramebuffer(); + + } + + } else { + + renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer(); + + } + + } + + } else { + + if ( texture.mipmaps && texture.mipmaps.length > 0 ) { + + renderTargetProperties.__webglFramebuffer = []; + + for ( let level = 0; level < texture.mipmaps.length; level ++ ) { + + renderTargetProperties.__webglFramebuffer[ level ] = _gl.createFramebuffer(); + + } + + } else { + + renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer(); + + } + + if ( isMultipleRenderTargets ) { + + for ( let i = 0, il = textures.length; i < il; i ++ ) { + + const attachmentProperties = properties.get( textures[ i ] ); + + if ( attachmentProperties.__webglTexture === undefined ) { + + attachmentProperties.__webglTexture = _gl.createTexture(); + + info.memory.textures ++; + + } + + } + + } + + if ( ( renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) { + + renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer(); + renderTargetProperties.__webglColorRenderbuffer = []; + + state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer ); + + for ( let i = 0; i < textures.length; i ++ ) { + + const texture = textures[ i ]; + renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer(); + + _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + const glFormat = utils.convert( texture.format, texture.colorSpace ); + const glType = utils.convert( texture.type ); + const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, renderTarget.isXRRenderTarget === true ); + const samples = getRenderTargetSamples( renderTarget ); + _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + } + + _gl.bindRenderbuffer( _gl.RENDERBUFFER, null ); + + if ( renderTarget.depthBuffer ) { + + renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true ); + + } + + state.bindFramebuffer( _gl.FRAMEBUFFER, null ); + + } + + } + + // Setup color buffer + + if ( isCube ) { + + state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture ); + setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture ); + + for ( let i = 0; i < 6; i ++ ) { + + if ( texture.mipmaps && texture.mipmaps.length > 0 ) { + + for ( let level = 0; level < texture.mipmaps.length; level ++ ) { + + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ][ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level ); + + } + + } else { + + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0 ); + + } + + } + + if ( textureNeedsGenerateMipmaps( texture ) ) { + + generateMipmap( _gl.TEXTURE_CUBE_MAP ); + + } + + state.unbindTexture(); + + } else if ( isMultipleRenderTargets ) { + + for ( let i = 0, il = textures.length; i < il; i ++ ) { + + const attachment = textures[ i ]; + const attachmentProperties = properties.get( attachment ); + + state.bindTexture( _gl.TEXTURE_2D, attachmentProperties.__webglTexture ); + setTextureParameters( _gl.TEXTURE_2D, attachment ); + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, 0 ); + + if ( textureNeedsGenerateMipmaps( attachment ) ) { + + generateMipmap( _gl.TEXTURE_2D ); + + } + + } + + state.unbindTexture(); + + } else { + + let glTextureType = _gl.TEXTURE_2D; + + if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) { + + glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY; + + } + + state.bindTexture( glTextureType, textureProperties.__webglTexture ); + setTextureParameters( glTextureType, texture ); + + if ( texture.mipmaps && texture.mipmaps.length > 0 ) { + + for ( let level = 0; level < texture.mipmaps.length; level ++ ) { + + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, level ); + + } + + } else { + + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, 0 ); + + } + + if ( textureNeedsGenerateMipmaps( texture ) ) { + + generateMipmap( glTextureType ); + + } + + state.unbindTexture(); + + } + + // Setup depth and stencil buffers + + if ( renderTarget.depthBuffer ) { + + setupDepthRenderbuffer( renderTarget ); + + } + + } + + function updateRenderTargetMipmap( renderTarget ) { + + const textures = renderTarget.textures; + + for ( let i = 0, il = textures.length; i < il; i ++ ) { + + const texture = textures[ i ]; + + if ( textureNeedsGenerateMipmaps( texture ) ) { + + const targetType = getTargetType( renderTarget ); + const webglTexture = properties.get( texture ).__webglTexture; + + state.bindTexture( targetType, webglTexture ); + generateMipmap( targetType ); + state.unbindTexture(); + + } + + } + + } + + const invalidationArrayRead = []; + const invalidationArrayDraw = []; + + function updateMultisampleRenderTarget( renderTarget ) { + + if ( renderTarget.samples > 0 ) { + + if ( useMultisampledRTT( renderTarget ) === false ) { + + const textures = renderTarget.textures; + const width = renderTarget.width; + const height = renderTarget.height; + let mask = _gl.COLOR_BUFFER_BIT; + const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const renderTargetProperties = properties.get( renderTarget ); + const isMultipleRenderTargets = ( textures.length > 1 ); + + // If MRT we need to remove FBO attachments + if ( isMultipleRenderTargets ) { + + for ( let i = 0; i < textures.length; i ++ ) { + + state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer ); + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null ); + + state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer ); + _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0 ); + + } + + } + + state.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer ); + + const mipmaps = renderTarget.texture.mipmaps; + + if ( mipmaps && mipmaps.length > 0 ) { + + state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ 0 ] ); + + } else { + + state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer ); + + } + + for ( let i = 0; i < textures.length; i ++ ) { + + if ( renderTarget.resolveDepthBuffer ) { + + if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT; + + // resolving stencil is slow with a D3D backend. disable it for all transmission render targets (see #27799) + + if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT; + + } + + if ( isMultipleRenderTargets ) { + + _gl.framebufferRenderbuffer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + const webglTexture = properties.get( textures[ i ] ).__webglTexture; + _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0 ); + + } + + _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST ); + + if ( supportsInvalidateFramebuffer === true ) { + + invalidationArrayRead.length = 0; + invalidationArrayDraw.length = 0; + + invalidationArrayRead.push( _gl.COLOR_ATTACHMENT0 + i ); + + if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false ) { + + invalidationArrayRead.push( depthStyle ); + invalidationArrayDraw.push( depthStyle ); + + _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, invalidationArrayDraw ); + + } + + _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, invalidationArrayRead ); + + } + + } + + state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null ); + state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null ); + + // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments + if ( isMultipleRenderTargets ) { + + for ( let i = 0; i < textures.length; i ++ ) { + + state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer ); + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] ); + + const webglTexture = properties.get( textures[ i ] ).__webglTexture; + + state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer ); + _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0 ); + + } + + } + + state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer ); + + } else { + + if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false && supportsInvalidateFramebuffer ) { + + const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + + _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, [ depthStyle ] ); + + } + + } + + } + + } + + function getRenderTargetSamples( renderTarget ) { + + return Math.min( capabilities.maxSamples, renderTarget.samples ); + + } + + function useMultisampledRTT( renderTarget ) { + + const renderTargetProperties = properties.get( renderTarget ); + + return renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false; + + } + + function updateVideoTexture( texture ) { + + const frame = info.render.frame; + + // Check the last frame we updated the VideoTexture + + if ( _videoTextures.get( texture ) !== frame ) { + + _videoTextures.set( texture, frame ); + texture.update(); + + } + + } + + function verifyColorSpace( texture, image ) { + + const colorSpace = texture.colorSpace; + const format = texture.format; + const type = texture.type; + + if ( texture.isCompressedTexture === true || texture.isVideoTexture === true ) return image; + + if ( colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace ) { + + // sRGB + + if ( ColorManagement.getTransfer( colorSpace ) === SRGBTransfer ) { + + // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format + + if ( format !== RGBAFormat || type !== UnsignedByteType ) { + + console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' ); + + } + + } else { + + console.error( 'THREE.WebGLTextures: Unsupported texture color space:', colorSpace ); + + } + + } + + return image; + + } + + function getDimensions( image ) { + + if ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) { + + // if intrinsic data are not available, fallback to width/height + + _imageDimensions.width = image.naturalWidth || image.width; + _imageDimensions.height = image.naturalHeight || image.height; + + } else if ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) { + + _imageDimensions.width = image.displayWidth; + _imageDimensions.height = image.displayHeight; + + } else { + + _imageDimensions.width = image.width; + _imageDimensions.height = image.height; + + } + + return _imageDimensions; + + } + + // + + this.allocateTextureUnit = allocateTextureUnit; + this.resetTextureUnits = resetTextureUnits; + + this.setTexture2D = setTexture2D; + this.setTexture2DArray = setTexture2DArray; + this.setTexture3D = setTexture3D; + this.setTextureCube = setTextureCube; + this.rebindTextures = rebindTextures; + this.setupRenderTarget = setupRenderTarget; + this.updateRenderTargetMipmap = updateRenderTargetMipmap; + this.updateMultisampleRenderTarget = updateMultisampleRenderTarget; + this.setupDepthRenderbuffer = setupDepthRenderbuffer; + this.setupFrameBufferTexture = setupFrameBufferTexture; + this.useMultisampledRTT = useMultisampledRTT; + +} + +function WebGLUtils( gl, extensions ) { + + function convert( p, colorSpace = NoColorSpace ) { + + let extension; + + const transfer = ColorManagement.getTransfer( colorSpace ); + + if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE; + if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4; + if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1; + if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV; + + if ( p === ByteType ) return gl.BYTE; + if ( p === ShortType ) return gl.SHORT; + if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT; + if ( p === IntType ) return gl.INT; + if ( p === UnsignedIntType ) return gl.UNSIGNED_INT; + if ( p === FloatType ) return gl.FLOAT; + if ( p === HalfFloatType ) return gl.HALF_FLOAT; + + if ( p === AlphaFormat ) return gl.ALPHA; + if ( p === RGBFormat ) return gl.RGB; + if ( p === RGBAFormat ) return gl.RGBA; + if ( p === DepthFormat ) return gl.DEPTH_COMPONENT; + if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL; + + // WebGL2 formats. + + if ( p === RedFormat ) return gl.RED; + if ( p === RedIntegerFormat ) return gl.RED_INTEGER; + if ( p === RGFormat ) return gl.RG; + if ( p === RGIntegerFormat ) return gl.RG_INTEGER; + if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER; + + // S3TC + + if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) { + + if ( transfer === SRGBTransfer ) { + + extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' ); + + if ( extension !== null ) { + + if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT; + if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; + if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT; + if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; + + } else { + + return null; + + } + + } else { + + extension = extensions.get( 'WEBGL_compressed_texture_s3tc' ); + + if ( extension !== null ) { + + if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT; + if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT; + if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT; + if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT; + + } else { + + return null; + + } + + } + + } + + // PVRTC + + if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) { + + extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' ); + + if ( extension !== null ) { + + if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; + if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; + if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; + if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; + + } else { + + return null; + + } + + } + + // ETC + + if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) { + + extension = extensions.get( 'WEBGL_compressed_texture_etc' ); + + if ( extension !== null ) { + + if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2; + if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC; + + } else { + + return null; + + } + + } + + // ASTC + + if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format || + p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format || + p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format || + p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format || + p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) { + + extension = extensions.get( 'WEBGL_compressed_texture_astc' ); + + if ( extension !== null ) { + + if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR; + if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR; + if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR; + if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR; + if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR; + if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR; + if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR; + if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR; + if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR; + if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR; + if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR; + if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR; + if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR; + if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR; + + } else { + + return null; + + } + + } + + // BPTC + + if ( p === RGBA_BPTC_Format || p === RGB_BPTC_SIGNED_Format || p === RGB_BPTC_UNSIGNED_Format ) { + + extension = extensions.get( 'EXT_texture_compression_bptc' ); + + if ( extension !== null ) { + + if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT; + if ( p === RGB_BPTC_SIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT; + if ( p === RGB_BPTC_UNSIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT; + + } else { + + return null; + + } + + } + + // RGTC + + if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) { + + extension = extensions.get( 'EXT_texture_compression_rgtc' ); + + if ( extension !== null ) { + + if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT; + if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT; + if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT; + if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT; + + } else { + + return null; + + } + + } + + // + + if ( p === UnsignedInt248Type ) return gl.UNSIGNED_INT_24_8; + + // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats) + + return ( gl[ p ] !== undefined ) ? gl[ p ] : null; + + } + + return { convert: convert }; + +} + +const _occlusion_vertex = ` +void main() { + + gl_Position = vec4( position, 1.0 ); + +}`; + +const _occlusion_fragment = ` +uniform sampler2DArray depthColor; +uniform float depthWidth; +uniform float depthHeight; + +void main() { + + vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight ); + + if ( coord.x >= 1.0 ) { + + gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r; + + } else { + + gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r; + + } + +}`; + +/** + * A XR module that manages the access to the Depth Sensing API. + */ +class WebXRDepthSensing { + + /** + * Constructs a new depth sensing module. + */ + constructor() { + + /** + * A texture representing the depth of the user's environment. + * + * @type {?Texture} + */ + this.texture = null; + + /** + * A plane mesh for visualizing the depth texture. + * + * @type {?Mesh} + */ + this.mesh = null; + + /** + * The depth near value. + * + * @type {number} + */ + this.depthNear = 0; + + /** + * The depth near far. + * + * @type {number} + */ + this.depthFar = 0; + + } + + /** + * Inits the depth sensing module + * + * @param {WebGLRenderer} renderer - The renderer. + * @param {XRWebGLDepthInformation} depthData - The XR depth data. + * @param {XRRenderState} renderState - The XR render state. + */ + init( renderer, depthData, renderState ) { + + if ( this.texture === null ) { + + const texture = new Texture(); + + const texProps = renderer.properties.get( texture ); + texProps.__webglTexture = depthData.texture; + + if ( ( depthData.depthNear !== renderState.depthNear ) || ( depthData.depthFar !== renderState.depthFar ) ) { + + this.depthNear = depthData.depthNear; + this.depthFar = depthData.depthFar; + + } + + this.texture = texture; + + } + + } + + /** + * Returns a plane mesh that visualizes the depth texture. + * + * @param {ArrayCamera} cameraXR - The XR camera. + * @return {?Mesh} The plane mesh. + */ + getMesh( cameraXR ) { + + if ( this.texture !== null ) { + + if ( this.mesh === null ) { + + const viewport = cameraXR.cameras[ 0 ].viewport; + const material = new ShaderMaterial( { + vertexShader: _occlusion_vertex, + fragmentShader: _occlusion_fragment, + uniforms: { + depthColor: { value: this.texture }, + depthWidth: { value: viewport.z }, + depthHeight: { value: viewport.w } + } + } ); + + this.mesh = new Mesh( new PlaneGeometry( 20, 20 ), material ); + + } + + } + + return this.mesh; + + } + + /** + * Resets the module + */ + reset() { + + this.texture = null; + this.mesh = null; + + } + + /** + * Returns a texture representing the depth of the user's environment. + * + * @return {?Texture} The depth texture. + */ + getDepthTexture() { + + return this.texture; + + } + +} + +/** + * This class represents an abstraction of the WebXR Device API and is + * internally used by {@link WebGLRenderer}. `WebXRManager` also provides a public + * interface that allows users to enable/disable XR and perform XR related + * tasks like for instance retrieving controllers. + * + * @augments EventDispatcher + * @hideconstructor + */ +class WebXRManager extends EventDispatcher { + + /** + * Constructs a new WebGL renderer. + * + * @param {WebGLRenderer} renderer - The renderer. + * @param {WebGL2RenderingContext} gl - The rendering context. + */ + constructor( renderer, gl ) { + + super(); + + const scope = this; + + let session = null; + + let framebufferScaleFactor = 1.0; + + let referenceSpace = null; + let referenceSpaceType = 'local-floor'; + // Set default foveation to maximum. + let foveation = 1.0; + let customReferenceSpace = null; + + let pose = null; + let glBinding = null; + let glProjLayer = null; + let glBaseLayer = null; + let xrFrame = null; + + const depthSensing = new WebXRDepthSensing(); + const attributes = gl.getContextAttributes(); + + let initialRenderTarget = null; + let newRenderTarget = null; + + const controllers = []; + const controllerInputSources = []; + + const currentSize = new Vector2(); + let currentPixelRatio = null; + + // + + const cameraL = new PerspectiveCamera(); + cameraL.viewport = new Vector4(); + + const cameraR = new PerspectiveCamera(); + cameraR.viewport = new Vector4(); + + const cameras = [ cameraL, cameraR ]; + + const cameraXR = new ArrayCamera(); + + let _currentDepthNear = null; + let _currentDepthFar = null; + + // + + /** + * Whether the manager's XR camera should be automatically updated or not. + * + * @type {boolean} + * @default true + */ + this.cameraAutoUpdate = true; + + /** + * This flag notifies the renderer to be ready for XR rendering. Set it to `true` + * if you are going to use XR in your app. + * + * @type {boolean} + * @default false + */ + this.enabled = false; + + /** + * Whether XR presentation is active or not. + * + * @type {boolean} + * @readonly + * @default false + */ + this.isPresenting = false; + + /** + * Returns a group representing the `target ray` space of the XR controller. + * Use this space for visualizing 3D objects that support the user in pointing + * tasks like UI interaction. + * + * @param {number} index - The index of the controller. + * @return {Group} A group representing the `target ray` space. + */ + this.getController = function ( index ) { + + let controller = controllers[ index ]; + + if ( controller === undefined ) { + + controller = new WebXRController(); + controllers[ index ] = controller; + + } + + return controller.getTargetRaySpace(); + + }; + + /** + * Returns a group representing the `grip` space of the XR controller. + * Use this space for visualizing 3D objects that support the user in pointing + * tasks like UI interaction. + * + * Note: If you want to show something in the user's hand AND offer a + * pointing ray at the same time, you'll want to attached the handheld object + * to the group returned by `getControllerGrip()` and the ray to the + * group returned by `getController()`. The idea is to have two + * different groups in two different coordinate spaces for the same WebXR + * controller. + * + * @param {number} index - The index of the controller. + * @return {Group} A group representing the `grip` space. + */ + this.getControllerGrip = function ( index ) { + + let controller = controllers[ index ]; + + if ( controller === undefined ) { + + controller = new WebXRController(); + controllers[ index ] = controller; + + } + + return controller.getGripSpace(); + + }; + + /** + * Returns a group representing the `hand` space of the XR controller. + * Use this space for visualizing 3D objects that support the user in pointing + * tasks like UI interaction. + * + * @param {number} index - The index of the controller. + * @return {Group} A group representing the `hand` space. + */ + this.getHand = function ( index ) { + + let controller = controllers[ index ]; + + if ( controller === undefined ) { + + controller = new WebXRController(); + controllers[ index ] = controller; + + } + + return controller.getHandSpace(); + + }; + + // + + function onSessionEvent( event ) { + + const controllerIndex = controllerInputSources.indexOf( event.inputSource ); + + if ( controllerIndex === -1 ) { + + return; + + } + + const controller = controllers[ controllerIndex ]; + + if ( controller !== undefined ) { + + controller.update( event.inputSource, event.frame, customReferenceSpace || referenceSpace ); + controller.dispatchEvent( { type: event.type, data: event.inputSource } ); + + } + + } + + function onSessionEnd() { + + session.removeEventListener( 'select', onSessionEvent ); + session.removeEventListener( 'selectstart', onSessionEvent ); + session.removeEventListener( 'selectend', onSessionEvent ); + session.removeEventListener( 'squeeze', onSessionEvent ); + session.removeEventListener( 'squeezestart', onSessionEvent ); + session.removeEventListener( 'squeezeend', onSessionEvent ); + session.removeEventListener( 'end', onSessionEnd ); + session.removeEventListener( 'inputsourceschange', onInputSourcesChange ); + + for ( let i = 0; i < controllers.length; i ++ ) { + + const inputSource = controllerInputSources[ i ]; + + if ( inputSource === null ) continue; + + controllerInputSources[ i ] = null; + + controllers[ i ].disconnect( inputSource ); + + } + + _currentDepthNear = null; + _currentDepthFar = null; + + depthSensing.reset(); + + // restore framebuffer/rendering state + + renderer.setRenderTarget( initialRenderTarget ); + + glBaseLayer = null; + glProjLayer = null; + glBinding = null; + session = null; + newRenderTarget = null; + + // + + animation.stop(); + + scope.isPresenting = false; + + renderer.setPixelRatio( currentPixelRatio ); + renderer.setSize( currentSize.width, currentSize.height, false ); + + scope.dispatchEvent( { type: 'sessionend' } ); + + } + + /** + * Sets the framebuffer scale factor. + * + * This method can not be used during a XR session. + * + * @param {number} value - The framebuffer scale factor. + */ + this.setFramebufferScaleFactor = function ( value ) { + + framebufferScaleFactor = value; + + if ( scope.isPresenting === true ) { + + console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' ); + + } + + }; + + /** + * Sets the reference space type. Can be used to configure a spatial relationship with the user's physical + * environment. Depending on how the user moves in 3D space, setting an appropriate reference space can + * improve tracking. Default is `local-floor`. Valid values can be found here + * https://developer.mozilla.org/en-US/docs/Web/API/XRReferenceSpace#reference_space_types. + * + * This method can not be used during a XR session. + * + * @param {string} value - The reference space type. + */ + this.setReferenceSpaceType = function ( value ) { + + referenceSpaceType = value; + + if ( scope.isPresenting === true ) { + + console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' ); + + } + + }; + + /** + * Returns the XR reference space. + * + * @return {XRReferenceSpace} The XR reference space. + */ + this.getReferenceSpace = function () { + + return customReferenceSpace || referenceSpace; + + }; + + /** + * Sets a custom XR reference space. + * + * @param {XRReferenceSpace} space - The XR reference space. + */ + this.setReferenceSpace = function ( space ) { + + customReferenceSpace = space; + + }; + + /** + * Returns the current base layer. + * + * @return {?(XRWebGLLayer|XRProjectionLayer)} The XR base layer. + */ + this.getBaseLayer = function () { + + return glProjLayer !== null ? glProjLayer : glBaseLayer; + + }; + + /** + * Returns the current XR binding. + * + * @return {?XRWebGLBinding} The XR binding. + */ + this.getBinding = function () { + + return glBinding; + + }; + + /** + * Returns the current XR frame. + * + * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session. + */ + this.getFrame = function () { + + return xrFrame; + + }; + + /** + * Returns the current XR session. + * + * @return {?XRSession} The XR session. Returns `null` when used outside a XR session. + */ + this.getSession = function () { + + return session; + + }; + + /** + * After a XR session has been requested usually with one of the `*Button` modules, it + * is injected into the renderer with this method. This method triggers the start of + * the actual XR rendering. + * + * @async + * @param {XRSession} value - The XR session to set. + * @return {Promise} A Promise that resolves when the session has been set. + */ + this.setSession = async function ( value ) { + + session = value; + + if ( session !== null ) { + + initialRenderTarget = renderer.getRenderTarget(); + + session.addEventListener( 'select', onSessionEvent ); + session.addEventListener( 'selectstart', onSessionEvent ); + session.addEventListener( 'selectend', onSessionEvent ); + session.addEventListener( 'squeeze', onSessionEvent ); + session.addEventListener( 'squeezestart', onSessionEvent ); + session.addEventListener( 'squeezeend', onSessionEvent ); + session.addEventListener( 'end', onSessionEnd ); + session.addEventListener( 'inputsourceschange', onInputSourcesChange ); + + if ( attributes.xrCompatible !== true ) { + + await gl.makeXRCompatible(); + + } + + currentPixelRatio = renderer.getPixelRatio(); + renderer.getSize( currentSize ); + + // Check that the browser implements the necessary APIs to use an + // XRProjectionLayer rather than an XRWebGLLayer + const useLayers = typeof XRWebGLBinding !== 'undefined' && 'createProjectionLayer' in XRWebGLBinding.prototype; + + if ( ! useLayers ) { + + const layerInit = { + antialias: attributes.antialias, + alpha: true, + depth: attributes.depth, + stencil: attributes.stencil, + framebufferScaleFactor: framebufferScaleFactor + }; + + glBaseLayer = new XRWebGLLayer( session, gl, layerInit ); + + session.updateRenderState( { baseLayer: glBaseLayer } ); + + renderer.setPixelRatio( 1 ); + renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false ); + + newRenderTarget = new WebGLRenderTarget( + glBaseLayer.framebufferWidth, + glBaseLayer.framebufferHeight, + { + format: RGBAFormat, + type: UnsignedByteType, + colorSpace: renderer.outputColorSpace, + stencilBuffer: attributes.stencil, + resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ), + resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false ) + + } + ); + + } else { + + let depthFormat = null; + let depthType = null; + let glDepthFormat = null; + + if ( attributes.depth ) { + + glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24; + depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat; + depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType; + + } + + const projectionlayerInit = { + colorFormat: gl.RGBA8, + depthFormat: glDepthFormat, + scaleFactor: framebufferScaleFactor + }; + + glBinding = new XRWebGLBinding( session, gl ); + + glProjLayer = glBinding.createProjectionLayer( projectionlayerInit ); + + session.updateRenderState( { layers: [ glProjLayer ] } ); + + renderer.setPixelRatio( 1 ); + renderer.setSize( glProjLayer.textureWidth, glProjLayer.textureHeight, false ); + + newRenderTarget = new WebGLRenderTarget( + glProjLayer.textureWidth, + glProjLayer.textureHeight, + { + format: RGBAFormat, + type: UnsignedByteType, + depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ), + stencilBuffer: attributes.stencil, + colorSpace: renderer.outputColorSpace, + samples: attributes.antialias ? 4 : 0, + resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ), + resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false ) + } ); + + } + + newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278 + + this.setFoveation( foveation ); + + customReferenceSpace = null; + referenceSpace = await session.requestReferenceSpace( referenceSpaceType ); + + animation.setContext( session ); + animation.start(); + + scope.isPresenting = true; + + scope.dispatchEvent( { type: 'sessionstart' } ); + + } + + }; + + /** + * Returns the environment blend mode from the current XR session. + * + * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session. + */ + this.getEnvironmentBlendMode = function () { + + if ( session !== null ) { + + return session.environmentBlendMode; + + } + + }; + + /** + * Returns the current depth texture computed via depth sensing. + * + * @return {?Texture} The depth texture. + */ + this.getDepthTexture = function () { + + return depthSensing.getDepthTexture(); + + }; + + function onInputSourcesChange( event ) { + + // Notify disconnected + + for ( let i = 0; i < event.removed.length; i ++ ) { + + const inputSource = event.removed[ i ]; + const index = controllerInputSources.indexOf( inputSource ); + + if ( index >= 0 ) { + + controllerInputSources[ index ] = null; + controllers[ index ].disconnect( inputSource ); + + } + + } + + // Notify connected + + for ( let i = 0; i < event.added.length; i ++ ) { + + const inputSource = event.added[ i ]; + + let controllerIndex = controllerInputSources.indexOf( inputSource ); + + if ( controllerIndex === -1 ) { + + // Assign input source a controller that currently has no input source + + for ( let i = 0; i < controllers.length; i ++ ) { + + if ( i >= controllerInputSources.length ) { + + controllerInputSources.push( inputSource ); + controllerIndex = i; + break; + + } else if ( controllerInputSources[ i ] === null ) { + + controllerInputSources[ i ] = inputSource; + controllerIndex = i; + break; + + } + + } + + // If all controllers do currently receive input we ignore new ones + + if ( controllerIndex === -1 ) break; + + } + + const controller = controllers[ controllerIndex ]; + + if ( controller ) { + + controller.connect( inputSource ); + + } + + } + + } + + // + + const cameraLPos = new Vector3(); + const cameraRPos = new Vector3(); + + /** + * Assumes 2 cameras that are parallel and share an X-axis, and that + * the cameras' projection and world matrices have already been set. + * And that near and far planes are identical for both cameras. + * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765 + * + * @param {ArrayCamera} camera - The camera to update. + * @param {PerspectiveCamera} cameraL - The left camera. + * @param {PerspectiveCamera} cameraR - The right camera. + */ + function setProjectionFromUnion( camera, cameraL, cameraR ) { + + cameraLPos.setFromMatrixPosition( cameraL.matrixWorld ); + cameraRPos.setFromMatrixPosition( cameraR.matrixWorld ); + + const ipd = cameraLPos.distanceTo( cameraRPos ); + + const projL = cameraL.projectionMatrix.elements; + const projR = cameraR.projectionMatrix.elements; + + // VR systems will have identical far and near planes, and + // most likely identical top and bottom frustum extents. + // Use the left camera for these values. + const near = projL[ 14 ] / ( projL[ 10 ] - 1 ); + const far = projL[ 14 ] / ( projL[ 10 ] + 1 ); + const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ]; + const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ]; + + const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ]; + const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ]; + const left = near * leftFov; + const right = near * rightFov; + + // Calculate the new camera's position offset from the + // left camera. xOffset should be roughly half `ipd`. + const zOffset = ipd / ( - leftFov + rightFov ); + const xOffset = zOffset * - leftFov; + + // TODO: Better way to apply this offset? + cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale ); + camera.translateX( xOffset ); + camera.translateZ( zOffset ); + camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale ); + camera.matrixWorldInverse.copy( camera.matrixWorld ).invert(); + + // Check if the projection uses an infinite far plane. + if ( projL[ 10 ] === -1 ) { + + // Use the projection matrix from the left eye. + // The camera offset is sufficient to include the view volumes + // of both eyes (assuming symmetric projections). + camera.projectionMatrix.copy( cameraL.projectionMatrix ); + camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse ); + + } else { + + // Find the union of the frustum values of the cameras and scale + // the values so that the near plane's position does not change in world space, + // although must now be relative to the new union camera. + const near2 = near + zOffset; + const far2 = far + zOffset; + const left2 = left - xOffset; + const right2 = right + ( ipd - xOffset ); + const top2 = topFov * far / far2 * near2; + const bottom2 = bottomFov * far / far2 * near2; + + camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 ); + camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert(); + + } + + } + + function updateCamera( camera, parent ) { + + if ( parent === null ) { + + camera.matrixWorld.copy( camera.matrix ); + + } else { + + camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix ); + + } + + camera.matrixWorldInverse.copy( camera.matrixWorld ).invert(); + + } + + /** + * Updates the state of the XR camera. Use this method on app level if you + * set cameraAutoUpdate` to `false`. The method requires the non-XR + * camera of the scene as a parameter. The passed in camera's transformation + * is automatically adjusted to the position of the XR camera when calling + * this method. + * + * @param {Camera} camera - The camera. + */ + this.updateCamera = function ( camera ) { + + if ( session === null ) return; + + let depthNear = camera.near; + let depthFar = camera.far; + + if ( depthSensing.texture !== null ) { + + if ( depthSensing.depthNear > 0 ) depthNear = depthSensing.depthNear; + if ( depthSensing.depthFar > 0 ) depthFar = depthSensing.depthFar; + + } + + cameraXR.near = cameraR.near = cameraL.near = depthNear; + cameraXR.far = cameraR.far = cameraL.far = depthFar; + + if ( _currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far ) { + + // Note that the new renderState won't apply until the next frame. See #18320 + + session.updateRenderState( { + depthNear: cameraXR.near, + depthFar: cameraXR.far + } ); + + _currentDepthNear = cameraXR.near; + _currentDepthFar = cameraXR.far; + + } + + cameraL.layers.mask = camera.layers.mask | 0b010; + cameraR.layers.mask = camera.layers.mask | 0b100; + cameraXR.layers.mask = cameraL.layers.mask | cameraR.layers.mask; + + const parent = camera.parent; + const cameras = cameraXR.cameras; + + updateCamera( cameraXR, parent ); + + for ( let i = 0; i < cameras.length; i ++ ) { + + updateCamera( cameras[ i ], parent ); + + } + + // update projection matrix for proper view frustum culling + + if ( cameras.length === 2 ) { + + setProjectionFromUnion( cameraXR, cameraL, cameraR ); + + } else { + + // assume single camera setup (AR) + + cameraXR.projectionMatrix.copy( cameraL.projectionMatrix ); + + } + + // update user camera and its children + + updateUserCamera( camera, cameraXR, parent ); + + }; + + function updateUserCamera( camera, cameraXR, parent ) { + + if ( parent === null ) { + + camera.matrix.copy( cameraXR.matrixWorld ); + + } else { + + camera.matrix.copy( parent.matrixWorld ); + camera.matrix.invert(); + camera.matrix.multiply( cameraXR.matrixWorld ); + + } + + camera.matrix.decompose( camera.position, camera.quaternion, camera.scale ); + camera.updateMatrixWorld( true ); + + camera.projectionMatrix.copy( cameraXR.projectionMatrix ); + camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse ); + + if ( camera.isPerspectiveCamera ) { + + camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] ); + camera.zoom = 1; + + } + + } + + /** + * Returns an instance of {@link ArrayCamera} which represents the XR camera + * of the active XR session. For each view it holds a separate camera object. + * + * The camera's `fov` is currently not used and does not reflect the fov of + * the XR camera. If you need the fov on app level, you have to compute in + * manually from the XR camera's projection matrices. + * + * @return {ArrayCamera} The XR camera. + */ + this.getCamera = function () { + + return cameraXR; + + }; + + /** + * Returns the amount of foveation used by the XR compositor for the projection layer. + * + * @return {number} The amount of foveation. + */ + this.getFoveation = function () { + + if ( glProjLayer === null && glBaseLayer === null ) { + + return undefined; + + } + + return foveation; + + }; + + /** + * Sets the foveation value. + * + * @param {number} value - A number in the range `[0,1]` where `0` means no foveation (full resolution) + * and `1` means maximum foveation (the edges render at lower resolution). + */ + this.setFoveation = function ( value ) { + + // 0 = no foveation = full resolution + // 1 = maximum foveation = the edges render at lower resolution + + foveation = value; + + if ( glProjLayer !== null ) { + + glProjLayer.fixedFoveation = value; + + } + + if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) { + + glBaseLayer.fixedFoveation = value; + + } + + }; + + /** + * Returns `true` if depth sensing is supported. + * + * @return {boolean} Whether depth sensing is supported or not. + */ + this.hasDepthSensing = function () { + + return depthSensing.texture !== null; + + }; + + /** + * Returns the depth sensing mesh. + * + * @return {Mesh} The depth sensing mesh. + */ + this.getDepthSensingMesh = function () { + + return depthSensing.getMesh( cameraXR ); + + }; + + // Animation Loop + + let onAnimationFrameCallback = null; + + function onAnimationFrame( time, frame ) { + + pose = frame.getViewerPose( customReferenceSpace || referenceSpace ); + xrFrame = frame; + + if ( pose !== null ) { + + const views = pose.views; + + if ( glBaseLayer !== null ) { + + renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer ); + renderer.setRenderTarget( newRenderTarget ); + + } + + let cameraXRNeedsUpdate = false; + + // check if it's necessary to rebuild cameraXR's camera list + + if ( views.length !== cameraXR.cameras.length ) { + + cameraXR.cameras.length = 0; + cameraXRNeedsUpdate = true; + + } + + for ( let i = 0; i < views.length; i ++ ) { + + const view = views[ i ]; + + let viewport = null; + + if ( glBaseLayer !== null ) { + + viewport = glBaseLayer.getViewport( view ); + + } else { + + const glSubImage = glBinding.getViewSubImage( glProjLayer, view ); + viewport = glSubImage.viewport; + + // For side-by-side projection, we only produce a single texture for both eyes. + if ( i === 0 ) { + + renderer.setRenderTargetTextures( + newRenderTarget, + glSubImage.colorTexture, + glSubImage.depthStencilTexture ); + + renderer.setRenderTarget( newRenderTarget ); + + } + + } + + let camera = cameras[ i ]; + + if ( camera === undefined ) { + + camera = new PerspectiveCamera(); + camera.layers.enable( i ); + camera.viewport = new Vector4(); + cameras[ i ] = camera; + + } + + camera.matrix.fromArray( view.transform.matrix ); + camera.matrix.decompose( camera.position, camera.quaternion, camera.scale ); + camera.projectionMatrix.fromArray( view.projectionMatrix ); + camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert(); + camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height ); + + if ( i === 0 ) { + + cameraXR.matrix.copy( camera.matrix ); + cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale ); + + } + + if ( cameraXRNeedsUpdate === true ) { + + cameraXR.cameras.push( camera ); + + } + + } + + // + + const enabledFeatures = session.enabledFeatures; + const gpuDepthSensingEnabled = enabledFeatures && + enabledFeatures.includes( 'depth-sensing' ) && + session.depthUsage == 'gpu-optimized'; + + if ( gpuDepthSensingEnabled && glBinding ) { + + const depthData = glBinding.getDepthInformation( views[ 0 ] ); + + if ( depthData && depthData.isValid && depthData.texture ) { + + depthSensing.init( renderer, depthData, session.renderState ); + + } + + } + + } + + // + + for ( let i = 0; i < controllers.length; i ++ ) { + + const inputSource = controllerInputSources[ i ]; + const controller = controllers[ i ]; + + if ( inputSource !== null && controller !== undefined ) { + + controller.update( inputSource, frame, customReferenceSpace || referenceSpace ); + + } + + } + + if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame ); + + if ( frame.detectedPlanes ) { + + scope.dispatchEvent( { type: 'planesdetected', data: frame } ); + + } + + xrFrame = null; + + } + + const animation = new WebGLAnimation(); + + animation.setAnimationLoop( onAnimationFrame ); + + this.setAnimationLoop = function ( callback ) { + + onAnimationFrameCallback = callback; + + }; + + this.dispose = function () {}; + + } + +} + +const _e1 = /*@__PURE__*/ new Euler(); +const _m1 = /*@__PURE__*/ new Matrix4(); + +function WebGLMaterials( renderer, properties ) { + + function refreshTransformUniform( map, uniform ) { + + if ( map.matrixAutoUpdate === true ) { + + map.updateMatrix(); + + } + + uniform.value.copy( map.matrix ); + + } + + function refreshFogUniforms( uniforms, fog ) { + + fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) ); + + if ( fog.isFog ) { + + uniforms.fogNear.value = fog.near; + uniforms.fogFar.value = fog.far; + + } else if ( fog.isFogExp2 ) { + + uniforms.fogDensity.value = fog.density; + + } + + } + + function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) { + + if ( material.isMeshBasicMaterial ) { + + refreshUniformsCommon( uniforms, material ); + + } else if ( material.isMeshLambertMaterial ) { + + refreshUniformsCommon( uniforms, material ); + + } else if ( material.isMeshToonMaterial ) { + + refreshUniformsCommon( uniforms, material ); + refreshUniformsToon( uniforms, material ); + + } else if ( material.isMeshPhongMaterial ) { + + refreshUniformsCommon( uniforms, material ); + refreshUniformsPhong( uniforms, material ); + + } else if ( material.isMeshStandardMaterial ) { + + refreshUniformsCommon( uniforms, material ); + refreshUniformsStandard( uniforms, material ); + + if ( material.isMeshPhysicalMaterial ) { + + refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ); + + } + + } else if ( material.isMeshMatcapMaterial ) { + + refreshUniformsCommon( uniforms, material ); + refreshUniformsMatcap( uniforms, material ); + + } else if ( material.isMeshDepthMaterial ) { + + refreshUniformsCommon( uniforms, material ); + + } else if ( material.isMeshDistanceMaterial ) { + + refreshUniformsCommon( uniforms, material ); + refreshUniformsDistance( uniforms, material ); + + } else if ( material.isMeshNormalMaterial ) { + + refreshUniformsCommon( uniforms, material ); + + } else if ( material.isLineBasicMaterial ) { + + refreshUniformsLine( uniforms, material ); + + if ( material.isLineDashedMaterial ) { + + refreshUniformsDash( uniforms, material ); + + } + + } else if ( material.isPointsMaterial ) { + + refreshUniformsPoints( uniforms, material, pixelRatio, height ); + + } else if ( material.isSpriteMaterial ) { + + refreshUniformsSprites( uniforms, material ); + + } else if ( material.isShadowMaterial ) { + + uniforms.color.value.copy( material.color ); + uniforms.opacity.value = material.opacity; + + } else if ( material.isShaderMaterial ) { + + material.uniformsNeedUpdate = false; // #15581 + + } + + } + + function refreshUniformsCommon( uniforms, material ) { + + uniforms.opacity.value = material.opacity; + + if ( material.color ) { + + uniforms.diffuse.value.copy( material.color ); + + } + + if ( material.emissive ) { + + uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity ); + + } + + if ( material.map ) { + + uniforms.map.value = material.map; + + refreshTransformUniform( material.map, uniforms.mapTransform ); + + } + + if ( material.alphaMap ) { + + uniforms.alphaMap.value = material.alphaMap; + + refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform ); + + } + + if ( material.bumpMap ) { + + uniforms.bumpMap.value = material.bumpMap; + + refreshTransformUniform( material.bumpMap, uniforms.bumpMapTransform ); + + uniforms.bumpScale.value = material.bumpScale; + + if ( material.side === BackSide ) { + + uniforms.bumpScale.value *= -1; + + } + + } + + if ( material.normalMap ) { + + uniforms.normalMap.value = material.normalMap; + + refreshTransformUniform( material.normalMap, uniforms.normalMapTransform ); + + uniforms.normalScale.value.copy( material.normalScale ); + + if ( material.side === BackSide ) { + + uniforms.normalScale.value.negate(); + + } + + } + + if ( material.displacementMap ) { + + uniforms.displacementMap.value = material.displacementMap; + + refreshTransformUniform( material.displacementMap, uniforms.displacementMapTransform ); + + uniforms.displacementScale.value = material.displacementScale; + uniforms.displacementBias.value = material.displacementBias; + + } + + if ( material.emissiveMap ) { + + uniforms.emissiveMap.value = material.emissiveMap; + + refreshTransformUniform( material.emissiveMap, uniforms.emissiveMapTransform ); + + } + + if ( material.specularMap ) { + + uniforms.specularMap.value = material.specularMap; + + refreshTransformUniform( material.specularMap, uniforms.specularMapTransform ); + + } + + if ( material.alphaTest > 0 ) { + + uniforms.alphaTest.value = material.alphaTest; + + } + + const materialProperties = properties.get( material ); + + const envMap = materialProperties.envMap; + const envMapRotation = materialProperties.envMapRotation; + + if ( envMap ) { + + uniforms.envMap.value = envMap; + + _e1.copy( envMapRotation ); + + // accommodate left-handed frame + _e1.x *= -1; _e1.y *= -1; _e1.z *= -1; + + if ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) { + + // environment maps which are not cube render targets or PMREMs follow a different convention + _e1.y *= -1; + _e1.z *= -1; + + } + + uniforms.envMapRotation.value.setFromMatrix4( _m1.makeRotationFromEuler( _e1 ) ); + + uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? -1 : 1; + + uniforms.reflectivity.value = material.reflectivity; + uniforms.ior.value = material.ior; + uniforms.refractionRatio.value = material.refractionRatio; + + } + + if ( material.lightMap ) { + + uniforms.lightMap.value = material.lightMap; + uniforms.lightMapIntensity.value = material.lightMapIntensity; + + refreshTransformUniform( material.lightMap, uniforms.lightMapTransform ); + + } + + if ( material.aoMap ) { + + uniforms.aoMap.value = material.aoMap; + uniforms.aoMapIntensity.value = material.aoMapIntensity; + + refreshTransformUniform( material.aoMap, uniforms.aoMapTransform ); + + } + + } + + function refreshUniformsLine( uniforms, material ) { + + uniforms.diffuse.value.copy( material.color ); + uniforms.opacity.value = material.opacity; + + if ( material.map ) { + + uniforms.map.value = material.map; + + refreshTransformUniform( material.map, uniforms.mapTransform ); + + } + + } + + function refreshUniformsDash( uniforms, material ) { + + uniforms.dashSize.value = material.dashSize; + uniforms.totalSize.value = material.dashSize + material.gapSize; + uniforms.scale.value = material.scale; + + } + + function refreshUniformsPoints( uniforms, material, pixelRatio, height ) { + + uniforms.diffuse.value.copy( material.color ); + uniforms.opacity.value = material.opacity; + uniforms.size.value = material.size * pixelRatio; + uniforms.scale.value = height * 0.5; + + if ( material.map ) { + + uniforms.map.value = material.map; + + refreshTransformUniform( material.map, uniforms.uvTransform ); + + } + + if ( material.alphaMap ) { + + uniforms.alphaMap.value = material.alphaMap; + + refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform ); + + } + + if ( material.alphaTest > 0 ) { + + uniforms.alphaTest.value = material.alphaTest; + + } + + } + + function refreshUniformsSprites( uniforms, material ) { + + uniforms.diffuse.value.copy( material.color ); + uniforms.opacity.value = material.opacity; + uniforms.rotation.value = material.rotation; + + if ( material.map ) { + + uniforms.map.value = material.map; + + refreshTransformUniform( material.map, uniforms.mapTransform ); + + } + + if ( material.alphaMap ) { + + uniforms.alphaMap.value = material.alphaMap; + + refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform ); + + } + + if ( material.alphaTest > 0 ) { + + uniforms.alphaTest.value = material.alphaTest; + + } + + } + + function refreshUniformsPhong( uniforms, material ) { + + uniforms.specular.value.copy( material.specular ); + uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 ) + + } + + function refreshUniformsToon( uniforms, material ) { + + if ( material.gradientMap ) { + + uniforms.gradientMap.value = material.gradientMap; + + } + + } + + function refreshUniformsStandard( uniforms, material ) { + + uniforms.metalness.value = material.metalness; + + if ( material.metalnessMap ) { + + uniforms.metalnessMap.value = material.metalnessMap; + + refreshTransformUniform( material.metalnessMap, uniforms.metalnessMapTransform ); + + } + + uniforms.roughness.value = material.roughness; + + if ( material.roughnessMap ) { + + uniforms.roughnessMap.value = material.roughnessMap; + + refreshTransformUniform( material.roughnessMap, uniforms.roughnessMapTransform ); + + } + + if ( material.envMap ) { + + //uniforms.envMap.value = material.envMap; // part of uniforms common + + uniforms.envMapIntensity.value = material.envMapIntensity; + + } + + } + + function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) { + + uniforms.ior.value = material.ior; // also part of uniforms common + + if ( material.sheen > 0 ) { + + uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen ); + + uniforms.sheenRoughness.value = material.sheenRoughness; + + if ( material.sheenColorMap ) { + + uniforms.sheenColorMap.value = material.sheenColorMap; + + refreshTransformUniform( material.sheenColorMap, uniforms.sheenColorMapTransform ); + + } + + if ( material.sheenRoughnessMap ) { + + uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap; + + refreshTransformUniform( material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform ); + + } + + } + + if ( material.clearcoat > 0 ) { + + uniforms.clearcoat.value = material.clearcoat; + uniforms.clearcoatRoughness.value = material.clearcoatRoughness; + + if ( material.clearcoatMap ) { + + uniforms.clearcoatMap.value = material.clearcoatMap; + + refreshTransformUniform( material.clearcoatMap, uniforms.clearcoatMapTransform ); + + } + + if ( material.clearcoatRoughnessMap ) { + + uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap; + + refreshTransformUniform( material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform ); + + } + + if ( material.clearcoatNormalMap ) { + + uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap; + + refreshTransformUniform( material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform ); + + uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale ); + + if ( material.side === BackSide ) { + + uniforms.clearcoatNormalScale.value.negate(); + + } + + } + + } + + if ( material.dispersion > 0 ) { + + uniforms.dispersion.value = material.dispersion; + + } + + if ( material.iridescence > 0 ) { + + uniforms.iridescence.value = material.iridescence; + uniforms.iridescenceIOR.value = material.iridescenceIOR; + uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ]; + uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ]; + + if ( material.iridescenceMap ) { + + uniforms.iridescenceMap.value = material.iridescenceMap; + + refreshTransformUniform( material.iridescenceMap, uniforms.iridescenceMapTransform ); + + } + + if ( material.iridescenceThicknessMap ) { + + uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap; + + refreshTransformUniform( material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform ); + + } + + } + + if ( material.transmission > 0 ) { + + uniforms.transmission.value = material.transmission; + uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture; + uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height ); + + if ( material.transmissionMap ) { + + uniforms.transmissionMap.value = material.transmissionMap; + + refreshTransformUniform( material.transmissionMap, uniforms.transmissionMapTransform ); + + } + + uniforms.thickness.value = material.thickness; + + if ( material.thicknessMap ) { + + uniforms.thicknessMap.value = material.thicknessMap; + + refreshTransformUniform( material.thicknessMap, uniforms.thicknessMapTransform ); + + } + + uniforms.attenuationDistance.value = material.attenuationDistance; + uniforms.attenuationColor.value.copy( material.attenuationColor ); + + } + + if ( material.anisotropy > 0 ) { + + uniforms.anisotropyVector.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) ); + + if ( material.anisotropyMap ) { + + uniforms.anisotropyMap.value = material.anisotropyMap; + + refreshTransformUniform( material.anisotropyMap, uniforms.anisotropyMapTransform ); + + } + + } + + uniforms.specularIntensity.value = material.specularIntensity; + uniforms.specularColor.value.copy( material.specularColor ); + + if ( material.specularColorMap ) { + + uniforms.specularColorMap.value = material.specularColorMap; + + refreshTransformUniform( material.specularColorMap, uniforms.specularColorMapTransform ); + + } + + if ( material.specularIntensityMap ) { + + uniforms.specularIntensityMap.value = material.specularIntensityMap; + + refreshTransformUniform( material.specularIntensityMap, uniforms.specularIntensityMapTransform ); + + } + + } + + function refreshUniformsMatcap( uniforms, material ) { + + if ( material.matcap ) { + + uniforms.matcap.value = material.matcap; + + } + + } + + function refreshUniformsDistance( uniforms, material ) { + + const light = properties.get( material ).light; + + uniforms.referencePosition.value.setFromMatrixPosition( light.matrixWorld ); + uniforms.nearDistance.value = light.shadow.camera.near; + uniforms.farDistance.value = light.shadow.camera.far; + + } + + return { + refreshFogUniforms: refreshFogUniforms, + refreshMaterialUniforms: refreshMaterialUniforms + }; + +} + +function WebGLUniformsGroups( gl, info, capabilities, state ) { + + let buffers = {}; + let updateList = {}; + let allocatedBindingPoints = []; + + const maxBindingPoints = gl.getParameter( gl.MAX_UNIFORM_BUFFER_BINDINGS ); // binding points are global whereas block indices are per shader program + + function bind( uniformsGroup, program ) { + + const webglProgram = program.program; + state.uniformBlockBinding( uniformsGroup, webglProgram ); + + } + + function update( uniformsGroup, program ) { + + let buffer = buffers[ uniformsGroup.id ]; + + if ( buffer === undefined ) { + + prepareUniformsGroup( uniformsGroup ); + + buffer = createBuffer( uniformsGroup ); + buffers[ uniformsGroup.id ] = buffer; + + uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose ); + + } + + // ensure to update the binding points/block indices mapping for this program + + const webglProgram = program.program; + state.updateUBOMapping( uniformsGroup, webglProgram ); + + // update UBO once per frame + + const frame = info.render.frame; + + if ( updateList[ uniformsGroup.id ] !== frame ) { + + updateBufferData( uniformsGroup ); + + updateList[ uniformsGroup.id ] = frame; + + } + + } + + function createBuffer( uniformsGroup ) { + + // the setup of an UBO is independent of a particular shader program but global + + const bindingPointIndex = allocateBindingPointIndex(); + uniformsGroup.__bindingPointIndex = bindingPointIndex; + + const buffer = gl.createBuffer(); + const size = uniformsGroup.__size; + const usage = uniformsGroup.usage; + + gl.bindBuffer( gl.UNIFORM_BUFFER, buffer ); + gl.bufferData( gl.UNIFORM_BUFFER, size, usage ); + gl.bindBuffer( gl.UNIFORM_BUFFER, null ); + gl.bindBufferBase( gl.UNIFORM_BUFFER, bindingPointIndex, buffer ); + + return buffer; + + } + + function allocateBindingPointIndex() { + + for ( let i = 0; i < maxBindingPoints; i ++ ) { + + if ( allocatedBindingPoints.indexOf( i ) === -1 ) { + + allocatedBindingPoints.push( i ); + return i; + + } + + } + + console.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' ); + + return 0; + + } + + function updateBufferData( uniformsGroup ) { + + const buffer = buffers[ uniformsGroup.id ]; + const uniforms = uniformsGroup.uniforms; + const cache = uniformsGroup.__cache; + + gl.bindBuffer( gl.UNIFORM_BUFFER, buffer ); + + for ( let i = 0, il = uniforms.length; i < il; i ++ ) { + + const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ]; + + for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) { + + const uniform = uniformArray[ j ]; + + if ( hasUniformChanged( uniform, i, j, cache ) === true ) { + + const offset = uniform.__offset; + + const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ]; + + let arrayOffset = 0; + + for ( let k = 0; k < values.length; k ++ ) { + + const value = values[ k ]; + + const info = getUniformSize( value ); + + // TODO add integer and struct support + if ( typeof value === 'number' || typeof value === 'boolean' ) { + + uniform.__data[ 0 ] = value; + gl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data ); + + } else if ( value.isMatrix3 ) { + + // manually converting 3x3 to 3x4 + + uniform.__data[ 0 ] = value.elements[ 0 ]; + uniform.__data[ 1 ] = value.elements[ 1 ]; + uniform.__data[ 2 ] = value.elements[ 2 ]; + uniform.__data[ 3 ] = 0; + uniform.__data[ 4 ] = value.elements[ 3 ]; + uniform.__data[ 5 ] = value.elements[ 4 ]; + uniform.__data[ 6 ] = value.elements[ 5 ]; + uniform.__data[ 7 ] = 0; + uniform.__data[ 8 ] = value.elements[ 6 ]; + uniform.__data[ 9 ] = value.elements[ 7 ]; + uniform.__data[ 10 ] = value.elements[ 8 ]; + uniform.__data[ 11 ] = 0; + + } else { + + value.toArray( uniform.__data, arrayOffset ); + + arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT; + + } + + } + + gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data ); + + } + + } + + } + + gl.bindBuffer( gl.UNIFORM_BUFFER, null ); + + } + + function hasUniformChanged( uniform, index, indexArray, cache ) { + + const value = uniform.value; + const indexString = index + '_' + indexArray; + + if ( cache[ indexString ] === undefined ) { + + // cache entry does not exist so far + + if ( typeof value === 'number' || typeof value === 'boolean' ) { + + cache[ indexString ] = value; + + } else { + + cache[ indexString ] = value.clone(); + + } + + return true; + + } else { + + const cachedObject = cache[ indexString ]; + + // compare current value with cached entry + + if ( typeof value === 'number' || typeof value === 'boolean' ) { + + if ( cachedObject !== value ) { + + cache[ indexString ] = value; + return true; + + } + + } else { + + if ( cachedObject.equals( value ) === false ) { + + cachedObject.copy( value ); + return true; + + } + + } + + } + + return false; + + } + + function prepareUniformsGroup( uniformsGroup ) { + + // determine total buffer size according to the STD140 layout + // Hint: STD140 is the only supported layout in WebGL 2 + + const uniforms = uniformsGroup.uniforms; + + let offset = 0; // global buffer offset in bytes + const chunkSize = 16; // size of a chunk in bytes + + for ( let i = 0, l = uniforms.length; i < l; i ++ ) { + + const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ]; + + for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) { + + const uniform = uniformArray[ j ]; + + const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ]; + + for ( let k = 0, kl = values.length; k < kl; k ++ ) { + + const value = values[ k ]; + + const info = getUniformSize( value ); + + const chunkOffset = offset % chunkSize; // offset in the current chunk + const chunkPadding = chunkOffset % info.boundary; // required padding to match boundary + const chunkStart = chunkOffset + chunkPadding; // the start position in the current chunk for the data + + offset += chunkPadding; + + // Check for chunk overflow + if ( chunkStart !== 0 && ( chunkSize - chunkStart ) < info.storage ) { + + // Add padding and adjust offset + offset += ( chunkSize - chunkStart ); + + } + + // the following two properties will be used for partial buffer updates + uniform.__data = new Float32Array( info.storage / Float32Array.BYTES_PER_ELEMENT ); + uniform.__offset = offset; + + // Update the global offset + offset += info.storage; + + } + + } + + } + + // ensure correct final padding + + const chunkOffset = offset % chunkSize; + + if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset ); + + // + + uniformsGroup.__size = offset; + uniformsGroup.__cache = {}; + + return this; + + } + + function getUniformSize( value ) { + + const info = { + boundary: 0, // bytes + storage: 0 // bytes + }; + + // determine sizes according to STD140 + + if ( typeof value === 'number' || typeof value === 'boolean' ) { + + // float/int/bool + + info.boundary = 4; + info.storage = 4; + + } else if ( value.isVector2 ) { + + // vec2 + + info.boundary = 8; + info.storage = 8; + + } else if ( value.isVector3 || value.isColor ) { + + // vec3 + + info.boundary = 16; + info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes + + } else if ( value.isVector4 ) { + + // vec4 + + info.boundary = 16; + info.storage = 16; + + } else if ( value.isMatrix3 ) { + + // mat3 (in STD140 a 3x3 matrix is represented as 3x4) + + info.boundary = 48; + info.storage = 48; + + } else if ( value.isMatrix4 ) { + + // mat4 + + info.boundary = 64; + info.storage = 64; + + } else if ( value.isTexture ) { + + console.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' ); + + } else { + + console.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value ); + + } + + return info; + + } + + function onUniformsGroupsDispose( event ) { + + const uniformsGroup = event.target; + + uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose ); + + const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex ); + allocatedBindingPoints.splice( index, 1 ); + + gl.deleteBuffer( buffers[ uniformsGroup.id ] ); + + delete buffers[ uniformsGroup.id ]; + delete updateList[ uniformsGroup.id ]; + + } + + function dispose() { + + for ( const id in buffers ) { + + gl.deleteBuffer( buffers[ id ] ); + + } + + allocatedBindingPoints = []; + buffers = {}; + updateList = {}; + + } + + return { + + bind: bind, + update: update, + + dispose: dispose + + }; + +} + +/** + * This renderer uses WebGL 2 to display scenes. + * + * WebGL 1 is not supported since `r163`. + */ +class WebGLRenderer { + + /** + * Constructs a new WebGL renderer. + * + * @param {WebGLRenderer~Options} [parameters] - The configuration parameter. + */ + constructor( parameters = {} ) { + + const { + canvas = createCanvasElement(), + context = null, + depth = true, + stencil = false, + alpha = false, + antialias = false, + premultipliedAlpha = true, + preserveDrawingBuffer = false, + powerPreference = 'default', + failIfMajorPerformanceCaveat = false, + reverseDepthBuffer = false, + } = parameters; + + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ + this.isWebGLRenderer = true; + + let _alpha; + + if ( context !== null ) { + + if ( typeof WebGLRenderingContext !== 'undefined' && context instanceof WebGLRenderingContext ) { + + throw new Error( 'THREE.WebGLRenderer: WebGL 1 is not supported since r163.' ); + + } + + _alpha = context.getContextAttributes().alpha; + + } else { + + _alpha = alpha; + + } + + const uintClearColor = new Uint32Array( 4 ); + const intClearColor = new Int32Array( 4 ); + + let currentRenderList = null; + let currentRenderState = null; + + // render() can be called from within a callback triggered by another render. + // We track this so that the nested render call gets its list and state isolated from the parent render call. + + const renderListStack = []; + const renderStateStack = []; + + // public properties + + /** + * A canvas where the renderer draws its output.This is automatically created by the renderer + * in the constructor (if not provided already); you just need to add it to your page like so: + * ```js + * document.body.appendChild( renderer.domElement ); + * ``` + * + * @type {DOMElement} + */ + this.domElement = canvas; + + /** + * A object with debug configuration settings. + * + * - `checkShaderErrors`: If it is `true`, defines whether material shader programs are + * checked for errors during compilation and linkage process. It may be useful to disable + * this check in production for performance gain. It is strongly recommended to keep these + * checks enabled during development. If the shader does not compile and link - it will not + * work and associated material will not render. + * - `onShaderError(gl, program, glVertexShader,glFragmentShader)`: A callback function that + * can be used for custom error reporting. The callback receives the WebGL context, an instance + * of WebGLProgram as well two instances of WebGLShader representing the vertex and fragment shader. + * Assigning a custom function disables the default error reporting. + * + * @type {Object} + */ + this.debug = { + + /** + * Enables error checking and reporting when shader programs are being compiled. + * @type {boolean} + */ + checkShaderErrors: true, + /** + * Callback for custom error reporting. + * @type {?Function} + */ + onShaderError: null + }; + + // clearing + + /** + * Whether the renderer should automatically clear its output before rendering a frame or not. + * + * @type {boolean} + * @default true + */ + this.autoClear = true; + + /** + * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear + * the color buffer or not. + * + * @type {boolean} + * @default true + */ + this.autoClearColor = true; + + /** + * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear + * the depth buffer or not. + * + * @type {boolean} + * @default true + */ + this.autoClearDepth = true; + + /** + * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear + * the stencil buffer or not. + * + * @type {boolean} + * @default true + */ + this.autoClearStencil = true; + + // scene graph + + /** + * Whether the renderer should sort objects or not. + * + * Note: Sorting is used to attempt to properly render objects that have some + * degree of transparency. By definition, sorting objects may not work in all + * cases. Depending on the needs of application, it may be necessary to turn + * off sorting and use other methods to deal with transparency rendering e.g. + * manually determining each object's rendering order. + * + * @type {boolean} + * @default true + */ + this.sortObjects = true; + + // user-defined clipping + + /** + * User-defined clipping planes specified in world space. These planes apply globally. + * Points in space whose dot product with the plane is negative are cut away. + * + * @type {Array} + */ + this.clippingPlanes = []; + + /** + * Whether the renderer respects object-level clipping planes or not. + * + * @type {boolean} + * @default false + */ + this.localClippingEnabled = false; + + // tone mapping + + /** + * The tone mapping technique of the renderer. + * + * @type {(NoToneMapping|LinearToneMapping|ReinhardToneMapping|CineonToneMapping|ACESFilmicToneMapping|CustomToneMapping|AgXToneMapping|NeutralToneMapping)} + * @default NoToneMapping + */ + this.toneMapping = NoToneMapping; + + /** + * Exposure level of tone mapping. + * + * @type {number} + * @default 1 + */ + this.toneMappingExposure = 1.0; + + // transmission + + /** + * The normalized resolution scale for the transmission render target, measured in percentage + * of viewport dimensions. Lowering this value can result in significant performance improvements + * when using {@link MeshPhysicalMaterial#transmission}. + * + * @type {number} + * @default 1 + */ + this.transmissionResolutionScale = 1.0; + + // internal properties + + const _this = this; + + let _isContextLost = false; + + // internal state cache + + this._outputColorSpace = SRGBColorSpace; + + let _currentActiveCubeFace = 0; + let _currentActiveMipmapLevel = 0; + let _currentRenderTarget = null; + let _currentMaterialId = -1; + + let _currentCamera = null; + + const _currentViewport = new Vector4(); + const _currentScissor = new Vector4(); + let _currentScissorTest = null; + + const _currentClearColor = new Color( 0x000000 ); + let _currentClearAlpha = 0; + + // + + let _width = canvas.width; + let _height = canvas.height; + + let _pixelRatio = 1; + let _opaqueSort = null; + let _transparentSort = null; + + const _viewport = new Vector4( 0, 0, _width, _height ); + const _scissor = new Vector4( 0, 0, _width, _height ); + let _scissorTest = false; + + // frustum + + const _frustum = new Frustum(); + + // clipping + + let _clippingEnabled = false; + let _localClippingEnabled = false; + + // camera matrices cache + + const _currentProjectionMatrix = new Matrix4(); + const _projScreenMatrix = new Matrix4(); + + const _vector3 = new Vector3(); + + const _vector4 = new Vector4(); + + const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true }; + + let _renderBackground = false; + + function getTargetPixelRatio() { + + return _currentRenderTarget === null ? _pixelRatio : 1; + + } + + // initialize + + let _gl = context; + + function getContext( contextName, contextAttributes ) { + + return canvas.getContext( contextName, contextAttributes ); + + } + + try { + + const contextAttributes = { + alpha: true, + depth, + stencil, + antialias, + premultipliedAlpha, + preserveDrawingBuffer, + powerPreference, + failIfMajorPerformanceCaveat, + }; + + // OffscreenCanvas does not have setAttribute, see #22811 + if ( 'setAttribute' in canvas ) canvas.setAttribute( 'data-engine', `three.js r${REVISION}` ); + + // event listeners must be registered before WebGL context is created, see #12753 + canvas.addEventListener( 'webglcontextlost', onContextLost, false ); + canvas.addEventListener( 'webglcontextrestored', onContextRestore, false ); + canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false ); + + if ( _gl === null ) { + + const contextName = 'webgl2'; + + _gl = getContext( contextName, contextAttributes ); + + if ( _gl === null ) { + + if ( getContext( contextName ) ) { + + throw new Error( 'Error creating WebGL context with your selected attributes.' ); + + } else { + + throw new Error( 'Error creating WebGL context.' ); + + } + + } + + } + + } catch ( error ) { + + console.error( 'THREE.WebGLRenderer: ' + error.message ); + throw error; + + } + + let extensions, capabilities, state, info; + let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects; + let programCache, materials, renderLists, renderStates, clipping, shadowMap; + + let background, morphtargets, bufferRenderer, indexedBufferRenderer; + + let utils, bindingStates, uniformsGroups; + + function initGLContext() { + + extensions = new WebGLExtensions( _gl ); + extensions.init(); + + utils = new WebGLUtils( _gl, extensions ); + + capabilities = new WebGLCapabilities( _gl, extensions, parameters, utils ); + + state = new WebGLState( _gl, extensions ); + + if ( capabilities.reverseDepthBuffer && reverseDepthBuffer ) { + + state.buffers.depth.setReversed( true ); + + } + + info = new WebGLInfo( _gl ); + properties = new WebGLProperties(); + textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ); + cubemaps = new WebGLCubeMaps( _this ); + cubeuvmaps = new WebGLCubeUVMaps( _this ); + attributes = new WebGLAttributes( _gl ); + bindingStates = new WebGLBindingStates( _gl, attributes ); + geometries = new WebGLGeometries( _gl, attributes, info, bindingStates ); + objects = new WebGLObjects( _gl, geometries, attributes, info ); + morphtargets = new WebGLMorphtargets( _gl, capabilities, textures ); + clipping = new WebGLClipping( properties ); + programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ); + materials = new WebGLMaterials( _this, properties ); + renderLists = new WebGLRenderLists(); + renderStates = new WebGLRenderStates( extensions ); + background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha ); + shadowMap = new WebGLShadowMap( _this, objects, capabilities ); + uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state ); + + bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info ); + indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info ); + + info.programs = programCache.programs; + + /** + * Holds details about the capabilities of the current rendering context. + * + * @name WebGLRenderer#capabilities + * @type {WebGLRenderer~Capabilities} + */ + _this.capabilities = capabilities; + + /** + * Provides methods for retrieving and testing WebGL extensions. + * + * - `get(extensionName:string)`: Used to check whether a WebGL extension is supported + * and return the extension object if available. + * - `has(extensionName:string)`: returns `true` if the extension is supported. + * + * @name WebGLRenderer#extensions + * @type {Object} + */ + _this.extensions = extensions; + + /** + * Used to track properties of other objects like native WebGL objects. + * + * @name WebGLRenderer#properties + * @type {Object} + */ + _this.properties = properties; + + /** + * Manages the render lists of the renderer. + * + * @name WebGLRenderer#renderLists + * @type {Object} + */ + _this.renderLists = renderLists; + + + + /** + * Interface for managing shadows. + * + * @name WebGLRenderer#shadowMap + * @type {WebGLRenderer~ShadowMap} + */ + _this.shadowMap = shadowMap; + + /** + * Interface for managing the WebGL state. + * + * @name WebGLRenderer#state + * @type {Object} + */ + _this.state = state; + + /** + * Holds a series of statistical information about the GPU memory + * and the rendering process. Useful for debugging and monitoring. + * + * By default these data are reset at each render call but when having + * multiple render passes per frame (e.g. when using post processing) it can + * be preferred to reset with a custom pattern. First, set `autoReset` to + * `false`. + * ```js + * renderer.info.autoReset = false; + * ``` + * Call `reset()` whenever you have finished to render a single frame. + * ```js + * renderer.info.reset(); + * ``` + * + * @name WebGLRenderer#info + * @type {WebGLRenderer~Info} + */ + _this.info = info; + + } + + initGLContext(); + + // xr + + const xr = new WebXRManager( _this, _gl ); + + /** + * A reference to the XR manager. + * + * @type {WebXRManager} + */ + this.xr = xr; + + /** + * Returns the rendering context. + * + * @return {WebGL2RenderingContext} The rendering context. + */ + this.getContext = function () { + + return _gl; + + }; + + /** + * Returns the rendering context attributes. + * + * @return {WebGLContextAttributes} The rendering context attributes. + */ + this.getContextAttributes = function () { + + return _gl.getContextAttributes(); + + }; + + /** + * Simulates a loss of the WebGL context. This requires support for the `WEBGL_lose_context` extension. + */ + this.forceContextLoss = function () { + + const extension = extensions.get( 'WEBGL_lose_context' ); + if ( extension ) extension.loseContext(); + + }; + + /** + * Simulates a restore of the WebGL context. This requires support for the `WEBGL_lose_context` extension. + */ + this.forceContextRestore = function () { + + const extension = extensions.get( 'WEBGL_lose_context' ); + if ( extension ) extension.restoreContext(); + + }; + + /** + * Returns the pixel ratio. + * + * @return {number} The pixel ratio. + */ + this.getPixelRatio = function () { + + return _pixelRatio; + + }; + + /** + * Sets the given pixel ratio and resizes the canvas if necessary. + * + * @param {number} value - The pixel ratio. + */ + this.setPixelRatio = function ( value ) { + + if ( value === undefined ) return; + + _pixelRatio = value; + + this.setSize( _width, _height, false ); + + }; + + /** + * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio. + * + * @param {Vector2} target - The method writes the result in this target object. + * @return {Vector2} The renderer's size in logical pixels. + */ + this.getSize = function ( target ) { + + return target.set( _width, _height ); + + }; + + /** + * Resizes the output canvas to (width, height) with device pixel ratio taken + * into account, and also sets the viewport to fit that size, starting in (0, + * 0). Setting `updateStyle` to false prevents any style changes to the output canvas. + * + * @param {number} width - The width in logical pixels. + * @param {number} height - The height in logical pixels. + * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not. + */ + this.setSize = function ( width, height, updateStyle = true ) { + + if ( xr.isPresenting ) { + + console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' ); + return; + + } + + _width = width; + _height = height; + + canvas.width = Math.floor( width * _pixelRatio ); + canvas.height = Math.floor( height * _pixelRatio ); + + if ( updateStyle === true ) { + + canvas.style.width = width + 'px'; + canvas.style.height = height + 'px'; + + } + + this.setViewport( 0, 0, width, height ); + + }; + + /** + * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio. + * + * @param {Vector2} target - The method writes the result in this target object. + * @return {Vector2} The drawing buffer size. + */ + this.getDrawingBufferSize = function ( target ) { + + return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor(); + + }; + + /** + * This method allows to define the drawing buffer size by specifying + * width, height and pixel ratio all at once. The size of the drawing + * buffer is computed with this formula: + * ```js + * size.x = width * pixelRatio; + * size.y = height * pixelRatio; + * ``` + * + * @param {number} width - The width in logical pixels. + * @param {number} height - The height in logical pixels. + * @param {number} pixelRatio - The pixel ratio. + */ + this.setDrawingBufferSize = function ( width, height, pixelRatio ) { + + _width = width; + _height = height; + + _pixelRatio = pixelRatio; + + canvas.width = Math.floor( width * pixelRatio ); + canvas.height = Math.floor( height * pixelRatio ); + + this.setViewport( 0, 0, width, height ); + + }; + + /** + * Returns the current viewport definition. + * + * @param {Vector2} target - The method writes the result in this target object. + * @return {Vector2} The current viewport definition. + */ + this.getCurrentViewport = function ( target ) { + + return target.copy( _currentViewport ); + + }; + + /** + * Returns the viewport definition. + * + * @param {Vector4} target - The method writes the result in this target object. + * @return {Vector4} The viewport definition. + */ + this.getViewport = function ( target ) { + + return target.copy( _viewport ); + + }; + + /** + * Sets the viewport to render from `(x, y)` to `(x + width, y + height)`. + * + * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit. + * Or alternatively a four-component vector specifying all the parameters of the viewport. + * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit. + * @param {number} width - The width of the viewport in logical pixel unit. + * @param {number} height - The height of the viewport in logical pixel unit. + */ + this.setViewport = function ( x, y, width, height ) { + + if ( x.isVector4 ) { + + _viewport.set( x.x, x.y, x.z, x.w ); + + } else { + + _viewport.set( x, y, width, height ); + + } + + state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).round() ); + + }; + + /** + * Returns the scissor region. + * + * @param {Vector4} target - The method writes the result in this target object. + * @return {Vector4} The scissor region. + */ + this.getScissor = function ( target ) { + + return target.copy( _scissor ); + + }; + + /** + * Sets the scissor region to render from `(x, y)` to `(x + width, y + height)`. + * + * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the scissor region origin in logical pixel unit. + * Or alternatively a four-component vector specifying all the parameters of the scissor region. + * @param {number} y - The vertical coordinate for the lower left corner of the scissor region origin in logical pixel unit. + * @param {number} width - The width of the scissor region in logical pixel unit. + * @param {number} height - The height of the scissor region in logical pixel unit. + */ + this.setScissor = function ( x, y, width, height ) { + + if ( x.isVector4 ) { + + _scissor.set( x.x, x.y, x.z, x.w ); + + } else { + + _scissor.set( x, y, width, height ); + + } + + state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).round() ); + + }; + + /** + * Returns `true` if the scissor test is enabled. + * + * @return {boolean} Whether the scissor test is enabled or not. + */ + this.getScissorTest = function () { + + return _scissorTest; + + }; + + /** + * Enable or disable the scissor test. When this is enabled, only the pixels + * within the defined scissor area will be affected by further renderer + * actions. + * + * @param {boolean} boolean - Whether the scissor test is enabled or not. + */ + this.setScissorTest = function ( boolean ) { + + state.setScissorTest( _scissorTest = boolean ); + + }; + + /** + * Sets a custom opaque sort function for the render lists. Pass `null` + * to use the default `painterSortStable` function. + * + * @param {?Function} method - The opaque sort function. + */ + this.setOpaqueSort = function ( method ) { + + _opaqueSort = method; + + }; + + /** + * Sets a custom transparent sort function for the render lists. Pass `null` + * to use the default `reversePainterSortStable` function. + * + * @param {?Function} method - The opaque sort function. + */ + this.setTransparentSort = function ( method ) { + + _transparentSort = method; + + }; + + // Clearing + + /** + * Returns the clear color. + * + * @param {Color} target - The method writes the result in this target object. + * @return {Color} The clear color. + */ + this.getClearColor = function ( target ) { + + return target.copy( background.getClearColor() ); + + }; + + /** + * Sets the clear color and alpha. + * + * @param {Color} color - The clear color. + * @param {number} [alpha=1] - The clear alpha. + */ + this.setClearColor = function () { + + background.setClearColor( ...arguments ); + + }; + + /** + * Returns the clear alpha. Ranges within `[0,1]`. + * + * @return {number} The clear alpha. + */ + this.getClearAlpha = function () { + + return background.getClearAlpha(); + + }; + + /** + * Sets the clear alpha. + * + * @param {number} alpha - The clear alpha. + */ + this.setClearAlpha = function () { + + background.setClearAlpha( ...arguments ); + + }; + + /** + * Tells the renderer to clear its color, depth or stencil drawing buffer(s). + * This method initializes the buffers to the current clear color values. + * + * @param {boolean} [color=true] - Whether the color buffer should be cleared or not. + * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not. + * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not. + */ + this.clear = function ( color = true, depth = true, stencil = true ) { + + let bits = 0; + + if ( color ) { + + // check if we're trying to clear an integer target + let isIntegerFormat = false; + if ( _currentRenderTarget !== null ) { + + const targetFormat = _currentRenderTarget.texture.format; + isIntegerFormat = targetFormat === RGBAIntegerFormat || + targetFormat === RGIntegerFormat || + targetFormat === RedIntegerFormat; + + } + + // use the appropriate clear functions to clear the target if it's a signed + // or unsigned integer target + if ( isIntegerFormat ) { + + const targetType = _currentRenderTarget.texture.type; + const isUnsignedType = targetType === UnsignedByteType || + targetType === UnsignedIntType || + targetType === UnsignedShortType || + targetType === UnsignedInt248Type || + targetType === UnsignedShort4444Type || + targetType === UnsignedShort5551Type; + + const clearColor = background.getClearColor(); + const a = background.getClearAlpha(); + const r = clearColor.r; + const g = clearColor.g; + const b = clearColor.b; + + if ( isUnsignedType ) { + + uintClearColor[ 0 ] = r; + uintClearColor[ 1 ] = g; + uintClearColor[ 2 ] = b; + uintClearColor[ 3 ] = a; + _gl.clearBufferuiv( _gl.COLOR, 0, uintClearColor ); + + } else { + + intClearColor[ 0 ] = r; + intClearColor[ 1 ] = g; + intClearColor[ 2 ] = b; + intClearColor[ 3 ] = a; + _gl.clearBufferiv( _gl.COLOR, 0, intClearColor ); + + } + + } else { + + bits |= _gl.COLOR_BUFFER_BIT; + + } + + } + + if ( depth ) { + + bits |= _gl.DEPTH_BUFFER_BIT; + + } + + if ( stencil ) { + + bits |= _gl.STENCIL_BUFFER_BIT; + this.state.buffers.stencil.setMask( 0xffffffff ); + + } + + _gl.clear( bits ); + + }; + + /** + * Clears the color buffer. Equivalent to calling `renderer.clear( true, false, false )`. + */ + this.clearColor = function () { + + this.clear( true, false, false ); + + }; + + /** + * Clears the depth buffer. Equivalent to calling `renderer.clear( false, true, false )`. + */ + this.clearDepth = function () { + + this.clear( false, true, false ); + + }; + + /** + * Clears the stencil buffer. Equivalent to calling `renderer.clear( false, false, true )`. + */ + this.clearStencil = function () { + + this.clear( false, false, true ); + + }; + + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + */ + this.dispose = function () { + + canvas.removeEventListener( 'webglcontextlost', onContextLost, false ); + canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false ); + canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false ); + + background.dispose(); + renderLists.dispose(); + renderStates.dispose(); + properties.dispose(); + cubemaps.dispose(); + cubeuvmaps.dispose(); + objects.dispose(); + bindingStates.dispose(); + uniformsGroups.dispose(); + programCache.dispose(); + + xr.dispose(); + + xr.removeEventListener( 'sessionstart', onXRSessionStart ); + xr.removeEventListener( 'sessionend', onXRSessionEnd ); + + animation.stop(); + + }; + + // Events + + function onContextLost( event ) { + + event.preventDefault(); + + console.log( 'THREE.WebGLRenderer: Context Lost.' ); + + _isContextLost = true; + + } + + function onContextRestore( /* event */ ) { + + console.log( 'THREE.WebGLRenderer: Context Restored.' ); + + _isContextLost = false; + + const infoAutoReset = info.autoReset; + const shadowMapEnabled = shadowMap.enabled; + const shadowMapAutoUpdate = shadowMap.autoUpdate; + const shadowMapNeedsUpdate = shadowMap.needsUpdate; + const shadowMapType = shadowMap.type; + + initGLContext(); + + info.autoReset = infoAutoReset; + shadowMap.enabled = shadowMapEnabled; + shadowMap.autoUpdate = shadowMapAutoUpdate; + shadowMap.needsUpdate = shadowMapNeedsUpdate; + shadowMap.type = shadowMapType; + + } + + function onContextCreationError( event ) { + + console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage ); + + } + + function onMaterialDispose( event ) { + + const material = event.target; + + material.removeEventListener( 'dispose', onMaterialDispose ); + + deallocateMaterial( material ); + + } + + // Buffer deallocation + + function deallocateMaterial( material ) { + + releaseMaterialProgramReferences( material ); + + properties.remove( material ); + + } + + + function releaseMaterialProgramReferences( material ) { + + const programs = properties.get( material ).programs; + + if ( programs !== undefined ) { + + programs.forEach( function ( program ) { + + programCache.releaseProgram( program ); + + } ); + + if ( material.isShaderMaterial ) { + + programCache.releaseShaderCache( material ); + + } + + } + + } + + // Buffer rendering + + this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) { + + if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null) + + const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 ); + + const program = setProgram( camera, scene, geometry, material, object ); + + state.setMaterial( material, frontFaceCW ); + + // + + let index = geometry.index; + let rangeFactor = 1; + + if ( material.wireframe === true ) { + + index = geometries.getWireframeAttribute( geometry ); + + if ( index === undefined ) return; + + rangeFactor = 2; + + } + + // + + const drawRange = geometry.drawRange; + const position = geometry.attributes.position; + + let drawStart = drawRange.start * rangeFactor; + let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor; + + if ( group !== null ) { + + drawStart = Math.max( drawStart, group.start * rangeFactor ); + drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor ); + + } + + if ( index !== null ) { + + drawStart = Math.max( drawStart, 0 ); + drawEnd = Math.min( drawEnd, index.count ); + + } else if ( position !== undefined && position !== null ) { + + drawStart = Math.max( drawStart, 0 ); + drawEnd = Math.min( drawEnd, position.count ); + + } + + const drawCount = drawEnd - drawStart; + + if ( drawCount < 0 || drawCount === Infinity ) return; + + // + + bindingStates.setup( object, material, program, geometry, index ); + + let attribute; + let renderer = bufferRenderer; + + if ( index !== null ) { + + attribute = attributes.get( index ); + + renderer = indexedBufferRenderer; + renderer.setIndex( attribute ); + + } + + // + + if ( object.isMesh ) { + + if ( material.wireframe === true ) { + + state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() ); + renderer.setMode( _gl.LINES ); + + } else { + + renderer.setMode( _gl.TRIANGLES ); + + } + + } else if ( object.isLine ) { + + let lineWidth = material.linewidth; + + if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material + + state.setLineWidth( lineWidth * getTargetPixelRatio() ); + + if ( object.isLineSegments ) { + + renderer.setMode( _gl.LINES ); + + } else if ( object.isLineLoop ) { + + renderer.setMode( _gl.LINE_LOOP ); + + } else { + + renderer.setMode( _gl.LINE_STRIP ); + + } + + } else if ( object.isPoints ) { + + renderer.setMode( _gl.POINTS ); + + } else if ( object.isSprite ) { + + renderer.setMode( _gl.TRIANGLES ); + + } + + if ( object.isBatchedMesh ) { + + if ( object._multiDrawInstances !== null ) { + + // @deprecated, r174 + warnOnce( 'THREE.WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' ); + renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances ); + + } else { + + if ( ! extensions.get( 'WEBGL_multi_draw' ) ) { + + const starts = object._multiDrawStarts; + const counts = object._multiDrawCounts; + const drawCount = object._multiDrawCount; + const bytesPerElement = index ? attributes.get( index ).bytesPerElement : 1; + const uniforms = properties.get( material ).currentProgram.getUniforms(); + for ( let i = 0; i < drawCount; i ++ ) { + + uniforms.setValue( _gl, '_gl_DrawID', i ); + renderer.render( starts[ i ] / bytesPerElement, counts[ i ] ); + + } + + } else { + + renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount ); + + } + + } + + } else if ( object.isInstancedMesh ) { + + renderer.renderInstances( drawStart, drawCount, object.count ); + + } else if ( geometry.isInstancedBufferGeometry ) { + + const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity; + const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount ); + + renderer.renderInstances( drawStart, drawCount, instanceCount ); + + } else { + + renderer.render( drawStart, drawCount ); + + } + + }; + + // Compile + + function prepareMaterial( material, scene, object ) { + + if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) { + + material.side = BackSide; + material.needsUpdate = true; + getProgram( material, scene, object ); + + material.side = FrontSide; + material.needsUpdate = true; + getProgram( material, scene, object ); + + material.side = DoubleSide; + + } else { + + getProgram( material, scene, object ); + + } + + } + + /** + * Compiles all materials in the scene with the camera. This is useful to precompile shaders + * before the first rendering. If you want to add a 3D object to an existing scene, use the third + * optional parameter for applying the target scene. + * + * Note that the (target) scene's lighting and environment must be configured before calling this method. + * + * @param {Object3D} scene - The scene or another type of 3D object to precompile. + * @param {Camera} camera - The camera. + * @param {?Scene} [targetScene=null] - The target scene. + * @return {Set} The precompiled materials. + */ + this.compile = function ( scene, camera, targetScene = null ) { + + if ( targetScene === null ) targetScene = scene; + + currentRenderState = renderStates.get( targetScene ); + currentRenderState.init( camera ); + + renderStateStack.push( currentRenderState ); + + // gather lights from both the target scene and the new object that will be added to the scene. + + targetScene.traverseVisible( function ( object ) { + + if ( object.isLight && object.layers.test( camera.layers ) ) { + + currentRenderState.pushLight( object ); + + if ( object.castShadow ) { + + currentRenderState.pushShadow( object ); + + } + + } + + } ); + + if ( scene !== targetScene ) { + + scene.traverseVisible( function ( object ) { + + if ( object.isLight && object.layers.test( camera.layers ) ) { + + currentRenderState.pushLight( object ); + + if ( object.castShadow ) { + + currentRenderState.pushShadow( object ); + + } + + } + + } ); + + } + + currentRenderState.setupLights(); + + // Only initialize materials in the new scene, not the targetScene. + + const materials = new Set(); + + scene.traverse( function ( object ) { + + if ( ! ( object.isMesh || object.isPoints || object.isLine || object.isSprite ) ) { + + return; + + } + + const material = object.material; + + if ( material ) { + + if ( Array.isArray( material ) ) { + + for ( let i = 0; i < material.length; i ++ ) { + + const material2 = material[ i ]; + + prepareMaterial( material2, targetScene, object ); + materials.add( material2 ); + + } + + } else { + + prepareMaterial( material, targetScene, object ); + materials.add( material ); + + } + + } + + } ); + + currentRenderState = renderStateStack.pop(); + + return materials; + + }; + + // compileAsync + + /** + * Asynchronous version of {@link WebGLRenderer#compile}. + * + * This method makes use of the `KHR_parallel_shader_compile` WebGL extension. Hence, + * it is recommended to use this version of `compile()` whenever possible. + * + * @async + * @param {Object3D} scene - The scene or another type of 3D object to precompile. + * @param {Camera} camera - The camera. + * @param {?Scene} [targetScene=null] - The target scene. + * @return {Promise} A Promise that resolves when the given scene can be rendered without unnecessary stalling due to shader compilation. + */ + this.compileAsync = function ( scene, camera, targetScene = null ) { + + const materials = this.compile( scene, camera, targetScene ); + + // Wait for all the materials in the new object to indicate that they're + // ready to be used before resolving the promise. + + return new Promise( ( resolve ) => { + + function checkMaterialsReady() { + + materials.forEach( function ( material ) { + + const materialProperties = properties.get( material ); + const program = materialProperties.currentProgram; + + if ( program.isReady() ) { + + // remove any programs that report they're ready to use from the list + materials.delete( material ); + + } + + } ); + + // once the list of compiling materials is empty, call the callback + + if ( materials.size === 0 ) { + + resolve( scene ); + return; + + } + + // if some materials are still not ready, wait a bit and check again + + setTimeout( checkMaterialsReady, 10 ); + + } + + if ( extensions.get( 'KHR_parallel_shader_compile' ) !== null ) { + + // If we can check the compilation status of the materials without + // blocking then do so right away. + + checkMaterialsReady(); + + } else { + + // Otherwise start by waiting a bit to give the materials we just + // initialized a chance to finish. + + setTimeout( checkMaterialsReady, 10 ); + + } + + } ); + + }; + + // Animation Loop + + let onAnimationFrameCallback = null; + + function onAnimationFrame( time ) { + + if ( onAnimationFrameCallback ) onAnimationFrameCallback( time ); + + } + + function onXRSessionStart() { + + animation.stop(); + + } + + function onXRSessionEnd() { + + animation.start(); + + } + + const animation = new WebGLAnimation(); + animation.setAnimationLoop( onAnimationFrame ); + + if ( typeof self !== 'undefined' ) animation.setContext( self ); + + this.setAnimationLoop = function ( callback ) { + + onAnimationFrameCallback = callback; + xr.setAnimationLoop( callback ); + + ( callback === null ) ? animation.stop() : animation.start(); + + }; + + xr.addEventListener( 'sessionstart', onXRSessionStart ); + xr.addEventListener( 'sessionend', onXRSessionEnd ); + + // Rendering + + /** + * Renders the given scene (or other type of 3D object) using the given camera. + * + * The render is done to a previously specified render target set by calling {@link WebGLRenderer#setRenderTarget} + * or to the canvas as usual. + * + * By default render buffers are cleared before rendering but you can prevent + * this by setting the property `autoClear` to `false`. If you want to prevent + * only certain buffers being cleared you can `autoClearColor`, `autoClearDepth` + * or `autoClearStencil` to `false`. To force a clear, use {@link WebGLRenderer#clear}. + * + * @param {Object3D} scene - The scene to render. + * @param {Camera} camera - The camera. + */ + this.render = function ( scene, camera ) { + + if ( camera !== undefined && camera.isCamera !== true ) { + + console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' ); + return; + + } + + if ( _isContextLost === true ) return; + + // update scene graph + + if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld(); + + // update camera matrices and frustum + + if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld(); + + if ( xr.enabled === true && xr.isPresenting === true ) { + + if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera ); + + camera = xr.getCamera(); // use XR camera for rendering + + } + + // + if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget ); + + currentRenderState = renderStates.get( scene, renderStateStack.length ); + currentRenderState.init( camera ); + + renderStateStack.push( currentRenderState ); + + _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); + _frustum.setFromProjectionMatrix( _projScreenMatrix ); + + _localClippingEnabled = this.localClippingEnabled; + _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled ); + + currentRenderList = renderLists.get( scene, renderListStack.length ); + currentRenderList.init(); + + renderListStack.push( currentRenderList ); + + if ( xr.enabled === true && xr.isPresenting === true ) { + + const depthSensingMesh = _this.xr.getDepthSensingMesh(); + + if ( depthSensingMesh !== null ) { + + projectObject( depthSensingMesh, camera, - Infinity, _this.sortObjects ); + + } + + } + + projectObject( scene, camera, 0, _this.sortObjects ); + + currentRenderList.finish(); + + if ( _this.sortObjects === true ) { + + currentRenderList.sort( _opaqueSort, _transparentSort ); + + } + + _renderBackground = xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false; + if ( _renderBackground ) { + + background.addToRenderList( currentRenderList, scene ); + + } + + // + + this.info.render.frame ++; + + if ( _clippingEnabled === true ) clipping.beginShadows(); + + const shadowsArray = currentRenderState.state.shadowsArray; + + shadowMap.render( shadowsArray, scene, camera ); + + if ( _clippingEnabled === true ) clipping.endShadows(); + + // + + if ( this.info.autoReset === true ) this.info.reset(); + + // render scene + + const opaqueObjects = currentRenderList.opaque; + const transmissiveObjects = currentRenderList.transmissive; + + currentRenderState.setupLights(); + + if ( camera.isArrayCamera ) { + + const cameras = camera.cameras; + + if ( transmissiveObjects.length > 0 ) { + + for ( let i = 0, l = cameras.length; i < l; i ++ ) { + + const camera2 = cameras[ i ]; + + renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera2 ); + + } + + } + + if ( _renderBackground ) background.render( scene ); + + for ( let i = 0, l = cameras.length; i < l; i ++ ) { + + const camera2 = cameras[ i ]; + + renderScene( currentRenderList, scene, camera2, camera2.viewport ); + + } + + } else { + + if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ); + + if ( _renderBackground ) background.render( scene ); + + renderScene( currentRenderList, scene, camera ); + + } + + // + + if ( _currentRenderTarget !== null && _currentActiveMipmapLevel === 0 ) { + + // resolve multisample renderbuffers to a single-sample texture if necessary + + textures.updateMultisampleRenderTarget( _currentRenderTarget ); + + // Generate mipmap if we're using any kind of mipmap filtering + + textures.updateRenderTargetMipmap( _currentRenderTarget ); + + } + + // + + if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera ); + + // _gl.finish(); + + bindingStates.resetDefaultState(); + _currentMaterialId = -1; + _currentCamera = null; + + renderStateStack.pop(); + + if ( renderStateStack.length > 0 ) { + + currentRenderState = renderStateStack[ renderStateStack.length - 1 ]; + + if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, currentRenderState.state.camera ); + + } else { + + currentRenderState = null; + + } + + renderListStack.pop(); + + if ( renderListStack.length > 0 ) { + + currentRenderList = renderListStack[ renderListStack.length - 1 ]; + + } else { + + currentRenderList = null; + + } + + }; + + function projectObject( object, camera, groupOrder, sortObjects ) { + + if ( object.visible === false ) return; + + const visible = object.layers.test( camera.layers ); + + if ( visible ) { + + if ( object.isGroup ) { + + groupOrder = object.renderOrder; + + } else if ( object.isLOD ) { + + if ( object.autoUpdate === true ) object.update( camera ); + + } else if ( object.isLight ) { + + currentRenderState.pushLight( object ); + + if ( object.castShadow ) { + + currentRenderState.pushShadow( object ); + + } + + } else if ( object.isSprite ) { + + if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) { + + if ( sortObjects ) { + + _vector4.setFromMatrixPosition( object.matrixWorld ) + .applyMatrix4( _projScreenMatrix ); + + } + + const geometry = objects.update( object ); + const material = object.material; + + if ( material.visible ) { + + currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null ); + + } + + } + + } else if ( object.isMesh || object.isLine || object.isPoints ) { + + if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) { + + const geometry = objects.update( object ); + const material = object.material; + + if ( sortObjects ) { + + if ( object.boundingSphere !== undefined ) { + + if ( object.boundingSphere === null ) object.computeBoundingSphere(); + _vector4.copy( object.boundingSphere.center ); + + } else { + + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + _vector4.copy( geometry.boundingSphere.center ); + + } + + _vector4 + .applyMatrix4( object.matrixWorld ) + .applyMatrix4( _projScreenMatrix ); + + } + + if ( Array.isArray( material ) ) { + + const groups = geometry.groups; + + for ( let i = 0, l = groups.length; i < l; i ++ ) { + + const group = groups[ i ]; + const groupMaterial = material[ group.materialIndex ]; + + if ( groupMaterial && groupMaterial.visible ) { + + currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group ); + + } + + } + + } else if ( material.visible ) { + + currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null ); + + } + + } + + } + + } + + const children = object.children; + + for ( let i = 0, l = children.length; i < l; i ++ ) { + + projectObject( children[ i ], camera, groupOrder, sortObjects ); + + } + + } + + function renderScene( currentRenderList, scene, camera, viewport ) { + + const opaqueObjects = currentRenderList.opaque; + const transmissiveObjects = currentRenderList.transmissive; + const transparentObjects = currentRenderList.transparent; + + currentRenderState.setupLightsView( camera ); + + if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera ); + + if ( viewport ) state.viewport( _currentViewport.copy( viewport ) ); + + if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera ); + if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera ); + if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera ); + + // Ensure depth buffer writing is enabled so it can be cleared on next render + + state.buffers.depth.setTest( true ); + state.buffers.depth.setMask( true ); + state.buffers.color.setMask( true ); + + state.setPolygonOffset( false ); + + } + + function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) { + + const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null; + + if ( overrideMaterial !== null ) { + + return; + + } + + if ( currentRenderState.state.transmissionRenderTarget[ camera.id ] === undefined ) { + + currentRenderState.state.transmissionRenderTarget[ camera.id ] = new WebGLRenderTarget( 1, 1, { + generateMipmaps: true, + type: ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) ) ? HalfFloatType : UnsignedByteType, + minFilter: LinearMipmapLinearFilter, + samples: 4, + stencilBuffer: stencil, + resolveDepthBuffer: false, + resolveStencilBuffer: false, + colorSpace: ColorManagement.workingColorSpace, + } ); + + // debug + + /* + const geometry = new PlaneGeometry(); + const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } ); + + const mesh = new Mesh( geometry, material ); + scene.add( mesh ); + */ + + } + + const transmissionRenderTarget = currentRenderState.state.transmissionRenderTarget[ camera.id ]; + + const activeViewport = camera.viewport || _currentViewport; + transmissionRenderTarget.setSize( activeViewport.z * _this.transmissionResolutionScale, activeViewport.w * _this.transmissionResolutionScale ); + + // + + const currentRenderTarget = _this.getRenderTarget(); + _this.setRenderTarget( transmissionRenderTarget ); + + _this.getClearColor( _currentClearColor ); + _currentClearAlpha = _this.getClearAlpha(); + if ( _currentClearAlpha < 1 ) _this.setClearColor( 0xffffff, 0.5 ); + + _this.clear(); + + if ( _renderBackground ) background.render( scene ); + + // Turn off the features which can affect the frag color for opaque objects pass. + // Otherwise they are applied twice in opaque objects pass and transmission objects pass. + const currentToneMapping = _this.toneMapping; + _this.toneMapping = NoToneMapping; + + // Remove viewport from camera to avoid nested render calls resetting viewport to it (e.g Reflector). + // Transmission render pass requires viewport to match the transmissionRenderTarget. + const currentCameraViewport = camera.viewport; + if ( camera.viewport !== undefined ) camera.viewport = undefined; + + currentRenderState.setupLightsView( camera ); + + if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera ); + + renderObjects( opaqueObjects, scene, camera ); + + textures.updateMultisampleRenderTarget( transmissionRenderTarget ); + textures.updateRenderTargetMipmap( transmissionRenderTarget ); + + if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === false ) { // see #28131 + + let renderTargetNeedsUpdate = false; + + for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) { + + const renderItem = transmissiveObjects[ i ]; + + const object = renderItem.object; + const geometry = renderItem.geometry; + const material = renderItem.material; + const group = renderItem.group; + + if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) { + + const currentSide = material.side; + + material.side = BackSide; + material.needsUpdate = true; + + renderObject( object, scene, camera, geometry, material, group ); + + material.side = currentSide; + material.needsUpdate = true; + + renderTargetNeedsUpdate = true; + + } + + } + + if ( renderTargetNeedsUpdate === true ) { + + textures.updateMultisampleRenderTarget( transmissionRenderTarget ); + textures.updateRenderTargetMipmap( transmissionRenderTarget ); + + } + + } + + _this.setRenderTarget( currentRenderTarget ); + + _this.setClearColor( _currentClearColor, _currentClearAlpha ); + + if ( currentCameraViewport !== undefined ) camera.viewport = currentCameraViewport; + + _this.toneMapping = currentToneMapping; + + } + + function renderObjects( renderList, scene, camera ) { + + const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null; + + for ( let i = 0, l = renderList.length; i < l; i ++ ) { + + const renderItem = renderList[ i ]; + + const object = renderItem.object; + const geometry = renderItem.geometry; + const group = renderItem.group; + let material = renderItem.material; + + if ( material.allowOverride === true && overrideMaterial !== null ) { + + material = overrideMaterial; + + } + + if ( object.layers.test( camera.layers ) ) { + + renderObject( object, scene, camera, geometry, material, group ); + + } + + } + + } + + function renderObject( object, scene, camera, geometry, material, group ) { + + object.onBeforeRender( _this, scene, camera, geometry, material, group ); + + object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); + object.normalMatrix.getNormalMatrix( object.modelViewMatrix ); + + material.onBeforeRender( _this, scene, camera, geometry, object, group ); + + if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) { + + material.side = BackSide; + material.needsUpdate = true; + _this.renderBufferDirect( camera, scene, geometry, material, object, group ); + + material.side = FrontSide; + material.needsUpdate = true; + _this.renderBufferDirect( camera, scene, geometry, material, object, group ); + + material.side = DoubleSide; + + } else { + + _this.renderBufferDirect( camera, scene, geometry, material, object, group ); + + } + + object.onAfterRender( _this, scene, camera, geometry, material, group ); + + } + + function getProgram( material, scene, object ) { + + if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ... + + const materialProperties = properties.get( material ); + + const lights = currentRenderState.state.lights; + const shadowsArray = currentRenderState.state.shadowsArray; + + const lightsStateVersion = lights.state.version; + + const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object ); + const programCacheKey = programCache.getProgramCacheKey( parameters ); + + let programs = materialProperties.programs; + + // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change + + materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null; + materialProperties.fog = scene.fog; + materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment ); + materialProperties.envMapRotation = ( materialProperties.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation; + + if ( programs === undefined ) { + + // new material + + material.addEventListener( 'dispose', onMaterialDispose ); + + programs = new Map(); + materialProperties.programs = programs; + + } + + let program = programs.get( programCacheKey ); + + if ( program !== undefined ) { + + // early out if program and light state is identical + + if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) { + + updateCommonMaterialProperties( material, parameters ); + + return program; + + } + + } else { + + parameters.uniforms = programCache.getUniforms( material ); + + material.onBeforeCompile( parameters, _this ); + + program = programCache.acquireProgram( parameters, programCacheKey ); + programs.set( programCacheKey, program ); + + materialProperties.uniforms = parameters.uniforms; + + } + + const uniforms = materialProperties.uniforms; + + if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) { + + uniforms.clippingPlanes = clipping.uniform; + + } + + updateCommonMaterialProperties( material, parameters ); + + // store the light setup it was created for + + materialProperties.needsLights = materialNeedsLights( material ); + materialProperties.lightsStateVersion = lightsStateVersion; + + if ( materialProperties.needsLights ) { + + // wire up the material to this renderer's lighting state + + uniforms.ambientLightColor.value = lights.state.ambient; + uniforms.lightProbe.value = lights.state.probe; + uniforms.directionalLights.value = lights.state.directional; + uniforms.directionalLightShadows.value = lights.state.directionalShadow; + uniforms.spotLights.value = lights.state.spot; + uniforms.spotLightShadows.value = lights.state.spotShadow; + uniforms.rectAreaLights.value = lights.state.rectArea; + uniforms.ltc_1.value = lights.state.rectAreaLTC1; + uniforms.ltc_2.value = lights.state.rectAreaLTC2; + uniforms.pointLights.value = lights.state.point; + uniforms.pointLightShadows.value = lights.state.pointShadow; + uniforms.hemisphereLights.value = lights.state.hemi; + + uniforms.directionalShadowMap.value = lights.state.directionalShadowMap; + uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix; + uniforms.spotShadowMap.value = lights.state.spotShadowMap; + uniforms.spotLightMatrix.value = lights.state.spotLightMatrix; + uniforms.spotLightMap.value = lights.state.spotLightMap; + uniforms.pointShadowMap.value = lights.state.pointShadowMap; + uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; + // TODO (abelnation): add area lights shadow info to uniforms + + } + + materialProperties.currentProgram = program; + materialProperties.uniformsList = null; + + return program; + + } + + function getUniformList( materialProperties ) { + + if ( materialProperties.uniformsList === null ) { + + const progUniforms = materialProperties.currentProgram.getUniforms(); + materialProperties.uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, materialProperties.uniforms ); + + } + + return materialProperties.uniformsList; + + } + + function updateCommonMaterialProperties( material, parameters ) { + + const materialProperties = properties.get( material ); + + materialProperties.outputColorSpace = parameters.outputColorSpace; + materialProperties.batching = parameters.batching; + materialProperties.batchingColor = parameters.batchingColor; + materialProperties.instancing = parameters.instancing; + materialProperties.instancingColor = parameters.instancingColor; + materialProperties.instancingMorph = parameters.instancingMorph; + materialProperties.skinning = parameters.skinning; + materialProperties.morphTargets = parameters.morphTargets; + materialProperties.morphNormals = parameters.morphNormals; + materialProperties.morphColors = parameters.morphColors; + materialProperties.morphTargetsCount = parameters.morphTargetsCount; + materialProperties.numClippingPlanes = parameters.numClippingPlanes; + materialProperties.numIntersection = parameters.numClipIntersection; + materialProperties.vertexAlphas = parameters.vertexAlphas; + materialProperties.vertexTangents = parameters.vertexTangents; + materialProperties.toneMapping = parameters.toneMapping; + + } + + function setProgram( camera, scene, geometry, material, object ) { + + if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ... + + textures.resetTextureUnits(); + + const fog = scene.fog; + const environment = material.isMeshStandardMaterial ? scene.environment : null; + const colorSpace = ( _currentRenderTarget === null ) ? _this.outputColorSpace : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace ); + const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment ); + const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4; + const vertexTangents = !! geometry.attributes.tangent && ( !! material.normalMap || material.anisotropy > 0 ); + const morphTargets = !! geometry.morphAttributes.position; + const morphNormals = !! geometry.morphAttributes.normal; + const morphColors = !! geometry.morphAttributes.color; + + let toneMapping = NoToneMapping; + + if ( material.toneMapped ) { + + if ( _currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true ) { + + toneMapping = _this.toneMapping; + + } + + } + + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0; + + const materialProperties = properties.get( material ); + const lights = currentRenderState.state.lights; + + if ( _clippingEnabled === true ) { + + if ( _localClippingEnabled === true || camera !== _currentCamera ) { + + const useCache = + camera === _currentCamera && + material.id === _currentMaterialId; + + // we might want to call this function with some ClippingGroup + // object instead of the material, once it becomes feasible + // (#8465, #8379) + clipping.setState( material, camera, useCache ); + + } + + } + + // + + let needsProgramChange = false; + + if ( material.version === materialProperties.__version ) { + + if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) { + + needsProgramChange = true; + + } else if ( materialProperties.outputColorSpace !== colorSpace ) { + + needsProgramChange = true; + + } else if ( object.isBatchedMesh && materialProperties.batching === false ) { + + needsProgramChange = true; + + } else if ( ! object.isBatchedMesh && materialProperties.batching === true ) { + + needsProgramChange = true; + + } else if ( object.isBatchedMesh && materialProperties.batchingColor === true && object.colorTexture === null ) { + + needsProgramChange = true; + + } else if ( object.isBatchedMesh && materialProperties.batchingColor === false && object.colorTexture !== null ) { + + needsProgramChange = true; + + } else if ( object.isInstancedMesh && materialProperties.instancing === false ) { + + needsProgramChange = true; + + } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) { + + needsProgramChange = true; + + } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) { + + needsProgramChange = true; + + } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) { + + needsProgramChange = true; + + } else if ( object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null ) { + + needsProgramChange = true; + + } else if ( object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null ) { + + needsProgramChange = true; + + } else if ( object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null ) { + + needsProgramChange = true; + + } else if ( object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null ) { + + needsProgramChange = true; + + } else if ( materialProperties.envMap !== envMap ) { + + needsProgramChange = true; + + } else if ( material.fog === true && materialProperties.fog !== fog ) { + + needsProgramChange = true; + + } else if ( materialProperties.numClippingPlanes !== undefined && + ( materialProperties.numClippingPlanes !== clipping.numPlanes || + materialProperties.numIntersection !== clipping.numIntersection ) ) { + + needsProgramChange = true; + + } else if ( materialProperties.vertexAlphas !== vertexAlphas ) { + + needsProgramChange = true; + + } else if ( materialProperties.vertexTangents !== vertexTangents ) { + + needsProgramChange = true; + + } else if ( materialProperties.morphTargets !== morphTargets ) { + + needsProgramChange = true; + + } else if ( materialProperties.morphNormals !== morphNormals ) { + + needsProgramChange = true; + + } else if ( materialProperties.morphColors !== morphColors ) { + + needsProgramChange = true; + + } else if ( materialProperties.toneMapping !== toneMapping ) { + + needsProgramChange = true; + + } else if ( materialProperties.morphTargetsCount !== morphTargetsCount ) { + + needsProgramChange = true; + + } + + } else { + + needsProgramChange = true; + materialProperties.__version = material.version; + + } + + // + + let program = materialProperties.currentProgram; + + if ( needsProgramChange === true ) { + + program = getProgram( material, scene, object ); + + } + + let refreshProgram = false; + let refreshMaterial = false; + let refreshLights = false; + + const p_uniforms = program.getUniforms(), + m_uniforms = materialProperties.uniforms; + + if ( state.useProgram( program.program ) ) { + + refreshProgram = true; + refreshMaterial = true; + refreshLights = true; + + } + + if ( material.id !== _currentMaterialId ) { + + _currentMaterialId = material.id; + + refreshMaterial = true; + + } + + if ( refreshProgram || _currentCamera !== camera ) { + + // common camera uniforms + + const reverseDepthBuffer = state.buffers.depth.getReversed(); + + if ( reverseDepthBuffer ) { + + _currentProjectionMatrix.copy( camera.projectionMatrix ); + + toNormalizedProjectionMatrix( _currentProjectionMatrix ); + toReversedProjectionMatrix( _currentProjectionMatrix ); + + p_uniforms.setValue( _gl, 'projectionMatrix', _currentProjectionMatrix ); + + } else { + + p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix ); + + } + + p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse ); + + const uCamPos = p_uniforms.map.cameraPosition; + + if ( uCamPos !== undefined ) { + + uCamPos.setValue( _gl, _vector3.setFromMatrixPosition( camera.matrixWorld ) ); + + } + + if ( capabilities.logarithmicDepthBuffer ) { + + p_uniforms.setValue( _gl, 'logDepthBufFC', + 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) ); + + } + + // consider moving isOrthographic to UniformLib and WebGLMaterials, see https://github.com/mrdoob/three.js/pull/26467#issuecomment-1645185067 + + if ( material.isMeshPhongMaterial || + material.isMeshToonMaterial || + material.isMeshLambertMaterial || + material.isMeshBasicMaterial || + material.isMeshStandardMaterial || + material.isShaderMaterial ) { + + p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true ); + + } + + if ( _currentCamera !== camera ) { + + _currentCamera = camera; + + // lighting uniforms depend on the camera so enforce an update + // now, in case this material supports lights - or later, when + // the next material that does gets activated: + + refreshMaterial = true; // set to true on material change + refreshLights = true; // remains set until update done + + } + + } + + // skinning and morph target uniforms must be set even if material didn't change + // auto-setting of texture unit for bone and morph texture must go before other textures + // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures + + if ( object.isSkinnedMesh ) { + + p_uniforms.setOptional( _gl, object, 'bindMatrix' ); + p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' ); + + const skeleton = object.skeleton; + + if ( skeleton ) { + + if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture(); + + p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures ); + + } + + } + + if ( object.isBatchedMesh ) { + + p_uniforms.setOptional( _gl, object, 'batchingTexture' ); + p_uniforms.setValue( _gl, 'batchingTexture', object._matricesTexture, textures ); + + p_uniforms.setOptional( _gl, object, 'batchingIdTexture' ); + p_uniforms.setValue( _gl, 'batchingIdTexture', object._indirectTexture, textures ); + + p_uniforms.setOptional( _gl, object, 'batchingColorTexture' ); + if ( object._colorsTexture !== null ) { + + p_uniforms.setValue( _gl, 'batchingColorTexture', object._colorsTexture, textures ); + + } + + } + + const morphAttributes = geometry.morphAttributes; + + if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined ) ) { + + morphtargets.update( object, geometry, program ); + + } + + if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) { + + materialProperties.receiveShadow = object.receiveShadow; + p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow ); + + } + + // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512 + + if ( material.isMeshGouraudMaterial && material.envMap !== null ) { + + m_uniforms.envMap.value = envMap; + + m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? -1 : 1; + + } + + if ( material.isMeshStandardMaterial && material.envMap === null && scene.environment !== null ) { + + m_uniforms.envMapIntensity.value = scene.environmentIntensity; + + } + + if ( refreshMaterial ) { + + p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure ); + + if ( materialProperties.needsLights ) { + + // the current material requires lighting info + + // note: all lighting uniforms are always set correctly + // they simply reference the renderer's state for their + // values + // + // use the current material's .needsUpdate flags to set + // the GL state when required + + markUniformsLightsNeedsUpdate( m_uniforms, refreshLights ); + + } + + // refresh uniforms common to several materials + + if ( fog && material.fog === true ) { + + materials.refreshFogUniforms( m_uniforms, fog ); + + } + + materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, currentRenderState.state.transmissionRenderTarget[ camera.id ] ); + + WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures ); + + } + + if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) { + + WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures ); + material.uniformsNeedUpdate = false; + + } + + if ( material.isSpriteMaterial ) { + + p_uniforms.setValue( _gl, 'center', object.center ); + + } + + // common matrices + + p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix ); + p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix ); + p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld ); + + // UBOs + + if ( material.isShaderMaterial || material.isRawShaderMaterial ) { + + const groups = material.uniformsGroups; + + for ( let i = 0, l = groups.length; i < l; i ++ ) { + + const group = groups[ i ]; + + uniformsGroups.update( group, program ); + uniformsGroups.bind( group, program ); + + } + + } + + return program; + + } + + // If uniforms are marked as clean, they don't need to be loaded to the GPU. + + function markUniformsLightsNeedsUpdate( uniforms, value ) { + + uniforms.ambientLightColor.needsUpdate = value; + uniforms.lightProbe.needsUpdate = value; + + uniforms.directionalLights.needsUpdate = value; + uniforms.directionalLightShadows.needsUpdate = value; + uniforms.pointLights.needsUpdate = value; + uniforms.pointLightShadows.needsUpdate = value; + uniforms.spotLights.needsUpdate = value; + uniforms.spotLightShadows.needsUpdate = value; + uniforms.rectAreaLights.needsUpdate = value; + uniforms.hemisphereLights.needsUpdate = value; + + } + + function materialNeedsLights( material ) { + + return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || + material.isMeshStandardMaterial || material.isShadowMaterial || + ( material.isShaderMaterial && material.lights === true ); + + } + + /** + * Returns the active cube face. + * + * @return {number} The active cube face. + */ + this.getActiveCubeFace = function () { + + return _currentActiveCubeFace; + + }; + + /** + * Returns the active mipmap level. + * + * @return {number} The active mipmap level. + */ + this.getActiveMipmapLevel = function () { + + return _currentActiveMipmapLevel; + + }; + + /** + * Returns the active render target. + * + * @return {?WebGLRenderTarget} The active render target. Returns `null` if no render target + * is currently set. + */ + this.getRenderTarget = function () { + + return _currentRenderTarget; + + }; + + this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) { + + const renderTargetProperties = properties.get( renderTarget ); + + renderTargetProperties.__autoAllocateDepthBuffer = renderTarget.resolveDepthBuffer === false; + if ( renderTargetProperties.__autoAllocateDepthBuffer === false ) { + + // The multisample_render_to_texture extension doesn't work properly if there + // are midframe flushes and an external depth buffer. Disable use of the extension. + renderTargetProperties.__useRenderToTexture = false; + + } + + properties.get( renderTarget.texture ).__webglTexture = colorTexture; + properties.get( renderTarget.depthTexture ).__webglTexture = renderTargetProperties.__autoAllocateDepthBuffer ? undefined : depthTexture; + + renderTargetProperties.__hasExternalTextures = true; + + }; + + this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) { + + const renderTargetProperties = properties.get( renderTarget ); + renderTargetProperties.__webglFramebuffer = defaultFramebuffer; + renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined; + + }; + + const _scratchFrameBuffer = _gl.createFramebuffer(); + + /** + * Sets the active rendertarget. + * + * @param {?WebGLRenderTarget} renderTarget - The render target to set. When `null` is given, + * the canvas is set as the active render target instead. + * @param {number} [activeCubeFace=0] - The active cube face when using a cube render target. + * Indicates the z layer to render in to when using 3D or array render targets. + * @param {number} [activeMipmapLevel=0] - The active mipmap level. + */ + this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) { + + _currentRenderTarget = renderTarget; + _currentActiveCubeFace = activeCubeFace; + _currentActiveMipmapLevel = activeMipmapLevel; + + let useDefaultFramebuffer = true; + let framebuffer = null; + let isCube = false; + let isRenderTarget3D = false; + + if ( renderTarget ) { + + const renderTargetProperties = properties.get( renderTarget ); + + if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) { + + // We need to make sure to rebind the framebuffer. + state.bindFramebuffer( _gl.FRAMEBUFFER, null ); + useDefaultFramebuffer = false; + + } else if ( renderTargetProperties.__webglFramebuffer === undefined ) { + + textures.setupRenderTarget( renderTarget ); + + } else if ( renderTargetProperties.__hasExternalTextures ) { + + // Color and depth texture must be rebound in order for the swapchain to update. + textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture ); + + } else if ( renderTarget.depthBuffer ) { + + // check if the depth texture is already bound to the frame buffer and that it's been initialized + const depthTexture = renderTarget.depthTexture; + if ( renderTargetProperties.__boundDepthTexture !== depthTexture ) { + + // check if the depth texture is compatible + if ( + depthTexture !== null && + properties.has( depthTexture ) && + ( renderTarget.width !== depthTexture.image.width || renderTarget.height !== depthTexture.image.height ) + ) { + + throw new Error( 'WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.' ); + + } + + // Swap the depth buffer to the currently attached one + textures.setupDepthRenderbuffer( renderTarget ); + + } + + } + + const texture = renderTarget.texture; + + if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) { + + isRenderTarget3D = true; + + } + + const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer; + + if ( renderTarget.isWebGLCubeRenderTarget ) { + + if ( Array.isArray( __webglFramebuffer[ activeCubeFace ] ) ) { + + framebuffer = __webglFramebuffer[ activeCubeFace ][ activeMipmapLevel ]; + + } else { + + framebuffer = __webglFramebuffer[ activeCubeFace ]; + + } + + isCube = true; + + } else if ( ( renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) { + + framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer; + + } else { + + if ( Array.isArray( __webglFramebuffer ) ) { + + framebuffer = __webglFramebuffer[ activeMipmapLevel ]; + + } else { + + framebuffer = __webglFramebuffer; + + } + + } + + _currentViewport.copy( renderTarget.viewport ); + _currentScissor.copy( renderTarget.scissor ); + _currentScissorTest = renderTarget.scissorTest; + + } else { + + _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor(); + _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor(); + _currentScissorTest = _scissorTest; + + } + + // Use a scratch frame buffer if rendering to a mip level to avoid depth buffers + // being bound that are different sizes. + if ( activeMipmapLevel !== 0 ) { + + framebuffer = _scratchFrameBuffer; + + } + + const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + + if ( framebufferBound && useDefaultFramebuffer ) { + + state.drawBuffers( renderTarget, framebuffer ); + + } + + state.viewport( _currentViewport ); + state.scissor( _currentScissor ); + state.setScissorTest( _currentScissorTest ); + + if ( isCube ) { + + const textureProperties = properties.get( renderTarget.texture ); + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel ); + + } else if ( isRenderTarget3D ) { + + const textureProperties = properties.get( renderTarget.texture ); + const layer = activeCubeFace; + _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel, layer ); + + } else if ( renderTarget !== null && activeMipmapLevel !== 0 ) { + + // Only bind the frame buffer if we are using a scratch frame buffer to render to a mipmap. + // If we rebind the texture when using a multi sample buffer then an error about inconsistent samples will be thrown. + const textureProperties = properties.get( renderTarget.texture ); + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, textureProperties.__webglTexture, activeMipmapLevel ); + + } + + _currentMaterialId = -1; // reset current material to ensure correct uniform bindings + + }; + + /** + * Reads the pixel data from the given render target into the given buffer. + * + * @param {WebGLRenderTarget} renderTarget - The render target to read from. + * @param {number} x - The `x` coordinate of the copy region's origin. + * @param {number} y - The `y` coordinate of the copy region's origin. + * @param {number} width - The width of the copy region. + * @param {number} height - The height of the copy region. + * @param {TypedArray} buffer - The result buffer. + * @param {number} [activeCubeFaceIndex] - The active cube face index. + */ + this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) { + + if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) { + + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' ); + return; + + } + + let framebuffer = properties.get( renderTarget ).__webglFramebuffer; + + if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) { + + framebuffer = framebuffer[ activeCubeFaceIndex ]; + + } + + if ( framebuffer ) { + + state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + + try { + + const texture = renderTarget.texture; + const textureFormat = texture.format; + const textureType = texture.type; + + if ( ! capabilities.textureFormatReadable( textureFormat ) ) { + + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' ); + return; + + } + + if ( ! capabilities.textureTypeReadable( textureType ) ) { + + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' ); + return; + + } + + // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604) + + if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) { + + _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer ); + + } + + } finally { + + // restore framebuffer of current render target if necessary + + const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null; + state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + + } + + } + + }; + + /** + * Asynchronous, non-blocking version of {@link WebGLRenderer#readRenderTargetPixels}. + * + * It is recommended to use this version of `readRenderTargetPixels()` whenever possible. + * + * @async + * @param {WebGLRenderTarget} renderTarget - The render target to read from. + * @param {number} x - The `x` coordinate of the copy region's origin. + * @param {number} y - The `y` coordinate of the copy region's origin. + * @param {number} width - The width of the copy region. + * @param {number} height - The height of the copy region. + * @param {TypedArray} buffer - The result buffer. + * @param {number} [activeCubeFaceIndex] - The active cube face index. + * @return {Promise} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array. + */ + this.readRenderTargetPixelsAsync = async function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) { + + if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) { + + throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' ); + + } + + let framebuffer = properties.get( renderTarget ).__webglFramebuffer; + if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) { + + framebuffer = framebuffer[ activeCubeFaceIndex ]; + + } + + if ( framebuffer ) { + + // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604) + if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) { + + // set the active frame buffer to the one we want to read + state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + + const texture = renderTarget.texture; + const textureFormat = texture.format; + const textureType = texture.type; + + if ( ! capabilities.textureFormatReadable( textureFormat ) ) { + + throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.' ); + + } + + if ( ! capabilities.textureTypeReadable( textureType ) ) { + + throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.' ); + + } + + const glBuffer = _gl.createBuffer(); + _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer ); + _gl.bufferData( _gl.PIXEL_PACK_BUFFER, buffer.byteLength, _gl.STREAM_READ ); + _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), 0 ); + + // reset the frame buffer to the currently set buffer before waiting + const currFramebuffer = _currentRenderTarget !== null ? properties.get( _currentRenderTarget ).__webglFramebuffer : null; + state.bindFramebuffer( _gl.FRAMEBUFFER, currFramebuffer ); + + // check if the commands have finished every 8 ms + const sync = _gl.fenceSync( _gl.SYNC_GPU_COMMANDS_COMPLETE, 0 ); + + _gl.flush(); + + await probeAsync( _gl, sync, 4 ); + + // read the data and delete the buffer + _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer ); + _gl.getBufferSubData( _gl.PIXEL_PACK_BUFFER, 0, buffer ); + _gl.deleteBuffer( glBuffer ); + _gl.deleteSync( sync ); + + return buffer; + + } else { + + throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.' ); + + } + + } + + }; + + /** + * Copies pixels from the current bound framebuffer into the given texture. + * + * @param {FramebufferTexture} texture - The texture. + * @param {?Vector2} [position=null] - The start position of the copy operation. + * @param {number} [level=0] - The mip level. The default represents the base mip. + */ + this.copyFramebufferToTexture = function ( texture, position = null, level = 0 ) { + + const levelScale = Math.pow( 2, - level ); + const width = Math.floor( texture.image.width * levelScale ); + const height = Math.floor( texture.image.height * levelScale ); + + const x = position !== null ? position.x : 0; + const y = position !== null ? position.y : 0; + + textures.setTexture2D( texture, 0 ); + + _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, x, y, width, height ); + + state.unbindTexture(); + + }; + + const _srcFramebuffer = _gl.createFramebuffer(); + const _dstFramebuffer = _gl.createFramebuffer(); + + /** + * Copies data of the given source texture into a destination texture. + * + * When using render target textures as `srcTexture` and `dstTexture`, you must make sure both render targets are initialized + * {@link WebGLRenderer#initRenderTarget}. + * + * @param {Texture} srcTexture - The source texture. + * @param {Texture} dstTexture - The destination texture. + * @param {?(Box2|Box3)} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional. + * @param {?(Vector2|Vector3)} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional. + * @param {number} [srcLevel=0] - The source mipmap level to copy. + * @param {?number} [dstLevel=null] - The destination mipmap level. + */ + this.copyTextureToTexture = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = null ) { + + // support the previous signature with just a single dst mipmap level + if ( dstLevel === null ) { + + if ( srcLevel !== 0 ) { + + // @deprecated, r171 + warnOnce( 'WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels.' ); + dstLevel = srcLevel; + srcLevel = 0; + + } else { + + dstLevel = 0; + + } + + } + + // gather the necessary dimensions to copy + let width, height, depth, minX, minY, minZ; + let dstX, dstY, dstZ; + const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image; + if ( srcRegion !== null ) { + + width = srcRegion.max.x - srcRegion.min.x; + height = srcRegion.max.y - srcRegion.min.y; + depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1; + minX = srcRegion.min.x; + minY = srcRegion.min.y; + minZ = srcRegion.isBox3 ? srcRegion.min.z : 0; + + } else { + + const levelScale = Math.pow( 2, - srcLevel ); + width = Math.floor( image.width * levelScale ); + height = Math.floor( image.height * levelScale ); + if ( srcTexture.isDataArrayTexture ) { + + depth = image.depth; + + } else if ( srcTexture.isData3DTexture ) { + + depth = Math.floor( image.depth * levelScale ); + + } else { + + depth = 1; + + } + + minX = 0; + minY = 0; + minZ = 0; + + } + + if ( dstPosition !== null ) { + + dstX = dstPosition.x; + dstY = dstPosition.y; + dstZ = dstPosition.z; + + } else { + + dstX = 0; + dstY = 0; + dstZ = 0; + + } + + // Set up the destination target + const glFormat = utils.convert( dstTexture.format ); + const glType = utils.convert( dstTexture.type ); + let glTarget; + + if ( dstTexture.isData3DTexture ) { + + textures.setTexture3D( dstTexture, 0 ); + glTarget = _gl.TEXTURE_3D; + + } else if ( dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture ) { + + textures.setTexture2DArray( dstTexture, 0 ); + glTarget = _gl.TEXTURE_2D_ARRAY; + + } else { + + textures.setTexture2D( dstTexture, 0 ); + glTarget = _gl.TEXTURE_2D; + + } + + _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY ); + _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha ); + _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment ); + + // used for copying data from cpu + const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH ); + const currentUnpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT ); + const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS ); + const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS ); + const currentUnpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES ); + + _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width ); + _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height ); + _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, minX ); + _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, minY ); + _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, minZ ); + + // set up the src texture + const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture; + const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture; + if ( srcTexture.isDepthTexture ) { + + const srcTextureProperties = properties.get( srcTexture ); + const dstTextureProperties = properties.get( dstTexture ); + const srcRenderTargetProperties = properties.get( srcTextureProperties.__renderTarget ); + const dstRenderTargetProperties = properties.get( dstTextureProperties.__renderTarget ); + state.bindFramebuffer( _gl.READ_FRAMEBUFFER, srcRenderTargetProperties.__webglFramebuffer ); + state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, dstRenderTargetProperties.__webglFramebuffer ); + + for ( let i = 0; i < depth; i ++ ) { + + // if the source or destination are a 3d target then a layer needs to be bound + if ( isSrc3D ) { + + _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( srcTexture ).__webglTexture, srcLevel, minZ + i ); + _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( dstTexture ).__webglTexture, dstLevel, dstZ + i ); + + } + + _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.DEPTH_BUFFER_BIT, _gl.NEAREST ); + + } + + state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null ); + state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null ); + + } else if ( srcLevel !== 0 || srcTexture.isRenderTargetTexture || properties.has( srcTexture ) ) { + + // get the appropriate frame buffers + const srcTextureProperties = properties.get( srcTexture ); + const dstTextureProperties = properties.get( dstTexture ); + + // bind the frame buffer targets + state.bindFramebuffer( _gl.READ_FRAMEBUFFER, _srcFramebuffer ); + state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, _dstFramebuffer ); + + for ( let i = 0; i < depth; i ++ ) { + + // assign the correct layers and mip maps to the frame buffers + if ( isSrc3D ) { + + _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, srcTextureProperties.__webglTexture, srcLevel, minZ + i ); + + } else { + + _gl.framebufferTexture2D( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, srcTextureProperties.__webglTexture, srcLevel ); + + } + + if ( isDst3D ) { + + _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, dstTextureProperties.__webglTexture, dstLevel, dstZ + i ); + + } else { + + _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, dstTextureProperties.__webglTexture, dstLevel ); + + } + + // copy the data using the fastest function that can achieve the copy + if ( srcLevel !== 0 ) { + + _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.COLOR_BUFFER_BIT, _gl.NEAREST ); + + } else if ( isDst3D ) { + + _gl.copyTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height ); + + } else { + + _gl.copyTexSubImage2D( glTarget, dstLevel, dstX, dstY, minX, minY, width, height ); + + } + + } + + // unbind read, draw buffers + state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null ); + state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null ); + + } else { + + if ( isDst3D ) { + + // copy data into the 3d texture + if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) { + + _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data ); + + } else if ( dstTexture.isCompressedArrayTexture ) { + + _gl.compressedTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data ); + + } else { + + _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image ); + + } + + } else { + + // copy data into the 2d texture + if ( srcTexture.isDataTexture ) { + + _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data ); + + } else if ( srcTexture.isCompressedTexture ) { + + _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data ); + + } else { + + _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image ); + + } + + } + + } + + // reset values + _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen ); + _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight ); + _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels ); + _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows ); + _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages ); + + // Generate mipmaps only when copying level 0 + if ( dstLevel === 0 && dstTexture.generateMipmaps ) { + + _gl.generateMipmap( glTarget ); + + } + + state.unbindTexture(); + + }; + + this.copyTextureToTexture3D = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) { + + // @deprecated, r170 + warnOnce( 'WebGLRenderer: copyTextureToTexture3D function has been deprecated. Use "copyTextureToTexture" instead.' ); + + return this.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level ); + + }; + + /** + * Initializes the given WebGLRenderTarget memory. Useful for initializing a render target so data + * can be copied into it using {@link WebGLRenderer#copyTextureToTexture} before it has been + * rendered to. + * + * @param {WebGLRenderTarget} target - The render target. + */ + this.initRenderTarget = function ( target ) { + + if ( properties.get( target ).__webglFramebuffer === undefined ) { + + textures.setupRenderTarget( target ); + + } + + }; + + /** + * Initializes the given texture. Useful for preloading a texture rather than waiting until first + * render (which can cause noticeable lags due to decode and GPU upload overhead). + * + * @param {Texture} texture - The texture. + */ + this.initTexture = function ( texture ) { + + if ( texture.isCubeTexture ) { + + textures.setTextureCube( texture, 0 ); + + } else if ( texture.isData3DTexture ) { + + textures.setTexture3D( texture, 0 ); + + } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) { + + textures.setTexture2DArray( texture, 0 ); + + } else { + + textures.setTexture2D( texture, 0 ); + + } + + state.unbindTexture(); + + }; + + /** + * Can be used to reset the internal WebGL state. This method is mostly + * relevant for applications which share a single WebGL context across + * multiple WebGL libraries. + */ + this.resetState = function () { + + _currentActiveCubeFace = 0; + _currentActiveMipmapLevel = 0; + _currentRenderTarget = null; + + state.reset(); + bindingStates.reset(); + + }; + + if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { + + __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); + + } + + } + + /** + * Defines the coordinate system of the renderer. + * + * In `WebGLRenderer`, the value is always `WebGLCoordinateSystem`. + * + * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem} + * @default WebGLCoordinateSystem + * @readonly + */ + get coordinateSystem() { + + return WebGLCoordinateSystem; + + } + + /** + * Defines the output color space of the renderer. + * + * @type {SRGBColorSpace|LinearSRGBColorSpace} + * @default SRGBColorSpace + */ + get outputColorSpace() { + + return this._outputColorSpace; + + } + + set outputColorSpace( colorSpace ) { + + this._outputColorSpace = colorSpace; + + const gl = this.getContext(); + gl.drawingBufferColorSpace = ColorManagement._getDrawingBufferColorSpace( colorSpace ); + gl.unpackColorSpace = ColorManagement._getUnpackColorSpace(); + + } + +} + +export { ACESFilmicToneMapping, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, ArrayCamera, BackSide, BoxGeometry, BufferAttribute, BufferGeometry, ByteType, CineonToneMapping, ClampToEdgeWrapping, Color, ColorManagement, ConstantAlphaFactor, ConstantColorFactor, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeUVReflectionMapping, CullFaceBack, CullFaceFront, CullFaceNone, CustomBlending, CustomToneMapping, Data3DTexture, DataArrayTexture, DepthFormat, DepthStencilFormat, DepthTexture, DoubleSide, DstAlphaFactor, DstColorFactor, EqualCompare, EqualDepth, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, FloatType, FrontSide, Frustum, GLSL3, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, HalfFloatType, IntType, Layers, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LinearFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Matrix3, Matrix4, MaxEquation, Mesh, MeshBasicMaterial, MeshDepthMaterial, MeshDistanceMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NoBlending, NoColorSpace, NoToneMapping, NormalBlending, NotEqualCompare, NotEqualDepth, ObjectSpaceNormalMap, OneFactor, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, PCFShadowMap, PCFSoftShadowMap, PMREMGenerator, PerspectiveCamera, Plane, PlaneGeometry, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBADepthPacking, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBFormat, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RedFormat, RedIntegerFormat, ReinhardToneMapping, RepeatWrapping, ReverseSubtractEquation, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, ShaderChunk, ShaderLib, ShaderMaterial, ShortType, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, SubtractEquation, SubtractiveBlending, TangentSpaceNormalMap, Texture, Uint16BufferAttribute, Uint32BufferAttribute, UniformsLib, UniformsUtils, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, VSMShadowMap, Vector2, Vector3, Vector4, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGLRenderTarget, WebGLRenderer, WebGLUtils, WebXRController, ZeroFactor, createCanvasElement }; diff --git a/clickplanet-webapp/src/app/components/earth/globe.rs b/clickplanet-webapp/src/app/components/earth/globe.rs index 15e53d8..75e9648 100644 --- a/clickplanet-webapp/src/app/components/earth/globe.rs +++ b/clickplanet-webapp/src/app/components/earth/globe.rs @@ -1,54 +1,15 @@ use dioxus::prelude::*; -use log::{debug, error, info}; -use web_sys::HtmlCanvasElement; -use wasm_bindgen::JsCast; -use wasm_bindgen_futures; -use crate::app::components::earth::setup_webgpu::{setup_scene, use_animation_state}; +use log::info; +/// The Globe component acts as a wrapper for our Three.js implementation +/// This uses the Three.js renderer instead of WebGPU directly for better compatibility #[component] -pub fn globe() -> Element { - let mut canvas_ref = use_signal(|| None::); - - // Create animation state signal that will be used for rotation - let rotation = use_animation_state(); - - use_effect(move || { - to_owned![canvas_ref, rotation]; - wasm_bindgen_futures::spawn_local(async move { - if let Some(canvas) = canvas_ref.read().clone() { - info!("Canvas found - initializing WebGPU Earth rendering"); - // Hand off to setup_webgpu for real initialization with animation signal - setup_scene(canvas, rotation).await; - } else { - error!("No canvas found for globe rendering"); - } - }); - - () - }); +pub fn Globe() -> Element { + info!("Rendering Earth Globe with Three.js"); rsx! { - div { - style: "width: 100%; height: 100%; overflow: hidden;", - canvas { - id: "globe-canvas", - style: "width: 100%; height: 100%; display: block; background-color: #001020;", - onmounted: move |_| { - debug!("Canvas mounted"); - let window = web_sys::window().expect("no global window"); - let document = window.document().expect("no document on window"); - if let Some(element) = document.get_element_by_id("globe-canvas") { - if let Some(canvas) = element.dyn_ref::() { - debug!("Canvas element captured"); - canvas_ref.set(Some(canvas.clone())); - } else { - error!("Failed to convert to HtmlCanvasElement"); - } - } else { - error!("Could not find canvas element with ID 'globe-canvas'"); - } - } - } + div { class: "globe-container", + crate::app::components::earth::three_js::ThreeJsGlobe {} } } } \ No newline at end of file diff --git a/clickplanet-webapp/src/app/components/earth/mod.rs b/clickplanet-webapp/src/app/components/earth/mod.rs index 2a16719..8db021c 100644 --- a/clickplanet-webapp/src/app/components/earth/mod.rs +++ b/clickplanet-webapp/src/app/components/earth/mod.rs @@ -1,5 +1,3 @@ pub mod globe; -mod create_sphere; -mod setup_webgpu; -mod animation_loop; -mod shader_validation; +pub mod wgpu; +pub mod three_js; diff --git a/clickplanet-webapp/src/app/components/earth/three_js/bindings.rs b/clickplanet-webapp/src/app/components/earth/three_js/bindings.rs new file mode 100644 index 0000000..cffd334 --- /dev/null +++ b/clickplanet-webapp/src/app/components/earth/three_js/bindings.rs @@ -0,0 +1,155 @@ +use wasm_bindgen::prelude::*; +use web_sys::Element; + +// Three.js bindings - using standard imports without module paths +#[wasm_bindgen] +extern "C" { + // Main Three.js namespace + #[wasm_bindgen(js_namespace = THREE)] + pub type Scene; + + #[wasm_bindgen(constructor, js_namespace = THREE)] + pub fn new() -> Scene; + + #[wasm_bindgen(method, js_namespace = THREE, js_name = add)] + pub fn add(this: &Scene, object: &Object3D); + + #[wasm_bindgen(js_namespace = THREE)] + pub type Object3D; + + #[wasm_bindgen(extends = Object3D, js_namespace = THREE)] + pub type Mesh; + + #[wasm_bindgen(constructor, js_namespace = THREE)] + pub fn new_with_geometry_material(geometry: &BufferGeometry, material: &Material) -> Mesh; + + #[wasm_bindgen(js_namespace = THREE)] + pub type WebGLRenderer; + + #[wasm_bindgen(constructor, js_namespace = THREE)] + pub fn new_with_parameters(params: &JsValue) -> WebGLRenderer; + + #[wasm_bindgen(method, js_namespace = THREE, js_name = setSize)] + pub fn set_size(this: &WebGLRenderer, width: f64, height: f64); + + #[wasm_bindgen(method, js_namespace = THREE, js_name = setClearColor)] + pub fn set_clear_color(this: &WebGLRenderer, color: u32); + + #[wasm_bindgen(method, getter, js_namespace = THREE)] + pub fn domElement(this: &WebGLRenderer) -> Element; + + #[wasm_bindgen(method, js_namespace = THREE, js_name = render)] + pub fn render(this: &WebGLRenderer, scene: &Scene, camera: &OrthographicCamera); + + #[wasm_bindgen(method, js_namespace = THREE, js_name = dispose)] + pub fn dispose(this: &WebGLRenderer); + + #[wasm_bindgen(extends = Object3D, js_namespace = THREE)] + pub type OrthographicCamera; + + #[wasm_bindgen(constructor, js_namespace = THREE)] + pub fn new(left: f64, right: f64, top: f64, bottom: f64, near: f64, far: f64) -> OrthographicCamera; + + #[wasm_bindgen(method, getter, js_namespace = THREE, js_name = position)] + pub fn position(this: &OrthographicCamera) -> Vector3; + + #[wasm_bindgen(method, js_namespace = THREE, js_name = updateProjectionMatrix)] + pub fn update_projection_matrix(this: &OrthographicCamera); + + #[wasm_bindgen(method, getter, js_namespace = THREE)] + pub fn zoom(this: &OrthographicCamera) -> f64; + + #[wasm_bindgen(method, setter, js_namespace = THREE)] + pub fn set_left(this: &OrthographicCamera, left: f64); + + #[wasm_bindgen(method, setter, js_namespace = THREE)] + pub fn set_right(this: &OrthographicCamera, right: f64); + + #[wasm_bindgen(extends = Object3D, js_namespace = THREE)] + pub type AmbientLight; + + #[wasm_bindgen(constructor, js_namespace = THREE)] + pub fn new(color: u32, intensity: f64) -> AmbientLight; + + #[wasm_bindgen(js_namespace = THREE)] + pub type BufferGeometry; + + #[wasm_bindgen(js_namespace = THREE)] + pub type IcosahedronGeometry; + + #[wasm_bindgen(constructor, js_namespace = THREE)] + pub fn new(radius: f64, detail: u32) -> IcosahedronGeometry; + + #[wasm_bindgen(js_namespace = THREE)] + pub type Material; + + #[wasm_bindgen(js_namespace = THREE)] + pub type MeshStandardMaterial; + + #[wasm_bindgen(constructor, js_namespace = THREE)] + pub fn new_with_params(params: &JsValue) -> MeshStandardMaterial; + + #[wasm_bindgen(js_namespace = THREE)] + pub type Texture; + + #[wasm_bindgen(js_namespace = THREE)] + pub type TextureLoader; + + #[wasm_bindgen(constructor, js_namespace = THREE)] + pub fn new() -> TextureLoader; + + #[wasm_bindgen(method, js_namespace = THREE, js_name = load)] + pub fn load(this: &TextureLoader, url: &str) -> Texture; + + #[wasm_bindgen(js_namespace = THREE)] + pub type Vector3; + + #[wasm_bindgen(constructor, js_namespace = THREE)] + pub fn new(x: f64, y: f64, z: f64) -> Vector3; + + #[wasm_bindgen(method, setter, js_namespace = THREE)] + pub fn set_z(this: &Vector3, z: f64); + + #[wasm_bindgen(js_namespace = THREE)] + pub type Vector2; + + #[wasm_bindgen(constructor, js_namespace = THREE)] + pub fn new(x: f64, y: f64) -> Vector2; + +} + +// OrbitControls bindings - using standard imports +#[wasm_bindgen] +extern "C" { + pub type OrbitControls; + + #[wasm_bindgen(constructor)] + pub fn new(camera: &OrthographicCamera, dom_element: &Element) -> OrbitControls; + + #[wasm_bindgen(method)] + pub fn update(this: &OrbitControls); + + #[wasm_bindgen(method, setter)] + pub fn set_min_zoom(this: &OrbitControls, min_zoom: f64); + + #[wasm_bindgen(method, setter)] + pub fn set_max_zoom(this: &OrbitControls, max_zoom: f64); + + #[wasm_bindgen(method, setter)] + pub fn set_pan_speed(this: &OrbitControls, speed: f64); + + #[wasm_bindgen(method, setter)] + pub fn set_enable_damping(this: &OrbitControls, enable: bool); + + #[wasm_bindgen(method, setter)] + pub fn set_auto_rotate(this: &OrbitControls, auto_rotate: bool); + + #[wasm_bindgen(method, setter)] + pub fn set_auto_rotate_speed(this: &OrbitControls, speed: f64); + + #[wasm_bindgen(method, setter)] + pub fn set_rotate_speed(this: &OrbitControls, speed: f64); + + #[wasm_bindgen(method, js_name = addEventListener)] + pub fn add_event_listener(this: &OrbitControls, event_name: &str, callback: &Closure); +} diff --git a/clickplanet-webapp/src/app/components/earth/three_js/globe.rs b/clickplanet-webapp/src/app/components/earth/three_js/globe.rs new file mode 100644 index 0000000..54f1c9c --- /dev/null +++ b/clickplanet-webapp/src/app/components/earth/three_js/globe.rs @@ -0,0 +1,279 @@ +use wasm_bindgen::prelude::*; +use web_sys::{HtmlCanvasElement, window}; +use gloo_utils::document; +use std::rc::Rc; +use std::cell::RefCell; +use log::info; + +use super::bindings::*; + +// Global state for ThreeJS objects +thread_local! { + static SCENE: RefCell> = RefCell::new(None); + static CAMERA: RefCell> = RefCell::new(None); + static RENDERER: RefCell> = RefCell::new(None); + static CONTROLS: RefCell> = RefCell::new(None); + static EARTH_MESH: RefCell> = RefCell::new(None); + static ANIMATION_FRAME: RefCell> = RefCell::new(None); + static CALLBACKS: RefCell>> = RefCell::new(Vec::new()); +} + +/// Initialize the Three.js scene with the Earth globe +pub fn init_globe(canvas_id: &str) -> Result<(), JsError> { + // Set the static site URL as a global variable for texture loading + let static_site = env!("CITYWARS_STATIC_SITE"); + let window = web_sys::window().ok_or_else(|| JsError::new("No window found"))?; + + // Set the static site URL directly on the window object + js_sys::Reflect::set( + &window, + &JsValue::from_str("CITYWARS_STATIC_SITE"), + &JsValue::from_str(static_site) + ).map_err(|_| JsError::new("Failed to set static site URL"))?; + // Get the canvas element + let document = document(); + let canvas = document + .get_element_by_id(canvas_id) + .ok_or_else(|| JsError::new(&format!("No canvas found with id: {}", canvas_id)))?; + + let canvas: HtmlCanvasElement = canvas + .dyn_into::() + .map_err(|_| JsError::new("Element is not a canvas"))?; + + // Create scene + let scene = Scene::new(); + + // Set up camera + let web_window = web_sys::window().ok_or_else(|| JsError::new("No window found"))?; + let width = web_window.inner_width().unwrap().as_f64().unwrap(); + let height = web_window.inner_height().unwrap().as_f64().unwrap(); + let aspect = width / height; + let camera_size = 1.0; + + let camera = OrthographicCamera::new( + -camera_size * aspect, + camera_size * aspect, + camera_size, + -camera_size, + 0.01, + 100.0 + ); + + // Position camera + let position = camera.position(); + position.set_z(5.0); + + // Create renderer with canvas + let renderer_params = js_sys::Object::new(); + js_sys::Reflect::set(&renderer_params, &"canvas".into(), &canvas).unwrap(); + js_sys::Reflect::set(&renderer_params, &"antialias".into(), &JsValue::from_bool(true)).unwrap(); + + let renderer = WebGLRenderer::new_with_parameters(&renderer_params); + renderer.set_size(width, height); + renderer.set_clear_color(0x000000); + + // Add lighting + let light = AmbientLight::new(0xffffff, 2.0); + scene.add(&light); + + // Create earth sphere + let static_site = env!("CITYWARS_STATIC_SITE"); + let texture_loader = TextureLoader::new(); + let earth_texture = texture_loader.load(&format!("{}/earth/3_no_ice_clouds_16k.jpg", static_site)); + + let material_params = js_sys::Object::new(); + js_sys::Reflect::set(&material_params, &"map".into(), &earth_texture).unwrap(); + + let earth_geometry = IcosahedronGeometry::new(0.999, 50); + let earth_material = MeshStandardMaterial::new_with_params(&material_params); + // Cast to appropriate types for function call + let geometry_js_value: &JsValue = earth_geometry.as_ref(); + let material_js_value: &JsValue = earth_material.as_ref(); + let buffer_geometry = geometry_js_value.unchecked_ref::(); + let material = material_js_value.unchecked_ref::(); + let earth_mesh = Mesh::new_with_geometry_material(buffer_geometry, material); + + scene.add(&earth_mesh); + + // Set up orbit controls + // Create OrbitControls instance directly using the constructor binding + let controls = OrbitControls::new(&camera, &renderer.domElement()); + controls.set_min_zoom(1.0); + controls.set_max_zoom(50.0); + controls.set_pan_speed(0.1); + controls.set_enable_damping(true); + controls.set_auto_rotate(true); + controls.set_auto_rotate_speed(0.5); + + // Add handler for orbit controls changes + let control_change_callback = Closure::wrap(Box::new(move || { + CONTROLS.with(|controls_ref| { + if let Some(controls) = &*controls_ref.borrow() { + CAMERA.with(|camera_ref| { + if let Some(camera) = &*camera_ref.borrow() { + let zoom = camera.zoom(); + controls.set_auto_rotate(zoom == 1.0); + controls.set_rotate_speed((1.0 / zoom) / 1.5); + } + }); + } + }); + }) as Box); + + controls.add_event_listener("change", &control_change_callback); + + // Store callback to prevent it from being dropped + CALLBACKS.with(|callbacks| { + callbacks.borrow_mut().push(control_change_callback); + }); + + // Handle window resize + let resize_callback = Closure::wrap(Box::new(move || { + let web_window = web_sys::window().unwrap(); + let width = web_window.inner_width().unwrap().as_f64().unwrap(); + let height = web_window.inner_height().unwrap().as_f64().unwrap(); + let aspect = width / height; + let camera_size = 1.0; + + CAMERA.with(|camera_ref| { + if let Some(camera) = &*camera_ref.borrow() { + // Update camera aspect ratio + camera.set_left(-camera_size * aspect); + camera.set_right(camera_size * aspect); + camera.update_projection_matrix(); + } + }); + + RENDERER.with(|renderer_ref| { + if let Some(renderer) = &*renderer_ref.borrow() { + renderer.set_size(width, height); + } + }); + }) as Box); + + let web_window = web_sys::window().ok_or_else(|| JsError::new("No window found"))?; + web_window.add_event_listener_with_callback("resize", resize_callback.as_ref().unchecked_ref()) + .map_err(|_| JsError::new("Failed to add resize event listener"))?; + + // Store callback to prevent it from being dropped + CALLBACKS.with(|callbacks| { + callbacks.borrow_mut().push(resize_callback); + }); + + // Store the objects + SCENE.with(|scene_ref| { + *scene_ref.borrow_mut() = Some(scene); + }); + + CAMERA.with(|camera_ref| { + *camera_ref.borrow_mut() = Some(camera); + }); + + RENDERER.with(|renderer_ref| { + *renderer_ref.borrow_mut() = Some(renderer); + }); + + CONTROLS.with(|controls_ref| { + *controls_ref.borrow_mut() = Some(controls); + }); + + EARTH_MESH.with(|earth_mesh_ref| { + *earth_mesh_ref.borrow_mut() = Some(earth_mesh); + }); + + // Start animation loop + start_animation(); + + info!("Three.js Earth globe initialized"); + Ok(()) +} + +// Animation loop +fn start_animation() { + let f = Rc::new(RefCell::new(None)); + let g = f.clone(); + + *g.borrow_mut() = Some(Closure::wrap(Box::new(move || { + // Request next frame + request_animation_frame(f.borrow().as_ref().unwrap()); + + // Update controls + CONTROLS.with(|controls_ref| { + if let Some(controls) = &*controls_ref.borrow() { + controls.update(); + } + }); + + // Render scene + SCENE.with(|scene_ref| { + if let Some(scene) = &*scene_ref.borrow() { + CAMERA.with(|camera_ref| { + if let Some(camera) = &*camera_ref.borrow() { + RENDERER.with(|renderer_ref| { + if let Some(renderer) = &*renderer_ref.borrow() { + renderer.render(scene, camera); + } + }); + } + }); + } + }); + }) as Box)); + + // Start the first frame + request_animation_frame(g.borrow().as_ref().unwrap()); +} + +// Helper function to request animation frame +fn request_animation_frame(f: &Closure) { + let web_window = web_sys::window().unwrap(); + let id = web_window + .request_animation_frame(f.as_ref().unchecked_ref()) + .expect("Failed to request animation frame"); + + ANIMATION_FRAME.with(|frame_ref| { + *frame_ref.borrow_mut() = Some(id); + }); +} + +/// Clean up Three.js resources +pub fn cleanup_globe() { + // Cancel animation frame + ANIMATION_FRAME.with(|frame_ref| { + if let Some(id) = *frame_ref.borrow() { + let web_window = web_sys::window().unwrap(); + web_window.cancel_animation_frame(id).unwrap(); + *frame_ref.borrow_mut() = None; + } + }); + + // Dispose renderer + RENDERER.with(|renderer_ref| { + if let Some(renderer) = &*renderer_ref.borrow() { + renderer.dispose(); + *renderer_ref.borrow_mut() = None; + } + }); + + // Clear references to other objects + SCENE.with(|scene_ref| { + *scene_ref.borrow_mut() = None; + }); + + CAMERA.with(|camera_ref| { + *camera_ref.borrow_mut() = None; + }); + + CONTROLS.with(|controls_ref| { + *controls_ref.borrow_mut() = None; + }); + + EARTH_MESH.with(|earth_mesh_ref| { + *earth_mesh_ref.borrow_mut() = None; + }); + + // Clear callbacks + CALLBACKS.with(|callbacks| { + callbacks.borrow_mut().clear(); + }); +} diff --git a/clickplanet-webapp/src/app/components/earth/three_js/mod.rs b/clickplanet-webapp/src/app/components/earth/three_js/mod.rs new file mode 100644 index 0000000..9392223 --- /dev/null +++ b/clickplanet-webapp/src/app/components/earth/three_js/mod.rs @@ -0,0 +1,66 @@ +mod bindings; +mod globe; + +use dioxus::prelude::*; +use dioxus::document; +use wasm_bindgen_futures::spawn_local; +use log::error; + +pub use self::globe::init_globe; + +#[component] +pub fn ThreeJsGlobe() -> Element { + let canvas_id = "three-js-canvas"; + let mut scripts_loaded = use_signal(|| false); + + // Initialize Three.js when scripts are loaded + use_effect(move || { + if scripts_loaded() { + // Initialize Three.js with the canvas element + spawn_local(async move { + if let Err(e) = init_globe(canvas_id) { + error!("Failed to initialize Three.js: {:?}", e); + } + }); + } + () + }); + + // Set a timer to mark scripts as loaded after a delay + // This is a workaround since onload is not directly available + use_effect(move || { + // A timeout ensures scripts are loaded before we attempt to use them + let timeout_ms = 500; + let handle = gloo_timers::callback::Timeout::new(timeout_ms, move || { + scripts_loaded.set(true); + }); + + (|| { drop(handle); })() + }); + + rsx! { + // Load Three.js and OrbitControls in head + document::Script { + src: asset!("public/js/three.module.js"), + r#type: "module" + } + + document::Script { + src: asset!("public/js/OrbitControls.js"), + r#type: "module" + } + + div { + id: "three-js-container", + style: "width: 100%; height: 100vh; overflow: hidden;", + + // Canvas for Three.js rendering + canvas { + id: "{canvas_id}", + width: "100%", + height: "100%", + style: "display: block; background-color: #000;" + } + } + } +} diff --git a/clickplanet-webapp/src/app/components/earth/animation_loop.rs b/clickplanet-webapp/src/app/components/earth/wgpu/animation_loop.rs similarity index 98% rename from clickplanet-webapp/src/app/components/earth/animation_loop.rs rename to clickplanet-webapp/src/app/components/earth/wgpu/animation_loop.rs index 6ff0423..3ffaa04 100644 --- a/clickplanet-webapp/src/app/components/earth/animation_loop.rs +++ b/clickplanet-webapp/src/app/components/earth/wgpu/animation_loop.rs @@ -4,7 +4,7 @@ use log::{debug, info}; use wasm_bindgen_futures::spawn_local; use glam::{Mat4, Vec3}; -use crate::app::components::earth::setup_webgpu::{Uniforms, WebGpuContext}; +use super::setup_webgpu::{Uniforms, WebGpuContext}; #[allow(dead_code)] pub struct RenderLoopContext { diff --git a/clickplanet-webapp/src/app/components/earth/create_sphere.rs b/clickplanet-webapp/src/app/components/earth/wgpu/create_sphere.rs similarity index 100% rename from clickplanet-webapp/src/app/components/earth/create_sphere.rs rename to clickplanet-webapp/src/app/components/earth/wgpu/create_sphere.rs diff --git a/clickplanet-webapp/src/app/components/earth/earth_textured.wgsl b/clickplanet-webapp/src/app/components/earth/wgpu/earth_textured.wgsl similarity index 100% rename from clickplanet-webapp/src/app/components/earth/earth_textured.wgsl rename to clickplanet-webapp/src/app/components/earth/wgpu/earth_textured.wgsl diff --git a/clickplanet-webapp/src/app/components/earth/wgpu/mod.rs b/clickplanet-webapp/src/app/components/earth/wgpu/mod.rs new file mode 100644 index 0000000..bb007f2 --- /dev/null +++ b/clickplanet-webapp/src/app/components/earth/wgpu/mod.rs @@ -0,0 +1,9 @@ +mod animation_loop; +mod setup_webgpu; +mod shader_validation; +mod create_sphere; + +pub use animation_loop::*; +pub use setup_webgpu::*; +pub use shader_validation::*; +pub use create_sphere::*; diff --git a/clickplanet-webapp/src/app/components/earth/setup_webgpu.rs b/clickplanet-webapp/src/app/components/earth/wgpu/setup_webgpu.rs similarity index 98% rename from clickplanet-webapp/src/app/components/earth/setup_webgpu.rs rename to clickplanet-webapp/src/app/components/earth/wgpu/setup_webgpu.rs index 0209de1..0eeddb9 100644 --- a/clickplanet-webapp/src/app/components/earth/setup_webgpu.rs +++ b/clickplanet-webapp/src/app/components/earth/wgpu/setup_webgpu.rs @@ -8,8 +8,8 @@ use wasm_bindgen_futures::spawn_local; use gloo_net::http::Request; use image::{GenericImageView, imageops::FilterType}; -use crate::app::components::earth::create_sphere::{Vertex, create_sphere}; -use crate::app::components::earth::animation_loop::{start_animation, RenderLoopContext}; +use super::create_sphere::{Vertex, create_sphere}; +use super::animation_loop::{start_animation, RenderLoopContext}; #[cfg(test)] use crate::app::components::earth::shader_validation::validate_shader_code; diff --git a/clickplanet-webapp/src/app/components/earth/shader_validation.rs b/clickplanet-webapp/src/app/components/earth/wgpu/shader_validation.rs similarity index 100% rename from clickplanet-webapp/src/app/components/earth/shader_validation.rs rename to clickplanet-webapp/src/app/components/earth/wgpu/shader_validation.rs diff --git a/clickplanet-webapp/src/main.rs b/clickplanet-webapp/src/main.rs index 4365d85..57108e7 100644 --- a/clickplanet-webapp/src/main.rs +++ b/clickplanet-webapp/src/main.rs @@ -89,7 +89,7 @@ fn Home() -> Element { } } - // app::components::earth::globe::globe {} + app::components::earth::globe::Globe {} div { class: "menu", app::components::leaderboard::Leaderboard {} From 3265af247689736fb11210c0eee2afafd79b01e5 Mon Sep 17 00:00:00 2001 From: Laurent Valdes Date: Mon, 5 May 2025 23:40:26 +0200 Subject: [PATCH 09/28] feat(threejs): implement ThreeJs integration with spinning cube - Add Three.js bindings for WebAssembly interaction - Create spinning cube component as initial 3D element - Fix borrow checker issues in animation loop - Clean up console logging - Implement proper script loading - Improve error handling for WebGL renderer --- .../src/app/components/earth/globe.rs | 104 ++++++++- .../app/components/earth/three_js/bindings.rs | 102 ++++++++- .../src/app/components/earth/three_js/cube.rs | 216 ++++++++++++++++++ .../app/components/earth/three_js/globe.rs | 8 + .../src/app/components/earth/three_js/mod.rs | 36 ++- clickplanet-webapp/src/main.rs | 39 ++-- 6 files changed, 471 insertions(+), 34 deletions(-) create mode 100644 clickplanet-webapp/src/app/components/earth/three_js/cube.rs diff --git a/clickplanet-webapp/src/app/components/earth/globe.rs b/clickplanet-webapp/src/app/components/earth/globe.rs index 75e9648..21ab31b 100644 --- a/clickplanet-webapp/src/app/components/earth/globe.rs +++ b/clickplanet-webapp/src/app/components/earth/globe.rs @@ -1,15 +1,111 @@ use dioxus::prelude::*; -use log::info; +use gloo_timers::callback::Timeout; /// The Globe component acts as a wrapper for our Three.js implementation /// This uses the Three.js renderer instead of WebGPU directly for better compatibility #[component] pub fn Globe() -> Element { - info!("Rendering Earth Globe with Three.js"); + let mut cube_loaded = use_signal(|| false); + let mut scripts_loaded = use_signal(|| false); + let canvas_id = "simple-cube-canvas"; + + // Check if scripts are loaded and initialize Three.js + use_effect(move || { + if scripts_loaded() { + use wasm_bindgen_futures::spawn_local; + use crate::app::components::earth::three_js::{init_cube, is_three_available}; + + spawn_local(async move { + // Additional verification that Three.js is available + if is_three_available() { + if let Err(_) = init_cube(canvas_id) { + // Silently handle error + } else { + cube_loaded.set(true); + } + } + }); + } + + // No cleanup needed + () + }); + + // Set a timer to check if scripts are loaded + use_effect(move || { + use wasm_bindgen::prelude::*; + + // Wait for scripts to load + let timeout_ms = 1000; // Give scripts enough time to load + + let handle = Timeout::new(timeout_ms, move || { + // Check if Three.js is available after timeout + use crate::app::components::earth::three_js::is_three_available; + + let three_available = is_three_available(); + if three_available { + scripts_loaded.set(true); + } + }); + + // Cleanup function + (|| { drop(handle); })() + }); + + // Simplified script loading - load Three.js directly in the RSX + // Then use the hook to check if it's available and initialize the cube + // Check if scripts are loaded and initialize Three.js - this is called immediately and after scripts load + use_effect(move || { + use wasm_bindgen::prelude::*; + use wasm_bindgen_futures::spawn_local; + use crate::app::components::earth::three_js::{init_cube, is_three_available}; + + // Check if Three.js is available + spawn_local(async move { + // Direct check - wait a little to ensure scripts have a chance to load + gloo_timers::future::TimeoutFuture::new(500).await; + + let three_available = is_three_available(); + + if three_available { + scripts_loaded.set(true); + + // Now initialize the cube + if let Err(_) = init_cube(canvas_id) { + // Silently handle error + } else { + cube_loaded.set(true); + } + } + }); + + // No cleanup needed + () + }); + rsx! { - div { class: "globe-container", - crate::app::components::earth::three_js::ThreeJsGlobe {} + // Load Three.js as a regular script (not a module) to make it globally available + document::Script { + src: "https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.min.js" + } + + // Load OrbitControls after Three.js + document::Script { + src: "https://cdn.jsdelivr.net/npm/three@0.160.0/examples/js/controls/OrbitControls.js" + } + + div { + class: "earth-container", + style: "width: 100%; height: 100vh; overflow: hidden;", + + // Canvas for Three.js rendering + canvas { + id: "{canvas_id}", + width: "100%", + height: "100%", + style: "display: block; background-color: #000;" + } } } } \ No newline at end of file diff --git a/clickplanet-webapp/src/app/components/earth/three_js/bindings.rs b/clickplanet-webapp/src/app/components/earth/three_js/bindings.rs index cffd334..bae4c8a 100644 --- a/clickplanet-webapp/src/app/components/earth/three_js/bindings.rs +++ b/clickplanet-webapp/src/app/components/earth/three_js/bindings.rs @@ -16,6 +16,9 @@ extern "C" { #[wasm_bindgen(js_namespace = THREE)] pub type Object3D; + + #[wasm_bindgen(method, getter, js_namespace = THREE)] + pub fn rotation(this: &Object3D) -> Euler; #[wasm_bindgen(extends = Object3D, js_namespace = THREE)] pub type Mesh; @@ -38,11 +41,22 @@ extern "C" { #[wasm_bindgen(method, getter, js_namespace = THREE)] pub fn domElement(this: &WebGLRenderer) -> Element; + // Generic render method that can handle any camera type by using JsValue #[wasm_bindgen(method, js_namespace = THREE, js_name = render)] - pub fn render(this: &WebGLRenderer, scene: &Scene, camera: &OrthographicCamera); + pub fn render(this: &WebGLRenderer, scene: &Scene, camera: &JsValue); #[wasm_bindgen(method, js_namespace = THREE, js_name = dispose)] pub fn dispose(this: &WebGLRenderer); + + // PerspectiveCamera for the cube example + #[wasm_bindgen(extends = Object3D, js_namespace = THREE)] + pub type PerspectiveCamera; + + #[wasm_bindgen(constructor, js_namespace = THREE)] + pub fn new(fov: f64, aspect: f64, near: f64, far: f64) -> PerspectiveCamera; + + #[wasm_bindgen(method, getter, js_namespace = THREE, js_name = position)] + pub fn position(this: &PerspectiveCamera) -> Vector3; #[wasm_bindgen(extends = Object3D, js_namespace = THREE)] pub type OrthographicCamera; @@ -71,17 +85,33 @@ extern "C" { #[wasm_bindgen(constructor, js_namespace = THREE)] pub fn new(color: u32, intensity: f64) -> AmbientLight; + // Base BufferGeometry type #[wasm_bindgen(js_namespace = THREE)] pub type BufferGeometry; + + // BoxGeometry extends BufferGeometry + #[wasm_bindgen(js_namespace = THREE)] + pub type BoxGeometry; + + #[wasm_bindgen(constructor, js_namespace = THREE)] + pub fn new(width: f64, height: f64, depth: f64) -> BoxGeometry; #[wasm_bindgen(js_namespace = THREE)] pub type IcosahedronGeometry; #[wasm_bindgen(constructor, js_namespace = THREE)] pub fn new(radius: f64, detail: u32) -> IcosahedronGeometry; - + + // Base Material type #[wasm_bindgen(js_namespace = THREE)] pub type Material; + + // MeshBasicMaterial extends Material + #[wasm_bindgen(js_namespace = THREE)] + pub type MeshBasicMaterial; + + #[wasm_bindgen(constructor, js_namespace = THREE)] + pub fn new_with_params(params: &JsValue) -> MeshBasicMaterial; #[wasm_bindgen(js_namespace = THREE)] pub type MeshStandardMaterial; @@ -100,6 +130,22 @@ extern "C" { #[wasm_bindgen(method, js_namespace = THREE, js_name = load)] pub fn load(this: &TextureLoader, url: &str) -> Texture; + + // Euler for rotation + #[wasm_bindgen(js_namespace = THREE)] + pub type Euler; + + #[wasm_bindgen(method, getter, js_namespace = THREE)] + pub fn x(this: &Euler) -> f64; + + #[wasm_bindgen(method, getter, js_namespace = THREE)] + pub fn y(this: &Euler) -> f64; + + #[wasm_bindgen(method, setter, js_namespace = THREE)] + pub fn set_x(this: &Euler, x: f64); + + #[wasm_bindgen(method, setter, js_namespace = THREE)] + pub fn set_y(this: &Euler, y: f64); #[wasm_bindgen(js_namespace = THREE)] pub type Vector3; @@ -118,6 +164,58 @@ extern "C" { } +// Function to check if Three.js is available in the global scope +pub fn is_three_available() -> bool { + use wasm_bindgen::prelude::*; + use web_sys::console; + + // Try to access the THREE global object via window + console::log_1(&JsValue::from_str("Checking for THREE global object...")); + + if let Some(window) = web_sys::window() { + // Log all available global objects for debugging + if let Ok(keys) = js_sys::Reflect::own_keys(&window) { + console::log_2( + &JsValue::from_str("Window global objects available:"), + &keys + ); + } + + // Check if THREE is directly available on window + if js_sys::Reflect::has(&window, &JsValue::from_str("THREE")).unwrap_or(false) { + console::log_1(&JsValue::from_str("THREE found directly on window object!")); + return true; + } + + // Try the eval approach as a backup + let eval_script = r#"(function() { + try { + if (typeof THREE !== 'undefined') { + console.log('THREE found with type:', typeof THREE); + console.log('THREE version:', THREE.REVISION || 'unknown'); + return true; + } else { + console.log('THREE is undefined in global scope'); + return false; + } + } catch(err) { + console.error('Error checking THREE:', err); + return false; + } + })() + "#; + + // Execute the evaluation script + if let Ok(result) = js_sys::eval(eval_script) { + console::log_1(&JsValue::from_str(&format!("THREE availability check result: {}", result.is_truthy()))); + return result.is_truthy(); + } + } + + console::log_1(&JsValue::from_str("Failed to check THREE availability")); + false +} + // OrbitControls bindings - using standard imports #[wasm_bindgen] extern "C" { diff --git a/clickplanet-webapp/src/app/components/earth/three_js/cube.rs b/clickplanet-webapp/src/app/components/earth/three_js/cube.rs new file mode 100644 index 0000000..38002d5 --- /dev/null +++ b/clickplanet-webapp/src/app/components/earth/three_js/cube.rs @@ -0,0 +1,216 @@ +use wasm_bindgen::prelude::*; +use web_sys::{HtmlCanvasElement}; +use gloo_utils::document; +use std::cell::RefCell; + +use super::bindings::*; + +// Use a struct to hold the animation state to avoid thread_local borrowing issues +struct ThreeJsState { + scene: Option, + camera: Option, + renderer: Option, + cube: Option, + animation_frame: Option, +} + +// Global state for ThreeJS objects +thread_local! { + static STATE: RefCell = RefCell::new(ThreeJsState { + scene: None, + camera: None, + renderer: None, + cube: None, + animation_frame: None, + }); + static CALLBACKS: RefCell>> = RefCell::new(Vec::new()); +} + +/// Initialize a simple Three.js scene with a spinning cube +pub fn init_cube(canvas_id: &str) -> Result<(), JsError> { + // Clean up any previous instance + cleanup_cube(); + + // Get the canvas element + let document = document(); + let canvas = document + .get_element_by_id(canvas_id) + .ok_or_else(|| JsError::new(&format!("No canvas found with id: {}", canvas_id)))?; + + let canvas: HtmlCanvasElement = canvas + .dyn_into::() + .map_err(|_| JsError::new("Element is not a canvas"))?; + + // Create scene + let scene = Scene::new(); + + // Set up camera + let window = web_sys::window().ok_or_else(|| JsError::new("No window found"))?; + let width = window.inner_width().unwrap().as_f64().unwrap(); + let height = window.inner_height().unwrap().as_f64().unwrap(); + let aspect = width / height; + + let camera = PerspectiveCamera::new(75.0, aspect, 0.1, 1000.0); + camera.position().set_z(5.0); + + // Create renderer + let renderer_params = js_sys::Object::new(); + js_sys::Reflect::set(&renderer_params, &JsValue::from_str("canvas"), &canvas) + .map_err(|_| JsError::new("Failed to set canvas parameter"))?; + + let renderer = WebGLRenderer::new_with_parameters(&renderer_params); + renderer.set_size(width, height); + renderer.set_clear_color(0x000000); + + // Create a cube + let geometry = BoxGeometry::new(1.0, 1.0, 1.0); + // Create material with green color (0x00ff00 = 65280 in decimal) + let material_params = js_sys::Object::new(); + js_sys::Reflect::set(&material_params, &JsValue::from_str("color"), &JsValue::from_f64(65280.0)) + .map_err(|_| JsError::new("Failed to set material color"))?; + + let material = MeshBasicMaterial::new_with_params(&material_params); + + // Convert types implicitly using JsValue for JavaScript interop + let geom_js: &JsValue = geometry.as_ref(); + let mat_js: &JsValue = material.as_ref(); + + // Create the mesh with the geometry and material + let cube = Mesh::new_with_geometry_material( + &geom_js.clone().into(), // Convert to the expected BufferGeometry type + &mat_js.clone().into(), // Convert to the expected Material type + ); + + // Add cube to scene + scene.add(&cube); + + // Store objects in our state struct + STATE.with(|state_ref| { + let mut state = state_ref.borrow_mut(); + state.scene = Some(scene); + state.camera = Some(camera); + state.renderer = Some(renderer); + state.cube = Some(cube); + }); + + // Start animation loop + start_animation()?; + + // Cube initialization complete + Ok(()) +} + +/// Start the animation loop for the cube +fn start_animation() -> Result<(), JsError> { + // Create animation callback + let callback = Closure::wrap(Box::new(move || { + // Use a safer approach by getting each piece of state individually + STATE.with(|state_ref| { + // First, check if everything is initialized + let is_initialized = { + let state = state_ref.borrow(); + state.scene.is_some() && state.camera.is_some() && + state.renderer.is_some() && state.cube.is_some() + }; + + if !is_initialized { + return; + } + + // Handle cube rotation - separate borrow + { + let state = state_ref.borrow(); + if let Some(cube) = &state.cube { + // Get the current rotation values + let current_x = cube.rotation().x(); + let current_y = cube.rotation().y(); + + // Update rotation + cube.rotation().set_x(current_x + 0.01); + cube.rotation().set_y(current_y + 0.01); + } + } + + // Render the scene - separate borrow + { + let state = state_ref.borrow(); + if let (Some(scene), Some(camera), Some(renderer)) = ( + &state.scene, &state.camera, &state.renderer) { + // Convert camera to JsValue for the render method + let camera_js: &JsValue = camera.as_ref(); + renderer.render(scene, camera_js); + } + } + + // Request next animation frame - separate borrow + CALLBACKS.with(|callbacks_ref| { + let callback = callbacks_ref.borrow(); + if let Some(callback) = callback.get(0) { + let id = request_animation_frame(callback); + // Update animation frame ID with a new borrow + let mut state = state_ref.borrow_mut(); + state.animation_frame = Some(id); + } + }); + }); + }) as Box); + + // Store callback to keep it alive + CALLBACKS.with(|callbacks_ref| { + callbacks_ref.borrow_mut().push(callback); + }); + + // Request first animation frame + CALLBACKS.with(|callbacks_ref| { + let callback = callbacks_ref.borrow(); + if let Some(callback) = callback.get(0) { + let id = request_animation_frame(callback); + STATE.with(|state_ref| { + let mut state = state_ref.borrow_mut(); + state.animation_frame = Some(id); + }); + } + }); + + Ok(()) +} + +/// Helper function to request animation frame +fn request_animation_frame(f: &Closure) -> i32 { + let window = web_sys::window().expect("no global window exists"); + window + .request_animation_frame(f.as_ref().unchecked_ref()) + .expect("should register `requestAnimationFrame` OK") +} + +/// Clean up Three.js resources +pub fn cleanup_cube() { + // Cancel animation frame and clean up all resources in a single borrow + STATE.with(|state_ref| { + let mut state = state_ref.borrow_mut(); + + // Cancel animation frame + if let Some(id) = state.animation_frame { + if let Some(window) = web_sys::window() { + window.cancel_animation_frame(id).ok(); + } + } + + // Dispose of renderer if needed + if let Some(renderer) = &state.renderer { + renderer.dispose(); + } + + // Reset all state + state.animation_frame = None; + state.scene = None; + state.camera = None; + state.renderer = None; + state.cube = None; + }); + + // Clear callbacks + CALLBACKS.with(|callbacks_ref| { + callbacks_ref.borrow_mut().clear(); + }); +} diff --git a/clickplanet-webapp/src/app/components/earth/three_js/globe.rs b/clickplanet-webapp/src/app/components/earth/three_js/globe.rs index 54f1c9c..4416349 100644 --- a/clickplanet-webapp/src/app/components/earth/three_js/globe.rs +++ b/clickplanet-webapp/src/app/components/earth/three_js/globe.rs @@ -24,6 +24,14 @@ pub fn init_globe(canvas_id: &str) -> Result<(), JsError> { let static_site = env!("CITYWARS_STATIC_SITE"); let window = web_sys::window().ok_or_else(|| JsError::new("No window found"))?; + // Check if THREE object is available in the global scope + let three_available = js_sys::Reflect::has(&window, &JsValue::from_str("THREE")) + .map_err(|_| JsError::new("Failed to check for THREE global object"))?; + + if !three_available { + return Err(JsError::new("THREE global object not found. Make sure Three.js is loaded properly.")); + } + // Set the static site URL directly on the window object js_sys::Reflect::set( &window, diff --git a/clickplanet-webapp/src/app/components/earth/three_js/mod.rs b/clickplanet-webapp/src/app/components/earth/three_js/mod.rs index 9392223..26a2514 100644 --- a/clickplanet-webapp/src/app/components/earth/three_js/mod.rs +++ b/clickplanet-webapp/src/app/components/earth/three_js/mod.rs @@ -1,12 +1,14 @@ mod bindings; mod globe; +mod cube; use dioxus::prelude::*; use dioxus::document; use wasm_bindgen_futures::spawn_local; -use log::error; pub use self::globe::init_globe; +pub use self::cube::init_cube; +pub use self::bindings::is_three_available; #[component] pub fn ThreeJsGlobe() -> Element { @@ -18,42 +20,52 @@ pub fn ThreeJsGlobe() -> Element { if scripts_loaded() { // Initialize Three.js with the canvas element spawn_local(async move { - if let Err(e) = init_globe(canvas_id) { - error!("Failed to initialize Three.js: {:?}", e); + if let Err(_) = init_globe(canvas_id) { + // Silently handle error } }); } + // No cleanup needed () }); - // Set a timer to mark scripts as loaded after a delay + // Set a timer to mark scripts as loaded after a delay and check THREE availability // This is a workaround since onload is not directly available use_effect(move || { + use wasm_bindgen::prelude::*; + // A timeout ensures scripts are loaded before we attempt to use them let timeout_ms = 500; + let handle = gloo_timers::callback::Timeout::new(timeout_ms, move || { - scripts_loaded.set(true); + // Check if Three.js is available + let three_available = is_three_available(); + + if three_available { + scripts_loaded.set(true); + } }); (|| { drop(handle); })() }); rsx! { - // Load Three.js and OrbitControls in head + // Load Three.js as a regular script (not a module) to make it globally available document::Script { - src: asset!("public/js/three.module.js"), - r#type: "module" + src: "https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.min.js" } - document::Script { - src: asset!("public/js/OrbitControls.js"), - r#type: "module" - } + // Load OrbitControls after Three.js + // document::Script { + // src: "https://cdn.jsdelivr.net/npm/three@0.160.0/examples/js/controls/OrbitControls.js" + //} div { id: "three-js-container", style: "width: 100%; height: 100vh; overflow: hidden;", + + // Canvas for Three.js rendering canvas { id: "{canvas_id}", diff --git a/clickplanet-webapp/src/main.rs b/clickplanet-webapp/src/main.rs index 57108e7..8d2c062 100644 --- a/clickplanet-webapp/src/main.rs +++ b/clickplanet-webapp/src/main.rs @@ -28,18 +28,18 @@ enum Route { fn App() -> Element { rsx! { - document::Link { rel: "icon", href: asset!("public/static/favicon.png") } - Stylesheet { href: asset!("public/styles/base.css") } - Stylesheet { href: asset!("public/styles/DiscordButton.css") } - Stylesheet { href: asset!("public/styles/BuyMeACoffee.css") } - Stylesheet { href: asset!("public/styles/Modal.css") } - Stylesheet { href: asset!("public/styles/CloseButton.css") } - Stylesheet { href: asset!("public/styles/SelectWithSearch.css") } - Stylesheet { href: asset!("public/styles/About.css") } - Stylesheet { href: asset!("public/styles/Leaderboard.css") } - Stylesheet { href: asset!("public/styles/Menu.css") } + // document::Link { rel: "icon", href: asset!("public/static/favicon.png") } + // Stylesheet { href: asset!("public/styles/base.css") } + // Stylesheet { href: asset!("public/styles/DiscordButton.css") } + // Stylesheet { href: asset!("public/styles/BuyMeACoffee.css") } + // Stylesheet { href: asset!("public/styles/Modal.css") } + // Stylesheet { href: asset!("public/styles/CloseButton.css") } + // Stylesheet { href: asset!("public/styles/SelectWithSearch.css") } + // Stylesheet { href: asset!("public/styles/About.css") } + // Stylesheet { href: asset!("public/styles/Leaderboard.css") } + // Stylesheet { href: asset!("public/styles/Menu.css") } - Stylesheet { href: asset!("public/styles/rust-specific.css") } + // Stylesheet { href: asset!("public/styles/rust-specific.css") } div { class: "content", // Router uses the Route enum to handle URL-based routing Router:: {} @@ -50,21 +50,23 @@ fn App() -> Element { // Home component with the globe and main UI #[component] fn Home() -> Element { - let mut show_welcome_modal = use_signal(|| true); + // let mut show_welcome_modal = use_signal(|| true); // Manage country state here, similar to the original TypeScript implementation - let mut country = use_signal(|| Country { + /*let mut country = use_signal(|| Country { name: "United States".to_string(), code: "us".to_string(), - }); + });*/ // Callback to update country - let set_country = move |new_country: Country| { + /*let set_country = move |new_country: Country| { country.set(new_country); - }; + };*/ rsx! { div { class: "container", + // Commented out welcome modal + /* if show_welcome_modal() { app::components::on_load_modal::OnLoadModal { title: "Dear earthlings".to_string(), @@ -88,9 +90,13 @@ fn Home() -> Element { } } } + */ + // Only show the globe component for now app::components::earth::globe::Globe {} + // Commented out menu and other UI elements + /* div { class: "menu", app::components::leaderboard::Leaderboard {} div { class: "menu-actions", @@ -104,6 +110,7 @@ fn Home() -> Element { } } } + */ } } } From acd0e98393b9ee14198cbd714516fc501b160340 Mon Sep 17 00:00:00 2001 From: Laurent Valdes Date: Tue, 6 May 2025 01:19:42 +0200 Subject: [PATCH 10/28] refactor(three.js): improve WebGLRenderer and MeshBasicMaterial params with Rust idioms --- Cargo.lock | 1 + clickplanet-webapp/Cargo.toml | 1 + .../src/app/components/earth/globe.rs | 133 +++------- .../app/components/earth/three_js/bindings.rs | 157 +++++++++++- .../src/app/components/earth/three_js/cube.rs | 240 ++++++++---------- .../src/app/components/earth/three_js/mod.rs | 75 +++--- 6 files changed, 347 insertions(+), 260 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 095b317..d70ab0d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -938,6 +938,7 @@ dependencies = [ "getrandom 0.2.15", "glam", "gloo", + "gloo-console", "gloo-net 0.6.0", "gloo-timers", "gloo-utils", diff --git a/clickplanet-webapp/Cargo.toml b/clickplanet-webapp/Cargo.toml index 840acef..4d9e275 100644 --- a/clickplanet-webapp/Cargo.toml +++ b/clickplanet-webapp/Cargo.toml @@ -62,6 +62,7 @@ bytemuck = { version = "1.14", features = ["derive"] } raw-window-handle = "0.6.0" gloo-timers = { version = "0.3.0", features = ["futures"] } gloo-utils = "0.2.0" +gloo-console = "0.3.0" # Enable/disable features based on target diff --git a/clickplanet-webapp/src/app/components/earth/globe.rs b/clickplanet-webapp/src/app/components/earth/globe.rs index 21ab31b..f4f1df5 100644 --- a/clickplanet-webapp/src/app/components/earth/globe.rs +++ b/clickplanet-webapp/src/app/components/earth/globe.rs @@ -1,110 +1,61 @@ use dioxus::prelude::*; -use gloo_timers::callback::Timeout; +use dioxus::web::WebEventExt; +use wasm_bindgen::JsCast; +use web_sys::HtmlCanvasElement; +use wasm_bindgen_futures::spawn_local; +use gloo_timers::future::TimeoutFuture; +use crate::app::components::earth::three_js::{init_cube, is_three_available}; /// The Globe component acts as a wrapper for our Three.js implementation /// This uses the Three.js renderer instead of WebGPU directly for better compatibility #[component] pub fn Globe() -> Element { let mut cube_loaded = use_signal(|| false); - let mut scripts_loaded = use_signal(|| false); let canvas_id = "simple-cube-canvas"; - // Check if scripts are loaded and initialize Three.js - use_effect(move || { - if scripts_loaded() { - use wasm_bindgen_futures::spawn_local; - use crate::app::components::earth::three_js::{init_cube, is_three_available}; - - spawn_local(async move { - // Additional verification that Three.js is available - if is_three_available() { - if let Err(_) = init_cube(canvas_id) { - // Silently handle error - } else { - cube_loaded.set(true); - } - } - }); - } - - // No cleanup needed - () - }); - - // Set a timer to check if scripts are loaded - use_effect(move || { - use wasm_bindgen::prelude::*; - - // Wait for scripts to load - let timeout_ms = 1000; // Give scripts enough time to load - - let handle = Timeout::new(timeout_ms, move || { - // Check if Three.js is available after timeout - use crate::app::components::earth::three_js::is_three_available; - - let three_available = is_three_available(); - if three_available { - scripts_loaded.set(true); - } - }); - - // Cleanup function - (|| { drop(handle); })() - }); - - // Simplified script loading - load Three.js directly in the RSX - // Then use the hook to check if it's available and initialize the cube - - // Check if scripts are loaded and initialize Three.js - this is called immediately and after scripts load - use_effect(move || { - use wasm_bindgen::prelude::*; - use wasm_bindgen_futures::spawn_local; - use crate::app::components::earth::three_js::{init_cube, is_three_available}; - - // Check if Three.js is available - spawn_local(async move { - // Direct check - wait a little to ensure scripts have a chance to load - gloo_timers::future::TimeoutFuture::new(500).await; - - let three_available = is_three_available(); - - if three_available { - scripts_loaded.set(true); - - // Now initialize the cube - if let Err(_) = init_cube(canvas_id) { - // Silently handle error + // We'll skip most of the complex lifecycle management and script loading checks + rsx! { + div { + div { class: "status-indicator", + if cube_loaded() { + "Three.js Cube is loaded and running." } else { - cube_loaded.set(true); + "Loading Three.js cube..." } } - }); - - // No cleanup needed - () - }); - - rsx! { - // Load Three.js as a regular script (not a module) to make it globally available - document::Script { - src: "https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.min.js" - } - - // Load OrbitControls after Three.js - document::Script { - src: "https://cdn.jsdelivr.net/npm/three@0.160.0/examples/js/controls/OrbitControls.js" - } - - div { - class: "earth-container", - style: "width: 100%; height: 100vh; overflow: hidden;", - // Canvas for Three.js rendering + // Load Three.js script + script { src: "https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.min.js" } + + // Canvas for the 3D cube - using onmounted to get direct access canvas { id: "{canvas_id}", + height: "500", width: "100%", - height: "100%", - style: "display: block; background-color: #000;" + style: "background-color: black;", + onmounted: move |_element| { + // In Dioxus, we need to use the as_web_event method to get access to the web_sys::Element + // WebEventExt is imported at the top of the file + let web_element = _element.as_web_event(); + + // Now cast to HtmlCanvasElement + if let Some(canvas) = web_element.dyn_into::().ok() { + // Initialize Three.js with the canvas element directly + spawn_local(async move { + // Use gloo_timers to wait for Three.js to load + TimeoutFuture::new(500).await; + + // Initialize the cube with canvas directly + // three_js functions are imported at the top of the file + + if is_three_available() { + if let Ok(_) = init_cube(&canvas) { + cube_loaded.set(true); + } + } + }); + } + } } } } diff --git a/clickplanet-webapp/src/app/components/earth/three_js/bindings.rs b/clickplanet-webapp/src/app/components/earth/three_js/bindings.rs index bae4c8a..3dbc53e 100644 --- a/clickplanet-webapp/src/app/components/earth/three_js/bindings.rs +++ b/clickplanet-webapp/src/app/components/earth/three_js/bindings.rs @@ -1,7 +1,159 @@ use wasm_bindgen::prelude::*; use web_sys::Element; +use js_sys; + +#[wasm_bindgen] +pub struct WebGLRendererParams { + #[wasm_bindgen(skip)] + pub canvas: Option, + + pub alpha: Option, + pub antialias: Option, + pub depth: Option, + pub premultiplied_alpha: Option, + pub preserve_drawing_buffer: Option, +} + +#[wasm_bindgen] +impl WebGLRendererParams { + #[wasm_bindgen(constructor)] + pub fn new() -> Self { + Self { + canvas: None, + alpha: None, + antialias: None, + depth: None, + premultiplied_alpha: None, + preserve_drawing_buffer: None, + } + } + + pub fn set_canvas(&mut self, canvas: &web_sys::HtmlCanvasElement) { + self.canvas = Some(canvas.clone()); + } + + pub fn set_alpha(&mut self, alpha: bool) { + self.alpha = Some(alpha); + } + + pub fn set_antialias(&mut self, antialias: bool) { + self.antialias = Some(antialias); + } + + pub fn set_depth(&mut self, depth: bool) { + self.depth = Some(depth); + } + + pub fn set_premultiplied_alpha(&mut self, premultiplied_alpha: bool) { + self.premultiplied_alpha = Some(premultiplied_alpha); + } + + pub fn set_preserve_drawing_buffer(&mut self, preserve_drawing_buffer: bool) { + self.preserve_drawing_buffer = Some(preserve_drawing_buffer); + } +} + +impl From<&WebGLRendererParams> for JsValue { + fn from(params: &WebGLRendererParams) -> Self { + let obj = js_sys::Object::new(); + + if let Some(canvas) = ¶ms.canvas { + let _ = js_sys::Reflect::set(&obj, &JsValue::from_str("canvas"), canvas); + } + + if let Some(alpha) = params.alpha { + let _ = js_sys::Reflect::set(&obj, &JsValue::from_str("alpha"), &JsValue::from_bool(alpha)); + } + + if let Some(antialias) = params.antialias { + let _ = js_sys::Reflect::set(&obj, &JsValue::from_str("antialias"), &JsValue::from_bool(antialias)); + } + + if let Some(depth) = params.depth { + let _ = js_sys::Reflect::set(&obj, &JsValue::from_str("depth"), &JsValue::from_bool(depth)); + } + + if let Some(premultiplied_alpha) = params.premultiplied_alpha { + let _ = js_sys::Reflect::set( + &obj, + &JsValue::from_str("premultipliedAlpha"), + &JsValue::from_bool(premultiplied_alpha) + ); + } + + if let Some(preserve_drawing_buffer) = params.preserve_drawing_buffer { + let _ = js_sys::Reflect::set( + &obj, + &JsValue::from_str("preserveDrawingBuffer"), + &JsValue::from_bool(preserve_drawing_buffer) + ); + } + + obj.into() + } +} + +#[wasm_bindgen] +pub struct MeshBasicMaterialParams { + pub color: Option, + pub wireframe: Option, + pub transparent: Option, + pub opacity: Option, +} + +#[wasm_bindgen] +impl MeshBasicMaterialParams { + #[wasm_bindgen(constructor)] + pub fn new() -> Self { + Self { + color: None, + wireframe: None, + transparent: None, + opacity: None, + } + } + + pub fn set_color(&mut self, color: u32) { + self.color = Some(color); + } + + pub fn set_wireframe(&mut self, wireframe: bool) { + self.wireframe = Some(wireframe); + } + + pub fn set_transparent(&mut self, transparent: bool) { + self.transparent = Some(transparent); + } + + pub fn set_opacity(&mut self, opacity: f64) { + self.opacity = Some(opacity); + } +} + +impl From<&MeshBasicMaterialParams> for JsValue { + fn from(params: &MeshBasicMaterialParams) -> Self { + let obj = js_sys::Object::new(); + + if let Some(color) = params.color { + let _ = js_sys::Reflect::set(&obj, &JsValue::from_str("color"), &JsValue::from_f64(color as f64)); + } + + if let Some(wireframe) = params.wireframe { + let _ = js_sys::Reflect::set(&obj, &JsValue::from_str("wireframe"), &JsValue::from_bool(wireframe)); + } + + if let Some(transparent) = params.transparent { + let _ = js_sys::Reflect::set(&obj, &JsValue::from_str("transparent"), &JsValue::from_bool(transparent)); + } + + if let Some(opacity) = params.opacity { + let _ = js_sys::Reflect::set(&obj, &JsValue::from_str("opacity"), &JsValue::from_f64(opacity)); + } + + obj.into() + } +} -// Three.js bindings - using standard imports without module paths #[wasm_bindgen] extern "C" { // Main Three.js namespace @@ -29,6 +181,9 @@ extern "C" { #[wasm_bindgen(js_namespace = THREE)] pub type WebGLRenderer; + #[wasm_bindgen(constructor, js_namespace = THREE)] + pub fn new() -> WebGLRenderer; + #[wasm_bindgen(constructor, js_namespace = THREE)] pub fn new_with_parameters(params: &JsValue) -> WebGLRenderer; diff --git a/clickplanet-webapp/src/app/components/earth/three_js/cube.rs b/clickplanet-webapp/src/app/components/earth/three_js/cube.rs index 38002d5..f21a1dd 100644 --- a/clickplanet-webapp/src/app/components/earth/three_js/cube.rs +++ b/clickplanet-webapp/src/app/components/earth/three_js/cube.rs @@ -1,20 +1,21 @@ use wasm_bindgen::prelude::*; -use web_sys::{HtmlCanvasElement}; -use gloo_utils::document; +use web_sys::HtmlCanvasElement; use std::cell::RefCell; +use std::rc::Rc; +use gloo::render::{AnimationFrame, request_animation_frame}; +use gloo_utils::window; +use super::bindings::{WebGLRendererParams, WebGLRenderer, MeshBasicMaterialParams}; use super::bindings::*; -// Use a struct to hold the animation state to avoid thread_local borrowing issues struct ThreeJsState { scene: Option, camera: Option, renderer: Option, cube: Option, - animation_frame: Option, + animation_frame: Option, } -// Global state for ThreeJS objects thread_local! { static STATE: RefCell = RefCell::new(ThreeJsState { scene: None, @@ -23,68 +24,68 @@ thread_local! { cube: None, animation_frame: None, }); - static CALLBACKS: RefCell>> = RefCell::new(Vec::new()); } -/// Initialize a simple Three.js scene with a spinning cube -pub fn init_cube(canvas_id: &str) -> Result<(), JsError> { - // Clean up any previous instance +pub fn init_cube(canvas: &HtmlCanvasElement) -> Result<(), JsError> { cleanup_cube(); - - // Get the canvas element - let document = document(); - let canvas = document - .get_element_by_id(canvas_id) - .ok_or_else(|| JsError::new(&format!("No canvas found with id: {}", canvas_id)))?; - - let canvas: HtmlCanvasElement = canvas - .dyn_into::() - .map_err(|_| JsError::new("Element is not a canvas"))?; - // Create scene let scene = Scene::new(); + + let window = window(); - // Set up camera - let window = web_sys::window().ok_or_else(|| JsError::new("No window found"))?; - let width = window.inner_width().unwrap().as_f64().unwrap(); - let height = window.inner_height().unwrap().as_f64().unwrap(); + + let width = window.inner_width() + .map_err(|_| JsError::new("Failed to get window width"))? + .as_f64() + .ok_or_else(|| JsError::new("Failed to convert width to f64"))?; + + let height = window.inner_height() + .map_err(|_| JsError::new("Failed to get window height"))? + .as_f64() + .ok_or_else(|| JsError::new("Failed to convert height to f64"))?; + let aspect = width / height; let camera = PerspectiveCamera::new(75.0, aspect, 0.1, 1000.0); camera.position().set_z(5.0); - // Create renderer - let renderer_params = js_sys::Object::new(); - js_sys::Reflect::set(&renderer_params, &JsValue::from_str("canvas"), &canvas) - .map_err(|_| JsError::new("Failed to set canvas parameter"))?; + + let mut renderer_params = WebGLRendererParams::new(); + renderer_params.set_canvas(canvas); + renderer_params.set_antialias(true); + renderer_params.set_alpha(true); - let renderer = WebGLRenderer::new_with_parameters(&renderer_params); + let js_params = JsValue::from(&renderer_params); + let renderer = WebGLRenderer::new_with_parameters(&js_params); renderer.set_size(width, height); renderer.set_clear_color(0x000000); - // Create a cube let geometry = BoxGeometry::new(1.0, 1.0, 1.0); - // Create material with green color (0x00ff00 = 65280 in decimal) - let material_params = js_sys::Object::new(); - js_sys::Reflect::set(&material_params, &JsValue::from_str("color"), &JsValue::from_f64(65280.0)) - .map_err(|_| JsError::new("Failed to set material color"))?; - let material = MeshBasicMaterial::new_with_params(&material_params); + let mut material_params = MeshBasicMaterialParams::new(); + material_params.set_color(0x00ff00); - // Convert types implicitly using JsValue for JavaScript interop - let geom_js: &JsValue = geometry.as_ref(); - let mat_js: &JsValue = material.as_ref(); + let js_material_params = JsValue::from(&material_params); + let material = MeshBasicMaterial::new_with_params(&js_material_params); - // Create the mesh with the geometry and material + + let geometry_js: &JsValue = geometry.as_ref(); + let material_js: &JsValue = material.as_ref(); + + + let buffer_geometry = geometry_js.clone().into(); + let material_value = material_js.clone().into(); + + let cube = Mesh::new_with_geometry_material( - &geom_js.clone().into(), // Convert to the expected BufferGeometry type - &mat_js.clone().into(), // Convert to the expected Material type + &buffer_geometry, + &material_value, ); - // Add cube to scene + scene.add(&cube); - // Store objects in our state struct + STATE.with(|state_ref| { let mut state = state_ref.borrow_mut(); state.scene = Some(scene); @@ -93,124 +94,99 @@ pub fn init_cube(canvas_id: &str) -> Result<(), JsError> { state.cube = Some(cube); }); - // Start animation loop + + start_animation()?; - - // Cube initialization complete + + Ok(()) } -/// Start the animation loop for the cube fn start_animation() -> Result<(), JsError> { - // Create animation callback - let callback = Closure::wrap(Box::new(move || { - // Use a safer approach by getting each piece of state individually - STATE.with(|state_ref| { - // First, check if everything is initialized - let is_initialized = { - let state = state_ref.borrow(); - state.scene.is_some() && state.camera.is_some() && - state.renderer.is_some() && state.cube.is_some() - }; - - if !is_initialized { - return; - } + + fn request_next_frame(state_ref: Rc>>) { + + + let state_ref_clone = state_ref.clone(); + let callback = move |_timestamp: f64| { + + + if state_ref_clone.borrow().is_none() { + STATE.with(|global_state| { + let mut state = global_state.borrow_mut(); + - // Handle cube rotation - separate borrow - { - let state = state_ref.borrow(); - if let Some(cube) = &state.cube { - // Get the current rotation values - let current_x = cube.rotation().x(); - let current_y = cube.rotation().y(); + if state.scene.is_none() || state.camera.is_none() || + state.renderer.is_none() || state.cube.is_none() { + return; + } - // Update rotation - cube.rotation().set_x(current_x + 0.01); - cube.rotation().set_y(current_y + 0.01); - } + + *state_ref_clone.borrow_mut() = Some(( + state.scene.take().unwrap(), + state.camera.take().unwrap(), + state.renderer.take().unwrap(), + state.cube.take().unwrap(), + )); + }); } - // Render the scene - separate borrow - { - let state = state_ref.borrow(); - if let (Some(scene), Some(camera), Some(renderer)) = ( - &state.scene, &state.camera, &state.renderer) { - // Convert camera to JsValue for the render method - let camera_js: &JsValue = camera.as_ref(); - renderer.render(scene, camera_js); - } + + let state_exists = state_ref_clone.borrow().is_some(); + if !state_exists { + return; } - // Request next animation frame - separate borrow - CALLBACKS.with(|callbacks_ref| { - let callback = callbacks_ref.borrow(); - if let Some(callback) = callback.get(0) { - let id = request_animation_frame(callback); - // Update animation frame ID with a new borrow - let mut state = state_ref.borrow_mut(); - state.animation_frame = Some(id); - } - }); - }); - }) as Box); - // Store callback to keep it alive - CALLBACKS.with(|callbacks_ref| { - callbacks_ref.borrow_mut().push(callback); - }); + let mut state_borrowed = state_ref_clone.borrow_mut(); + let (scene, camera, renderer, cube) = state_borrowed.as_mut().unwrap(); + - // Request first animation frame - CALLBACKS.with(|callbacks_ref| { - let callback = callbacks_ref.borrow(); - if let Some(callback) = callback.get(0) { - let id = request_animation_frame(callback); - STATE.with(|state_ref| { - let mut state = state_ref.borrow_mut(); - state.animation_frame = Some(id); - }); - } - }); + let current_x = cube.rotation().x(); + let current_y = cube.rotation().y(); + cube.rotation().set_x(current_x + 0.01); + cube.rotation().set_y(current_y + 0.01); + - Ok(()) -} + let camera_js: &JsValue = camera.as_ref(); + renderer.render(scene, camera_js); + + + request_next_frame(state_ref_clone.clone()); + }; + + + let handle = request_animation_frame(callback); + -/// Helper function to request animation frame -fn request_animation_frame(f: &Closure) -> i32 { - let window = web_sys::window().expect("no global window exists"); - window - .request_animation_frame(f.as_ref().unchecked_ref()) - .expect("should register `requestAnimationFrame` OK") + STATE.with(|state_ref| { + let mut state = state_ref.borrow_mut(); + state.animation_frame = Some(handle); + }); + } + + + let shared_state = Rc::new(RefCell::new(None)); + request_next_frame(shared_state); + + Ok(()) } -/// Clean up Three.js resources pub fn cleanup_cube() { - // Cancel animation frame and clean up all resources in a single borrow + STATE.with(|state_ref| { let mut state = state_ref.borrow_mut(); - // Cancel animation frame - if let Some(id) = state.animation_frame { - if let Some(window) = web_sys::window() { - window.cancel_animation_frame(id).ok(); - } - } - - // Dispose of renderer if needed + if let Some(renderer) = &state.renderer { renderer.dispose(); } - // Reset all state + state.animation_frame = None; state.scene = None; state.camera = None; state.renderer = None; state.cube = None; }); - - // Clear callbacks - CALLBACKS.with(|callbacks_ref| { - callbacks_ref.borrow_mut().clear(); - }); } diff --git a/clickplanet-webapp/src/app/components/earth/three_js/mod.rs b/clickplanet-webapp/src/app/components/earth/three_js/mod.rs index 26a2514..fbf9615 100644 --- a/clickplanet-webapp/src/app/components/earth/three_js/mod.rs +++ b/clickplanet-webapp/src/app/components/earth/three_js/mod.rs @@ -5,6 +5,8 @@ mod cube; use dioxus::prelude::*; use dioxus::document; use wasm_bindgen_futures::spawn_local; +use web_sys::HtmlCanvasElement; +use wasm_bindgen::JsCast; pub use self::globe::init_globe; pub use self::cube::init_cube; @@ -13,41 +15,23 @@ pub use self::bindings::is_three_available; #[component] pub fn ThreeJsGlobe() -> Element { let canvas_id = "three-js-canvas"; - let mut scripts_loaded = use_signal(|| false); - // Initialize Three.js when scripts are loaded - use_effect(move || { - if scripts_loaded() { - // Initialize Three.js with the canvas element - spawn_local(async move { - if let Err(_) = init_globe(canvas_id) { - // Silently handle error - } - }); - } - // No cleanup needed - () - }); + // We'll directly check scripts are loaded when the canvas is mounted + // instead of relying on signals and effect hooks - // Set a timer to mark scripts as loaded after a delay and check THREE availability - // This is a workaround since onload is not directly available - use_effect(move || { - use wasm_bindgen::prelude::*; - - // A timeout ensures scripts are loaded before we attempt to use them - let timeout_ms = 500; - - let handle = gloo_timers::callback::Timeout::new(timeout_ms, move || { - // Check if Three.js is available - let three_available = is_three_available(); - - if three_available { - scripts_loaded.set(true); - } - }); + // Function to initialize Three.js with a canvas element directly + fn init_three_js_with_canvas(canvas: &HtmlCanvasElement) -> Result<(), String> { + // Ensure Three.js is available before trying to use it + if !is_three_available() { + return Err("Three.js is not available".to_string()); + } - (|| { drop(handle); })() - }); + // Initialize cube with the canvas directly instead of looking it up by ID + match init_cube(canvas) { + Ok(_) => Ok(()), + Err(e) => Err(format!("Failed to initialize Three.js: {:?}", e)), + } + } rsx! { // Load Three.js as a regular script (not a module) to make it globally available @@ -64,14 +48,33 @@ pub fn ThreeJsGlobe() -> Element { id: "three-js-container", style: "width: 100%; height: 100vh; overflow: hidden;", - - - // Canvas for Three.js rendering + // Canvas for Three.js rendering - using onmounted to get direct access canvas { id: "{canvas_id}", width: "100%", height: "100%", - style: "display: block; background-color: #000;" + style: "display: block; background-color: #000;", + // Use onmounted to get direct access to the canvas element + onmounted: move |_element| { + // In Dioxus, we need to use the as_web_event method to get access to the web_sys::Element + use dioxus::web::WebEventExt; + let web_element = _element.as_web_event(); + + // Now cast to HtmlCanvasElement + if let Some(canvas) = web_element.dyn_into::().ok() { + // Initialize Three.js with the canvas element directly + spawn_local(async move { + // Wait a brief moment to ensure Three.js is loaded + gloo_timers::future::TimeoutFuture::new(500).await; + + // Initialize cube with the canvas + if let Err(err) = init_three_js_with_canvas(&canvas) { + // Handle error silently + web_sys::console::log_1(&format!("Failed to initialize Three.js: {}", err).into()); + } + }); + } + } } } } From 79b954c0d40f16940ee4e1807d702f6663045367 Mon Sep 17 00:00:00 2001 From: Laurent Valdes Date: Tue, 6 May 2025 09:59:44 +0200 Subject: [PATCH 11/28] refactor(earth): refactor globe.rs to follow Rust-idiomatic approach --- .../src/app/components/earth/globe.rs | 24 +- .../app/components/earth/three_js/bindings.rs | 6 + .../app/components/earth/three_js/globe.rs | 364 ++++++++++-------- .../src/app/components/earth/three_js/mod.rs | 77 +--- 4 files changed, 212 insertions(+), 259 deletions(-) diff --git a/clickplanet-webapp/src/app/components/earth/globe.rs b/clickplanet-webapp/src/app/components/earth/globe.rs index f4f1df5..385484f 100644 --- a/clickplanet-webapp/src/app/components/earth/globe.rs +++ b/clickplanet-webapp/src/app/components/earth/globe.rs @@ -4,7 +4,7 @@ use wasm_bindgen::JsCast; use web_sys::HtmlCanvasElement; use wasm_bindgen_futures::spawn_local; use gloo_timers::future::TimeoutFuture; -use crate::app::components::earth::three_js::{init_cube, is_three_available}; +use crate::app::components::earth::three_js::{init_globe, is_three_available}; /// The Globe component acts as a wrapper for our Three.js implementation /// This uses the Three.js renderer instead of WebGPU directly for better compatibility @@ -25,31 +25,27 @@ pub fn Globe() -> Element { } // Load Three.js script - script { src: "https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.min.js" } - - // Canvas for the 3D cube - using onmounted to get direct access + script { + src: "https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.min.js" + } + script { + src: "/orbit-controls-global.js", + r#type: "module" + } canvas { id: "{canvas_id}", height: "500", width: "100%", style: "background-color: black;", onmounted: move |_element| { - // In Dioxus, we need to use the as_web_event method to get access to the web_sys::Element - // WebEventExt is imported at the top of the file let web_element = _element.as_web_event(); - // Now cast to HtmlCanvasElement if let Some(canvas) = web_element.dyn_into::().ok() { - // Initialize Three.js with the canvas element directly spawn_local(async move { - // Use gloo_timers to wait for Three.js to load TimeoutFuture::new(500).await; - - // Initialize the cube with canvas directly - // three_js functions are imported at the top of the file - + if is_three_available() { - if let Ok(_) = init_cube(&canvas) { + if let Ok(_) = init_globe(&canvas) { cube_loaded.set(true); } } diff --git a/clickplanet-webapp/src/app/components/earth/three_js/bindings.rs b/clickplanet-webapp/src/app/components/earth/three_js/bindings.rs index 3dbc53e..2c771ad 100644 --- a/clickplanet-webapp/src/app/components/earth/three_js/bindings.rs +++ b/clickplanet-webapp/src/app/components/earth/three_js/bindings.rs @@ -234,6 +234,12 @@ extern "C" { #[wasm_bindgen(method, setter, js_namespace = THREE)] pub fn set_right(this: &OrthographicCamera, right: f64); + #[wasm_bindgen(method, setter, js_namespace = THREE)] + pub fn set_top(this: &OrthographicCamera, top: f64); + + #[wasm_bindgen(method, setter, js_namespace = THREE)] + pub fn set_bottom(this: &OrthographicCamera, bottom: f64); + #[wasm_bindgen(extends = Object3D, js_namespace = THREE)] pub type AmbientLight; diff --git a/clickplanet-webapp/src/app/components/earth/three_js/globe.rs b/clickplanet-webapp/src/app/components/earth/three_js/globe.rs index 4416349..c0cf8bc 100644 --- a/clickplanet-webapp/src/app/components/earth/three_js/globe.rs +++ b/clickplanet-webapp/src/app/components/earth/three_js/globe.rs @@ -1,28 +1,43 @@ use wasm_bindgen::prelude::*; -use web_sys::{HtmlCanvasElement, window}; -use gloo_utils::document; +use web_sys::HtmlCanvasElement; +use gloo_utils::{document, window}; use std::rc::Rc; use std::cell::RefCell; +use gloo::render::{AnimationFrame, request_animation_frame}; use log::info; +use super::bindings::{WebGLRendererParams, WebGLRenderer}; use super::bindings::*; -// Global state for ThreeJS objects +struct ThreeJsGlobeState { + scene: Option, + camera: Option, + renderer: Option, + earth_mesh: Option, + controls: Option, + animation_id: Option, + callbacks: Vec>, +} + thread_local! { - static SCENE: RefCell> = RefCell::new(None); - static CAMERA: RefCell> = RefCell::new(None); - static RENDERER: RefCell> = RefCell::new(None); - static CONTROLS: RefCell> = RefCell::new(None); - static EARTH_MESH: RefCell> = RefCell::new(None); - static ANIMATION_FRAME: RefCell> = RefCell::new(None); - static CALLBACKS: RefCell>> = RefCell::new(Vec::new()); + static STATE: RefCell = RefCell::new(ThreeJsGlobeState { + scene: None, + camera: None, + renderer: None, + earth_mesh: None, + controls: None, + animation_id: None, + callbacks: Vec::new(), + }); } /// Initialize the Three.js scene with the Earth globe -pub fn init_globe(canvas_id: &str) -> Result<(), JsError> { +pub fn init_globe(canvas: &HtmlCanvasElement) -> Result<(), JsError> { + cleanup_globe(); + // Set the static site URL as a global variable for texture loading let static_site = env!("CITYWARS_STATIC_SITE"); - let window = web_sys::window().ok_or_else(|| JsError::new("No window found"))?; + let window = window(); // Check if THREE object is available in the global scope let three_available = js_sys::Reflect::has(&window, &JsValue::from_str("THREE")) @@ -38,23 +53,21 @@ pub fn init_globe(canvas_id: &str) -> Result<(), JsError> { &JsValue::from_str("CITYWARS_STATIC_SITE"), &JsValue::from_str(static_site) ).map_err(|_| JsError::new("Failed to set static site URL"))?; - // Get the canvas element - let document = document(); - let canvas = document - .get_element_by_id(canvas_id) - .ok_or_else(|| JsError::new(&format!("No canvas found with id: {}", canvas_id)))?; - - let canvas: HtmlCanvasElement = canvas - .dyn_into::() - .map_err(|_| JsError::new("Element is not a canvas"))?; // Create scene let scene = Scene::new(); // Set up camera - let web_window = web_sys::window().ok_or_else(|| JsError::new("No window found"))?; - let width = web_window.inner_width().unwrap().as_f64().unwrap(); - let height = web_window.inner_height().unwrap().as_f64().unwrap(); + let width = window.inner_width() + .map_err(|_| JsError::new("Failed to get window width"))? + .as_f64() + .ok_or_else(|| JsError::new("Failed to convert width to f64"))?; + + let height = window.inner_height() + .map_err(|_| JsError::new("Failed to get window height"))? + .as_f64() + .ok_or_else(|| JsError::new("Failed to convert height to f64"))?; + let aspect = width / height; let camera_size = 1.0; @@ -71,12 +84,13 @@ pub fn init_globe(canvas_id: &str) -> Result<(), JsError> { let position = camera.position(); position.set_z(5.0); - // Create renderer with canvas - let renderer_params = js_sys::Object::new(); - js_sys::Reflect::set(&renderer_params, &"canvas".into(), &canvas).unwrap(); - js_sys::Reflect::set(&renderer_params, &"antialias".into(), &JsValue::from_bool(true)).unwrap(); + // Create renderer with Rust-idiomatic parameters + let mut renderer_params = WebGLRendererParams::new(); + renderer_params.set_canvas(&canvas); + renderer_params.set_antialias(true); - let renderer = WebGLRenderer::new_with_parameters(&renderer_params); + let js_params = JsValue::from(&renderer_params); + let renderer = WebGLRenderer::new_with_parameters(&js_params); renderer.set_size(width, height); renderer.set_clear_color(0x000000); @@ -94,194 +108,206 @@ pub fn init_globe(canvas_id: &str) -> Result<(), JsError> { let earth_geometry = IcosahedronGeometry::new(0.999, 50); let earth_material = MeshStandardMaterial::new_with_params(&material_params); - // Cast to appropriate types for function call - let geometry_js_value: &JsValue = earth_geometry.as_ref(); - let material_js_value: &JsValue = earth_material.as_ref(); - let buffer_geometry = geometry_js_value.unchecked_ref::(); - let material = material_js_value.unchecked_ref::(); - let earth_mesh = Mesh::new_with_geometry_material(buffer_geometry, material); + + // Properly cast the types for Rust + let geometry_js: &JsValue = earth_geometry.as_ref(); + let material_js: &JsValue = earth_material.as_ref(); + + // Create BufferGeometry and Material from JS representations + let buffer_geometry = geometry_js.clone().into(); + let material_value = material_js.clone().into(); + + let earth_mesh = Mesh::new_with_geometry_material( + &buffer_geometry, + &material_value + ); scene.add(&earth_mesh); - // Set up orbit controls - // Create OrbitControls instance directly using the constructor binding + // Set up orbit controls similar to the original frontend let controls = OrbitControls::new(&camera, &renderer.domElement()); controls.set_min_zoom(1.0); controls.set_max_zoom(50.0); controls.set_pan_speed(0.1); controls.set_enable_damping(true); controls.set_auto_rotate(true); - controls.set_auto_rotate_speed(0.5); + controls.set_rotate_speed(1.0 / 1.5); - // Add handler for orbit controls changes - let control_change_callback = Closure::wrap(Box::new(move || { - CONTROLS.with(|controls_ref| { - if let Some(controls) = &*controls_ref.borrow() { - CAMERA.with(|camera_ref| { - if let Some(camera) = &*camera_ref.borrow() { - let zoom = camera.zoom(); - controls.set_auto_rotate(zoom == 1.0); - controls.set_rotate_speed((1.0 / zoom) / 1.5); - } - }); + // Store the controls in STATE before creating the closure + STATE.with(|state_ref| { + let mut state = state_ref.borrow_mut(); + state.controls = Some(controls); + }); + + // Create a callback that works with controls via STATE rather than direct capture + let control_change_callback = Closure::wrap(Box::new(|| { + // Access controls through STATE to avoid move issues + STATE.with(|state_ref| { + let state = state_ref.borrow(); + if let Some(controls) = &state.controls { + // We can update controls settings here if needed } }); }) as Box); - controls.add_event_listener("change", &control_change_callback); + // Get a reference to controls from STATE to add the event listener + STATE.with(|state_ref| { + let state = state_ref.borrow(); + if let Some(controls) = &state.controls { + controls.add_event_listener("change", &control_change_callback); + } + }); - // Store callback to prevent it from being dropped - CALLBACKS.with(|callbacks| { - callbacks.borrow_mut().push(control_change_callback); + // Store the callback so it doesn't get dropped + STATE.with(|state_ref| { + let mut state = state_ref.borrow_mut(); + state.callbacks.push(control_change_callback); }); - // Handle window resize + // Register window resize handler let resize_callback = Closure::wrap(Box::new(move || { - let web_window = web_sys::window().unwrap(); - let width = web_window.inner_width().unwrap().as_f64().unwrap(); - let height = web_window.inner_height().unwrap().as_f64().unwrap(); - let aspect = width / height; - let camera_size = 1.0; - - CAMERA.with(|camera_ref| { - if let Some(camera) = &*camera_ref.borrow() { - // Update camera aspect ratio + STATE.with(|state_ref| { + let state = state_ref.borrow(); + if let (Some(renderer), Some(camera)) = (&state.renderer, &state.camera) { + let window = web_sys::window().unwrap(); + let width = window.inner_width().unwrap().as_f64().unwrap(); + let height = window.inner_height().unwrap().as_f64().unwrap(); + let aspect = width / height; + + let camera_size = 1.0; camera.set_left(-camera_size * aspect); camera.set_right(camera_size * aspect); + camera.set_top(camera_size); + camera.set_bottom(-camera_size); camera.update_projection_matrix(); - } - }); - - RENDERER.with(|renderer_ref| { - if let Some(renderer) = &*renderer_ref.borrow() { + renderer.set_size(width, height); } }); }) as Box); - let web_window = web_sys::window().ok_or_else(|| JsError::new("No window found"))?; - web_window.add_event_listener_with_callback("resize", resize_callback.as_ref().unchecked_ref()) - .map_err(|_| JsError::new("Failed to add resize event listener"))?; - - // Store callback to prevent it from being dropped - CALLBACKS.with(|callbacks| { - callbacks.borrow_mut().push(resize_callback); - }); + // Add the resize listener + window.add_event_listener_with_callback("resize", resize_callback.as_ref().unchecked_ref()).unwrap(); - // Store the objects - SCENE.with(|scene_ref| { - *scene_ref.borrow_mut() = Some(scene); + // Store the callback to prevent it from being dropped + STATE.with(|state_ref| { + let mut state = state_ref.borrow_mut(); + state.callbacks.push(resize_callback); }); - CAMERA.with(|camera_ref| { - *camera_ref.borrow_mut() = Some(camera); - }); - - RENDERER.with(|renderer_ref| { - *renderer_ref.borrow_mut() = Some(renderer); - }); - - CONTROLS.with(|controls_ref| { - *controls_ref.borrow_mut() = Some(controls); - }); - - EARTH_MESH.with(|earth_mesh_ref| { - *earth_mesh_ref.borrow_mut() = Some(earth_mesh); + // Store remaining objects in our state struct (controls already stored above) + STATE.with(|state_ref| { + let mut state = state_ref.borrow_mut(); + state.scene = Some(scene); + state.camera = Some(camera); + state.renderer = Some(renderer); + state.earth_mesh = Some(earth_mesh); + // controls already stored above }); // Start animation loop - start_animation(); + start_animation()?; info!("Three.js Earth globe initialized"); Ok(()) } -// Animation loop -fn start_animation() { - let f = Rc::new(RefCell::new(None)); - let g = f.clone(); - - *g.borrow_mut() = Some(Closure::wrap(Box::new(move || { - // Request next frame - request_animation_frame(f.borrow().as_ref().unwrap()); - - // Update controls - CONTROLS.with(|controls_ref| { - if let Some(controls) = &*controls_ref.borrow() { - controls.update(); - } - }); - - // Render scene - SCENE.with(|scene_ref| { - if let Some(scene) = &*scene_ref.borrow() { - CAMERA.with(|camera_ref| { - if let Some(camera) = &*camera_ref.borrow() { - RENDERER.with(|renderer_ref| { - if let Some(renderer) = &*renderer_ref.borrow() { - renderer.render(scene, camera); - } - }); +fn start_animation() -> Result<(), JsError> { + // Create an animation loop using Rc and RefCell for shared state + // let animation_state = Rc::new(RefCell::new(None)); + + // Recursive function to request the next animation frame + fn request_next_frame(state_ref_clone: Rc>>){ + // Use a recursive function to create a perpetual animation loop + let state_ref_clone = state_ref_clone.clone(); + let callback = move |_timestamp: f64| { + // First time setup - extract the state from thread_local + if state_ref_clone.borrow().is_none() { + STATE.with(|global_state| { + let mut state = global_state.borrow_mut(); + + // If we don't have the scene or renderer, return + if state.scene.is_none() || state.camera.is_none() || + state.renderer.is_none() { + return; } + + // Move objects from thread_local to our Rc + *state_ref_clone.borrow_mut() = Some(( + state.scene.take().unwrap(), + state.camera.take().unwrap(), + state.renderer.take().unwrap(), + )); }); } + + // Check if we have the state + let state_exists = state_ref_clone.borrow().is_some(); + if !state_exists { + return; + } + + // Use the state to render the scene + let mut state_borrowed = state_ref_clone.borrow_mut(); + let (scene, camera, renderer) = state_borrowed.as_mut().unwrap(); + + // Update controls and auto-rotate the earth + STATE.with(|state_ref| { + let state = state_ref.borrow(); + if let Some(controls) = &state.controls { + controls.update(); + } + + // Also apply a gentle auto-rotation to the earth mesh + if let Some(earth) = &state.earth_mesh { + let rotation = earth.rotation(); + rotation.set_y(rotation.y() + 0.002); + } + }); + + // Render the scene + let camera_js: &JsValue = camera.as_ref(); + renderer.render(scene, camera_js); + + // Schedule the next animation frame + request_next_frame(state_ref_clone.clone()); + }; + + // Request a single animation frame + let handle = request_animation_frame(callback); + + // Store the animation frame + STATE.with(|state_ref| { + let mut state = state_ref.borrow_mut(); + state.animation_id = Some(handle); }); - }) as Box)); + } - // Start the first frame - request_animation_frame(g.borrow().as_ref().unwrap()); -} - -// Helper function to request animation frame -fn request_animation_frame(f: &Closure) { - let web_window = web_sys::window().unwrap(); - let id = web_window - .request_animation_frame(f.as_ref().unchecked_ref()) - .expect("Failed to request animation frame"); + // Start the animation loop + let shared_state = Rc::new(RefCell::new(None)); + request_next_frame(shared_state); - ANIMATION_FRAME.with(|frame_ref| { - *frame_ref.borrow_mut() = Some(id); - }); + Ok(()) } /// Clean up Three.js resources pub fn cleanup_globe() { - // Cancel animation frame - ANIMATION_FRAME.with(|frame_ref| { - if let Some(id) = *frame_ref.borrow() { - let web_window = web_sys::window().unwrap(); - web_window.cancel_animation_frame(id).unwrap(); - *frame_ref.borrow_mut() = None; - } - }); - - // Dispose renderer - RENDERER.with(|renderer_ref| { - if let Some(renderer) = &*renderer_ref.borrow() { + STATE.with(|state_ref| { + let mut state = state_ref.borrow_mut(); + + // Dispose of renderer if needed + if let Some(renderer) = &state.renderer { renderer.dispose(); - *renderer_ref.borrow_mut() = None; } + + // Reset all state - AnimationFrame automatically cancels on drop + state.animation_id = None; + state.scene = None; + state.camera = None; + state.renderer = None; + state.earth_mesh = None; + state.controls = None; + state.callbacks.clear(); }); - - // Clear references to other objects - SCENE.with(|scene_ref| { - *scene_ref.borrow_mut() = None; - }); - - CAMERA.with(|camera_ref| { - *camera_ref.borrow_mut() = None; - }); - - CONTROLS.with(|controls_ref| { - *controls_ref.borrow_mut() = None; - }); - - EARTH_MESH.with(|earth_mesh_ref| { - *earth_mesh_ref.borrow_mut() = None; - }); - - // Clear callbacks - CALLBACKS.with(|callbacks| { - callbacks.borrow_mut().clear(); - }); + } diff --git a/clickplanet-webapp/src/app/components/earth/three_js/mod.rs b/clickplanet-webapp/src/app/components/earth/three_js/mod.rs index fbf9615..38da68e 100644 --- a/clickplanet-webapp/src/app/components/earth/three_js/mod.rs +++ b/clickplanet-webapp/src/app/components/earth/three_js/mod.rs @@ -2,80 +2,5 @@ mod bindings; mod globe; mod cube; -use dioxus::prelude::*; -use dioxus::document; -use wasm_bindgen_futures::spawn_local; -use web_sys::HtmlCanvasElement; -use wasm_bindgen::JsCast; - pub use self::globe::init_globe; -pub use self::cube::init_cube; -pub use self::bindings::is_three_available; - -#[component] -pub fn ThreeJsGlobe() -> Element { - let canvas_id = "three-js-canvas"; - - // We'll directly check scripts are loaded when the canvas is mounted - // instead of relying on signals and effect hooks - - // Function to initialize Three.js with a canvas element directly - fn init_three_js_with_canvas(canvas: &HtmlCanvasElement) -> Result<(), String> { - // Ensure Three.js is available before trying to use it - if !is_three_available() { - return Err("Three.js is not available".to_string()); - } - - // Initialize cube with the canvas directly instead of looking it up by ID - match init_cube(canvas) { - Ok(_) => Ok(()), - Err(e) => Err(format!("Failed to initialize Three.js: {:?}", e)), - } - } - - rsx! { - // Load Three.js as a regular script (not a module) to make it globally available - document::Script { - src: "https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.min.js" - } - - // Load OrbitControls after Three.js - // document::Script { - // src: "https://cdn.jsdelivr.net/npm/three@0.160.0/examples/js/controls/OrbitControls.js" - //} - - div { - id: "three-js-container", - style: "width: 100%; height: 100vh; overflow: hidden;", - - // Canvas for Three.js rendering - using onmounted to get direct access - canvas { - id: "{canvas_id}", - width: "100%", - height: "100%", - style: "display: block; background-color: #000;", - // Use onmounted to get direct access to the canvas element - onmounted: move |_element| { - // In Dioxus, we need to use the as_web_event method to get access to the web_sys::Element - use dioxus::web::WebEventExt; - let web_element = _element.as_web_event(); - - // Now cast to HtmlCanvasElement - if let Some(canvas) = web_element.dyn_into::().ok() { - // Initialize Three.js with the canvas element directly - spawn_local(async move { - // Wait a brief moment to ensure Three.js is loaded - gloo_timers::future::TimeoutFuture::new(500).await; - - // Initialize cube with the canvas - if let Err(err) = init_three_js_with_canvas(&canvas) { - // Handle error silently - web_sys::console::log_1(&format!("Failed to initialize Three.js: {}", err).into()); - } - }); - } - } - } - } - } -} +pub use self::bindings::is_three_available; \ No newline at end of file From 6d6c58a5d1bb96520d3415d2c9871309d96e630f Mon Sep 17 00:00:00 2001 From: Laurent Valdes Date: Tue, 6 May 2025 17:53:46 +0200 Subject: [PATCH 12/28] fix: create basic red sphere with black background for Three.js globe - Commented out texture loading code instead of removing it - Implemented basic red sphere rendering - Disabled controls and animation for simpler testing - Added extensive logging to diagnose rendering issues - Fixed color value specification in material --- .../src/app/components/earth/globe.rs | 88 +++++--- .../app/components/earth/three_js/bindings.rs | 98 +++++---- .../src/app/components/earth/three_js/cube.rs | 192 ------------------ .../app/components/earth/three_js/globe.rs | 94 +++++++-- .../src/app/components/earth/three_js/mod.rs | 1 - .../src/app/components/earth/wgpu/mod.rs | 6 - .../earth/wgpu/shader_validation.rs | 56 ----- clickplanet-webapp/src/main.rs | 58 +++--- 8 files changed, 232 insertions(+), 361 deletions(-) delete mode 100644 clickplanet-webapp/src/app/components/earth/three_js/cube.rs delete mode 100644 clickplanet-webapp/src/app/components/earth/wgpu/shader_validation.rs diff --git a/clickplanet-webapp/src/app/components/earth/globe.rs b/clickplanet-webapp/src/app/components/earth/globe.rs index 385484f..430be90 100644 --- a/clickplanet-webapp/src/app/components/earth/globe.rs +++ b/clickplanet-webapp/src/app/components/earth/globe.rs @@ -10,49 +10,83 @@ use crate::app::components::earth::three_js::{init_globe, is_three_available}; /// This uses the Three.js renderer instead of WebGPU directly for better compatibility #[component] pub fn Globe() -> Element { - let mut cube_loaded = use_signal(|| false); + let cube_loaded = use_signal(|| false); let canvas_id = "simple-cube-canvas"; - // We'll skip most of the complex lifecycle management and script loading checks rsx! { + script { + r#type: "module", + {r#" + import * as THREE from "three"; + import { OrbitControls } from "three/addons/controls/OrbitControls.js"; + import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js"; + + window.THREE = THREE; + window.OrbitControls = OrbitControls; + window.GLTFLoader = GLTFLoader; + + // Direct JS console logging + console.log('THREE.js imports loaded. THREE version:', THREE.REVISION); + console.log('OrbitControls available:', typeof OrbitControls); + console.log('GLTFLoader available:', typeof GLTFLoader); + + // Add texture loading test to check if the URL is correct + const textureUrl = window.CITYWARS_STATIC_SITE + '/earth/3_no_ice_clouds_16k.jpg'; + console.log('Testing texture URL:', textureUrl); + const img = new Image(); + img.onload = () => console.log('✅ Texture loaded successfully:', textureUrl); + img.onerror = () => console.error('❌ Texture failed to load:', textureUrl); + img.src = textureUrl; + "#} + } + div { - div { class: "status-indicator", - if cube_loaded() { - "Three.js Cube is loaded and running." - } else { - "Loading Three.js cube..." - } - } - - // Load Three.js script - script { - src: "https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.min.js" - } - script { - src: "/orbit-controls-global.js", - r#type: "module" - } + height: "100%", + width: "100%", canvas { id: "{canvas_id}", - height: "500", + height: "100vh", width: "100%", style: "background-color: black;", - onmounted: move |_element| { - let web_element = _element.as_web_event(); + onmounted: move |el| { + // Direct JS logging to check canvas element + let js_code = format!(r#"console.log('Canvas onmounted triggered for id: {}');"#, canvas_id); + let _ = js_sys::eval(&js_code); + + let mut cube_loaded_clone = cube_loaded.clone(); + let web_element = el.as_web_event(); + + if let Some(canvas) = web_element.dyn_into::().ok() { + // Log canvas dimensions + let js_code = format!(r#"console.log('Canvas dimensions:', document.getElementById('{}').clientWidth, 'x', document.getElementById('{}').clientHeight);"#, canvas_id, canvas_id); + let _ = js_sys::eval(&js_code); - if let Some(canvas) = web_element.dyn_into::().ok() { - spawn_local(async move { - TimeoutFuture::new(500).await; - + spawn_local(async move { + // Wait for scripts to load - THREE is loaded asynchronously + // so we need to wait before checking availability + gloo_console::log!("Waiting for THREE to load..."); + TimeoutFuture::new(1000).await; // Wait 1 second for scripts to load + + // Now check THREE availability after waiting + gloo_console::log!("Checking THREE availability"); + if is_three_available() { + gloo_console::log!("THREE is available, initializing globe"); if let Ok(_) = init_globe(&canvas) { - cube_loaded.set(true); + cube_loaded_clone.set(true); + gloo_console::log!("Globe initialization successful"); + } else { + gloo_console::log!("Globe initialization FAILED"); } + } else { + gloo_console::log!("THREE is NOT available after waiting"); } }); + } else { + gloo_console::log!("Failed to get HtmlCanvasElement"); } } } } - } +} } \ No newline at end of file diff --git a/clickplanet-webapp/src/app/components/earth/three_js/bindings.rs b/clickplanet-webapp/src/app/components/earth/three_js/bindings.rs index 2c771ad..f8a9ef4 100644 --- a/clickplanet-webapp/src/app/components/earth/three_js/bindings.rs +++ b/clickplanet-webapp/src/app/components/earth/three_js/bindings.rs @@ -327,54 +327,84 @@ extern "C" { // Function to check if Three.js is available in the global scope pub fn is_three_available() -> bool { + js_sys::eval("typeof THREE !== 'undefined'").unwrap().as_bool().unwrap_or(false) +} + +pub fn diagnose_three_js_loading() -> String { use wasm_bindgen::prelude::*; use web_sys::console; - // Try to access the THREE global object via window - console::log_1(&JsValue::from_str("Checking for THREE global object...")); - - if let Some(window) = web_sys::window() { - // Log all available global objects for debugging - if let Ok(keys) = js_sys::Reflect::own_keys(&window) { - console::log_2( - &JsValue::from_str("Window global objects available:"), - &keys - ); - } + let diagnostic_script = r#"(function() { + let results = { + three: { + available: false, + version: null, + error: null + }, + orbitControls: { + available: false, + error: null + }, + scripts: [] + }; + + // Check for all script tags loaded + document.querySelectorAll('script').forEach(script => { + if (script.src) { + results.scripts.push(script.src); + } + }); - // Check if THREE is directly available on window - if js_sys::Reflect::has(&window, &JsValue::from_str("THREE")).unwrap_or(false) { - console::log_1(&JsValue::from_str("THREE found directly on window object!")); - return true; + // Check THREE + try { + if (typeof THREE !== 'undefined') { + results.three.available = true; + results.three.version = THREE.REVISION || 'unknown'; + } + } catch(err) { + results.three.error = err.toString(); } - // Try the eval approach as a backup - let eval_script = r#"(function() { - try { + // Check OrbitControls - when using ES modules, it should be exposed as a global via our script + try { + if (typeof OrbitControls !== 'undefined') { + results.orbitControls.available = true; + } else { + results.orbitControls.error = 'OrbitControls is not defined in global scope'; + // If THREE is available but not OrbitControls, provide more context if (typeof THREE !== 'undefined') { - console.log('THREE found with type:', typeof THREE); - console.log('THREE version:', THREE.REVISION || 'unknown'); - return true; + results.orbitControls.note = 'THREE is loaded but OrbitControls was not properly exposed to the global scope'; } else { - console.log('THREE is undefined in global scope'); - return false; + results.orbitControls.note = 'THREE is not loaded, so OrbitControls cannot be used'; } - } catch(err) { - console.error('Error checking THREE:', err); - return false; } - })() - "#; + } catch(err) { + results.orbitControls.error = err.toString(); + } - // Execute the evaluation script - if let Ok(result) = js_sys::eval(eval_script) { - console::log_1(&JsValue::from_str(&format!("THREE availability check result: {}", result.is_truthy()))); - return result.is_truthy(); + return JSON.stringify(results); + })() + "#; + + // Execute the diagnostic script + if let Ok(result) = js_sys::eval(diagnostic_script) { + if let Some(result_str) = result.as_string() { + console::log_1(&JsValue::from_str(&format!("THREE diagnostic result: {}", result_str))); + return result_str; } } - console::log_1(&JsValue::from_str("Failed to check THREE availability")); - false + console::log_1(&JsValue::from_str("Failed to run diagnostic script")); + "Failed to run diagnostic script".to_string() +} + +// SphereGeometry bindings +#[wasm_bindgen] +extern "C" { + pub type SphereGeometry; + + #[wasm_bindgen(constructor)] + pub fn new(radius: f64, width_segments: u32, height_segments: u32) -> SphereGeometry; } // OrbitControls bindings - using standard imports diff --git a/clickplanet-webapp/src/app/components/earth/three_js/cube.rs b/clickplanet-webapp/src/app/components/earth/three_js/cube.rs deleted file mode 100644 index f21a1dd..0000000 --- a/clickplanet-webapp/src/app/components/earth/three_js/cube.rs +++ /dev/null @@ -1,192 +0,0 @@ -use wasm_bindgen::prelude::*; -use web_sys::HtmlCanvasElement; -use std::cell::RefCell; -use std::rc::Rc; -use gloo::render::{AnimationFrame, request_animation_frame}; -use gloo_utils::window; - -use super::bindings::{WebGLRendererParams, WebGLRenderer, MeshBasicMaterialParams}; -use super::bindings::*; - -struct ThreeJsState { - scene: Option, - camera: Option, - renderer: Option, - cube: Option, - animation_frame: Option, -} - -thread_local! { - static STATE: RefCell = RefCell::new(ThreeJsState { - scene: None, - camera: None, - renderer: None, - cube: None, - animation_frame: None, - }); -} - -pub fn init_cube(canvas: &HtmlCanvasElement) -> Result<(), JsError> { - cleanup_cube(); - - let scene = Scene::new(); - - let window = window(); - - - let width = window.inner_width() - .map_err(|_| JsError::new("Failed to get window width"))? - .as_f64() - .ok_or_else(|| JsError::new("Failed to convert width to f64"))?; - - let height = window.inner_height() - .map_err(|_| JsError::new("Failed to get window height"))? - .as_f64() - .ok_or_else(|| JsError::new("Failed to convert height to f64"))?; - - let aspect = width / height; - - let camera = PerspectiveCamera::new(75.0, aspect, 0.1, 1000.0); - camera.position().set_z(5.0); - - - let mut renderer_params = WebGLRendererParams::new(); - renderer_params.set_canvas(canvas); - renderer_params.set_antialias(true); - renderer_params.set_alpha(true); - - let js_params = JsValue::from(&renderer_params); - let renderer = WebGLRenderer::new_with_parameters(&js_params); - renderer.set_size(width, height); - renderer.set_clear_color(0x000000); - - let geometry = BoxGeometry::new(1.0, 1.0, 1.0); - - let mut material_params = MeshBasicMaterialParams::new(); - material_params.set_color(0x00ff00); - - let js_material_params = JsValue::from(&material_params); - let material = MeshBasicMaterial::new_with_params(&js_material_params); - - - let geometry_js: &JsValue = geometry.as_ref(); - let material_js: &JsValue = material.as_ref(); - - - let buffer_geometry = geometry_js.clone().into(); - let material_value = material_js.clone().into(); - - - let cube = Mesh::new_with_geometry_material( - &buffer_geometry, - &material_value, - ); - - - scene.add(&cube); - - - STATE.with(|state_ref| { - let mut state = state_ref.borrow_mut(); - state.scene = Some(scene); - state.camera = Some(camera); - state.renderer = Some(renderer); - state.cube = Some(cube); - }); - - - - start_animation()?; - - - Ok(()) -} - -fn start_animation() -> Result<(), JsError> { - - fn request_next_frame(state_ref: Rc>>) { - - - let state_ref_clone = state_ref.clone(); - let callback = move |_timestamp: f64| { - - - if state_ref_clone.borrow().is_none() { - STATE.with(|global_state| { - let mut state = global_state.borrow_mut(); - - - if state.scene.is_none() || state.camera.is_none() || - state.renderer.is_none() || state.cube.is_none() { - return; - } - - - *state_ref_clone.borrow_mut() = Some(( - state.scene.take().unwrap(), - state.camera.take().unwrap(), - state.renderer.take().unwrap(), - state.cube.take().unwrap(), - )); - }); - } - - - let state_exists = state_ref_clone.borrow().is_some(); - if !state_exists { - return; - } - - - let mut state_borrowed = state_ref_clone.borrow_mut(); - let (scene, camera, renderer, cube) = state_borrowed.as_mut().unwrap(); - - - let current_x = cube.rotation().x(); - let current_y = cube.rotation().y(); - cube.rotation().set_x(current_x + 0.01); - cube.rotation().set_y(current_y + 0.01); - - - let camera_js: &JsValue = camera.as_ref(); - renderer.render(scene, camera_js); - - - request_next_frame(state_ref_clone.clone()); - }; - - - let handle = request_animation_frame(callback); - - - STATE.with(|state_ref| { - let mut state = state_ref.borrow_mut(); - state.animation_frame = Some(handle); - }); - } - - - let shared_state = Rc::new(RefCell::new(None)); - request_next_frame(shared_state); - - Ok(()) -} - -pub fn cleanup_cube() { - - STATE.with(|state_ref| { - let mut state = state_ref.borrow_mut(); - - - if let Some(renderer) = &state.renderer { - renderer.dispose(); - } - - - state.animation_frame = None; - state.scene = None; - state.camera = None; - state.renderer = None; - state.cube = None; - }); -} diff --git a/clickplanet-webapp/src/app/components/earth/three_js/globe.rs b/clickplanet-webapp/src/app/components/earth/three_js/globe.rs index c0cf8bc..7953f3e 100644 --- a/clickplanet-webapp/src/app/components/earth/three_js/globe.rs +++ b/clickplanet-webapp/src/app/components/earth/three_js/globe.rs @@ -1,13 +1,15 @@ use wasm_bindgen::prelude::*; use web_sys::HtmlCanvasElement; -use gloo_utils::{document, window}; +use gloo_utils::{window}; use std::rc::Rc; use std::cell::RefCell; use gloo::render::{AnimationFrame, request_animation_frame}; -use log::info; +use gloo_console; +use log; -use super::bindings::{WebGLRendererParams, WebGLRenderer}; -use super::bindings::*; +use super::bindings::{self, AmbientLight, Scene, OrthographicCamera, OrbitControls, + WebGLRenderer, WebGLRendererParams, TextureLoader, Mesh, IcosahedronGeometry, + MeshStandardMaterial, diagnose_three_js_loading, is_three_available}; struct ThreeJsGlobeState { scene: Option, @@ -33,12 +35,18 @@ thread_local! { /// Initialize the Three.js scene with the Earth globe pub fn init_globe(canvas: &HtmlCanvasElement) -> Result<(), JsError> { + // First log to check if function is being called + gloo_console::log!("INIT GLOBE STARTING"); cleanup_globe(); // Set the static site URL as a global variable for texture loading let static_site = env!("CITYWARS_STATIC_SITE"); let window = window(); + // Run detailed diagnostic to check Three.js and OrbitControls availability + let diagnostic_result = super::bindings::diagnose_three_js_loading(); + gloo_console::log!("THREE diagnostics: {}", diagnostic_result); + // Check if THREE object is available in the global scope let three_available = js_sys::Reflect::has(&window, &JsValue::from_str("THREE")) .map_err(|_| JsError::new("Failed to check for THREE global object"))?; @@ -56,6 +64,7 @@ pub fn init_globe(canvas: &HtmlCanvasElement) -> Result<(), JsError> { // Create scene let scene = Scene::new(); + gloo_console::log!("Scene created"); // Set up camera let width = window.inner_width() @@ -71,6 +80,7 @@ pub fn init_globe(canvas: &HtmlCanvasElement) -> Result<(), JsError> { let aspect = width / height; let camera_size = 1.0; + // Use OrthographicCamera as in the original code let camera = OrthographicCamera::new( -camera_size * aspect, camera_size * aspect, @@ -80,9 +90,10 @@ pub fn init_globe(canvas: &HtmlCanvasElement) -> Result<(), JsError> { 100.0 ); - // Position camera + // Position camera just like in the original code let position = camera.position(); position.set_z(5.0); + gloo_console::log!("Camera created and positioned at z=5.0"); // Create renderer with Rust-idiomatic parameters let mut renderer_params = WebGLRendererParams::new(); @@ -90,22 +101,40 @@ pub fn init_globe(canvas: &HtmlCanvasElement) -> Result<(), JsError> { renderer_params.set_antialias(true); let js_params = JsValue::from(&renderer_params); + let renderer = WebGLRenderer::new_with_parameters(&js_params); renderer.set_size(width, height); + + // Ensure the background is black (0x000000) renderer.set_clear_color(0x000000); + gloo_console::log!("Setting renderer background to black"); - // Add lighting + // Fix the formatting syntax for gloo_console + let size_msg = format!("Renderer created with size: {} x {}", width, height); + gloo_console::log!(size_msg); + + // Add lighting just like in the original code let light = AmbientLight::new(0xffffff, 2.0); scene.add(&light); + gloo_console::log!("Lighting added to scene"); // Create earth sphere let static_site = env!("CITYWARS_STATIC_SITE"); - let texture_loader = TextureLoader::new(); - let earth_texture = texture_loader.load(&format!("{}/earth/3_no_ice_clouds_16k.jpg", static_site)); + // let texture_loader = TextureLoader::new(); + + // COMMENTED OUT: Texture loading for now + // let earth_texture = texture_loader.load(&format!("{}/earth/3_no_ice_clouds_16k.jpg", static_site)); + // let texture_msg = format!("Texture loading from: {}/earth/3_no_ice_clouds_16k.jpg", static_site); + // gloo_console::log!(texture_msg); + // Create a simple red material instead let material_params = js_sys::Object::new(); - js_sys::Reflect::set(&material_params, &"map".into(), &earth_texture).unwrap(); + // Set color to red (0xFF0000) + js_sys::Reflect::set(&material_params, &"color".into(), &JsValue::from_f64(16711680.0)).unwrap(); // 0xFF0000 as f64 + gloo_console::log!("Using red material for sphere instead of texture"); + // Create inner sphere with slightly smaller radius to match original + // This exactly matches the innerSphere() function in the original code let earth_geometry = IcosahedronGeometry::new(0.999, 50); let earth_material = MeshStandardMaterial::new_with_params(&material_params); @@ -123,7 +152,10 @@ pub fn init_globe(canvas: &HtmlCanvasElement) -> Result<(), JsError> { ); scene.add(&earth_mesh); + gloo_console::log!("Earth mesh added to scene"); + // COMMENTED OUT: Orbit controls setup + /* // Set up orbit controls similar to the original frontend let controls = OrbitControls::new(&camera, &renderer.domElement()); controls.set_min_zoom(1.0); @@ -138,23 +170,32 @@ pub fn init_globe(canvas: &HtmlCanvasElement) -> Result<(), JsError> { let mut state = state_ref.borrow_mut(); state.controls = Some(controls); }); + */ + + // Render once without controls for now - MUST be done before moving to STATE + renderer.render(&scene, &camera); + // COMMENTED OUT: Control change callback + /* // Create a callback that works with controls via STATE rather than direct capture let control_change_callback = Closure::wrap(Box::new(|| { - // Access controls through STATE to avoid move issues STATE.with(|state_ref| { let state = state_ref.borrow(); - if let Some(controls) = &state.controls { - // We can update controls settings here if needed + if let (Some(scene), Some(camera), Some(renderer)) = (&state.scene, &state.camera, &state.renderer) { + renderer.render(scene, camera); } }); }) as Box); + */ + + // Simple empty callback for now + let control_change_callback = Closure::wrap(Box::new(|| {}) as Box); // Get a reference to controls from STATE to add the event listener STATE.with(|state_ref| { let state = state_ref.borrow(); if let Some(controls) = &state.controls { - controls.add_event_listener("change", &control_change_callback); + // controls.add_event_listener("change", &control_change_callback); } }); @@ -164,7 +205,7 @@ pub fn init_globe(canvas: &HtmlCanvasElement) -> Result<(), JsError> { state.callbacks.push(control_change_callback); }); - // Register window resize handler + /* COMMENTED OUT: Window resize handler let resize_callback = Closure::wrap(Box::new(move || { STATE.with(|state_ref| { let state = state_ref.borrow(); @@ -175,6 +216,7 @@ pub fn init_globe(canvas: &HtmlCanvasElement) -> Result<(), JsError> { let aspect = width / height; let camera_size = 1.0; + // Update the orthographic camera parameters camera.set_left(-camera_size * aspect); camera.set_right(camera_size * aspect); camera.set_top(camera_size); @@ -185,6 +227,9 @@ pub fn init_globe(canvas: &HtmlCanvasElement) -> Result<(), JsError> { } }); }) as Box); + */ + // Simple empty callback for now + let resize_callback = Closure::wrap(Box::new(move || {}) as Box); // Add the resize listener window.add_event_listener_with_callback("resize", resize_callback.as_ref().unchecked_ref()).unwrap(); @@ -202,13 +247,15 @@ pub fn init_globe(canvas: &HtmlCanvasElement) -> Result<(), JsError> { state.camera = Some(camera); state.renderer = Some(renderer); state.earth_mesh = Some(earth_mesh); - // controls already stored above + // state.controls = Some(controls); // Commented out since we commented the controls }); - // Start animation loop - start_animation()?; + // COMMENTED OUT: Animation + // start_animation()?; + + // No need for another render call here, already rendered above - info!("Three.js Earth globe initialized"); + log::info!("Three.js Earth globe initialized"); Ok(()) } @@ -269,6 +316,17 @@ fn start_animation() -> Result<(), JsError> { let camera_js: &JsValue = camera.as_ref(); renderer.render(scene, camera_js); + // Log the first few animation frames to confirm rendering is happening + static mut FRAME_COUNT: u32 = 0; + unsafe { + if FRAME_COUNT < 5 { + // Fix the formatting syntax for gloo_console + let frame_msg = format!("Animation frame rendered: {}", FRAME_COUNT); + gloo_console::log!(frame_msg); + FRAME_COUNT += 1; + } + } + // Schedule the next animation frame request_next_frame(state_ref_clone.clone()); }; diff --git a/clickplanet-webapp/src/app/components/earth/three_js/mod.rs b/clickplanet-webapp/src/app/components/earth/three_js/mod.rs index 38da68e..d1f9ca1 100644 --- a/clickplanet-webapp/src/app/components/earth/three_js/mod.rs +++ b/clickplanet-webapp/src/app/components/earth/three_js/mod.rs @@ -1,6 +1,5 @@ mod bindings; mod globe; -mod cube; pub use self::globe::init_globe; pub use self::bindings::is_three_available; \ No newline at end of file diff --git a/clickplanet-webapp/src/app/components/earth/wgpu/mod.rs b/clickplanet-webapp/src/app/components/earth/wgpu/mod.rs index bb007f2..5255d99 100644 --- a/clickplanet-webapp/src/app/components/earth/wgpu/mod.rs +++ b/clickplanet-webapp/src/app/components/earth/wgpu/mod.rs @@ -1,9 +1,3 @@ mod animation_loop; mod setup_webgpu; -mod shader_validation; mod create_sphere; - -pub use animation_loop::*; -pub use setup_webgpu::*; -pub use shader_validation::*; -pub use create_sphere::*; diff --git a/clickplanet-webapp/src/app/components/earth/wgpu/shader_validation.rs b/clickplanet-webapp/src/app/components/earth/wgpu/shader_validation.rs deleted file mode 100644 index e56d291..0000000 --- a/clickplanet-webapp/src/app/components/earth/wgpu/shader_validation.rs +++ /dev/null @@ -1,56 +0,0 @@ - -/// Validates WGSL shader code by attempting to compile it -#[cfg(test)] -pub fn validate_shader_code(shader_source: &str) { - use wgpu::ShaderSource; - - // This function ensures the shader code is syntactically valid - // by attempting to create a shader module with it. - // It will panic if the shader has syntax errors. - - // Create a headless device for testing - pollster::block_on(async { - let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::default()); - let adapter = instance - .request_adapter(&wgpu::RequestAdapterOptions { - power_preference: wgpu::PowerPreference::default(), - compatible_surface: None, - force_fallback_adapter: false, - }) - .await - .expect("Failed to find an appropriate adapter for shader testing"); - - let (device, _) = adapter - .request_device( - &wgpu::DeviceDescriptor { - label: Some("Test Device"), - features: wgpu::Features::empty(), - limits: wgpu::Limits::default(), - memory_hints: wgpu::MemoryHints::default(), - trace: wgpu::Trace::default(), - }, - ) - .await - .expect("Failed to create device for shader testing"); - - // Create shader module - this will validate the syntax - let _shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { - label: Some("Test Shader"), - source: ShaderSource::Wgsl(std::borrow::Cow::Borrowed(shader_source)), - }); - - // If we reach here without panicking, the shader is valid - println!("WGSL shader validation successful"); - }); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_globe_shader_validation() { - // This test validates that the globe.wgsl shader has valid syntax - validate_shader_code(include_str!("globe.wgsl")); - } -} diff --git a/clickplanet-webapp/src/main.rs b/clickplanet-webapp/src/main.rs index 8d2c062..2d4015e 100644 --- a/clickplanet-webapp/src/main.rs +++ b/clickplanet-webapp/src/main.rs @@ -26,22 +26,32 @@ enum Route { // Root app component that sets up the router #[allow(non_snake_case)] fn App() -> Element { - + let import_map = r#"{ + "imports": { + "three": "https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js", + "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/" + } + }"#.to_string(); + rsx! { - // document::Link { rel: "icon", href: asset!("public/static/favicon.png") } - // Stylesheet { href: asset!("public/styles/base.css") } - // Stylesheet { href: asset!("public/styles/DiscordButton.css") } - // Stylesheet { href: asset!("public/styles/BuyMeACoffee.css") } - // Stylesheet { href: asset!("public/styles/Modal.css") } - // Stylesheet { href: asset!("public/styles/CloseButton.css") } - // Stylesheet { href: asset!("public/styles/SelectWithSearch.css") } - // Stylesheet { href: asset!("public/styles/About.css") } - // Stylesheet { href: asset!("public/styles/Leaderboard.css") } - // Stylesheet { href: asset!("public/styles/Menu.css") } + document::Link { rel: "icon", href: asset!("public/static/favicon.png") } + Stylesheet { href: asset!("public/styles/base.css") } + Stylesheet { href: asset!("public/styles/DiscordButton.css") } + Stylesheet { href: asset!("public/styles/BuyMeACoffee.css") } + Stylesheet { href: asset!("public/styles/Modal.css") } + Stylesheet { href: asset!("public/styles/CloseButton.css") } + Stylesheet { href: asset!("public/styles/SelectWithSearch.css") } + Stylesheet { href: asset!("public/styles/About.css") } + Stylesheet { href: asset!("public/styles/Leaderboard.css") } + Stylesheet { href: asset!("public/styles/Menu.css") } + + script { + r#type: "importmap", + {import_map} + } - // Stylesheet { href: asset!("public/styles/rust-specific.css") } + Stylesheet { href: asset!("public/styles/rust-specific.css") } div { class: "content", - // Router uses the Route enum to handle URL-based routing Router:: {} } } @@ -50,23 +60,21 @@ fn App() -> Element { // Home component with the globe and main UI #[component] fn Home() -> Element { - // let mut show_welcome_modal = use_signal(|| true); + let mut show_welcome_modal = use_signal(|| true); // Manage country state here, similar to the original TypeScript implementation - /*let mut country = use_signal(|| Country { + let mut country = use_signal(|| Country { name: "United States".to_string(), code: "us".to_string(), - });*/ + }); // Callback to update country - /*let set_country = move |new_country: Country| { + let set_country = move |new_country: Country| { country.set(new_country); - };*/ + }; rsx! { - div { class: "container", - // Commented out welcome modal - /* + div { class: "container", if show_welcome_modal() { app::components::on_load_modal::OnLoadModal { title: "Dear earthlings".to_string(), @@ -90,13 +98,10 @@ fn Home() -> Element { } } } - */ - // Only show the globe component for now - app::components::earth::globe::Globe {} - // Commented out menu and other UI elements - /* + app::components::earth::globe::Globe {} + div { class: "menu", app::components::leaderboard::Leaderboard {} div { class: "menu-actions", @@ -110,7 +115,6 @@ fn Home() -> Element { } } } - */ } } } From c174cc2be37ed9d5db5fa2c5d4449ddd9651ae3c Mon Sep 17 00:00:00 2001 From: Laurent Valdes Date: Wed, 7 May 2025 18:10:32 +0200 Subject: [PATCH 13/28] fix(texture): implement texture loading with gloo_timers --- .../src/app/components/earth/globe.rs | 12 +- .../app/components/earth/three_js/bindings.rs | 3 + .../app/components/earth/three_js/globe.rs | 142 ++++++++++-------- 3 files changed, 93 insertions(+), 64 deletions(-) diff --git a/clickplanet-webapp/src/app/components/earth/globe.rs b/clickplanet-webapp/src/app/components/earth/globe.rs index 430be90..18700e3 100644 --- a/clickplanet-webapp/src/app/components/earth/globe.rs +++ b/clickplanet-webapp/src/app/components/earth/globe.rs @@ -30,13 +30,15 @@ pub fn Globe() -> Element { console.log('OrbitControls available:', typeof OrbitControls); console.log('GLTFLoader available:', typeof GLTFLoader); - // Add texture loading test to check if the URL is correct + // Make sure to expose environment variable to JavaScript + window.CITYWARS_STATIC_SITE = "https://storage.googleapis.com/lv-project-313715-clickwars-static/static"; + // Add texture loading test with detailed diagnostics const textureUrl = window.CITYWARS_STATIC_SITE + '/earth/3_no_ice_clouds_16k.jpg'; console.log('Testing texture URL:', textureUrl); - const img = new Image(); - img.onload = () => console.log('✅ Texture loaded successfully:', textureUrl); - img.onerror = () => console.error('❌ Texture failed to load:', textureUrl); - img.src = textureUrl; + + // Check CORS environment + console.log('CORS Origin:', window.location.origin); + console.log('CORS Headers available in browser:', typeof Headers); "#} } diff --git a/clickplanet-webapp/src/app/components/earth/three_js/bindings.rs b/clickplanet-webapp/src/app/components/earth/three_js/bindings.rs index f8a9ef4..fafd495 100644 --- a/clickplanet-webapp/src/app/components/earth/three_js/bindings.rs +++ b/clickplanet-webapp/src/app/components/earth/three_js/bindings.rs @@ -291,6 +291,9 @@ extern "C" { #[wasm_bindgen(method, js_namespace = THREE, js_name = load)] pub fn load(this: &TextureLoader, url: &str) -> Texture; + + #[wasm_bindgen(method, js_namespace = THREE, js_name = setCrossOrigin)] + pub fn set_cross_origin(this: &TextureLoader, cross_origin: &str); // Euler for rotation #[wasm_bindgen(js_namespace = THREE)] diff --git a/clickplanet-webapp/src/app/components/earth/three_js/globe.rs b/clickplanet-webapp/src/app/components/earth/three_js/globe.rs index 7953f3e..a93127e 100644 --- a/clickplanet-webapp/src/app/components/earth/three_js/globe.rs +++ b/clickplanet-webapp/src/app/components/earth/three_js/globe.rs @@ -1,15 +1,18 @@ use wasm_bindgen::prelude::*; use web_sys::HtmlCanvasElement; -use gloo_utils::{window}; +use js_sys::Object; +use gloo_utils::window; use std::rc::Rc; use std::cell::RefCell; use gloo::render::{AnimationFrame, request_animation_frame}; use gloo_console; +use gloo_timers::callback::Timeout; use log; -use super::bindings::{self, AmbientLight, Scene, OrthographicCamera, OrbitControls, - WebGLRenderer, WebGLRendererParams, TextureLoader, Mesh, IcosahedronGeometry, - MeshStandardMaterial, diagnose_three_js_loading, is_three_available}; +use crate::app::components::earth::three_js::bindings::{Scene, WebGLRenderer, OrbitControls, AmbientLight, + MeshStandardMaterial, BufferGeometry, Material, Texture, Mesh, OrthographicCamera, WebGLRendererParams, + IcosahedronGeometry}; +use crate::app::components::earth::three_js::bindings::TextureLoader; struct ThreeJsGlobeState { scene: Option, @@ -33,21 +36,86 @@ thread_local! { }); } +fn create_earth_geometry() -> BufferGeometry { + let earth_geometry: IcosahedronGeometry = IcosahedronGeometry::new(0.999, 50); + let geometry_js: &JsValue = earth_geometry.as_ref(); + let buffer_geometry: BufferGeometry = geometry_js.clone().into(); + buffer_geometry +} + +/// Helper function to create a material with a specific color +fn create_material_with_color(color: u32) -> MeshStandardMaterial { + let params = js_sys::Object::new(); + js_sys::Reflect::set(¶ms, &"color".into(), &color.into()).unwrap(); + MeshStandardMaterial::new_with_params(¶ms) +} + +/// Creates earth material following the original frontend implementation +fn create_earth_material(static_site: &str) -> Material { + + + // Debug original implementation pattern + gloo_console::log!("ORIGINAL: creating THREE.MeshStandardMaterial with map: textureLoader.load(...)"); + + // Create a material with white base color using our helper function + let earth_material: MeshStandardMaterial = create_material_with_color(0xFFFFFF); + + // Load texture + let texture_url: String = format!("{}/earth/3_no_ice_clouds_16k.jpg", static_site); + gloo_console::log!(format!("Loading texture from: {}", texture_url)); + + // Create texture loader with CORS handling + let texture_loader: TextureLoader = TextureLoader::new(); + texture_loader.set_cross_origin("anonymous"); + + // Load the texture + let earth_texture: Texture = texture_loader.load(&texture_url); + + // Check initial texture properties + gloo_console::log!("Initial texture object:"); + gloo_console::log!(&earth_texture); + + // Set the texture on the material now + gloo_console::log!("Setting texture on material"); + js_sys::Reflect::set(earth_material.as_ref(), &"map".into(), earth_texture.as_ref()).unwrap(); + + // Create a shared reference to the material that can be used from the timer closure + let material_ref = Rc::new(earth_material); + let material_clone = material_ref.clone(); + + // Set up a timer to update the material after 2 seconds when texture has loaded + gloo_console::log!("Setting up 2-second gloo timer for texture loading"); + let timeout = Timeout::new(2_000, move || { + gloo_console::log!("Timer complete - updating material"); + + // Set needsUpdate to true to tell Three.js to refresh the material + js_sys::Reflect::set(material_clone.as_ref(), &"needsUpdate".into(), &JsValue::from_bool(true)).unwrap(); + + gloo_console::log!("Material updated with texture"); + }); + + // Forget the timeout so it's not dropped early + timeout.forget(); + + // Get the material from the Rc and convert it to the right type + // We need to explicitly convert to JsValue first + let js_val: JsValue = wasm_bindgen::JsValue::from(material_ref.as_ref()); + let material_value = Material::from(js_val); + + material_value +} + /// Initialize the Three.js scene with the Earth globe pub fn init_globe(canvas: &HtmlCanvasElement) -> Result<(), JsError> { - // First log to check if function is being called gloo_console::log!("INIT GLOBE STARTING"); cleanup_globe(); - // Set the static site URL as a global variable for texture loading let static_site = env!("CITYWARS_STATIC_SITE"); let window = window(); - // Run detailed diagnostic to check Three.js and OrbitControls availability let diagnostic_result = super::bindings::diagnose_three_js_loading(); gloo_console::log!("THREE diagnostics: {}", diagnostic_result); - // Check if THREE object is available in the global scope let three_available = js_sys::Reflect::has(&window, &JsValue::from_str("THREE")) .map_err(|_| JsError::new("Failed to check for THREE global object"))?; @@ -55,18 +123,15 @@ pub fn init_globe(canvas: &HtmlCanvasElement) -> Result<(), JsError> { return Err(JsError::new("THREE global object not found. Make sure Three.js is loaded properly.")); } - // Set the static site URL directly on the window object js_sys::Reflect::set( &window, &JsValue::from_str("CITYWARS_STATIC_SITE"), &JsValue::from_str(static_site) ).map_err(|_| JsError::new("Failed to set static site URL"))?; - // Create scene let scene = Scene::new(); gloo_console::log!("Scene created"); - // Set up camera let width = window.inner_width() .map_err(|_| JsError::new("Failed to get window width"))? .as_f64() @@ -80,7 +145,6 @@ pub fn init_globe(canvas: &HtmlCanvasElement) -> Result<(), JsError> { let aspect = width / height; let camera_size = 1.0; - // Use OrthographicCamera as in the original code let camera = OrthographicCamera::new( -camera_size * aspect, camera_size * aspect, @@ -90,65 +154,25 @@ pub fn init_globe(canvas: &HtmlCanvasElement) -> Result<(), JsError> { 100.0 ); - // Position camera just like in the original code let position = camera.position(); position.set_z(5.0); gloo_console::log!("Camera created and positioned at z=5.0"); - // Create renderer with Rust-idiomatic parameters let mut renderer_params = WebGLRendererParams::new(); renderer_params.set_canvas(&canvas); renderer_params.set_antialias(true); - let js_params = JsValue::from(&renderer_params); + let js_params: JsValue = JsValue::from(&renderer_params); - let renderer = WebGLRenderer::new_with_parameters(&js_params); + let renderer: WebGLRenderer = WebGLRenderer::new_with_parameters(&js_params); renderer.set_size(width, height); - - // Ensure the background is black (0x000000) renderer.set_clear_color(0x000000); - gloo_console::log!("Setting renderer background to black"); - - // Fix the formatting syntax for gloo_console - let size_msg = format!("Renderer created with size: {} x {}", width, height); - gloo_console::log!(size_msg); - - // Add lighting just like in the original code - let light = AmbientLight::new(0xffffff, 2.0); - scene.add(&light); - gloo_console::log!("Lighting added to scene"); - - // Create earth sphere - let static_site = env!("CITYWARS_STATIC_SITE"); - // let texture_loader = TextureLoader::new(); - - // COMMENTED OUT: Texture loading for now - // let earth_texture = texture_loader.load(&format!("{}/earth/3_no_ice_clouds_16k.jpg", static_site)); - // let texture_msg = format!("Texture loading from: {}/earth/3_no_ice_clouds_16k.jpg", static_site); - // gloo_console::log!(texture_msg); - - // Create a simple red material instead - let material_params = js_sys::Object::new(); - // Set color to red (0xFF0000) - js_sys::Reflect::set(&material_params, &"color".into(), &JsValue::from_f64(16711680.0)).unwrap(); // 0xFF0000 as f64 - gloo_console::log!("Using red material for sphere instead of texture"); - - // Create inner sphere with slightly smaller radius to match original - // This exactly matches the innerSphere() function in the original code - let earth_geometry = IcosahedronGeometry::new(0.999, 50); - let earth_material = MeshStandardMaterial::new_with_params(&material_params); - - // Properly cast the types for Rust - let geometry_js: &JsValue = earth_geometry.as_ref(); - let material_js: &JsValue = earth_material.as_ref(); - // Create BufferGeometry and Material from JS representations - let buffer_geometry = geometry_js.clone().into(); - let material_value = material_js.clone().into(); + scene.add(&AmbientLight::new(0xffffff, 2.0)); - let earth_mesh = Mesh::new_with_geometry_material( - &buffer_geometry, - &material_value + let earth_mesh: Mesh = Mesh::new_with_geometry_material( + &create_earth_geometry(), + &create_earth_material(static_site) ); scene.add(&earth_mesh); @@ -194,7 +218,7 @@ pub fn init_globe(canvas: &HtmlCanvasElement) -> Result<(), JsError> { // Get a reference to controls from STATE to add the event listener STATE.with(|state_ref| { let state = state_ref.borrow(); - if let Some(controls) = &state.controls { + if let Some(_controls) = &state.controls { // controls.add_event_listener("change", &control_change_callback); } }); From 7165a98a77abfd2593eacf9fa984821f7add9719 Mon Sep 17 00:00:00 2001 From: Laurent Valdes Date: Wed, 7 May 2025 19:13:42 +0200 Subject: [PATCH 14/28] fix(three_js): implement pure Rust texture loading with callbacks - Add proper TextureLoader bindings with callback support - Replace JS evaluation code with Rust implementation - Fix animation loop to prevent panics - Improve state management for resources and callbacks - Fix type conversions between geometry and material types --- .../src/app/components/earth/globe.rs | 32 -- .../app/components/earth/three_js/bindings.rs | 6 + .../app/components/earth/three_js/globe.rs | 384 +++++++----------- 3 files changed, 152 insertions(+), 270 deletions(-) diff --git a/clickplanet-webapp/src/app/components/earth/globe.rs b/clickplanet-webapp/src/app/components/earth/globe.rs index 18700e3..ab51c59 100644 --- a/clickplanet-webapp/src/app/components/earth/globe.rs +++ b/clickplanet-webapp/src/app/components/earth/globe.rs @@ -6,8 +6,6 @@ use wasm_bindgen_futures::spawn_local; use gloo_timers::future::TimeoutFuture; use crate::app::components::earth::three_js::{init_globe, is_three_available}; -/// The Globe component acts as a wrapper for our Three.js implementation -/// This uses the Three.js renderer instead of WebGPU directly for better compatibility #[component] pub fn Globe() -> Element { let cube_loaded = use_signal(|| false); @@ -24,21 +22,6 @@ pub fn Globe() -> Element { window.THREE = THREE; window.OrbitControls = OrbitControls; window.GLTFLoader = GLTFLoader; - - // Direct JS console logging - console.log('THREE.js imports loaded. THREE version:', THREE.REVISION); - console.log('OrbitControls available:', typeof OrbitControls); - console.log('GLTFLoader available:', typeof GLTFLoader); - - // Make sure to expose environment variable to JavaScript - window.CITYWARS_STATIC_SITE = "https://storage.googleapis.com/lv-project-313715-clickwars-static/static"; - // Add texture loading test with detailed diagnostics - const textureUrl = window.CITYWARS_STATIC_SITE + '/earth/3_no_ice_clouds_16k.jpg'; - console.log('Testing texture URL:', textureUrl); - - // Check CORS environment - console.log('CORS Origin:', window.location.origin); - console.log('CORS Headers available in browser:', typeof Headers); "#} } @@ -51,32 +34,17 @@ pub fn Globe() -> Element { width: "100%", style: "background-color: black;", onmounted: move |el| { - // Direct JS logging to check canvas element - let js_code = format!(r#"console.log('Canvas onmounted triggered for id: {}');"#, canvas_id); - let _ = js_sys::eval(&js_code); - let mut cube_loaded_clone = cube_loaded.clone(); let web_element = el.as_web_event(); if let Some(canvas) = web_element.dyn_into::().ok() { - // Log canvas dimensions - let js_code = format!(r#"console.log('Canvas dimensions:', document.getElementById('{}').clientWidth, 'x', document.getElementById('{}').clientHeight);"#, canvas_id, canvas_id); - let _ = js_sys::eval(&js_code); spawn_local(async move { - // Wait for scripts to load - THREE is loaded asynchronously - // so we need to wait before checking availability - gloo_console::log!("Waiting for THREE to load..."); TimeoutFuture::new(1000).await; // Wait 1 second for scripts to load - // Now check THREE availability after waiting - gloo_console::log!("Checking THREE availability"); - if is_three_available() { - gloo_console::log!("THREE is available, initializing globe"); if let Ok(_) = init_globe(&canvas) { cube_loaded_clone.set(true); - gloo_console::log!("Globe initialization successful"); } else { gloo_console::log!("Globe initialization FAILED"); } diff --git a/clickplanet-webapp/src/app/components/earth/three_js/bindings.rs b/clickplanet-webapp/src/app/components/earth/three_js/bindings.rs index fafd495..761ccdb 100644 --- a/clickplanet-webapp/src/app/components/earth/three_js/bindings.rs +++ b/clickplanet-webapp/src/app/components/earth/three_js/bindings.rs @@ -289,6 +289,12 @@ extern "C" { #[wasm_bindgen(constructor, js_namespace = THREE)] pub fn new() -> TextureLoader; + // Single load method with all parameters + // When calling this method, you can pass JsValue::UNDEFINED for callbacks you don't need + #[wasm_bindgen(method, js_namespace = THREE, js_name = load)] + pub fn load_with_callbacks(this: &TextureLoader, url: &str, on_load: &JsValue, on_progress: &JsValue, on_error: &JsValue) -> Texture; + + // Convenience method for simple loading without callbacks #[wasm_bindgen(method, js_namespace = THREE, js_name = load)] pub fn load(this: &TextureLoader, url: &str) -> Texture; diff --git a/clickplanet-webapp/src/app/components/earth/three_js/globe.rs b/clickplanet-webapp/src/app/components/earth/three_js/globe.rs index a93127e..9259f35 100644 --- a/clickplanet-webapp/src/app/components/earth/three_js/globe.rs +++ b/clickplanet-webapp/src/app/components/earth/three_js/globe.rs @@ -1,27 +1,25 @@ use wasm_bindgen::prelude::*; use web_sys::HtmlCanvasElement; -use js_sys::Object; use gloo_utils::window; -use std::rc::Rc; use std::cell::RefCell; -use gloo::render::{AnimationFrame, request_animation_frame}; +use gloo::render::AnimationFrame; use gloo_console; -use gloo_timers::callback::Timeout; use log; -use crate::app::components::earth::three_js::bindings::{Scene, WebGLRenderer, OrbitControls, AmbientLight, - MeshStandardMaterial, BufferGeometry, Material, Texture, Mesh, OrthographicCamera, WebGLRendererParams, - IcosahedronGeometry}; -use crate::app::components::earth::three_js::bindings::TextureLoader; +use crate::app::components::earth::three_js::bindings::*; struct ThreeJsGlobeState { scene: Option, camera: Option, renderer: Option, earth_mesh: Option, + earth_material: Option, controls: Option, animation_id: Option, - callbacks: Vec>, + resize_callback: Option>, + animation_callback: Option>, + texture_callback: Option>, + error_callback: Option>, } thread_local! { @@ -32,80 +30,14 @@ thread_local! { earth_mesh: None, controls: None, animation_id: None, - callbacks: Vec::new(), + resize_callback: None, + animation_callback: None, + earth_material: None, + texture_callback: None, + error_callback: None, }); } -fn create_earth_geometry() -> BufferGeometry { - let earth_geometry: IcosahedronGeometry = IcosahedronGeometry::new(0.999, 50); - let geometry_js: &JsValue = earth_geometry.as_ref(); - let buffer_geometry: BufferGeometry = geometry_js.clone().into(); - buffer_geometry -} - -/// Helper function to create a material with a specific color -fn create_material_with_color(color: u32) -> MeshStandardMaterial { - let params = js_sys::Object::new(); - js_sys::Reflect::set(¶ms, &"color".into(), &color.into()).unwrap(); - MeshStandardMaterial::new_with_params(¶ms) -} - -/// Creates earth material following the original frontend implementation -fn create_earth_material(static_site: &str) -> Material { - - - // Debug original implementation pattern - gloo_console::log!("ORIGINAL: creating THREE.MeshStandardMaterial with map: textureLoader.load(...)"); - - // Create a material with white base color using our helper function - let earth_material: MeshStandardMaterial = create_material_with_color(0xFFFFFF); - - // Load texture - let texture_url: String = format!("{}/earth/3_no_ice_clouds_16k.jpg", static_site); - gloo_console::log!(format!("Loading texture from: {}", texture_url)); - - // Create texture loader with CORS handling - let texture_loader: TextureLoader = TextureLoader::new(); - texture_loader.set_cross_origin("anonymous"); - - // Load the texture - let earth_texture: Texture = texture_loader.load(&texture_url); - - // Check initial texture properties - gloo_console::log!("Initial texture object:"); - gloo_console::log!(&earth_texture); - - // Set the texture on the material now - gloo_console::log!("Setting texture on material"); - js_sys::Reflect::set(earth_material.as_ref(), &"map".into(), earth_texture.as_ref()).unwrap(); - - // Create a shared reference to the material that can be used from the timer closure - let material_ref = Rc::new(earth_material); - let material_clone = material_ref.clone(); - - // Set up a timer to update the material after 2 seconds when texture has loaded - gloo_console::log!("Setting up 2-second gloo timer for texture loading"); - let timeout = Timeout::new(2_000, move || { - gloo_console::log!("Timer complete - updating material"); - - // Set needsUpdate to true to tell Three.js to refresh the material - js_sys::Reflect::set(material_clone.as_ref(), &"needsUpdate".into(), &JsValue::from_bool(true)).unwrap(); - - gloo_console::log!("Material updated with texture"); - }); - - // Forget the timeout so it's not dropped early - timeout.forget(); - - // Get the material from the Rc and convert it to the right type - // We need to explicitly convert to JsValue first - let js_val: JsValue = wasm_bindgen::JsValue::from(material_ref.as_ref()); - let material_value = Material::from(js_val); - - material_value -} - -/// Initialize the Three.js scene with the Earth globe pub fn init_globe(canvas: &HtmlCanvasElement) -> Result<(), JsError> { gloo_console::log!("INIT GLOBE STARTING"); cleanup_globe(); @@ -130,7 +62,6 @@ pub fn init_globe(canvas: &HtmlCanvasElement) -> Result<(), JsError> { ).map_err(|_| JsError::new("Failed to set static site URL"))?; let scene = Scene::new(); - gloo_console::log!("Scene created"); let width = window.inner_width() .map_err(|_| JsError::new("Failed to get window width"))? @@ -156,7 +87,6 @@ pub fn init_globe(canvas: &HtmlCanvasElement) -> Result<(), JsError> { let position = camera.position(); position.set_z(5.0); - gloo_console::log!("Camera created and positioned at z=5.0"); let mut renderer_params = WebGLRendererParams::new(); renderer_params.set_canvas(&canvas); @@ -167,80 +97,62 @@ pub fn init_globe(canvas: &HtmlCanvasElement) -> Result<(), JsError> { let renderer: WebGLRenderer = WebGLRenderer::new_with_parameters(&js_params); renderer.set_size(width, height); renderer.set_clear_color(0x000000); - scene.add(&AmbientLight::new(0xffffff, 2.0)); + + let earth_geometry = IcosahedronGeometry::new(0.999, 50); - let earth_mesh: Mesh = Mesh::new_with_geometry_material( - &create_earth_geometry(), - &create_earth_material(static_site) - ); + let material_params = js_sys::Object::new(); + js_sys::Reflect::set(&material_params, &JsValue::from_str("color"), &JsValue::from_f64(0xFFFFFF as f64)) + .expect("Failed to set material color"); + + let earth_material = MeshStandardMaterial::new_with_params(&material_params); + + let earth_geometry_js: &JsValue = earth_geometry.as_ref(); + let earth_geometry_as_buffer: &BufferGeometry = earth_geometry_js.unchecked_ref(); + + let earth_material_js: &JsValue = earth_material.as_ref(); + let earth_material_as_material: &Material = earth_material_js.unchecked_ref(); + + let earth_mesh = Mesh::new_with_geometry_material(earth_geometry_as_buffer, earth_material_as_material); scene.add(&earth_mesh); - gloo_console::log!("Earth mesh added to scene"); - // COMMENTED OUT: Orbit controls setup - /* - // Set up orbit controls similar to the original frontend - let controls = OrbitControls::new(&camera, &renderer.domElement()); - controls.set_min_zoom(1.0); - controls.set_max_zoom(50.0); - controls.set_pan_speed(0.1); - controls.set_enable_damping(true); - controls.set_auto_rotate(true); - controls.set_rotate_speed(1.0 / 1.5); + let texture_loader = TextureLoader::new(); + texture_loader.set_cross_origin("anonymous"); + let texture_url = format!("{}/earth/3_no_ice_clouds_16k.jpg", static_site); - // Store the controls in STATE before creating the closure STATE.with(|state_ref| { let mut state = state_ref.borrow_mut(); - state.controls = Some(controls); + state.earth_material = Some(earth_material); }); - */ - - // Render once without controls for now - MUST be done before moving to STATE - renderer.render(&scene, &camera); - // COMMENTED OUT: Control change callback - /* - // Create a callback that works with controls via STATE rather than direct capture - let control_change_callback = Closure::wrap(Box::new(|| { + let on_load_callback = Closure::wrap(Box::new(move |texture: Texture| { STATE.with(|state_ref| { let state = state_ref.borrow(); - if let (Some(scene), Some(camera), Some(renderer)) = (&state.scene, &state.camera, &state.renderer) { - renderer.render(scene, camera); + if let Some(material) = &state.earth_material { + js_sys::Reflect::set(material.as_ref(), &JsValue::from_str("map"), &texture) + .expect("Failed to set texture map"); + + js_sys::Reflect::set(material.as_ref(), &JsValue::from_str("needsUpdate"), &JsValue::from_bool(true)) + .expect("Failed to set needsUpdate"); } }); - }) as Box); - */ - - // Simple empty callback for now - let control_change_callback = Closure::wrap(Box::new(|| {}) as Box); - - // Get a reference to controls from STATE to add the event listener - STATE.with(|state_ref| { - let state = state_ref.borrow(); - if let Some(_controls) = &state.controls { - // controls.add_event_listener("change", &control_change_callback); - } - }); + }) as Box); - // Store the callback so it doesn't get dropped - STATE.with(|state_ref| { - let mut state = state_ref.borrow_mut(); - state.callbacks.push(control_change_callback); - }); - - /* COMMENTED OUT: Window resize handler + let on_error_callback = Closure::wrap(Box::new(move |err: JsValue| { + gloo_console::error!("Error loading texture: {:?}", err); + }) as Box); + let resize_callback = Closure::wrap(Box::new(move || { + let window = web_sys::window().unwrap(); + let width = window.inner_width().unwrap().as_f64().unwrap(); + let height = window.inner_height().unwrap().as_f64().unwrap(); + let aspect = width / height; + STATE.with(|state_ref| { let state = state_ref.borrow(); if let (Some(renderer), Some(camera)) = (&state.renderer, &state.camera) { - let window = web_sys::window().unwrap(); - let width = window.inner_width().unwrap().as_f64().unwrap(); - let height = window.inner_height().unwrap().as_f64().unwrap(); - let aspect = width / height; - let camera_size = 1.0; - // Update the orthographic camera parameters camera.set_left(-camera_size * aspect); camera.set_right(camera_size * aspect); camera.set_top(camera_size); @@ -248,127 +160,121 @@ pub fn init_globe(canvas: &HtmlCanvasElement) -> Result<(), JsError> { camera.update_projection_matrix(); renderer.set_size(width, height); + + if let Some(scene) = &state.scene { + renderer.render(&scene, &camera); + } + + gloo_console::log!("Window resized: {}x{}", width, height); } }); }) as Box); - */ - // Simple empty callback for now - let resize_callback = Closure::wrap(Box::new(move || {}) as Box); - // Add the resize listener - window.add_event_listener_with_callback("resize", resize_callback.as_ref().unchecked_ref()).unwrap(); + let animate_callback = Closure::wrap(Box::new(|_timestamp: f64| { + STATE.with(|state_ref| { + let state = state_ref.borrow(); + if let (Some(scene), Some(camera), Some(renderer)) = (&state.scene, &state.camera, &state.renderer) { + renderer.render(scene, camera); + } + }); + + if let Some(window) = web_sys::window() { + STATE.with(|state_ref| { + let state = state_ref.borrow(); + if let Some(callback) = &state.animation_callback { + let callback_js_ref = callback.as_ref().unchecked_ref(); + let _ = window.request_animation_frame(callback_js_ref); + } + }); + } + }) as Box); - // Store the callback to prevent it from being dropped + + let on_load_js_ref = on_load_callback.as_ref().unchecked_ref(); + let on_error_js_ref = on_error_callback.as_ref().unchecked_ref(); + + texture_loader.load_with_callbacks( + &texture_url, + on_load_js_ref, + &JsValue::UNDEFINED, + on_error_js_ref + ); + + let resize_js_ref = resize_callback.as_ref().unchecked_ref(); + window.add_event_listener_with_callback("resize", resize_js_ref) + .map_err(|_| JsError::new("Failed to add resize event listener"))?; + + if let Some(window) = web_sys::window() { + let callback_js_ref = animate_callback.as_ref().unchecked_ref(); + let _ = window.request_animation_frame(callback_js_ref); + } + STATE.with(|state_ref| { let mut state = state_ref.borrow_mut(); - state.callbacks.push(resize_callback); + state.texture_callback = Some(on_load_callback); + state.error_callback = Some(on_error_callback); + state.resize_callback = Some(resize_callback); + state.animation_callback = Some(animate_callback); }); + + // Make iitial render + renderer.render(&scene, &camera); - // Store remaining objects in our state struct (controls already stored above) STATE.with(|state_ref| { let mut state = state_ref.borrow_mut(); state.scene = Some(scene); state.camera = Some(camera); state.renderer = Some(renderer); state.earth_mesh = Some(earth_mesh); - // state.controls = Some(controls); // Commented out since we commented the controls + // state.controls = None; // Orbit controls are disabled }); - - // COMMENTED OUT: Animation - // start_animation()?; - - // No need for another render call here, already rendered above - - log::info!("Three.js Earth globe initialized"); - Ok(()) -} -fn start_animation() -> Result<(), JsError> { - // Create an animation loop using Rc and RefCell for shared state - // let animation_state = Rc::new(RefCell::new(None)); - // Recursive function to request the next animation frame - fn request_next_frame(state_ref_clone: Rc>>){ - // Use a recursive function to create a perpetual animation loop - let state_ref_clone = state_ref_clone.clone(); - let callback = move |_timestamp: f64| { - // First time setup - extract the state from thread_local - if state_ref_clone.borrow().is_none() { - STATE.with(|global_state| { - let mut state = global_state.borrow_mut(); - - // If we don't have the scene or renderer, return - if state.scene.is_none() || state.camera.is_none() || - state.renderer.is_none() { - return; - } - - // Move objects from thread_local to our Rc - *state_ref_clone.borrow_mut() = Some(( - state.scene.take().unwrap(), - state.camera.take().unwrap(), - state.renderer.take().unwrap(), - )); - }); - } - - // Check if we have the state - let state_exists = state_ref_clone.borrow().is_some(); - if !state_exists { - return; - } - - // Use the state to render the scene - let mut state_borrowed = state_ref_clone.borrow_mut(); - let (scene, camera, renderer) = state_borrowed.as_mut().unwrap(); - - // Update controls and auto-rotate the earth - STATE.with(|state_ref| { - let state = state_ref.borrow(); - if let Some(controls) = &state.controls { - controls.update(); - } - - // Also apply a gentle auto-rotation to the earth mesh - if let Some(earth) = &state.earth_mesh { - let rotation = earth.rotation(); - rotation.set_y(rotation.y() + 0.002); - } - }); - - // Render the scene - let camera_js: &JsValue = camera.as_ref(); - renderer.render(scene, camera_js); - - // Log the first few animation frames to confirm rendering is happening - static mut FRAME_COUNT: u32 = 0; - unsafe { - if FRAME_COUNT < 5 { - // Fix the formatting syntax for gloo_console - let frame_msg = format!("Animation frame rendered: {}", FRAME_COUNT); - gloo_console::log!(frame_msg); - FRAME_COUNT += 1; - } - } - - // Schedule the next animation frame - request_next_frame(state_ref_clone.clone()); - }; - - // Request a single animation frame - let handle = request_animation_frame(callback); - - // Store the animation frame + /* + // Set up orbit controls similar to the original frontend + let controls = OrbitControls::new(&camera, &renderer.domElement()); + controls.set_min_zoom(1.0); + controls.set_max_zoom(50.0); + controls.set_pan_speed(0.1); + controls.set_zoom_speed(0.5); + controls.set_enable_damping(true); + controls.set_auto_rotate(true); + controls.set_rotate_speed(1.0 / 1.5); + */ + + // COMMENTED OUT: Control change callback + /* + // Create a callback that works with controls via STATE rather than direct capture + let control_change_callback = Closure::wrap(Box::new(|| { STATE.with(|state_ref| { - let mut state = state_ref.borrow_mut(); - state.animation_id = Some(handle); + let state = state_ref.borrow(); + if let (Some(scene), Some(camera), Some(renderer)) = (&state.scene, &state.camera, &state.renderer) { + renderer.render(scene, camera); + } }); - } + }) as Box); + */ - // Start the animation loop - let shared_state = Rc::new(RefCell::new(None)); - request_next_frame(shared_state); + // Simple empty callback for now + //let control_change_callback = Closure::wrap(Box::new(|| {}) as Box); + // Get a reference to controls from STATE to add the event listener + /*STATE.with(|state_ref| { + let state = state_ref.borrow(); + if let Some(_controls) = &state.controls { + // controls.add_event_listener("change", &control_change_callback); + } + });*/ + + // Store the callback so it doesn't get dropped + /*STATE.with(|state_ref| { + let mut state = state_ref.borrow_mut(); + state.callbacks.push(control_change_callback); + });*/ + + // No need for another render call here, already rendered above + + log::info!("Three.js Earth globe initialized"); Ok(()) } @@ -377,19 +283,21 @@ pub fn cleanup_globe() { STATE.with(|state_ref| { let mut state = state_ref.borrow_mut(); - // Dispose of renderer if needed if let Some(renderer) = &state.renderer { renderer.dispose(); } - // Reset all state - AnimationFrame automatically cancels on drop state.animation_id = None; state.scene = None; state.camera = None; state.renderer = None; state.earth_mesh = None; state.controls = None; - state.callbacks.clear(); + state.resize_callback = None; + state.animation_callback = None; + state.texture_callback = None; + state.error_callback = None; + state.earth_material = None; }); } From 1ae4bc87de1280f7ce1bb130da3b029b96fb1a71 Mon Sep 17 00:00:00 2001 From: Laurent Valdes Date: Thu, 8 May 2025 02:48:51 +0200 Subject: [PATCH 15/28] refactor: simplify the binding --- Cargo.lock | 448 ++++++++---------- clickplanet-webapp/.cargo/config.toml | 9 + clickplanet-webapp/Cargo.toml | 77 ++- .../app/components/earth/three_js/bindings.rs | 53 +-- .../app/components/earth/three_js/globe.rs | 9 +- 5 files changed, 261 insertions(+), 335 deletions(-) create mode 100644 clickplanet-webapp/.cargo/config.toml diff --git a/Cargo.lock b/Cargo.lock index d70ab0d..d24cda8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -117,6 +117,15 @@ version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" +[[package]] +name = "ash" +version = "0.38.0+1.3.281" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f" +dependencies = [ + "libloading", +] + [[package]] name = "async-channel" version = "1.9.0" @@ -476,15 +485,6 @@ version = "1.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "89e25b6adfb930f02d1981565a6e5d9c547ac15a96606256d3b59040e5cd4ca3" -[[package]] -name = "bincode" -version = "1.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad" -dependencies = [ - "serde", -] - [[package]] name = "bindgen" version = "0.69.5" @@ -538,6 +538,12 @@ dependencies = [ "serde", ] +[[package]] +name = "block" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a" + [[package]] name = "block-buffer" version = "0.7.3" @@ -645,9 +651,9 @@ checksum = "e3b5ca7a04898ad4bcd41c90c5285445ff5b791899bb1b0abdd2a2aa791211d7" [[package]] name = "bytemuck" -version = "1.22.0" +version = "1.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6b1fc10dbac614ebc03540c9dbd60e83887fda27794998c6528f1782047d540" +checksum = "9134a6ef01ce4b366b50689c94f82c14bc72bc5d0386829828a2e2752ef7958c" dependencies = [ "bytemuck_derive", ] @@ -937,9 +943,9 @@ dependencies = [ "futures-util", "getrandom 0.2.15", "glam", - "gloo", "gloo-console", - "gloo-net 0.6.0", + "gloo-net", + "gloo-render", "gloo-timers", "gloo-utils", "image", @@ -1113,6 +1119,17 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "core-graphics-types" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf" +dependencies = [ + "bitflags 1.3.2", + "core-foundation 0.9.4", + "libc", +] + [[package]] name = "cpufeatures" version = "0.2.16" @@ -1158,9 +1175,9 @@ checksum = "22ec99545bb0ed0ea7bb9b8e1e9122ea386ff8a48c0922e43f36d45ab09e0e80" [[package]] name = "crunchy" -version = "0.2.2" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a81dae078cea95a014a339291cec439d2f232ebe854a9d672b796c6afafa9b7" +checksum = "43da5946c66ffcc7745f48db692ffbb10a83bfe0afd96235c5c2a4fb23994929" [[package]] name = "crypto-common" @@ -1795,18 +1812,18 @@ dependencies = [ [[package]] name = "enumset" -version = "1.1.5" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d07a4b049558765cef5f0c1a273c3fc57084d768b44d2f98127aef4cceb17293" +checksum = "11a6b7c3d347de0a9f7bfd2f853be43fe32fa6fac30c70f6d6d67a1e936b87ee" dependencies = [ "enumset_derive", ] [[package]] name = "enumset_derive" -version = "0.10.0" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59c3b24c345d8c314966bdc1832f6c2635bfcce8e7cf363bd115987bba2ee242" +checksum = "6da3ea9e1d1a3b1593e15781f930120e72aa7501610b2f82e5b6739c72e8eac5" dependencies = [ "darling", "proc-macro2", @@ -1979,7 +1996,28 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" dependencies = [ - "foreign-types-shared", + "foreign-types-shared 0.1.1", +] + +[[package]] +name = "foreign-types" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965" +dependencies = [ + "foreign-types-macros", + "foreign-types-shared 0.3.1", +] + +[[package]] +name = "foreign-types-macros" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a5c6c585bc94aaf2c7b51dd4c2ba22680844aba4c687be581871a6f518c5742" +dependencies = [ + "proc-macro2", + "quote", + "syn", ] [[package]] @@ -1988,6 +2026,12 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" +[[package]] +name = "foreign-types-shared" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" + [[package]] name = "form_urlencoded" version = "1.2.1" @@ -2202,9 +2246,9 @@ dependencies = [ [[package]] name = "glam" -version = "0.30.1" +version = "0.30.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf3aa70d918d2b234126ff4f850f628f172542bf0603ded26b8ee36e5e22d5f9" +checksum = "6b46b9ca4690308844c644e7c634d68792467260e051c8543e0c7871662b3ba7" [[package]] name = "glob" @@ -2212,25 +2256,6 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" -[[package]] -name = "gloo" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d15282ece24eaf4bd338d73ef580c6714c8615155c4190c781290ee3fa0fd372" -dependencies = [ - "gloo-console", - "gloo-dialogs", - "gloo-events", - "gloo-file", - "gloo-history", - "gloo-net 0.5.0", - "gloo-render", - "gloo-storage", - "gloo-timers", - "gloo-utils", - "gloo-worker", -] - [[package]] name = "gloo-console" version = "0.3.0" @@ -2244,76 +2269,6 @@ dependencies = [ "web-sys", ] -[[package]] -name = "gloo-dialogs" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf4748e10122b01435750ff530095b1217cf6546173459448b83913ebe7815df" -dependencies = [ - "wasm-bindgen", - "web-sys", -] - -[[package]] -name = "gloo-events" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27c26fb45f7c385ba980f5fa87ac677e363949e065a083722697ef1b2cc91e41" -dependencies = [ - "wasm-bindgen", - "web-sys", -] - -[[package]] -name = "gloo-file" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97563d71863fb2824b2e974e754a81d19c4a7ec47b09ced8a0e6656b6d54bd1f" -dependencies = [ - "gloo-events", - "js-sys", - "wasm-bindgen", - "web-sys", -] - -[[package]] -name = "gloo-history" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "903f432be5ba34427eac5e16048ef65604a82061fe93789f2212afc73d8617d6" -dependencies = [ - "getrandom 0.2.15", - "gloo-events", - "gloo-utils", - "serde", - "serde-wasm-bindgen 0.6.5", - "serde_urlencoded", - "thiserror 1.0.69", - "wasm-bindgen", - "web-sys", -] - -[[package]] -name = "gloo-net" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43aaa242d1239a8822c15c645f02166398da4f8b5c4bae795c1f5b44e9eee173" -dependencies = [ - "futures-channel", - "futures-core", - "futures-sink", - "gloo-utils", - "http 0.2.12", - "js-sys", - "pin-project", - "serde", - "serde_json", - "thiserror 1.0.69", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", -] - [[package]] name = "gloo-net" version = "0.6.0" @@ -2345,21 +2300,6 @@ dependencies = [ "web-sys", ] -[[package]] -name = "gloo-storage" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fbc8031e8c92758af912f9bc08fbbadd3c6f3cfcbf6b64cdf3d6a81f0139277a" -dependencies = [ - "gloo-utils", - "js-sys", - "serde", - "serde_json", - "thiserror 1.0.69", - "wasm-bindgen", - "web-sys", -] - [[package]] name = "gloo-timers" version = "0.3.0" @@ -2386,55 +2326,75 @@ dependencies = [ ] [[package]] -name = "gloo-worker" -version = "0.5.0" +name = "glow" +version = "0.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "085f262d7604911c8150162529cefab3782e91adb20202e8658f7275d2aefe5d" +checksum = "c5e5ea60d70410161c8bf5da3fdfeaa1c72ed2c15f8bbb9d19fe3a4fad085f08" dependencies = [ - "bincode", - "futures", - "gloo-utils", - "gloo-worker-macros", "js-sys", - "pinned", - "serde", - "thiserror 1.0.69", + "slotmap", "wasm-bindgen", - "wasm-bindgen-futures", "web-sys", ] [[package]] -name = "gloo-worker-macros" -version = "0.1.0" +name = "glutin_wgl_sys" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "956caa58d4857bc9941749d55e4bd3000032d8212762586fa5705632967140e7" +checksum = "2c4ee00b289aba7a9e5306d57c2d05499b2e5dc427f84ac708bd2c090212cf3e" dependencies = [ - "proc-macro-crate", - "proc-macro2", - "quote", - "syn", + "gl_generator", ] [[package]] -name = "glow" -version = "0.16.0" +name = "gpu-alloc" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5e5ea60d70410161c8bf5da3fdfeaa1c72ed2c15f8bbb9d19fe3a4fad085f08" +checksum = "fbcd2dba93594b227a1f57ee09b8b9da8892c34d55aa332e034a228d0fe6a171" dependencies = [ - "js-sys", - "slotmap", - "wasm-bindgen", - "web-sys", + "bitflags 2.9.0", + "gpu-alloc-types", ] [[package]] -name = "glutin_wgl_sys" -version = "0.6.1" +name = "gpu-alloc-types" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c4ee00b289aba7a9e5306d57c2d05499b2e5dc427f84ac708bd2c090212cf3e" +checksum = "98ff03b468aa837d70984d55f5d3f846f6ec31fe34bbb97c4f85219caeee1ca4" dependencies = [ - "gl_generator", + "bitflags 2.9.0", +] + +[[package]] +name = "gpu-allocator" +version = "0.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c151a2a5ef800297b4e79efa4f4bec035c5f51d5ae587287c9b952bdf734cacd" +dependencies = [ + "log", + "presser", + "thiserror 1.0.69", + "windows", +] + +[[package]] +name = "gpu-descriptor" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dcf29e94d6d243368b7a56caa16bc213e4f9f8ed38c4d9557069527b5d5281ca" +dependencies = [ + "bitflags 2.9.0", + "gpu-descriptor-types", + "hashbrown 0.15.2", +] + +[[package]] +name = "gpu-descriptor-types" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdf242682df893b86f33a73828fb09ca4b2d3bb6cc95249707fc684d27484b91" +dependencies = [ + "bitflags 2.9.0", ] [[package]] @@ -2904,9 +2864,9 @@ dependencies = [ [[package]] name = "image" -version = "0.25.5" +version = "0.25.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd6f44aed642f18953a158afeb30206f4d50da59fbc66ecb53c66488de73563b" +checksum = "db35664ce6b9810857a38a906215e75a9c879f0696556a39f59c62829710251a" dependencies = [ "bytemuck", "byteorder-lite", @@ -3214,6 +3174,21 @@ dependencies = [ "libc", ] +[[package]] +name = "metal" +version = "0.31.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f569fb946490b5743ad69813cb19629130ce9374034abe31614a36402d18f99e" +dependencies = [ + "bitflags 2.9.0", + "block", + "core-graphics-types", + "foreign-types 0.5.0", + "log", + "objc", + "paste", +] + [[package]] name = "mime" version = "0.3.17" @@ -3272,6 +3247,7 @@ dependencies = [ "num-traits", "once_cell", "rustc-hash", + "spirv", "strum", "thiserror 2.0.8", "unicode-ident", @@ -3412,7 +3388,7 @@ checksum = "61cfb4e166a8bb8c9b55c500bc2308550148ece889be90f609377e58140f42c6" dependencies = [ "bitflags 2.9.0", "cfg-if", - "foreign-types", + "foreign-types 0.3.2", "libc", "once_cell", "openssl-macros", @@ -3531,6 +3507,15 @@ dependencies = [ "tracing", ] +[[package]] +name = "ordered-float" +version = "4.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7bb71e1b3fa6ca1c61f383464aaf2bb0e2f8e772a1f01d486832464de363b951" +dependencies = [ + "num-traits", +] + [[package]] name = "osmpbf" version = "0.3.4" @@ -3695,17 +3680,6 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" -[[package]] -name = "pinned" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a829027bd95e54cfe13e3e258a1ae7b645960553fb82b75ff852c29688ee595b" -dependencies = [ - "futures", - "rustversion", - "thiserror 1.0.69", -] - [[package]] name = "piper" version = "0.2.4" @@ -3735,9 +3709,9 @@ checksum = "953ec861398dccce10c670dfeaf3ec4911ca479e9c02154b3a215178c5f566f2" [[package]] name = "png" -version = "0.17.15" +version = "0.17.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b67582bd5b65bdff614270e2ea89a1cf15bef71245cc1e5f7ea126977144211d" +checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526" dependencies = [ "bitflags 1.3.2", "crc32fast", @@ -3822,9 +3796,15 @@ version = "0.2.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77957b295656769bb8ad2b6a6b09d897d94f05c41b069aede1fcdaa675eaea04" dependencies = [ - "zerocopy 0.7.35", + "zerocopy", ] +[[package]] +name = "presser" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa" + [[package]] name = "pretty_assertions" version = "1.4.1" @@ -3845,16 +3825,6 @@ dependencies = [ "syn", ] -[[package]] -name = "proc-macro-crate" -version = "1.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919" -dependencies = [ - "once_cell", - "toml_edit", -] - [[package]] name = "proc-macro2" version = "1.0.92" @@ -4013,13 +3983,12 @@ dependencies = [ [[package]] name = "rand" -version = "0.9.0" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3779b94aeb87e8bd4e834cee3650289ee9e0d5677f976ecdb6d219e5f4f6cd94" +checksum = "9fbfd9d094a40bf3ae768db9361049ace4c0e04a4fd6b359518bd7b73a73dd97" dependencies = [ "rand_chacha 0.9.0", "rand_core 0.9.3", - "zerocopy 0.8.24", ] [[package]] @@ -4060,6 +4029,12 @@ dependencies = [ "getrandom 0.3.2", ] +[[package]] +name = "range-alloc" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d6831663a5098ea164f89cff59c6284e95f4e3c76ce9848d4529f5ccca9bde" + [[package]] name = "raw-window-handle" version = "0.6.2" @@ -4647,7 +4622,7 @@ dependencies = [ "const_format", "dashmap", "futures", - "gloo-net 0.6.0", + "gloo-net", "http 1.2.0", "js-sys", "once_cell", @@ -4802,9 +4777,9 @@ dependencies = [ [[package]] name = "sledgehammer_bindgen_macro" -version = "0.6.0" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33a1b4f13e2bbf2f5b29d09dfebc9de69229ffee245aed80e3b70f9b5fd28c06" +checksum = "f62f06db0370222f7f498ef478fce9f8df5828848d1d3517e3331936d7074f55" dependencies = [ "quote", "syn", @@ -4857,6 +4832,15 @@ version = "0.9.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" +[[package]] +name = "spirv" +version = "0.3.0+sdk-1.3.268.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eda41003dc44290527a59b13432d4a0379379fa074b70174882adfbdfd917844" +dependencies = [ + "bitflags 2.9.0", +] + [[package]] name = "spki" version = "0.7.3" @@ -5347,23 +5331,6 @@ dependencies = [ "tokio", ] -[[package]] -name = "toml_datetime" -version = "0.6.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0dd7358ecb8fc2f8d014bf86f6f638ce72ba252a2c3a2572f2a795f1d23efb41" - -[[package]] -name = "toml_edit" -version = "0.19.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" -dependencies = [ - "indexmap 2.9.0", - "toml_datetime", - "winnow", -] - [[package]] name = "tonic" version = "0.12.3" @@ -5604,7 +5571,7 @@ dependencies = [ "http 1.2.0", "httparse", "log", - "rand 0.9.0", + "rand 0.9.1", "sha1", "thiserror 2.0.8", "utf-8", @@ -5955,12 +5922,32 @@ dependencies = [ "rustc-hash", "smallvec", "thiserror 2.0.8", + "wgpu-core-deps-apple", + "wgpu-core-deps-emscripten", "wgpu-core-deps-wasm", "wgpu-core-deps-windows-linux-android", "wgpu-hal", "wgpu-types", ] +[[package]] +name = "wgpu-core-deps-apple" +version = "25.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfd488b3239b6b7b185c3b045c39ca6bf8af34467a4c5de4e0b1a564135d093d" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-core-deps-emscripten" +version = "25.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f09ad7aceb3818e52539acc679f049d3475775586f3f4e311c30165cf2c00445" +dependencies = [ + "wgpu-hal", +] + [[package]] name = "wgpu-core-deps-wasm" version = "25.0.0" @@ -5985,31 +5972,45 @@ version = "25.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fb7c4a1dc42ff14c23c9b11ebf1ee85cde661a9b1cf0392f79c1faca5bc559fb" dependencies = [ + "android_system_properties", "arrayvec", + "ash", + "bit-set", "bitflags 2.9.0", + "block", "bytemuck", "cfg-if", "cfg_aliases", + "core-graphics-types", "glow", "glutin_wgl_sys", + "gpu-alloc", + "gpu-allocator", + "gpu-descriptor", "hashbrown 0.15.2", "js-sys", "khronos-egl", + "libc", "libloading", "log", + "metal", "naga", "ndk-sys", "objc", + "ordered-float", "parking_lot", "portable-atomic", "profiling", + "range-alloc", "raw-window-handle", "renderdoc-sys", + "smallvec", "thiserror 2.0.8", "wasm-bindgen", "web-sys", "wgpu-types", "windows", + "windows-core 0.58.0", ] [[package]] @@ -6312,15 +6313,6 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" -[[package]] -name = "winnow" -version = "0.5.40" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f593a95398737aeed53e489c785df13f3618e41dbcd6718c6addbf1395aa6876" -dependencies = [ - "memchr", -] - [[package]] name = "wit-bindgen-rt" version = "0.39.0" @@ -6361,9 +6353,9 @@ checksum = "a62ce76d9b56901b19a74f19431b0d8b3bc7ca4ad685a746dfd78ca8f4fc6bda" [[package]] name = "xxhash-rust" -version = "0.8.13" +version = "0.8.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a08fd76779ae1883bbf1e46c2c46a75a0c4e37c445e68a24b01479d438f26ae6" +checksum = "fdd20c5420375476fbd4394763288da7eb0cc0b8c11deed431a91562af7335d3" [[package]] name = "yansi" @@ -6402,16 +6394,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0" dependencies = [ "byteorder", - "zerocopy-derive 0.7.35", -] - -[[package]] -name = "zerocopy" -version = "0.8.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2586fea28e186957ef732a5f8b3be2da217d65c5969d4b1e17f973ebbe876879" -dependencies = [ - "zerocopy-derive 0.8.24", + "zerocopy-derive", ] [[package]] @@ -6425,17 +6408,6 @@ dependencies = [ "syn", ] -[[package]] -name = "zerocopy-derive" -version = "0.8.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a996a8f63c5c4448cd959ac1bab0aaa3306ccfd060472f85943ee0750f0169be" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "zerofrom" version = "0.1.5" diff --git a/clickplanet-webapp/.cargo/config.toml b/clickplanet-webapp/.cargo/config.toml new file mode 100644 index 0000000..b697286 --- /dev/null +++ b/clickplanet-webapp/.cargo/config.toml @@ -0,0 +1,9 @@ +[build] +target = "wasm32-unknown-unknown" +rustflags = ["--cfg=web_sys_unstable_apis"] + +[target.wasm32-unknown-unknown] +runner = "wasm-server-runner" + +[env] +CITYWARS_STATIC_SITE = "https://storage.googleapis.com/lv-project-313715-clickwars-static/static" diff --git a/clickplanet-webapp/Cargo.toml b/clickplanet-webapp/Cargo.toml index 4d9e275..bde73e4 100644 --- a/clickplanet-webapp/Cargo.toml +++ b/clickplanet-webapp/Cargo.toml @@ -16,6 +16,27 @@ path = "src/scripts/compute_points.rs" [dependencies] clickplanet-proto = { path = "../clickplanet-proto" } +serde = {workspace = true, features = ["derive"] } +prost.workspace = true +anyhow = "1.0" +image = { version = "0.25.5", default-features = false, features = ["png", "jpeg"] } +serde_json = "1.0" +uuid = { version = "1.11.0", features = ["v4", "serde"] } +rand = "0.8.5" +base64 = "0.22.1" +bytemuck = { version = "1.14", features = ["derive"] } +lazy_static = "1.4.0" +async-trait = "0.1.83" +futures-util = "0.3.31" + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +reqwest = { version = "0.12.9", features = ["json"] } +tokio = { version = "1.42.0", features = ["sync", "rt", "time", "macros", "io-util", "net"] } +tokio-tungstenite = "0.26.1" +wgpu = { version = "25.0.0", features = ["wgsl"], default-features = true } + +[target.'cfg(target_arch = "wasm32")'.dependencies] +raw-window-handle = "0.6.0" wasm-bindgen = { version = "0.2.89", features = ["serde-serialize"] } web-sys = { version = "0.3", features = [ "WebSocket", "MessageEvent", "CloseEvent", "ErrorEvent", "console", @@ -26,58 +47,18 @@ web-sys = { version = "0.3", features = [ "WebGlTexture", "WebGl2RenderingContext", "Performance" ] } js-sys = "0.3" serde-wasm-bindgen = "0.6.5" -serde.workspace = true -prost.workspace = true -anyhow = "1.0" -image = { version = "0.25.5", default-features = false, features = ["png", "jpeg"] } -serde_json = "1.0" -glam = "0.30.1" -uuid = { version = "1.11.0", features = ["v4", "serde"] } -# For WebAssembly compatibility -getrandom = { version = "0.2.10", features = ["js"] } -rand = "0.8.5" -base64 = "0.22.1" -# For WebAssembly, use the browser's native APIs instead of native libs -# Removing all native libs that don't work in WASM - -# Use gloo-net for HTTP requests in WASM -gloo-net = "0.6.0" - -# Use gloo for WebSockets and timers in WASM -gloo = { version = "0.11.0", features = ["net", "timers"] } - -# Ensure wasm-bindgen-futures is available for async ops wasm-bindgen-futures = "0.4.39" - -# Dioxus dependencies for UI -dioxus = { version = "0.6.2", features = ["web", "router"] } -dioxus-web = { version = "0.6.2" } -dioxus-hooks = "0.6.2" -dioxus-router = "0.6.3" -console_log = "1.0.0" -log = "0.4.21" - -wgpu = { version = "25.0.0", features = ["webgl", "webgpu", "wgsl"], default-features = false } -bytemuck = { version = "1.14", features = ["derive"] } -raw-window-handle = "0.6.0" +gloo-net = "0.6.0" +gloo-utils = { version = "0.2.0", features = ["serde"] } gloo-timers = { version = "0.3.0", features = ["futures"] } -gloo-utils = "0.2.0" gloo-console = "0.3.0" - - -# Enable/disable features based on target -[target.'cfg(not(target_arch = "wasm32"))'.dependencies] -reqwest = { version = "0.12.9", features = ["json"] } -tokio = { version = "1.42.0", features = ["sync", "rt", "time"] } -tokio-tungstenite = "0.26.1" -async-trait = "0.1.83" -futures-util = "0.3.31" +gloo-render = "0.2.0" +wgpu = { version = "25.0.0", features = ["webgl", "webgpu", "wgsl"], default-features = false } +getrandom = { version = "0.2.10", features = ["js"] } +glam = "0.30.1" +console_log = "1.0.0" dioxus = { version = "0.6.2", features = ["web", "router"] } dioxus-web = { version = "0.6.2" } dioxus-hooks = "0.6.2" dioxus-router = "0.6.3" -console_log = "1.0.0" -log = "0.4.22" -wasm-bindgen-futures = "0.4.39" -gloo-timers = "0.3.0" -lazy_static = "1.4.0" +log = "0.4.22" \ No newline at end of file diff --git a/clickplanet-webapp/src/app/components/earth/three_js/bindings.rs b/clickplanet-webapp/src/app/components/earth/three_js/bindings.rs index 761ccdb..362f05a 100644 --- a/clickplanet-webapp/src/app/components/earth/three_js/bindings.rs +++ b/clickplanet-webapp/src/app/components/earth/three_js/bindings.rs @@ -1,11 +1,15 @@ use wasm_bindgen::prelude::*; use web_sys::Element; use js_sys; +use serde::Deserialize; +use serde::Serialize; #[wasm_bindgen] +#[derive(Serialize, Deserialize)] pub struct WebGLRendererParams { - #[wasm_bindgen(skip)] - pub canvas: Option, + #[wasm_bindgen(getter_with_clone)] + #[serde(with = "serde_wasm_bindgen::preserve")] + pub canvas: web_sys::HtmlCanvasElement, pub alpha: Option, pub antialias: Option, @@ -17,9 +21,9 @@ pub struct WebGLRendererParams { #[wasm_bindgen] impl WebGLRendererParams { #[wasm_bindgen(constructor)] - pub fn new() -> Self { + pub fn new(canvas: &web_sys::HtmlCanvasElement) -> Self { Self { - canvas: None, + canvas: canvas.clone(), alpha: None, antialias: None, depth: None, @@ -29,7 +33,7 @@ impl WebGLRendererParams { } pub fn set_canvas(&mut self, canvas: &web_sys::HtmlCanvasElement) { - self.canvas = Some(canvas.clone()); + self.canvas = canvas.clone(); } pub fn set_alpha(&mut self, alpha: bool) { @@ -53,45 +57,6 @@ impl WebGLRendererParams { } } -impl From<&WebGLRendererParams> for JsValue { - fn from(params: &WebGLRendererParams) -> Self { - let obj = js_sys::Object::new(); - - if let Some(canvas) = ¶ms.canvas { - let _ = js_sys::Reflect::set(&obj, &JsValue::from_str("canvas"), canvas); - } - - if let Some(alpha) = params.alpha { - let _ = js_sys::Reflect::set(&obj, &JsValue::from_str("alpha"), &JsValue::from_bool(alpha)); - } - - if let Some(antialias) = params.antialias { - let _ = js_sys::Reflect::set(&obj, &JsValue::from_str("antialias"), &JsValue::from_bool(antialias)); - } - - if let Some(depth) = params.depth { - let _ = js_sys::Reflect::set(&obj, &JsValue::from_str("depth"), &JsValue::from_bool(depth)); - } - - if let Some(premultiplied_alpha) = params.premultiplied_alpha { - let _ = js_sys::Reflect::set( - &obj, - &JsValue::from_str("premultipliedAlpha"), - &JsValue::from_bool(premultiplied_alpha) - ); - } - - if let Some(preserve_drawing_buffer) = params.preserve_drawing_buffer { - let _ = js_sys::Reflect::set( - &obj, - &JsValue::from_str("preserveDrawingBuffer"), - &JsValue::from_bool(preserve_drawing_buffer) - ); - } - - obj.into() - } -} #[wasm_bindgen] pub struct MeshBasicMaterialParams { diff --git a/clickplanet-webapp/src/app/components/earth/three_js/globe.rs b/clickplanet-webapp/src/app/components/earth/three_js/globe.rs index 9259f35..7916708 100644 --- a/clickplanet-webapp/src/app/components/earth/three_js/globe.rs +++ b/clickplanet-webapp/src/app/components/earth/three_js/globe.rs @@ -2,7 +2,7 @@ use wasm_bindgen::prelude::*; use web_sys::HtmlCanvasElement; use gloo_utils::window; use std::cell::RefCell; -use gloo::render::AnimationFrame; +use gloo_render::AnimationFrame; use gloo_console; use log; @@ -88,12 +88,11 @@ pub fn init_globe(canvas: &HtmlCanvasElement) -> Result<(), JsError> { let position = camera.position(); position.set_z(5.0); - let mut renderer_params = WebGLRendererParams::new(); - renderer_params.set_canvas(&canvas); + let mut renderer_params = WebGLRendererParams::new(&canvas); renderer_params.set_antialias(true); - let js_params: JsValue = JsValue::from(&renderer_params); - + let js_params = serde_wasm_bindgen::to_value(&renderer_params).unwrap(); + let renderer: WebGLRenderer = WebGLRenderer::new_with_parameters(&js_params); renderer.set_size(width, height); renderer.set_clear_color(0x000000); From 18c2c62e0c9bad0f370dd668f2dc64aa3cf8bc0f Mon Sep 17 00:00:00 2001 From: Laurent Valdes Date: Thu, 8 May 2025 16:57:02 +0200 Subject: [PATCH 16/28] fix: match orbit and planet rotation behavior with original frontend --- .../app/components/earth/three_js/bindings.rs | 160 +++++++++++++----- .../app/components/earth/three_js/globe.rs | 154 +++++++---------- 2 files changed, 179 insertions(+), 135 deletions(-) diff --git a/clickplanet-webapp/src/app/components/earth/three_js/bindings.rs b/clickplanet-webapp/src/app/components/earth/three_js/bindings.rs index 362f05a..75874dd 100644 --- a/clickplanet-webapp/src/app/components/earth/three_js/bindings.rs +++ b/clickplanet-webapp/src/app/components/earth/three_js/bindings.rs @@ -59,6 +59,7 @@ impl WebGLRendererParams { #[wasm_bindgen] +#[derive(Serialize, Deserialize)] pub struct MeshBasicMaterialParams { pub color: Option, pub wireframe: Option, @@ -67,7 +68,20 @@ pub struct MeshBasicMaterialParams { } #[wasm_bindgen] -impl MeshBasicMaterialParams { +#[derive(Serialize, Deserialize)] +pub struct MeshStandardMaterialParams { + pub color: Option, + pub wireframe: Option, + pub transparent: Option, + pub opacity: Option, + pub roughness: Option, + pub metalness: Option, + pub emissive: Option, + pub side: Option, +} + +#[wasm_bindgen] +impl MeshStandardMaterialParams { #[wasm_bindgen(constructor)] pub fn new() -> Self { Self { @@ -75,6 +89,10 @@ impl MeshBasicMaterialParams { wireframe: None, transparent: None, opacity: None, + roughness: None, + metalness: None, + emissive: None, + side: None, } } @@ -93,34 +111,56 @@ impl MeshBasicMaterialParams { pub fn set_opacity(&mut self, opacity: f64) { self.opacity = Some(opacity); } + + pub fn set_roughness(&mut self, roughness: f64) { + self.roughness = Some(roughness); + } + + pub fn set_metalness(&mut self, metalness: f64) { + self.metalness = Some(metalness); + } + + pub fn set_emissive(&mut self, emissive: u32) { + self.emissive = Some(emissive); + } + + pub fn set_side(&mut self, side: u32) { + self.side = Some(side); + } } -impl From<&MeshBasicMaterialParams> for JsValue { - fn from(params: &MeshBasicMaterialParams) -> Self { - let obj = js_sys::Object::new(); - - if let Some(color) = params.color { - let _ = js_sys::Reflect::set(&obj, &JsValue::from_str("color"), &JsValue::from_f64(color as f64)); - } - - if let Some(wireframe) = params.wireframe { - let _ = js_sys::Reflect::set(&obj, &JsValue::from_str("wireframe"), &JsValue::from_bool(wireframe)); - } - - if let Some(transparent) = params.transparent { - let _ = js_sys::Reflect::set(&obj, &JsValue::from_str("transparent"), &JsValue::from_bool(transparent)); - } - - if let Some(opacity) = params.opacity { - let _ = js_sys::Reflect::set(&obj, &JsValue::from_str("opacity"), &JsValue::from_f64(opacity)); +#[wasm_bindgen] +impl MeshBasicMaterialParams { + #[wasm_bindgen(constructor)] + pub fn new() -> Self { + Self { + color: None, + wireframe: None, + transparent: None, + opacity: None, } - - obj.into() + } + + pub fn set_color(&mut self, color: u32) { + self.color = Some(color); + } + + pub fn set_wireframe(&mut self, wireframe: bool) { + self.wireframe = Some(wireframe); + } + + pub fn set_transparent(&mut self, transparent: bool) { + self.transparent = Some(transparent); + } + + pub fn set_opacity(&mut self, opacity: f64) { + self.opacity = Some(opacity); } } + #[wasm_bindgen] -extern "C" { +unsafe extern "C" { // Main Three.js namespace #[wasm_bindgen(js_namespace = THREE)] pub type Scene; @@ -150,7 +190,7 @@ extern "C" { pub fn new() -> WebGLRenderer; #[wasm_bindgen(constructor, js_namespace = THREE)] - pub fn new_with_parameters(params: &JsValue) -> WebGLRenderer; + pub fn new_with_parameters(params:WebGLRendererParams) -> WebGLRenderer; #[wasm_bindgen(method, js_namespace = THREE, js_name = setSize)] pub fn set_size(this: &WebGLRenderer, width: f64, height: f64); @@ -158,8 +198,8 @@ extern "C" { #[wasm_bindgen(method, js_namespace = THREE, js_name = setClearColor)] pub fn set_clear_color(this: &WebGLRenderer, color: u32); - #[wasm_bindgen(method, getter, js_namespace = THREE)] - pub fn domElement(this: &WebGLRenderer) -> Element; + #[wasm_bindgen(method, getter, js_namespace = THREE, js_name = domElement)] + pub fn dom_element(this: &WebGLRenderer) -> Element; // Generic render method that can handle any camera type by using JsValue #[wasm_bindgen(method, js_namespace = THREE, js_name = render)] @@ -211,40 +251,45 @@ extern "C" { #[wasm_bindgen(constructor, js_namespace = THREE)] pub fn new(color: u32, intensity: f64) -> AmbientLight; - // Base BufferGeometry type #[wasm_bindgen(js_namespace = THREE)] pub type BufferGeometry; - // BoxGeometry extends BufferGeometry - #[wasm_bindgen(js_namespace = THREE)] + #[wasm_bindgen(js_namespace = THREE, extends = BufferGeometry)] pub type BoxGeometry; #[wasm_bindgen(constructor, js_namespace = THREE)] pub fn new(width: f64, height: f64, depth: f64) -> BoxGeometry; - #[wasm_bindgen(js_namespace = THREE)] + #[wasm_bindgen(js_namespace = THREE, extends = BufferGeometry)] + pub type PolyhedronGeometry; + + #[wasm_bindgen(js_namespace = THREE, extends = PolyhedronGeometry, extends = BufferGeometry)] pub type IcosahedronGeometry; #[wasm_bindgen(constructor, js_namespace = THREE)] pub fn new(radius: f64, detail: u32) -> IcosahedronGeometry; - // Base Material type #[wasm_bindgen(js_namespace = THREE)] pub type Material; - // MeshBasicMaterial extends Material - #[wasm_bindgen(js_namespace = THREE)] + #[wasm_bindgen(js_namespace = THREE, extends = Material)] pub type MeshBasicMaterial; #[wasm_bindgen(constructor, js_namespace = THREE)] - pub fn new_with_params(params: &JsValue) -> MeshBasicMaterial; + pub fn new_with_params(params: MeshBasicMaterialParams) -> MeshBasicMaterial; - #[wasm_bindgen(js_namespace = THREE)] + #[wasm_bindgen(js_namespace = THREE, extends = Material)] pub type MeshStandardMaterial; #[wasm_bindgen(constructor, js_namespace = THREE)] - pub fn new_with_params(params: &JsValue) -> MeshStandardMaterial; - + pub fn new_with_params(params: MeshStandardMaterialParams) -> MeshStandardMaterial; + + #[wasm_bindgen(method, setter, js_namespace = THREE)] + pub fn set_map(this: &MeshStandardMaterial, map: &Texture); + + #[wasm_bindgen(method, setter, js_namespace = THREE, js_name = needsUpdate)] + pub fn set_needs_update(this: &MeshStandardMaterial, needs_update: bool); + #[wasm_bindgen(js_namespace = THREE)] pub type Texture; @@ -392,25 +437,54 @@ extern "C" { #[wasm_bindgen(method)] pub fn update(this: &OrbitControls); - #[wasm_bindgen(method, setter)] + // Min zoom getter/setter + #[wasm_bindgen(method, getter, js_name = "minZoom")] + pub fn min_zoom(this: &OrbitControls) -> f64; + + #[wasm_bindgen(method, setter, js_name = "minZoom")] pub fn set_min_zoom(this: &OrbitControls, min_zoom: f64); - #[wasm_bindgen(method, setter)] + #[wasm_bindgen(method, getter, js_name = "maxZoom")] + pub fn max_zoom(this: &OrbitControls) -> f64; + + #[wasm_bindgen(method, setter, js_name = "maxZoom")] pub fn set_max_zoom(this: &OrbitControls, max_zoom: f64); - #[wasm_bindgen(method, setter)] + // Pan speed getter/setter + #[wasm_bindgen(method, getter, js_name = "panSpeed")] + pub fn pan_speed(this: &OrbitControls) -> f64; + + #[wasm_bindgen(method, setter, js_name = "panSpeed")] pub fn set_pan_speed(this: &OrbitControls, speed: f64); - #[wasm_bindgen(method, setter)] + #[wasm_bindgen(method, getter, js_name = "zoomSpeed")] + pub fn zoom_speed(this: &OrbitControls) -> f64; + + #[wasm_bindgen(method, setter, js_name = "zoomSpeed")] + pub fn set_zoom_speed(this: &OrbitControls, speed: f64); + + #[wasm_bindgen(method, getter, js_name = "enableDamping")] + pub fn enable_damping(this: &OrbitControls) -> bool; + + #[wasm_bindgen(method, setter, js_name = "enableDamping")] pub fn set_enable_damping(this: &OrbitControls, enable: bool); - #[wasm_bindgen(method, setter)] + #[wasm_bindgen(method, getter, js_name = "autoRotate")] + pub fn auto_rotate(this: &OrbitControls) -> bool; + + #[wasm_bindgen(method, setter, js_name = "autoRotate")] pub fn set_auto_rotate(this: &OrbitControls, auto_rotate: bool); - #[wasm_bindgen(method, setter)] + #[wasm_bindgen(method, getter, js_name = "autoRotateSpeed")] + pub fn auto_rotate_speed(this: &OrbitControls) -> f64; + + #[wasm_bindgen(method, setter, js_name = "autoRotateSpeed")] pub fn set_auto_rotate_speed(this: &OrbitControls, speed: f64); - #[wasm_bindgen(method, setter)] + #[wasm_bindgen(method, getter, js_name = "rotateSpeed")] + pub fn rotate_speed(this: &OrbitControls) -> f64; + + #[wasm_bindgen(method, setter, js_name = "rotateSpeed")] pub fn set_rotate_speed(this: &OrbitControls, speed: f64); #[wasm_bindgen(method, js_name = addEventListener)] diff --git a/clickplanet-webapp/src/app/components/earth/three_js/globe.rs b/clickplanet-webapp/src/app/components/earth/three_js/globe.rs index 7916708..25a2bf0 100644 --- a/clickplanet-webapp/src/app/components/earth/three_js/globe.rs +++ b/clickplanet-webapp/src/app/components/earth/three_js/globe.rs @@ -17,6 +17,7 @@ struct ThreeJsGlobeState { controls: Option, animation_id: Option, resize_callback: Option>, + control_callback: Option>, animation_callback: Option>, texture_callback: Option>, error_callback: Option>, @@ -35,6 +36,7 @@ thread_local! { earth_material: None, texture_callback: None, error_callback: None, + control_callback: None }); } @@ -45,23 +47,7 @@ pub fn init_globe(canvas: &HtmlCanvasElement) -> Result<(), JsError> { let static_site = env!("CITYWARS_STATIC_SITE"); let window = window(); - let diagnostic_result = super::bindings::diagnose_three_js_loading(); - gloo_console::log!("THREE diagnostics: {}", diagnostic_result); - - let three_available = js_sys::Reflect::has(&window, &JsValue::from_str("THREE")) - .map_err(|_| JsError::new("Failed to check for THREE global object"))?; - - if !three_available { - return Err(JsError::new("THREE global object not found. Make sure Three.js is loaded properly.")); - } - - js_sys::Reflect::set( - &window, - &JsValue::from_str("CITYWARS_STATIC_SITE"), - &JsValue::from_str(static_site) - ).map_err(|_| JsError::new("Failed to set static site URL"))?; - - let scene = Scene::new(); + let scene: Scene = Scene::new(); let width = window.inner_width() .map_err(|_| JsError::new("Failed to get window width"))? @@ -76,7 +62,7 @@ pub fn init_globe(canvas: &HtmlCanvasElement) -> Result<(), JsError> { let aspect = width / height; let camera_size = 1.0; - let camera = OrthographicCamera::new( + let camera: OrthographicCamera = OrthographicCamera::new( -camera_size * aspect, camera_size * aspect, camera_size, @@ -88,31 +74,22 @@ pub fn init_globe(canvas: &HtmlCanvasElement) -> Result<(), JsError> { let position = camera.position(); position.set_z(5.0); - let mut renderer_params = WebGLRendererParams::new(&canvas); + let mut renderer_params: WebGLRendererParams = WebGLRendererParams::new(&canvas); renderer_params.set_antialias(true); - - let js_params = serde_wasm_bindgen::to_value(&renderer_params).unwrap(); - let renderer: WebGLRenderer = WebGLRenderer::new_with_parameters(&js_params); + let renderer: WebGLRenderer = WebGLRenderer::new_with_parameters(renderer_params); renderer.set_size(width, height); renderer.set_clear_color(0x000000); scene.add(&AmbientLight::new(0xffffff, 2.0)); - let earth_geometry = IcosahedronGeometry::new(0.999, 50); - - let material_params = js_sys::Object::new(); - js_sys::Reflect::set(&material_params, &JsValue::from_str("color"), &JsValue::from_f64(0xFFFFFF as f64)) - .expect("Failed to set material color"); - - let earth_material = MeshStandardMaterial::new_with_params(&material_params); + let earth_geometry: IcosahedronGeometry = IcosahedronGeometry::new(0.999, 50); - let earth_geometry_js: &JsValue = earth_geometry.as_ref(); - let earth_geometry_as_buffer: &BufferGeometry = earth_geometry_js.unchecked_ref(); + let mut material_params = MeshStandardMaterialParams::new(); + material_params.set_color(0xFFFFFF); - let earth_material_js: &JsValue = earth_material.as_ref(); - let earth_material_as_material: &Material = earth_material_js.unchecked_ref(); + let earth_material: MeshStandardMaterial = MeshStandardMaterial::new_with_params(material_params); - let earth_mesh = Mesh::new_with_geometry_material(earth_geometry_as_buffer, earth_material_as_material); + let earth_mesh = Mesh::new_with_geometry_material(earth_geometry.as_ref(), earth_material.as_ref()); scene.add(&earth_mesh); @@ -129,11 +106,8 @@ pub fn init_globe(canvas: &HtmlCanvasElement) -> Result<(), JsError> { STATE.with(|state_ref| { let state = state_ref.borrow(); if let Some(material) = &state.earth_material { - js_sys::Reflect::set(material.as_ref(), &JsValue::from_str("map"), &texture) - .expect("Failed to set texture map"); - - js_sys::Reflect::set(material.as_ref(), &JsValue::from_str("needsUpdate"), &JsValue::from_bool(true)) - .expect("Failed to set needsUpdate"); + material.set_map(&texture); + material.set_needs_update(true); } }); }) as Box); @@ -172,6 +146,11 @@ pub fn init_globe(canvas: &HtmlCanvasElement) -> Result<(), JsError> { let animate_callback = Closure::wrap(Box::new(|_timestamp: f64| { STATE.with(|state_ref| { let state = state_ref.borrow(); + + if let Some(controls) = &state.controls { + controls.update(); + } + if let (Some(scene), Some(camera), Some(renderer)) = (&state.scene, &state.camera, &state.renderer) { renderer.render(scene, camera); } @@ -188,6 +167,31 @@ pub fn init_globe(canvas: &HtmlCanvasElement) -> Result<(), JsError> { } }) as Box); + let control_change_callback = Closure::wrap(Box::new(|| { + STATE.with(|state_ref| { + let state = state_ref.borrow(); + if let (Some(camera), Some(controls)) = (&state.camera, &state.controls) { + let zoom = camera.zoom(); + let should_auto_rotate = zoom == 1.0; + controls.set_auto_rotate(should_auto_rotate); + + let rotate_speed = (1.0 / zoom) / 1.5; + controls.set_rotate_speed(rotate_speed); + } else { + gloo_console::warn!("Control change called but camera or controls are None"); + if state.camera.is_none() { + gloo_console::warn!("Camera is None"); + } + if state.controls.is_none() { + gloo_console::warn!("Controls is None"); + } + } + + if let (Some(scene), Some(camera), Some(renderer)) = (&state.scene, &state.camera, &state.renderer) { + renderer.render(scene, camera); + } + }); + }) as Box); let on_load_js_ref = on_load_callback.as_ref().unchecked_ref(); let on_error_js_ref = on_error_callback.as_ref().unchecked_ref(); @@ -199,85 +203,50 @@ pub fn init_globe(canvas: &HtmlCanvasElement) -> Result<(), JsError> { on_error_js_ref ); + let controls = OrbitControls::new(&camera, &renderer.dom_element()); + controls.set_min_zoom(1.0); + controls.set_max_zoom(50.0); + controls.set_pan_speed(0.1); + controls.set_enable_damping(true); + controls.set_auto_rotate(true); + controls.set_rotate_speed(1.0 / 1.5); + let resize_js_ref = resize_callback.as_ref().unchecked_ref(); window.add_event_listener_with_callback("resize", resize_js_ref) .map_err(|_| JsError::new("Failed to add resize event listener"))?; + if let Some(window) = web_sys::window() { let callback_js_ref = animate_callback.as_ref().unchecked_ref(); let _ = window.request_animation_frame(callback_js_ref); } + controls.add_event_listener("change", &control_change_callback); + STATE.with(|state_ref| { let mut state = state_ref.borrow_mut(); - state.texture_callback = Some(on_load_callback); - state.error_callback = Some(on_error_callback); - state.resize_callback = Some(resize_callback); - state.animation_callback = Some(animate_callback); + state.controls = Some(controls); }); - // Make iitial render renderer.render(&scene, &camera); STATE.with(|state_ref| { let mut state = state_ref.borrow_mut(); + state.texture_callback = Some(on_load_callback); + state.error_callback = Some(on_error_callback); + state.resize_callback = Some(resize_callback); + state.animation_callback = Some(animate_callback); + state.control_callback = Some(control_change_callback); state.scene = Some(scene); state.camera = Some(camera); state.renderer = Some(renderer); state.earth_mesh = Some(earth_mesh); - // state.controls = None; // Orbit controls are disabled }); - - - /* - // Set up orbit controls similar to the original frontend - let controls = OrbitControls::new(&camera, &renderer.domElement()); - controls.set_min_zoom(1.0); - controls.set_max_zoom(50.0); - controls.set_pan_speed(0.1); - controls.set_zoom_speed(0.5); - controls.set_enable_damping(true); - controls.set_auto_rotate(true); - controls.set_rotate_speed(1.0 / 1.5); - */ - - // COMMENTED OUT: Control change callback - /* - // Create a callback that works with controls via STATE rather than direct capture - let control_change_callback = Closure::wrap(Box::new(|| { - STATE.with(|state_ref| { - let state = state_ref.borrow(); - if let (Some(scene), Some(camera), Some(renderer)) = (&state.scene, &state.camera, &state.renderer) { - renderer.render(scene, camera); - } - }); - }) as Box); - */ - - // Simple empty callback for now - //let control_change_callback = Closure::wrap(Box::new(|| {}) as Box); - - // Get a reference to controls from STATE to add the event listener - /*STATE.with(|state_ref| { - let state = state_ref.borrow(); - if let Some(_controls) = &state.controls { - // controls.add_event_listener("change", &control_change_callback); - } - });*/ - - // Store the callback so it doesn't get dropped - /*STATE.with(|state_ref| { - let mut state = state_ref.borrow_mut(); - state.callbacks.push(control_change_callback); - });*/ - - // No need for another render call here, already rendered above - + log::info!("Three.js Earth globe initialized"); Ok(()) } -/// Clean up Three.js resources pub fn cleanup_globe() { STATE.with(|state_ref| { let mut state = state_ref.borrow_mut(); @@ -297,6 +266,7 @@ pub fn cleanup_globe() { state.texture_callback = None; state.error_callback = None; state.earth_material = None; + state.control_callback = None; }); } From 08f1ffbb3b2bb4c01a0396baa0c8fa909d0b5943 Mon Sep 17 00:00:00 2001 From: Laurent Valdes Date: Thu, 8 May 2025 17:08:00 +0200 Subject: [PATCH 17/28] chore: cleanup Dioxus config and html title --- clickplanet-webapp/Dioxus.toml | 7 +------ clickplanet-webapp/index.html | 2 +- 2 files changed, 2 insertions(+), 7 deletions(-) diff --git a/clickplanet-webapp/Dioxus.toml b/clickplanet-webapp/Dioxus.toml index 8a71c0e..d32614b 100644 --- a/clickplanet-webapp/Dioxus.toml +++ b/clickplanet-webapp/Dioxus.toml @@ -1,13 +1,8 @@ [application] - name = "clickplanet" [web.app] - -# HTML title tag content -title = "clickplanet" - -# include `assets` in web platform +title = "ClickPlanet" script = [] [web.resource] diff --git a/clickplanet-webapp/index.html b/clickplanet-webapp/index.html index f628893..38669e2 100644 --- a/clickplanet-webapp/index.html +++ b/clickplanet-webapp/index.html @@ -3,8 +3,8 @@ + - ClickPlanet From 5e21c2bbe5a733e5b739487bc6921307708344c0 Mon Sep 17 00:00:00 2001 From: Laurent Valdes Date: Thu, 8 May 2025 18:33:24 +0200 Subject: [PATCH 18/28] refactor: implement repository pattern for country management - Remove CountriesMap in favor of plain HashMap - Move all country-related logic to CountryRepository - Update settings component to use repository pattern - Remove JsValue conversions in favor of plain Rust types - Simplify error handling with String errors --- .../src/app/components/settings.rs | 46 ++++++----- clickplanet-webapp/src/app/countries.rs | 79 ++++++++++--------- clickplanet-webapp/src/main.rs | 9 +-- 3 files changed, 67 insertions(+), 67 deletions(-) diff --git a/clickplanet-webapp/src/app/components/settings.rs b/clickplanet-webapp/src/app/components/settings.rs index 4e03f4f..62e7455 100644 --- a/clickplanet-webapp/src/app/components/settings.rs +++ b/clickplanet-webapp/src/app/components/settings.rs @@ -2,7 +2,7 @@ use dioxus::prelude::*; use crate::app::components::modal_manager::ModalManager; use crate::app::components::select_with_search::{SelectWithSearch, Value as CountryValue}; use crate::app::components::block_button::BlockButtonProps; -use crate::app::countries::Country; +use crate::app::countries::{Country, CountryRepository}; #[derive(Props, PartialEq, Clone)] pub struct SettingsProps { @@ -10,35 +10,39 @@ pub struct SettingsProps { pub set_country: Callback, } -/// Settings component for controlling country selection #[component] pub fn Settings(props: SettingsProps) -> Element { - let country = props.country.clone(); + let selected_country = CountryValue { + code: props.country.code.clone(), + name: props.country.name.clone(), + }; - // Callback to handle country selection let on_change = move |selected_country: CountryValue| { let new_country = Country { name: selected_country.name, code: selected_country.code, }; + if let Ok(_) = CountryRepository::save_selected(&new_country) { + gloo_console::info!("Saved country selection to localStorage", &serde_wasm_bindgen::to_value(&new_country).unwrap()); + } props.set_country.call(new_country); }; - // Convert country to CountryValue for SelectWithSearch - let selected_country = CountryValue { - code: country.code.clone(), - name: country.name.clone(), - }; + let mut countries = use_signal(Vec::new); - // Create a list of available countries - // In a full implementation, this would be populated from the API - let available_countries = vec![ - CountryValue { code: "us".to_string(), name: "United States".to_string() }, - CountryValue { code: "fr".to_string(), name: "France".to_string() }, - CountryValue { code: "de".to_string(), name: "Germany".to_string() }, - CountryValue { code: "jp".to_string(), name: "Japan".to_string() }, - CountryValue { code: "gb".to_string(), name: "United Kingdom".to_string() }, - ]; + use_future(move || async move { + if let Ok(countries_map) = CountryRepository::load_all().await { + let loaded_countries: Vec = countries_map + .into_iter() + .map(|(code, country)| CountryValue { + code, + name: country.name, + }) + .collect(); + log::debug!("Setting {} countries", loaded_countries.len()); + countries.set(loaded_countries); + } + }); rsx! { ModalManager { @@ -46,8 +50,8 @@ pub fn Settings(props: SettingsProps) -> Element { modal_title: "Country".to_string(), button_props: BlockButtonProps { on_click: Callback::new(|_| {}), - text: country.name.clone(), - image_url: format!("{}/countries/svg/{}.svg", env!("CITYWARS_STATIC_SITE"), country.code.to_lowercase()), + text: props.country.name.clone(), + image_url: None, class_name: Some("button-settings".to_string()), }, close_button_text: None, @@ -56,7 +60,7 @@ pub fn Settings(props: SettingsProps) -> Element { SelectWithSearch { on_change: on_change, selected: selected_country, - values: available_countries, + values: countries.read().to_vec(), } } }, diff --git a/clickplanet-webapp/src/app/countries.rs b/clickplanet-webapp/src/app/countries.rs index 4d8f395..9711dfa 100644 --- a/clickplanet-webapp/src/app/countries.rs +++ b/clickplanet-webapp/src/app/countries.rs @@ -1,59 +1,60 @@ use serde::{Deserialize, Serialize}; use std::collections::HashMap; -use wasm_bindgen::prelude::*; +use gloo_storage::{LocalStorage, Storage}; +use gloo_net::http::Request; +/// Country data structure #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct Country { pub name: String, pub code: String, } -#[wasm_bindgen] -pub struct CountriesMap { - countries: HashMap, -} - -#[wasm_bindgen] -impl CountriesMap { - #[wasm_bindgen(constructor)] - pub fn new(data: JsValue) -> CountriesMap { - let countries_data: HashMap = serde_wasm_bindgen::from_value(data) - .map_err(|e| js_sys::Error::new(&e.to_string())) - .unwrap_throw(); - - let countries: HashMap = countries_data - .into_iter() - .map(|(code, name)| { - (code.clone(), Country { - name, - code, - }) - }) - .collect(); +const STORAGE_KEY: &str = "clickplanet-country"; - CountriesMap { countries } - } +/// Country repository +pub struct CountryRepository; - pub fn get(&self, code: &str) -> JsValue { - match self.countries.get(code) { - Some(country) => serde_wasm_bindgen::to_value(country).unwrap(), - None => JsValue::null(), +impl CountryRepository { + pub fn default_country() -> Country { + Country { + name: String::from("🇺🇸 United States"), + code: String::from("us"), } } - pub fn contains_key(&self, code: &str) -> bool { - self.countries.contains_key(code) - } - - pub fn keys(&self) -> Vec { - self.countries.keys().cloned().collect() + pub fn load_selected() -> Country { + LocalStorage::get(STORAGE_KEY).unwrap_or_else(|_| Self::default_country()) } - pub fn len(&self) -> usize { - self.countries.len() + pub fn save_selected(country: &Country) -> Result<(), String> { + LocalStorage::set(STORAGE_KEY, country) + .map_err(|e| e.to_string()) } - pub fn is_empty(&self) -> bool { - self.countries.is_empty() + pub async fn load_all() -> Result, String> { + let static_site = env!("CITYWARS_STATIC_SITE"); + let url = format!("{}/countries/countries.json", static_site); + + let resp = Request::get(&url) + .send() + .await + .map_err(|e| e.to_string())?; + + let countries_data: HashMap = resp.json() + .await + .map_err(|e| e.to_string())?; + + log::debug!("Loaded {} countries", countries_data.len()); + + Ok(countries_data + .into_iter() + .map(|(code, name)| { + (code.clone(), Country { + name, + code, + }) + }) + .collect()) } } \ No newline at end of file diff --git a/clickplanet-webapp/src/main.rs b/clickplanet-webapp/src/main.rs index 2d4015e..93bf328 100644 --- a/clickplanet-webapp/src/main.rs +++ b/clickplanet-webapp/src/main.rs @@ -1,6 +1,6 @@ use dioxus::prelude::*; use dioxus::document::Stylesheet; -use crate::app::countries::Country; +use crate::app::countries::{Country, CountryRepository}; mod app; mod backends; @@ -62,13 +62,8 @@ fn App() -> Element { fn Home() -> Element { let mut show_welcome_modal = use_signal(|| true); - // Manage country state here, similar to the original TypeScript implementation - let mut country = use_signal(|| Country { - name: "United States".to_string(), - code: "us".to_string(), - }); + let mut country = use_signal(|| CountryRepository::load_selected()); - // Callback to update country let set_country = move |new_country: Country| { country.set(new_country); }; From af195dd0852e561cd11a93b4c0128da99a78b4df Mon Sep 17 00:00:00 2001 From: Laurent Valdes Date: Thu, 8 May 2025 18:47:59 +0200 Subject: [PATCH 19/28] style: adjust button padding - Remove default padding from base button class - Add specific padding for about button --- clickplanet-webapp/public/styles/base.css | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/clickplanet-webapp/public/styles/base.css b/clickplanet-webapp/public/styles/base.css index 8b7880a..2370679 100644 --- a/clickplanet-webapp/public/styles/base.css +++ b/clickplanet-webapp/public/styles/base.css @@ -69,7 +69,6 @@ table { } .button { - padding: 18px; color: white; background: transparent; cursor: pointer; @@ -81,6 +80,10 @@ table { font-family: "Luckiest Guy", sans-serif; } +.button-about { + padding: 8px; +} + .button:hover { background: #FFFFFF25; transition: 0.125s ease; From 1397cf99f4173547d6d75c6a3bb23462181633c7 Mon Sep 17 00:00:00 2001 From: Laurent Valdes Date: Thu, 8 May 2025 18:52:21 +0200 Subject: [PATCH 20/28] refactor: clean up codebase and improve components - Update BlockButton to use Option for image_url - Remove unused viewer module - Clean up comments and code formatting - Add gloo-storage dependency - Update devcontainer configuration - Remove duplicate code in windsurfrules - Improve SelectWithSearch component --- .devcontainer/.devcontainer.json | 11 ------ .devcontainer/devcontainer.json | 37 +++++++++++++++++++ .windsurfrules | 9 +++-- Cargo.lock | 16 ++++++++ clickplanet-webapp/Cargo.toml | 1 + .../src/app/components/about.rs | 2 +- .../src/app/components/block_button.rs | 8 ++-- .../src/app/components/select_with_search.rs | 7 ++-- clickplanet-webapp/src/app/mod.rs | 3 +- clickplanet-webapp/src/main.rs | 6 --- 10 files changed, 69 insertions(+), 31 deletions(-) delete mode 100644 .devcontainer/.devcontainer.json create mode 100644 .devcontainer/devcontainer.json diff --git a/.devcontainer/.devcontainer.json b/.devcontainer/.devcontainer.json deleted file mode 100644 index 47b7061..0000000 --- a/.devcontainer/.devcontainer.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "Rust Development Environment", - "image": "mcr.microsoft.com/devcontainers/rust:latest", - "customizations": { - "vscode": { - "extensions": [ - "rust-lang.rust-analyzer" - ] - } - } -} \ No newline at end of file diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000..783a7cb --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,37 @@ +// For format details, see https://aka.ms/devcontainer.json. For config options, see the +// README at: https://github.com/devcontainers/templates/tree/main/src/rust +{ + "name": "Rust", + // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile + "image": "mcr.microsoft.com/devcontainers/rust:1-1-bullseye", + + // Use 'mounts' to make the cargo cache persistent in a Docker Volume. + // "mounts": [ + // { + // "source": "devcontainer-cargo-cache-${devcontainerId}", + // "target": "/usr/local/cargo", + // "type": "volume" + // } + // ] + + // Features to add to the dev container. More info: https://containers.dev/features. + "features": { + "ghcr.io/devcontainers/features/git:1": {}, + "ghcr.io/devcontainers/features/python:1": {}, + "ghcr.io/devcontainers-extra/features/sbt-sdkman:2": {}, + "ghcr.io/devcontainers-extra/features/spark-sdkman:2": {}, + "ghcr.io/devcontainers-extra/features/protoc:1": {} + } + + // Use 'forwardPorts' to make a list of ports inside the container available locally. + // "forwardPorts": [], + + // Use 'postCreateCommand' to run commands after the container is created. + // "postCreateCommand": "rustc --version", + + // Configure tool-specific properties. + // "customizations": {}, + + // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root. + // "remoteUser": "root" +} diff --git a/.windsurfrules b/.windsurfrules index ec4656a..9db270d 100644 --- a/.windsurfrules +++ b/.windsurfrules @@ -41,7 +41,6 @@ And finally: Always use the edit tool. If it does not work, read the file first Make sure we use conventional commits Do not use interactive rebase (you are an LLM). If a git MCP server does rebases, use it. -Try to use dioxus hot reload. It is does not work, instead of allocating a new port, use or kill the older dioxus instances. If it is just for building, just use cargo check or cargo compile. Do not use docker build when building locally. CITYWARS_STATIC_SITE="https://storage.googleapis.com/lv-project-313715-clickwars-static/static" is the right environnement variable to place in front of RUSTFLAGS="--cfg=web_sys_unstable_apis" cargo build --target wasm32-unknown-unknown or dx serve command. @@ -60,6 +59,10 @@ When compiling the webapp, the chain should be wasm, and not local machine one. When you launch a command use the Windsurf terminal API so that I can kill or stop a process by myself. -When downloading a caego or js or sbt dependency, check the latest one using your browser tools, before guessing. Your memory is not up to date. +When downloading a cargo or js or sbt dependency, check the latest one using your browser tools, before guessing. Your memory is not up to date. -When I say, read the public docs, or review the public docs, you have to do it and use the fucking documentation or the source code of the project. \ No newline at end of file +When I say, read the public docs, or review the public docs, you have to do it and use the fucking documentation or the source code of the project. + +Do not launch dx serve yourself. I will do it. + +Don't make JS code if you can do the same with rust and wasm. Use gloo: timers, utils, etc \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock index d24cda8..35ef364 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -946,6 +946,7 @@ dependencies = [ "gloo-console", "gloo-net", "gloo-render", + "gloo-storage", "gloo-timers", "gloo-utils", "image", @@ -2300,6 +2301,21 @@ dependencies = [ "web-sys", ] +[[package]] +name = "gloo-storage" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbc8031e8c92758af912f9bc08fbbadd3c6f3cfcbf6b64cdf3d6a81f0139277a" +dependencies = [ + "gloo-utils", + "js-sys", + "serde", + "serde_json", + "thiserror 1.0.69", + "wasm-bindgen", + "web-sys", +] + [[package]] name = "gloo-timers" version = "0.3.0" diff --git a/clickplanet-webapp/Cargo.toml b/clickplanet-webapp/Cargo.toml index bde73e4..873d040 100644 --- a/clickplanet-webapp/Cargo.toml +++ b/clickplanet-webapp/Cargo.toml @@ -49,6 +49,7 @@ js-sys = "0.3" serde-wasm-bindgen = "0.6.5" wasm-bindgen-futures = "0.4.39" gloo-net = "0.6.0" +gloo-storage = "0.3.0" gloo-utils = { version = "0.2.0", features = ["serde"] } gloo-timers = { version = "0.3.0", features = ["futures"] } gloo-console = "0.3.0" diff --git a/clickplanet-webapp/src/app/components/about.rs b/clickplanet-webapp/src/app/components/about.rs index 01297f8..bddf72a 100644 --- a/clickplanet-webapp/src/app/components/about.rs +++ b/clickplanet-webapp/src/app/components/about.rs @@ -12,7 +12,7 @@ pub fn About() -> Element { button_props: BlockButtonProps { on_click: Callback::new(|_| {}), text: "About".to_string(), - image_url: asset!("public/static/favicon.png").to_string(), + image_url: Some(asset!("public/static/favicon.png").to_string()), class_name: Some("button-about".to_string()), }, close_button_text: Some("Back".to_string()), diff --git a/clickplanet-webapp/src/app/components/block_button.rs b/clickplanet-webapp/src/app/components/block_button.rs index cdfc8bd..1550b03 100644 --- a/clickplanet-webapp/src/app/components/block_button.rs +++ b/clickplanet-webapp/src/app/components/block_button.rs @@ -4,7 +4,7 @@ use dioxus::prelude::*; pub struct BlockButtonProps { pub on_click: Callback, pub text: String, // Text to display on the button - pub image_url: String, // Optional image URL (not used in the current implementation) + pub image_url: Option, // Optional image URL (not used in the current implementation) pub class_name: Option, // Optional class name for styling } @@ -18,10 +18,10 @@ pub fn BlockButton(props: BlockButtonProps) -> Element { rsx! { button { class: class_name, - onclick: move |evt| props.on_click.call(evt), // Call the callback - if !props.image_url.is_empty() { + onclick: move |evt| props.on_click.call(evt), + if props.image_url.is_some() { img { - src: props.image_url, + src: props.image_url.expect("Image URL is required"), alt: props.text.clone(), class: "button-icon", style: "margin-right: 8px; width: 20px; height: 20px;" diff --git a/clickplanet-webapp/src/app/components/select_with_search.rs b/clickplanet-webapp/src/app/components/select_with_search.rs index 429e691..a0a3b73 100644 --- a/clickplanet-webapp/src/app/components/select_with_search.rs +++ b/clickplanet-webapp/src/app/components/select_with_search.rs @@ -27,7 +27,7 @@ fn get_flag_emoji(country_code: &str) -> String { .collect() } -#[derive(PartialEq, Clone)] +#[derive(PartialEq, Clone, Debug, serde::Serialize)] pub struct Value { pub code: String, pub name: String, @@ -84,8 +84,7 @@ pub fn SelectWithSearch(props: SelectWithSearchProps) -> Element { size: "5", {filtered_options.into_iter().map(|v| { let value = v.clone(); - // Format the display text with flag emoji outside the RSX macro - let display_text = format!("{} {}", get_flag_emoji(&v.code), v.name); + let display_text = v.name; rsx!( option { @@ -94,7 +93,7 @@ pub fn SelectWithSearch(props: SelectWithSearchProps) -> Element { selected.set(value.clone()); props.on_change.call(value.clone()); }, - key: "{v.code}", // Unique key for each option + key: "{v.code}", value: "{v.code}", "{display_text}" } diff --git a/clickplanet-webapp/src/app/mod.rs b/clickplanet-webapp/src/app/mod.rs index 685b638..db247ae 100644 --- a/clickplanet-webapp/src/app/mod.rs +++ b/clickplanet-webapp/src/app/mod.rs @@ -1,3 +1,2 @@ pub mod components; -pub mod countries; -pub mod viewer; +pub mod countries; \ No newline at end of file diff --git a/clickplanet-webapp/src/main.rs b/clickplanet-webapp/src/main.rs index 93bf328..de95e4b 100644 --- a/clickplanet-webapp/src/main.rs +++ b/clickplanet-webapp/src/main.rs @@ -11,19 +11,15 @@ fn main() { launch(App); } -// Define app routes with Routable trait #[derive(Routable, Clone, PartialEq)] enum Route { #[route("/")] Home {}, - - // Fallback route for when no other routes match #[route("/:..segments")] NotFound { segments: Vec }, } -// Root app component that sets up the router #[allow(non_snake_case)] fn App() -> Element { let import_map = r#"{ @@ -57,7 +53,6 @@ fn App() -> Element { } } -// Home component with the globe and main UI #[component] fn Home() -> Element { let mut show_welcome_modal = use_signal(|| true); @@ -132,7 +127,6 @@ fn About() -> Element { } -// 404 Not Found component #[component] fn NotFound(segments: Vec) -> Element { let url_path = if segments.is_empty() { From 88d90a3ddc5681178d026b740147229cea907d1f Mon Sep 17 00:00:00 2001 From: Laurent Valdes Date: Thu, 8 May 2025 18:52:43 +0200 Subject: [PATCH 21/28] refactor: remove unused viewer module --- clickplanet-webapp/src/app/viewer.rs | 13 ------------- 1 file changed, 13 deletions(-) delete mode 100644 clickplanet-webapp/src/app/viewer.rs diff --git a/clickplanet-webapp/src/app/viewer.rs b/clickplanet-webapp/src/app/viewer.rs deleted file mode 100644 index 2dad933..0000000 --- a/clickplanet-webapp/src/app/viewer.rs +++ /dev/null @@ -1,13 +0,0 @@ -// Placeholder for the viewer module -// This will be implemented later as part of the globe visualization enhancements - -use dioxus::prelude::*; - -#[component] -pub fn Viewer() -> Element { - rsx! { - div { class: "viewer-container", - "Viewer component will be implemented here" - } - } -} From 9d10becfffa15d26f2d73f84fe12d4ebcef5fc68 Mon Sep 17 00:00:00 2001 From: Laurent Valdes Date: Thu, 8 May 2025 18:54:59 +0200 Subject: [PATCH 22/28] chore: cleanup components --- clickplanet-webapp/src/lib.rs | 34 --------------- clickplanet-webapp/src/simple_list_display.rs | 42 ------------------- clickplanet-webapp/src/websocket.rs | 41 ------------------ 3 files changed, 117 deletions(-) delete mode 100644 clickplanet-webapp/src/simple_list_display.rs delete mode 100644 clickplanet-webapp/src/websocket.rs diff --git a/clickplanet-webapp/src/lib.rs b/clickplanet-webapp/src/lib.rs index db74304..1f48975 100644 --- a/clickplanet-webapp/src/lib.rs +++ b/clickplanet-webapp/src/lib.rs @@ -1,6 +1,3 @@ -mod simple_list_display; -mod websocket; - mod app { mod countries; } @@ -9,35 +6,4 @@ mod backends { mod backend; mod fake_backend; mod http_backend; -} - -use wasm_bindgen::prelude::*; -use crate::simple_list_display::DomDisplay; -use crate::websocket::WebSocketWrapper; - -#[wasm_bindgen(start)] -pub fn main() -> Result<(), JsValue> { - let display = DomDisplay::new()?; - - // Create the WebSocket - let protocol = "wss"; - let hostname = "clickplanet.lol"; - let port = 443; - let ws_url = format!("{}://{}:{}/v2/ws/listen", protocol, hostname, port); - - let ws = WebSocketWrapper::new(&ws_url)?; - - // Create message handler - let display_ref = display.clone(); - let callback = Closure::wrap(Box::new(move |message: String| { - if let Err(e) = display_ref.add_message(&message) { - web_sys::console::error_1(&format!("Error displaying message: {:?}", e).into()); - } - }) as Box); - - ws.set_message_handler(&callback.as_ref().unchecked_ref())?; - - callback.forget(); - - Ok(()) } \ No newline at end of file diff --git a/clickplanet-webapp/src/simple_list_display.rs b/clickplanet-webapp/src/simple_list_display.rs deleted file mode 100644 index 09fde0e..0000000 --- a/clickplanet-webapp/src/simple_list_display.rs +++ /dev/null @@ -1,42 +0,0 @@ -use wasm_bindgen::prelude::*; -use web_sys::Element; - -#[wasm_bindgen] -#[derive(Clone)] -pub struct DomDisplay(Element); - -#[wasm_bindgen] -impl DomDisplay { - #[wasm_bindgen(constructor)] - pub fn new() -> Result { - let window = web_sys::window().unwrap(); - let document = window.document().unwrap(); - - let output_div = match document.get_element_by_id("output") { - Some(div) => div, - None => { - let div = document.create_element("div")?; - div.set_id("output"); - document.body() - .ok_or_else(|| JsValue::from_str("No body element found"))? - .append_child(&div)?; - div - } - }; - - Ok(DomDisplay(output_div)) - } - - #[wasm_bindgen] - pub fn add_message(&self, message: &str) -> Result<(), JsValue> { - let document = self.0 - .owner_document() - .ok_or_else(|| JsValue::from_str("No owner document"))?; - - let msg_p = document.create_element("p")?; - msg_p.set_text_content(Some(message)); - self.0.append_child(&msg_p)?; - - Ok(()) - } -} \ No newline at end of file diff --git a/clickplanet-webapp/src/websocket.rs b/clickplanet-webapp/src/websocket.rs deleted file mode 100644 index 89f9596..0000000 --- a/clickplanet-webapp/src/websocket.rs +++ /dev/null @@ -1,41 +0,0 @@ -use wasm_bindgen::prelude::*; -use web_sys::{WebSocket, MessageEvent}; -use wasm_bindgen::JsCast; -use js_sys::{Uint8Array, ArrayBuffer, Function}; -use clickplanet_proto::clicks::UpdateNotification; -use prost::Message; - -#[wasm_bindgen] -pub struct WebSocketWrapper(WebSocket); - -#[wasm_bindgen] -impl WebSocketWrapper { - #[wasm_bindgen(constructor)] - pub fn new(url: &str) -> Result { - let ws = WebSocket::new(url)?; - ws.set_binary_type(web_sys::BinaryType::Arraybuffer); - Ok(WebSocketWrapper(ws)) - } - - #[wasm_bindgen] - pub fn set_message_handler(&self, callback: &Function) -> Result<(), JsValue> { - let cb_clone = callback.clone(); - let onmessage_fn = Closure::wrap(Box::new(move |e: MessageEvent| { - if let Ok(buffer) = e.data().dyn_into::() { - let uint8_array = Uint8Array::new(&buffer); - let data: Vec = uint8_array.to_vec(); - - if let Ok(notification) = UpdateNotification::decode(data.as_slice()) { - let _ = cb_clone.call1( - &JsValue::NULL, - &JsValue::from_str(&format!("{:?}", notification)) - ); - } - } - }) as Box); - - self.0.set_onmessage(Some(onmessage_fn.as_ref().unchecked_ref())); - onmessage_fn.forget(); - Ok(()) - } -} \ No newline at end of file From d35d72b83bfa105b520a149f5fd917724aedd728 Mon Sep 17 00:00:00 2001 From: Laurent Valdes Date: Thu, 8 May 2025 19:12:28 +0200 Subject: [PATCH 23/28] ci: update build workflow for wasm and native targets - Replace trunk with dx build --release for WASM - Add proper env vars for WASM build - Package and publish WASM build to GitHub Packages - Exclude webapp from native build and tests - Split build steps for better target separation --- .github/workflows/build-and-test.yml | 41 +++++++++++++++++++++------- 1 file changed, 31 insertions(+), 10 deletions(-) diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml index 2e0cc82..7f600cd 100644 --- a/.github/workflows/build-and-test.yml +++ b/.github/workflows/build-and-test.yml @@ -39,29 +39,50 @@ jobs: run: | cargo fetch - # Step 5. Build the Project - - name: Build the project + # Step 5. Build Native Project + - name: Build native project run: | - cargo build --verbose --workspace + cargo build --verbose --workspace --exclude clickplanet-webapp - # Step 6. Run Tests - - name: Run tests + # Step 6. Run Native Tests + - name: Run native tests run: | - cargo test --verbose --workspace + cargo test --verbose --workspace --exclude clickplanet-webapp # Step 6. Run Build for WebAssembly frontend - - name: Install Trunk + - name: Install Dioxus CLI run: | - cargo install trunk --locked + cargo install dioxus-cli - name: Install wasm32 target run: | rustup target add wasm32-unknown-unknown - - name: Build WebAssembly with Trunk + - name: Build WebAssembly with Dioxus + env: + CITYWARS_STATIC_SITE: "https://storage.googleapis.com/lv-project-313715-clickwars-static/static" + RUSTFLAGS: "--cfg=web_sys_unstable_apis" run: | cd clickplanet-webapp - trunk build --release + dx build --release + + - name: Package WASM + run: | + cd clickplanet-webapp/dist + tar czf ../../clickplanet-webapp.tar.gz . + + - name: Upload WASM Package + uses: actions/upload-artifact@v3 + with: + name: clickplanet-webapp + path: clickplanet-webapp.tar.gz + + - name: Upload to GitHub Packages + if: github.ref == 'refs/heads/main' + uses: actions/upload-artifact@v3 + with: + name: clickplanet-webapp-${{ github.sha }} + path: clickplanet-webapp.tar.gz # Step 7. Lint and Format (Optional) # - name: Run Clippy (Lint) From 5e78fe18809907a8a2b77008b43ff01658dfdbe4 Mon Sep 17 00:00:00 2001 From: Laurent Valdes Date: Thu, 8 May 2025 19:16:18 +0200 Subject: [PATCH 24/28] ci: update action versions and add digests --- .github/workflows/build-and-test.yml | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml index 7f600cd..7fffe8d 100644 --- a/.github/workflows/build-and-test.yml +++ b/.github/workflows/build-and-test.yml @@ -72,18 +72,11 @@ jobs: tar czf ../../clickplanet-webapp.tar.gz . - name: Upload WASM Package - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: clickplanet-webapp path: clickplanet-webapp.tar.gz - - name: Upload to GitHub Packages - if: github.ref == 'refs/heads/main' - uses: actions/upload-artifact@v3 - with: - name: clickplanet-webapp-${{ github.sha }} - path: clickplanet-webapp.tar.gz - # Step 7. Lint and Format (Optional) # - name: Run Clippy (Lint) # run: | From 27e19e65755e236c8314b2cf4dc9513982d5cae7 Mon Sep 17 00:00:00 2001 From: Laurent Valdes Date: Thu, 8 May 2025 19:21:58 +0200 Subject: [PATCH 25/28] ci: split build into native and webassembly jobs - Create separate native and webassembly jobs - Set proper targets for each job (x86_64-linux-gnu and wasm32-unknown-unknown) - Remove redundant protoc install from wasm job - Fix action versions and add digests --- .github/workflows/build-and-test.yml | 47 ++++++++++++++-------------- 1 file changed, 24 insertions(+), 23 deletions(-) diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml index 7fffe8d..7ab6f9e 100644 --- a/.github/workflows/build-and-test.yml +++ b/.github/workflows/build-and-test.yml @@ -10,54 +10,63 @@ on: - main jobs: - build: - name: Build and Test + native: + name: Build and Test Native runs-on: ubuntu-latest steps: - # Step 1. Checkout the Repository - name: Checkout code uses: actions/checkout@v3 - # Step 2. Install Protocol Buffers Compiler (protoc) - name: Install Protobuf Compiler (protoc) run: | sudo apt-get update sudo apt-get install -y protobuf-compiler protoc --version # Print protoc version to confirm installation - # Step 3. Install Rust (via rustup) - name: Setup Rust uses: actions-rs/toolchain@v1 with: toolchain: stable - components: rustfmt, clippy # Install supplementary tools + components: rustfmt, clippy override: true - # Step 4. Install Cargo Dependencies - name: Install dependencies run: | cargo fetch - # Step 5. Build Native Project - name: Build native project run: | cargo build --verbose --workspace --exclude clickplanet-webapp - # Step 6. Run Native Tests - name: Run native tests run: | cargo test --verbose --workspace --exclude clickplanet-webapp - # Step 6. Run Build for WebAssembly frontend + webassembly: + name: Build WebAssembly + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v3 + with: + ref: ${{ github.sha }} + # Version: 3.6.0 + # Digest: sha256:942562b9c7d4b1f2557f1da21f4d3eb4eb4fd01f2ad78b2a6e187d1b193e0a0f + + - name: Setup Rust + uses: actions-rs/toolchain@16499b5e05bf2e26879000db0c1d13f7e13fa3af # v1 + with: + toolchain: stable + target: wasm32-unknown-unknown + components: rustfmt, clippy # Install supplementary tools + override: true + - name: Install Dioxus CLI run: | cargo install dioxus-cli - - - name: Install wasm32 target - run: | - rustup target add wasm32-unknown-unknown - + - name: Build WebAssembly with Dioxus env: CITYWARS_STATIC_SITE: "https://storage.googleapis.com/lv-project-313715-clickwars-static/static" @@ -77,14 +86,6 @@ jobs: name: clickplanet-webapp path: clickplanet-webapp.tar.gz - # Step 7. Lint and Format (Optional) -# - name: Run Clippy (Lint) -# run: | -# cargo clippy --workspace --all-targets --all-features -- -D warnings -# - name: Check formatting -# run: | -# cargo fmt --all -- --check - docker: name: Build Docker Images runs-on: ubuntu-latest From 348b63022dcdc64f153c3138ec7e85db7d8d8364 Mon Sep 17 00:00:00 2001 From: Laurent Valdes Date: Thu, 8 May 2025 19:36:05 +0200 Subject: [PATCH 26/28] ci: add protoc installation to webassembly job - Install protobuf compiler in WebAssembly build - Required for clickplanet-proto dependency --- .github/workflows/build-and-test.yml | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml index 7ab6f9e..166854c 100644 --- a/.github/workflows/build-and-test.yml +++ b/.github/workflows/build-and-test.yml @@ -22,7 +22,7 @@ jobs: run: | sudo apt-get update sudo apt-get install -y protobuf-compiler - protoc --version # Print protoc version to confirm installation + protoc --version - name: Setup Rust uses: actions-rs/toolchain@v1 @@ -52,17 +52,21 @@ jobs: uses: actions/checkout@v3 with: ref: ${{ github.sha }} - # Version: 3.6.0 - # Digest: sha256:942562b9c7d4b1f2557f1da21f4d3eb4eb4fd01f2ad78b2a6e187d1b193e0a0f - name: Setup Rust - uses: actions-rs/toolchain@16499b5e05bf2e26879000db0c1d13f7e13fa3af # v1 + uses: actions-rs/toolchain@16499b5e05bf2e26879000db0c1d13f7e13fa3af with: toolchain: stable target: wasm32-unknown-unknown - components: rustfmt, clippy # Install supplementary tools + components: rustfmt, clippy override: true + - name: Install Protobuf Compiler (protoc) + run: | + sudo apt-get update + sudo apt-get install -y protobuf-compiler + protoc --version + - name: Install Dioxus CLI run: | cargo install dioxus-cli From a03dbac7bced1dc5385353ad0c8165d9c5b8f0cb Mon Sep 17 00:00:00 2001 From: Laurent Valdes Date: Thu, 8 May 2025 19:39:14 +0200 Subject: [PATCH 27/28] ci: optimize build speed with caching - Use cache-cargo-install-action for faster dioxus-cli install - Add cargo caching for both native and wasm builds - Use different cache keys for native and wasm targets --- .github/workflows/build-and-test.yml | 30 +++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml index 166854c..f5b5797 100644 --- a/.github/workflows/build-and-test.yml +++ b/.github/workflows/build-and-test.yml @@ -31,6 +31,17 @@ jobs: components: rustfmt, clippy override: true + - name: Cache Rust dependencies + uses: actions/cache@v4 + with: + path: | + ~/.cargo/registry + ~/.cargo/git + target + key: ${{ runner.os }}-cargo-native-${{ hashFiles('**/Cargo.lock') }} + restore-keys: | + ${{ runner.os }}-cargo-native- + - name: Install dependencies run: | cargo fetch @@ -65,11 +76,24 @@ jobs: run: | sudo apt-get update sudo apt-get install -y protobuf-compiler - protoc --version + protoc --version # Print protoc version to confirm installation + + # Step 4. Cache Dependencies + - name: Cache Rust dependencies + uses: actions/cache@v4 + with: + path: | + ~/.cargo/registry + ~/.cargo/git + target + key: ${{ runner.os }}-cargo-wasm-${{ hashFiles('**/Cargo.lock') }} + restore-keys: | + ${{ runner.os }}-cargo-wasm- - name: Install Dioxus CLI - run: | - cargo install dioxus-cli + uses: taiki-e/cache-cargo-install-action@v2 + with: + tool: dioxus-cli - name: Build WebAssembly with Dioxus env: From 7190e472f0fdbd703a32ae1b4e12e2509ab18855 Mon Sep 17 00:00:00 2001 From: Laurent Valdes Date: Thu, 8 May 2025 23:26:21 +0200 Subject: [PATCH 28/28] ci: fix wasm packaging by using clickplanet-webapp/dist --- .github/workflows/build-and-test.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml index f5b5797..5e94c45 100644 --- a/.github/workflows/build-and-test.yml +++ b/.github/workflows/build-and-test.yml @@ -76,9 +76,8 @@ jobs: run: | sudo apt-get update sudo apt-get install -y protobuf-compiler - protoc --version # Print protoc version to confirm installation + protoc --version - # Step 4. Cache Dependencies - name: Cache Rust dependencies uses: actions/cache@v4 with: @@ -102,6 +101,8 @@ jobs: run: | cd clickplanet-webapp dx build --release + mkdir -p dist + cp -r ../target/dx/clickplanet-webapp/release/web/public/* dist/ - name: Package WASM run: |