Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
feat(cursor): sculpt the original themes' 3D arrow and hand
EtienneLescot262326de028f
diff --git a/crates/compositor/src/compositor_linux.rs b/crates/compositor/src/compositor_linux.rsindex b6291f46d..fd900f0e8 100644--- a/crates/compositor/src/compositor_linux.rs+++ b/crates/compositor/src/compositor_linux.rs@@ -341,8 +341,8 @@ pub struct Compositor {/// touche depuis appartient au jeu actif et ne peut pas etre evince -- voir/// `cached_image`.img_frame_start: std::cell::Cell<u64>,- /// Champs et reliefs des sprites de curseur (mode 15), RG16F, par chemin, avec leur forme.- /// Pas d'eviction : l'ensemble des cartes livrees reste inferieur a quelques dizaines de Mo.+ /// Champs de distance des sprites de curseur (mode 15), R16F, par chemin, avec leur forme.+ /// Pas d'eviction : seuls les sprites du theme en cours y passent (~2,6 Mo pour les seize).sdf_cache: RefCell<std::collections::HashMap<String, (wgpu::Texture, SpriteShape)>>,/// Copie mipmappee de la frame composee, lue par les annotations « flou »@@ -1321,19 +1321,14 @@ impl Compositor {Ok((tex, w, h))}- /// Champ et relief du sprite `path` (binding 2 du mode 15) et sa forme, calcules au+ /// Champ de distance du sprite `path` (binding 2 du mode 15) et sa forme, calcules au/// premier appel. Parite `compositor_windows::cursor_sdf`.- fn cursor_sdf(- &self,- path: &str,- depth_path: Option<&str>,- ) -> Result<(wgpu::Texture, SpriteShape)> {- let cache_key = format!("{path}\0{}", depth_path.unwrap_or_default());- if let Some(hit) = self.sdf_cache.borrow().get(&cache_key) {+ fn cursor_sdf(&self, path: &str) -> Result<(wgpu::Texture, SpriteShape)> {+ if let Some(hit) = self.sdf_cache.borrow().get(path) {return Ok(hit.clone());}- let sdf = crate::cursor_sdf::CursorSdf::load_with_depth(path, depth_path)?;- let texels = sdf.rg16_bytes();+ let sdf = crate::cursor_sdf::CursorSdf::load(path)?;+ let texels = sdf.f16_bytes();let size = wgpu::Extent3d { width: sdf.width, height: sdf.height, depth_or_array_layers: 1 };let tex = self.gpu.device.create_texture(&wgpu::TextureDescriptor {label: Some("cursor-sdf"),@@ -1341,7 +1336,7 @@ impl Compositor {mip_level_count: 1,sample_count: 1,dimension: wgpu::TextureDimension::D2,- format: wgpu::TextureFormat::Rg16Float,+ format: wgpu::TextureFormat::R16Float,usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,view_formats: &[],});@@ -1355,13 +1350,13 @@ impl Compositor {&texels,wgpu::TexelCopyBufferLayout {offset: 0,- bytes_per_row: Some(sdf.width * 4),+ bytes_per_row: Some(sdf.width * 2),rows_per_image: Some(sdf.height),},size,);let entry = (tex, sdf.shape);- self.sdf_cache.borrow_mut().insert(cache_key, entry.clone());+ self.sdf_cache.borrow_mut().insert(path.to_string(), entry.clone());Ok(entry)}@@ -2833,9 +2828,9 @@ impl Compositor {// Curseur modelise (mode 15) : ce meme sprite extrude, `plan_cursor` en a tire la// pose. Sprite au binding 1 (texY), champ au binding 2 (texU). Parite Windows/macOS.if let Some(pose) = plan.model {- match self.cursor_sdf(&sprite.path, sprite.model_depth_path.as_deref()) {+ match self.cursor_sdf(&sprite.path) {Ok((sdf, shape)) => {- let shape = SpriteShape { hotspot, ..shape };+ let shape = crate::frame_geometry::model_shape(sprite, shape);let sdf_view = sdf.create_view(&wgpu::TextureViewDescriptor::default());for placement in placements {let Some(cb) = cursor_model_cb(@@ -5167,6 +5162,14 @@ mod tests {comp.set_cursor(track.clone());comp.set_cursor_time(Some(2.0));comp.set_timeline_time(Some(2.0));+ let cfg = model_cfg();+ unsafe {+ comp.compose_frame(screen.as_ptr(), screen.as_ptr(), 0.0, &cfg).expect("compose_frame");+ comp.readback_direct().expect("readback_direct").2+ }+ }++ fn model_cfg() -> crate::config::Cfg {let mut cfg = crate::config::Cfg::c8();cfg.bg_blur = false;cfg.zoom = false;@@ -5174,9 +5177,37 @@ mod tests {cfg.cursor = true;cfg.mblur_n = 1;cfg.shadow = false;- unsafe {- comp.compose_frame(screen.as_ptr(), screen.as_ptr(), 0.0, &cfg).expect("compose_frame");- comp.readback_direct().expect("readback_direct").2+ cfg+ }++ /// Le pixel du hotspot et l'unité du modèle (px) que `plan_cursor` donne à la scène que+ /// `compose_model` rend.+ fn model_tip(json: &str, track: &crate::cursor::CursorTrack) -> ([f32; 2], f32) {+ let scene = crate::scene::Scene::from_json(json).expect("scene json");+ let (cfg, live, render_px, src) = (model_cfg(), live_params_from_scene(&scene), [1280.0, 720.0], [640.0, 360.0]);+ let g = plan_frame(&FrameGeometryInput {+ render_px,+ screen_tex_px: src,+ screen_visible_px: src,+ webcam_visible_px: src,+ u_max: 1.0,+ v_max: 1.0,+ frame: 0.0,+ cfg: &cfg,+ live,+ scene: Some(&scene),+ cursor: Some(track),+ timeline_t_override: Some(2.0),+ programme_time: None,+ });+ let input = CursorPlanInput { render_px, u_max: 1.0, v_max: 1.0, cfg: &cfg, live, scene: Some(&scene), track, t: 2.0 };+ let plan = plan_cursor(&g, &input).expect("un curseur a dessiner");+ match plan.placement {+ CursorPlacement::Tilted { plane_pt, quad, center_px, .. } => {+ let (x, y) = quad.point_px(plane_pt[0], plane_pt[1]);+ ([center_px[0] + x, center_px[1] + y], plan.size_px * quad.scale)+ }+ CursorPlacement::Upright { center } => ([center[0] * render_px[0], center[1] * render_px[1]], plan.size_px),}}@@ -5414,6 +5445,67 @@ mod tests {assert!(failures.is_empty(), "{failures:#?}");}+ /// Pendant de `the_sculpted_cursors_stand_at_the_hotspot` (Windows) : la flèche et la main+ /// sculptées des thèmes d'origine (`sculpt.rs`) passent par le WGSL, tiennent au hotspot, en+ /// bas à droite de lui, et portent leur ombre en l'air.+ #[test]+ fn the_sculpted_cursors_stand_at_the_hotspot() {+ let Some(gpu) = gpu() else { return };+ let comp = Compositor::new_sized(&gpu, 1280, 720).expect("Compositor::new_sized");+ let (y, uv) = model_screen_planes(false);+ let blue = FakeFrame::from_planes(&gpu, 640, 360, &y, &uv);+ let (y, uv) = model_screen_planes(true);+ let orange = FakeFrame::from_planes(&gpu, 640, 360, &y, &uv);+ let extruded = model_scene_json("null", Some(true), "default", true, 5.0);+ let hidden = model_scene_json("null", Some(true), "default", false, 5.0);+ let bare = compose_model(&comp, &blue, &hidden, &model_track("arrow", false, 0.5));+ let mut failures = Vec::new();+ for state in ["arrow", "pointer"] {+ let still = model_track(state, false, 0.5);+ let sprite = compose_model(&comp, &blue, &extruded, &still);+ for theme in ["studio-ink", "prism-glow", "pop-coral", "pixel-candy", "star-sprout"] {+ // Le sprite reste celui du theme par defaut : seul le nom pose le modele.+ let json = extruded+ .replace(&format!(r#"/{state}.png","#), &format!(r#"/{state}.png","sculpt":"{theme}/{state}","#));+ let (hover, hover_b) = (compose_model(&comp, &blue, &json, &still), compose_model(&comp, &orange, &json, &still));+ model_save(&format!("sculpt-{theme}-{state}"), &hover);+ if hover == sprite {+ failures.push(format!("{theme}/{state}: le sprite extrude au lieu du modele"));+ }+ let (tip, u) = model_tip(&json, &still);+ let mask = model_opaque(&hover, &hover_b, &bare);+ let (mut body, mut c, mut near) = (0usize, [0.0f32; 2], f32::MAX);+ for (i, _) in mask.iter().enumerate().filter(|(_, m)| **m) {+ let (x, y) = ((i % 1280) as f32, (i / 1280) as f32);+ body += 1;+ c = [c[0] + x, c[1] + y];+ near = near.min((x - tip[0]).hypot(y - tip[1]));+ }+ let c = [c[0] / body.max(1) as f32, c[1] / body.max(1) as f32];+ let shadow = (0..1280 * 720)+ .filter(|&i| {+ let (a, b) = (&hover[i * 4..i * 4 + 3], &bare[i * 4..i * 4 + 3]);+ !mask[i] && a != b && model_luma(a) < model_luma(b) - 6.0+ })+ .count();+ println!("{theme}/{state} : unite {u:.1} px, corps {body} px, a {near:.1} px du hotspot {tip:?}, centroide {c:?}, ombre {shadow} px");+ if (body as f32) < 0.12 * u * u {+ failures.push(format!("{theme}/{state}: {body} px de corps pour {u:.0} px d'unite"));+ }+ if near > 0.08 * u {+ failures.push(format!("{theme}/{state}: le modele est a {near:.1} px du hotspot"));+ }+ if !(c[0] > tip[0] && c[1] > tip[1] + 0.2 * u) {+ failures.push(format!("{theme}/{state}: corps en {c:?}, pas en bas a droite de {tip:?}"));+ }+ if shadow * 10 < body * 3 {+ failures.push(format!("{theme}/{state}: pas d'ombre en l'air ({shadow} px)"));+ }+ }+ }+ assert!(failures.is_empty(), "{failures:#?}");+ }+/// Pendant de `tests/cursor_tap_render.rs` (Windows) : sous un lissage qui traine loin/// derriere la souris, la pointe du modele se pose sur la pastille rouge du clic, et l'anneau/// de l'impact (mode 16) l'entoure, a plat et incline.diff --git a/crates/compositor/src/compositor_macos.rs b/crates/compositor/src/compositor_macos.rsindex 01e809026..21abc2113 100644--- a/crates/compositor/src/compositor_macos.rs+++ b/crates/compositor/src/compositor_macos.rs@@ -282,8 +282,8 @@ pub struct Compositor {/// Valeur de `img_tick` au début de la frame en cours. Tout ce qui a été touché depuis/// appartient au jeu actif et ne peut pas être évincé — voir `cached_image`.img_frame_start: std::cell::Cell<u64>,- /// Champs et reliefs des sprites de curseur (mode 15), RG16F, par chemin, avec leur forme.- /// Pas d'éviction : l'ensemble des cartes livrées reste inférieur à quelques dizaines de Mo.+ /// Champs de distance des sprites de curseur (mode 15), R16F, par chemin, avec leur forme.+ /// Pas d'éviction : seuls les sprites du thème en cours y passent (~2,6 Mo pour les seize).sdf_cache: RefCell<std::collections::HashMap<String, (metal::Texture, crate::frame_geometry::SpriteShape)>,>,@@ -908,23 +908,18 @@ impl Compositor {Ok((tex, w, h))}- /// Champ et relief du sprite `path` (texture(4) du mode 15) et sa forme, calculés au- /// premier appel. Parité `compositor_windows::cursor_sdf`. RG16Float : filtrable sur tous+ /// Champ de distance du sprite `path` (texture(4) du mode 15) et sa forme, calculés au+ /// premier appel. Parité `compositor_windows::cursor_sdf`. R16Float : filtrable sur tous/// les GPU Apple, contrairement au R32Float.- fn cursor_sdf(- &self,- path: &str,- depth_path: Option<&str>,- ) -> Result<(metal::Texture, crate::frame_geometry::SpriteShape)> {- let cache_key = format!("{path}\0{}", depth_path.unwrap_or_default());- if let Some(hit) = self.sdf_cache.borrow().get(&cache_key) {+ fn cursor_sdf(&self, path: &str) -> Result<(metal::Texture, crate::frame_geometry::SpriteShape)> {+ if let Some(hit) = self.sdf_cache.borrow().get(path) {return Ok(hit.clone());}- let sdf = crate::cursor_sdf::CursorSdf::load_with_depth(path, depth_path)?;- let texels = sdf.rg16_bytes();+ let sdf = crate::cursor_sdf::CursorSdf::load(path)?;+ let texels = sdf.f16_bytes();let tex = make_texture(&self.gpu.device,- metal::MTLPixelFormat::RG16Float,+ metal::MTLPixelFormat::R16Float,sdf.width,sdf.height,metal::MTLStorageMode::Shared,@@ -937,10 +932,10 @@ impl Compositor {},0,texels.as_ptr() as *const std::ffi::c_void,- (sdf.width * 4) as u64,+ (sdf.width * 2) as u64,);let entry = (tex, sdf.shape);- self.sdf_cache.borrow_mut().insert(cache_key, entry.clone());+ self.sdf_cache.borrow_mut().insert(path.to_string(), entry.clone());Ok(entry)}@@ -1977,12 +1972,9 @@ impl Compositor {let (tex, iw, ih) = self.cached_image(sprite.path.as_str())?;// Sans champ de distance, repli sur le sprite plat plutôt qu'aucun curseur. Parité Linux.if let Some(pose) = model {- match self.cursor_sdf(sprite.path.as_str(), sprite.model_depth_path.as_deref()) {+ match self.cursor_sdf(sprite.path.as_str()) {Ok((sdf, shape)) => {- let shape = crate::frame_geometry::SpriteShape {- hotspot: [sprite.hotspot_x, sprite.hotspot_y],- ..shape- };+ let shape = crate::frame_geometry::model_shape(sprite, shape);if let Some(cb) = crate::frame_geometry::cursor_model_cb(placement, size_px, pose, shape, a, clip,) {diff --git a/crates/compositor/src/compositor_windows.rs b/crates/compositor/src/compositor_windows.rsindex 721ea309b..f6bf3bdd6 100644--- a/crates/compositor/src/compositor_windows.rs+++ b/crates/compositor/src/compositor_windows.rs@@ -179,8 +179,8 @@ pub struct Compositor {/// Valeur de `img_tick` au début de la frame en cours. Tout ce qui a été touché depuis/// appartient au jeu actif et ne peut pas être évincé — voir `cached_image`.img_frame_start: std::cell::Cell<u64>,- /// Champs et reliefs des sprites de curseur (mode 15), RG16F, par chemin, avec leur forme.- /// Pas d'éviction : l'ensemble des cartes livrées reste inférieur à quelques dizaines de Mo.+ /// Champs de distance des sprites de curseur (mode 15), R16F, par chemin, avec leur forme.+ /// Pas d'éviction : seuls les sprites du thème en cours y passent (~2,6 Mo pour les seize).sdf_cache: RefCell<HashMap<String, (ID3D11ShaderResourceView, SpriteShape)>>,/// Masque de segmentation du sujet webcam, R8 à la résolution du modèle. Écrit par/// `set_webcam_mask` depuis le thread d'inférence, lu au moment de dessiner la webcam.@@ -1088,24 +1088,19 @@ impl Compositor {Ok((srv.unwrap(), w, h))}- /// Champ et carte de relief du sprite `path` (t4 du mode 15) et sa forme, calculés au premier appel.- unsafe fn cursor_sdf(- &self,- path: &str,- depth_path: Option<&str>,- ) -> Result<(ID3D11ShaderResourceView, SpriteShape)> {- let cache_key = format!("{path}\0{}", depth_path.unwrap_or_default());- if let Some(hit) = self.sdf_cache.borrow().get(&cache_key) {+ /// Champ de distance du sprite `path` (t4 du mode 15) et sa forme, calculés au premier appel.+ unsafe fn cursor_sdf(&self, path: &str) -> Result<(ID3D11ShaderResourceView, SpriteShape)> {+ if let Some(hit) = self.sdf_cache.borrow().get(path) {return Ok(hit.clone());}- let sdf = crate::cursor_sdf::CursorSdf::load_with_depth(path, depth_path)?;- let texels = sdf.rg16_bytes();+ let sdf = crate::cursor_sdf::CursorSdf::load(path)?;+ let texels = sdf.f16_bytes();let td = D3D11_TEXTURE2D_DESC {Width: sdf.width,Height: sdf.height,MipLevels: 1,ArraySize: 1,- Format: DXGI_FORMAT_R16G16_FLOAT,+ Format: DXGI_FORMAT_R16_FLOAT,SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },Usage: D3D11_USAGE_IMMUTABLE,BindFlags: D3D11_BIND_SHADER_RESOURCE.0 as u32,@@ -1114,7 +1109,7 @@ impl Compositor {};let init = D3D11_SUBRESOURCE_DATA {pSysMem: texels.as_ptr() as *const c_void,- SysMemPitch: sdf.width * 4,+ SysMemPitch: sdf.width * 2,SysMemSlicePitch: 0,};let mut tex: Option<ID3D11Texture2D> = None;@@ -1122,7 +1117,7 @@ impl Compositor {let mut srv: Option<ID3D11ShaderResourceView> = None;self.dev.CreateShaderResourceView(&tex.unwrap(), None, Some(&mut srv))?;let entry = (srv.unwrap(), sdf.shape);- self.sdf_cache.borrow_mut().insert(cache_key, entry.clone());+ self.sdf_cache.borrow_mut().insert(path.to_string(), entry.clone());Ok(entry)}@@ -1535,10 +1530,9 @@ impl Compositor {// Sans champ de distance, repli sur le sprite plat plutôt que sur le curseur math.// Parité Linux.if let Some(pose) = model {- match self.cursor_sdf(path, sprite.model_depth_path.as_deref()) {+ match self.cursor_sdf(path) {Ok((sdf, shape)) => {- let shape =- SpriteShape { hotspot: [sprite.hotspot_x, sprite.hotspot_y], ..shape };+ let shape = crate::frame_geometry::model_shape(sprite, shape);if let Some(cb) = crate::frame_geometry::cursor_model_cb(placement, size_px, pose, shape, a, clip,) {diff --git a/crates/compositor/src/cursor_sdf.rs b/crates/compositor/src/cursor_sdf.rsindex 1dbce9c7e..161793a40 100644--- a/crates/compositor/src/cursor_sdf.rs+++ b/crates/compositor/src/cursor_sdf.rs@@ -14,8 +14,9 @@//! en tiraient des stries sur les flancs. Le flou efface l'escalier ; il laisse en place un bord//! droit (le champ y est affine) et n'arrondit un coin que d'un demi-texel source.//!-//! La texture RG16F, même rect que le sprite, stocke le champ de distance dans R et le relief de la-//! face dans G. Le relief vient d'une carte PNG en niveaux de gris, étirée sur le même suréchantillon.+//! La texture (R16F, même rect que le sprite) garde les distances telles quelles : un demi-flottant+//! est exact au millième près autour de zéro, là où la silhouette se joue, et il est filtrable sur+//! les trois backends (D3D11, Metal, wgpu), contrairement au R32F.use anyhow::{anyhow, Result};@@ -34,8 +35,6 @@ pub struct CursorSdf {/// Distances signées (unités du modèle, négatives dedans), ligne par ligne, texels centrés/// comme ceux du sprite : la texture couvre exactement son rect.pub texels: Vec<f32>,- /// Hauteur du dessus au même point, en unités du modèle.- pub heights: Vec<f32>,/// La forme, hotspot nul : l'appelant pose celui de la scène.pub shape: SpriteShape,}@@ -43,11 +42,6 @@ pub struct CursorSdf {impl CursorSdf {/// Décode `path` (chemin ou data URI, comme les sprites) et en tire le champ.pub fn load(path: &str) -> Result<CursorSdf> {- Self::load_with_depth(path, None)- }-- /// Décode le sprite et une éventuelle carte de relief PNG alignée sur lui.- pub fn load_with_depth(path: &str, depth_path: Option<&str>) -> Result<CursorSdf> {let img = if let Some(bytes) = crate::frame_geometry::decode_data_uri(path) {image::load_from_memory(&bytes)} else {@@ -56,27 +50,11 @@ impl CursorSdf {.map_err(|e| anyhow!("sprite {path} : {e}"))?.to_rgba8();let (w, h) = img.dimensions();- let heights = if let Some(depth_path) = depth_path {- let depth = image::open(depth_path)- .map_err(|e| anyhow!("relief {depth_path} : {e}"))?- .to_luma8();- if depth.dimensions() != (w, h) {- return Err(anyhow!("relief {depth_path} : taille différente du sprite {path}"));- }- Some(depth.into_raw())- } else {- None- };- Ok(CursorSdf::from_rgba_with_height(img.as_raw(), w, h, heights.as_deref()))+ Ok(CursorSdf::from_rgba(img.as_raw(), w, h))}/// `rgba` : `w`×`h` texels RGBA8, alpha droit.pub fn from_rgba(rgba: &[u8], w: u32, h: u32) -> CursorSdf {- Self::from_rgba_with_height(rgba, w, h, None)- }-- /// `heights`, quand présent, est une image grise `w`×`h` (255 = relief maximal).- fn from_rgba_with_height(rgba: &[u8], w: u32, h: u32, heights: Option<&[u8]>) -> CursorSdf {const K: usize = SDF_UPSAMPLE;// Une marge de texels transparents : un texel intérieur collé au bord du sprite trouve// ainsi son voisin extérieur, qui n'existe pas dans le rect.@@ -108,8 +86,6 @@ impl CursorSdf {let scale = 1.0 / (K * w.max(h)) as f32;let mut texels = Vec::with_capacity(fw * fh);- let mut relief = Vec::with_capacity(fw * fh);- let mut max_height = 0.0f32;let mut top_row = fh;for fy in 0..fh {for fx in 0..fw {@@ -122,25 +98,6 @@ impl CursorSdf {to_inside[g].sqrt().min((gw + gh) as f64) - 0.5};texels.push(d as f32 * scale);-- let height = if let Some(heights) = heights {- let sx = (fx as f32 + 0.5) / K as f32 - 0.5;- let sy = (fy as f32 + 0.5) / K as f32 - 0.5;- let (x0, y0) = (sx.floor(), sy.floor());- let (tx, ty) = (sx - x0, sy - y0);- let (x0, y0) = (x0 as isize, y0 as isize);- let at = |x: isize, y: isize| {- let (x, y) = (x.clamp(0, w as isize - 1) as usize, y.clamp(0, h as isize - 1) as usize);- heights[y * w as usize + x] as f32 / 255.0- };- let top = at(x0, y0) * (1.0 - tx) + at(x0 + 1, y0) * tx;- let bottom = at(x0, y0 + 1) * (1.0 - tx) + at(x0 + 1, y0 + 1) * tx;- (top * (1.0 - ty) + bottom * ty) * crate::frame_geometry::MODEL_RELIEF_MAX- } else {- 0.0- };- relief.push(height);- max_height = max_height.max(height);}}for _ in 0..2 {@@ -151,32 +108,22 @@ impl CursorSdf {width: fw as u32,height: fh as u32,texels,- heights: relief,shape: SpriteShape {size: [w as f32 / long, h as f32 / long],hotspot: [0.0; 2],top: top_row as f32 / fh as f32,- max_height,+ max_height: 0.0,+ thick: crate::frame_geometry::MODEL_THICK,+ sculpt: 0,},}}- /// Le champ de distance seul en demi-flottants petit-boutistes, pour les tests mono-canal.+ /// Les texels en demi-flottants petit-boutistes, pour une texture R16F.pub fn f16_bytes(&self) -> Vec<u8> {self.texels.iter().flat_map(|&d| f16_bits(d).to_le_bytes()).collect()}- /// Le champ et le relief intercalés en demi-flottants petit-boutistes, pour une texture RG16F.- pub fn rg16_bytes(&self) -> Vec<u8> {- self.texels- .iter()- .zip(&self.heights)- .flat_map(|(&distance, &height)| {- f16_bits(distance).to_le_bytes().into_iter().chain(f16_bits(height).to_le_bytes())- })- .collect()- }-/// Le champ en `uv` (0..1 sur le rect du sprite), filtré comme le sampler des shaders :/// bilinéaire, bord prolongé. Miroir CPU de l'échantillonnage du mode 15.#[cfg(test)]@@ -466,25 +413,4 @@ mod tests {assert!(sdf.sample([0.9, 0.1]) > 0.0);assert_eq!(sdf.f16_bytes().len(), sdf.texels.len() * 2);}-- #[test]- fn each_original_theme_loads_its_aligned_sculpted_faces() {- let root = concat!(env!("CARGO_MANIFEST_DIR"), "/../../public/cursors/");- for theme in ["studio-ink", "prism-glow", "pop-coral", "pixel-candy", "star-sprout"] {- for state in ["arrow", "pointer"] {- let face = format!("{root}{theme}/model-{state}.png");- let depth = format!("{root}{theme}/model-{state}-depth.png");- let sdf = CursorSdf::load_with_depth(&face, Some(&depth))- .unwrap_or_else(|error| panic!("{theme}/{state}: {error}"));- assert_eq!(sdf.width, 128 * SDF_UPSAMPLE as u32, "{theme}/{state}");- assert_eq!(sdf.height, 128 * SDF_UPSAMPLE as u32, "{theme}/{state}");- assert!(sdf.shape.max_height > 0.02, "{theme}/{state} has no sculpted relief");- assert!(- sdf.shape.max_height- <= crate::frame_geometry::MODEL_RELIEF_MAX + f32::EPSILON- );- assert_eq!(sdf.rg16_bytes().len(), sdf.texels.len() * 4, "{theme}/{state}");- }- }- }}diff --git a/crates/compositor/src/frame_geometry.rs b/crates/compositor/src/frame_geometry.rsindex 6e24d12e9..dd38c8705 100644--- a/crates/compositor/src/frame_geometry.rs+++ b/crates/compositor/src/frame_geometry.rs@@ -3539,15 +3539,16 @@ pub fn plan_cursor(g: &FrameGeometry, input: &CursorPlanInput) -> Option<CursorP// ============ Curseur modélisé (mode 15) ============//-// Le sprite de l'état courant devient un OBJET : sa silhouette et son relief rasterisé sont lancés-// de rayons par pixel dans le shader, éclairés, et portent une vraie ombre sur l'écran. Le champ de-// distance vient de l'alpha ; le second canal porte la hauteur de face propre au modèle. Le dessus-// garde son art, et les flancs prennent sa matière de bord. Rust calcule la pose, la caméra et la-// boîte de dessin ; les trois shaders font le reste avec les MÊMES constantes.+// Le curseur devient un OBJET, lancé de rayons par pixel dans le shader, éclairé, et qui porte une+// vraie ombre sur l'écran : la flèche ou la main d'un thème d'origine SCULPTÉE en volumes+// (`sculpt.rs`), sinon le sprite de l'état courant extrudé, sa silhouette tirée de l'alpha+// (`cursor_sdf`), son dessus portant l'art du sprite et ses flancs la couleur de son bord. Rust+// calcule la pose, la caméra et la boîte de dessin ; les trois shaders font le reste avec les+// MÊMES constantes.//// Repère du MODÈLE : unité = plus grand côté du sprite (`size_px`, la taille du curseur), origine-// au hotspot de la face du dessus, x à droite, y vers le bas, z vers la caméra ; le dessous reste-// en z = -MODEL_THICK, l'arête est en z = 0 et le relief monte jusqu'à MODEL_RELIEF_MAX.+// au hotspot, x à droite, y vers le bas, z vers la caméra ; le modèle occupe z de+// -`SpriteShape::thick` à `SpriteShape::max_height`.//// Emplacements du `LayerCB` au mode 15 (128 octets, inchangés) :// dst rect de dessin (sortie 0..1) : boîte du modèle ET de son ombre@@ -3567,14 +3568,14 @@ pub fn plan_cursor(g: &FrameGeometry, input: &CursorPlanInput) -> Option<CursorP// mb.zw translation du plan dans le repère caméra (px, `TiltedQuad::offset`) : le// plan vaut `R·p + (mb.zw, 0)`, œil en (0, 0, P). Nulle sous un angle fixe.// radius_px rapport w/h du sprite : sa taille (unités) en découle, plus grand côté = 1-// Textures : le sprite RGBA (alpha droit) et le champ RG16F (`cursor_sdf`, distance + hauteur), sur le même rect.+// trail_a le curseur sculpté (0 = le sprite extrudé), l'épaisseur sous z = 0 avant+// écrasement, la hauteur au-dessus de z = 0 (`SpriteShape`), 0+// Textures : le sprite RGBA (alpha droit) et son champ R16F (`cursor_sdf`), sur le même rect.// Windows et macOS : sprite en t2/texture(2) (`texImg`), champ en t4/texture(4) (`texSdf`).// Linux : sprite au binding 1 (`texY`), champ au binding 2 (`texU`).-/// Épaisseur du modèle : l'arête est à z = 0, celle du dessous à z = -épaisseur.+/// Épaisseur du sprite extrudé : son dessus est en z = 0, son dessous en z = -épaisseur.pub const MODEL_THICK: f32 = 0.19;-/// Relief maximal des faces sculptées, en unités du modèle.-pub const MODEL_RELIEF_MAX: f32 = 0.12;/// Rayon du chanfrein arrondi des arêtes du dessus et du dessous.pub const MODEL_BEVEL: f32 = 0.045;/// Direction VERS la lumière, repère caméra (x droite, y bas, z vers le spectateur) : en haut à@@ -3624,8 +3625,13 @@ pub struct SpriteShape {pub hotspot: [f32; 2],/// Haut de la silhouette (alpha 0,5), fraction de la hauteur du sprite.pub top: f32,- /// Hauteur maximale de la face au-dessus de l'arête du sprite, en unités du modèle.+ /// Hauteur du modèle au-dessus de z = 0, en unités du modèle : 0 pour un sprite extrudé.pub max_height: f32,+ /// Épaisseur sous z = 0, avant écrasement : `MODEL_THICK` pour un sprite extrudé, celle du+ /// modèle pour un curseur sculpté (`sculpt::sculpted_shape`).+ pub thick: f32,+ /// Le curseur sculpté que dessine le shader (`sculpt`), 0 pour le sprite extrudé.+ pub sculpt: u32,}impl SpriteShape {@@ -3638,7 +3644,7 @@ impl SpriteShape {fn model_box(&self, squash: f32) -> ([f32; 3], [f32; 3]) {let [x, y] = self.origin();(- [x, y, -MODEL_THICK * squash],+ [x, y, -self.thick * squash],[x + self.size[0], y + self.size[1], self.max_height],)}@@ -3649,7 +3655,7 @@ impl SpriteShape {/// basculé, un jour d'au plus ~1 % de l'unité, invisible sous l'ombre de contact.fn contact_lift(&self, pitch: f32, squash: f32) -> f32 {let y_top = (self.top - self.hotspot[1]) * self.size[1];- MODEL_THICK * squash * pitch.cos() - y_top * pitch.sin()+ self.thick * squash * pitch.cos() - y_top * pitch.sin()}}@@ -3734,6 +3740,17 @@ pub fn cursor_pose(CursorPose { clearance, pitch, yaw, squash }}+/// La forme que le mode 15 donne à `sprite` : son curseur sculpté s'il en a un+/// (`sculpt::sculpted_shape`), sinon le sprite extrudé (`sdf_shape`, du champ de son PNG) au+/// hotspot de la scène. Commun aux trois backends.+pub fn model_shape(sprite: &crate::scene::SceneCursorSprite, sdf_shape: SpriteShape) -> SpriteShape {+ sprite+ .sculpt+ .as_deref()+ .and_then(crate::sculpt::sculpted_shape)+ .unwrap_or(SpriteShape { hotspot: [sprite.hotspot_x, sprite.hotspot_y], ..sdf_shape })+}+/// Le sprite que les backends résoudraient pour `cursor_type` : c'est lui que le mode 15 modèle./// Même résolution qu'eux : l'état s'il a un sprite, sinon la flèche.fn modelled_sprite<'a>(@@ -3924,6 +3941,7 @@ pub fn cursor_model_cb(dst_prev: clip,mb: [view.half[0], view.half[1], view.offset[0], view.offset[1]],radius_px: shape.size[0] / shape.size[1],+ trail_a: [shape.sculpt as f32, shape.thick, shape.max_height, 0.0],..Default::default()})}@@ -7140,7 +7158,7 @@ mod tests {/// Miroir CPU de `sd_model`, écrasé à `squash`.fn sd_model(sdf: &crate::cursor_sdf::CursorSdf, shape: SpriteShape, squash: f32, p: [f32; 3]) -> f32 {- let half_t = MODEL_THICK * squash * 0.5;+ let half_t = shape.thick * squash * 0.5;let w = [sd2(sdf, shape, [p[0], p[1]]) + MODEL_BEVEL, (p[2] + half_t).abs() - (half_t - MODEL_BEVEL)];w[0].max(w[1]).min(0.0) + w[0].max(0.0).hypot(w[1].max(0.0)) - MODEL_BEVEL}@@ -7204,7 +7222,7 @@ mod tests {continue;}let wx = (s + MODEL_BEVEL).max(0.0);- let z = -MODEL_THICK * view.pose.squash + MODEL_BEVEL - (MODEL_BEVEL * MODEL_BEVEL - wx * wx).sqrt();+ let z = -shape.thick * view.pose.squash + MODEL_BEVEL - (MODEL_BEVEL * MODEL_BEVEL - wx * wx).sqrt();lowest = lowest.min(view.model_to_plane([x, y, z])[2]);}}@@ -7222,7 +7240,7 @@ mod tests {path: sprite_path(key),hotspot_x: hx,hotspot_y: hy,- model_depth_path: None,+ sculpt: None,},);}@@ -7426,23 +7444,20 @@ mod tests {model_plan([0.0; 3], &scene, &unknown, 0.3, true).expect("plan").model,Some(cursor_pose(&unknown, 0.3, 2.5, 1.0)));- // Les faces propres à un thème autre que `default` ont aussi accès au mode 3D.+ // Un thème d'origine passe sa flèche sculptée : c'est elle que le mode 3D pose, le sprite+ // plat restant l'art en 2D.let mut themed = model_scene();themed.cursor.theme = "studio-ink".into();let themed_arrow = crate::scene::SceneCursorSprite {- path: "studio-ink/model-arrow.png".into(),- hotspot_x: 0.1977,- hotspot_y: 0.0635,- model_depth_path: Some("studio-ink/model-arrow-depth.png".into()),+ path: "studio-ink/arrow.png".into(),+ hotspot_x: 0.1947,+ hotspot_y: 0.0656,+ sculpt: Some("studio-ink/arrow".into()),};themed.cursor.cursor_sprites.insert("arrow".into(), themed_arrow.clone());assert_eq!(- modelled_sprite(Some(&themed), None).map(|sprite| sprite.path.as_str()),- Some("studio-ink/model-arrow.png")- );- assert_eq!(- modelled_sprite(Some(&themed), None).and_then(|sprite| sprite.model_depth_path.as_deref()),- Some("studio-ink/model-arrow-depth.png")+ modelled_sprite(Some(&themed), None).and_then(|sprite| sprite.sculpt.as_deref()),+ Some("studio-ink/arrow"));assert!(model_plan([0.0; 3], &themed, &track, 0.3, true).expect("plan").model.is_some());diff --git a/crates/compositor/src/lib.rs b/crates/compositor/src/lib.rsindex e8c97bf13..e26480cc6 100644--- a/crates/compositor/src/lib.rs+++ b/crates/compositor/src/lib.rs@@ -45,6 +45,7 @@ pub mod regions;// n'est spécifique à Linux.pub mod remux;pub mod scene;+pub mod sculpt;// Segmentation du sujet webcam (masque -> `t3`). Le module compile toujours ; sans la feature// `segmentation` ses deux entrées échouent proprement, ce qui garde le reste du crate// indépendant du choix de packaging d'ONNX Runtime.diff --git a/crates/compositor/src/scene.rs b/crates/compositor/src/scene.rsindex 12296b1eb..becb44895 100644--- a/crates/compositor/src/scene.rs+++ b/crates/compositor/src/scene.rs@@ -535,9 +535,9 @@ pub struct SceneCursor {pub smoothing: f32,pub motion_blur: f32,pub click_bounce: f32,- /// Curseur MODÉLISÉ en 3D (mode 15) : face raster et relief dédiés lorsqu'un état du thème en- /// fournit, sinon le sprite de cet état est extrudé. `#[serde(default)]` : absent des projets- /// et des JSON écrits avant le réglage, qui gardent donc le curseur plat.+ /// Curseur MODÉLISÉ en 3D (mode 15) : le curseur sculpté d'un état qui en a un+ /// (`SceneCursorSprite::sculpt`), sinon son sprite extrudé. `#[serde(default)]` : absent des+ /// projets et des JSON écrits avant le réglage, qui gardent donc le curseur plat.#[serde(default)]pub model3d: bool,pub clip_to_bounds: bool,@@ -568,10 +568,10 @@ pub struct SceneCursorSprite {/// que le curseur était agrandi — le bug que ce champ corrige.pub hotspot_x: f32,pub hotspot_y: f32,- /// Carte PNG en niveaux de gris, alignée sur la face du modèle (255 = relief maximal).- /// Les états sans carte gardent une face plate au sommet de leur extrusion.+ /// Le curseur sculpté de cet état en 3D, `"<thème>/<état>"` (`sculpt::sculpted_shape`) : les+ /// shaders le modèlent au lieu d'extruder le sprite, qui reste l'art en 2D.#[serde(default)]- pub model_depth_path: Option<String>,+ pub sculpt: Option<String>,}#[derive(Debug, Clone, Copy, Deserialize)]diff --git a/crates/compositor/src/sculpt.rs b/crates/compositor/src/sculpt.rsnew file mode 100644index 000000000..de9c4e65a--- /dev/null+++ b/crates/compositor/src/sculpt.rs@@ -0,0 +1,148 @@+//! Curseurs sculptés : la flèche et la main des cinq thèmes d'origine, modelées en volumes dans les+//! shaders (mode 15, `sculpt_proto`) au lieu d'extruder leur PNG — capsules et unions lissées,+//! extrusions arrondies, voxels, polyèdres taillés. Ce module en tient ce que la géométrie doit+//! savoir côté CPU : l'identifiant que lit le shader, et la boîte du modèle (`SpriteShape`) qui pose+//! le hotspot, règle la garde au sol et borne la boîte de dessin.+//!+//! Les formes sont écrites dans le repère du PROTOTYPE où elles ont été dessinées : hauteur du+//! curseur 1, x à droite, y VERS LE HAUT, z vers la caméra, l'écran en z = 0. Les constantes+//! ci-dessous sont le miroir des `SCULPT_*` des trois shaders.+//!+//! Les voxels de la flèche de Pixel Candy (`SCULPT_ARROWPIX`, `SCULPT_ARROWBACK`) sont son polygone+//! échantillonné : une cellule de 1/16 porte un voxel quand son centre est à plus de 0,01 dedans, un+//! bloc de la couche violette quand il est à moins de 0,9 cellule. Changer le polygone, c'est+//! régénérer ces deux tables.++use crate::frame_geometry::SpriteShape;++/// Unités du sprite par unité du prototype : un curseur sculpté (~1,03 de haut) a alors la taille+/// de la flèche plate des thèmes, qui occupe 87,5 % de son sprite.+pub const SCULPT_SCALE: f32 = 0.85;+/// Hauteur, dans le prototype, du z = 0 du modèle (le hotspot) : le dessus de la pointe de la+/// flèche, l'axe du bout de l'index.+const ZREF_ARROW: f32 = 0.2;+const ZREF_HAND: f32 = 0.185;+/// Le dessous de tous les modèles, dans le prototype.+const Z_LOW: f32 = 0.05;+/// Le plus haut : la table de la flèche taillée, l'étoile de Star Sprout sur la manchette.+const Z_HIGH_ARROW: f32 = 0.29;+const Z_HIGH_HAND: f32 = 0.4;+/// Boîtes des deux formes dans le prototype (x0, x1, haut), qui contiennent leurs cinq variantes :+/// couche violette des voxels, étoile, cristal compris. Leur hauteur est celle du sprite, 1 / SCULPT_SCALE :+/// le mode 15 tient le plus grand côté de la boîte pour 1 (`sprite_size`).+const BOX_ARROW: [f32; 3] = [-0.1, 0.75, 0.09];+const BOX_HAND: [f32; 3] = [-0.27, 0.73, 0.07];++/// Dans l'ordre des identifiants du shader.+const THEMES: [&str; 5] = ["studio-ink", "prism-glow", "pop-coral", "pixel-candy", "star-sprout"];++/// Le haut de la silhouette (y du prototype) : la couche violette des voxels dépasse la pointe+/// d'une cellule, la pointe arrondie de la flèche et le sommet de sa table taillée dépassent le+/// hotspot de 0,03, le bout de l'index y est.+fn silhouette_top(theme: usize, arrow: bool) -> f32 {+ match (THEMES[theme], arrow) {+ ("pixel-candy", _) => 0.0625,+ (_, true) => 0.03,+ (_, false) => 0.0,+ }+}++/// Le curseur sculpté que nomme la scène (`"<thème>/<état>"`, cf. `resolveCursorSprites`), sous+/// la forme que le mode 15 attend. `None` pour un nom inconnu : l'appelant extrude le sprite.+pub fn sculpted_shape(name: &str) -> Option<SpriteShape> {+ let (theme, state) = name.split_once('/')?;+ let theme = THEMES.iter().position(|t| *t == theme)?;+ let arrow = match state {+ "arrow" => true,+ "pointer" => false,+ _ => return None,+ };+ let [x0, x1, y1] = if arrow { BOX_ARROW } else { BOX_HAND };+ let (zref, z_high) = if arrow { (ZREF_ARROW, Z_HIGH_ARROW) } else { (ZREF_HAND, Z_HIGH_HAND) };+ let s = SCULPT_SCALE;+ // Repère du modèle : y vers le bas, le coin haut-gauche de la boîte est donc (x0, y1).+ let size = [(x1 - x0) * s, 1.0];+ Some(SpriteShape {+ size,+ hotspot: [-x0 * s / size[0], y1 * s],+ top: (y1 - silhouette_top(theme, arrow)) * s,+ max_height: (z_high - zref) * s,+ thick: (zref - Z_LOW) * s,+ sculpt: 1 + 2 * theme as u32 + u32::from(!arrow),+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ const NAMES: [&str; 10] = [+ "studio-ink/arrow",+ "studio-ink/pointer",+ "prism-glow/arrow",+ "prism-glow/pointer",+ "pop-coral/arrow",+ "pop-coral/pointer",+ "pixel-candy/arrow",+ "pixel-candy/pointer",+ "star-sprout/arrow",+ "star-sprout/pointer",+ ];++ #[test]+ fn each_theme_arrow_and_hand_has_its_own_id_in_shader_order() {+ for (k, name) in NAMES.iter().enumerate() {+ let shape = sculpted_shape(name).expect(name);+ assert_eq!(shape.sculpt, k as u32 + 1, "{name}");+ }+ }++ #[test]+ fn other_states_and_themes_keep_the_extruded_sprite() {+ for name in ["default/arrow", "pop-coral/text", "pop-coral", "", "pop-coral/arrow/x"] {+ assert!(sculpted_shape(name).is_none(), "{name}");+ }+ }++ /// Le hotspot est dans la boîte, sous le haut de la silhouette ; le modèle a une épaisseur et+ /// une hauteur ; la boîte a la hauteur du sprite, son plus grand côté, comme le veut le mode 15.+ #[test]+ fn the_box_holds_the_hotspot_and_the_silhouette_top() {+ for name in NAMES {+ let s = sculpted_shape(name).unwrap();+ assert!((0.0..1.0).contains(&s.hotspot[0]) && (0.0..1.0).contains(&s.hotspot[1]), "{name}");+ assert!(s.top <= s.hotspot[1] + 1e-6, "{name} : haut de silhouette sous le hotspot");+ assert!(s.thick > 0.05 && s.max_height > 0.0, "{name}");+ assert!(s.size[0] < 1.0 && s.size[1] == 1.0, "{name} : le plus grand côté n'est pas 1");+ }+ }++ /// Les constantes que ce module et les shaders partagent ne divergent pas.+ #[test]+ fn the_shaders_mirror_the_constants() {+ let shaders = [+ ("shaders.hlsl", include_str!("shaders.hlsl")),+ ("shaders.metal", include_str!("shaders.metal")),+ ("vk_shaders/layer.wgsl", include_str!("vk_shaders/layer.wgsl")),+ ];+ for (file, src) in shaders {+ for (name, value) in [+ ("SCULPT_SCALE", SCULPT_SCALE),+ ("SCULPT_ZREF_ARROW", ZREF_ARROW),+ ("SCULPT_ZREF_HAND", ZREF_HAND),+ ("SCULPT_HOVER", Z_LOW),+ ] {+ let line = src+ .lines()+ .find(|l| l.contains(name) && l.contains('='))+ .unwrap_or_else(|| panic!("{file} : {name} absent"));+ let v: f32 = line+ .split('=')+ .nth(1)+ .and_then(|r| r.trim().trim_end_matches(';').trim().parse().ok())+ .unwrap_or_else(|| panic!("{file} : {name} illisible : {line}"));+ assert_eq!(v, value, "{file} : {name}");+ }+ }+ }+}diff --git a/crates/compositor/src/shaders.hlsl b/crates/compositor/src/shaders.hlslindex c8b5c4e30..b5edd6e26 100644--- a/crates/compositor/src/shaders.hlsl+++ b/crates/compositor/src/shaders.hlsl@@ -49,9 +49,9 @@ Texture2D<float4> texImg : register(t2); // wallpaper image RGBA (fond, mode 6)// resolution du modele (256x144) ; l'upscale vers la resolution webcam est fait par le sampler// lineaire, ce qui est exactement le filtrage qu'on veut sur un masque.Texture2D<float> texMask : register(t3);-// Champ signé et hauteur du sprite de curseur (mode 15 seulement), RG16F, cf. `cursor_sdf.rs`.+// Champ de distance signé du sprite de curseur (mode 15 seulement), R16F, cf. `cursor_sdf.rs`.// Le sprite lui-même est en t2 (texImg), comme aux modes 7 et 13.-Texture2D<float2> texSdf : register(t4);+Texture2D<float> texSdf : register(t4);SamplerState samp : register(s0);// Plafond de la profondeur de champ du mode 8, en niveau de la pyramide demi-résolution (1.5 =@@ -410,24 +410,26 @@ float3 blur_webcam_bg(float2 uv, float intensity, float2 qpx, float2 local_px)}// ============ Curseur MODÉLISÉ (mode 15) ============-// Le sprite de l'état courant en objet 3D : sa silhouette (champ de distance signé tiré de son-// alpha par `cursor_sdf.rs`), extrudée avec un chanfrein, lancé de rayons par pixel. Le dessus-// porte l'art du sprite ; le chanfrein et les flancs, la couleur de son bord. Ce qui touche le-// modèle est éclairé ; ce qui le rate tombe sur le plan de l'écran, où l'on mesure l'ombre portée-// (marche vers la lumière, pénombre douce) et l'ombre de contact. La caméra est reconstruite à-// l'identique de `regions::rotate_point` + perspective P / (P - z) ; la pose, la caméra et la-// boîte de dessin viennent de `frame_geometry::cursor_model_cb`, qui documente les emplacements-// du cbuffer.+// L'état courant en objet 3D, lancé de rayons par pixel. Deux sortes d'objets :+// - un curseur SCULPTÉ (`trail_a.x` > 0) : la flèche ou la main d'un des cinq thèmes d'origine,+// modelée en volumes (capsules et unions lissées, extrusions arrondies, voxels, polyèdres+// taillés), chacune avec ses matières ;+// - sinon le sprite de l'état : sa silhouette (champ de distance signé tiré de son alpha par+// `cursor_sdf.rs`), extrudée avec un chanfrein. Le dessus porte l'art du sprite ; le chanfrein+// et les flancs, la couleur de son bord.+// Ce qui touche le modèle est éclairé par une LAMPE proche (un dégradé et un reflet même sur une+// face plane), avec ombres propres, occlusion et reflets d'un studio ; ce qui le rate tombe sur le+// plan de l'écran, où l'on mesure l'ombre portée (marche vers la lumière, pénombre douce) et+// l'ombre de contact. La caméra est reconstruite à l'identique de `regions::rotate_point` ++// perspective P / (P - z) ; la pose, la caméra et la boîte de dessin viennent de+// `frame_geometry::cursor_model_cb`, qui documente les emplacements du cbuffer.//-// Repère du MODÈLE : unité = plus grand côté du sprite, origine au hotspot de la face du dessus,-// x à droite, y vers le bas, z vers la caméra ; le dessous reste à -MODEL_THICK, le dessus peut-// monter jusqu'à MODEL_RELIEF_MAX. Le rect du sprite y commence en `color.rg` et mesure+// Repère du MODÈLE : unité = plus grand côté du sprite, origine au hotspot, x à droite, y vers le+// bas, z vers la caméra ; le dessous est à -`model_thick()`, le dessus monte jusqu'à `trail_a.z`.+// Le rect du sprite (ou la boîte du modèle sculpté) y commence en `color.rg` et mesure// `sprite_size()` (rapport w/h dans `radius_px`). Textures : t2 (texImg) = le sprite, RGBA ;-// t4 (texSdf) = champ signé en R et relief en G, RG16F, en-// unités du modèle, négatif dedans, sur le même rect.-// Constantes : miroir exact de `frame_geometry.rs` (MODEL_*).-static const float MODEL_THICK = 0.19;-static const float MODEL_RELIEF_MAX = 0.12;+// t4 (texSdf) = son champ, R16F, en unités du modèle, négatif dedans, sur le même rect.+// Constantes : miroir exact de `frame_geometry.rs` (MODEL_*) et de `sculpt.rs` (SCULPT_*).// Taille du sprite, repère du modèle : son plus grand côté vaut 1, `radius_px` porte w/h.float2 sprite_size()@@ -445,17 +447,25 @@ float sprite_texel()return CURSOR_SDF_UPSAMPLE / (float)max(w, h);}-// Épaisseur du modèle, écrasé au clic de `color.b` (`CursorPose::squash`).+// Épaisseur sous z = 0 (`SpriteShape::thick`), écrasée au clic de `color.b` (`CursorPose::squash`).float model_thick(){- return MODEL_THICK * color.b;+ return trail_a.y * color.b;+}++// Le curseur sculpté de ce dessin (`SpriteShape::sculpt`), 0 = le sprite extrudé.+int sculpt_id()+{+ return (int)(trail_a.x + 0.5);}static const float MODEL_BEVEL = 0.045;-// Direction VERS la lumière, repère caméra : haut-gauche, devant.+// Direction VERS la lumière, repère caméra : haut-gauche, devant. La lumière d'appoint, repère+// caméra aussi : à droite, un peu en bas, devant.static const float3 MODEL_LIGHT = float3(-0.4194, -0.5792, 0.6990);+static const float3 MODEL_FILL = float3(0.7557, 0.2519, 0.6046);+// Ambiance et diffus de l'appareil modelé (mode 17), qui garde son éclairage d'origine.static const float MODEL_AMBIENT = 0.36;static const float MODEL_DIFFUSE = 0.75;-static const float MODEL_SPECULAR = 0.45;// Profondeur (texels du sprite) à laquelle on lit la couleur du bord : assez loin de la frange// antialiasée, assez près pour rester dans le filet de l'art (~4 texels).static const float MODEL_RIM_INSET = 1.5;@@ -469,48 +479,476 @@ static const float MODEL_SHADOW_ALPHA = 0.5;static const float MODEL_CONTACT_RADIUS = 0.12;static const float MODEL_CONTACT_ALPHA = 0.5;-// Distance signée à la silhouette (plan xy du modèle). Dans le rect du sprite, le champ ; hors de-// lui, une borne inférieure exacte le long de la normale au rect : le sprite tient dans son rect,-// qui est convexe, donc |p - s|² >= |p - c|² + |c - s|² pour tout point s du sprite (c = p ramené-// dans le rect). Échantillonné au niveau 0 : la marche est une boucle à sortie anticipée.-float sd_sprite2(float2 p)+// ---- Curseurs sculptés ----+// Les formes sont écrites dans le repère du PROTOTYPE où elles ont été dessinées : hauteur du+// curseur 1, x à droite, y VERS LE HAUT, z vers la caméra, l'écran en z = 0 et le modèle posé à+// SCULPT_HOVER au-dessus. `sculpt_point` y amène un point du repère du modèle. Identifiant :+// 1 + 2 × thème + forme ; thèmes 0 Studio Ink, 1 Prism Glow, 2 Pop Coral, 3 Pixel Candy,+// 4 Star Sprout ; formes 0 flèche, 1 main. Id des matières : 1 corps, 2 liseré ou manchette,+// 3 étoile, 4 feuilles, 5 yeux, 6 face des voxels, 7 couche violette, 8 cristal.+static const float SCULPT_SCALE = 0.85;+static const float SCULPT_HOVER = 0.05;+static const float SCULPT_VOX = 0.0625;+static const float SCULPT_AR_ROUND = 0.03;+static const float SCULPT_HAND_ZC = 0.185;+// Hauteur, dans le prototype, du z = 0 du modèle : le dessus de la pointe de la flèche, l'axe du+// bout de l'index.+static const float SCULPT_ZREF_ARROW = 0.2;+static const float SCULPT_ZREF_HAND = 0.185;+// La lampe, à cette distance du centre du modèle (unités du modèle) dans la direction de la lumière.+static const float SCULPT_LAMP_DIST = 1.9;+// L'écran vu depuis le modèle (sa couleur n'est pas connue ici), linéaire : un gris moyen.+static const float3 SCULPT_SCREEN = float3(0.32, 0.32, 0.32);++float3 s_lin(float r, float g, float b){- float2 c = clamp(p, color.rg, color.rg + sprite_size());- float d = texSdf.SampleLevel(samp, (c - color.rg) / sprite_size(), 0.0).r;- float2 o = p - c;- float out2 = dot(o, o);- float e = max(d, 0.0);- return out2 > 0.0 ? sqrt(out2 + e * e) : d;+ return pow(float3(r, g, b), 2.2);}-// Hauteur du dessus : zéro pour un sprite sans carte, model-specific pour un modèle sculpté.-float model_top_height(float2 p)+float s_smin(float a, float b, float k){- float2 c = clamp(p, color.rg, color.rg + sprite_size());- float relief = texSdf.SampleLevel(samp, (c - color.rg) / sprite_size(), 0.0).g;- return clamp(relief * color.b, 0.0, MODEL_RELIEF_MAX);+ float h = max(k - abs(a - b), 0.0) / k;+ return min(a, b) - h * h * k * 0.25;+}++float2 s_opu(float2 a, float2 b)+{+ return a.x < b.x ? a : b;+}++float s_capsule(float3 p, float3 a, float3 b, float r)+{+ float3 pa = p - a, ba = b - a;+ float h = saturate(dot(pa, ba) / dot(ba, ba));+ return length(pa - ba * h) - r;+}++float s_round_box(float3 p, float3 b, float r)+{+ float3 q = abs(p) - b + r;+ return length(max(q, 0.0)) + min(max(q.x, max(q.y, q.z)), 0.0) - r;+}++float s_ellipsoid(float3 p, float3 r)+{+ float k0 = length(p / r);+ float k1 = length(p / (r * r));+ return k0 * (k0 - 1.0) / k1;+}++// Extrusion d'une distance 2D à arêtes arrondies : demi-hauteur h, rayon r.+float s_extrude(float d2, float z, float h, float r)+{+ float2 w = float2(d2 + r, abs(z) - h + r);+ return min(max(w.x, w.y), 0.0) + length(max(w, 0.0)) - r;+}++float2 s_rot(float2 v, float a)+{+ float c = cos(a), s = sin(a);+ return float2(c * v.x - s * v.y, s * v.x + c * v.y);+}++// La flèche : polygone à sept sommets, pointe à l'origine.+static const float2 SCULPT_ARROW[7] = {+ float2(0.0, 0.0), float2(0.0, -0.86), float2(0.215, -0.665), float2(0.37, -1.0),+ float2(0.53, -0.93), float2(0.38, -0.60), float2(0.64, -0.60)+};++float s_arrow2(float2 p)+{+ float d = dot(p - SCULPT_ARROW[0], p - SCULPT_ARROW[0]);+ float s = 1.0;+ int j = 6;+ [loop] for (int i = 0; i < 7; i++)+ {+ float2 e = SCULPT_ARROW[j] - SCULPT_ARROW[i];+ float2 w = p - SCULPT_ARROW[i];+ float2 b = w - e * saturate(dot(w, e) / dot(e, e));+ d = min(d, dot(b, b));+ bool c0 = p.y >= SCULPT_ARROW[i].y;+ bool c1 = p.y < SCULPT_ARROW[j].y;+ bool c2 = e.x * w.y > e.y * w.x;+ if ((c0 && c1 && c2) || (!c0 && !c1 && !c2))+ {+ s = -s;+ }+ j = i;+ }+ return s * sqrt(d);+}++float s_star5(float2 p, float r, float rf)+{+ const float2 k1 = float2(0.809016994375, -0.587785252292);+ const float2 k2 = float2(-0.809016994375, -0.587785252292);+ p.x = abs(p.x);+ p -= 2.0 * max(dot(k1, p), 0.0) * k1;+ p -= 2.0 * max(dot(k2, p), 0.0) * k2;+ p.x = abs(p.x);+ p.y -= r;+ float2 ba = rf * float2(-k1.y, k1.x) - float2(0.0, 1.0);+ float h = clamp(dot(p, ba) / dot(ba, ba), 0.0, r);+ return length(p - ba * h) * sign(p.y * ba.x - p.x * ba.y);+}++// La flèche en volume : extrusion arrondie, bombée d'un dôme qui plafonne avant l'axe médian de+// la silhouette (un dôme qui monterait encore y plierait le dessus).+float s_arrow_solid(float3 p, float h, float re, float dome)+{+ float d2 = s_arrow2(p.xy) - SCULPT_AR_ROUND;+ float hh = h + dome * smoothstep(0.0, 0.07, -d2);+ return s_extrude(d2, p.z - (SCULPT_HOVER + h + dome), hh, re);+}++// Le liseré de Studio Ink : un jonc posé sur le dessus, en retrait du bord.+float s_piping(float3 p, float ztop)+{+ float d2 = s_arrow2(p.xy) - SCULPT_AR_ROUND;+ return length(float2(d2 + 0.075, p.z - ztop)) - 0.017;+}++// Le gant : l'index levé, trois doigts repliés, le pouce, fondus dans la paume.+float s_glove(float3 p, float zc)+{+ float index = s_capsule(p, float3(0.0, -0.10, zc), float3(0.0, -0.52, zc), 0.098);+ float palm = s_round_box(p - float3(0.185, -0.70, zc), float3(0.255, 0.19, 0.105), 0.1);+ float f1 = s_capsule(p, float3(0.17, -0.57, zc + 0.012), float3(0.17, -0.41, zc + 0.045), 0.086);+ float f2 = s_capsule(p, float3(0.31, -0.59, zc + 0.01), float3(0.31, -0.45, zc + 0.04), 0.08);+ float f3 = s_capsule(p, float3(0.435, -0.625, zc + 0.005), float3(0.435, -0.52, zc + 0.03), 0.07);+ float thumb = s_capsule(p, float3(0.03, -0.77, zc + 0.03), float3(-0.165, -0.60, zc + 0.065), 0.082);+ float d = s_smin(palm, min(f1, min(f2, f3)), 0.035);+ d = s_smin(d, index, 0.05);+ return s_smin(d, thumb, 0.05);+}++// La manchette, ronde autour du poignet (elliptique en xz) : le gant y entre.+float s_cuff(float3 p, float zc)+{+ float3 q = p - float3(0.185, -0.925, zc);+ float2 ab = float2(0.272, 0.12);+ float e = (length(q.xz / ab) - 1.0) * min(ab.x, ab.y);+ return s_extrude(e, q.y, 0.07, 0.06);+}++// L'étoile de Star Sprout, face à la caméra, centrée en c : son visage et ses deux feuilles.+float2 s_sprout(float3 p, float3 c)+{+ float3 q = p - c;+ float st2 = s_star5(q.xy, 0.125, 0.52) - 0.022;+ float2 r = float2(s_extrude(st2, q.z, 0.038, 0.034), 3.0);+ float3 e = float3(abs(q.x) - 0.032, q.y + 0.005, q.z - 0.036);+ r = s_opu(r, float2(length(e) - 0.0135, 5.0));+ float3 l1 = q - float3(-0.04, 0.15, 0.0);+ l1.xy = s_rot(l1.xy, -0.6);+ float3 l2 = q - float3(0.045, 0.155, 0.0);+ l2.xy = s_rot(l2.xy, 0.7);+ float leaves = min(s_ellipsoid(l1, float3(0.03, 0.058, 0.02)), s_ellipsoid(l2, float3(0.03, 0.058, 0.02)));+ return s_opu(r, float2(leaves, 4.0));+}++// Pixel Candy : une ligne par entier, bit c = colonne c, ligne 0 juste sous la pointe. La flèche+// est le polygone échantillonné à 16 cellules par unité (`sculpt.rs` dit comment la régénérer) ;+// la main est dessinée à la main, un gant échantillonné fondant ses doigts. Les tables *BACK+// portent la couche violette, la face dilatée d'une cellule, décalée d'une ligne et d'une colonne.+static const int SCULPT_ARROWPIX[16] = { 0, 1, 3, 7, 31, 63, 127, 255, 511, 63, 55, 115, 113, 224, 224, 64 };+static const int SCULPT_ARROWBACK[18] = {+ 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 255, 511, 511, 999, 995, 960, 192+};+static const int SCULPT_HANDPIX[15] = { 4, 14, 14, 14, 110, 878, 7022, 7022, 8190, 8191, 8191, 8191, 8190, 4092, 4092 };+static const int SCULPT_HANDBACK[17] = {+ 28, 62, 62, 62, 510, 4094, 32766, 32766, 32766, 32767, 32767, 32767, 32767, 32767, 32766, 16380, 16380+};+// La couche violette de la main, une plage de colonnes par ligne (toutes pleines) : la distance+// exacte à son contour, pour l'ombre portée.+static const float2 SCULPT_HANDSPAN[17] = {+ float2(2.0, 4.0), float2(1.0, 5.0), float2(1.0, 5.0), float2(1.0, 5.0), float2(1.0, 8.0),+ float2(1.0, 11.0), float2(1.0, 14.0), float2(1.0, 14.0), float2(1.0, 14.0), float2(0.0, 14.0),+ float2(0.0, 14.0), float2(0.0, 14.0), float2(0.0, 14.0), float2(0.0, 14.0), float2(1.0, 14.0),+ float2(2.0, 13.0), float2(2.0, 13.0)+};++// Origine de la grille : la flèche part de sa pointe, la main de 2,5 cellules à sa gauche.+float2 s_grid_origin(int shape)+{+ return shape == 0 ? float2(0.0, 0.0) : float2(-2.5 * SCULPT_VOX, 0.0);+}++// Le bit `c` de la ligne `r` d'une table de `rows` lignes et `cols` colonnes. FXC évalue les deux+// côtés d'un `&&` : l'index est ramené dans la table avant la lecture, le test fait le reste.+bool s_bit(int row, int r, int c, int rows, int cols)+{+ return r >= 0 && r < rows && c >= 0 && c < cols && ((row >> clamp(c, 0, 31)) & 1) == 1;+}++// La cellule `id` (colonne, ligne, y vers le haut) porte-t-elle un voxel de la face ?+bool s_occ(float2 id, int shape)+{+ int c = (int)id.x;+ int r = -(int)id.y - 1;+ if (shape == 0)+ {+ return s_bit(SCULPT_ARROWPIX[clamp(r, 0, 15)], r, c, 16, 16);+ }+ return s_bit(SCULPT_HANDPIX[clamp(r, 0, 14)], r, c, 15, 13);+}++// … et un bloc de la couche violette.+bool s_occ_back(float2 id, int shape)+{+ int c = (int)id.x + 1;+ int r = -(int)id.y;+ if (shape == 0)+ {+ return s_bit(SCULPT_ARROWBACK[clamp(r, 0, 17)], r, c, 18, 17);+ }+ return s_bit(SCULPT_HANDBACK[clamp(r, 0, 16)], r, c, 17, 15);+}++// Chaque cellule pleine est un cube biseauté ; la couche violette est un étage plus bas. Hors du+// voisinage 3×3, une borne : une cellule au moins, et jamais plus près que la boîte de la forme.+float2 s_voxels(float3 p, int shape)+{+ float2 o = s_grid_origin(shape);+ float2 cell = floor((p.xy - o) / SCULPT_VOX);+ float2 bc = shape == 0 ? float2(0.33, -0.5) : float2(0.25, -0.47);+ float2 bh = shape == 0 ? float2(0.44, 0.61) : float2(0.48, 0.55);+ float2 bq = max(abs(p.xy - bc) - bh, 0.0);+ float bz = max(abs(p.z - (SCULPT_HOVER + 0.07)) - 0.07, 0.0);+ float far = max(SCULPT_VOX, sqrt(dot(bq, bq) + bz * bz));+ float dF = far;+ float dB = far;+ const float3 half_cell = float3(0.5 * SCULPT_VOX, 0.5 * SCULPT_VOX, 0.04);+ [loop] for (int j = -1; j <= 1; j++)+ {+ [loop] for (int i = -1; i <= 1; i++)+ {+ float2 id = cell + float2(i, j);+ float3 q = float3(p.xy - (o + (id + 0.5) * SCULPT_VOX), p.z);+ if (s_occ(id, shape))+ {+ dF = min(dF, s_round_box(q - float3(0.0, 0.0, SCULPT_HOVER + 0.1), half_cell, 0.009));+ }+ if (s_occ_back(id, shape))+ {+ dB = min(dB, s_round_box(q - float3(0.0, 0.0, SCULPT_HOVER + 0.04), half_cell, 0.009));+ }+ }+ }+ return dF < dB ? float2(dF, 6.0) : float2(dB, 7.0);+}++// Distance, dans le plan de l'écran, au contour de la couche violette de la main.+float s_pixel_hand_dist(float2 p)+{+ float d = 1e9;+ [loop] for (int r = 0; r < 17; r++)+ {+ float2 x = (SCULPT_HANDSPAN[r] + float2(-3.5, -2.5)) * SCULPT_VOX;+ float2 y = float2(-r, 1.0 - r) * SCULPT_VOX;+ float2 q = max(max(float2(x.x, y.x) - p, p - float2(x.y, y.y)), 0.0);+ d = min(d, length(q));+ }+ return d;+}++// Prism Glow est taillé, pas peint : chaque pièce est un polyèdre convexe (le max de ses plans),+// les facettes sont planes et la silhouette polygonale.++// Une arête d'un contour convexe de gemme (a -> b, sens trigonométrique) : sa paroi, une facette+// de rondiste raide, et deux facettes de couronne qui se rejoignent au milieu de l'arête. Les+// couronnes de toutes les arêtes se rejoignent en arêtes vives au-dessus du centre.+float s_gem_edge(float3 p, float2 a, float2 b, float z0)+{+ float2 e = b - a;+ float len = length(e);+ float2 d = e / len;+ float2 q = p.xy - a;+ float dist = dot(q, float2(-d.y, d.x));+ float along = abs(dot(q, d) - 0.5 * len);+ float z = p.z - z0;+ float girdle = (z - 0.035 - 2.2 * dist) * 0.4138;+ float crown = (z - 0.07 - 0.6 * dist + 0.18 * along) * 0.8438;+ return max(-dist, max(girdle, crown));+}++float s_gem_arrow(float3 p)+{+ float z0 = SCULPT_HOVER + 0.03;+ float slab = max(p.z - z0 - 0.2, z0 - 0.03 - p.z);+ float head = max(slab, max(s_gem_edge(p, float2(-0.02, 0.03), float2(-0.02, -0.88), z0),+ max(s_gem_edge(p, float2(-0.02, -0.88), float2(0.66, -0.61), z0),+ s_gem_edge(p, float2(0.66, -0.61), float2(-0.02, 0.03), z0))));+ float tail = max(slab, max(max(s_gem_edge(p, float2(0.215, -0.665), float2(0.37, -1.0), z0),+ s_gem_edge(p, float2(0.37, -1.0), float2(0.53, -0.93), z0)),+ max(s_gem_edge(p, float2(0.53, -0.93), float2(0.38, -0.60), z0),+ s_gem_edge(p, float2(0.38, -0.60), float2(0.215, -0.665), z0))));+ return min(head, tail);+}++// Capsule taillée a -> b : un prisme hexagonal coiffé en b de deux couronnes de facettes+// décalées et d'une facette sommitale, tous les plans tangents à la sphère du bout.+float s_facet_capsule(float3 p, float3 a, float3 b, float r, float spin)+{+ float3 u = normalize(b - a);+ float3 v = normalize(cross(u, float3(0.0, 0.0, 1.0)));+ float3 w = cross(u, v);+ float3 q = p - b;+ float h = dot(q, u);+ float2 rad = float2(dot(q, v), dot(q, w));+ float d = max(h - r, -dot(p - a, u) - r);+ [loop] for (int k = 0; k < 6; k++)+ {+ float an = spin + k * 1.0471976;+ float s = dot(rad, float2(cos(an), sin(an)));+ d = max(d, s - r);+ d = max(d, dot(rad, float2(cos(an + 0.5236), sin(an + 0.5236))) * 0.8660 + h * 0.5 - r);+ d = max(d, s * 0.5 + h * 0.8660 - r);+ }+ return d;+}++// Ellipsoïde taillé : les plans tangents dans dix directions du premier octant, reportées dans+// les huit. Une pierre aux facettes de taille égale.+static const float3 SCULPT_FACETS[10] = {+ float3(1.0, 0.0, 0.0), float3(0.0, 1.0, 0.0), float3(0.0, 0.0, 1.0),+ float3(0.7071, 0.7071, 0.0), float3(0.7071, 0.0, 0.7071), float3(0.0, 0.7071, 0.7071),+ float3(0.5774, 0.5774, 0.5774), float3(0.4472, 0.0, 0.8944), float3(0.0, 0.4472, 0.8944),+ float3(0.3015, 0.3015, 0.9045)+};++float s_facet_ellipsoid(float3 p, float3 r)+{+ float3 q = abs(p);+ float d = -1e9;+ [loop] for (int i = 0; i < 10; i++)+ {+ d = max(d, dot(q, SCULPT_FACETS[i]) - length(r * SCULPT_FACETS[i]));+ }+ return d;+}++// Le gant des autres thèmes, mêmes os, taillé en facettes.+float s_crystal_hand(float3 p)+{+ float zc = SCULPT_HAND_ZC;+ float d = s_facet_ellipsoid(p - float3(0.185, -0.70, zc), float3(0.3, 0.235, 0.125));+ d = min(d, s_facet_capsule(p, float3(0.0, -0.52, zc), float3(0.0, -0.10, zc), 0.098, 0.3));+ d = min(d, s_facet_capsule(p, float3(0.17, -0.57, zc + 0.012), float3(0.17, -0.41, zc + 0.045), 0.086, 0.1));+ d = min(d, s_facet_capsule(p, float3(0.31, -0.59, zc + 0.01), float3(0.31, -0.45, zc + 0.04), 0.08, 0.5));+ d = min(d, s_facet_capsule(p, float3(0.435, -0.625, zc + 0.005), float3(0.435, -0.52, zc + 0.03), 0.07, 0.2));+ return min(d, s_facet_capsule(p, float3(0.03, -0.77, zc + 0.03), float3(-0.165, -0.60, zc + 0.065), 0.082, 0.7));+}++// Le modèle `shape` du thème `theme`, repère du prototype : (distance, id de matière).+float2 sculpt_proto(float3 p, int theme, int shape)+{+ if (theme == 3)+ {+ return s_voxels(p, shape);+ }+ if (theme == 1)+ {+ return float2(shape == 0 ? s_gem_arrow(p) : s_crystal_hand(p), 8.0);+ }+ float2 body;+ float3 star;+ if (shape == 0)+ {+ float h = 0.075, re = 0.03, dome = 0.0;+ if (theme == 2)+ {+ h = 0.07;+ re = 0.06;+ dome = 0.035;+ }+ if (theme == 4)+ {+ h = 0.07;+ re = 0.055;+ dome = 0.025;+ }+ float2 r = float2(s_arrow_solid(p, h, re, dome), 1.0);+ if (theme == 0)+ {+ r = s_opu(r, float2(s_piping(p, SCULPT_HOVER + 2.0 * h - 0.004), 2.0));+ }+ body = r;+ star = float3(0.57, -0.86, SCULPT_HOVER + 2.0 * h + dome);+ }+ else+ {+ body = s_opu(float2(s_glove(p, SCULPT_HAND_ZC), 1.0), float2(s_cuff(p, SCULPT_HAND_ZC), 2.0));+ star = float3(0.185, -0.93, SCULPT_HAND_ZC + 0.15);+ }+ // L'étoile de Star Sprout : un seul appel pour les deux formes (FXC recopie chaque appel).+ return theme == 4 ? s_opu(body, s_sprout(p, star)) : body;+}++// Repère du modèle -> prototype. L'écrasement du clic ne raccourcit que z, autour du hotspot.+float3 sculpt_point(float3 q)+{+ float zref = (sculpt_id() - 1) % 2 == 0 ? SCULPT_ZREF_ARROW : SCULPT_ZREF_HAND;+ return float3(q.x, -q.y, q.z / max(color.b, 1e-3)) / SCULPT_SCALE + float3(0.0, 0.0, zref);+}++// Une distance du prototype en unités du modèle : écrasé, z raccourcit, d'où le min (une borne+// inférieure reste une borne inférieure).+float sculpt_units()+{+ return SCULPT_SCALE * min(color.b, 1.0);}-// Distance signée au modèle : le contour rentré du chanfrein, épaisseur rentrée du chanfrein, puis-// regonflé : les arêtes du dessus et du dessous sont arrondies de MODEL_BEVEL.-float sd_model(float3 p)+// Le curseur sculpté en `q` (repère du modèle) : distance et id de matière. `occ` : ce qui porte+// l'ombre sur l'écran. La borne des plans d'une gemme et le champ des voxels sont de mauvaises+// distances loin de la surface : la pénombre s'y strie, ou s'arrête net au bord de la boîte des+// voxels. Le cristal porte donc l'ombre de la forme lisse de Pop Coral, les voxels celle de leur+// contour extrudé sur toute leur hauteur.+float2 sculpt_eval(float3 q, bool occ){- float top = model_top_height(p.xy);- float thick = model_thick();- float half_t = (top + thick) * 0.5;- float center_z = (top - thick) * 0.5;- float2 w = float2(sd_sprite2(p.xy) + MODEL_BEVEL, abs(p.z - center_z) - (half_t - MODEL_BEVEL));- return min(max(w.x, w.y), 0.0) + length(max(w, 0.0)) - MODEL_BEVEL;+ int id = sculpt_id() - 1;+ int theme = id / 2, shape = id % 2;+ float3 p = sculpt_point(q);+ float2 r;+ if (occ && theme == 3)+ {+ float d2 = shape == 0 ? s_arrow2(p.xy) - 1.2 * SCULPT_VOX : s_pixel_hand_dist(p.xy);+ float dz = abs(p.z - (SCULPT_HOVER + 0.07)) - 0.07;+ r = float2(length(max(float2(d2, dz), 0.0)) + min(max(d2, dz), 0.0), 7.0);+ }+ else+ {+ r = sculpt_proto(p, occ && theme == 1 ? 2 : theme, shape);+ }+ return float2(r.x * sculpt_units(), r.y);}-// Normale par le gradient du champ (tétraèdre, quatre évaluations).-float3 model_normal(float3 p)+// Distance signée à la silhouette du sprite (plan xy du modèle). Dans le rect du sprite, le champ ;+// hors de lui, une borne inférieure exacte le long de la normale au rect : le sprite tient dans son+// rect, qui est convexe, donc |p - s|² >= |p - c|² + |c - s|² pour tout point s du sprite (c = p+// ramené dans le rect). Échantillonné au niveau 0 : la marche est une boucle à sortie anticipée.+float sd_sprite2(float2 p){- const float e = 0.002;- return normalize(float3(1, -1, -1) * sd_model(p + float3(1, -1, -1) * e) +- float3(-1, -1, 1) * sd_model(p + float3(-1, -1, 1) * e) +- float3(-1, 1, -1) * sd_model(p + float3(-1, 1, -1) * e) +- float3(1, 1, 1) * sd_model(p + float3(1, 1, 1) * e));+ float2 c = clamp(p, color.rg, color.rg + sprite_size());+ float d = texSdf.SampleLevel(samp, (c - color.rg) / sprite_size(), 0.0);+ float2 o = p - c;+ float out2 = dot(o, o);+ float e = max(d, 0.0);+ return out2 > 0.0 ? sqrt(out2 + e * e) : d;+}++// Le modèle en `p` : distance signée et id de matière (0 pour un sprite). Sculpté, sa forme+// (`sculpt_eval`, dont `occ`) ; sinon le contour rentré du chanfrein, épaisseur rentrée du+// chanfrein, puis regonflé : les arêtes du dessus et du dessous sont arrondies de MODEL_BEVEL.+float2 model_eval(float3 p, bool occ)+{+ if (sculpt_id() > 0)+ {+ return sculpt_eval(p, occ);+ }+ float half_t = model_thick() * 0.5;+ float2 w = float2(sd_sprite2(p.xy) + MODEL_BEVEL, abs(p.z + half_t) - (half_t - MODEL_BEVEL));+ return float2(min(max(w.x, w.y), 0.0) + length(max(w, 0.0)) - MODEL_BEVEL, 0.0);}// Entrée/sortie d'un rayon dans une boîte alignée (x = entrée, y = sortie ; x >= y : raté).@@ -562,30 +1000,6 @@ float3 plane_to_model(float3 v, ModelFrame f)return float3(x, y * f.cp + v.z * f.sp, -y * f.sp + v.z * f.cp);}-// Pénombre vers la lumière depuis `o` (1 = éclairé, 0 = dans l'ombre). Marche bornée à la boîte-// du modèle élargie de la portée de la pénombre, pas bornés, sortie dès que l'ombre est pleine.-float model_soft_shadow(float3 o, float3 l, float3 lo, float3 hi)-{- float2 tb = ray_box(o, l, lo - MODEL_SHADOW_PAD, hi + MODEL_SHADOW_PAD);- if (tb.x >= tb.y || tb.y <= 0.0)- {- return 1.0;- }- float res = 1.0;- float t = max(tb.x, 0.004);- [loop] for (int k = 0; k < 32; k++)- {- float d = sd_model(o + l * t);- res = min(res, MODEL_SOFTNESS * d / t);- if (res < 0.002 || t > tb.y)- {- break;- }- t += clamp(d, 0.01, 0.2);- }- res = saturate(res);- return res * res * (3.0 - 2.0 * res);-}// Couleur de la matière au point `p` du plan xy (alpha droit) : l'art du sprite, lu au plus à// MODEL_RIM_INSET texels du bord vers l'intérieur. Le dessus garde donc son art, et le chanfrein,@@ -601,17 +1015,200 @@ float3 model_albedo(float2 p)return texImg.SampleLevel(samp, (q - color.rg) / sprite_size(), 0.0).rgb;}-// Couleur (alpha droit) d'un point de la surface vu le long de `rd`.-float3 model_shade(float3 q, float3 rd, float3 l)+struct SculptMat{- float3 n = model_normal(q);- float3 albedo = model_albedo(q.xy);- float diffuse = saturate(dot(n, l));- // Reflet sur les arrondis seulement : une face plane l'allumerait d'un bloc (la lumière est- // directionnelle), et le dessus sombre d'un sprite virerait au gris à chaque clic.- float gloss = 1.0 - smoothstep(0.97, 0.995, abs(n.z));- float spec = gloss * pow(saturate(dot(n, normalize(l - rd))), 110.0);- return albedo * (MODEL_AMBIENT + MODEL_DIFFUSE * diffuse) + MODEL_SPECULAR * spec;+ float3 alb; // albédo, linéaire+ float rough;+ float spec;+ float sss; // enveloppe du diffus (matières tendres : caoutchouc, céramique)+ float refl;+};++SculptMat s_mat(float3 alb, float rough, float spec, float sss, float refl)+{+ SculptMat m;+ m.alb = alb;+ m.rough = rough;+ m.spec = spec;+ m.sss = sss;+ m.refl = refl;+ return m;+}++// Couleur de face du voxel qui porte `p` (prototype) : menthe où le bord regarde en bas à gauche,+// rose pâle où il regarde en haut à droite, rose dedans.+float3 s_pixel_colour(float3 p, int shape)+{+ float2 id = floor((p.xy - s_grid_origin(shape)) / SCULPT_VOX);+ if (!s_occ(id + float2(-1.0, 0.0), shape) || !s_occ(id + float2(0.0, -1.0), shape))+ {+ return s_lin(0.52, 0.91, 0.77);+ }+ if (!s_occ(id + float2(1.0, 0.0), shape) || !s_occ(id + float2(0.0, 1.0), shape))+ {+ return s_lin(1.0, 0.78, 0.87);+ }+ return s_lin(1.0, 0.50, 0.71);+}++// La matière `mat` (id de `sculpt_proto`) au point `p` du prototype.+SculptMat sculpt_material(float mat, float3 p, int theme, int shape)+{+ bool primary = mat < 1.5;+ if (theme == 0)+ {+ if (shape == 0 && primary) return s_mat(s_lin(0.10, 0.10, 0.115), 0.3, 0.2, 0.0, 0.9);+ if (shape == 0) return s_mat(s_lin(0.94, 0.91, 0.84), 0.45, 0.4, 0.2, 0.3);+ if (primary) return s_mat(s_lin(0.95, 0.92, 0.85), 0.55, 0.35, 0.35, 0.25);+ return s_mat(s_lin(0.17, 0.18, 0.22), 0.35, 0.6, 0.0, 0.6);+ }+ if (theme == 2)+ {+ if (shape == 0) return s_mat(s_lin(1.0, 0.40, 0.30), 0.5, 0.45, 0.4, 0.25);+ if (primary) return s_mat(s_lin(1.0, 0.79, 0.16), 0.5, 0.45, 0.4, 0.25);+ return s_mat(s_lin(0.18, 0.20, 0.29), 0.4, 0.5, 0.0, 0.4);+ }+ if (theme == 4)+ {+ if (primary && shape == 0) return s_mat(s_lin(0.62, 0.91, 0.78), 0.22, 0.8, 0.25, 0.6);+ if (primary) return s_mat(s_lin(0.96, 0.94, 0.88), 0.5, 0.35, 0.35, 0.25);+ if (mat < 2.5) return s_mat(s_lin(0.62, 0.91, 0.78), 0.25, 0.7, 0.25, 0.5);+ if (mat < 3.5) return s_mat(s_lin(1.0, 0.80, 0.20), 0.3, 0.6, 0.3, 0.4);+ if (mat < 4.5) return s_mat(s_lin(0.38, 0.80, 0.55), 0.35, 0.5, 0.35, 0.3);+ return s_mat(s_lin(0.16, 0.12, 0.10), 0.2, 0.8, 0.0, 0.5);+ }+ if (mat < 6.5) return s_mat(s_pixel_colour(p, shape), 0.45, 0.35, 0.15, 0.2);+ return s_mat(s_lin(0.36, 0.18, 0.54), 0.45, 0.35, 0.1, 0.2);+}++// L'environnement du studio vu du modèle : l'écran dessous, la pièce au-dessus (z du modèle), une+// boîte à lumière dans la direction de la lampe et une bande dans celle de l'appoint. Un matériau+// rugueux les voit plus larges et plus ternes.+float3 model_env(float3 d, float rough, float3 l, float3 fill)+{+ float3 col = lerp(SCULPT_SCREEN * 0.9, s_lin(0.82, 0.85, 0.92) * 0.55, smoothstep(-0.15, 0.35, d.z));+ float w = rough * 0.3;+ float k = 1.0 - rough * 0.6;+ col += s_lin(1.0, 0.97, 0.92) * 5.0 * k * smoothstep(0.90 - w, 0.97, dot(d, l));+ col += s_lin(0.85, 0.9, 1.0) * 1.6 * k * smoothstep(0.93 - w, 0.98, dot(d, fill));+ return col;+}++// Cyan, bleu, violet, orchidée.+float3 s_gem(float k)+{+ k = saturate(k) * 3.0;+ float3 a = s_lin(0.20, 0.95, 1.0);+ float3 b = s_lin(0.15, 0.42, 1.0);+ float3 c = s_lin(0.45, 0.25, 0.95);+ float3 d = s_lin(0.88, 0.50, 1.0);+ if (k < 1.0) return lerp(a, b, k);+ if (k < 2.0) return lerp(b, c, k - 1.0);+ return lerp(c, d, k - 2.0);+}++// Le cristal : la teinte vient d'où la facette regarde et d'où elle plie la vue (lues y vers le+// haut, comme au prototype) ; la dispersion sépare le décalage par canal. Les facettes tournées+// vers la lampe sont cyan, les autres violettes.+float3 model_shade_crystal(float3 n, float3 rd, float3 L, float fall, float3 l, float3 fill)+{+ float cosi = saturate(dot(-rd, n));+ float F = 0.04 + 0.96 * pow(1.0 - cosi, 5.0);+ float3 t = refract(rd, n, 1.0 / 1.6);+ float k = 0.42 + 0.9 * dot(float2(n.x, -n.y), float2(0.7557, -0.6549))+ + 0.6 * dot(float2(t.x, -t.y), float2(0.6, -0.8));+ float3 body = float3(s_gem(k - 0.08).r, s_gem(k).g, s_gem(k + 0.08).b);+ float3 col = body * (0.1 + 1.8 * fall * pow(max(dot(n, L), 0.0), 2.5));+ // Éclat : la vue rebondit sur le dos plat et allume la facette quand elle trouve la lampe.+ col += body * model_env(reflect(t, float3(0.0, 0.0, 1.0)) * float3(1.0, 1.0, -1.0), 0.15, l, fill) * 0.5;+ col += pow(max(dot(reflect(rd, n), L), 0.0), 30.0) * 2.0;+ col += model_env(reflect(rd, n), 0.05, l, fill) * F;+ col += s_lin(0.5, 0.9, 1.0) * pow(1.0 - cosi, 4.0) * 0.6;+ return col;+}++// Khronos PBR Neutral : garde les teintes, ne comprime que les hautes lumières ; puis sRGB.+float3 model_tonemap(float3 c)+{+ const float start = 0.76;+ float x = min(c.r, min(c.g, c.b));+ c -= x < 0.08 ? x - 6.25 * x * x : 0.04;+ float peak = max(c.r, max(c.g, c.b));+ if (peak >= start)+ {+ const float d = 1.0 - start;+ float np = 1.0 - d * d / (peak + d - start);+ c *= np / peak;+ float g = 1.0 - 1.0 / (0.15 * (peak - np) + 1.0);+ c = lerp(c, float3(np, np, np), g);+ }+ return pow(saturate(c), 1.0 / 2.2);+}+++// Couleur (alpha droit, sRGB) du point `q` du modèle, de normale `n`, vu le long de `rd`. La+// lumière est une LAMPE (direction `L`, intensité `fall` rapportée au centre du modèle), pas un+// soleil : un dégradé et un reflet même sur une face plane. `sh` : pénombre du modèle sur+// lui-même ; `ao` : occlusion ; `mat` : id de matière d'un sculpté ; `l` et `fill` : directions de+// la lumière et de l'appoint. Peu d'ambiance : le côté à l'abri de la lampe tombe dans l'ombre,+// dans un ton plus profond de la matière elle-même (l'albédo compté deux fois), pas dans un voile+// gris.+float3 model_shade(float3 q, float3 n, float3 rd, float3 L, float fall, float sh, float ao, float mat,+ float3 l, float3 fill)+{+ int id = sculpt_id();+ if (id > 0 && (id - 1) / 2 == 1)+ {+ return model_tonemap(model_shade_crystal(n, rd, L, fall, l, fill));+ }+ SculptMat m;+ // Sur un sprite, reflets et brillance sur les arrondis seulement : le dessus plat d'un sprite+ // sombre virerait au gris sous la lampe.+ float gloss = 1.0;+ if (id > 0)+ {+ // La matière d'un voxel se lit juste sous la surface : son flanc lit sa propre cellule.+ float3 p = sculpt_point(q) - float3(n.x, -n.y, n.z) * 0.01;+ m = sculpt_material(mat, p, (id - 1) / 2, (id - 1) % 2);+ }+ else+ {+ m = s_mat(pow(model_albedo(q.xy), 2.2), 0.45, 0.35, 0.2, 0.3);+ gloss = 1.0 - smoothstep(0.97, 0.995, abs(n.z));+ }+ float3 key = s_lin(1.0, 0.97, 0.93) * 2.1 * fall;+ float ndl = dot(n, L);+ float wrap = 0.5 * m.sss;+ float dif = saturate((ndl + wrap) / (1.0 + wrap)) * lerp(sh, 1.0, 0.15 * m.sss);+ float ndh = saturate(dot(n, normalize(L - rd)));+ float shin = exp2(10.0 * (1.0 - m.rough) + 1.0);+ // Un lobe net selon la rugosité, plus un lustre large : les formes arrondies se lisent sous+ // tous les angles.+ float spe = (pow(ndh, shin) * (shin + 8.0) / 25.0 + 0.15 * pow(ndh, 8.0)) * sh * saturate(ndl * 4.0);+ float fre = pow(1.0 - saturate(dot(n, -rd)), 5.0);+ float3 amb = lerp(SCULPT_SCREEN * 0.12, s_lin(0.88, 0.92, 1.0) * 0.22, 0.5 + 0.5 * n.z);+ float3 fl = s_lin(0.85, 0.9, 1.0) * saturate(dot(n, fill)) * 0.12;+ float3 col = m.alb * (key * dif + (amb + fl) * ao * lerp(float3(1.0, 1.0, 1.0), m.alb, 0.5));+ col += key * spe * m.spec * gloss;+ col += model_env(reflect(rd, n), m.rough, l, fill) * m.refl * (0.04 + 0.96 * fre) * ao * gloss;+ col += s_lin(0.9, 0.95, 1.0) * fre * 0.08 * ao * sh;+ return model_tonemap(col);+}++// Les passes de la boucle unique de `cursor_model`, dans l'ordre. Chaque tour n'évalue le modèle+// QU'UNE fois (`model_eval`) : FXC recopie une fonction à chaque appel, et un curseur sculpté est+// assez gros pour qu'un appel par passe multiplie par neuf le temps de compilation de ps_main.+static const int STAGE_MARCH = 0; // le rayon de vue jusqu'au modèle (96 pas au plus)+static const int STAGE_NORMAL = 1; // quatre sondes en tétraèdre autour du point touché+static const int STAGE_AO = 2; // cinq sondes le long de la normale, jusqu'à 0,08 du prototype+static const int STAGE_SELF = 3; // pénombre du modèle sur lui-même, vers la lampe (32 pas)+static const int STAGE_PLANE = 4; // le point du plan : son contact, puis sa pénombre (32 pas)+static const int STAGE_DONE = 5;++// Sonde `k` de la normale, sommet d'un tétraèdre.+float3 model_tetra(int k)+{+ return 0.5773 * (2.0 * float3((((k + 3) >> 1) & 1), ((k >> 1) & 1), (k & 1)) - 1.0);}float4 cursor_model(float2 local)@@ -628,7 +1225,7 @@ float4 cursor_model(float2 local)float3 tip = src_prev.xyz;// La boîte du modèle : le rect du sprite, sur toute l'épaisseur.float3 lo = float3(color.rg, -model_thick());- float3 hi = float3(color.rg + sprite_size(), MODEL_RELIEF_MAX);+ float3 hi = float3(color.rg + sprite_size(), trail_a.z);// Le rayon de ce pixel : de la caméra (0, 0, P) à travers le pixel sur le plan image z = 0.// Le plan est translaté de mb.zw dans le repère caméra (caméra réelle, 0 sous un angle fixe).@@ -637,66 +1234,198 @@ float4 cursor_model(float2 local)float3 ro = plane_to_model((world_to_plane(float3(-mb.z, -mb.w, persp), f) - tip) / unit, f);float3 rd = plane_to_model(world_to_plane(dw / dlen, f), f);float3 l = plane_to_model(world_to_plane(MODEL_LIGHT, f), f);+ float3 fill = plane_to_model(world_to_plane(MODEL_FILL, f), f);// Le plan de l'écran dans le repère du modèle : dot(p, nz) = hz.float3 nz = plane_to_model(float3(0.0, 0.0, 1.0), f);float hz = -tip.z / unit;+ // Un sculpté n'est pas une borne exacte partout (dôme, ellipsoïdes) : pas raccourcis.+ float stride = sculpt_id() > 0 ? 0.85 : 1.0;+ // La lampe, à SCULPT_LAMP_DIST du centre du modèle dans la direction de la lumière.+ float3 lamp = float3(color.rg + sprite_size() * 0.5, 0.0) + l * SCULPT_LAMP_DIST;- // Le modèle. Silhouette antialiasée : un rayon qui la frôle à moins d'un pixel la couvre en- // partie (`best`, la plus petite distance rencontrée, en pixels).- float cov = 0.0;- float3 rgb = 0.0;+ // Silhouette antialiasée : un rayon qui frôle le modèle à moins d'un pixel le couvre en partie+ // (`best`, la plus petite distance rencontrée, en pixels).float2 tb = ray_box(ro, rd, lo - 0.02, hi + 0.02);- if (tb.x < tb.y && tb.y > 0.0)+ int stage = tb.x < tb.y && tb.y > 0.0 ? STAGE_MARCH : STAGE_DONE;+ // Le point du plan derrière le pixel est à régler avant le prochain tour.+ bool plane_next = stage == STAGE_DONE;+ int k = 0;+ float t = max(tb.x, 0.0);+ float best = 1e9;+ float t_best = t;+ float mat = 0.0;+ float cov = 0.0;+ float3 q = 0.0;+ float3 n = 0.0;+ float3 L = 0.0;+ float ao = 1.0;+ float sh = 1.0;+ // Marche d'une ombre : x = distance parcourue, y = sortie de la boîte élargie ; `res` sa+ // pénombre.+ float2 ts = 0.0;+ float res = 1.0;+ float3 g = 0.0;+ float inside = 0.0;+ float contact = 0.0;+ float dropped = 0.0;+ [loop] for (int it = 0; it < 180; it++){- float t = max(tb.x, 0.0);- float best = 1e9;- float t_best = t;- bool hit = false;- [loop] for (int k = 0; k < 64; k++)+ if (plane_next)+ {+ // Le plan, là où le modèle ne couvre pas tout le pixel : ombre portée et ombre de+ // contact, seulement à l'intérieur de l'écran (`mb.xy` = sa demi-taille, px du plan).+ plane_next = false;+ stage = STAGE_DONE;+ float denom = dot(rd, nz);+ if (cov < 1.0 && denom < -1e-4)+ {+ g = ro + rd * ((hz - dot(ro, nz)) / denom);+ float3 gp = tip + unit * model_to_plane(g, f);+ inside = saturate(min(mb.x - abs(gp.x), mb.y - abs(gp.y)) + 0.5);+ if (inside > 0.0)+ {+ stage = STAGE_PLANE;+ k = 0;+ ts = 0.0;+ }+ }+ }+ float3 pos;+ if (stage == STAGE_MARCH)+ {+ pos = ro + rd * t;+ }+ else if (stage == STAGE_NORMAL)+ {+ pos = q + 0.002 * model_tetra(k);+ }+ else if (stage == STAGE_AO)+ {+ pos = q + (0.01 + 0.0175 * k) * SCULPT_SCALE * n;+ }+ else if (stage == STAGE_SELF)+ {+ pos = q + n * 0.003 + L * ts.x;+ }+ else if (stage == STAGE_PLANE)+ {+ pos = g + l * ts.x;+ }+ else+ {+ break;+ }+ float2 m = model_eval(pos, stage == STAGE_PLANE);+ float d = m.x;+ if (stage == STAGE_MARCH){- float d = sd_model(ro + rd * t);float fp = t / dlen;- if (d < 0.1 * fp)+ bool hit = d < 0.1 * fp;+ if (hit || d / fp < best){- hit = true;+ best = hit ? 0.0 : d / fp;t_best = t;- break;+ mat = m.y;}- if (d / fp < best)+ t += d * stride;+ k++;+ if (hit || t > tb.y || k == 96){- best = d / fp;- t_best = t;+ cov = saturate(1.0 - best);+ if (cov > 0.0)+ {+ q = ro + rd * t_best;+ stage = STAGE_NORMAL;+ k = 0;+ }+ else+ {+ plane_next = true;+ }}- t += d;- if (t > tb.y)+ }+ else if (stage == STAGE_NORMAL)+ {+ n += model_tetra(k) * d;+ k++;+ if (k == 4){- break;+ n = normalize(n);+ stage = STAGE_AO;+ k = 0;+ ao = 0.0;}}- cov = hit ? 1.0 : saturate(1.0 - best);- if (cov > 0.0)+ else if (stage == STAGE_AO){- rgb = model_shade(ro + rd * t_best, rd, l);+ ao += ((0.01 + 0.0175 * k) * SCULPT_SCALE - d) * pow(0.85, k);+ k++;+ if (k == 5)+ {+ ao = saturate(1.0 - 3.5 * ao / SCULPT_SCALE);+ L = normalize(lamp - q);+ float2 tbs = ray_box(q + n * 0.003, L, lo - MODEL_SHADOW_PAD, hi + MODEL_SHADOW_PAD);+ if (tbs.x < tbs.y && tbs.y > 0.0)+ {+ stage = STAGE_SELF;+ k = 0;+ ts = float2(max(tbs.x, 0.004), tbs.y);+ res = 1.0;+ }+ else+ {+ plane_next = true;+ }+ }}- }-- // Le plan, là où le modèle ne couvre pas tout le pixel : ombre portée et ombre de contact,- // seulement à l'intérieur de l'écran (`mb.xy` = sa demi-taille, px du plan).- float shadow = 0.0;- float denom = dot(rd, nz);- if (cov < 1.0 && denom < -1e-4)- {- float3 g = ro + rd * ((hz - dot(ro, nz)) / denom);- float3 gp = tip + unit * model_to_plane(g, f);- float inside = saturate(min(mb.x - abs(gp.x), mb.y - abs(gp.y)) + 0.5);- if (inside > 0.0)+ else if (stage == STAGE_SELF)+ {+ res = min(res, MODEL_SOFTNESS * d / ts.x);+ ts.x += clamp(d, 0.01, 0.2);+ k++;+ if (res < 0.002 || ts.x > ts.y || k == 32)+ {+ res = saturate(res);+ sh = res * res * (3.0 - 2.0 * res);+ plane_next = true;+ }+ }+ else if (k == 0){- float dropped = 1.0 - model_soft_shadow(g, l, lo, hi);- float contact = 1.0 - smoothstep(0.0, MODEL_CONTACT_RADIUS, sd_model(g));- shadow = inside * max(dropped * MODEL_SHADOW_ALPHA, contact * MODEL_CONTACT_ALPHA);+ // Premier tour du plan : le contact, au point même. Ensuite la pénombre vers la+ // lumière, marche bornée à la boîte du modèle élargie de sa portée.+ contact = 1.0 - smoothstep(0.0, MODEL_CONTACT_RADIUS, d);+ float2 tbp = ray_box(g, l, lo - MODEL_SHADOW_PAD, hi + MODEL_SHADOW_PAD);+ ts = float2(max(tbp.x, 0.004), tbp.y);+ res = 1.0;+ k = 1;+ if (!(tbp.x < tbp.y && tbp.y > 0.0))+ {+ stage = STAGE_DONE;+ }+ }+ else+ {+ res = min(res, MODEL_SOFTNESS * d / ts.x);+ ts.x += clamp(d, 0.01, 0.2);+ k++;+ if (res < 0.002 || ts.x > ts.y || k == 33)+ {+ res = saturate(res);+ dropped = 1.0 - res * res * (3.0 - 2.0 * res);+ stage = STAGE_DONE;+ }}}+ float3 rgb = 0.0;+ if (cov > 0.0)+ {+ float3 tl = lamp - q;+ float fall = SCULPT_LAMP_DIST * SCULPT_LAMP_DIST / dot(tl, tl);+ rgb = model_shade(q, n, rd, normalize(tl), fall, sh, ao, mat, l, fill);+ }+ float shadow = inside * max(dropped * MODEL_SHADOW_ALPHA, contact * MODEL_CONTACT_ALPHA);float a = cov * color.a;return float4(rgb * a, a + (1.0 - a) * shadow * color.a); // prémultiplié, ombre noire}diff --git a/crates/compositor/src/shaders.metal b/crates/compositor/src/shaders.metalindex 44bf67f98..336647ca3 100644--- a/crates/compositor/src/shaders.metal+++ b/crates/compositor/src/shaders.metal@@ -114,7 +114,7 @@ constant float DOF_MAX_LOD = 1.5;// Slots de texture, tenus par les paramètres des entry points :// ps_main : 0 = texY (Y, R8), 1 = texUV (CbCr, RG8), 2 = texImg (RGBA), 3 = texMask (R8),-// 4 = texSdf (champ + hauteur du sprite de curseur, RG16F, mode 15)+// 4 = texSdf (champ du sprite de curseur, R16F, mode 15)// ps_fs_* : 0 = rgbTex (RGBA)// =================================================================================@@ -461,16 +461,15 @@ inline float3 gradient_motion(float2 gp, float2 dir, float denom, float4 k0, flo// ============ Curseur MODÉLISÉ (mode 15) ============// Port ligne pour ligne de `cursor_model` (HLSL), dont les commentaires font foi ; seules// différences : `layer` et les textures arrivent en paramètres (le sprite en texture(2), son-// champ RG16F en texture(4)), `saturate` s'écrit `clamp`, `lerp` s'écrit `mix`, `SampleLevel`-// s'écrit `sample(…, level(0.0))`.-// Constantes : miroir exact de `frame_geometry.rs` (MODEL_*).-constant float MODEL_THICK = 0.19;-constant float MODEL_RELIEF_MAX = 0.12;+// champ R16F en texture(4)), `lerp` s'écrit `mix`, `SampleLevel` s'écrit `sample(…, level(0.0))`,+// et `pow` veut un exposant du type de sa base.+// Constantes : miroir exact de `frame_geometry.rs` (MODEL_*) et de `sculpt.rs` (SCULPT_*).constant float MODEL_BEVEL = 0.045;constant float3 MODEL_LIGHT = float3(-0.4194, -0.5792, 0.6990);+constant float3 MODEL_FILL = float3(0.7557, 0.2519, 0.6046);+// Ambiance et diffus de l'appareil modelé (mode 17), qui garde son éclairage d'origine.constant float MODEL_AMBIENT = 0.36;constant float MODEL_DIFFUSE = 0.75;-constant float MODEL_SPECULAR = 0.45;constant float MODEL_RIM_INSET = 1.5;constant float MODEL_SOFTNESS = 6.0;constant float MODEL_SHADOW_PAD = 0.45;@@ -491,10 +490,406 @@ inline float sprite_texel(texture2d<float, access::sample> texSdf)return CURSOR_SDF_UPSAMPLE / float(max(texSdf.get_width(), texSdf.get_height()));}-// Épaisseur du modèle, écrasé au clic de `color.b`.+// Épaisseur sous z = 0 (`SpriteShape::thick`), écrasée au clic de `color.b`.inline float model_thick(constant Layer &layer){- return MODEL_THICK * layer.color.b;+ return layer.trail_a.y * layer.color.b;+}++// Le curseur sculpté de ce dessin (`SpriteShape::sculpt`), 0 = le sprite extrudé.+inline int sculpt_id(constant Layer &layer)+{+ return int(layer.trail_a.x + 0.5);+}++// ---- Curseurs sculptés ---- (repère du PROTOTYPE : hauteur 1, y vers le haut, écran en z = 0)+constant float SCULPT_SCALE = 0.85;+constant float SCULPT_HOVER = 0.05;+constant float SCULPT_VOX = 0.0625;+constant float SCULPT_AR_ROUND = 0.03;+constant float SCULPT_HAND_ZC = 0.185;+constant float SCULPT_ZREF_ARROW = 0.2;+constant float SCULPT_ZREF_HAND = 0.185;+constant float SCULPT_LAMP_DIST = 1.9;+constant float3 SCULPT_SCREEN = float3(0.32, 0.32, 0.32);++inline float3 s_lin(float r, float g, float b)+{+ return pow(float3(r, g, b), float3(2.2));+}++inline float s_smin(float a, float b, float k)+{+ float h = max(k - abs(a - b), 0.0) / k;+ return min(a, b) - h * h * k * 0.25;+}++inline float2 s_opu(float2 a, float2 b)+{+ return a.x < b.x ? a : b;+}++static float s_capsule(float3 p, float3 a, float3 b, float r)+{+ float3 pa = p - a, ba = b - a;+ float h = saturate(dot(pa, ba) / dot(ba, ba));+ return length(pa - ba * h) - r;+}++static float s_round_box(float3 p, float3 b, float r)+{+ float3 q = abs(p) - b + r;+ return length(max(q, 0.0)) + min(max(q.x, max(q.y, q.z)), 0.0) - r;+}++static float s_ellipsoid(float3 p, float3 r)+{+ float k0 = length(p / r);+ float k1 = length(p / (r * r));+ return k0 * (k0 - 1.0) / k1;+}++// Extrusion d'une distance 2D à arêtes arrondies : demi-hauteur h, rayon r.+static float s_extrude(float d2, float z, float h, float r)+{+ float2 w = float2(d2 + r, abs(z) - h + r);+ return min(max(w.x, w.y), 0.0) + length(max(w, 0.0)) - r;+}++inline float2 s_rot(float2 v, float a)+{+ float c = cos(a), s = sin(a);+ return float2(c * v.x - s * v.y, s * v.x + c * v.y);+}++constant float2 SCULPT_ARROW[7] = {+ float2(0.0, 0.0), float2(0.0, -0.86), float2(0.215, -0.665), float2(0.37, -1.0),+ float2(0.53, -0.93), float2(0.38, -0.60), float2(0.64, -0.60)+};++static float s_arrow2(float2 p)+{+ float d = dot(p - SCULPT_ARROW[0], p - SCULPT_ARROW[0]);+ float s = 1.0;+ int j = 6;+ for (int i = 0; i < 7; i++)+ {+ float2 e = SCULPT_ARROW[j] - SCULPT_ARROW[i];+ float2 w = p - SCULPT_ARROW[i];+ float2 b = w - e * saturate(dot(w, e) / dot(e, e));+ d = min(d, dot(b, b));+ bool c0 = p.y >= SCULPT_ARROW[i].y;+ bool c1 = p.y < SCULPT_ARROW[j].y;+ bool c2 = e.x * w.y > e.y * w.x;+ if ((c0 && c1 && c2) || (!c0 && !c1 && !c2))+ {+ s = -s;+ }+ j = i;+ }+ return s * sqrt(d);+}++static float s_star5(float2 p, float r, float rf)+{+ const float2 k1 = float2(0.809016994375, -0.587785252292);+ const float2 k2 = float2(-0.809016994375, -0.587785252292);+ p.x = abs(p.x);+ p -= 2.0 * max(dot(k1, p), 0.0) * k1;+ p -= 2.0 * max(dot(k2, p), 0.0) * k2;+ p.x = abs(p.x);+ p.y -= r;+ float2 ba = rf * float2(-k1.y, k1.x) - float2(0.0, 1.0);+ float h = clamp(dot(p, ba) / dot(ba, ba), 0.0, r);+ return length(p - ba * h) * sign(p.y * ba.x - p.x * ba.y);+}++static float s_arrow_solid(float3 p, float h, float re, float dome)+{+ float d2 = s_arrow2(p.xy) - SCULPT_AR_ROUND;+ float hh = h + dome * smoothstep(0.0, 0.07, -d2);+ return s_extrude(d2, p.z - (SCULPT_HOVER + h + dome), hh, re);+}++static float s_piping(float3 p, float ztop)+{+ float d2 = s_arrow2(p.xy) - SCULPT_AR_ROUND;+ return length(float2(d2 + 0.075, p.z - ztop)) - 0.017;+}++static float s_glove(float3 p, float zc)+{+ float index = s_capsule(p, float3(0.0, -0.10, zc), float3(0.0, -0.52, zc), 0.098);+ float palm = s_round_box(p - float3(0.185, -0.70, zc), float3(0.255, 0.19, 0.105), 0.1);+ float f1 = s_capsule(p, float3(0.17, -0.57, zc + 0.012), float3(0.17, -0.41, zc + 0.045), 0.086);+ float f2 = s_capsule(p, float3(0.31, -0.59, zc + 0.01), float3(0.31, -0.45, zc + 0.04), 0.08);+ float f3 = s_capsule(p, float3(0.435, -0.625, zc + 0.005), float3(0.435, -0.52, zc + 0.03), 0.07);+ float thumb = s_capsule(p, float3(0.03, -0.77, zc + 0.03), float3(-0.165, -0.60, zc + 0.065), 0.082);+ float d = s_smin(palm, min(f1, min(f2, f3)), 0.035);+ d = s_smin(d, index, 0.05);+ return s_smin(d, thumb, 0.05);+}++static float s_cuff(float3 p, float zc)+{+ float3 q = p - float3(0.185, -0.925, zc);+ float2 ab = float2(0.272, 0.12);+ float e = (length(q.xz / ab) - 1.0) * min(ab.x, ab.y);+ return s_extrude(e, q.y, 0.07, 0.06);+}++static float2 s_sprout(float3 p, float3 c)+{+ float3 q = p - c;+ float st2 = s_star5(q.xy, 0.125, 0.52) - 0.022;+ float2 r = float2(s_extrude(st2, q.z, 0.038, 0.034), 3.0);+ float3 e = float3(abs(q.x) - 0.032, q.y + 0.005, q.z - 0.036);+ r = s_opu(r, float2(length(e) - 0.0135, 5.0));+ float3 l1 = float3(s_rot(q.xy - float2(-0.04, 0.15), -0.6), q.z);+ float3 l2 = float3(s_rot(q.xy - float2(0.045, 0.155), 0.7), q.z);+ float leaves = min(s_ellipsoid(l1, float3(0.03, 0.058, 0.02)), s_ellipsoid(l2, float3(0.03, 0.058, 0.02)));+ return s_opu(r, float2(leaves, 4.0));+}++// Pixel Candy : une ligne par entier, bit c = colonne c (cf. HLSL et `sculpt.rs`).+constant int SCULPT_ARROWPIX[16] = { 0, 1, 3, 7, 31, 63, 127, 255, 511, 63, 55, 115, 113, 224, 224, 64 };+constant int SCULPT_ARROWBACK[18] = {+ 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 255, 511, 511, 999, 995, 960, 192+};+constant int SCULPT_HANDPIX[15] = { 4, 14, 14, 14, 110, 878, 7022, 7022, 8190, 8191, 8191, 8191, 8190, 4092, 4092 };+constant int SCULPT_HANDBACK[17] = {+ 28, 62, 62, 62, 510, 4094, 32766, 32766, 32766, 32767, 32767, 32767, 32767, 32767, 32766, 16380, 16380+};+constant float2 SCULPT_HANDSPAN[17] = {+ float2(2.0, 4.0), float2(1.0, 5.0), float2(1.0, 5.0), float2(1.0, 5.0), float2(1.0, 8.0),+ float2(1.0, 11.0), float2(1.0, 14.0), float2(1.0, 14.0), float2(1.0, 14.0), float2(0.0, 14.0),+ float2(0.0, 14.0), float2(0.0, 14.0), float2(0.0, 14.0), float2(0.0, 14.0), float2(1.0, 14.0),+ float2(2.0, 13.0), float2(2.0, 13.0)+};++inline float2 s_grid_origin(int shape)+{+ return shape == 0 ? float2(0.0, 0.0) : float2(-2.5 * SCULPT_VOX, 0.0);+}++inline bool s_bit(int row, int r, int c, int rows, int cols)+{+ return r >= 0 && r < rows && c >= 0 && c < cols && ((row >> clamp(c, 0, 31)) & 1) == 1;+}++static bool s_occ(float2 id, int shape)+{+ int c = int(id.x);+ int r = -int(id.y) - 1;+ if (shape == 0)+ {+ return s_bit(SCULPT_ARROWPIX[clamp(r, 0, 15)], r, c, 16, 16);+ }+ return s_bit(SCULPT_HANDPIX[clamp(r, 0, 14)], r, c, 15, 13);+}++static bool s_occ_back(float2 id, int shape)+{+ int c = int(id.x) + 1;+ int r = -int(id.y);+ if (shape == 0)+ {+ return s_bit(SCULPT_ARROWBACK[clamp(r, 0, 17)], r, c, 18, 17);+ }+ return s_bit(SCULPT_HANDBACK[clamp(r, 0, 16)], r, c, 17, 15);+}++static float2 s_voxels(float3 p, int shape)+{+ float2 o = s_grid_origin(shape);+ float2 cell = floor((p.xy - o) / SCULPT_VOX);+ float2 bc = shape == 0 ? float2(0.33, -0.5) : float2(0.25, -0.47);+ float2 bh = shape == 0 ? float2(0.44, 0.61) : float2(0.48, 0.55);+ float2 bq = max(abs(p.xy - bc) - bh, 0.0);+ float bz = max(abs(p.z - (SCULPT_HOVER + 0.07)) - 0.07, 0.0);+ float far = max(SCULPT_VOX, sqrt(dot(bq, bq) + bz * bz));+ float dF = far;+ float dB = far;+ const float3 half_cell = float3(0.5 * SCULPT_VOX, 0.5 * SCULPT_VOX, 0.04);+ for (int j = -1; j <= 1; j++)+ {+ for (int i = -1; i <= 1; i++)+ {+ float2 id = cell + float2(float(i), float(j));+ float3 q = float3(p.xy - (o + (id + 0.5) * SCULPT_VOX), p.z);+ if (s_occ(id, shape))+ {+ dF = min(dF, s_round_box(q - float3(0.0, 0.0, SCULPT_HOVER + 0.1), half_cell, 0.009));+ }+ if (s_occ_back(id, shape))+ {+ dB = min(dB, s_round_box(q - float3(0.0, 0.0, SCULPT_HOVER + 0.04), half_cell, 0.009));+ }+ }+ }+ return dF < dB ? float2(dF, 6.0) : float2(dB, 7.0);+}++static float s_pixel_hand_dist(float2 p)+{+ float d = 1e9;+ for (int r = 0; r < 17; r++)+ {+ float2 x = (SCULPT_HANDSPAN[r] + float2(-3.5, -2.5)) * SCULPT_VOX;+ float2 y = float2(-float(r), 1.0 - float(r)) * SCULPT_VOX;+ float2 q = max(max(float2(x.x, y.x) - p, p - float2(x.y, y.y)), 0.0);+ d = min(d, length(q));+ }+ return d;+}++static float s_gem_edge(float3 p, float2 a, float2 b, float z0)+{+ float2 e = b - a;+ float len = length(e);+ float2 d = e / len;+ float2 q = p.xy - a;+ float dist = dot(q, float2(-d.y, d.x));+ float along = abs(dot(q, d) - 0.5 * len);+ float z = p.z - z0;+ float girdle = (z - 0.035 - 2.2 * dist) * 0.4138;+ float crown = (z - 0.07 - 0.6 * dist + 0.18 * along) * 0.8438;+ return max(-dist, max(girdle, crown));+}++static float s_gem_arrow(float3 p)+{+ float z0 = SCULPT_HOVER + 0.03;+ float slab = max(p.z - z0 - 0.2, z0 - 0.03 - p.z);+ float head = max(slab, max(s_gem_edge(p, float2(-0.02, 0.03), float2(-0.02, -0.88), z0),+ max(s_gem_edge(p, float2(-0.02, -0.88), float2(0.66, -0.61), z0),+ s_gem_edge(p, float2(0.66, -0.61), float2(-0.02, 0.03), z0))));+ float tail = max(slab, max(max(s_gem_edge(p, float2(0.215, -0.665), float2(0.37, -1.0), z0),+ s_gem_edge(p, float2(0.37, -1.0), float2(0.53, -0.93), z0)),+ max(s_gem_edge(p, float2(0.53, -0.93), float2(0.38, -0.60), z0),+ s_gem_edge(p, float2(0.38, -0.60), float2(0.215, -0.665), z0))));+ return min(head, tail);+}++static float s_facet_capsule(float3 p, float3 a, float3 b, float r, float spin)+{+ float3 u = normalize(b - a);+ float3 v = normalize(cross(u, float3(0.0, 0.0, 1.0)));+ float3 w = cross(u, v);+ float3 q = p - b;+ float h = dot(q, u);+ float2 rad = float2(dot(q, v), dot(q, w));+ float d = max(h - r, -dot(p - a, u) - r);+ for (int k = 0; k < 6; k++)+ {+ float an = spin + float(k) * 1.0471976;+ float s = dot(rad, float2(cos(an), sin(an)));+ d = max(d, s - r);+ d = max(d, dot(rad, float2(cos(an + 0.5236), sin(an + 0.5236))) * 0.8660 + h * 0.5 - r);+ d = max(d, s * 0.5 + h * 0.8660 - r);+ }+ return d;+}++constant float3 SCULPT_FACETS[10] = {+ float3(1.0, 0.0, 0.0), float3(0.0, 1.0, 0.0), float3(0.0, 0.0, 1.0),+ float3(0.7071, 0.7071, 0.0), float3(0.7071, 0.0, 0.7071), float3(0.0, 0.7071, 0.7071),+ float3(0.5774, 0.5774, 0.5774), float3(0.4472, 0.0, 0.8944), float3(0.0, 0.4472, 0.8944),+ float3(0.3015, 0.3015, 0.9045)+};++static float s_facet_ellipsoid(float3 p, float3 r)+{+ float3 q = abs(p);+ float d = -1e9;+ for (int i = 0; i < 10; i++)+ {+ d = max(d, dot(q, SCULPT_FACETS[i]) - length(r * SCULPT_FACETS[i]));+ }+ return d;+}++static float s_crystal_hand(float3 p)+{+ float zc = SCULPT_HAND_ZC;+ float d = s_facet_ellipsoid(p - float3(0.185, -0.70, zc), float3(0.3, 0.235, 0.125));+ d = min(d, s_facet_capsule(p, float3(0.0, -0.52, zc), float3(0.0, -0.10, zc), 0.098, 0.3));+ d = min(d, s_facet_capsule(p, float3(0.17, -0.57, zc + 0.012), float3(0.17, -0.41, zc + 0.045), 0.086, 0.1));+ d = min(d, s_facet_capsule(p, float3(0.31, -0.59, zc + 0.01), float3(0.31, -0.45, zc + 0.04), 0.08, 0.5));+ d = min(d, s_facet_capsule(p, float3(0.435, -0.625, zc + 0.005), float3(0.435, -0.52, zc + 0.03), 0.07, 0.2));+ return min(d, s_facet_capsule(p, float3(0.03, -0.77, zc + 0.03), float3(-0.165, -0.60, zc + 0.065), 0.082, 0.7));+}++static float2 sculpt_proto(float3 p, int theme, int shape)+{+ if (theme == 3)+ {+ return s_voxels(p, shape);+ }+ if (theme == 1)+ {+ return float2(shape == 0 ? s_gem_arrow(p) : s_crystal_hand(p), 8.0);+ }+ float2 body;+ float3 star;+ if (shape == 0)+ {+ float h = 0.075, re = 0.03, dome = 0.0;+ if (theme == 2)+ {+ h = 0.07;+ re = 0.06;+ dome = 0.035;+ }+ if (theme == 4)+ {+ h = 0.07;+ re = 0.055;+ dome = 0.025;+ }+ body = float2(s_arrow_solid(p, h, re, dome), 1.0);+ if (theme == 0)+ {+ body = s_opu(body, float2(s_piping(p, SCULPT_HOVER + 2.0 * h - 0.004), 2.0));+ }+ star = float3(0.57, -0.86, SCULPT_HOVER + 2.0 * h + dome);+ }+ else+ {+ body = s_opu(float2(s_glove(p, SCULPT_HAND_ZC), 1.0), float2(s_cuff(p, SCULPT_HAND_ZC), 2.0));+ star = float3(0.185, -0.93, SCULPT_HAND_ZC + 0.15);+ }+ return theme == 4 ? s_opu(body, s_sprout(p, star)) : body;+}++inline float3 sculpt_point(float3 q, constant Layer &layer)+{+ float zref = (sculpt_id(layer) - 1) % 2 == 0 ? SCULPT_ZREF_ARROW : SCULPT_ZREF_HAND;+ return float3(q.x, -q.y, q.z / max(layer.color.b, 1e-3)) / SCULPT_SCALE + float3(0.0, 0.0, zref);+}++inline float sculpt_units(constant Layer &layer)+{+ return SCULPT_SCALE * min(layer.color.b, 1.0);+}++static float2 sculpt_eval(float3 q, bool occ, constant Layer &layer)+{+ int id = sculpt_id(layer) - 1;+ int theme = id / 2, shape = id % 2;+ float3 p = sculpt_point(q, layer);+ float2 r;+ if (occ && theme == 3)+ {+ float d2 = shape == 0 ? s_arrow2(p.xy) - 1.2 * SCULPT_VOX : s_pixel_hand_dist(p.xy);+ float dz = abs(p.z - (SCULPT_HOVER + 0.07)) - 0.07;+ r = float2(length(max(float2(d2, dz), 0.0)) + min(max(d2, dz), 0.0), 7.0);+ }+ else+ {+ r = sculpt_proto(p, occ && theme == 1 ? 2 : theme, shape);+ }+ return float2(r.x * sculpt_units(layer), r.y);}static float sd_sprite2(float2 p, constant Layer &layer, texture2d<float, access::sample> texSdf)@@ -508,34 +903,16 @@ static float sd_sprite2(float2 p, constant Layer &layer, texture2d<float, accessreturn out2 > 0.0 ? sqrt(out2 + e * e) : d;}-static float model_top_height(float2 p, constant Layer &layer, texture2d<float, access::sample> texSdf)+static float2 model_eval(float3 p, bool occ, constant Layer &layer, texture2d<float, access::sample> texSdf){- float2 lo = layer.color.rg;- float2 c = clamp(p, lo, lo + sprite_size(layer));- float relief = texSdf.sample(samp, (c - lo) / sprite_size(layer), level(0.0)).g;- return clamp(relief * layer.color.b, 0.0, MODEL_RELIEF_MAX);-}--static float sd_model(float3 p, constant Layer &layer, texture2d<float, access::sample> texSdf)-{- float top = model_top_height(p.xy, layer, texSdf);- float thick = model_thick(layer);- float half_t = (top + thick) * 0.5;- float center_z = (top - thick) * 0.5;+ if (sculpt_id(layer) > 0)+ {+ return sculpt_eval(p, occ, layer);+ }+ float half_t = model_thick(layer) * 0.5;float2 w = float2(sd_sprite2(p.xy, layer, texSdf) + MODEL_BEVEL,- abs(p.z - center_z) - (half_t - MODEL_BEVEL));- return min(max(w.x, w.y), 0.0) + length(max(w, 0.0)) - MODEL_BEVEL;-}--static float3 model_normal(float3 p, constant Layer &layer, texture2d<float, access::sample> texSdf)-{- const float e = 0.002;- const float3 ka = float3(1.0, -1.0, -1.0);- const float3 kb = float3(-1.0, -1.0, 1.0);- const float3 kc = float3(-1.0, 1.0, -1.0);- const float3 kd = float3(1.0, 1.0, 1.0);- return normalize(ka * sd_model(p + ka * e, layer, texSdf) + kb * sd_model(p + kb * e, layer, texSdf) +- kc * sd_model(p + kc * e, layer, texSdf) + kd * sd_model(p + kd * e, layer, texSdf));+ abs(p.z + half_t) - (half_t - MODEL_BEVEL));+ return float2(min(max(w.x, w.y), 0.0) + length(max(w, 0.0)) - MODEL_BEVEL, 0.0);}static float2 ray_box(float3 o, float3 d, float3 lo, float3 hi)@@ -581,30 +958,6 @@ static float3 plane_to_model(float3 v, ModelFrame f)return float3(x, y * f.cp + v.z * f.sp, -y * f.sp + v.z * f.cp);}-static float model_soft_shadow(float3 o, float3 l, float3 lo, float3 hi, constant Layer &layer,- texture2d<float, access::sample> texSdf)-{- float2 tb = ray_box(o, l, lo - MODEL_SHADOW_PAD, hi + MODEL_SHADOW_PAD);- if (tb.x >= tb.y || tb.y <= 0.0)- {- return 1.0;- }- float res = 1.0;- float t = max(tb.x, 0.004);- for (int k = 0; k < 32; k++)- {- float d = sd_model(o + l * t, layer, texSdf);- res = min(res, MODEL_SOFTNESS * d / t);- if (res < 0.002 || t > tb.y)- {- break;- }- t += clamp(d, 0.01, 0.2);- }- res = clamp(res, 0.0, 1.0);- return res * res * (3.0 - 2.0 * res);-}-static float3 model_albedo(float2 p, constant Layer &layer, texture2d<float, access::sample> texSdf,texture2d<float, access::sample> texImg){@@ -617,16 +970,174 @@ static float3 model_albedo(float2 p, constant Layer &layer, texture2d<float, accreturn texImg.sample(samp, (q - layer.color.rg) / sprite_size(layer), level(0.0)).rgb;}-static float3 model_shade(float3 q, float3 rd, float3 l, constant Layer &layer,+struct SculptMat+{+ float3 alb;+ float rough;+ float spec;+ float sss;+ float refl;+};++inline SculptMat s_mat(float3 alb, float rough, float spec, float sss, float refl)+{+ SculptMat m;+ m.alb = alb;+ m.rough = rough;+ m.spec = spec;+ m.sss = sss;+ m.refl = refl;+ return m;+}++static float3 s_pixel_colour(float3 p, int shape)+{+ float2 id = floor((p.xy - s_grid_origin(shape)) / SCULPT_VOX);+ if (!s_occ(id + float2(-1.0, 0.0), shape) || !s_occ(id + float2(0.0, -1.0), shape))+ {+ return s_lin(0.52, 0.91, 0.77);+ }+ if (!s_occ(id + float2(1.0, 0.0), shape) || !s_occ(id + float2(0.0, 1.0), shape))+ {+ return s_lin(1.0, 0.78, 0.87);+ }+ return s_lin(1.0, 0.50, 0.71);+}++static SculptMat sculpt_material(float mat, float3 p, int theme, int shape)+{+ bool primary = mat < 1.5;+ if (theme == 0)+ {+ if (shape == 0 && primary) return s_mat(s_lin(0.10, 0.10, 0.115), 0.3, 0.2, 0.0, 0.9);+ if (shape == 0) return s_mat(s_lin(0.94, 0.91, 0.84), 0.45, 0.4, 0.2, 0.3);+ if (primary) return s_mat(s_lin(0.95, 0.92, 0.85), 0.55, 0.35, 0.35, 0.25);+ return s_mat(s_lin(0.17, 0.18, 0.22), 0.35, 0.6, 0.0, 0.6);+ }+ if (theme == 2)+ {+ if (shape == 0) return s_mat(s_lin(1.0, 0.40, 0.30), 0.5, 0.45, 0.4, 0.25);+ if (primary) return s_mat(s_lin(1.0, 0.79, 0.16), 0.5, 0.45, 0.4, 0.25);+ return s_mat(s_lin(0.18, 0.20, 0.29), 0.4, 0.5, 0.0, 0.4);+ }+ if (theme == 4)+ {+ if (primary && shape == 0) return s_mat(s_lin(0.62, 0.91, 0.78), 0.22, 0.8, 0.25, 0.6);+ if (primary) return s_mat(s_lin(0.96, 0.94, 0.88), 0.5, 0.35, 0.35, 0.25);+ if (mat < 2.5) return s_mat(s_lin(0.62, 0.91, 0.78), 0.25, 0.7, 0.25, 0.5);+ if (mat < 3.5) return s_mat(s_lin(1.0, 0.80, 0.20), 0.3, 0.6, 0.3, 0.4);+ if (mat < 4.5) return s_mat(s_lin(0.38, 0.80, 0.55), 0.35, 0.5, 0.35, 0.3);+ return s_mat(s_lin(0.16, 0.12, 0.10), 0.2, 0.8, 0.0, 0.5);+ }+ if (mat < 6.5) return s_mat(s_pixel_colour(p, shape), 0.45, 0.35, 0.15, 0.2);+ return s_mat(s_lin(0.36, 0.18, 0.54), 0.45, 0.35, 0.1, 0.2);+}++static float3 model_env(float3 d, float rough, float3 l, float3 fill)+{+ float3 col = mix(SCULPT_SCREEN * 0.9, s_lin(0.82, 0.85, 0.92) * 0.55, smoothstep(-0.15, 0.35, d.z));+ float w = rough * 0.3;+ float k = 1.0 - rough * 0.6;+ col += s_lin(1.0, 0.97, 0.92) * 5.0 * k * smoothstep(0.90 - w, 0.97, dot(d, l));+ col += s_lin(0.85, 0.9, 1.0) * 1.6 * k * smoothstep(0.93 - w, 0.98, dot(d, fill));+ return col;+}++static float3 s_gem(float k)+{+ k = saturate(k) * 3.0;+ float3 a = s_lin(0.20, 0.95, 1.0);+ float3 b = s_lin(0.15, 0.42, 1.0);+ float3 c = s_lin(0.45, 0.25, 0.95);+ float3 d = s_lin(0.88, 0.50, 1.0);+ if (k < 1.0) return mix(a, b, k);+ if (k < 2.0) return mix(b, c, k - 1.0);+ return mix(c, d, k - 2.0);+}++static float3 model_shade_crystal(float3 n, float3 rd, float3 L, float fall, float3 l, float3 fill)+{+ float cosi = saturate(dot(-rd, n));+ float F = 0.04 + 0.96 * pow(1.0 - cosi, 5.0);+ float3 t = refract(rd, n, 1.0 / 1.6);+ float k = 0.42 + 0.9 * dot(float2(n.x, -n.y), float2(0.7557, -0.6549))+ + 0.6 * dot(float2(t.x, -t.y), float2(0.6, -0.8));+ float3 body = float3(s_gem(k - 0.08).r, s_gem(k).g, s_gem(k + 0.08).b);+ float3 col = body * (0.1 + 1.8 * fall * pow(max(dot(n, L), 0.0), 2.5));+ col += body * model_env(reflect(t, float3(0.0, 0.0, 1.0)) * float3(1.0, 1.0, -1.0), 0.15, l, fill) * 0.5;+ col += pow(max(dot(reflect(rd, n), L), 0.0), 30.0) * 2.0;+ col += model_env(reflect(rd, n), 0.05, l, fill) * F;+ col += s_lin(0.5, 0.9, 1.0) * pow(1.0 - cosi, 4.0) * 0.6;+ return col;+}++static float3 model_tonemap(float3 c)+{+ const float start = 0.76;+ float x = min(c.r, min(c.g, c.b));+ c -= x < 0.08 ? x - 6.25 * x * x : 0.04;+ float peak = max(c.r, max(c.g, c.b));+ if (peak >= start)+ {+ const float d = 1.0 - start;+ float np = 1.0 - d * d / (peak + d - start);+ c *= np / peak;+ float g = 1.0 - 1.0 / (0.15 * (peak - np) + 1.0);+ c = mix(c, float3(np), g);+ }+ return pow(saturate(c), float3(1.0 / 2.2));+}++static float3 model_shade(float3 q, float3 n, float3 rd, float3 L, float fall, float sh, float ao, float mat,+ float3 l, float3 fill, constant Layer &layer,texture2d<float, access::sample> texSdf,texture2d<float, access::sample> texImg){- float3 n = model_normal(q, layer, texSdf);- float3 albedo = model_albedo(q.xy, layer, texSdf, texImg);- float diffuse = clamp(dot(n, l), 0.0, 1.0);- float gloss = 1.0 - smoothstep(0.97, 0.995, abs(n.z));- float spec = gloss * pow(clamp(dot(n, normalize(l - rd)), 0.0, 1.0), 110.0);- return albedo * (MODEL_AMBIENT + MODEL_DIFFUSE * diffuse) + MODEL_SPECULAR * spec;+ int id = sculpt_id(layer);+ if (id > 0 && (id - 1) / 2 == 1)+ {+ return model_tonemap(model_shade_crystal(n, rd, L, fall, l, fill));+ }+ SculptMat m;+ float gloss = 1.0;+ if (id > 0)+ {+ float3 p = sculpt_point(q, layer) - float3(n.x, -n.y, n.z) * 0.01;+ m = sculpt_material(mat, p, (id - 1) / 2, (id - 1) % 2);+ }+ else+ {+ m = s_mat(pow(model_albedo(q.xy, layer, texSdf, texImg), float3(2.2)), 0.45, 0.35, 0.2, 0.3);+ gloss = 1.0 - smoothstep(0.97, 0.995, abs(n.z));+ }+ float3 key = s_lin(1.0, 0.97, 0.93) * 2.1 * fall;+ float ndl = dot(n, L);+ float wrap = 0.5 * m.sss;+ float dif = saturate((ndl + wrap) / (1.0 + wrap)) * mix(sh, 1.0, 0.15 * m.sss);+ float ndh = saturate(dot(n, normalize(L - rd)));+ float shin = exp2(10.0 * (1.0 - m.rough) + 1.0);+ float spe = (pow(ndh, shin) * (shin + 8.0) / 25.0 + 0.15 * pow(ndh, 8.0)) * sh * saturate(ndl * 4.0);+ float fre = pow(1.0 - saturate(dot(n, -rd)), 5.0);+ float3 amb = mix(SCULPT_SCREEN * 0.12, s_lin(0.88, 0.92, 1.0) * 0.22, 0.5 + 0.5 * n.z);+ float3 fl = s_lin(0.85, 0.9, 1.0) * saturate(dot(n, fill)) * 0.12;+ float3 col = m.alb * (key * dif + (amb + fl) * ao * mix(float3(1.0), m.alb, 0.5));+ col += key * spe * m.spec * gloss;+ col += model_env(reflect(rd, n), m.rough, l, fill) * m.refl * (0.04 + 0.96 * fre) * ao * gloss;+ col += s_lin(0.9, 0.95, 1.0) * fre * 0.08 * ao * sh;+ return model_tonemap(col);+}++// Les passes de la boucle unique de `cursor_model` (cf. HLSL : un seul appel de `model_eval`).+constant int STAGE_MARCH = 0;+constant int STAGE_NORMAL = 1;+constant int STAGE_AO = 2;+constant int STAGE_SELF = 3;+constant int STAGE_PLANE = 4;+constant int STAGE_DONE = 5;++inline float3 model_tetra(int k)+{+ return 0.5773 * (2.0 * float3(float(((k + 3) >> 1) & 1), float((k >> 1) & 1), float(k & 1)) - 1.0);}static float4 cursor_model(float2 local, constant Layer &layer,@@ -644,7 +1155,7 @@ static float4 cursor_model(float2 local, constant Layer &layer,float unit = layer.src.w;float3 tip = layer.src_prev.xyz;float3 lo = float3(layer.color.rg, -model_thick(layer));- float3 hi = float3(layer.color.rg + sprite_size(layer), MODEL_RELIEF_MAX);+ float3 hi = float3(layer.color.rg + sprite_size(layer), layer.trail_a.z);float3 dw = float3(local + layer.src.xy, -persp);float dlen = length(dw);@@ -652,61 +1163,186 @@ static float4 cursor_model(float2 local, constant Layer &layer,float3 ro = plane_to_model((world_to_plane(float3(-layer.mb.z, -layer.mb.w, persp), f) - tip) / unit, f);float3 rd = plane_to_model(world_to_plane(dw / dlen, f), f);float3 l = plane_to_model(world_to_plane(MODEL_LIGHT, f), f);+ float3 fill = plane_to_model(world_to_plane(MODEL_FILL, f), f);float3 nz = plane_to_model(float3(0.0, 0.0, 1.0), f);float hz = -tip.z / unit;+ float stride = sculpt_id(layer) > 0 ? 0.85 : 1.0;+ float3 lamp = float3(layer.color.rg + sprite_size(layer) * 0.5, 0.0) + l * SCULPT_LAMP_DIST;- float cov = 0.0;- float3 rgb = float3(0.0);float2 tb = ray_box(ro, rd, lo - 0.02, hi + 0.02);- if (tb.x < tb.y && tb.y > 0.0)+ int stage = tb.x < tb.y && tb.y > 0.0 ? STAGE_MARCH : STAGE_DONE;+ bool plane_next = stage == STAGE_DONE;+ int k = 0;+ float t = max(tb.x, 0.0);+ float best = 1e9;+ float t_best = t;+ float mat = 0.0;+ float cov = 0.0;+ float3 q = float3(0.0);+ float3 n = float3(0.0);+ float3 L = float3(0.0);+ float ao = 1.0;+ float sh = 1.0;+ float2 ts = float2(0.0);+ float res = 1.0;+ float3 g = float3(0.0);+ float inside = 0.0;+ float contact = 0.0;+ float dropped = 0.0;+ for (int it = 0; it < 180; it++){- float t = max(tb.x, 0.0);- float best = 1e9;- float t_best = t;- bool hit = false;- for (int k = 0; k < 64; k++)+ if (plane_next)+ {+ plane_next = false;+ stage = STAGE_DONE;+ float denom = dot(rd, nz);+ if (cov < 1.0 && denom < -1e-4)+ {+ g = ro + rd * ((hz - dot(ro, nz)) / denom);+ float3 gp = tip + unit * model_to_plane(g, f);+ inside = saturate(min(layer.mb.x - abs(gp.x), layer.mb.y - abs(gp.y)) + 0.5);+ if (inside > 0.0)+ {+ stage = STAGE_PLANE;+ k = 0;+ ts = float2(0.0);+ }+ }+ }+ float3 pos;+ if (stage == STAGE_MARCH)+ {+ pos = ro + rd * t;+ }+ else if (stage == STAGE_NORMAL)+ {+ pos = q + 0.002 * model_tetra(k);+ }+ else if (stage == STAGE_AO)+ {+ pos = q + (0.01 + 0.0175 * float(k)) * SCULPT_SCALE * n;+ }+ else if (stage == STAGE_SELF)+ {+ pos = q + n * 0.003 + L * ts.x;+ }+ else if (stage == STAGE_PLANE)+ {+ pos = g + l * ts.x;+ }+ else+ {+ break;+ }+ float2 m = model_eval(pos, stage == STAGE_PLANE, layer, texSdf);+ float d = m.x;+ if (stage == STAGE_MARCH){- float d = sd_model(ro + rd * t, layer, texSdf);float fp = t / dlen;- if (d < 0.1 * fp)+ bool hit = d < 0.1 * fp;+ if (hit || d / fp < best){- hit = true;+ best = hit ? 0.0 : d / fp;t_best = t;- break;+ mat = m.y;}- if (d / fp < best)+ t += d * stride;+ k++;+ if (hit || t > tb.y || k == 96){- best = d / fp;- t_best = t;+ cov = saturate(1.0 - best);+ if (cov > 0.0)+ {+ q = ro + rd * t_best;+ stage = STAGE_NORMAL;+ k = 0;+ }+ else+ {+ plane_next = true;+ }}- t += d;- if (t > tb.y)+ }+ else if (stage == STAGE_NORMAL)+ {+ n += model_tetra(k) * d;+ k++;+ if (k == 4){- break;+ n = normalize(n);+ stage = STAGE_AO;+ k = 0;+ ao = 0.0;}}- cov = hit ? 1.0 : clamp(1.0 - best, 0.0, 1.0);- if (cov > 0.0)+ else if (stage == STAGE_AO){- rgb = model_shade(ro + rd * t_best, rd, l, layer, texSdf, texImg);+ ao += ((0.01 + 0.0175 * float(k)) * SCULPT_SCALE - d) * pow(0.85, float(k));+ k++;+ if (k == 5)+ {+ ao = saturate(1.0 - 3.5 * ao / SCULPT_SCALE);+ L = normalize(lamp - q);+ float2 tbs = ray_box(q + n * 0.003, L, lo - MODEL_SHADOW_PAD, hi + MODEL_SHADOW_PAD);+ if (tbs.x < tbs.y && tbs.y > 0.0)+ {+ stage = STAGE_SELF;+ k = 0;+ ts = float2(max(tbs.x, 0.004), tbs.y);+ res = 1.0;+ }+ else+ {+ plane_next = true;+ }+ }}- }-- float shadow = 0.0;- float denom = dot(rd, nz);- if (cov < 1.0 && denom < -1e-4)- {- float3 g = ro + rd * ((hz - dot(ro, nz)) / denom);- float3 gp = tip + unit * model_to_plane(g, f);- float inside = clamp(min(layer.mb.x - abs(gp.x), layer.mb.y - abs(gp.y)) + 0.5, 0.0, 1.0);- if (inside > 0.0)+ else if (stage == STAGE_SELF)+ {+ res = min(res, MODEL_SOFTNESS * d / ts.x);+ ts.x += clamp(d, 0.01, 0.2);+ k++;+ if (res < 0.002 || ts.x > ts.y || k == 32)+ {+ res = saturate(res);+ sh = res * res * (3.0 - 2.0 * res);+ plane_next = true;+ }+ }+ else if (k == 0)+ {+ contact = 1.0 - smoothstep(0.0, MODEL_CONTACT_RADIUS, d);+ float2 tbp = ray_box(g, l, lo - MODEL_SHADOW_PAD, hi + MODEL_SHADOW_PAD);+ ts = float2(max(tbp.x, 0.004), tbp.y);+ res = 1.0;+ k = 1;+ if (!(tbp.x < tbp.y && tbp.y > 0.0))+ {+ stage = STAGE_DONE;+ }+ }+ else{- float dropped = 1.0 - model_soft_shadow(g, l, lo, hi, layer, texSdf);- float contact = 1.0 - smoothstep(0.0, MODEL_CONTACT_RADIUS, sd_model(g, layer, texSdf));- shadow = inside * max(dropped * MODEL_SHADOW_ALPHA, contact * MODEL_CONTACT_ALPHA);+ res = min(res, MODEL_SOFTNESS * d / ts.x);+ ts.x += clamp(d, 0.01, 0.2);+ k++;+ if (res < 0.002 || ts.x > ts.y || k == 33)+ {+ res = saturate(res);+ dropped = 1.0 - res * res * (3.0 - 2.0 * res);+ stage = STAGE_DONE;+ }}}+ float3 rgb = float3(0.0);+ if (cov > 0.0)+ {+ float3 tl = lamp - q;+ float fall = SCULPT_LAMP_DIST * SCULPT_LAMP_DIST / dot(tl, tl);+ rgb = model_shade(q, n, rd, normalize(tl), fall, sh, ao, mat, l, fill, layer, texSdf, texImg);+ }+ float shadow = inside * max(dropped * MODEL_SHADOW_ALPHA, contact * MODEL_CONTACT_ALPHA);float a = cov * layer.color.a;return float4(rgb * a, a + (1.0 - a) * shadow * layer.color.a); // prémultiplié, ombre noire}@@ -1298,7 +1934,7 @@ fragment float4 ps_main(VSOut i [[stage_in]],// masque n'existe : Metal rend alors 0, ce qui est sans effet// puisque la branche n'est prise que si layer.fx.z > 0.5.texture2d<float, access::sample> texMask [[texture(3)]],- // Champ et relief du sprite de curseur (mode 15 seulement), RG16F, cf.+ // Champ de distance du sprite de curseur (mode 15 seulement), R16F, cf.// `cursor_sdf.rs`. Le sprite lui-même est en texture(2), comme aux// modes 7 et 13.texture2d<float, access::sample> texSdf [[texture(4)]])diff --git a/crates/compositor/src/vk_shaders/layer.wgsl b/crates/compositor/src/vk_shaders/layer.wgslindex ba240b7a2..6ca239649 100644--- a/crates/compositor/src/vk_shaders/layer.wgsl+++ b/crates/compositor/src/vk_shaders/layer.wgsl@@ -35,7 +35,7 @@ struct Layer {@group(0) @binding(0) var<uniform> layer: Layer;@group(0) @binding(1) var texY: texture_2d<f32>; // R8Unorm, sample .r ; modes 7, 13 et 15 : le sprite RGBA-@group(0) @binding(2) var texU: texture_2d<f32>; // R8Unorm, sample .r ; mode 15 : distance + relief RG16F+@group(0) @binding(2) var texU: texture_2d<f32>; // R8Unorm, sample .r ; mode 15 : le champ R16F du sprite@group(0) @binding(3) var samp: sampler;// Masque de segmentation du sujet webcam, R8. Une vue 1x1 est liee quand aucun masque// n'existe : la branche n'est de toute facon prise que si layer.fx.z > 0.5.@@ -467,21 +467,21 @@ fn blur_webcam_bg(uv: vec2<f32>, intensity: f32, qpx: vec2<f32>, local_px: vec2<}// ---- Curseur MODELISE (mode 15) -----// Port ligne pour ligne de `cursor_model` (HLSL), dont les commentaires font foi : le sprite de-// l'etat courant en objet 3D, sa silhouette (champ de distance signe tire de son alpha) extrudee,-// lancee de rayons par pixel, eclairee, et qui porte une ombre douce et une ombre de contact sur-// le plan de l'ecran. Constantes : miroir exact de `frame_geometry.rs` (MODEL_*), emplacements du-// cbuffer : `cursor_model_cb`.+// Port ligne pour ligne de `cursor_model` (HLSL), dont les commentaires font foi : un curseur+// SCULPTE (`trail_a.x` > 0, la fleche ou la main d'un des cinq themes d'origine modelee en+// volumes), sinon le sprite de l'etat courant extrude ; eclaire par une lampe proche, avec ombres+// propres et occlusion, et qui porte une ombre douce et une ombre de contact sur le plan de+// l'ecran. Constantes : miroir exact de `frame_geometry.rs` (MODEL_*) et de `sculpt.rs`+// (SCULPT_*), emplacements du cbuffer : `cursor_model_cb`.// Textures : le sprite RGBA (alpha droit) au binding 1 (`texY`, comme aux modes 7 et 13), son-// champ RG16F au binding 2 (`texU`), sur le meme rect ; `color.rg` = coin du sprite dans le repere+// champ R16F au binding 2 (`texU`), sur le meme rect ; `color.rg` = coin du sprite dans le repere// du modele, `sprite_size()` = sa taille (w/h dans `radius_px`), `color.b` = l'ecrasement au clic.-const MODEL_THICK: f32 = 0.19;-const MODEL_RELIEF_MAX: f32 = 0.12;const MODEL_BEVEL: f32 = 0.045;const MODEL_LIGHT = vec3<f32>(-0.4194, -0.5792, 0.6990);+const MODEL_FILL = vec3<f32>(0.7557, 0.2519, 0.6046);+// Ambiance et diffus de l'appareil modele (mode 17), qui garde son eclairage d'origine.const MODEL_AMBIENT: f32 = 0.36;const MODEL_DIFFUSE: f32 = 0.75;-const MODEL_SPECULAR: f32 = 0.45;const MODEL_RIM_INSET: f32 = 1.5;const MODEL_SOFTNESS: f32 = 6.0;const MODEL_SHADOW_PAD: f32 = 0.45;@@ -501,9 +501,360 @@ fn sprite_texel() -> f32 {return CURSOR_SDF_UPSAMPLE / max(d.x, d.y);}-// Epaisseur du modele, ecrase au clic de `color.b`.+// Epaisseur sous z = 0 (`SpriteShape::thick`), ecrasee au clic de `color.b`.fn model_thick() -> f32 {- return MODEL_THICK * layer.color.b;+ return layer.trail_a.y * layer.color.b;+}++// Le curseur sculpte de ce dessin (`SpriteShape::sculpt`), 0 = le sprite extrude.+fn sculpt_id() -> i32 {+ return i32(layer.trail_a.x + 0.5);+}++// ---- Curseurs sculptes ---- (repere du PROTOTYPE : hauteur 1, y vers le haut, ecran en z = 0)+const SCULPT_SCALE: f32 = 0.85;+const SCULPT_HOVER: f32 = 0.05;+const SCULPT_VOX: f32 = 0.0625;+const SCULPT_AR_ROUND: f32 = 0.03;+const SCULPT_HAND_ZC: f32 = 0.185;+const SCULPT_ZREF_ARROW: f32 = 0.2;+const SCULPT_ZREF_HAND: f32 = 0.185;+const SCULPT_LAMP_DIST: f32 = 1.9;+const SCULPT_SCREEN = vec3<f32>(0.32, 0.32, 0.32);++fn s_lin(r: f32, g: f32, b: f32) -> vec3<f32> {+ return pow(vec3<f32>(r, g, b), vec3<f32>(2.2));+}++fn s_smin(a: f32, b: f32, k: f32) -> f32 {+ let h = max(k - abs(a - b), 0.0) / k;+ return min(a, b) - h * h * k * 0.25;+}++fn s_opu(a: vec2<f32>, b: vec2<f32>) -> vec2<f32> {+ return select(b, a, a.x < b.x);+}++fn s_capsule(p: vec3<f32>, a: vec3<f32>, b: vec3<f32>, r: f32) -> f32 {+ let pa = p - a;+ let ba = b - a;+ let h = saturate(dot(pa, ba) / dot(ba, ba));+ return length(pa - ba * h) - r;+}++fn s_round_box(p: vec3<f32>, b: vec3<f32>, r: f32) -> f32 {+ let q = abs(p) - b + vec3<f32>(r);+ return length(max(q, vec3<f32>(0.0))) + min(max(q.x, max(q.y, q.z)), 0.0) - r;+}++fn s_ellipsoid(p: vec3<f32>, r: vec3<f32>) -> f32 {+ let k0 = length(p / r);+ let k1 = length(p / (r * r));+ return k0 * (k0 - 1.0) / k1;+}++// Extrusion d'une distance 2D a aretes arrondies : demi-hauteur h, rayon r.+fn s_extrude(d2: f32, z: f32, h: f32, r: f32) -> f32 {+ let w = vec2<f32>(d2 + r, abs(z) - h + r);+ return min(max(w.x, w.y), 0.0) + length(max(w, vec2<f32>(0.0))) - r;+}++fn s_rot(v: vec2<f32>, a: f32) -> vec2<f32> {+ let c = cos(a);+ let s = sin(a);+ return vec2<f32>(c * v.x - s * v.y, s * v.x + c * v.y);+}++const SCULPT_ARROW = array<vec2<f32>, 7>(+ vec2<f32>(0.0, 0.0), vec2<f32>(0.0, -0.86), vec2<f32>(0.215, -0.665), vec2<f32>(0.37, -1.0),+ vec2<f32>(0.53, -0.93), vec2<f32>(0.38, -0.60), vec2<f32>(0.64, -0.60)+);++fn s_arrow2(p: vec2<f32>) -> f32 {+ var d = dot(p - SCULPT_ARROW[0], p - SCULPT_ARROW[0]);+ var s = 1.0;+ var j = 6;+ for (var i = 0; i < 7; i++) {+ let e = SCULPT_ARROW[j] - SCULPT_ARROW[i];+ let w = p - SCULPT_ARROW[i];+ let b = w - e * saturate(dot(w, e) / dot(e, e));+ d = min(d, dot(b, b));+ let c0 = p.y >= SCULPT_ARROW[i].y;+ let c1 = p.y < SCULPT_ARROW[j].y;+ let c2 = e.x * w.y > e.y * w.x;+ if (c0 && c1 && c2) || (!c0 && !c1 && !c2) {+ s = -s;+ }+ j = i;+ }+ return s * sqrt(d);+}++fn s_star5(p0: vec2<f32>, r: f32, rf: f32) -> f32 {+ let k1 = vec2<f32>(0.809016994375, -0.587785252292);+ let k2 = vec2<f32>(-0.809016994375, -0.587785252292);+ var p = vec2<f32>(abs(p0.x), p0.y);+ p = p - 2.0 * max(dot(k1, p), 0.0) * k1;+ p = p - 2.0 * max(dot(k2, p), 0.0) * k2;+ p.x = abs(p.x);+ p.y = p.y - r;+ let ba = rf * vec2<f32>(-k1.y, k1.x) - vec2<f32>(0.0, 1.0);+ let h = clamp(dot(p, ba) / dot(ba, ba), 0.0, r);+ return length(p - ba * h) * sign(p.y * ba.x - p.x * ba.y);+}++fn s_arrow_solid(p: vec3<f32>, h: f32, re: f32, dome: f32) -> f32 {+ let d2 = s_arrow2(p.xy) - SCULPT_AR_ROUND;+ let hh = h + dome * smoothstep(0.0, 0.07, -d2);+ return s_extrude(d2, p.z - (SCULPT_HOVER + h + dome), hh, re);+}++fn s_piping(p: vec3<f32>, ztop: f32) -> f32 {+ let d2 = s_arrow2(p.xy) - SCULPT_AR_ROUND;+ return length(vec2<f32>(d2 + 0.075, p.z - ztop)) - 0.017;+}++fn s_glove(p: vec3<f32>, zc: f32) -> f32 {+ let index = s_capsule(p, vec3<f32>(0.0, -0.10, zc), vec3<f32>(0.0, -0.52, zc), 0.098);+ let palm = s_round_box(p - vec3<f32>(0.185, -0.70, zc), vec3<f32>(0.255, 0.19, 0.105), 0.1);+ let f1 = s_capsule(p, vec3<f32>(0.17, -0.57, zc + 0.012), vec3<f32>(0.17, -0.41, zc + 0.045), 0.086);+ let f2 = s_capsule(p, vec3<f32>(0.31, -0.59, zc + 0.01), vec3<f32>(0.31, -0.45, zc + 0.04), 0.08);+ let f3 = s_capsule(p, vec3<f32>(0.435, -0.625, zc + 0.005), vec3<f32>(0.435, -0.52, zc + 0.03), 0.07);+ let thumb = s_capsule(p, vec3<f32>(0.03, -0.77, zc + 0.03), vec3<f32>(-0.165, -0.60, zc + 0.065), 0.082);+ var d = s_smin(palm, min(f1, min(f2, f3)), 0.035);+ d = s_smin(d, index, 0.05);+ return s_smin(d, thumb, 0.05);+}++fn s_cuff(p: vec3<f32>, zc: f32) -> f32 {+ let q = p - vec3<f32>(0.185, -0.925, zc);+ let ab = vec2<f32>(0.272, 0.12);+ let e = (length(q.xz / ab) - 1.0) * min(ab.x, ab.y);+ return s_extrude(e, q.y, 0.07, 0.06);+}++fn s_sprout(p: vec3<f32>, c: vec3<f32>) -> vec2<f32> {+ let q = p - c;+ let st2 = s_star5(q.xy, 0.125, 0.52) - 0.022;+ var r = vec2<f32>(s_extrude(st2, q.z, 0.038, 0.034), 3.0);+ let e = vec3<f32>(abs(q.x) - 0.032, q.y + 0.005, q.z - 0.036);+ r = s_opu(r, vec2<f32>(length(e) - 0.0135, 5.0));+ let l1 = vec3<f32>(s_rot(q.xy - vec2<f32>(-0.04, 0.15), -0.6), q.z);+ let l2 = vec3<f32>(s_rot(q.xy - vec2<f32>(0.045, 0.155), 0.7), q.z);+ let leaves = min(s_ellipsoid(l1, vec3<f32>(0.03, 0.058, 0.02)), s_ellipsoid(l2, vec3<f32>(0.03, 0.058, 0.02)));+ return s_opu(r, vec2<f32>(leaves, 4.0));+}++// Pixel Candy : une ligne par entier, bit c = colonne c (cf. HLSL et `sculpt.rs`).+const SCULPT_ARROWPIX = array<i32, 16>(0, 1, 3, 7, 31, 63, 127, 255, 511, 63, 55, 115, 113, 224, 224, 64);+const SCULPT_ARROWBACK = array<i32, 18>(+ 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 255, 511, 511, 999, 995, 960, 192+);+const SCULPT_HANDPIX = array<i32, 15>(4, 14, 14, 14, 110, 878, 7022, 7022, 8190, 8191, 8191, 8191, 8190, 4092, 4092);+const SCULPT_HANDBACK = array<i32, 17>(+ 28, 62, 62, 62, 510, 4094, 32766, 32766, 32766, 32767, 32767, 32767, 32767, 32767, 32766, 16380, 16380+);+const SCULPT_HANDSPAN = array<vec2<f32>, 17>(+ vec2<f32>(2.0, 4.0), vec2<f32>(1.0, 5.0), vec2<f32>(1.0, 5.0), vec2<f32>(1.0, 5.0), vec2<f32>(1.0, 8.0),+ vec2<f32>(1.0, 11.0), vec2<f32>(1.0, 14.0), vec2<f32>(1.0, 14.0), vec2<f32>(1.0, 14.0), vec2<f32>(0.0, 14.0),+ vec2<f32>(0.0, 14.0), vec2<f32>(0.0, 14.0), vec2<f32>(0.0, 14.0), vec2<f32>(0.0, 14.0), vec2<f32>(1.0, 14.0),+ vec2<f32>(2.0, 13.0), vec2<f32>(2.0, 13.0)+);++fn s_grid_origin(shape: i32) -> vec2<f32> {+ return select(vec2<f32>(-2.5 * SCULPT_VOX, 0.0), vec2<f32>(0.0), shape == 0);+}++fn s_bit(row: i32, r: i32, c: i32, rows: i32, cols: i32) -> bool {+ return r >= 0 && r < rows && c >= 0 && c < cols && ((row >> u32(clamp(c, 0, 31))) & 1) == 1;+}++fn s_occ(id: vec2<f32>, shape: i32) -> bool {+ let c = i32(id.x);+ let r = -i32(id.y) - 1;+ if shape == 0 {+ return s_bit(SCULPT_ARROWPIX[clamp(r, 0, 15)], r, c, 16, 16);+ }+ return s_bit(SCULPT_HANDPIX[clamp(r, 0, 14)], r, c, 15, 13);+}++fn s_occ_back(id: vec2<f32>, shape: i32) -> bool {+ let c = i32(id.x) + 1;+ let r = -i32(id.y);+ if shape == 0 {+ return s_bit(SCULPT_ARROWBACK[clamp(r, 0, 17)], r, c, 18, 17);+ }+ return s_bit(SCULPT_HANDBACK[clamp(r, 0, 16)], r, c, 17, 15);+}++fn s_voxels(p: vec3<f32>, shape: i32) -> vec2<f32> {+ let o = s_grid_origin(shape);+ let cell = floor((p.xy - o) / SCULPT_VOX);+ let bc = select(vec2<f32>(0.25, -0.47), vec2<f32>(0.33, -0.5), shape == 0);+ let bh = select(vec2<f32>(0.48, 0.55), vec2<f32>(0.44, 0.61), shape == 0);+ let bq = max(abs(p.xy - bc) - bh, vec2<f32>(0.0));+ let bz = max(abs(p.z - (SCULPT_HOVER + 0.07)) - 0.07, 0.0);+ let far = max(SCULPT_VOX, sqrt(dot(bq, bq) + bz * bz));+ var dF = far;+ var dB = far;+ let half_cell = vec3<f32>(0.5 * SCULPT_VOX, 0.5 * SCULPT_VOX, 0.04);+ for (var j = -1; j <= 1; j++) {+ for (var i = -1; i <= 1; i++) {+ let id = cell + vec2<f32>(f32(i), f32(j));+ let q = vec3<f32>(p.xy - (o + (id + vec2<f32>(0.5)) * SCULPT_VOX), p.z);+ if s_occ(id, shape) {+ dF = min(dF, s_round_box(q - vec3<f32>(0.0, 0.0, SCULPT_HOVER + 0.1), half_cell, 0.009));+ }+ if s_occ_back(id, shape) {+ dB = min(dB, s_round_box(q - vec3<f32>(0.0, 0.0, SCULPT_HOVER + 0.04), half_cell, 0.009));+ }+ }+ }+ return select(vec2<f32>(dB, 7.0), vec2<f32>(dF, 6.0), dF < dB);+}++fn s_pixel_hand_dist(p: vec2<f32>) -> f32 {+ var d = 1e9;+ for (var r = 0; r < 17; r++) {+ let x = (SCULPT_HANDSPAN[r] + vec2<f32>(-3.5, -2.5)) * SCULPT_VOX;+ let y = vec2<f32>(-f32(r), 1.0 - f32(r)) * SCULPT_VOX;+ let q = max(max(vec2<f32>(x.x, y.x) - p, p - vec2<f32>(x.y, y.y)), vec2<f32>(0.0));+ d = min(d, length(q));+ }+ return d;+}++fn s_gem_edge(p: vec3<f32>, a: vec2<f32>, b: vec2<f32>, z0: f32) -> f32 {+ let e = b - a;+ let len = length(e);+ let d = e / len;+ let q = p.xy - a;+ let dist = dot(q, vec2<f32>(-d.y, d.x));+ let along = abs(dot(q, d) - 0.5 * len);+ let z = p.z - z0;+ let girdle = (z - 0.035 - 2.2 * dist) * 0.4138;+ let crown = (z - 0.07 - 0.6 * dist + 0.18 * along) * 0.8438;+ return max(-dist, max(girdle, crown));+}++fn s_gem_arrow(p: vec3<f32>) -> f32 {+ let z0 = SCULPT_HOVER + 0.03;+ let slab = max(p.z - z0 - 0.2, z0 - 0.03 - p.z);+ let head = max(slab, max(s_gem_edge(p, vec2<f32>(-0.02, 0.03), vec2<f32>(-0.02, -0.88), z0),+ max(s_gem_edge(p, vec2<f32>(-0.02, -0.88), vec2<f32>(0.66, -0.61), z0),+ s_gem_edge(p, vec2<f32>(0.66, -0.61), vec2<f32>(-0.02, 0.03), z0))));+ let tail = max(slab, max(max(s_gem_edge(p, vec2<f32>(0.215, -0.665), vec2<f32>(0.37, -1.0), z0),+ s_gem_edge(p, vec2<f32>(0.37, -1.0), vec2<f32>(0.53, -0.93), z0)),+ max(s_gem_edge(p, vec2<f32>(0.53, -0.93), vec2<f32>(0.38, -0.60), z0),+ s_gem_edge(p, vec2<f32>(0.38, -0.60), vec2<f32>(0.215, -0.665), z0))));+ return min(head, tail);+}++fn s_facet_capsule(p: vec3<f32>, a: vec3<f32>, b: vec3<f32>, r: f32, spin: f32) -> f32 {+ let u = normalize(b - a);+ let v = normalize(cross(u, vec3<f32>(0.0, 0.0, 1.0)));+ let w = cross(u, v);+ let q = p - b;+ let h = dot(q, u);+ let rad = vec2<f32>(dot(q, v), dot(q, w));+ var d = max(h - r, -dot(p - a, u) - r);+ for (var k = 0; k < 6; k++) {+ let an = spin + f32(k) * 1.0471976;+ let s = dot(rad, vec2<f32>(cos(an), sin(an)));+ d = max(d, s - r);+ d = max(d, dot(rad, vec2<f32>(cos(an + 0.5236), sin(an + 0.5236))) * 0.8660 + h * 0.5 - r);+ d = max(d, s * 0.5 + h * 0.8660 - r);+ }+ return d;+}++const SCULPT_FACETS = array<vec3<f32>, 10>(+ vec3<f32>(1.0, 0.0, 0.0), vec3<f32>(0.0, 1.0, 0.0), vec3<f32>(0.0, 0.0, 1.0),+ vec3<f32>(0.7071, 0.7071, 0.0), vec3<f32>(0.7071, 0.0, 0.7071), vec3<f32>(0.0, 0.7071, 0.7071),+ vec3<f32>(0.5774, 0.5774, 0.5774), vec3<f32>(0.4472, 0.0, 0.8944), vec3<f32>(0.0, 0.4472, 0.8944),+ vec3<f32>(0.3015, 0.3015, 0.9045)+);++fn s_facet_ellipsoid(p: vec3<f32>, r: vec3<f32>) -> f32 {+ let q = abs(p);+ var d = -1e9;+ for (var i = 0; i < 10; i++) {+ d = max(d, dot(q, SCULPT_FACETS[i]) - length(r * SCULPT_FACETS[i]));+ }+ return d;+}++fn s_crystal_hand(p: vec3<f32>) -> f32 {+ let zc = SCULPT_HAND_ZC;+ var d = s_facet_ellipsoid(p - vec3<f32>(0.185, -0.70, zc), vec3<f32>(0.3, 0.235, 0.125));+ d = min(d, s_facet_capsule(p, vec3<f32>(0.0, -0.52, zc), vec3<f32>(0.0, -0.10, zc), 0.098, 0.3));+ d = min(d, s_facet_capsule(p, vec3<f32>(0.17, -0.57, zc + 0.012), vec3<f32>(0.17, -0.41, zc + 0.045), 0.086, 0.1));+ d = min(d, s_facet_capsule(p, vec3<f32>(0.31, -0.59, zc + 0.01), vec3<f32>(0.31, -0.45, zc + 0.04), 0.08, 0.5));+ d = min(d, s_facet_capsule(p, vec3<f32>(0.435, -0.625, zc + 0.005), vec3<f32>(0.435, -0.52, zc + 0.03), 0.07, 0.2));+ return min(d, s_facet_capsule(p, vec3<f32>(0.03, -0.77, zc + 0.03), vec3<f32>(-0.165, -0.60, zc + 0.065), 0.082, 0.7));+}++fn sculpt_proto(p: vec3<f32>, theme: i32, shape: i32) -> vec2<f32> {+ if theme == 3 {+ return s_voxels(p, shape);+ }+ if theme == 1 {+ return vec2<f32>(select(s_crystal_hand(p), s_gem_arrow(p), shape == 0), 8.0);+ }+ var body: vec2<f32>;+ var star: vec3<f32>;+ if shape == 0 {+ var h = 0.075;+ var re = 0.03;+ var dome = 0.0;+ if theme == 2 {+ h = 0.07;+ re = 0.06;+ dome = 0.035;+ }+ if theme == 4 {+ h = 0.07;+ re = 0.055;+ dome = 0.025;+ }+ body = vec2<f32>(s_arrow_solid(p, h, re, dome), 1.0);+ if theme == 0 {+ body = s_opu(body, vec2<f32>(s_piping(p, SCULPT_HOVER + 2.0 * h - 0.004), 2.0));+ }+ star = vec3<f32>(0.57, -0.86, SCULPT_HOVER + 2.0 * h + dome);+ } else {+ body = s_opu(vec2<f32>(s_glove(p, SCULPT_HAND_ZC), 1.0), vec2<f32>(s_cuff(p, SCULPT_HAND_ZC), 2.0));+ star = vec3<f32>(0.185, -0.93, SCULPT_HAND_ZC + 0.15);+ }+ if theme == 4 {+ return s_opu(body, s_sprout(p, star));+ }+ return body;+}++fn sculpt_point(q: vec3<f32>) -> vec3<f32> {+ let zref = select(SCULPT_ZREF_HAND, SCULPT_ZREF_ARROW, (sculpt_id() - 1) % 2 == 0);+ return vec3<f32>(q.x, -q.y, q.z / max(layer.color.b, 1e-3)) / SCULPT_SCALE + vec3<f32>(0.0, 0.0, zref);+}++fn sculpt_units() -> f32 {+ return SCULPT_SCALE * min(layer.color.b, 1.0);+}++fn sculpt_eval(q: vec3<f32>, occ: bool) -> vec2<f32> {+ let id = sculpt_id() - 1;+ let theme = id / 2;+ let shape = id % 2;+ let p = sculpt_point(q);+ var r: vec2<f32>;+ if occ && theme == 3 {+ let d2 = select(s_pixel_hand_dist(p.xy), s_arrow2(p.xy) - 1.2 * SCULPT_VOX, shape == 0);+ let dz = abs(p.z - (SCULPT_HOVER + 0.07)) - 0.07;+ r = vec2<f32>(length(max(vec2<f32>(d2, dz), vec2<f32>(0.0))) + min(max(d2, dz), 0.0), 7.0);+ } else {+ r = sculpt_proto(p, select(theme, 2, occ && theme == 1), shape);+ }+ return vec2<f32>(r.x * sculpt_units(), r.y);}fn sd_sprite2(p: vec2<f32>) -> f32 {@@ -517,30 +868,13 @@ fn sd_sprite2(p: vec2<f32>) -> f32 {return select(d, sqrt(out2 + e * e), out2 > 0.0);}-fn model_top_height(p: vec2<f32>) -> f32 {- let lo = layer.color.rg;- let c = clamp(p, lo, lo + sprite_size());- let relief = textureSampleLevel(texU, samp, (c - lo) / sprite_size(), 0.0).g;- return clamp(relief * layer.color.b, 0.0, MODEL_RELIEF_MAX);-}--fn sd_model(p: vec3<f32>) -> f32 {- let top = model_top_height(p.xy);- let thick = model_thick();- let half_t = (top + thick) * 0.5;- let center_z = (top - thick) * 0.5;- let w = vec2<f32>(sd_sprite2(p.xy) + MODEL_BEVEL, abs(p.z - center_z) - (half_t - MODEL_BEVEL));- return min(max(w.x, w.y), 0.0) + length(max(w, vec2<f32>(0.0))) - MODEL_BEVEL;-}--fn model_normal(p: vec3<f32>) -> vec3<f32> {- let e = 0.002;- let ka = vec3<f32>(1.0, -1.0, -1.0);- let kb = vec3<f32>(-1.0, -1.0, 1.0);- let kc = vec3<f32>(-1.0, 1.0, -1.0);- let kd = vec3<f32>(1.0, 1.0, 1.0);- return normalize(ka * sd_model(p + ka * e) + kb * sd_model(p + kb * e) +- kc * sd_model(p + kc * e) + kd * sd_model(p + kd * e));+fn model_eval(p: vec3<f32>, occ: bool) -> vec2<f32> {+ if sculpt_id() > 0 {+ return sculpt_eval(p, occ);+ }+ let half_t = model_thick() * 0.5;+ let w = vec2<f32>(sd_sprite2(p.xy) + MODEL_BEVEL, abs(p.z + half_t) - (half_t - MODEL_BEVEL));+ return vec2<f32>(min(max(w.x, w.y), 0.0) + length(max(w, vec2<f32>(0.0))) - MODEL_BEVEL, 0.0);}fn ray_box(o: vec3<f32>, d: vec3<f32>, lo: vec3<f32>, hi: vec3<f32>) -> vec2<f32> {@@ -581,25 +915,6 @@ fn plane_to_model(v: vec3<f32>, f: ModelFrame) -> vec3<f32> {return vec3<f32>(x, y * f.cp + v.z * f.sp, -y * f.sp + v.z * f.cp);}-fn model_soft_shadow(o: vec3<f32>, l: vec3<f32>, lo: vec3<f32>, hi: vec3<f32>) -> f32 {- let tb = ray_box(o, l, lo - vec3<f32>(MODEL_SHADOW_PAD), hi + vec3<f32>(MODEL_SHADOW_PAD));- if tb.x >= tb.y || tb.y <= 0.0 {- return 1.0;- }- var res = 1.0;- var t = max(tb.x, 0.004);- for (var k = 0; k < 32; k = k + 1) {- let d = sd_model(o + l * t);- res = min(res, MODEL_SOFTNESS * d / t);- if res < 0.002 || t > tb.y {- break;- }- t = t + clamp(d, 0.01, 0.2);- }- res = clamp(res, 0.0, 1.0);- return res * res * (3.0 - 2.0 * res);-}-fn model_albedo(p: vec2<f32>) -> vec3<f32> {let texel = sprite_texel();let e = 0.25 * texel;@@ -609,13 +924,169 @@ fn model_albedo(p: vec2<f32>) -> vec3<f32> {return textureSampleLevel(texY, samp, (q - layer.color.rg) / sprite_size(), 0.0).rgb;}-fn model_shade(q: vec3<f32>, rd: vec3<f32>, l: vec3<f32>) -> vec3<f32> {- let n = model_normal(q);- let albedo = model_albedo(q.xy);- let diffuse = clamp(dot(n, l), 0.0, 1.0);- let gloss = 1.0 - smoothstep(0.97, 0.995, abs(n.z));- let spec = gloss * pow(clamp(dot(n, normalize(l - rd)), 0.0, 1.0), 110.0);- return albedo * (MODEL_AMBIENT + MODEL_DIFFUSE * diffuse) + MODEL_SPECULAR * spec;+struct SculptMat {+ alb: vec3<f32>,+ rough: f32,+ spec: f32,+ sss: f32,+ refl: f32,+}++fn s_pixel_colour(p: vec3<f32>, shape: i32) -> vec3<f32> {+ let id = floor((p.xy - s_grid_origin(shape)) / SCULPT_VOX);+ if !s_occ(id + vec2<f32>(-1.0, 0.0), shape) || !s_occ(id + vec2<f32>(0.0, -1.0), shape) {+ return s_lin(0.52, 0.91, 0.77);+ }+ if !s_occ(id + vec2<f32>(1.0, 0.0), shape) || !s_occ(id + vec2<f32>(0.0, 1.0), shape) {+ return s_lin(1.0, 0.78, 0.87);+ }+ return s_lin(1.0, 0.50, 0.71);+}++fn sculpt_material(mat: f32, p: vec3<f32>, theme: i32, shape: i32) -> SculptMat {+ let primary = mat < 1.5;+ if theme == 0 {+ if shape == 0 && primary {+ return SculptMat(s_lin(0.10, 0.10, 0.115), 0.3, 0.2, 0.0, 0.9);+ }+ if shape == 0 {+ return SculptMat(s_lin(0.94, 0.91, 0.84), 0.45, 0.4, 0.2, 0.3);+ }+ if primary {+ return SculptMat(s_lin(0.95, 0.92, 0.85), 0.55, 0.35, 0.35, 0.25);+ }+ return SculptMat(s_lin(0.17, 0.18, 0.22), 0.35, 0.6, 0.0, 0.6);+ }+ if theme == 2 {+ if shape == 0 {+ return SculptMat(s_lin(1.0, 0.40, 0.30), 0.5, 0.45, 0.4, 0.25);+ }+ if primary {+ return SculptMat(s_lin(1.0, 0.79, 0.16), 0.5, 0.45, 0.4, 0.25);+ }+ return SculptMat(s_lin(0.18, 0.20, 0.29), 0.4, 0.5, 0.0, 0.4);+ }+ if theme == 4 {+ if primary && shape == 0 {+ return SculptMat(s_lin(0.62, 0.91, 0.78), 0.22, 0.8, 0.25, 0.6);+ }+ if primary {+ return SculptMat(s_lin(0.96, 0.94, 0.88), 0.5, 0.35, 0.35, 0.25);+ }+ if mat < 2.5 {+ return SculptMat(s_lin(0.62, 0.91, 0.78), 0.25, 0.7, 0.25, 0.5);+ }+ if mat < 3.5 {+ return SculptMat(s_lin(1.0, 0.80, 0.20), 0.3, 0.6, 0.3, 0.4);+ }+ if mat < 4.5 {+ return SculptMat(s_lin(0.38, 0.80, 0.55), 0.35, 0.5, 0.35, 0.3);+ }+ return SculptMat(s_lin(0.16, 0.12, 0.10), 0.2, 0.8, 0.0, 0.5);+ }+ if mat < 6.5 {+ return SculptMat(s_pixel_colour(p, shape), 0.45, 0.35, 0.15, 0.2);+ }+ return SculptMat(s_lin(0.36, 0.18, 0.54), 0.45, 0.35, 0.1, 0.2);+}++fn model_env(d: vec3<f32>, rough: f32, l: vec3<f32>, fill: vec3<f32>) -> vec3<f32> {+ var col = mix(SCULPT_SCREEN * 0.9, s_lin(0.82, 0.85, 0.92) * 0.55, smoothstep(-0.15, 0.35, d.z));+ let w = rough * 0.3;+ let k = 1.0 - rough * 0.6;+ col = col + s_lin(1.0, 0.97, 0.92) * 5.0 * k * smoothstep(0.90 - w, 0.97, dot(d, l));+ col = col + s_lin(0.85, 0.9, 1.0) * 1.6 * k * smoothstep(0.93 - w, 0.98, dot(d, fill));+ return col;+}++fn s_gem(k0: f32) -> vec3<f32> {+ let k = saturate(k0) * 3.0;+ let a = s_lin(0.20, 0.95, 1.0);+ let b = s_lin(0.15, 0.42, 1.0);+ let c = s_lin(0.45, 0.25, 0.95);+ let d = s_lin(0.88, 0.50, 1.0);+ if k < 1.0 {+ return mix(a, b, k);+ }+ if k < 2.0 {+ return mix(b, c, k - 1.0);+ }+ return mix(c, d, k - 2.0);+}++fn model_shade_crystal(n: vec3<f32>, rd: vec3<f32>, L: vec3<f32>, fall: f32, l: vec3<f32>, fill: vec3<f32>) -> vec3<f32> {+ let cosi = saturate(dot(-rd, n));+ let F = 0.04 + 0.96 * pow(1.0 - cosi, 5.0);+ let t = refract(rd, n, 1.0 / 1.6);+ let k = 0.42 + 0.9 * dot(vec2<f32>(n.x, -n.y), vec2<f32>(0.7557, -0.6549))+ + 0.6 * dot(vec2<f32>(t.x, -t.y), vec2<f32>(0.6, -0.8));+ let body = vec3<f32>(s_gem(k - 0.08).r, s_gem(k).g, s_gem(k + 0.08).b);+ var col = body * (0.1 + 1.8 * fall * pow(max(dot(n, L), 0.0), 2.5));+ col = col + body * model_env(reflect(t, vec3<f32>(0.0, 0.0, 1.0)) * vec3<f32>(1.0, 1.0, -1.0), 0.15, l, fill) * 0.5;+ col = col + vec3<f32>(pow(max(dot(reflect(rd, n), L), 0.0), 30.0) * 2.0);+ col = col + model_env(reflect(rd, n), 0.05, l, fill) * F;+ col = col + s_lin(0.5, 0.9, 1.0) * pow(1.0 - cosi, 4.0) * 0.6;+ return col;+}++fn model_tonemap(c0: vec3<f32>) -> vec3<f32> {+ let start = 0.76;+ let x = min(c0.r, min(c0.g, c0.b));+ var c = c0 - vec3<f32>(select(0.04, x - 6.25 * x * x, x < 0.08));+ let peak = max(c.r, max(c.g, c.b));+ if peak >= start {+ let d = 1.0 - start;+ let np = 1.0 - d * d / (peak + d - start);+ c = c * (np / peak);+ let g = 1.0 - 1.0 / (0.15 * (peak - np) + 1.0);+ c = mix(c, vec3<f32>(np), g);+ }+ return pow(saturate(c), vec3<f32>(1.0 / 2.2));+}++fn model_shade(q: vec3<f32>, n: vec3<f32>, rd: vec3<f32>, L: vec3<f32>, fall: f32, sh: f32, ao: f32, mat: f32,+ l: vec3<f32>, fill: vec3<f32>) -> vec3<f32> {+ let id = sculpt_id();+ if id > 0 && (id - 1) / 2 == 1 {+ return model_tonemap(model_shade_crystal(n, rd, L, fall, l, fill));+ }+ var m: SculptMat;+ var gloss = 1.0;+ if id > 0 {+ let p = sculpt_point(q) - vec3<f32>(n.x, -n.y, n.z) * 0.01;+ m = sculpt_material(mat, p, (id - 1) / 2, (id - 1) % 2);+ } else {+ m = SculptMat(pow(model_albedo(q.xy), vec3<f32>(2.2)), 0.45, 0.35, 0.2, 0.3);+ gloss = 1.0 - smoothstep(0.97, 0.995, abs(n.z));+ }+ let key = s_lin(1.0, 0.97, 0.93) * 2.1 * fall;+ let ndl = dot(n, L);+ let wrap = 0.5 * m.sss;+ let dif = saturate((ndl + wrap) / (1.0 + wrap)) * mix(sh, 1.0, 0.15 * m.sss);+ let ndh = saturate(dot(n, normalize(L - rd)));+ let shin = exp2(10.0 * (1.0 - m.rough) + 1.0);+ let spe = (pow(ndh, shin) * (shin + 8.0) / 25.0 + 0.15 * pow(ndh, 8.0)) * sh * saturate(ndl * 4.0);+ let fre = pow(1.0 - saturate(dot(n, -rd)), 5.0);+ let amb = mix(SCULPT_SCREEN * 0.12, s_lin(0.88, 0.92, 1.0) * 0.22, 0.5 + 0.5 * n.z);+ let fl = s_lin(0.85, 0.9, 1.0) * saturate(dot(n, fill)) * 0.12;+ var col = m.alb * (key * dif + (amb + fl) * ao * mix(vec3<f32>(1.0), m.alb, 0.5));+ col = col + key * spe * m.spec * gloss;+ col = col + model_env(reflect(rd, n), m.rough, l, fill) * m.refl * (0.04 + 0.96 * fre) * ao * gloss;+ col = col + s_lin(0.9, 0.95, 1.0) * fre * 0.08 * ao * sh;+ return model_tonemap(col);+}++// Les passes de la boucle unique de `cursor_model` (cf. HLSL : un seul appel de `model_eval`).+const STAGE_MARCH: i32 = 0;+const STAGE_NORMAL: i32 = 1;+const STAGE_AO: i32 = 2;+const STAGE_SELF: i32 = 3;+const STAGE_PLANE: i32 = 4;+const STAGE_DONE: i32 = 5;++fn model_tetra(k: i32) -> vec3<f32> {+ let b = vec3<f32>(f32(((k + 3) >> 1u) & 1), f32((k >> 1u) & 1), f32(k & 1));+ return 0.5773 * (2.0 * b - vec3<f32>(1.0));}fn cursor_model(local: vec2<f32>) -> vec4<f32> {@@ -630,7 +1101,7 @@ fn cursor_model(local: vec2<f32>) -> vec4<f32> {let unit = layer.src.w;let tip = layer.src_prev.xyz;let lo = vec3<f32>(layer.color.rg, -model_thick());- let hi = vec3<f32>(layer.color.rg + sprite_size(), MODEL_RELIEF_MAX);+ let hi = vec3<f32>(layer.color.rg + sprite_size(), layer.trail_a.z);let dw = vec3<f32>(local + layer.src.xy, -persp);let dlen = length(dw);@@ -638,53 +1109,146 @@ fn cursor_model(local: vec2<f32>) -> vec4<f32> {let ro = plane_to_model((world_to_plane(vec3<f32>(-layer.mb.z, -layer.mb.w, persp), f) - tip) / unit, f);let rd = plane_to_model(world_to_plane(dw / dlen, f), f);let l = plane_to_model(world_to_plane(MODEL_LIGHT, f), f);+ let fill = plane_to_model(world_to_plane(MODEL_FILL, f), f);let nz = plane_to_model(vec3<f32>(0.0, 0.0, 1.0), f);let hz = -tip.z / unit;+ let stride = select(1.0, 0.85, sculpt_id() > 0);+ let lamp = vec3<f32>(layer.color.rg + sprite_size() * 0.5, 0.0) + l * SCULPT_LAMP_DIST;- var cov = 0.0;- var rgb = vec3<f32>(0.0);let tb = ray_box(ro, rd, lo - vec3<f32>(0.02), hi + vec3<f32>(0.02));- if tb.x < tb.y && tb.y > 0.0 {- var t = max(tb.x, 0.0);- var best = 1e9;- var t_best = t;- var hit = false;- for (var k = 0; k < 64; k = k + 1) {- let d = sd_model(ro + rd * t);+ var stage = select(STAGE_DONE, STAGE_MARCH, tb.x < tb.y && tb.y > 0.0);+ var plane_next = stage == STAGE_DONE;+ var k = 0;+ var t = max(tb.x, 0.0);+ var best = 1e9;+ var t_best = t;+ var mat = 0.0;+ var cov = 0.0;+ var q = vec3<f32>(0.0);+ var n = vec3<f32>(0.0);+ var L = vec3<f32>(0.0);+ var ao = 1.0;+ var sh = 1.0;+ var ts = vec2<f32>(0.0);+ var res = 1.0;+ var g = vec3<f32>(0.0);+ var inside = 0.0;+ var contact = 0.0;+ var dropped = 0.0;+ for (var it = 0; it < 180; it++) {+ if plane_next {+ plane_next = false;+ stage = STAGE_DONE;+ let denom = dot(rd, nz);+ if cov < 1.0 && denom < -1e-4 {+ g = ro + rd * ((hz - dot(ro, nz)) / denom);+ let gp = tip + unit * model_to_plane(g, f);+ inside = saturate(min(layer.mb.x - abs(gp.x), layer.mb.y - abs(gp.y)) + 0.5);+ if inside > 0.0 {+ stage = STAGE_PLANE;+ k = 0;+ ts = vec2<f32>(0.0);+ }+ }+ }+ var pos: vec3<f32>;+ if stage == STAGE_MARCH {+ pos = ro + rd * t;+ } else if stage == STAGE_NORMAL {+ pos = q + 0.002 * model_tetra(k);+ } else if stage == STAGE_AO {+ pos = q + (0.01 + 0.0175 * f32(k)) * SCULPT_SCALE * n;+ } else if stage == STAGE_SELF {+ pos = q + n * 0.003 + L * ts.x;+ } else if stage == STAGE_PLANE {+ pos = g + l * ts.x;+ } else {+ break;+ }+ let m = model_eval(pos, stage == STAGE_PLANE);+ let d = m.x;+ if stage == STAGE_MARCH {let fp = t / dlen;- if d < 0.1 * fp {- hit = true;+ let hit = d < 0.1 * fp;+ if hit || d / fp < best {+ best = select(d / fp, 0.0, hit);t_best = t;- break;+ mat = m.y;}- if d / fp < best {- best = d / fp;- t_best = t;+ t = t + d * stride;+ k++;+ if hit || t > tb.y || k == 96 {+ cov = saturate(1.0 - best);+ if cov > 0.0 {+ q = ro + rd * t_best;+ stage = STAGE_NORMAL;+ k = 0;+ } else {+ plane_next = true;+ }}- t = t + d;- if t > tb.y {- break;+ } else if stage == STAGE_NORMAL {+ n = n + model_tetra(k) * d;+ k++;+ if k == 4 {+ n = normalize(n);+ stage = STAGE_AO;+ k = 0;+ ao = 0.0;+ }+ } else if stage == STAGE_AO {+ ao = ao + ((0.01 + 0.0175 * f32(k)) * SCULPT_SCALE - d) * pow(0.85, f32(k));+ k++;+ if k == 5 {+ ao = saturate(1.0 - 3.5 * ao / SCULPT_SCALE);+ L = normalize(lamp - q);+ let tbs = ray_box(q + n * 0.003, L, lo - vec3<f32>(MODEL_SHADOW_PAD), hi + vec3<f32>(MODEL_SHADOW_PAD));+ if tbs.x < tbs.y && tbs.y > 0.0 {+ stage = STAGE_SELF;+ k = 0;+ ts = vec2<f32>(max(tbs.x, 0.004), tbs.y);+ res = 1.0;+ } else {+ plane_next = true;+ }+ }+ } else if stage == STAGE_SELF {+ res = min(res, MODEL_SOFTNESS * d / ts.x);+ ts.x = ts.x + clamp(d, 0.01, 0.2);+ k++;+ if res < 0.002 || ts.x > ts.y || k == 32 {+ res = saturate(res);+ sh = res * res * (3.0 - 2.0 * res);+ plane_next = true;+ }+ } else if k == 0 {+ contact = 1.0 - smoothstep(0.0, MODEL_CONTACT_RADIUS, d);+ let tbp = ray_box(g, l, lo - vec3<f32>(MODEL_SHADOW_PAD), hi + vec3<f32>(MODEL_SHADOW_PAD));+ ts = vec2<f32>(max(tbp.x, 0.004), tbp.y);+ res = 1.0;+ k = 1;+ if !(tbp.x < tbp.y && tbp.y > 0.0) {+ stage = STAGE_DONE;+ }+ } else {+ res = min(res, MODEL_SOFTNESS * d / ts.x);+ ts.x = ts.x + clamp(d, 0.01, 0.2);+ k++;+ if res < 0.002 || ts.x > ts.y || k == 33 {+ res = saturate(res);+ dropped = 1.0 - res * res * (3.0 - 2.0 * res);+ stage = STAGE_DONE;}- }- cov = select(clamp(1.0 - best, 0.0, 1.0), 1.0, hit);- if cov > 0.0 {- rgb = model_shade(ro + rd * t_best, rd, l);}}- var shadow = 0.0;- let denom = dot(rd, nz);- if cov < 1.0 && denom < -1e-4 {- let g = ro + rd * ((hz - dot(ro, nz)) / denom);- let gp = tip + unit * model_to_plane(g, f);- let inside = clamp(min(layer.mb.x - abs(gp.x), layer.mb.y - abs(gp.y)) + 0.5, 0.0, 1.0);- if inside > 0.0 {- let dropped = 1.0 - model_soft_shadow(g, l, lo, hi);- let contact = 1.0 - smoothstep(0.0, MODEL_CONTACT_RADIUS, sd_model(g));- shadow = inside * max(dropped * MODEL_SHADOW_ALPHA, contact * MODEL_CONTACT_ALPHA);- }+ var rgb = vec3<f32>(0.0);+ if cov > 0.0 {+ let tl = lamp - q;+ let fall = SCULPT_LAMP_DIST * SCULPT_LAMP_DIST / dot(tl, tl);+ rgb = model_shade(q, n, rd, normalize(tl), fall, sh, ao, mat, l, fill);}-+ let shadow = inside * max(dropped * MODEL_SHADOW_ALPHA, contact * MODEL_CONTACT_ALPHA);let a = cov * layer.color.a;return vec4<f32>(rgb * a, a + (1.0 - a) * shadow * layer.color.a); // premultiplie, ombre noire}diff --git a/crates/compositor/tests/cursor_model_render.rs b/crates/compositor/tests/cursor_model_render.rsindex 9b473ec8f..aa54170de 100644--- a/crates/compositor/tests/cursor_model_render.rs+++ b/crates/compositor/tests/cursor_model_render.rs@@ -150,21 +150,65 @@ impl FakeFrame {/// Les seize sprites livrés, au format `cursorSprites` de la scène.fn sprites_json() -> String {- let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))- .join("../../public/cursors/default")+ sprites_json_with(None)+}++/// Le dossier des curseurs livrés, `public/cursors`.+fn cursors_dir() -> String {+ std::path::Path::new(env!("CARGO_MANIFEST_DIR"))+ .join("../../public/cursors").to_string_lossy()- .replace('\\', "/");+ .replace('\\', "/")+}++/// Les cinq thèmes d'origine et les hotspots de leur flèche et de leur main plates+/// (`CURSOR_THEMES`, `src/lib/cursor/cursorThemes.ts`, sur 32).+const SCULPTED: [(&str, [f32; 2], [f32; 2]); 5] = [+ ("studio-ink", [6.2304, 2.0992], [12.848, 2.0704]),+ ("prism-glow", [6.3456, 2.0672], [11.968, 2.0352]),+ ("pop-coral", [10.4768, 2.1792], [12.3456, 2.0]),+ ("pixel-candy", [7.3664, 2.0], [13.376, 1.9264]),+ ("star-sprout", [4.7232, 2.1152], [13.1712, 2.0384]),+];++/// `sprites_json`, avec la flèche et la main plates du thème d'origine `sculpted` et leur curseur+/// sculpté, comme les passe `resolveCursorSprites` en 3D.+fn sprites_json_with(sculpted: Option<&str>) -> String {+ let dir = cursors_dir();+ let theme = sculpted.map(|name| *SCULPTED.iter().find(|(t, ..)| *t == name).expect("thème d'origine"));let entries: Vec<String> = STATES.iter()- .map(|(key, [hx, hy])| format!(r#""{key}":{{"path":"{dir}/{key}.png","hotspotX":{hx},"hotspotY":{hy}}}"#))+ .map(|(key, [hx, hy])| match (theme, *key) {+ (Some((name, [ax, ay], _)), "arrow") | (Some((name, _, [ax, ay])), "pointer") => format!(+ r#""{key}":{{"path":"{dir}/{name}/{key}.png","hotspotX":{},"hotspotY":{},"sculpt":"{name}/{key}"}}"#,+ ax / 32.0,+ ay / 32.0+ ),+ _ => format!(r#""{key}":{{"path":"{dir}/default/{key}.png","hotspotX":{hx},"hotspotY":{hy}}}"#),+ }).collect();format!("{{{}}}", entries.join(","))}/// `model3d` : `None` = clé absente (payload d'avant le réglage).fn scene_json(rotation: &str, model3d: Option<bool>, theme: &str, motion_blur: f32, size: f32) -> String {+ scene_json_with(rotation, model3d, theme, motion_blur, size, &sprites_json())+}++/// Un thème d'origine en 3D : sa flèche et sa main sculptées.+fn sculpted_scene_json(rotation: &str, theme: &str, size: f32) -> String {+ scene_json_with(rotation, Some(true), theme, 0.0, size, &sprites_json_with(Some(theme)))+}++fn scene_json_with(+ rotation: &str,+ model3d: Option<bool>,+ theme: &str,+ motion_blur: f32,+ size: f32,+ sprites: &str,+) -> String {let model3d = model3d.map(|m| format!(r#","model3d":{m}"#)).unwrap_or_default();- let sprites = sprites_json();format!(r##"{{"clips":[{{"screenPath":"/s.mp4","webcamPath":"","sourceStartSec":0,"sourceEndSec":10,"webcamOffsetSec":0,"hasAudio":false}}],"layout":{{"preset":"no-webcam","webcamSize":1,"webcamShape":"rounded","webcamMirror":false,"webcamPosition":null,"webcamReactiveZoom":false,@@ -710,6 +754,65 @@ fn the_motion_blur_trail_draws_modelled_copies() {assert!(rgba != flat, "la traînée 3D est celle du sprite plat");}+/// Les dix curseurs sculptés (cinq thèmes, flèche et main), dessinés par le shader et non+/// extrudés d'un PNG : chacun est là, sa pointe sur le hotspot, son corps en bas à droite de+/// celle-ci (y vers le bas : un modèle retourné finirait au-dessus), et il porte son ombre en+/// l'air.+#[test]+fn the_sculpted_cursors_stand_at_the_hotspot() {+ let Some(gpu) = gpu() else { return };+ let comp = Compositor::new_sized(&gpu, 1280, 720).expect("compositor");+ let (blue, orange) = (FakeFrame::new(&gpu, Tint::Blue), FakeFrame::new(&gpu, Tint::Orange));+ let bare = render_any(&comp, &blue, &hidden_json("null"), &resting("sculpt-bare", false)).0;+ let mut failures = Vec::new();+ for (theme, ..) in SCULPTED {+ for state in ["arrow", "pointer"] {+ let json = sculpted_scene_json("null", theme, 5.0);+ let still = resting_at(&format!("sculpt-{theme}-{state}"), Some(state), false, 0.5);+ let (hover, p) = render(&comp, &blue, &json, &still);+ let hover_b = render(&comp, &orange, &json, &still).0;+ save(&format!("sculpt-{theme}-{state}"), &hover);+ let mask = opaque_mask(&hover, &hover_b, &bare);+ let (mut body, mut c, mut near) = (0usize, [0.0f32; 2], f32::MAX);+ for y in 0..720 {+ for x in 0..1280 {+ if mask[y * 1280 + x] {+ body += 1;+ c = [c[0] + x as f32, c[1] + y as f32];+ near = near.min((x as f32 - p.tip[0]).hypot(y as f32 - p.tip[1]));+ }+ }+ }+ let c = [c[0] / body.max(1) as f32, c[1] / body.max(1) as f32];+ let shadow = (0..1280 * 720)+ .filter(|&i| {+ let (a, b) = (&hover[i * 4..i * 4 + 4], &bare[i * 4..i * 4 + 4]);+ !mask[i] && a != b && luma([a[0], a[1], a[2], 255]) < luma([b[0], b[1], b[2], 255]) - 6.0+ })+ .count();+ let u = p.unit;+ println!(+ "{theme}/{state} : unité {u:.1} px, corps {body} px, pointe à {near:.1} px du hotspot, \+ centroïde {c:?} pour la pointe {:?}, ombre {shadow} px",+ p.tip+ );+ if (body as f32) < 0.12 * u * u {+ failures.push(format!("{theme}/{state} : {body} px de corps pour {u:.0} px d'unité"));+ }+ if near > 0.08 * u {+ failures.push(format!("{theme}/{state} : le modèle est à {near:.1} px du hotspot"));+ }+ if !(c[0] > p.tip[0] && c[1] > p.tip[1] + 0.2 * u) {+ failures.push(format!("{theme}/{state} : corps en {c:?}, pas en bas à droite de {:?}", p.tip));+ }+ if shadow * 10 < body * 3 {+ failures.push(format!("{theme}/{state} : pas d'ombre en l'air ({shadow} px)"));+ }+ }+ }+ assert!(failures.is_empty(), "{failures:#?}");+}+/// Planches à regarder (opt-in, `OPENSCREEN_CURSOR3D_OUT`) : les seize états en l'air sur un/// écran à plat, chacun à côté de son sprite plat ; la flèche, la main et le I posés sur un écran/// incliné ; et les grandes flèches (taille 8) qui servent à la comparaison avec le modèle@@ -751,6 +854,19 @@ fn contact_sheets() {}tilted.save(format!("{dir}/states-touch-flat-and-iso.png")).expect("planche");+ // Les dix curseurs sculptés : un thème par ligne, flèche et main en l'air sur l'écran à plat,+ // puis posées sur l'écran incliné.+ let cases = [("arrow", "null", false), ("pointer", "null", false), ("arrow", r#""iso""#, true), ("pointer", r#""iso""#, true)];+ let mut sculpted = image::RgbaImage::new(4 * CELL, SCULPTED.len() as u32 * CELL);+ for (row, (theme, ..)) in SCULPTED.iter().enumerate() {+ for (col, (state, rotation, click)) in cases.iter().enumerate() {+ let track = resting_as(&format!("sheet-{theme}-{col}"), Some(state), *click);+ let (rgba, p) = render(&comp, &screen, &sculpted_scene_json(rotation, theme, 5.0), &track);+ image::imageops::overlay(&mut sculpted, &crop(&rgba, p), (col as u32 * CELL) as i64, (row as u32 * CELL) as i64);+ }+ }+ sculpted.save(format!("{dir}/sculpted.png")).expect("planche");+let (still, clicked) = (resting("big-still", false), resting("big-clicked", true));for (name, rotation) in [("flat", "null"), ("iso", r#""iso""#)] {for (case, tr) in [("hover", &still), ("touch", &clicked)] {diff --git a/design/cursors/3d-direction.md b/design/cursors/3d-direction.mdindex 2274bc836..6333c23d0 100644--- a/design/cursors/3d-direction.md+++ b/design/cursors/3d-direction.md@@ -1,36 +1,30 @@# Modelled cursor themes-`3d-concept.png` is a visual reference, not a render from OpenScreen. Mode 15-now ray-marches each cursor silhouette with an authored grayscale height map-for its top surface. This changes the surface normals, lighting and shadow as-the cursor tilts; it is still a raster height-field model rather than an-individually rigged mesh.+`3d-concept.png` is a visual reference, not a render from OpenScreen.-The five original packs have separate PNG faces and relief maps for their-arrow and pointing hand. Their model hotspots are authored independently from-the 2D hotspots. Text, resize, move and other OS cursor states keep their own-built-in shapes and use the compositor's beveled extrusion while 3D is on.-Themes without a dedicated model face use the same state-specific fallback.--The face PNG supplies color only. Its alpha defines the silhouette and its-separate grayscale PNG defines height (black at the edge, brighter at the-raised face). The height scale is 0.12 model units. Pop Coral's decorative-offset and rays are omitted from the sculpted face; Pixel Candy uses stepped-height bands; Prism Glow varies its facets; Studio Ink recesses the ivory-inlay and removes the glove outline; Star Sprout raises the star and leaves.-Regenerate both faces and relief maps with-`node scripts/generate-original-cursor-themes.mjs`.+With the 3D option on, mode 15 ray-marches each original theme's arrow and hand+as a sculpted model: signed distance functions written in the compositor's three+shaders (HLSL, Metal, WGSL), not a PNG face or a height map.+`crates/compositor/src/sculpt.rs` names the ten models and holds their bounding+boxes and hotspots. The scene names the model (`"<theme>/<state>"`); text,+resize, move and the other OS states keep their built-in art and the+compositor's beveled extrusion.| Theme | Arrow model | Hand model || --- | --- | --- |-| Studio Ink | Matte black body; ivory line becomes an inset groove, not an outer stroke. | Ivory glove with convex palm and separate rounded fingers; no dark silhouette outline. |-| Prism Glow | Solid transparent crystal with its own faceted edges; no navy ink stroke. | Individually faceted crystal fingers and palm; no navy ink stroke. |-| Pop Coral | Soft coral rubber body with a gently rounded tip and no fake yellow offset or navy rim. | Plump yellow rubber fingers and palm; no navy outline, with any accent placed on a physical cuff. |-| Pixel Candy | Pink and mint face voxels; purple is visible side/back blocks, not a painted line. | Distinct finger voxels and small bevels; purple stays as real side/back blocks. |-| Star Sprout | Mint ceramic body without a heavy blue border; star and leaves are attached raised pieces. | Ivory glove without blue border; mint cuff and tiny star/leaves are separate parts. |+| Studio Ink | Matte black body with an ivory piping set in from the edge. | Ivory glove with a dark cuff. |+| Prism Glow | Cut crystal: flat facets, a polygonal silhouette, cyan to violet dispersion. | The same glove cut into faceted fingers and palm. |+| Pop Coral | Soft coral rubber with rounded edges and a gentle dome. | Plump yellow rubber glove with a navy cuff. |+| Pixel Candy | Beveled voxels: a pink face with mint and pale pink edges, purple blocks one step behind. | Voxel glove with the same colours and purple back layer. |+| Star Sprout | Glossy mint ceramic carrying a star with a face and two leaves. | Ivory glove with a mint cuff and the same star. |++All models share one close lamp: a gradient and a highlight even on flat faces,+soft self shadows, ambient occlusion and a studio environment in the+reflections, plus the compositor's cast and contact shadows on the screen. The+hotspot stays on the arrow tip and the index fingertip through hover, tilt, yaw,+click and size changes.-The model keeps the compositor's contact shadows and stable hotspot during-yaw, pitch, click and size changes. A future mesh pipeline could give fingers-more undercut and independent articulation; the current height field already-provides a style-specific convex palm, raised finger ridges and sculpted arrow-faces while remaining compatible with the shared ray-march renderer.+To change a model, edit it in all three shaders (`sculpt_proto`,+`sculpt_material`) and keep `sculpt.rs` in step: its boxes must contain the+shapes, and a test checks that the shaders mirror its constants. Pixel Candy's+arrow voxels are sampled from the arrow polygon; `sculpt.rs` says how.diff --git a/design/cursors/README.md b/design/cursors/README.mdindex 991cc2b44..b3a21cd3c 100644--- a/design/cursors/README.md+++ b/design/cursors/README.md@@ -15,21 +15,17 @@ original high-resolution masters; there is no SVG conversion step.Each `source.png` contains an arrow on the left and a hand on the right. Run`node scripts/generate-original-cursor-themes.mjs` to crop, remove low-alphafringe pixels, and resize them into transparent 128 × 128 PNGs under-`public/cursors/<theme>/`. Each `model-source.png` is a separate raster face-pair for the 3D option. The same script builds the model face PNGs and aligned-grayscale relief PNGs; the relief is not vector art. It prints the normalized-tip hotspots; copy them into `src/lib/cursor/cursorThemes.ts` after changing a-master.+`public/cursors/<theme>/`. It prints the normalized tip hotspots; copy them into+`src/lib/cursor/cursorThemes.ts` after changing a master.-The model face is selected only while the existing 3D option is enabled. The-theme picker and normal cursor rendering continue to use each flat `source.png`-version. Text, resize, move and other states remain state-accurate through the-built-in art and receive the shared 3D extrusion. Pop Coral's older-`source-3d.png` remains a reference for its offset-free treatment.+With the 3D option on, the compositor draws each theme's arrow and hand as a+model sculpted in its shaders (`crates/compositor/src/sculpt.rs`), not from these+PNGs. The theme picker and the flat cursor keep using the PNGs. Text, resize,+move and other states remain state-accurate through the built-in art and+receive the shared 3D extrusion.`contact-sheet.png` shows the sprites enlarged on a light background;`dark-32px.png` shows them at their 32-pixel reference size on a dark background.-`model-face-sheet.png` compares the separate 3D arrow and hand faces.The 3D modeling direction and concept image are in `3d-direction.md` and`3d-concept.png`.The consolidated acceptance list is in `requirements.md`.diff --git a/design/cursors/model-face-sheet.png b/design/cursors/model-face-sheet.pngdeleted file mode 100644index fc3ea30ec..000000000Binary files a/design/cursors/model-face-sheet.png and /dev/null differdiff --git a/design/cursors/pixel-candy/model-source.png b/design/cursors/pixel-candy/model-source.pngdeleted file mode 100644index 1447b17c0..000000000Binary files a/design/cursors/pixel-candy/model-source.png and /dev/null differdiff --git a/design/cursors/pop-coral/model-source.png b/design/cursors/pop-coral/model-source.pngdeleted file mode 100644index 651148a00..000000000Binary files a/design/cursors/pop-coral/model-source.png and /dev/null differdiff --git a/design/cursors/pop-coral/source-3d.png b/design/cursors/pop-coral/source-3d.pngdeleted file mode 100644index 509aa7dc7..000000000Binary files a/design/cursors/pop-coral/source-3d.png and /dev/null differdiff --git a/design/cursors/prism-glow/model-source.png b/design/cursors/prism-glow/model-source.pngdeleted file mode 100644index 5a732c57a..000000000Binary files a/design/cursors/prism-glow/model-source.png and /dev/null differdiff --git a/design/cursors/requirements.md b/design/cursors/requirements.mdindex 59e772b46..3274014c7 100644--- a/design/cursors/requirements.md+++ b/design/cursors/requirements.md@@ -21,13 +21,14 @@ their 3D models.- Every replacement theme and supported cursor state must work with theexisting 3D cursor option.-- Every replacement arrow and hand has its own PNG face and aligned grayscale- relief map. The compositor ray-marches the varying top surface so lighting,- normals and contact shadows respond to cursor tilt and rotation.+- Every replacement arrow and hand is a real volume, sculpted in the+ compositor's shaders (`crates/compositor/src/sculpt.rs`): lighting, normals,+ self shadows and contact shadows respond to cursor tilt and rotation. A PNG+ face or a height map is not a model.- A rounded extrusion of the PNG silhouette remains the fallback for cursorstates that do not have a dedicated theme model. The five replacement packs- add style-specific volume: a convex palm and separate finger ridges, faceted- crystal faces, puffy rubber, stepped voxel heights, and ceramic accents.+ add style-specific volume: a glove with separate fingers, cut crystal facets,+ puffy rubber, beveled voxels, and ceramic accents.- Model the arrow and hand separately for every theme. Do not apply onecontour, material, or roundness rule to all designs.- Preserve the cursor hotspot through hover, tilt, yaw, click, and size changes.@@ -39,7 +40,7 @@ their 3D models.| Theme | Arrow | Hand || --- | --- | --- |-| Studio Ink | Matte black sculpted body; ivory mark becomes an inset groove. | Ivory glove with a convex palm and separate fingers; remove the dark outline. |+| Studio Ink | Matte black sculpted body; ivory mark becomes a piping set in from the edge. | Ivory glove with a convex palm and separate fingers; remove the dark outline. || Prism Glow | Translucent faceted crystal; no navy ink contour. | Crystal palm and distinct faceted fingers; no navy ink contour. || Pop Coral | Rounded coral rubber; omit the yellow offset and navy rim. | Plump yellow rubber glove; no navy outline, accents become physical details. || Pixel Candy | Keep the stepped voxel form; purple is side/back blocks, not a flat outline. | Stepped voxel fingers and palm; preserve purple as physical side/back blocks. |diff --git a/design/cursors/star-sprout/model-source.png b/design/cursors/star-sprout/model-source.pngdeleted file mode 100644index 7a34a12a8..000000000Binary files a/design/cursors/star-sprout/model-source.png and /dev/null differdiff --git a/design/cursors/studio-ink/model-source.png b/design/cursors/studio-ink/model-source.pngdeleted file mode 100644index 186abe1fe..000000000Binary files a/design/cursors/studio-ink/model-source.png and /dev/null differdiff --git a/docs/3d-effects-v2.md b/docs/3d-effects-v2.mdindex 5536e3cca..f52e52f68 100644--- a/docs/3d-effects-v2.md+++ b/docs/3d-effects-v2.md@@ -201,24 +201,25 @@ inconnues sont ignorées).### B.2 Le réglage-**Un seul interrupteur**, `cursor.model3d` (« 3D cursor », **éteint par défaut**) : il remplace-**chaque état** du thème par défaut (les seize de `DEFAULT_CURSOR_SPRITES` : flèche, I, main,-croix, mains ouverte et fermée, redimensionnements, déplacement, interdit, attente…) par son-sprite extrudé. Les autres thèmes gardent leur sprite plat ; l'indice du panneau le dit-(« Default style: every cursor shape turns 3D »). Curseur masqué, l'interrupteur est grisé et+**Un seul interrupteur**, `cursor.model3d` (« 3D cursor », **éteint par défaut**) : il passe+**chaque état** du curseur en 3D. La flèche et la main des cinq thèmes d'origine deviennent leur+modèle sculpté (B.3 bis) ; les autres états, et tous ceux du thème par défaut (les seize de+`DEFAULT_CURSOR_SPRITES` : flèche, I, main, croix, mains ouverte et fermée, redimensionnements,+déplacement, interdit, attente…), leur sprite extrudé. Curseur masqué, l'interrupteur est grisé etson info-bulle dit pourquoi. Éteint, la frame est celle d'avant **à l'octet** (vérifié à plat etincliné contre le commit de base).Tuyauterie : `CursorVisualSettings.model3d`, clé legacy `cursorModel3d`, préréglages (absent →éteint), `SceneCursor.model3d` (`serde(default)`), `LiveParams.cursor_model3d`, paramètre live-`cursorModel3d`. Le contrat de scène ne gagne que ce champ optionnel, sans donnée de sprite-neuve : le modèle se tire du sprite que la scène transporte déjà.+`cursorModel3d`. Le contrat de scène gagne ce champ optionnel et, par sprite, le nom de son+modèle sculpté (`SceneCursorSprite::sculpt`, `"<thème>/<état>"`, posé par `resolveCursorSprites`) ;+un sprite sans ce nom est extrudé.### B.3 Le modèle (mode 15)Un seul mode de shader, identique en HLSL, MSL et WGSL (`cursor_model`), lancé de rayons par-pixel dans la boîte de dessin. **Aucune forme n'est modélisée à la main** : le modèle est la-silhouette du sprite de l'état courant.+pixel dans la boîte de dessin. Deux sortes de modèles : le curseur sculpté d'un thème d'origine+(B.3 bis), sinon la silhouette du sprite de l'état courant, extrudée comme suit.- **Forme** : un champ de distance signé tiré de l'alpha du PNG, une fois au chargement(`cursor_sdf.rs`) : alpha suréchantillonné ×4 (bilinéaire), seuil 0,5, transformée de@@ -237,8 +238,8 @@ silhouette du sprite de l'état courant.- **Matières** : celles du sprite. Le dessus porte son art (alpha droit, comme aux modes 7 et 13) ;le chanfrein, les flancs et le dessous lisent l'art à 1,5 texel à l'intérieur de la silhouette,le long du gradient du champ : la couleur du bord de CE sprite (filet blanc de la flèche, trait- noir des mains), jamais la frange mêlée au transparent. Lumière fixée à la **caméra**- (haut-gauche, devant), ambiante 0,36, diffuse 0,75, reflet sur les arrondis seulement.+ noir des mains), jamais la frange mêlée au transparent. Éclairage : celui des curseurs sculptés+ (B.3 bis), le reflet restant sur les arrondis.- **Ombre** : un rayon qui rate le modèle tombe sur le plan de l'écran. De là, marche vers lalumière (pénombre `k·d/t`, k = 6, bornée à 0,45 unité) et ombre de contact (0,12 unité autourdu modèle). Opacité 0,5 chacune, et seulement à l'intérieur de l'écran.@@ -253,6 +254,27 @@ coïncide avec l'alpha seuillé (IoU ≥ 0,9997 hors frange) ; sur un disque etsynthétiques, l'écart au champ exact reste sous 0,5 texel source dans la bande de 3 texels autourdu bord (0,48 au pire), sous 1 texel au-delà (le flou arrondit les crêtes).+### B.3 bis Les curseurs sculptés++La flèche et la main des cinq thèmes d'origine sont **modélisées à la main**, en fonctions de+distance signée écrites dans les trois shaders (`sculpt_proto`, `sculpt_material`) : capsules et+unions lissées pour les gants, extrusion arrondie et bombée pour les flèches, voxels biseautés+pour Pixel Candy, polyèdres taillés pour le cristal de Prism Glow. Le PNG du thème reste l'art en+2D. En 3D, la scène nomme le modèle ; `sculpt.rs` en tient la boîte, qui pose le hotspot (pointe+de la flèche, bout de l'index), règle la garde au sol et borne la boîte de dessin. Emplacement du+cbuffer : `trail_a` = [modèle, épaisseur sous z = 0, hauteur au-dessus, 0] (`cursor_model_cb`).++- **Éclairage**, sprites extrudés compris : une lampe proche en haut à gauche, qui met un dégradé+ et un reflet même sur une face plane ; une lumière d'appoint faible ; le côté ombré teinté par+ la matière ; occlusion ambiante, ombre propre douce vers la lampe, studio dans les reflets,+ liseré de Fresnel ; tone map Khronos PBR Neutral.+- **Ombre sur l'écran** : celle de B.3. Le cristal et les voxels donnent de mauvaises distances+ loin de leur surface (bornes de plans, champ de grille) : l'ombre prend la forme lisse de Pop+ Coral pour le cristal et le contour extrudé pour les voxels.+- **Coût de compilation** : FXC recopie chaque appel. La marche, les normales, l'occlusion et les+ ombres forment donc une seule boucle à étapes avec un seul appel au modèle, et l'étoile de Star+ Sprout un seul appel pour les deux formes.+### B.4 La caméra et l'ancrageLa caméra est reconstruite par pixel exactement comme `regions.rs` projette le plan : rotationdiff --git a/electron/native-bridge/services/compositorViewService.test.ts b/electron/native-bridge/services/compositorViewService.test.tsindex d6b3aade7..46e4beb28 100644--- a/electron/native-bridge/services/compositorViewService.test.ts+++ b/electron/native-bridge/services/compositorViewService.test.ts@@ -378,10 +378,7 @@ describe("resolveSceneAssetPaths", () => {fs.mkdirSync(modelDir, { recursive: true });fs.writeFileSync(path.join(modelDir, "selfie_segmentation_landscape.onnx"), "onnx");const assetPaths = [- ...Object.values(themed?.assets ?? {}).flatMap((asset) => [- asset.assetPath,- ...(asset.model3d ? [asset.model3d.assetPath, asset.model3d.depthPath] : []),- ]),+ ...Object.values(themed?.assets ?? {}).map((asset) => asset.assetPath),...Object.values(DEFAULT_CURSOR_SPRITES).map((s) => s.assetPath),];for (const assetPath of assetPaths) {@@ -422,7 +419,7 @@ describe("resolveSceneAssetPaths", () => {path: string;hotspotX: number;hotspotY: number;- modelDepthPath?: string;+ sculpt?: string;};// The renderer asks for an effect and knows nothing about the disk; this process answers@@ -520,16 +517,16 @@ describe("resolveSceneAssetPaths", () => {expect(fs.existsSync(arrow.path)).toBe(true);});- it("resolves a themed 3D face and its relief map to paths that exist on disk", () => {- const model3d = themed?.assets.arrow?.model3d;- if (!themed || !model3d) throw new Error("a bundled theme needs a 3D arrow face");- const arrow = resolved({ cursor: { theme: themed.id, model3d: true } }).cursor.cursorSprites- .arrow;+ // In 3D the compositor draws the theme's own sculpted arrow; the flat sprite still has to+ // resolve, since the state falls back to it when the model is unknown.+ it("names a themed arrow's sculpted 3D model next to its flat sprite", () => {+ if (!themed) throw new Error("a bundled theme needs an arrow");+ const arrow: ResolvedSprite = resolved({ cursor: { theme: themed.id, model3d: true } }).cursor+ .cursorSprites.arrow;- expect(arrow.path).toBe(path.join(resources, model3d.assetPath));- expect(arrow.modelDepthPath).toBe(path.join(resources, model3d.depthPath));+ expect(arrow.path).toBe(path.join(resources, themed.assets.arrow!.assetPath));+ expect(arrow.sculpt).toBe(`${themed.id}/arrow`);expect(fs.existsSync(arrow.path)).toBe(true);- expect(fs.existsSync(arrow.modelDepthPath!)).toBe(true);});it("fills the states a theme doesn't ship with the built-in art", () => {diff --git a/electron/native-bridge/services/compositorViewService.ts b/electron/native-bridge/services/compositorViewService.tsindex aa9774e07..2725cd0ae 100644--- a/electron/native-bridge/services/compositorViewService.ts+++ b/electron/native-bridge/services/compositorViewService.ts@@ -103,22 +103,21 @@ function resolveCursorSpritePaths(themeId: string,alwaysArrow: boolean,model3d = false,-): Record<string, { path: string; hotspotX: number; hotspotY: number; modelDepthPath?: string }> {+): Record<string, { path: string; hotspotX: number; hotspotY: number; sculpt?: string }> {const resolved: Record<string,- { path: string; hotspotX: number; hotspotY: number; modelDepthPath?: string }+ { path: string; hotspotX: number; hotspotY: number; sculpt?: string }> = {};for (const [type, sprite] of Object.entries(resolveCursorSprites(themeId, alwaysArrow, model3d),)) {const absolute = resolveSceneAssetPath(sprite.assetPath);if (absolute) {- const depthPath = sprite.modelDepthPath ? resolveSceneAssetPath(sprite.modelDepthPath) : null;resolved[type] = {path: absolute,hotspotX: sprite.hotspotX,hotspotY: sprite.hotspotY,- ...(depthPath ? { modelDepthPath: depthPath } : {}),+ ...(sprite.sculpt ? { sculpt: sprite.sculpt } : {}),};}}@@ -140,7 +139,7 @@ export function resolveSceneAssetPaths(sceneJson: string): string {model3d?: boolean;cursorSprites?: Record<string,- { path: string; hotspotX: number; hotspotY: number; modelDepthPath?: string }+ { path: string; hotspotX: number; hotspotY: number; sculpt?: string }>;};webcamEffect?: {diff --git a/public/cursors/pixel-candy/model-arrow-depth.png b/public/cursors/pixel-candy/model-arrow-depth.pngdeleted file mode 100644index ab56d559d..000000000Binary files a/public/cursors/pixel-candy/model-arrow-depth.png and /dev/null differdiff --git a/public/cursors/pixel-candy/model-arrow.png b/public/cursors/pixel-candy/model-arrow.pngdeleted file mode 100644index 4ce1b459e..000000000Binary files a/public/cursors/pixel-candy/model-arrow.png and /dev/null differdiff --git a/public/cursors/pixel-candy/model-pointer-depth.png b/public/cursors/pixel-candy/model-pointer-depth.pngdeleted file mode 100644index c0cfb3142..000000000Binary files a/public/cursors/pixel-candy/model-pointer-depth.png and /dev/null differdiff --git a/public/cursors/pixel-candy/model-pointer.png b/public/cursors/pixel-candy/model-pointer.pngdeleted file mode 100644index 0ad6acf45..000000000Binary files a/public/cursors/pixel-candy/model-pointer.png and /dev/null differdiff --git a/public/cursors/pop-coral/arrow-3d.png b/public/cursors/pop-coral/arrow-3d.pngdeleted file mode 100644index 517581d25..000000000Binary files a/public/cursors/pop-coral/arrow-3d.png and /dev/null differdiff --git a/public/cursors/pop-coral/model-arrow-depth.png b/public/cursors/pop-coral/model-arrow-depth.pngdeleted file mode 100644index e9a71d215..000000000Binary files a/public/cursors/pop-coral/model-arrow-depth.png and /dev/null differdiff --git a/public/cursors/pop-coral/model-arrow.png b/public/cursors/pop-coral/model-arrow.pngdeleted file mode 100644index 203ee4308..000000000Binary files a/public/cursors/pop-coral/model-arrow.png and /dev/null differdiff --git a/public/cursors/pop-coral/model-pointer-depth.png b/public/cursors/pop-coral/model-pointer-depth.pngdeleted file mode 100644index dd432eff9..000000000Binary files a/public/cursors/pop-coral/model-pointer-depth.png and /dev/null differdiff --git a/public/cursors/pop-coral/model-pointer.png b/public/cursors/pop-coral/model-pointer.pngdeleted file mode 100644index 8a5fc1996..000000000Binary files a/public/cursors/pop-coral/model-pointer.png and /dev/null differdiff --git a/public/cursors/pop-coral/pointer-3d.png b/public/cursors/pop-coral/pointer-3d.pngdeleted file mode 100644index cd1eca32d..000000000Binary files a/public/cursors/pop-coral/pointer-3d.png and /dev/null differdiff --git a/public/cursors/prism-glow/model-arrow-depth.png b/public/cursors/prism-glow/model-arrow-depth.pngdeleted file mode 100644index 46be0f675..000000000Binary files a/public/cursors/prism-glow/model-arrow-depth.png and /dev/null differdiff --git a/public/cursors/prism-glow/model-arrow.png b/public/cursors/prism-glow/model-arrow.pngdeleted file mode 100644index f0f31a8a4..000000000Binary files a/public/cursors/prism-glow/model-arrow.png and /dev/null differdiff --git a/public/cursors/prism-glow/model-pointer-depth.png b/public/cursors/prism-glow/model-pointer-depth.pngdeleted file mode 100644index d99ea491d..000000000Binary files a/public/cursors/prism-glow/model-pointer-depth.png and /dev/null differdiff --git a/public/cursors/prism-glow/model-pointer.png b/public/cursors/prism-glow/model-pointer.pngdeleted file mode 100644index 53df9aa1b..000000000Binary files a/public/cursors/prism-glow/model-pointer.png and /dev/null differdiff --git a/public/cursors/star-sprout/model-arrow-depth.png b/public/cursors/star-sprout/model-arrow-depth.pngdeleted file mode 100644index 394eff6aa..000000000Binary files a/public/cursors/star-sprout/model-arrow-depth.png and /dev/null differdiff --git a/public/cursors/star-sprout/model-arrow.png b/public/cursors/star-sprout/model-arrow.pngdeleted file mode 100644index 4eadc2249..000000000Binary files a/public/cursors/star-sprout/model-arrow.png and /dev/null differdiff --git a/public/cursors/star-sprout/model-pointer-depth.png b/public/cursors/star-sprout/model-pointer-depth.pngdeleted file mode 100644index 66cc3f7f4..000000000Binary files a/public/cursors/star-sprout/model-pointer-depth.png and /dev/null differdiff --git a/public/cursors/star-sprout/model-pointer.png b/public/cursors/star-sprout/model-pointer.pngdeleted file mode 100644index c5acf9a83..000000000Binary files a/public/cursors/star-sprout/model-pointer.png and /dev/null differdiff --git a/public/cursors/studio-ink/model-arrow-depth.png b/public/cursors/studio-ink/model-arrow-depth.pngdeleted file mode 100644index 21fb37806..000000000Binary files a/public/cursors/studio-ink/model-arrow-depth.png and /dev/null differdiff --git a/public/cursors/studio-ink/model-arrow.png b/public/cursors/studio-ink/model-arrow.pngdeleted file mode 100644index 4e30e03fd..000000000Binary files a/public/cursors/studio-ink/model-arrow.png and /dev/null differdiff --git a/public/cursors/studio-ink/model-pointer-depth.png b/public/cursors/studio-ink/model-pointer-depth.pngdeleted file mode 100644index bc808d07c..000000000Binary files a/public/cursors/studio-ink/model-pointer-depth.png and /dev/null differdiff --git a/public/cursors/studio-ink/model-pointer.png b/public/cursors/studio-ink/model-pointer.pngdeleted file mode 100644index 6ae633f31..000000000Binary files a/public/cursors/studio-ink/model-pointer.png and /dev/null differdiff --git a/scripts/generate-original-cursor-themes.mjs b/scripts/generate-original-cursor-themes.mjsindex 4d6118d4e..678cae5ff 100644--- a/scripts/generate-original-cursor-themes.mjs+++ b/scripts/generate-original-cursor-themes.mjs@@ -18,204 +18,66 @@ const themes = [{id: "studio-ink",hotspots: { arrow: [158, 48], pointer: [1258, 50] },- modelHotspots: { arrow: [158, 44], pointer: [1256, 86] },},{id: "prism-glow",hotspots: { arrow: [208, 42], pointer: [1220, 50] },- modelHotspots: { arrow: [204, 40], pointer: [1219, 55] },},{id: "pop-coral",hotspots: { arrow: [265, 58], pointer: [1245, 65] },- modelHotspots: { arrow: [254, 61], pointer: [1263, 92] },},{id: "pixel-candy",hotspots: { arrow: [273, 76], pointer: [1218, 78] },- modelHotspots: { arrow: [294, 113], pointer: [1238, 112] },},{id: "star-sprout",hotspots: { arrow: [210, 65], pointer: [1218, 65] },- modelHotspots: { arrow: [234, 119], pointer: [1227, 103] },},];const browser = await chromium.launch();try {const page = await browser.newPage();- const modelFaces = [];await page.goto("about:blank");for (const theme of themes) {const output = path.join(PUBLIC_DIR, theme.id);await mkdir(output, { recursive: true });- for (const variant of theme.id === "pop-coral" ? ["", "-3d"] : [""]) {- const source = await readFile(path.join(SOURCE_DIR, theme.id, `source${variant}.png`));- for (const type of ["arrow", "pointer"]) {- const result = await page.evaluate(- async ({ png, type, size, innerSize, hotspot }) => {- const image = new Image();- image.src = `data:image/png;base64,${png}`;- await image.decode();- const halfWidth = image.width / 2;- const sourceX = type === "arrow" ? 0 : halfWidth;- const sourceCanvas = document.createElement("canvas");- sourceCanvas.width = halfWidth;- sourceCanvas.height = image.height;- const sourceContext = sourceCanvas.getContext("2d", { willReadFrequently: true });- sourceContext.drawImage(image, -sourceX, 0);- const pixels = sourceContext.getImageData(0, 0, halfWidth, image.height);- let minX = halfWidth;- let minY = image.height;- let maxX = 0;- let maxY = 0;- for (let y = 0; y < image.height; y++) {- for (let x = 0; x < halfWidth; x++) {- const alphaIndex = (y * halfWidth + x) * 4 + 3;- if (pixels.data[alphaIndex] < 28) {- pixels.data[alphaIndex] = 0;- continue;- }- minX = Math.min(minX, x);- minY = Math.min(minY, y);- maxX = Math.max(maxX, x);- maxY = Math.max(maxY, y);- }- }- if (minX > maxX || minY > maxY) throw new Error("Empty cursor artwork");- sourceContext.putImageData(pixels, 0, 0);- const width = maxX - minX + 1;- const height = maxY - minY + 1;- const scale = innerSize / Math.max(width, height);- const targetWidth = width * scale;- const targetHeight = height * scale;- const targetX = (size - targetWidth) / 2;- const targetY = (size - targetHeight) / 2;- const canvas = document.createElement("canvas");- canvas.width = canvas.height = size;- const context = canvas.getContext("2d");- context.imageSmoothingQuality = "high";- context.drawImage(- sourceCanvas,- minX,- minY,- width,- height,- targetX,- targetY,- targetWidth,- targetHeight,- );- return {- png: canvas.toDataURL("image/png").split(",")[1],- hotspotX: (targetX + (hotspot[0] - sourceX - minX) * scale) / size,- hotspotY: (targetY + (hotspot[1] - minY) * scale) / size,- };- },- {- png: source.toString("base64"),- type,- size: SIZE,- innerSize: INNER_SIZE,- hotspot: theme.hotspots[type],- },- );- const filename = `${type}${variant}.png`;- await writeFile(path.join(output, filename), Buffer.from(result.png, "base64"));- console.log(- `${theme.id}/${filename}: hotspot ${result.hotspotX.toFixed(4)}, ${result.hotspotY.toFixed(4)}`,- );- }- }-- // The model face is authored separately from its flat 2D face. The relief PNG is- // grayscale height data, aligned pixel-for-pixel with model-arrow/model-pointer.png.- const modelSource = await readFile(path.join(SOURCE_DIR, theme.id, "model-source.png"));+ const source = await readFile(path.join(SOURCE_DIR, theme.id, "source.png"));for (const type of ["arrow", "pointer"]) {const result = await page.evaluate(- async ({ png, type, size, innerSize, hotspot, themeId }) => {+ async ({ png, type, size, innerSize, hotspot }) => {const image = new Image();image.src = `data:image/png;base64,${png}`;await image.decode();- const halfWidth = Math.floor(image.width / 2);+ const halfWidth = image.width / 2;const sourceX = type === "arrow" ? 0 : halfWidth;const sourceCanvas = document.createElement("canvas");sourceCanvas.width = halfWidth;sourceCanvas.height = image.height;const sourceContext = sourceCanvas.getContext("2d", { willReadFrequently: true });sourceContext.drawImage(image, -sourceX, 0);- const sourcePixels = sourceContext.getImageData(0, 0, halfWidth, image.height);- const sourceMask = new Uint8Array(halfWidth * image.height);- for (let i = 0; i < sourceMask.length; i++) {- const alphaIndex = i * 4 + 3;- if (- themeId === "studio-ink" &&- type === "pointer" &&- sourcePixels.data[alphaIndex] >= 32- ) {- const colorIndex = i * 4;- const luminance =- 0.2126 * sourcePixels.data[colorIndex] +- 0.7152 * sourcePixels.data[colorIndex + 1] +- 0.0722 * sourcePixels.data[colorIndex + 2];- // The 3D glove is ivory ceramic. Drop the generated dark ink fringe so- // that it cannot become a fake blue/black sidewall in the volume.- if (luminance < 84) sourcePixels.data[alphaIndex] = 0;- }- if (sourcePixels.data[alphaIndex] < 32) sourcePixels.data[alphaIndex] = 0;- sourceMask[i] = sourcePixels.data[alphaIndex] >= 32 ? 1 : 0;- }-- // Drop disconnected specks from the transparent cutout without trimming the- // separate Star Sprout charm, which is deliberately a second modeled piece.- const visited = new Uint8Array(sourceMask.length);- const queue = new Int32Array(sourceMask.length);- const smallComponents = [];- for (let start = 0; start < sourceMask.length; start++) {- if (!sourceMask[start] || visited[start]) continue;- let head = 0;- let tail = 0;- queue[tail++] = start;- visited[start] = 1;- while (head < tail) {- const at = queue[head++];- const x = at % halfWidth;- const y = Math.floor(at / halfWidth);- for (let oy = -1; oy <= 1; oy++) {- for (let ox = -1; ox <= 1; ox++) {- const nx = x + ox;- const ny = y + oy;- if (nx < 0 || nx >= halfWidth || ny < 0 || ny >= image.height) continue;- const next = ny * halfWidth + nx;- if (sourceMask[next] && !visited[next]) {- visited[next] = 1;- queue[tail++] = next;- }- }- }- }- if (tail < 180) smallComponents.push(queue.slice(0, tail));- }- for (const component of smallComponents) {- for (const at of component) sourcePixels.data[at * 4 + 3] = 0;- }- sourceContext.putImageData(sourcePixels, 0, 0);-+ const pixels = sourceContext.getImageData(0, 0, halfWidth, image.height);let minX = halfWidth;let minY = image.height;let maxX = 0;let maxY = 0;for (let y = 0; y < image.height; y++) {for (let x = 0; x < halfWidth; x++) {- if (sourcePixels.data[(y * halfWidth + x) * 4 + 3] < 28) continue;+ const alphaIndex = (y * halfWidth + x) * 4 + 3;+ if (pixels.data[alphaIndex] < 28) {+ pixels.data[alphaIndex] = 0;+ continue;+ }minX = Math.min(minX, x);minY = Math.min(minY, y);maxX = Math.max(maxX, x);maxY = Math.max(maxY, y);}}- if (minX > maxX || minY > maxY) throw new Error(`${themeId}/${type}: empty model art`);+ if (minX > maxX || minY > maxY) throw new Error("Empty cursor artwork");+ sourceContext.putImageData(pixels, 0, 0);const width = maxX - minX + 1;const height = maxY - minY + 1;const scale = innerSize / Math.max(width, height);@@ -225,7 +87,7 @@ try {const targetY = (size - targetHeight) / 2;const canvas = document.createElement("canvas");canvas.width = canvas.height = size;- const context = canvas.getContext("2d", { willReadFrequently: true });+ const context = canvas.getContext("2d");context.imageSmoothingQuality = "high";context.drawImage(sourceCanvas,@@ -238,239 +100,27 @@ try {targetWidth,targetHeight,);- const face = context.getImageData(0, 0, size, size);- const mask = new Uint8Array(size * size);- const distance = new Float32Array(size * size);- const inf = 10000;- let bx0 = size;- let by0 = size;- let bx1 = 0;- let by1 = 0;- for (let y = 0; y < size; y++) {- for (let x = 0; x < size; x++) {- const i = y * size + x;- mask[i] = face.data[i * 4 + 3] >= 96 ? 1 : 0;- distance[i] = mask[i] ? inf : 0;- if (mask[i]) {- bx0 = Math.min(bx0, x);- by0 = Math.min(by0, y);- bx1 = Math.max(bx1, x);- by1 = Math.max(by1, y);- }- }- }- const diagonal = Math.SQRT2;- for (let y = 0; y < size; y++) {- for (let x = 0; x < size; x++) {- const i = y * size + x;- if (!mask[i]) continue;- let d = distance[i];- if (x > 0) d = Math.min(d, distance[i - 1] + 1);- if (y > 0) d = Math.min(d, distance[i - size] + 1);- if (x > 0 && y > 0) d = Math.min(d, distance[i - size - 1] + diagonal);- if (x + 1 < size && y > 0) d = Math.min(d, distance[i - size + 1] + diagonal);- distance[i] = d;- }- }- for (let y = size - 1; y >= 0; y--) {- for (let x = size - 1; x >= 0; x--) {- const i = y * size + x;- if (!mask[i]) continue;- let d = distance[i];- if (x + 1 < size) d = Math.min(d, distance[i + 1] + 1);- if (y + 1 < size) d = Math.min(d, distance[i + size] + 1);- if (x + 1 < size && y + 1 < size) d = Math.min(d, distance[i + size + 1] + diagonal);- if (x > 0 && y + 1 < size) d = Math.min(d, distance[i + size - 1] + diagonal);- distance[i] = d;- }- }-- const smooth = (a, b, x) => {- const t = Math.max(0, Math.min(1, (x - a) / (b - a)));- return t * t * (3 - 2 * t);- };- const clamp01 = (x) => Math.max(0, Math.min(1, x));- const segment = (u, v, a, b, c, d) => {- const vx = c - a;- const vy = d - b;- const t = clamp01(((u - a) * vx + (v - b) * vy) / (vx * vx + vy * vy));- return Math.hypot(u - (a + vx * t), v - (b + vy * t));- };- const ridgeSegments = [- [0.37, 0.0, 0.39, 0.52, 0.075],- [0.57, 0.12, 0.58, 0.55, 0.075],- [0.76, 0.23, 0.77, 0.57, 0.075],- [0.92, 0.36, 0.92, 0.6, 0.075],- [0.12, 0.47, 0.34, 0.68, 0.09],- ];- const ridge = (u, v) =>- Math.max(- ...ridgeSegments.map(([ax, ay, bx, by, radius]) =>- Math.exp(-((segment(u, v, ax, ay, bx, by) / radius) ** 2) * 2.2),- ),- );- const modelCanvas = document.createElement("canvas");- modelCanvas.width = modelCanvas.height = size;- const modelContext = modelCanvas.getContext("2d");- const heightMap = modelContext.createImageData(size, size);- const bw = Math.max(bx1 - bx0, 1);- const bh = Math.max(by1 - by0, 1);- let peak = 0;- for (let y = 0; y < size; y++) {- for (let x = 0; x < size; x++) {- const i = y * size + x;- const out = i * 4;- let top = 0;- if (mask[i]) {- const u = (x - bx0) / bw;- const v = (y - by0) / bh;- const edge = smooth(0.5, 12, distance[i]);- let [r, g, b] = [0, 1, 2].map((channel) => face.data[out + channel] / 255);- const luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b;- switch (themeId) {- case "studio-ink":- top = 0.022 + 0.024 * edge - 0.014 * smooth(0.56, 0.88, luminance);- if (type === "pointer") {- top +=- 0.014 *- Math.max(- 0.46 * Math.exp(-(((u - 0.55) / 0.43) ** 2 + ((v - 0.72) / 0.33) ** 2)),- 0.52 * ridge(u, v),- );- }- break;- case "prism-glow": {- const gx = u * 7;- const gy = v * 7;- const fx = gx - Math.floor(gx);- const fy = gy - Math.floor(gy);- const facet = Math.abs(- (Math.floor(gx) + Math.floor(gy)) % 2 === 0 ? fx - fy : fx + fy - 1,- );- const facetHeight = 1 - smooth(0.02, 0.5, facet);- top = 0.016 + 0.028 * edge + 0.022 * facetHeight + 0.012 * (1 - luminance);- break;- }- case "pop-coral": {- const dome = Math.max(- 0,- 1 - ((u - 0.5) / 0.59) ** 2 - ((v - 0.52) / 0.75) ** 2,- );- top = 0.015 + 0.075 * dome + (type === "pointer" ? 0.013 * ridge(u, v) : 0);- break;- }- case "pixel-candy": {- const stair = Math.floor(Math.min(distance[i], 16) / 3);- const block = (Math.floor(u * 16) + 2 * Math.floor(v * 16)) % 3;- const side =- distance[i] <= 5 && ((u > 0.64 && v > 0.18) || v > 0.78 || u < 0.11);- if (side) {- // Keep the original plum palette as a stepped rear/side face.- // It is directional and recessed instead of a uniform ink outline.- [r, g, b] = [0.36, 0.19, 0.47];- face.data[out] = Math.round(r * 255);- face.data[out + 1] = Math.round(g * 255);- face.data[out + 2] = Math.round(b * 255);- top = 0.012 + Math.max(0, stair - 1) * 0.003;- } else {- top =- 0.012 + stair * 0.0045 + block * 0.002 + 0.012 * smooth(0.7, 1, luminance);- if (type === "pointer") top += Math.floor(ridge(u, v) * 4) * 0.004;- }- break;- }- case "star-sprout": {- const yellow = r > 0.55 && g > 0.3 && b < 0.48;- const leaf = g > r * 1.08 && g > b * 0.72;- const dome = Math.max(- 0,- 1 - ((u - 0.5) / 0.62) ** 2 - ((v - 0.52) / 0.75) ** 2,- );- top =- 0.016 +- 0.045 * dome +- (yellow ? 0.035 : 0) +- (leaf ? 0.018 : 0) +- (type === "pointer" ? 0.018 * ridge(u, v) : 0);- break;- }- }- top = Math.min(top, 0.12);- peak = Math.max(peak, top);- }- const encoded = Math.round((top / 0.12) * 255);- heightMap.data[out] = encoded;- heightMap.data[out + 1] = encoded;- heightMap.data[out + 2] = encoded;- heightMap.data[out + 3] = 255;- }- }- context.putImageData(face, 0, 0);- modelContext.putImageData(heightMap, 0, 0);- const colorPng = canvas.toDataURL("image/png").split(",")[1];- const heightPng = modelCanvas.toDataURL("image/png").split(",")[1];return {- colorPng,- heightPng,- peak,+ png: canvas.toDataURL("image/png").split(",")[1],hotspotX: (targetX + (hotspot[0] - sourceX - minX) * scale) / size,hotspotY: (targetY + (hotspot[1] - minY) * scale) / size,};},{- png: modelSource.toString("base64"),+ png: source.toString("base64"),type,size: SIZE,innerSize: INNER_SIZE,- hotspot: theme.modelHotspots[type],- themeId: theme.id,+ hotspot: theme.hotspots[type],},);- const base = `model-${type}`;- await writeFile(path.join(output, `${base}.png`), Buffer.from(result.colorPng, "base64"));- await writeFile(- path.join(output, `${base}-depth.png`),- Buffer.from(result.heightPng, "base64"),- );- modelFaces.push({ theme: theme.id, type, png: result.colorPng });+ const filename = `${type}.png`;+ await writeFile(path.join(output, filename), Buffer.from(result.png, "base64"));console.log(- `${theme.id}/${base}.png: hotspot ${result.hotspotX.toFixed(4)}, ${result.hotspotY.toFixed(4)}, relief ${result.peak.toFixed(3)}`,+ `${theme.id}/${filename}: hotspot ${result.hotspotX.toFixed(4)}, ${result.hotspotY.toFixed(4)}`,);}}- const sheet = await page.evaluate(async (items) => {- const canvas = document.createElement("canvas");- canvas.width = 1150;- canvas.height = 540;- const context = canvas.getContext("2d");- context.fillStyle = "#eef2f8";- context.fillRect(0, 0, canvas.width, canvas.height);- for (let index = 0; index < items.length; index++) {- const item = items[index];- const column = Math.floor(index / 2);- const row = index % 2;- const x = column * 230 + 8;- const y = row * 270 + 8;- context.fillStyle = "#ffffff";- context.fillRect(x, y, 214, 254);- context.strokeStyle = "#d9e1ec";- context.strokeRect(x + 0.5, y + 0.5, 213, 253);- context.fillStyle = "#283347";- context.font = "600 14px system-ui, sans-serif";- context.textAlign = "center";- context.fillText(item.theme.replaceAll("-", " "), x + 107, y + 22);- context.fillStyle = "#68758a";- context.font = "11px system-ui, sans-serif";- context.fillText(item.type === "arrow" ? "ARROW" : "POINTING HAND", x + 107, y + 42);- const image = new Image();- image.src = `data:image/png;base64,${item.png}`;- await image.decode();- context.imageSmoothingEnabled = item.theme !== "pixel-candy";- context.drawImage(image, x + 28, y + 52, 158, 158);- }- return canvas.toDataURL("image/png").split(",")[1];- }, modelFaces);- await writeFile(path.join(SOURCE_DIR, "model-face-sheet.png"), Buffer.from(sheet, "base64"));} finally {await browser.close();}diff --git a/src/lib/cursor/cursorThemes.test.ts b/src/lib/cursor/cursorThemes.test.tsindex a2886cbca..96268fab0 100644--- a/src/lib/cursor/cursorThemes.test.ts+++ b/src/lib/cursor/cursorThemes.test.ts@@ -61,23 +61,24 @@ describe("normalizeCursorThemeId", () => {}});- it.each(CURSOR_THEMES)("ships aligned 3D arrow and hand assets for $name", (theme) => {+ // The compositor models these two states itself (`crates/compositor/src/sculpt.rs`, which+ // knows the same names): in 3D the scene names the model, and the sprite stays the flat art.+ it.each(CURSOR_THEMES)("names the sculpted 3D arrow and hand of $name", (theme) => {+ const flat = resolveCursorSprites(theme.id);const sprites = resolveCursorSprites(theme.id, false, true);for (const state of ["arrow", "pointer"] as const) {- const asset = theme.assets[state];- if (!asset?.model3d) throw new Error(`${theme.id}/${state} needs a 3D face and relief map`);-- expect(sprites[state].assetPath).toBe(asset.model3d.assetPath);- expect(sprites[state].modelDepthPath).toBe(asset.model3d.depthPath);- expect(sprites[state].hotspotX).toBeCloseTo(asset.model3d.hotspotX / 32);- expect(sprites[state].hotspotY).toBeCloseTo(asset.model3d.hotspotY / 32);+ expect(theme.assets[state]?.sculpted).toBe(true);+ expect(sprites[state]).toEqual({ ...flat[state], sculpt: `${theme.id}/${state}` });+ expect(flat[state].sculpt).toBeUndefined();+ }+ expect(sprites.text).toBe(DEFAULT_CURSOR_SPRITES.text);+ });- for (const path of [asset.model3d.assetPath, asset.model3d.depthPath]) {- const png = readFileSync(join(process.cwd(), "public", path));- expect(png.subarray(0, 8).toString("hex")).toBe("89504e470d0a1a0a");- expect(png.readUInt32BE(16)).toBe(128);- expect(png.readUInt32BE(20)).toBe(128);- }+ it("leaves the default art to the extruded sprite in 3D", () => {+ for (const sprite of Object.values(+ resolveCursorSprites(DEFAULT_CURSOR_THEME_ID, false, true),+ )) {+ expect(sprite.sculpt).toBeUndefined();}});});diff --git a/src/lib/cursor/cursorThemes.ts b/src/lib/cursor/cursorThemes.tsindex 2b13b463b..1bcef09ea 100644--- a/src/lib/cursor/cursorThemes.ts+++ b/src/lib/cursor/cursorThemes.ts@@ -15,14 +15,9 @@ export interface CursorThemeAsset {height: number;hotspotX: number;hotspotY: number;- /** Face and grayscale relief map for the optional modelled cursor. Hotspots use the same- * 32-logical-pixel reference as the flat asset above. */- model3d?: {- assetPath: string;- depthPath: string;- hotspotX: number;- hotspotY: number;- };+ /** The compositor models this state in 3D (`crates/compositor/src/sculpt.rs`) instead of+ * extruding the flat asset, which stays the 2D art. */+ sculpted?: boolean;}export interface CursorTheme {@@ -56,8 +51,9 @@ export interface CursorSprite {/** Hotspot as a fraction of the image width / height. */hotspotX: number;hotspotY: number;- /** Optional per-pixel top-surface height map used by the 3D cursor model. */- modelDepthPath?: string;+ /** The compositor's sculpted model for this state in 3D, `"<theme>/<state>"`+ * (`crates/compositor/src/sculpt.rs`). Without it, 3D extrudes the sprite. */+ sculpt?: string;}/**@@ -103,7 +99,8 @@ export const DEFAULT_CURSOR_SPRITES: Record<NativeCursorType, CursorSprite> = {** To add one: drop arrow.png/pointer.png into public/cursors/<id>/ and add an entry here* with hotspots normalized to the 32-logical reference (divide a 128px-pack hotspot by 4).- * Add a model3d face and depth map when the theme has its own 3D treatment. An id that leaves this list reads back as the default art+ * Mark an asset `sculpted` when the compositor has a 3D model for it (`sculpt.rs`); other states+ * are extruded from their sprite in 3D. An id that leaves this list reads back as the default art* through `normalizeCursorThemeId`, so a project saved with it still opens.*/export const CURSOR_THEMES: readonly CursorTheme[] = [@@ -117,12 +114,7 @@ export const CURSOR_THEMES: readonly CursorTheme[] = [height: 32,hotspotX: 6.2304,hotspotY: 2.0992,- model3d: {- assetPath: "cursors/studio-ink/model-arrow.png",- depthPath: "cursors/studio-ink/model-arrow-depth.png",- hotspotX: 6.3264,- hotspotY: 2.032,- },+ sculpted: true,},pointer: {assetPath: "cursors/studio-ink/pointer.png",@@ -130,12 +122,7 @@ export const CURSOR_THEMES: readonly CursorTheme[] = [height: 32,hotspotX: 12.848,hotspotY: 2.0704,- model3d: {- assetPath: "cursors/studio-ink/model-pointer.png",- depthPath: "cursors/studio-ink/model-pointer-depth.png",- hotspotX: 12.2304,- hotspotY: 1.9232,- },+ sculpted: true,},},},@@ -149,12 +136,7 @@ export const CURSOR_THEMES: readonly CursorTheme[] = [height: 32,hotspotX: 6.3456,hotspotY: 2.0672,- model3d: {- assetPath: "cursors/prism-glow/model-arrow.png",- depthPath: "cursors/prism-glow/model-arrow-depth.png",- hotspotX: 6.5728,- hotspotY: 1.9296,- },+ sculpted: true,},pointer: {assetPath: "cursors/prism-glow/pointer.png",@@ -162,12 +144,7 @@ export const CURSOR_THEMES: readonly CursorTheme[] = [height: 32,hotspotX: 11.968,hotspotY: 2.0352,- model3d: {- assetPath: "cursors/prism-glow/model-pointer.png",- depthPath: "cursors/prism-glow/model-pointer-depth.png",- hotspotX: 11.4816,- hotspotY: 2.0,- },+ sculpted: true,},},},@@ -181,12 +158,7 @@ export const CURSOR_THEMES: readonly CursorTheme[] = [height: 32,hotspotX: 10.4768,hotspotY: 2.1792,- model3d: {- assetPath: "cursors/pop-coral/model-arrow.png",- depthPath: "cursors/pop-coral/model-arrow-depth.png",- hotspotX: 7.2224,- hotspotY: 1.9648,- },+ sculpted: true,},pointer: {assetPath: "cursors/pop-coral/pointer.png",@@ -194,12 +166,7 @@ export const CURSOR_THEMES: readonly CursorTheme[] = [height: 32,hotspotX: 12.3456,hotspotY: 2,- model3d: {- assetPath: "cursors/pop-coral/model-pointer.png",- depthPath: "cursors/pop-coral/model-pointer-depth.png",- hotspotX: 12.1152,- hotspotY: 1.9616,- },+ sculpted: true,},},},@@ -213,12 +180,7 @@ export const CURSOR_THEMES: readonly CursorTheme[] = [height: 32,hotspotX: 7.3664,hotspotY: 2,- model3d: {- assetPath: "cursors/pixel-candy/model-arrow.png",- depthPath: "cursors/pixel-candy/model-arrow-depth.png",- hotspotX: 7.8176,- hotspotY: 1.9616,- },+ sculpted: true,},pointer: {assetPath: "cursors/pixel-candy/pointer.png",@@ -226,12 +188,7 @@ export const CURSOR_THEMES: readonly CursorTheme[] = [height: 32,hotspotX: 13.376,hotspotY: 1.9264,- model3d: {- assetPath: "cursors/pixel-candy/model-pointer.png",- depthPath: "cursors/pixel-candy/model-pointer-depth.png",- hotspotX: 13.6256,- hotspotY: 1.92,- },+ sculpted: true,},},},@@ -245,12 +202,7 @@ export const CURSOR_THEMES: readonly CursorTheme[] = [height: 32,hotspotX: 4.7232,hotspotY: 2.1152,- model3d: {- assetPath: "cursors/star-sprout/model-arrow.png",- depthPath: "cursors/star-sprout/model-arrow-depth.png",- hotspotX: 3.7824,- hotspotY: 1.9136,- },+ sculpted: true,},pointer: {assetPath: "cursors/star-sprout/pointer.png",@@ -258,12 +210,7 @@ export const CURSOR_THEMES: readonly CursorTheme[] = [height: 32,hotspotX: 13.1712,hotspotY: 2.0384,- model3d: {- assetPath: "cursors/star-sprout/model-pointer.png",- depthPath: "cursors/star-sprout/model-pointer-depth.png",- hotspotX: 12.8352,- hotspotY: 2.0,- },+ sculpted: true,},},},@@ -330,12 +277,12 @@ export function resolveCursorSprites(continue;}sprites[type as NativeCursorType] = {- assetPath: model3d && asset.model3d ? asset.model3d.assetPath : asset.assetPath,+ assetPath: asset.assetPath,// Theme hotspots are authored against the asset's own 32-logical reference;// the contract is a fraction of the image. See CursorSprite.- hotspotX: (model3d && asset.model3d ? asset.model3d.hotspotX : asset.hotspotX) / asset.width,- hotspotY: (model3d && asset.model3d ? asset.model3d.hotspotY : asset.hotspotY) / asset.height,- ...(model3d && asset.model3d ? { modelDepthPath: asset.model3d.depthPath } : {}),+ hotspotX: asset.hotspotX / asset.width,+ hotspotY: asset.hotspotY / asset.height,+ ...(model3d && asset.sculpted ? { sculpt: `${themeId}/${type}` } : {}),};}// "Always use arrow": one consistent pointer for the whole recording, the I-beam and the