bevy_symbios_shape 0.7.0

Bevy integration for Symbios Shape.
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
//! Shared utilities for bevy_symbios_shape examples.
//!
//! Include in each example with:
//! ```rust
//! #[path = "support/common.rs"]
//! mod common;
//! ```
#![allow(dead_code)]

use bevy::{color::palettes::css::WHITE, prelude::*};
use bevy_symbios_shape::{ShapeMeshCache, ShapeRegistry, SpawnShapeExt};
use bevy_symbios_texture::async_gen::TextureReady;
use rand::{SeedableRng, rngs::StdRng};
use symbios_genetics::Genotype;
use symbios_shape::{
    Axis, Interpreter, Quat as DQuat, Scope, ShapeOp, SplitSize, Vec3 as DVec3,
    expr::Expr,
    genetics::ShapeGenotype,
    ops::{CompTarget, FaceSelector, OffsetSelector, SplitEntry},
};

// ── Components ────────────────────────────────────────────────────────────────

/// Links a pending async texture task to the material it should update.
#[derive(Component)]
pub struct PendingMaterialTexture(pub Handle<StandardMaterial>);

// ── Resources ─────────────────────────────────────────────────────────────────

/// Tracks the live building entity and the grammar genotype between mutations.
#[derive(Resource, Default)]
pub struct BuildingState {
    pub root: Option<Entity>,
    pub generation: u64,
    pub genotype: Option<ShapeGenotype>,
}

/// Parameters for the click-driven mutation loop.
#[derive(Resource)]
pub struct MutationConfig {
    pub grammar_strength: f32,
    pub root_rule: String,
    pub trigger_button: MouseButton,
}

impl Default for MutationConfig {
    fn default() -> Self {
        Self {
            grammar_strength: 0.4,
            root_rule: "Lot".into(),
            trigger_button: MouseButton::Left,
        }
    }
}

/// A factory closure that constructs the initial [`Interpreter`] from scratch.
#[derive(Resource)]
pub struct InterpreterFactory(pub Box<dyn Fn() -> Interpreter + Send + Sync>);

/// A closure that computes the bounding lot scope from the current genotype.
#[derive(Resource)]
pub struct ScopeComputer(pub Box<dyn Fn(&ShapeGenotype) -> DVec3 + Send + Sync>);

// ── Systems ───────────────────────────────────────────────────────────────────

/// Spawns ambient and directional lighting suitable for architectural previews.
pub fn setup_lighting(mut commands: Commands) {
    commands.insert_resource(GlobalAmbientLight {
        color: WHITE.into(),
        brightness: 800.0,
        ..default()
    });

    commands.spawn((
        DirectionalLight {
            illuminance: 12_000.0,
            shadow_maps_enabled: true,
            ..default()
        },
        Transform::from_xyz(20.0, 35.0, -15.0).looking_at(Vec3::ZERO, Vec3::Y),
    ));
}

/// Applies generated albedo / normal / ORM textures to their target material
pub fn apply_textures(
    mut commands: Commands,
    ready_q: Query<(Entity, &TextureReady, &PendingMaterialTexture)>,
    mut materials: ResMut<Assets<StandardMaterial>>,
) {
    for (entity, ready, PendingMaterialTexture(mat_handle)) in &ready_q {
        if let Some(mut mat) = materials.get_mut(mat_handle) {
            mat.base_color_texture = Some(ready.0.albedo.clone());
            mat.normal_map_texture = Some(ready.0.normal.clone());
            mat.metallic_roughness_texture = Some(ready.0.roughness.clone());
            mat.occlusion_texture = Some(ready.0.roughness.clone());
        }
        commands.entity(entity).despawn();
    }
}

/// Derives the initial building from [`InterpreterFactory`] and stores the genotype.
#[allow(clippy::too_many_arguments)] // Bevy systems take their params individually.
pub fn spawn_building(
    mut commands: Commands,
    factory: Res<InterpreterFactory>,
    scope_computer: Res<ScopeComputer>,
    config: Res<MutationConfig>,
    registry: Res<ShapeRegistry>,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
    mut cache: ResMut<ShapeMeshCache>,
    mut state: ResMut<BuildingState>,
) {
    let interp = (factory.0)();
    let mut genotype = ShapeGenotype::from_interpreter(&interp);
    let scope = (scope_computer.0)(&genotype);
    propagate_normalize(&mut genotype, scope, &config.root_rule);
    state.genotype = Some(genotype);

    let footprint = Scope::new(DVec3::ZERO, DQuat::IDENTITY, scope);
    match commands.spawn_shape(
        &interp,
        footprint,
        &config.root_rule,
        &registry,
        &mut meshes,
        &mut materials,
        &mut cache,
    ) {
        Ok(entity) => {
            info!("Spawned building (Entity {:?})", entity);
            state.root = Some(entity);
        }
        Err(e) => error!("Derivation failed: {e}"),
    }
}

/// Despawns the current building, mutates the grammar genotype, and re-derives
#[allow(clippy::too_many_arguments)] // Bevy systems take their params individually.
pub fn mutate_on_click(
    mouse_input: Res<ButtonInput<MouseButton>>,
    mut commands: Commands,
    mut state: ResMut<BuildingState>,
    scope_computer: Res<ScopeComputer>,
    config: Res<MutationConfig>,
    registry: Res<ShapeRegistry>,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
    mut cache: ResMut<ShapeMeshCache>,
) {
    if !mouse_input.just_pressed(config.trigger_button) {
        return;
    }

    if let Some(root) = state.root.take() {
        commands.entity(root).despawn();
    }

    state.generation += 1;
    let generation = state.generation;

    let mut rng = StdRng::seed_from_u64(generation);

    let Some(ref mut genotype) = state.genotype else {
        error!("BuildingState genotype not initialised — skipping mutation");
        return;
    };
    genotype.mutate(&mut rng, config.grammar_strength);
    let scope = (scope_computer.0)(genotype);
    propagate_normalize(genotype, scope, &config.root_rule);
    let interp = genotype.to_interpreter();

    let footprint = Scope::new(DVec3::ZERO, DQuat::IDENTITY, scope);
    match commands.spawn_shape(
        &interp,
        footprint,
        &config.root_rule,
        &registry,
        &mut meshes,
        &mut materials,
        &mut cache,
    ) {
        Ok(entity) => {
            info!(
                "Mutated building to generation {} (Entity {:?})",
                generation, entity
            );
            state.root = Some(entity);
        }
        Err(e) => error!("Derivation failed on mutation: {e}"),
    }
}

// ── Grammar utilities ─────────────────────────────────────────────────────────

/// Sums the literal `Absolute` slot sizes in the first variant of `rule`.
/// Expression-valued sizes (0.3) count as zero — they cannot be summed
/// without an evaluation context. Rhythm-group slots are skipped: groups
/// tile to fit and never overflow a dimension.
pub fn sum_absolute_splits(genotype: &ShapeGenotype, rule: &str) -> f64 {
    genotype
        .rules
        .get(rule)
        .and_then(|def| def.variants.first())
        .and_then(|v| {
            v.ops.iter().find_map(|op| {
                if let ShapeOp::Split { entries, .. } = op {
                    let s: f64 = entries
                        .iter()
                        .filter_map(SplitEntry::as_slot)
                        .filter_map(|sl| match &sl.size {
                            SplitSize::Absolute(e) => e.as_lit(),
                            _ => None,
                        })
                        .sum();
                    (s > 0.0).then_some(s)
                } else {
                    None
                }
            })
        })
        .unwrap_or(0.0)
}

/// Propagates a bounding scope from `root_rule` down through every reachable
/// rule via BFS, normalising any `Split` whose `Absolute` slot sum would
/// exceed the available dimension. Traverses ALL stochastic variants.
pub fn propagate_normalize(genotype: &mut ShapeGenotype, lot: DVec3, root_rule: &str) {
    use std::collections::{HashMap, VecDeque};

    let mut queue: VecDeque<(String, f64, f64, f64)> = VecDeque::new();
    let mut min_scope: HashMap<String, (f64, f64, f64)> = HashMap::new();

    queue.push_back((root_rule.to_string(), lot.x, 0.0, lot.z));

    while let Some((rule_name, avail_x, avail_y, avail_z)) = queue.pop_front() {
        let new_or_tighter = match min_scope.get(&rule_name) {
            None => true,
            Some(&(mx, my, mz)) => avail_x < mx || avail_y < my || avail_z < mz,
        };
        if !new_or_tighter {
            continue;
        }
        let entry = min_scope
            .entry(rule_name.clone())
            .or_insert((avail_x, avail_y, avail_z));
        entry.0 = entry.0.min(avail_x);
        entry.1 = entry.1.min(avail_y);
        entry.2 = entry.2.min(avail_z);

        // Fetch variant count so we can iterate over all stochastic branches
        let variants_count = genotype
            .rules
            .get(&rule_name)
            .map(|def| def.variants.len())
            .unwrap_or(0);

        for v_idx in 0..variants_count {
            let ops = genotype.rules.get(&rule_name).unwrap().variants[v_idx]
                .ops
                .clone();

            let mut sx = avail_x;
            let mut sy = avail_y;
            let mut sz = avail_z;

            for (i, op) in ops.iter().enumerate() {
                match op {
                    // Literal-aware only: expression arguments (0.3) leave
                    // the tracked dimension unchanged — runtime guards own
                    // adaptive sizing now.
                    ShapeOp::Extrude(h) => {
                        if let Some(v) = h.as_lit() {
                            sy = v;
                        }
                    }

                    ShapeOp::Scale(v) => {
                        sx *= v[0].as_lit().unwrap_or(1.0);
                        sy *= v[1].as_lit().unwrap_or(1.0);
                        sz *= v[2].as_lit().unwrap_or(1.0);
                    }

                    ShapeOp::Split { axis, .. } => {
                        let dim = match axis {
                            Axis::X => sx,
                            Axis::Y => sy,
                            Axis::Z => sz,
                        };

                        // Literal single slots only: rhythm groups tile to
                        // fit (never overflow), expression sizes re-validate
                        // at derivation.
                        let mut entries = if let ShapeOp::Split { entries, .. } = &ops[i] {
                            entries.clone()
                        } else {
                            continue;
                        };

                        let lit_abs_sum = |entries: &[SplitEntry]| -> f64 {
                            entries
                                .iter()
                                .filter_map(SplitEntry::as_slot)
                                .filter_map(|s| match &s.size {
                                    SplitSize::Absolute(e) => e.as_lit(),
                                    _ => None,
                                })
                                .sum()
                        };
                        let mut abs_sum = lit_abs_sum(&entries);

                        if abs_sum > dim {
                            let scale = dim / abs_sum * 0.95;
                            for entry in entries.iter_mut() {
                                if let SplitEntry::Slot(slot) = entry
                                    && let SplitSize::Absolute(e) = &mut slot.size
                                    && let Some(v) = e.as_lit()
                                {
                                    *e = Expr::lit((v * scale).max(0.01));
                                }
                            }
                            // Write changes back to genotype
                            if let Some(def) = genotype.rules.get_mut(&rule_name)
                                && let ShapeOp::Split {
                                    entries: ref mut v_entries,
                                    ..
                                } = def.variants[v_idx].ops[i]
                            {
                                *v_entries = entries.clone();
                            }
                            abs_sum = lit_abs_sum(&entries);
                        }

                        let float_weight: f64 = entries
                            .iter()
                            .filter_map(SplitEntry::as_slot)
                            .filter_map(|s| match &s.size {
                                SplitSize::Floating(e) => e.as_lit(),
                                _ => None,
                            })
                            .sum();
                        let float_space = (dim - abs_sum).max(0.0);

                        for slot in entries.iter().filter_map(SplitEntry::as_slot) {
                            let child_dim = match &slot.size {
                                SplitSize::Absolute(e) => e.as_lit().unwrap_or(0.0),
                                SplitSize::Floating(e) => {
                                    let v = e.as_lit().unwrap_or(0.0);
                                    if float_weight > 0.0 {
                                        v / float_weight * float_space
                                    } else {
                                        0.0
                                    }
                                }
                                SplitSize::Relative(e) => e.as_lit().unwrap_or(0.0) * dim,
                            };
                            if child_dim <= 0.0 {
                                continue;
                            }
                            let (cx, cy, cz) = match axis {
                                Axis::X => (child_dim, sy, sz),
                                Axis::Y => (sx, child_dim, sz),
                                Axis::Z => (sx, sy, child_dim),
                            };
                            queue.push_back((slot.rule.name.clone(), cx, cy, cz));
                        }
                    }

                    ShapeOp::Comp(CompTarget::Faces(cases)) => {
                        for case in cases {
                            let (fx, fy) = match case.selector {
                                FaceSelector::Front | FaceSelector::Back => (sx, sy),
                                FaceSelector::Left | FaceSelector::Right => (sz, sy),
                                FaceSelector::Top | FaceSelector::Bottom => (sx, sz),
                                FaceSelector::Side | FaceSelector::All => (sx.min(sz), sy),
                            };
                            queue.push_back((case.rule.name.clone(), fx, fy, 0.0));
                        }
                    }

                    ShapeOp::Repeat {
                        axis,
                        tile_sizes,
                        rule,
                    } => {
                        for tile_size in tile_sizes {
                            let tile = tile_size.as_lit().unwrap_or(0.0);
                            if tile <= 0.0 {
                                continue;
                            }
                            let (rx, ry, rz) = match axis {
                                Axis::X => (tile, sy, sz),
                                Axis::Y => (sx, tile, sz),
                                Axis::Z => (sx, sy, tile),
                            };
                            queue.push_back((rule.name.clone(), rx, ry, rz));
                        }
                    }

                    ShapeOp::Rule(call) => {
                        queue.push_back((call.name.clone(), sx, sy, sz));
                    }

                    ShapeOp::Roof { cases, .. } => {
                        for case in cases {
                            queue.push_back((case.rule.name.clone(), sx, sy, sz));
                        }
                    }

                    ShapeOp::Offset { distance, cases } => {
                        let inset = -distance.as_lit().unwrap_or(0.0);
                        let mut inner_x = sx;
                        let mut inner_y = sy;
                        if inset > 0.0 {
                            inner_x = (sx - 2.0 * inset).max(0.1);
                            inner_y = (sy - 2.0 * inset).max(0.1);
                        }

                        for case in cases {
                            if case.selector == OffsetSelector::Inside {
                                queue.push_back((case.rule.name.clone(), inner_x, inner_y, sz));
                            } else {
                                queue.push_back((case.rule.name.clone(), sx, sy, sz));
                            }
                        }
                    }

                    _ => {}
                }
            }
        }
    }
}