1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
use bevy::{
    asset::{Assets, Handle},
    ecs::{
        system::{Command, Commands},
        world::World,
    },
    math::{IVec3, Vec3},
    pbr::StandardMaterial,
    render::mesh::Mesh,
};
use ndshape::Shape;

use crate::{VoxelModelCollection, VoxelModelInstance};

use super::{RawVoxel, Voxel, VoxelModel, VoxelQueryable};

/// Command that programatically modifies the voxels in a model.
///
/// This command will run the closure against every voxel within the region of the model.
///
/// ### Example
/// ```no_run
/// # use bevy::prelude::*;
/// # use bevy_vox_scene::{VoxelModelInstance, ModifyVoxelCommandsExt, VoxelRegionMode, VoxelRegion, Voxel};
/// # let mut commands: Commands = panic!();
/// # let model_instance: VoxelModelInstance = panic!();
/// // cut a sphere-shaped hole out of the loaded model
/// let sphere_center = IVec3::new(10, 10, 10);
/// let radius = 10;
/// let radius_squared = radius * radius;
/// let region = VoxelRegion {
///     origin: sphere_center - IVec3::splat(radius),
///     size: IVec3::splat(1 + (radius * 2)),
/// };
/// commands.modify_voxel_model(
///     model_instance.clone(),
///     VoxelRegionMode::Box(region),
///     move | position, voxel, model | {
///         // a signed-distance function for a sphere:
///         if position.distance_squared(sphere_center) <= radius_squared {
///             // inside of the sphere, return an empty cell
///             Voxel::EMPTY
///         } else {
///             // outside the sphere, return the underlying voxel value from the model
///             voxel.clone()
///         }
///     },
/// );
/// ```
pub trait ModifyVoxelCommandsExt {
    /// Run the `modify` closure against every voxel within the `region` of the `model`.
    ///
    /// ### Arguments
    /// * `model` - the id of the [`VoxelModel`] to be modified (you can obtain this by from the [`bevy::asset::Handle::id()`] method).
    /// * `region` - a [`VoxelRegion`] defining the area of the voxel model that the modifier will operate on.
    /// * `modify` - a closure that will run against every voxel within the `region`.
    ///
    /// ### Arguments passed to the `modify` closure
    /// * `position` - the position of the current voxel, in voxel space
    /// * `voxel` - the index of the current voxel
    /// * `model` - a reference to the model, allowing, for instance, querying neighbouring voxels via the methods in [`crate::VoxelQueryable`]
    ///
    /// ### Notes
    /// The smaller the `region` is, the more performant the operation will be.
    fn modify_voxel_model<
        F: Fn(IVec3, &Voxel, &dyn VoxelQueryable) -> Voxel + Send + Sync + 'static,
    >(
        &mut self,
        model: VoxelModelInstance,
        region: VoxelRegionMode,
        modify: F,
    ) -> &mut Self;
}

impl ModifyVoxelCommandsExt for Commands<'_, '_> {
    fn modify_voxel_model<
        F: Fn(IVec3, &Voxel, &dyn VoxelQueryable) -> Voxel + Send + Sync + 'static,
    >(
        &mut self,
        model: VoxelModelInstance,
        region: VoxelRegionMode,
        modify: F,
    ) -> &mut Self {
        self.add(ModifyVoxelModel {
            model,
            region,
            modify: Box::new(modify),
        });
        self
    }
}

struct ModifyVoxelModel {
    model: VoxelModelInstance,
    region: VoxelRegionMode,
    modify: Box<dyn Fn(IVec3, &Voxel, &dyn VoxelQueryable) -> Voxel + Send + Sync + 'static>,
}

impl Command for ModifyVoxelModel {
    fn apply(self, world: &mut World) {
        let cell = world.cell();
        let perform = || -> Option<()> {
            let mut meshes = cell.get_resource_mut::<Assets<Mesh>>()?;
            let mut materials = cell.get_resource_mut::<Assets<StandardMaterial>>()?;
            let mut collections = cell.get_resource_mut::<Assets<VoxelModelCollection>>()?;
            let collection = collections.get_mut(self.model.collection.id())?;
            let index = collection
                .index_for_model_name
                .get(&self.model.model_name)?;
            let model = collection.models.get_mut(*index)?;
            let refraction_indices = &collection.palette.indices_of_refraction;
            self.modify_model(
                model,
                &mut meshes,
                &mut materials,
                collection.opaque_material.clone(),
                collection.transmissive_material.clone(),
                refraction_indices,
            );
            Some(())
        };
        perform();
    }
}

impl ModifyVoxelModel {
    fn modify_model(
        &self,
        model: &mut VoxelModel,
        meshes: &mut Assets<Mesh>,
        materials: &mut Assets<StandardMaterial>,
        opaque_material: Handle<StandardMaterial>,
        transmissive_material: Handle<StandardMaterial>,
        refraction_indices: &[Option<f32>],
    ) {
        let leading_padding = IVec3::splat(model.data.padding() as i32 / 2);
        let model_size = model.size();
        let region = self.region.clamped(model_size);
        let start = leading_padding + region.origin;
        let end = start + region.size;
        let mut updated: Vec<RawVoxel> = model.data.voxels.clone();
        for x in start.x..end.x {
            for y in start.y..end.y {
                for z in start.z..end.z {
                    let index = model.data.shape.linearize([x as u32, y as u32, z as u32]) as usize;
                    let source: Voxel = model.data.voxels[index].clone().into();
                    updated[index] = RawVoxel::from((self.modify)(
                        IVec3::new(x, y, z) - leading_padding,
                        &source,
                        model,
                    ));
                }
            }
        }
        model.data.voxels = updated;
        let (mesh, average_ior) = model.data.remesh(refraction_indices);
        meshes.insert(&model.mesh, mesh);
        let has_translucency_old_value = model.has_translucency;
        model.has_translucency = average_ior.is_some();
        match (has_translucency_old_value, average_ior) {
            (true, Some(..)) | (false, None) => (), // no change in model's translucency
            (true, None) => {
                model.material = opaque_material;
            }
            (false, Some(ior)) => {
                let Some(mut translucent_material) = materials.get(transmissive_material).cloned()
                else {
                    return;
                };
                translucent_material.ior = ior;
                translucent_material.thickness = model.size().min_element() as f32;
                model.material = materials.add(translucent_material);
            }
        }
    }
}

/// The region of the model to modify
pub enum VoxelRegionMode {
    /// The entire area of the model
    All,
    /// A box region within the model, expressed in voxel space
    Box(VoxelRegion),
}

impl VoxelRegionMode {
    fn clamped(&self, model_size: IVec3) -> VoxelRegion {
        match self {
            VoxelRegionMode::All => VoxelRegion {
                origin: IVec3::ZERO,
                size: model_size,
            },
            VoxelRegionMode::Box(region) => {
                let origin = region.origin.clamp(IVec3::ZERO, model_size - IVec3::ONE);
                let max_size = model_size - origin;
                let size = region.size.clamp(IVec3::ONE, max_size);
                VoxelRegion { origin, size }
            }
        }
    }
}

/// A box region within a model
pub struct VoxelRegion {
    /// The lower-back-left corner of the region
    pub origin: IVec3,
    /// The size of the region
    pub size: IVec3,
}

impl VoxelRegion {
    /// Computes the center of the region
    pub fn center(&self) -> Vec3 {
        let origin = Vec3::new(
            self.origin.x as f32,
            self.origin.y as f32,
            self.origin.z as f32,
        );
        let size = Vec3::new(self.size.x as f32, self.size.y as f32, self.size.z as f32);
        origin + (size * 0.5)
    }
}