euv-core 0.57.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
use super::*;

#[cfg(not(target_arch = "wasm32"))]
// SAFETY: `EngineWorkerPool::parallel_for_chunks` assigns disjoint row spans `[y0..y1)` to each worker.
unsafe impl Sync for LiquidRgbaMutView {}

#[cfg(not(target_arch = "wasm32"))]
impl LiquidRgbaMutView {
    /// Returns the base mutable byte pointer while capturing the `Sync` wrapper by reference.
    ///
    /// # Returns
    ///
    /// - `*mut u8` - Base pointer to destination RGBA8 bytes.
    #[must_use]
    pub(crate) fn ptr(&self) -> *mut u8 {
        let Self { ptr } = *self;
        ptr
    }
}

/// Default 3D metaball + Marching Cubes surface reconstruction configuration.
impl Default for LiquidMesherConfig {
    /// Returns a balanced default `LiquidMesherConfig` with vertex welding and scalar-gradient normals enabled.
    ///
    /// # Returns
    ///
    /// - `Self` - Default mesher configuration.
    fn default() -> Self {
        Self {
            voxel_size: LIQUID_MESHER_DEFAULT_VOXEL_SIZE,
            influence_radius: LIQUID_MESHER_DEFAULT_INFLUENCE_RADIUS,
            iso_level: LIQUID_MESHER_DEFAULT_ISO_LEVEL,
            anisotropic: true,
            anisotropy_strength: 0.35,
            padding_cells: 2,
            max_grid_dim: 64,
            weld_vertices: true,
            smooth_normals_from_gradient: true,
        }
    }
}

/// Sanitization helpers for `LiquidMesherConfig`.
impl LiquidMesherConfig {
    /// Returns a validated, finite copy of this mesher configuration.
    ///
    /// # Returns
    ///
    /// - `Self` - Sanitized mesher configuration.
    #[must_use]
    pub fn sanitized(self) -> Self {
        Self {
            voxel_size: mesher_sanitize_f32(
                self.get_voxel_size(),
                LIQUID_MESHER_DEFAULT_VOXEL_SIZE,
            )
            .clamp(0.005, 4.0),
            influence_radius: mesher_sanitize_f32(
                self.get_influence_radius(),
                LIQUID_MESHER_DEFAULT_INFLUENCE_RADIUS,
            )
            .clamp(0.01, 10.0),
            iso_level: mesher_sanitize_f32(self.get_iso_level(), LIQUID_MESHER_DEFAULT_ISO_LEVEL)
                .clamp(0.02, 10.0),
            anisotropic: self.get_anisotropic(),
            anisotropy_strength: mesher_sanitize_f32(self.get_anisotropy_strength(), 0.35)
                .clamp(0.0, 0.85),
            padding_cells: self.get_padding_cells().clamp(1, 6),
            max_grid_dim: self.get_max_grid_dim().clamp(8, LIQUID_MESHER_MAX_GRID_DIM),
            weld_vertices: self.get_weld_vertices(),
            smooth_normals_from_gradient: self.get_smooth_normals_from_gradient(),
        }
    }
}

/// Default 2D screen-space metaball RGBA8 rasterization descriptor.
impl Default for LiquidRaster2DDesc {
    /// Returns a crisp `128 × 128` turquoise water 2D metaball raster descriptor.
    ///
    /// # Returns
    ///
    /// - `Self` - Default 2D raster descriptor.
    fn default() -> Self {
        Self {
            width: 128,
            height: 128,
            world_min: Vec2::new(-1.0, 0.0),
            world_max: Vec2::new(1.0, 2.0),
            influence_radius: 0.14,
            iso_level: 0.35,
            deep_color: Vec3::new(0.04, 0.30, 0.62),
            shallow_color: Vec3::new(0.18, 0.72, 0.86),
            specular_color: Vec3::new(0.92, 0.98, 1.0),
            background_rgba: [12, 18, 28, 255],
        }
    }
}

/// Default `LiquidSurfaceMesher` ready for 3D Marching Cubes and 2D metaball rasterization.
impl Default for LiquidSurfaceMesher {
    /// Creates a `LiquidSurfaceMesher` using `LiquidMesherConfig::default()`.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready liquid surface mesher.
    fn default() -> Self {
        Self::from_config(LiquidMesherConfig::default())
    }
}

/// 3D Marching Cubes mesh extraction and 2D screen-space metaball rasterization API for `LiquidSurfaceMesher`.
impl LiquidSurfaceMesher {
    /// Creates a `LiquidSurfaceMesher` configured with `config`.
    ///
    /// # Arguments
    ///
    /// - `LiquidMesherConfig` - Desired voxel spacing, metaball radius, isotropy, and welding settings.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized liquid surface mesher.
    #[must_use]
    pub fn from_config(config: LiquidMesherConfig) -> Self {
        Self {
            config: config.sanitized(),
            scratch: LiquidMesherScratch::default(),
        }
    }

    /// Reconstructs a smooth watertight 3D `Mesh3D` directly from active particles in `solver`.
    ///
    /// # Arguments
    ///
    /// - `&SphLiquidSolver3D` - Source particle liquid solver.
    /// - `&str` - Asset name assigned to the extracted `Mesh3D`.
    /// - `PbrMaterial` - Water PBR surface material.
    ///
    /// # Returns
    ///
    /// - `Mesh3D` - Reconstructed 3D liquid surface mesh.
    #[must_use]
    pub fn extract_mesh_from_solver(
        &mut self,
        solver: &SphLiquidSolver3D,
        name: &str,
        material: PbrMaterial,
    ) -> Mesh3D {
        let positions: Vec<Vec3> = solver
            .get_particles()
            .iter()
            .map(|p: &SphParticle| p.get_position())
            .collect();
        self.extract_mesh_from_positions(&positions, name, material)
    }

    /// Reconstructs a smooth watertight 3D `Mesh3D` from arbitrary 3D particle positions via metaballs + Marching Cubes.
    ///
    /// # Arguments
    ///
    /// - `&[Vec3]` - World-space particle center positions.
    /// - `&str` - Asset name assigned to the extracted `Mesh3D`.
    /// - `PbrMaterial` - Water PBR surface material.
    ///
    /// # Returns
    ///
    /// - `Mesh3D` - Extracted watertight 3D triangle mesh with welded vertices and finite smooth normals.
    #[must_use]
    pub fn extract_mesh_from_positions(
        &mut self,
        positions: &[Vec3],
        name: &str,
        material: PbrMaterial,
    ) -> Mesh3D {
        let cfg: LiquidMesherConfig = self.get_config();
        let mut scratch: LiquidMesherScratch = take(self.get_mut_scratch());
        let maybe_grid: Option<ScalarGrid3DDesc> =
            build_metaball_scalar_field_3d(positions, cfg, &mut scratch);
        let mesh: Mesh3D = match maybe_grid {
            Some(grid) => run_marching_cubes_3d(grid, cfg, &mut scratch, name, material),
            None => {
                let mesh_name: String = if name.is_empty() {
                    LIQUID_MESHER_DEFAULT_NAME.to_string()
                } else {
                    name.to_string()
                };
                Mesh3D::from_parts(mesh_name, Vec::new(), Vec::new(), material)
            }
        };
        self.set_scratch(scratch);
        mesh
    }

    /// Rasterizes active particles from a 2D `SphLiquidSolver3D` into a crisp RGBA8 metaball image.
    ///
    /// # Arguments
    ///
    /// - `&SphLiquidSolver3D` - Source 2D liquid solver.
    /// - `&LiquidRaster2DDesc` - Output dimensions, world bounds, and liquid optical palette.
    /// - `&mut [u8]` - Destination RGBA8 pixel buffer (`>= width * height * 4` bytes).
    pub fn rasterize_2d_from_solver(
        &mut self,
        solver: &SphLiquidSolver3D,
        desc: &LiquidRaster2DDesc,
        out_rgba: &mut [u8],
    ) {
        let positions: Vec<Vec2> = solver
            .get_particles()
            .iter()
            .map(|p: &SphParticle| Vec2::new(p.get_position().get_x(), p.get_position().get_y()))
            .collect();
        self.rasterize_2d_positions(&positions, desc, out_rgba);
    }

    /// Rasterizes arbitrary 2D particle positions into a crisp anti-aliased RGBA8 metaball image.
    ///
    /// # Arguments
    ///
    /// - `&[Vec2]` - World-space 2D particle coordinates.
    /// - `&LiquidRaster2DDesc` - Output dimensions, world bounds, and liquid optical palette.
    /// - `&mut [u8]` - Destination RGBA8 pixel buffer (`>= width * height * 4` bytes).
    pub fn rasterize_2d_positions(
        &mut self,
        positions: &[Vec2],
        desc: &LiquidRaster2DDesc,
        out_rgba: &mut [u8],
    ) {
        let mut scratch: LiquidMesherScratch = take(self.get_mut_scratch());
        rasterize_metaballs_2d_impl(positions, desc, &mut scratch, out_rgba);
        self.set_scratch(scratch);
    }
}