aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorValentin Popov <valentin@popov.link>2026-12-02 05:09:14 +0300
committerValentin Popov <valentin@popov.link>2026-12-02 05:09:14 +0300
commit0ad190894afd8e9592ef182e36e16ee7a61483f6 (patch)
treee9aacd5995bcad2024bee939d629f186c2667ef9
parent8e11cede8106e36aa1b91400318cff353c157986 (diff)
downloadfparkan-0ad190894afd8e9592ef182e36e16ee7a61483f6.tar.xz
fparkan-0ad190894afd8e9592ef182e36e16ee7a61483f6.zip
feat(ui): render assembled warbots in the designer
-rw-r--r--adapters/fparkan-render-vulkan/src/ffi.rs20
-rw-r--r--adapters/fparkan-render-vulkan/src/ffi/smoke.rs130
-rw-r--r--adapters/fparkan-render-vulkan/src/ffi/smoke_types.rs13
-rw-r--r--adapters/fparkan-render-vulkan/src/ffi/swapchain_resources.rs2
-rw-r--r--apps/fparkan-game/src/designer_model.rs222
-rw-r--r--apps/fparkan-game/src/factory_menu.rs45
-rw-r--r--apps/fparkan-game/src/main.rs12
-rw-r--r--apps/fparkan-game/src/mission_overlay.rs4
-rw-r--r--apps/fparkan-game/src/robot_designer.rs49
-rw-r--r--crates/fparkan-assets/src/designer_screen.rs27
-rw-r--r--crates/fparkan-runtime/src/lib.rs4
-rw-r--r--crates/fparkan-runtime/src/production.rs17
-rw-r--r--docs/tomes/06-behavior.md15
13 files changed, 503 insertions, 57 deletions
diff --git a/adapters/fparkan-render-vulkan/src/ffi.rs b/adapters/fparkan-render-vulkan/src/ffi.rs
index 72df48e2..292e4eec 100644
--- a/adapters/fparkan-render-vulkan/src/ffi.rs
+++ b/adapters/fparkan-render-vulkan/src/ffi.rs
@@ -22,7 +22,7 @@ mod swapchain;
mod swapchain_resources;
mod validation;
-const FRAME_VIEWS_PER_SLOT: usize = 3;
+const FRAME_VIEWS_PER_SLOT: usize = 4;
pub use self::asset_mesh::{
append_msh_damage_stages, node38_pose, node38_pose_from_hierarchy,
@@ -70,15 +70,15 @@ pub use self::runtime::{
VulkanLogicalDeviceError, VulkanLogicalDeviceProbe, VulkanLogicalDeviceReport,
};
pub use self::smoke_types::{
- VulkanDirectionalLight, VulkanDynamicDrawRange, VulkanFrameUniforms, VulkanPointLight,
- VulkanReadbackArtifact, VulkanSmokeBootstrapProgress, VulkanSmokeBootstrapSnapshot,
- VulkanSmokeFrameOutcome, VulkanSmokeRenderer, VulkanSmokeRendererCreateInfo,
- VulkanSmokeRendererError, VulkanSmokeRendererReport, VulkanSmokeShutdownReport,
- VulkanStaticCamera, VulkanStaticDrawRange, VulkanStaticMaterial, VulkanStaticMesh,
- VulkanStaticTexture, VulkanStaticTextureMip, VulkanStaticVertex, VulkanValidationReport,
- VULKAN_DIRECTIONAL_LIGHT_COUNT, VULKAN_FRAME_SLOT_COUNT, VULKAN_FRAME_UNIFORM_BYTES,
- VULKAN_MATERIAL_SPECULAR_RECORD_BYTES, VULKAN_POINT_LIGHT_HEADER_BYTES,
- VULKAN_POINT_LIGHT_RECORD_BYTES,
+ VulkanDirectionalLight, VulkanDynamicDrawRange, VulkanFrameUniforms, VulkanModelPreview,
+ VulkanPointLight, VulkanReadbackArtifact, VulkanSmokeBootstrapProgress,
+ VulkanSmokeBootstrapSnapshot, VulkanSmokeFrameOutcome, VulkanSmokeRenderer,
+ VulkanSmokeRendererCreateInfo, VulkanSmokeRendererError, VulkanSmokeRendererReport,
+ VulkanSmokeShutdownReport, VulkanStaticCamera, VulkanStaticDrawRange, VulkanStaticMaterial,
+ VulkanStaticMesh, VulkanStaticTexture, VulkanStaticTextureMip, VulkanStaticVertex,
+ VulkanValidationReport, VULKAN_DIRECTIONAL_LIGHT_COUNT, VULKAN_FRAME_SLOT_COUNT,
+ VULKAN_FRAME_UNIFORM_BYTES, VULKAN_MATERIAL_SPECULAR_RECORD_BYTES,
+ VULKAN_POINT_LIGHT_HEADER_BYTES, VULKAN_POINT_LIGHT_RECORD_BYTES,
};
#[cfg(test)]
use self::surface::extension_name;
diff --git a/adapters/fparkan-render-vulkan/src/ffi/smoke.rs b/adapters/fparkan-render-vulkan/src/ffi/smoke.rs
index 121ffd25..9c6b9f11 100644
--- a/adapters/fparkan-render-vulkan/src/ffi/smoke.rs
+++ b/adapters/fparkan-render-vulkan/src/ffi/smoke.rs
@@ -433,6 +433,7 @@ impl VulkanSmokeRenderer {
camera: create_info.camera,
frame_uniforms,
cockpit_camera: None,
+ model_preview: None,
point_lights: Vec::new(),
point_lights_explicit: false,
frame_sync: Vec::new(),
@@ -611,6 +612,40 @@ impl VulkanSmokeRenderer {
Ok(())
}
+ /// Selects the model to draw over the interface with its own camera and
+ /// depth buffer region. Only the main pass draws these ranges.
+ pub fn set_model_preview(
+ &mut self,
+ preview: Option<super::VulkanModelPreview>,
+ ) -> Result<(), VulkanSmokeRendererError> {
+ if let Some(model) = &preview {
+ let [left, top, right, bottom] = model.viewport;
+ if !model.camera.is_finite() || !model.eye.iter().all(|value| value.is_finite()) {
+ return Err(VulkanSmokeRendererError::InvalidStaticCamera {
+ context: "non-finite model preview camera",
+ });
+ }
+ if model.ranges.is_empty() || model.ranges.end > self.draw_ranges.len() {
+ return Err(VulkanSmokeRendererError::InvalidStaticMesh {
+ context: "invalid model preview draw ranges",
+ });
+ }
+ if !(left >= 0.0
+ && top >= 0.0
+ && right <= 1.0
+ && bottom <= 1.0
+ && left < right
+ && top < bottom)
+ {
+ return Err(VulkanSmokeRendererError::InvalidStaticCamera {
+ context: "invalid model preview viewport",
+ });
+ }
+ }
+ self.model_preview = preview;
+ Ok(())
+ }
+
/// Replaces lighting, fog, camera-position and matrix state for
/// subsequent frames without recreating GPU resources.
///
@@ -1662,6 +1697,23 @@ impl VulkanSmokeRenderer {
&uniforms.to_ne_bytes(),
)?;
}
+ if let Some(model) = &self.model_preview {
+ let lighting = super::VulkanFrameUniforms::default();
+ let mut uniforms = self.frame_uniforms;
+ uniforms.clip_from_world = model.camera.clip_from_world;
+ uniforms.camera_position = model.eye;
+ uniforms.fog_start = 0.0;
+ uniforms.fog_end = 0.0;
+ uniforms.directional_lights = lighting.directional_lights;
+ uniforms.lighting_floor = lighting.lighting_floor;
+ write_frame_uniform(
+ device,
+ &resources.frame_uniform_buffer,
+ resources.frame_uniform_stride,
+ main_slot + 3,
+ &uniforms.to_ne_bytes(),
+ )?;
+ }
write_point_light_buffer(
device,
&resources.point_light_buffer,
@@ -1976,7 +2028,12 @@ impl VulkanSmokeRenderer {
[usize::from(!reflected && reflection_plane.is_some())]],
&[],
);
- let mut viewport_depth = None;
+ let mut viewport_state = None;
+ let model_region = self
+ .model_preview
+ .as_ref()
+ .map(|preview| preview_rect(extent, preview.viewport));
+ let mut preview_depth_cleared = false;
// Native reflection queues the translucent water after the reflected world.
let draw_order =
self.draw_order
@@ -1991,7 +2048,11 @@ impl VulkanSmokeRenderer {
.cockpit_camera
.as_ref()
.is_some_and(|(ranges, _)| ranges.contains(&range_index));
- if reflected && cockpit {
+ let model = self
+ .model_preview
+ .as_ref()
+ .is_some_and(|preview| preview.ranges.contains(&range_index));
+ if reflected && (cockpit || model) {
continue;
}
let range = self.draw_ranges.get(range_index).ok_or(
@@ -1999,6 +2060,9 @@ impl VulkanSmokeRenderer {
context: "stable draw order range handle",
},
)?;
+ if model && range.index_count == 0 {
+ continue;
+ }
let texture_index = *self.draw_texture_indices.get(range_index).ok_or(
VulkanSmokeRendererError::InvariantViolation {
context: "stable draw texture range handle",
@@ -2023,7 +2087,13 @@ impl VulkanSmokeRenderer {
vk::PipelineBindPoint::GRAPHICS,
*pipeline,
);
- let view_slot = if cockpit { 2 } else { usize::from(reflected) };
+ let view_slot = if model {
+ 3
+ } else if cockpit {
+ 2
+ } else {
+ usize::from(reflected)
+ };
let frame_offset = u32::try_from(
resources.frame_uniform_stride.saturating_mul(
u64::try_from(
@@ -2169,13 +2239,39 @@ impl VulkanSmokeRenderer {
} else {
0
}) as f32;
- let viewport = super::swapchain_resources::draw_viewport(extent, material_mode);
- let next_viewport_depth = [viewport.min_depth, viewport.max_depth];
- if viewport_depth != Some(next_viewport_depth) {
+ let mut viewport =
+ super::swapchain_resources::draw_viewport(extent, material_mode);
+ let scissor = if model {
+ let rect = model_region.expect("active model preview has a viewport");
+ viewport.x = rect.offset.x as f32;
+ viewport.y = rect.offset.y as f32;
+ viewport.width = rect.extent.width as f32;
+ viewport.height = rect.extent.height as f32;
+ if !preview_depth_cleared {
+ let depth = vk::ClearAttachment::default()
+ .aspect_mask(vk::ImageAspectFlags::DEPTH)
+ .clear_value(clear_values[1]);
+ let region = vk::ClearRect::default().rect(rect).layer_count(1);
+ device.device().cmd_clear_attachments(
+ command_buffer,
+ &[depth],
+ &[region],
+ );
+ preview_depth_cleared = true;
+ }
+ rect
+ } else {
+ render_area
+ };
+ let next_viewport = (model, viewport.min_depth, viewport.max_depth);
+ if viewport_state != Some(next_viewport) {
device
.device()
.cmd_set_viewport(command_buffer, 0, &[viewport]);
- viewport_depth = Some(next_viewport_depth);
+ device
+ .device()
+ .cmd_set_scissor(command_buffer, 0, &[scissor]);
+ viewport_state = Some(next_viewport);
}
let material_mode = [material_mode.to_ne_bytes()];
device.device().cmd_push_constants(
@@ -2731,6 +2827,26 @@ fn world_material_pipeline_states(
/// compacted into world positions and sorted transparent ranges are inserted
/// after the last active background; fixed passes keep their relative order but
/// can shift slots. Zero-index-count ranges are inactive and are omitted.
+fn preview_rect((width, height): (u32, u32), viewport: [f32; 4]) -> vk::Rect2D {
+ let [left, top, right, bottom] = viewport;
+ let x = (left * width as f32).round() as u32;
+ let y = (top * height as f32).round() as u32;
+ let x = x.min(width - 1);
+ let y = y.min(height - 1);
+ let right = ((right * width as f32).round() as u32).clamp(x + 1, width);
+ let bottom = ((bottom * height as f32).round() as u32).clamp(y + 1, height);
+ vk::Rect2D {
+ offset: vk::Offset2D {
+ x: x as i32,
+ y: y as i32,
+ },
+ extent: vk::Extent2D {
+ width: right - x,
+ height: bottom - y,
+ },
+ }
+}
+
fn sorted_world_draw_order(
range_count: usize,
ranges: &[super::VulkanStaticDrawRange],
diff --git a/adapters/fparkan-render-vulkan/src/ffi/smoke_types.rs b/adapters/fparkan-render-vulkan/src/ffi/smoke_types.rs
index 54b409d1..cf795ccf 100644
--- a/adapters/fparkan-render-vulkan/src/ffi/smoke_types.rs
+++ b/adapters/fparkan-render-vulkan/src/ffi/smoke_types.rs
@@ -75,6 +75,18 @@ pub struct VulkanStaticCamera {
pub clip_from_world: [f32; 16],
}
+/// A depth-isolated view of prepared mesh ranges inside the main pass.
+pub struct VulkanModelPreview {
+ /// Contiguous preview draw ranges, appended above the UI background.
+ pub ranges: std::ops::Range<usize>,
+ /// Left, top, right and bottom as fractions of the main drawable.
+ pub viewport: [f32; 4],
+ /// Projection and view of the preview model.
+ pub camera: VulkanStaticCamera,
+ /// Eye position in model space for material lighting.
+ pub eye: [f32; 3],
+}
+
impl VulkanStaticCamera {
/// Builds a static camera from the recovered Ngi32 D3D7 camera contract.
#[must_use]
@@ -1624,6 +1636,7 @@ pub struct VulkanSmokeRenderer {
pub(super) camera: VulkanStaticCamera,
pub(super) frame_uniforms: VulkanFrameUniforms,
pub(super) cockpit_camera: Option<(std::ops::Range<usize>, VulkanStaticCamera)>,
+ pub(super) model_preview: Option<VulkanModelPreview>,
/// Dynamically sized point-light records submitted by the client.
pub(super) point_lights: Vec<VulkanPointLight>,
/// Whether `set_point_lights` has replaced legacy `frame_uniforms.point_light`.
diff --git a/adapters/fparkan-render-vulkan/src/ffi/swapchain_resources.rs b/adapters/fparkan-render-vulkan/src/ffi/swapchain_resources.rs
index ff172039..295cd70b 100644
--- a/adapters/fparkan-render-vulkan/src/ffi/swapchain_resources.rs
+++ b/adapters/fparkan-render-vulkan/src/ffi/swapchain_resources.rs
@@ -1214,7 +1214,7 @@ fn create_graphics_pipeline(
let color_blend_state = vk::PipelineColorBlendStateCreateInfo::default()
.logic_op_enable(false)
.attachments(&color_blend_attachments);
- let dynamic_states = [vk::DynamicState::VIEWPORT];
+ let dynamic_states = [vk::DynamicState::VIEWPORT, vk::DynamicState::SCISSOR];
let dynamic_state =
vk::PipelineDynamicStateCreateInfo::default().dynamic_states(&dynamic_states);
let create_info = vk::GraphicsPipelineCreateInfo::default()
diff --git a/apps/fparkan-game/src/designer_model.rs b/apps/fparkan-game/src/designer_model.rs
new file mode 100644
index 00000000..3639566f
--- /dev/null
+++ b/apps/fparkan-game/src/designer_model.rs
@@ -0,0 +1,222 @@
+use super::{
+ add3, clip_from_world_for_view, cross3, length3, normalize3, scale3, sub3, StaticPreviewScene,
+ VulkanSmokeRenderer, VulkanStaticCamera,
+};
+use fparkan_assets::designer_screen::MODEL_VIEWPORT;
+use fparkan_render_vulkan::VulkanModelPreview;
+use fparkan_runtime::{factory_project_root, Engine};
+use std::ops::Range;
+
+const SPIN_RADIANS_PER_MS: f32 = f32::from_bits(0x3a449ba6);
+const ELEVATION: f32 = 0.5;
+const HALF_FOV: f32 = std::f32::consts::FRAC_PI_6;
+
+pub(super) struct DesignerModels(Vec<Option<DesignerModel>>);
+
+struct DesignerModel {
+ draws: Range<usize>,
+ counts: Vec<u32>,
+ center: [f32; 3],
+ radius: f32,
+}
+
+impl DesignerModels {
+ pub(super) fn prepare(engine: &Engine, scene: &mut StaticPreviewScene) -> Result<Self, String> {
+ let mut models = Vec::new();
+ for root in (0..).map_while(|scheme| factory_project_root(engine, scheme)) {
+ models.push(DesignerModel::prepare(root, scene)?);
+ }
+ Ok(Self(models))
+ }
+
+ pub(super) fn ranges(&self) -> impl Iterator<Item = usize> + '_ {
+ self.0
+ .iter()
+ .flatten()
+ .flat_map(|model| model.draws.clone())
+ }
+
+ pub(super) fn draw(
+ &self,
+ renderer: &mut VulkanSmokeRenderer,
+ active: Option<(usize, u32)>,
+ viewport: [f32; 2],
+ ) -> Result<(), String> {
+ let preview = active.and_then(|(scheme, elapsed_ms)| {
+ self.0
+ .get(scheme)?
+ .as_ref()
+ .map(|model| model.view(elapsed_ms, viewport))
+ });
+ for (scheme, model) in self.0.iter().enumerate() {
+ let Some(model) = model else { continue };
+ let visible = active.is_some_and(|(selected, _)| selected == scheme);
+ for (index, count) in model.draws.clone().zip(&model.counts) {
+ renderer
+ .set_draw_range_index_count(index, if visible { *count } else { 0 })
+ .map_err(|error| error.to_string())?;
+ }
+ }
+ renderer
+ .set_model_preview(preview)
+ .map_err(|error| error.to_string())
+ }
+}
+
+impl DesignerModel {
+ fn prepare(root: usize, scene: &mut StaticPreviewScene) -> Result<Option<Self>, String> {
+ let source = scene.dynamic_component_geometry[root]
+ .iter()
+ .flatten()
+ .flat_map(|component| component.base_draws.clone())
+ .map(|index| scene.mesh.draw_ranges[index])
+ .filter(|range| range.index_count != 0)
+ .collect::<Vec<_>>();
+ let referenced = source.iter().flat_map(|range| {
+ let first = range.first_index as usize;
+ scene.mesh.indices[first..first + range.index_count as usize]
+ .iter()
+ .copied()
+ });
+ let Some(([min, max], [lo, hi])) = referenced.fold(None, |bounds, index| {
+ let position = scene.mesh.vertices[index as usize].position;
+ Some(bounds.map_or(
+ ([index; 2], [position; 2]),
+ |([min, max], [lo, hi]): Bounds| {
+ (
+ [min.min(index), max.max(index)],
+ [
+ std::array::from_fn(|axis| lo[axis].min(position[axis])),
+ std::array::from_fn(|axis| hi[axis].max(position[axis])),
+ ],
+ )
+ },
+ ))
+ }) else {
+ return Ok(None);
+ };
+ let sphere = scene
+ .dynamic_shadow_casters
+ .iter()
+ .find(|caster| caster.object_index == root)
+ .map(|caster| caster.initial_sphere);
+ let (center, radius) = sphere.map_or_else(
+ || {
+ (
+ scale3(add3(lo, hi), 0.5),
+ length3(sub3(hi, lo)).unwrap_or(0.0) * 0.5,
+ )
+ },
+ |sphere| (sphere.center, sphere.radius),
+ );
+ if !radius.is_finite() || radius <= f32::EPSILON {
+ return Ok(None);
+ }
+
+ // Keep the designer at its prepared pose even after the factory
+ // moves its first live unit out of the reserved world slot.
+ let vertex_start = u32::try_from(scene.mesh.vertices.len())
+ .map_err(|_| "designer vertex offset exceeds u32")?;
+ scene
+ .mesh
+ .vertices
+ .extend_from_within(min as usize..=max as usize);
+ let start = scene.mesh.draw_ranges.len();
+ let counts = source.iter().map(|range| range.index_count).collect();
+ for mut range in source {
+ let first = range.first_index as usize;
+ let next = scene.mesh.indices.len();
+ scene
+ .mesh
+ .indices
+ .extend_from_within(first..first + range.index_count as usize);
+ for index in &mut scene.mesh.indices[next..] {
+ *index = (*index - min)
+ .checked_add(vertex_start)
+ .ok_or("designer mesh index exceeds u32")?;
+ }
+ range.first_index =
+ u32::try_from(next).map_err(|_| "designer index offset exceeds u32")?;
+ range.owner_scope = 0;
+ scene.mesh.draw_ranges.push(range);
+ }
+ Ok(Some(Self {
+ draws: start..scene.mesh.draw_ranges.len(),
+ counts,
+ center,
+ radius,
+ }))
+ }
+
+ fn view(&self, elapsed_ms: u32, drawable: [f32; 2]) -> VulkanModelPreview {
+ let yaw = elapsed_ms as f64 * f64::from(SPIN_RADIANS_PER_MS);
+ let (sin_yaw, cos_yaw) = yaw.sin_cos();
+ let (sin_elevation, cos_elevation) = ELEVATION.sin_cos();
+ let outward = [
+ -cos_elevation * cos_yaw as f32,
+ cos_elevation * sin_yaw as f32,
+ sin_elevation,
+ ];
+ let radius = self.radius;
+ let near = 0.5;
+ let distance = (radius / HALF_FOV.sin()).max(radius + near);
+ let horizontal_half = (radius / distance).asin();
+ let eye = add3(self.center, scale3(outward, distance));
+ let forward = scale3(outward, -1.0);
+ let right = normalize3(cross3(forward, [0.0, 0.0, 1.0]))
+ .expect("designer elevation avoids the pole");
+ let up = cross3(right, forward);
+ let [l, t, r, b] = MODEL_VIEWPORT;
+ let viewport = [l / 640.0, t / 480.0, r / 640.0, b / 480.0];
+ let aspect = super::preview_aspect(
+ ((r - l) / 640.0 * drawable[0]) / ((b - t) / 480.0 * drawable[1]),
+ );
+ let vertical_fov = (horizontal_half.tan() / aspect).atan() * 2.0;
+ let far = 300.0_f32.max(distance + radius);
+ let camera = VulkanStaticCamera {
+ clip_from_world: clip_from_world_for_view(
+ eye,
+ forward,
+ right,
+ up,
+ vertical_fov,
+ near,
+ far,
+ aspect,
+ ),
+ };
+ VulkanModelPreview {
+ ranges: self.draws.clone(),
+ viewport,
+ camera,
+ eye,
+ }
+ }
+}
+
+type Bounds = ([u32; 2], [[f32; 3]; 2]);
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn designer_camera_orbits_the_same_project_center() {
+ let model = DesignerModel {
+ draws: 2..3,
+ counts: vec![3],
+ center: [8.0, -2.0, 5.0],
+ radius: 4.0,
+ };
+ let initial = model.view(0, [1280.0, 720.0]);
+ let later = model.view(1000, [1280.0, 720.0]);
+ let relative = sub3(initial.eye, model.center);
+ let rotated = sub3(later.eye, model.center);
+ assert!((relative[1]).abs() < 1.0e-5);
+ assert!((length3(relative).unwrap() - 8.0).abs() < 1.0e-5);
+ assert!((relative[2] - rotated[2]).abs() < 1.0e-5);
+ assert!((rotated[1].atan2(-rotated[0]) - 0.75).abs() < 1.0e-5);
+ assert_eq!(initial.viewport, later.viewport);
+ assert_ne!(initial.camera.clip_from_world, later.camera.clip_from_world);
+ }
+}
diff --git a/apps/fparkan-game/src/factory_menu.rs b/apps/fparkan-game/src/factory_menu.rs
index 743a438a..376b1723 100644
--- a/apps/fparkan-game/src/factory_menu.rs
+++ b/apps/fparkan-game/src/factory_menu.rs
@@ -39,6 +39,7 @@ pub(super) struct DesignerSession {
pub(super) first_part: usize,
pub(super) hover: Option<DesignerAction>,
pub(super) dirty: bool,
+ pub(super) model_started_ms: u32,
}
impl DesignerSession {
@@ -93,12 +94,13 @@ impl FactoryMenu {
first_part: 0,
hover: None,
dirty: true,
+ model_started_ms: 0,
};
designer.point(self.cursor);
self.designer = Some(designer);
}
- fn designer_action(&mut self, action: DesignerAction) {
+ fn designer_action(&mut self, action: DesignerAction, clock_ms: u32) {
let Some(designer) = &mut self.designer else {
return;
};
@@ -107,6 +109,7 @@ impl FactoryMenu {
designer.selected = Some(slot);
designer.first_part = 0;
designer.dirty = true;
+ designer.model_started_ms = clock_ms;
}
DesignerAction::Send => {
if let Some(slot) = designer.selected {
@@ -151,7 +154,11 @@ struct ProjectPicture {
}
impl FactoryProjectPanel {
- pub(super) fn load(root: &Path, preview: &mut StaticPreviewScene) -> Result<Self, String> {
+ pub(super) fn load(
+ root: &Path,
+ preview: &mut StaticPreviewScene,
+ engine: &Engine,
+ ) -> Result<Self, String> {
let images = FactoryProjectImages::load(&DirectoryVfs::new(root))?;
let range = append_picture(
preview,
@@ -164,12 +171,14 @@ impl FactoryProjectPanel {
],
)?;
#[cfg(windows)]
- let designer = RobotDesignerPanel::load(root, preview)
+ let designer = RobotDesignerPanel::load(root, preview, engine)
.map(Some)
.unwrap_or_else(|error| {
eprintln!("robot_designer_unavailable reason={error}");
None
});
+ #[cfg(not(windows))]
+ let _ = engine;
Ok(Self {
images,
range,
@@ -190,11 +199,11 @@ impl FactoryProjectPanel {
}
}
- pub(super) fn ranges(&self) -> impl Iterator<Item = usize> {
+ pub(super) fn ranges(&self) -> impl Iterator<Item = usize> + '_ {
#[cfg(windows)]
- let designer = self.designer.as_ref().map(RobotDesignerPanel::range_index);
+ let designer = self.designer.iter().flat_map(RobotDesignerPanel::ranges);
#[cfg(not(windows))]
- let designer = None;
+ let designer = std::iter::empty();
std::iter::once(self.range.range_index).chain(designer)
}
@@ -203,13 +212,15 @@ impl FactoryProjectPanel {
renderer: &mut VulkanSmokeRenderer,
mut menu: Option<&mut FactoryMenu>,
engine: Option<&Engine>,
+ viewport: [f32; 2],
+ clock_ms: u32,
) -> Result<(), String> {
#[cfg(windows)]
if let Some(designer) = &mut self.designer {
- designer.draw(renderer, menu.as_deref_mut(), engine)?;
+ designer.draw(renderer, menu.as_deref_mut(), engine, viewport, clock_ms)?;
}
#[cfg(not(windows))]
- let _ = (&mut menu, engine);
+ let _ = (&mut menu, engine, viewport, clock_ms);
if let Some(menu) = menu.filter(|menu| menu.designer.is_none()) {
let slots = menu.visible_slots();
let count = slots.len();
@@ -264,9 +275,11 @@ impl StaticVulkanApp {
if state == ElementState::Pressed && !repeat && !self.mission_paused {
if menu.designer.is_some() {
match code {
- KeyCode::Escape => menu.designer_action(DesignerAction::Exit),
+ KeyCode::Escape => {
+ menu.designer_action(DesignerAction::Exit, self.simulation_time_ms)
+ }
KeyCode::Enter | KeyCode::NumpadEnter => {
- menu.designer_action(DesignerAction::Send)
+ menu.designer_action(DesignerAction::Send, self.simulation_time_ms)
}
_ => {}
}
@@ -351,7 +364,7 @@ impl StaticVulkanApp {
{
if let Some(designer) = &menu.designer {
if let Some(action) = designer.hover {
- menu.designer_action(action);
+ menu.designer_action(action, self.simulation_time_ms);
self.update_mission_title();
}
return true;
@@ -451,15 +464,15 @@ mod tests {
.collect(),
);
menu.open_designer();
- menu.designer_action(DesignerAction::Send);
+ menu.designer_action(DesignerAction::Send, 0);
assert!(menu.designer.is_some());
- menu.designer_action(DesignerAction::Project(1));
- menu.designer_action(DesignerAction::Exit);
+ menu.designer_action(DesignerAction::Project(1), 0);
+ menu.designer_action(DesignerAction::Exit, 0);
assert_eq!(menu.selected().scheme, 0);
menu.open_designer();
- menu.designer_action(DesignerAction::Project(1));
- menu.designer_action(DesignerAction::Send);
+ menu.designer_action(DesignerAction::Project(1), 0);
+ menu.designer_action(DesignerAction::Send, 0);
assert!(menu.designer.is_none());
assert_eq!(menu.selected().scheme, 1);
}
diff --git a/apps/fparkan-game/src/main.rs b/apps/fparkan-game/src/main.rs
index 4b5734b0..8e372c9f 100644
--- a/apps/fparkan-game/src/main.rs
+++ b/apps/fparkan-game/src/main.rs
@@ -36,6 +36,8 @@ use fparkan_runtime::query_building_segment_world;
#[cfg(test)]
use player_collision::building_collision_nodes;
use player_collision::{building_collision_binding, BuildingCollisionBinding};
+#[cfg(windows)]
+mod designer_model;
mod player_fire;
mod player_footsteps;
mod player_service;
@@ -4846,6 +4848,8 @@ struct DynamicComponentGeometry {
parent_mount: Option<(usize, usize)>,
vertex_start: usize,
vertex_count: usize,
+ #[cfg(windows)]
+ base_draws: std::ops::Range<usize>,
damage_stages: Vec<fparkan_render_vulkan::DamageStageRanges>,
}
@@ -8604,6 +8608,8 @@ fn static_preview_mesh_and_materials(
parent_mount,
vertex_start,
vertex_count,
+ #[cfg(windows)]
+ base_draws: range_start..range_start + base_range_count,
damage_stages,
});
}
@@ -14501,6 +14507,8 @@ mod tests {
parent_mount: None,
vertex_start: 0,
vertex_count: parent_vertex_count,
+ #[cfg(windows)]
+ base_draws: 0..0,
damage_stages: Vec::new(),
}),
Some(DynamicComponentGeometry {
@@ -14511,6 +14519,8 @@ mod tests {
parent_mount: Some((0, 1)),
vertex_start: parent_vertex_count,
vertex_count: 3,
+ #[cfg(windows)]
+ base_draws: 0..0,
damage_stages: Vec::new(),
}),
]];
@@ -14854,6 +14864,8 @@ mod tests {
parent_mount,
vertex_start: 0,
vertex_count: mesh.vertices.len(),
+ #[cfg(windows)]
+ base_draws: 0..0,
damage_stages: Vec::new(),
}),
]];
diff --git a/apps/fparkan-game/src/mission_overlay.rs b/apps/fparkan-game/src/mission_overlay.rs
index ee3c2425..0c3ad122 100644
--- a/apps/fparkan-game/src/mission_overlay.rs
+++ b/apps/fparkan-game/src/mission_overlay.rs
@@ -88,7 +88,7 @@ impl MissionOverlay {
})
});
let factory_projects = cockpit.and_then(|_| {
- FactoryProjectPanel::load(root, preview)
+ FactoryProjectPanel::load(root, preview, engine)
.map(Some)
.unwrap_or_else(|error| {
eprintln!("factory_project_panel_unavailable reason={error}");
@@ -236,6 +236,8 @@ impl StaticVulkanApp {
renderer,
self.factory_menu.as_mut(),
self.mission_engine.as_ref(),
+ frame.viewport,
+ frame.clock.time_ms,
)?;
}
Ok(())
diff --git a/apps/fparkan-game/src/robot_designer.rs b/apps/fparkan-game/src/robot_designer.rs
index 80005b89..6b48ca77 100644
--- a/apps/fparkan-game/src/robot_designer.rs
+++ b/apps/fparkan-game/src/robot_designer.rs
@@ -1,4 +1,5 @@
use super::{
+ designer_model::DesignerModels,
factory_menu::{append_picture, picture_texture, FactoryMenu},
DirectoryVfs, EnvironmentGpuRange, StaticPreviewScene, VulkanSmokeRenderer,
};
@@ -9,11 +10,17 @@ use std::path::Path;
pub(super) struct RobotDesignerPanel {
assets: DesignerScreen,
+ background: EnvironmentGpuRange,
+ models: DesignerModels,
range: EnvironmentGpuRange,
}
impl RobotDesignerPanel {
- pub(super) fn load(root: &Path, preview: &mut StaticPreviewScene) -> Result<Self, String> {
+ pub(super) fn load(
+ root: &Path,
+ preview: &mut StaticPreviewScene,
+ engine: &Engine,
+ ) -> Result<Self, String> {
let strings = StringResources::open(&root.join("iron3d.dll"))?;
let read = |id| {
strings
@@ -29,12 +36,24 @@ impl RobotDesignerPanel {
exit: read(0x615)?,
},
)?;
- let range = append_picture(preview, EXTENT, [0.0, 0.0, 640.0, 480.0])?;
- Ok(Self { assets, range })
+ let screen = [0.0, 0.0, 640.0, 480.0];
+ let background = append_picture(preview, EXTENT, screen)?;
+ preview.materials[background.material_index].texture =
+ picture_texture(EXTENT, assets.paint_background().rgba8);
+ let models = DesignerModels::prepare(engine, preview)?;
+ let range = append_picture(preview, EXTENT, screen)?;
+ Ok(Self {
+ assets,
+ background,
+ models,
+ range,
+ })
}
- pub(super) fn range_index(&self) -> usize {
- self.range.range_index
+ pub(super) fn ranges(&self) -> impl Iterator<Item = usize> + '_ {
+ [self.background.range_index, self.range.range_index]
+ .into_iter()
+ .chain(self.models.ranges())
}
pub(super) fn draw(
@@ -42,8 +61,19 @@ impl RobotDesignerPanel {
renderer: &mut VulkanSmokeRenderer,
menu: Option<&mut FactoryMenu>,
engine: Option<&Engine>,
+ viewport: [f32; 2],
+ clock_ms: u32,
) -> Result<(), String> {
let visible = menu.as_ref().is_some_and(|menu| menu.designer.is_some());
+ let active = menu.as_ref().and_then(|menu| {
+ let designer = menu.designer.as_ref()?;
+ let root = designer.slots.start + designer.selected?;
+ Some((
+ menu.choices[root].scheme,
+ clock_ms.saturating_sub(designer.model_started_ms),
+ ))
+ });
+ self.models.draw(renderer, active, viewport)?;
if let Some(menu) = menu {
if let Some(designer) = menu.designer.as_mut().filter(|view| view.dirty) {
let project = designer.selected.and_then(|slot| {
@@ -67,8 +97,11 @@ impl RobotDesignerPanel {
designer.dirty = false;
}
}
- renderer
- .set_draw_range_index_count(self.range.range_index, if visible { 6 } else { 0 })
- .map_err(|error| error.to_string())
+ for range in [self.background, self.range] {
+ renderer
+ .set_draw_range_index_count(range.range_index, if visible { 6 } else { 0 })
+ .map_err(|error| error.to_string())?;
+ }
+ Ok(())
}
}
diff --git a/crates/fparkan-assets/src/designer_screen.rs b/crates/fparkan-assets/src/designer_screen.rs
index fea9eef9..58af85c8 100644
--- a/crates/fparkan-assets/src/designer_screen.rs
+++ b/crates/fparkan-assets/src/designer_screen.rs
@@ -16,6 +16,8 @@ const SEND: [u32; 4] = [194, 437, 229, 480];
const EXIT: [u32; 4] = [405, 437, 446, 480];
/// Extent of the designer's original font profile.
pub const EXTENT: [u32; 2] = [800, 600];
+/// Native inset used to frame the assembled robot, in 640×480 coordinates.
+pub const MODEL_VIEWPORT: [f32; 4] = [195.0, 10.0, 445.0, 300.0];
/// Number of part rows in the project viewport.
pub const PART_ROWS: usize = 18;
@@ -89,8 +91,8 @@ impl DesignerScreen {
})
}
- /// Paints the active project and every installed mount in Unit DAT order.
- pub fn paint(&self, view: DesignerPicture<'_>) -> Result<RgbaImage, String> {
+ /// Paints the opaque panes that sit behind the rotating model.
+ pub fn paint_background(&self) -> RgbaImage {
let [width, height] = EXTENT;
let mut image = RgbaImage {
width,
@@ -102,7 +104,20 @@ impl DesignerScreen {
}
self.frame
.paint(&mut image, [185, 2, 455, 480], [0, 48, 0, 255]);
- self.text(&mut image, &self.labels.title, [194, 10, 446, 26], [255; 3])?;
+ self.frame
+ .paint(&mut image, [462, 2, 637, 265], [0, 48, 0, 255]);
+ image
+ }
+
+ /// Paints project actions over the model and part descriptions in Unit DAT order.
+ pub fn paint(&self, view: DesignerPicture<'_>) -> Result<RgbaImage, String> {
+ let [width, height] = EXTENT;
+ let mut image = RgbaImage {
+ width,
+ height,
+ rgba8: vec![0; (width * height * 4) as usize],
+ };
+ self.text(&mut image, &self.labels.title, [469, 10, 630, 26], [255; 3])?;
self.text(
&mut image,
&self.labels.recent,
@@ -119,7 +134,7 @@ impl DesignerScreen {
sprite(&mut image, &self.recent, recent_slot(index), tint);
}
if let Some((_, name, records)) = view.project {
- self.text(&mut image, name, [194, 27, 446, 42], [255, 255, 100])?;
+ self.text(&mut image, name, [469, 27, 630, 42], [255, 255, 100])?;
self.paint_parts(&mut image, records, view.first_part)?;
sprite(&mut image, &self.send_frame, SEND, [255; 3]);
sprite(&mut image, &self.send, [201, 450, 225, 474], [255; 3]);
@@ -162,9 +177,9 @@ impl DesignerScreen {
if width == 0 {
continue;
}
- let left = scale(196 + depth[first + row].min(8) * 7);
+ let left = scale(471 + depth[first + row].min(8) * 6);
let top = scale(46 + 10 * row as u32);
- let width = width.min((scale(446) - left) as u16);
+ let width = width.min((scale(630) - left) as u16);
let glyphs = self.font.centered_line_bytes(text, width, glyph_height)?;
copy_sprite(
image,
diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs
index b5527a4a..35dfa5b0 100644
--- a/crates/fparkan-runtime/src/lib.rs
+++ b/crates/fparkan-runtime/src/lib.rs
@@ -197,8 +197,8 @@ pub use player_weapon::{
WeaponIndicator, WeaponLamp,
};
pub use production::{
- clan_factory_schemes, factory_project_components, factory_schemes, order_clan_factory_scheme,
- order_factory_robot, order_factory_scheme,
+ clan_factory_schemes, factory_project_components, factory_project_root, factory_schemes,
+ order_clan_factory_scheme, order_factory_robot, order_factory_scheme,
};
pub use projectile::{
apply_projectile_contact, apply_projectile_hit, apply_projectile_impact,
diff --git a/crates/fparkan-runtime/src/production.rs b/crates/fparkan-runtime/src/production.rs
index 9f6846f8..ef1c0f38 100644
--- a/crates/fparkan-runtime/src/production.rs
+++ b/crates/fparkan-runtime/src/production.rs
@@ -392,16 +392,21 @@ pub fn factory_project_components(
engine: &Engine,
scheme: usize,
) -> Option<&[UnitComponentRecord]> {
- let (mission, production) = loaded_production(engine).ok()?;
- if scheme >= production.player_scheme_count {
- return None;
- }
- mission
+ engine
+ .loaded
+ .as_ref()?
.object_drafts
- .get(production.reserve_start + scheme * RESERVE_SLOTS)
+ .get(factory_project_root(engine, scheme)?)
.map(|draft| draft.unit_components.as_slice())
}
+/// Index of the first prepared world root for a player factory project.
+pub fn factory_project_root(engine: &Engine, scheme: usize) -> Option<usize> {
+ let (_, production) = loaded_production(engine).ok()?;
+ (scheme < production.player_scheme_count)
+ .then(|| production.reserve_start + scheme * RESERVE_SLOTS)
+}
+
fn schemes_for_plant<'a>(
mission: &'a LoadedMissionState,
production: &'a Production,
diff --git a/docs/tomes/06-behavior.md b/docs/tomes/06-behavior.md
index 92d1ebd3..37ce8b2a 100644
--- a/docs/tomes/06-behavior.md
+++ b/docs/tomes/06-behavior.md
@@ -3762,6 +3762,21 @@ RVA `0x56090`. Внутри пять ячеек «Последние проекÑ
сохраняет прежний выбор завода. Подписи команд читаются из `iron3d.dll`,
значки ячеек и команд — из листа `icons`, рамки кнопок — из `page4`.
+Выбранный проект в конструкторе вращается в отдельном окне модели.
+Оригинал задаёт область (195, 10)–(445, 300) в логических координатах
+640×480, а затем передаёт геометрию отдельной камере. В той же GOG
+`iron3d.dll` область создаётся по RVA `0x51fd0`, наклон камеры и скорость
+задаются в `0x9e780`, а `0x9edd0` прибавляет к углу 0,00075 радиана на
+каждую миллисекунду. При открытии другого проекта угол начинается заново.
+
+FParkan берёт геометрию и материалы подготовленной заводской сборки,
+включая точки крепления башни и орудий. Предпросмотр хранит исходную
+позу сборки, поэтому выпущенная машина может двигаться независимо.
+Vulkan ограничивает отрисовку прямоугольником модели и очищает глубину
+только внутри него. Вращение реализовано движением камеры вокруг
+центра модели. Список установленных деталей вынесен вправо, кнопки
+проектов рисуются поверх модели.
+
На коммуникаторе B показывает схемы этого завода. При запуске можно
указать одну схему через `--build-scheme`. Повторяемый параметр
`--build-part СТАРАЯ=НОВАЯ` заменяет внутренние детали этой схемы.