aboutsummaryrefslogtreecommitdiff
path: root/apps/fparkan-game/src/live_factory_scene.rs
blob: c10de83a4b1cd54429767ce10441c085086e6c8a (plain) (blame)
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
//! Adds factory project models to the running mission's shared scene.

mod offsets;

use super::{
    chassis_animation::connect_walking_models,
    cockpit_geometry::CockpitGeometry,
    configure_world_material_categories,
    object_render::{ObjectRenderBuilder, ObjectRenderParts},
    projectile_render::{prepare_projectile_draw_into, ProjectileDraw, ProjectileLoader},
    shield_effects::ShieldEffects,
    shot_sound, EffectMaterials, MaterialAnimationBinding, Op2SoundCommand, PlayerWeaponLayout,
    StaticVulkanApp, VulkanStaticMaterial, VulkanStaticMesh,
};
use fparkan_assets::MissionAssets;
use fparkan_runtime::{
    autodemo_projectile_types, autonomous_weapon_effects, loaded_mission_assets,
    loaded_mission_object_drafts, prepared_warbot_weapons, AutoDemoProjectileType,
    MissionObjectDraft, PlayerWeapons,
};
pub(crate) use offsets::SceneOffsets;
use std::{
    collections::{HashMap, HashSet},
    path::Path,
};

#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) struct FactorySceneSlots {
    first: usize,
    caster_start: usize,
    player_projectiles: usize,
    autonomous_projectiles: usize,
    weapon_sounds: usize,
}

struct SceneSources<'a> {
    drafts: &'a [MissionObjectDraft],
    assets: &'a MissionAssets,
    asset_row: &'a dyn Fn(usize) -> usize,
    walking: &'a dyn Fn(usize) -> bool,
    projectiles: &'a [AutoDemoProjectileType],
    weapon_effects: &'a [(String, String)],
}

pub(super) struct FactorySceneExtension {
    slots: FactorySceneSlots,
    mesh: VulkanStaticMesh,
    materials: Vec<VulkanStaticMaterial>,
    animations: Vec<MaterialAnimationBinding>,
    parts: ObjectRenderParts,
    world_ranges: Vec<usize>,
    layouts: HashMap<usize, PlayerWeaponLayout>,
    projectile_draws: Vec<Option<ProjectileDraw>>,
    autonomous_draws: Vec<Option<ProjectileDraw>>,
    autonomous_sounds: Vec<Option<Op2SoundCommand>>,
    cockpits: CockpitGeometry,
    shields: ShieldEffects,
}

impl FactorySceneExtension {
    #[cfg(windows)]
    pub(super) fn prepare_saved(
        root: &Path,
        slots: FactorySceneSlots,
        project: &fparkan_runtime::PreparedSavedFactoryProject,
    ) -> Result<Self, String> {
        let scene = project.scene();
        if scene.first != slots.first {
            return Err("prepared slot range differs from scene range".into());
        }
        let objects = scene.first..scene.first + scene.drafts.len();
        let weapons = project.weapons();
        Self::prepare(
            root,
            slots,
            SceneSources {
                drafts: scene.drafts,
                assets: scene.assets,
                asset_row: &|_| 0,
                walking: &|_| scene.walking,
                projectiles: scene.projectiles,
                weapon_effects: scene.weapon_effects,
            },
            &|archive, name| project.load_projectile(archive, name),
            objects.clone().map(|index| (index, weapons.clone())),
            objects.flat_map(|index| project.shield_effects().map(move |effect| (index, effect))),
        )
    }

    fn prepare(
        root: &Path,
        slots: FactorySceneSlots,
        sources: SceneSources<'_>,
        load_projectile: &ProjectileLoader<'_>,
        weapons: impl IntoIterator<Item = (usize, PlayerWeapons)>,
        shields: impl Iterator<Item = (usize, (String, String))>,
    ) -> Result<Self, String> {
        let FactorySceneSlots {
            first,
            caster_start,
            player_projectiles,
            autonomous_projectiles,
            weapon_sounds,
        } = slots;
        let SceneSources {
            drafts,
            assets,
            asset_row,
            walking,
            projectiles,
            weapon_effects,
        } = sources;
        let mut mesh = VulkanStaticMesh {
            vertices: Vec::new(),
            indices: Vec::new(),
            draw_ranges: Vec::new(),
        };
        let mut materials = Vec::new();
        let mut animations = Vec::new();
        let mut builder = ObjectRenderBuilder::new(
            root,
            &mut mesh,
            &mut materials,
            &mut animations,
            caster_start,
        );
        for (index, draft) in (first..).zip(drafts) {
            builder.append(
                root,
                assets,
                index,
                asset_row(index),
                draft,
                None,
                None,
                true,
                None,
                true,
            )?;
        }
        let mut parts = builder.parts;
        connect_walking_models(
            first,
            |index| {
                if !walking(index) {
                    return None;
                }
                assets
                    .visual_for_object(asset_row(index))
                    .and_then(|id| assets.visual_by_id(id))
                    .and_then(|visual| visual.model_id)
            },
            &mut parts.control_animation_instances_by_object,
            &mut parts.dynamic_component_geometry_by_object,
            &mut parts.dynamic_shadow_casters,
        );
        let cockpits = CockpitGeometry::prepare_objects(
            assets,
            first,
            asset_row,
            &parts.dynamic_component_geometry_by_object,
            &parts.component_pose_buffers_by_object,
            &parts.component_mount_poses_by_object,
            &mut mesh,
            &mut materials,
            &mut animations,
            &mut parts.native_handedness_by_range,
            &mut parts.type16_present_ranges,
        )?;
        let mut projectile_materials = EffectMaterials::new(root);
        let (layouts, projectile_draws) = super::projectile_render::prepare_player_draws(
            root,
            load_projectile,
            weapons,
            player_projectiles,
            &mut mesh,
            &mut materials,
            &mut animations,
            &mut projectile_materials,
        );
        let autonomous_draws = projectiles
            .iter()
            .skip(autonomous_projectiles)
            .map(|kind| {
                match prepare_projectile_draw_into(
                    root,
                    load_projectile,
                    &kind.archive,
                    &kind.name,
                    |_| kind.capacity,
                    &mut mesh,
                    &mut materials,
                    &mut animations,
                    &mut projectile_materials,
                ) {
                    Ok(draw) => draw,
                    Err(error) => {
                        eprintln!(
                            "factory_projectile_layout_unavailable projectile={} reason={error}",
                            kind.name
                        );
                        None
                    }
                }
            })
            .collect();
        let autonomous_sounds = weapon_effects
            .iter()
            .skip(weapon_sounds)
            .map(|(archive, name)| shot_sound::load(root, archive, name))
            .collect();
        let shields = ShieldEffects::prepare_sources(
            root,
            shields,
            &mut mesh,
            &mut materials,
            &mut animations,
        )?;
        let fx_ranges = parts
            .ambient_effect_slots
            .iter()
            .flat_map(|slot| {
                std::iter::once(slot.range.range_index).chain(
                    slot.additional_particle_ranges
                        .iter()
                        .map(|range| range.range_index),
                )
            })
            .chain(shields.ranges())
            .collect::<HashSet<_>>();
        let world_ranges = (0..mesh.draw_ranges.len())
            .filter(|range| !fx_ranges.contains(range))
            .collect::<Vec<_>>();
        configure_world_material_categories(&mut mesh, &materials, &world_ranges)?;
        Ok(Self {
            slots,
            mesh,
            materials,
            animations,
            parts,
            world_ranges,
            layouts,
            projectile_draws,
            autonomous_draws,
            autonomous_sounds,
            cockpits,
            shields,
        })
    }
}

impl StaticVulkanApp {
    pub(super) fn factory_scene_slots(&self) -> FactorySceneSlots {
        FactorySceneSlots {
            first: self.mission_render_roots.len(),
            caster_start: self.shadow_casters.len(),
            player_projectiles: self.projectile_draws.len(),
            autonomous_projectiles: self.autodemo_draws.len(),
            weapon_sounds: self.autonomous_shot_sounds.len(),
        }
    }

    pub(super) fn append_factory_scene(&mut self, root: &Path) -> Result<(), String> {
        let engine = self
            .mission_engine
            .as_ref()
            .ok_or("mission is unavailable")?;
        let slots = self.factory_scene_slots();
        let first = slots.first;
        let drafts = loaded_mission_object_drafts(engine).ok_or("missing mission drafts")?;
        if first == drafts.len() {
            return Ok(());
        }
        let scene = FactorySceneExtension::prepare(
            root,
            slots,
            SceneSources {
                drafts: &drafts[first..],
                assets: loaded_mission_assets(engine).ok_or("missing mission assets")?,
                asset_row: &|index| index,
                walking: &|index| fparkan_runtime::loaded_walk_chassis(engine, index),
                projectiles: autodemo_projectile_types(engine),
                weapon_effects: autonomous_weapon_effects(engine),
            },
            &|archive, name| fparkan_runtime::load_player_projectile(engine, archive, name),
            prepared_warbot_weapons(engine).filter(|(index, _)| *index >= first),
            fparkan_runtime::shield_effect_sources(engine).filter(|(index, _)| *index >= first),
        )?;
        self.install_factory_scene(scene)
    }

    pub(super) fn install_factory_scene(
        &mut self,
        mut scene: FactorySceneExtension,
    ) -> Result<(), String> {
        if self.factory_scene_slots() != scene.slots {
            return Err("mission scene changed while preparing the project".into());
        }
        let renderer = self.renderer.as_mut().ok_or("renderer is unavailable")?;
        let offsets = SceneOffsets {
            vertices: self.shadow_base_vertex,
            indices: self.shadow_base_index,
            ranges: self.mesh.draw_ranges.len(),
            materials: self.materials.len(),
            animations: self.material_animations.len(),
        };
        scene.offset_geometry(offsets)?;
        let FactorySceneExtension {
            slots,
            mesh,
            materials,
            animations,
            parts,
            world_ranges,
            layouts,
            projectile_draws,
            autonomous_draws,
            autonomous_sounds,
            cockpits,
            shields,
        } = scene;
        let first = slots.first;
        let end = first + parts.component_pose_buffers_by_object.len();
        let scratch_vertices = self.mesh.vertices.split_off(offsets.vertices);
        let scratch_indices = self.mesh.indices.split_off(offsets.indices);
        self.mesh.vertices.extend(mesh.vertices);
        self.mesh.indices.extend(mesh.indices);
        self.mesh.draw_ranges.extend(mesh.draw_ranges);
        if let Err(error) = renderer.append_scene_mesh(
            &self.mesh,
            &materials,
            offsets.indices,
            self.shadow_range.range_index,
        ) {
            self.mesh.vertices.truncate(offsets.vertices);
            self.mesh.vertices.extend(scratch_vertices);
            self.mesh.indices.truncate(offsets.indices);
            self.mesh.indices.extend(scratch_indices);
            self.mesh.draw_ranges.truncate(offsets.ranges);
            return Err(error.to_string());
        }
        self.materials.extend(materials);
        self.material_animations.extend(animations);

        self.shadow_base_vertex = self.mesh.vertices.len();
        self.shadow_base_index = self.mesh.indices.len();
        self.world_range_index_counts.extend(
            world_ranges
                .iter()
                .map(|&range| (range, self.mesh.draw_ranges[range].index_count)),
        );
        self.world_range_indices.extend(world_ranges);
        self.native_handedness_by_range
            .extend(parts.native_handedness_by_range);
        self.type16_present_ranges
            .extend(parts.type16_present_ranges);
        self.ambient_effect_slots.extend(parts.ambient_effect_slots);
        self.control_point_light_slots
            .extend(parts.control_point_light_slots);
        self.control_sound_slots.extend(parts.control_sound_slots);
        self.unsupported_control_sounds += parts.unsupported_control_sounds;
        self.component_pose_buffers
            .extend(parts.component_pose_buffers_by_object);
        self.component_mount_poses
            .extend(parts.component_mount_poses_by_object);
        self.dynamic_component_geometry
            .extend(parts.dynamic_component_geometry_by_object);
        self.building_collision_bindings
            .extend(parts.building_collision_bindings);
        self.control_animation_instances
            .extend(parts.control_animation_instances_by_object);
        self.dynamic_shadow_casters
            .extend(parts.dynamic_shadow_casters);
        self.sun_occlusion_range_indices
            .extend(parts.sun_occlusion_range_indices);
        self.shadow_casters.extend(parts.shadow_casters);
        self.mesh_components += parts.mesh_components;
        self.cockpit_geometry.extend(cockpits);
        self.shield_effects
            .get_or_insert_with(ShieldEffects::default)
            .extend(shields);
        self.player_weapon_layouts.extend(layouts);
        self.projectile_draws.extend(projectile_draws);
        self.autodemo_draws.extend(autonomous_draws);
        self.autonomous_shot_sounds.extend(autonomous_sounds);
        self.mission_render_roots.resize_with(end, || None);
        self.removed_mission_roots.extend(first..end);
        // A waiting resize can redraw the latest scene. Sample it again so the
        // new ranges and their material state arrive in the same scene update.
        self.pending_scene_update = None;
        self.last_presented_mission_scene = None;
        Ok(())
    }
}