Compare commits

..

8 Commits

Author SHA1 Message Date
Jonas H
75a046d92a intent refactor 2026-03-28 13:24:05 +01:00
Jonas H
c8142708f5 +1 to text rendering 2026-03-28 13:23:51 +01:00
Jonas H
6b475825c2 +1 2026-03-28 13:23:42 +01:00
Jonas H
5c94bb34d5 agent update 2026-03-28 13:23:36 +01:00
Jonas H
e558b682e2 text rendering 2026-03-28 13:23:27 +01:00
Jonas H
dcd40ae443 ++1 2026-03-28 11:58:09 +01:00
Jonas H
3da031adc2 +1 2026-03-28 11:57:54 +01:00
Jonas H
9e8213da04 more reorganizing 2026-03-28 11:24:11 +01:00
30 changed files with 1174 additions and 130 deletions

View File

@@ -0,0 +1,10 @@
# Intent-Based Architecture Skill
Read the architecture document at `docs/self-gating-systems.md` (resolve relative to the project root `/home/jonas/projects/snow_trail_sdl/`) and follow its patterns when:
- Adding cross-system communication (use intents, not direct function calls)
- Adding new systems to the main loop
- Changing how game modes work (editor, dialog, gameplay)
- Working with camera, input, or mode-switching logic
Key rule: **systems communicate through typed intent data in shared queues** — producers insert intents, consumers process and remove them. No system calls another system's functions directly.

View File

@@ -10,6 +10,12 @@ Pure Rust game: SDL3 windowing, wgpu rendering, rapier3d physics, low-res retro
- **NO inline paths** — always add `use` statements at the top of files, never inline - **NO inline paths** — always add `use` statements at the top of files, never inline
- **NO `use` statements inside functions or impl blocks** — all `use` must be at the file (module) level - **NO `use` statements inside functions or impl blocks** — all `use` must be at the file (module) level
**Intent-Based Architecture:**
- Systems don't call each other. Cross-system communication goes through **intents** — one-frame typed structs in `Storage<T>` queues on `World`
- Producer inserts intent → consumer reads, acts, removes. Producer doesn't know which system processes it
- The main loop is a flat pipeline; systems self-gate based on data presence
- See `docs/self-gating-systems.md` for full pattern + examples
**Storage Parameters:** **Storage Parameters:**
- Functions should take specific storages they need rather than `&World` or `&mut World` - Functions should take specific storages they need rather than `&World` or `&mut World`
- Pass individual fields (`&world.transforms`, `&mut world.state_machines`) at the call site - Pass individual fields (`&world.transforms`, `&mut world.state_machines`) at the call site

View File

@@ -23,6 +23,7 @@ nalgebra = { version = "0.34.1", features = ["convert-glam030"] }
serde_json = "1.0" serde_json = "1.0"
bladeink = "1.2" bladeink = "1.2"
wesl = "0.2" wesl = "0.2"
ab_glyph = "0.2"
[build-dependencies] [build-dependencies]
wesl = "0.2" wesl = "0.2"

Binary file not shown.

135
docs/self-gating-systems.md Normal file
View File

@@ -0,0 +1,135 @@
# Intent-Based Architecture
Systems communicate through **intents** — one-frame typed data in shared queues — not through direct function calls. This decouples producers from consumers: the system that wants something to happen does not know or care which system processes it.
## The Pattern
```
Producer World (shared state) Consumer
──────── ──────────────────── ────────
detects dialog change
insert(camera, CameraTransitionIntent)
camera_transition_intents
camera_intent_system reads it
sets up CameraTransition component
removes intent
```
An intent is ephemeral (one frame). The state change it triggers (a component mutation) persists.
## Intent Types
Intents are plain structs stored in `Storage<T>` on `World`, keyed by target entity:
```rust
// components/intent.rs
pub struct FollowPlayerIntent;
pub struct StopFollowingIntent;
pub struct CameraTransitionIntent { pub duration: f32 }
```
```rust
// world.rs
pub follow_player_intents: Storage<FollowPlayerIntent>,
pub stop_following_intents: Storage<StopFollowingIntent>,
pub camera_transition_intents: Storage<CameraTransitionIntent>,
```
Adding a new intent = one struct + one storage field. Nothing else changes.
## Producing Intents
Any code with access to the storage can submit. The entity is the target:
```rust
// Event handler wants camera to follow player — doesn't call camera functions
world.follow_player_intents.insert(camera_entity, FollowPlayerIntent);
// Dialog system detects state change — doesn't know how transitions work
world.camera_transition_intents.insert(camera_entity, CameraTransitionIntent { duration: 0.8 });
```
Producers don't import consumer modules. They only know about the intent type and the storage.
## Consuming Intents
A consumer system reads, acts, and removes:
```rust
pub fn camera_intent_system(world: &mut World) {
// 1. Read
let follow_entities = world.follow_player_intents.all();
for entity in follow_entities {
// 2. Act — all the follow setup logic lives here
start_camera_following(world, entity);
// 3. Remove (consume)
world.follow_player_intents.remove(entity);
}
// ... same for stop_following_intents, camera_transition_intents
}
```
The consumer owns the implementation. `start_camera_following` is a private function inside the camera module — no other module can call it directly.
## Why This Matters
**Decoupling.** The dialog system doesn't import camera functions. It inserts a `CameraTransitionIntent`. If the camera system changes how transitions work, the dialog system is unaffected.
**Multiple producers, same path.** Editor toggle, dialog state changes, and future cutscene systems all produce the same `CameraTransitionIntent`. They all go through the same processing. No special cases.
**Testability.** To test camera transitions: insert a `CameraTransitionIntent`, call `camera_intent_system`, check the result. No need to simulate dialog state or editor toggles.
**Additive behavior.** To add a new reaction to `StopFollowingIntent` (e.g., play a sound), write a new system that reads the intent before the camera system consumes it. No existing code changes.
## Execution Order
The main loop is a flat pipeline. Order encodes causality:
```
Input + intent generation (camera_input, player_input, dialog_transition_detect)
Intent processing (camera_intent_system)
Camera behavior (noclip, dialog_camera, follow, transition, ground_clamp)
Editor overlay (UI only — not a game system)
Fixed-step physics (state_machine, physics, triggers, dialog)
Per-frame systems (state_machine, rotate, trees, spotlights, snow)
Render
```
Moving a system changes the data flow. The order is the contract.
## Systems Also Self-Gate
Because intents express what should happen, systems naturally have nothing to do when their data is absent:
- `camera_follow_system` — no `FollowComponent` = no work
- `dialog_camera_system` — no active bubbles = no work
- `player_input_system` — camera not following = no player input
- `camera_noclip_system` — camera has `FollowComponent` = skip
The main loop doesn't branch on mode flags. Systems check their own data.
## When to Use Intents vs. Direct Mutation
| Situation | Approach |
|---|---|
| One system wants another to do something | Intent |
| A system updating its own components | Direct mutation |
| Per-frame continuous computation | Components + tick system |
| Persistent state (is the camera following?) | Component (`FollowComponent`) |
| One-shot request (start following) | Intent (`FollowPlayerIntent`) |
## Adding New Intents
1. Define the struct in `components/intent.rs`
2. Add a `Storage<T>` field to `World` (+ `new()` + `despawn()`)
3. Producers insert into the storage
4. A consumer system reads, acts, and removes
5. Done — no other code changes

View File

@@ -18,8 +18,8 @@ use crate::loaders::mesh::Mesh;
use crate::paths; use crate::paths;
use crate::physics::PhysicsManager; use crate::physics::PhysicsManager;
use crate::render::Pipeline; use crate::render::Pipeline;
use crate::state::StateMachine; use crate::states::player_states::{LEAP_DURATION, ROLL_DURATION};
use crate::systems::player_states::{LEAP_DURATION, ROLL_DURATION}; use crate::states::state::StateMachine;
use crate::world::{Transform, World}; use crate::world::{Transform, World};
pub struct PlayerBundle pub struct PlayerBundle

View File

@@ -14,7 +14,7 @@ use crate::loaders::mesh::Mesh;
use crate::paths; use crate::paths;
use crate::physics::PhysicsManager; use crate::physics::PhysicsManager;
use crate::render::Pipeline; use crate::render::Pipeline;
use crate::state::StateMachine; use crate::states::state::StateMachine;
use crate::world::{Transform, World}; use crate::world::{Transform, World};
pub struct TestCharBundle pub struct TestCharBundle

View File

@@ -1,4 +1,13 @@
use glam::Mat4; use glam::{Mat4, Vec3};
pub struct CameraTransition
{
pub source_position: Vec3,
pub source_yaw: f32,
pub source_pitch: f32,
pub elapsed: f32,
pub duration: f32,
}
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
pub struct CameraComponent pub struct CameraComponent

8
src/components/intent.rs Normal file
View File

@@ -0,0 +1,8 @@
pub struct FollowPlayerIntent;
pub struct StopFollowingIntent;
pub struct CameraTransitionIntent
{
pub duration: f32,
}

View File

@@ -3,6 +3,7 @@ pub mod dialog;
pub mod dissolve; pub mod dissolve;
pub mod follow; pub mod follow;
pub mod input; pub mod input;
pub mod intent;
pub mod jump; pub mod jump;
pub mod lights; pub mod lights;
pub mod mesh; pub mod mesh;
@@ -14,7 +15,7 @@ pub mod rotate;
pub mod tree_instances; pub mod tree_instances;
pub mod trigger; pub mod trigger;
pub use camera::CameraComponent; pub use camera::{CameraComponent, CameraTransition};
pub use dialog::{ pub use dialog::{
DialogBubbleComponent, DialogOutcome, DialogOutcomeEvent, DialogPhase, DialogBubbleComponent, DialogOutcome, DialogOutcomeEvent, DialogPhase,
DialogProjectileComponent, DialogSourceComponent, ParryButton, DialogProjectileComponent, DialogSourceComponent, ParryButton,

View File

@@ -3,8 +3,6 @@ mod inspector;
use sdl3_sys::events::SDL_Event; use sdl3_sys::events::SDL_Event;
use crate::entity::EntityHandle; use crate::entity::EntityHandle;
use crate::systems::camera_noclip_system;
use crate::utility::input::InputState;
use crate::world::World; use crate::world::World;
pub use inspector::FrameStats; pub use inspector::FrameStats;
@@ -73,18 +71,8 @@ impl EditorState
} }
} }
pub fn editor_loop( pub fn editor_loop(editor: &mut EditorState, world: &mut World, stats: &FrameStats)
editor: &mut EditorState,
world: &mut World,
input_state: &InputState,
stats: &FrameStats,
delta: f32,
)
{ {
if editor.right_mouse_held
{
camera_noclip_system(world, input_state, delta);
}
let selected = editor.selected_entity; let selected = editor.selected_entity;
let show_player_state = editor.show_player_state; let show_player_state = editor.show_player_state;
editor editor

View File

@@ -9,7 +9,7 @@ mod physics;
mod picking; mod picking;
mod postprocess; mod postprocess;
mod render; mod render;
mod state; mod states;
mod systems; mod systems;
mod texture; mod texture;
mod utility; mod utility;
@@ -21,20 +21,21 @@ use crate::bundles::spotlight::spawn_spotlights;
use crate::bundles::terrain::{TerrainBundle, TerrainConfig}; use crate::bundles::terrain::{TerrainBundle, TerrainConfig};
use crate::bundles::test_char::TestCharBundle; use crate::bundles::test_char::TestCharBundle;
use crate::bundles::Bundle; use crate::bundles::Bundle;
use crate::components::intent::{FollowPlayerIntent, StopFollowingIntent};
use crate::debug::{collider_debug, DebugMode}; use crate::debug::{collider_debug, DebugMode};
use crate::editor::{editor_loop, EditorState, FrameStats}; use crate::editor::{editor_loop, EditorState, FrameStats};
use crate::entity::EntityHandle; use crate::entity::EntityHandle;
use crate::loaders::scene::Space; use crate::loaders::scene::Space;
use crate::physics::PhysicsManager; use crate::physics::PhysicsManager;
use crate::render::snow::{SnowConfig, SnowLayer}; use crate::render::snow::{SnowConfig, SnowLayer};
use crate::systems::camera::stop_camera_following;
use crate::systems::{ use crate::systems::{
camera_follow_system, camera_input_system, camera_view_matrix, dialog_bubble_render_system, camera_follow_system, camera_ground_clamp_system, camera_input_system, camera_intent_system,
dialog_camera_system, dialog_projectile_system, dialog_system, physics_sync_system, camera_noclip_system, camera_transition_system, camera_view_matrix,
player_input_system, render_system, rotate_system, snow_system, spotlight_sync_system, dialog_bubble_render_system, dialog_camera_system, dialog_camera_transition_system,
start_camera_following, state_machine_physics_system, state_machine_system, dialog_projectile_system, dialog_system, physics_sync_system, player_input_system,
tree_dissolve_update_system, tree_instance_buffer_update_system, tree_occlusion_system, render_system, rotate_system, snow_system, spotlight_sync_system, state_machine_physics_system,
trigger_system, state_machine_system, tree_dissolve_update_system, tree_instance_buffer_update_system,
tree_occlusion_system, trigger_system,
}; };
use crate::utility::input::InputState; use crate::utility::input::InputState;
use crate::utility::time::Time; use crate::utility::time::Time;
@@ -72,6 +73,7 @@ fn init() -> Result<Game, Box<dyn std::error::Error>>
.window("snow_trail", 1200, 900) .window("snow_trail", 1200, 900)
.position_centered() .position_centered()
.resizable() .resizable()
.high_pixel_density()
.vulkan() .vulkan()
.build()?; .build()?;
let renderer = pollster::block_on(Renderer::new(&window, 2))?; let renderer = pollster::block_on(Renderer::new(&window, 2))?;
@@ -85,7 +87,9 @@ fn init() -> Result<Game, Box<dyn std::error::Error>>
editor.init_platform(&window); editor.init_platform(&window);
let (mut world, camera_entity) = init_world()?; let (mut world, camera_entity) = init_world()?;
start_camera_following(&mut world, camera_entity); world
.follow_player_intents
.insert(camera_entity, FollowPlayerIntent);
let _event_pump = sdl_context.event_pump()?; let _event_pump = sdl_context.event_pump()?;
let input_state = InputState::new(); let input_state = InputState::new();
@@ -208,7 +212,9 @@ fn process_events(game: &mut Game) -> bool
{ {
game.editor.right_mouse_held = true; game.editor.right_mouse_held = true;
game.input_state.mouse_captured = true; game.input_state.mouse_captured = true;
stop_camera_following(&mut game.world, game.camera_entity); game.world
.stop_following_intents
.insert(game.camera_entity, StopFollowingIntent);
game.sdl_context game.sdl_context
.mouse() .mouse()
.set_relative_mouse_mode(&game.window, true); .set_relative_mouse_mode(&game.window, true);
@@ -265,7 +271,9 @@ fn toggle_editor(game: &mut Game)
game.editor.active = !game.editor.active; game.editor.active = !game.editor.active;
if game.editor.active if game.editor.active
{ {
stop_camera_following(&mut game.world, game.camera_entity); game.world
.stop_following_intents
.insert(game.camera_entity, StopFollowingIntent);
game.sdl_context game.sdl_context
.mouse() .mouse()
.set_relative_mouse_mode(&game.window, false); .set_relative_mouse_mode(&game.window, false);
@@ -274,7 +282,9 @@ fn toggle_editor(game: &mut Game)
} }
else else
{ {
start_camera_following(&mut game.world, game.camera_entity); game.world
.follow_player_intents
.insert(game.camera_entity, FollowPlayerIntent);
game.input_state.mouse_captured = true; game.input_state.mouse_captured = true;
game.sdl_context game.sdl_context
.mouse() .mouse()
@@ -323,7 +333,7 @@ fn submit_frame(game: &mut Game, draw_calls: &[render::DrawCall], time: f32, del
let view_proj = projection * view; let view_proj = projection * view;
let player_pos = game.world.player_position(); let player_pos = game.world.player_position();
let billboard_calls = let (billboard_calls, text_vertices) =
dialog_bubble_render_system(&game.world, camera_transform.position, view_proj); dialog_bubble_render_system(&game.world, camera_transform.position, view_proj);
let frame = render::render( let frame = render::render(
@@ -333,6 +343,7 @@ fn submit_frame(game: &mut Game, draw_calls: &[render::DrawCall], time: f32, del
player_pos, player_pos,
draw_calls, draw_calls,
&billboard_calls, &billboard_calls,
&text_vertices,
time, time,
delta, delta,
game.world.debug_mode, game.world.debug_mode,
@@ -384,36 +395,28 @@ fn main() -> Result<(), Box<dyn std::error::Error>>
game.editor.show_player_state = !game.editor.show_player_state; game.editor.show_player_state = !game.editor.show_player_state;
} }
// --- camera + input --- // --- intent generation ---
camera_input_system(&mut game.world, &game.input_state); camera_input_system(&mut game.world, &game.input_state);
player_input_system(&mut game.world, &game.input_state);
dialog_camera_transition_system(&mut game.world, game.camera_entity);
// --- intent processing + camera ---
camera_intent_system(&mut game.world);
camera_noclip_system(&mut game.world, &game.input_state, delta);
dialog_camera_system(&mut game.world, delta);
camera_follow_system(&mut game.world);
camera_transition_system(&mut game.world, delta);
camera_ground_clamp_system(&mut game.world);
// --- editor overlay ---
if game.editor.active if game.editor.active
{ {
editor_loop( editor_loop(&mut game.editor, &mut game.world, &game.stats);
&mut game.editor,
&mut game.world,
&game.input_state,
&game.stats,
delta,
);
} }
else
{
let dialog_active = !game.world.bubble_tags.all().is_empty();
if dialog_active
{
dialog_camera_system(&mut game.world, delta);
}
else
{
camera_follow_system(&mut game.world);
}
player_input_system(&mut game.world, &game.input_state);
if game.editor.show_player_state if game.editor.show_player_state
{ {
game.editor.build_hud(&game.world); game.editor.build_hud(&game.world);
} }
}
// --- fixed-step physics --- // --- fixed-step physics ---
let physics_start = Instant::now(); let physics_start = Instant::now();
@@ -443,7 +446,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>>
let spotlights = spotlight_sync_system(&game.world); let spotlights = spotlight_sync_system(&game.world);
render::update_spotlights(spotlights); render::update_spotlights(spotlights);
snow_system(&mut game.world, game.editor.active); snow_system(&mut game.world);
// --- draw call collection --- // --- draw call collection ---
let mut draw_calls = render_system(&game.world); let mut draw_calls = render_system(&game.world);

View File

@@ -63,6 +63,16 @@ pub mod dialogs
} }
} }
pub mod fonts
{
use crate::paths::ASSETS_DIR;
pub fn departure_mono() -> String
{
format!("{}/fonts/DepartureMono-Regular.otf", ASSETS_DIR)
}
}
pub mod shaders pub mod shaders
{ {
use crate::paths::SHADERS_DIR; use crate::paths::SHADERS_DIR;
@@ -87,6 +97,11 @@ pub mod shaders
format!("{}/snow_deform.wgsl", SHADERS_DIR) format!("{}/snow_deform.wgsl", SHADERS_DIR)
} }
pub fn text() -> String
{
format!("{}/text.wgsl", SHADERS_DIR)
}
pub const SHADOW_PACKAGE: &str = "package::shadow"; pub const SHADOW_PACKAGE: &str = "package::shadow";
pub const MAIN_PACKAGE: &str = "package::main"; pub const MAIN_PACKAGE: &str = "package::main";
pub const SNOW_LIGHT_ACCUMULATION_PACKAGE: &str = "package::snow_light_accumulation"; pub const SNOW_LIGHT_ACCUMULATION_PACKAGE: &str = "package::snow_light_accumulation";

264
src/render/font_atlas.rs Normal file
View File

@@ -0,0 +1,264 @@
use ab_glyph::{Font, FontVec, PxScale, ScaleFont};
use glam::Vec3;
use crate::paths;
use super::text_pipeline::TextVertex;
const ATLAS_COLS: u32 = 16;
const ATLAS_ROWS: u32 = 8;
const FIRST_CHAR: u32 = 32;
const LAST_CHAR: u32 = 126;
const NUM_GLYPHS: u32 = LAST_CHAR - FIRST_CHAR + 1;
const FONT_PX: f32 = 16.0;
struct GlyphMetrics
{
uv_min: [f32; 2],
uv_max: [f32; 2],
}
pub struct FontAtlas
{
pub texture_view: wgpu::TextureView,
pub sampler: wgpu::Sampler,
glyphs: Vec<GlyphMetrics>,
pub cell_w: f32,
pub cell_h: f32,
}
impl FontAtlas
{
pub fn load(device: &wgpu::Device, queue: &wgpu::Queue) -> Self
{
let path = paths::fonts::departure_mono();
let data = std::fs::read(&path).unwrap_or_else(|_| panic!("Failed to read font: {path}"));
let font = FontVec::try_from_vec(data).expect("Failed to parse font");
let scale = PxScale::from(FONT_PX);
let scaled = font.as_scaled(scale);
let ascent = scaled.ascent();
let descent = scaled.descent();
let cell_h = (ascent - descent).ceil() as u32;
let cell_w = scaled.h_advance(font.glyph_id(' ')).ceil() as u32;
let atlas_w = ATLAS_COLS * cell_w;
let atlas_h = ATLAS_ROWS * cell_h;
let mut pixels = vec![0u8; (atlas_w * atlas_h) as usize];
let mut glyphs = Vec::with_capacity(NUM_GLYPHS as usize);
for idx in 0..NUM_GLYPHS
{
let ch = char::from_u32(FIRST_CHAR + idx).unwrap_or(' ');
let col = idx % ATLAS_COLS;
let row = idx / ATLAS_COLS;
let cell_x = col * cell_w;
let cell_y = row * cell_h;
glyphs.push(GlyphMetrics {
uv_min: [cell_x as f32 / atlas_w as f32, cell_y as f32 / atlas_h as f32],
uv_max: [
(cell_x + cell_w) as f32 / atlas_w as f32,
(cell_y + cell_h) as f32 / atlas_h as f32,
],
});
let glyph_id = font.glyph_id(ch);
let glyph = glyph_id.with_scale_and_position(
scale,
ab_glyph::point(cell_x as f32, cell_y as f32 + ascent),
);
if let Some(outlined) = font.outline_glyph(glyph)
{
let bounds = outlined.px_bounds();
outlined.draw(|x, y, coverage| {
let abs_x = bounds.min.x.floor() as i32 + x as i32;
let abs_y = bounds.min.y.floor() as i32 + y as i32;
if abs_x >= 0 && abs_y >= 0
{
let ax = abs_x as u32;
let ay = abs_y as u32;
if ax < atlas_w && ay < atlas_h
{
let i = (ay * atlas_w + ax) as usize;
let v = (coverage * 255.0 + 0.5) as u8;
pixels[i] = pixels[i].max(v);
}
}
});
}
}
let extent = wgpu::Extent3d {
width: atlas_w,
height: atlas_h,
depth_or_array_layers: 1,
};
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("Font Atlas"),
size: extent,
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::R8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &texture,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
&pixels,
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(atlas_w),
rows_per_image: Some(atlas_h),
},
extent,
);
let texture_view = texture.create_view(&wgpu::TextureViewDescriptor::default());
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("Font Atlas Sampler"),
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
mag_filter: wgpu::FilterMode::Nearest,
min_filter: wgpu::FilterMode::Nearest,
..Default::default()
});
Self {
texture_view,
sampler,
glyphs,
cell_w: cell_w as f32,
cell_h: cell_h as f32,
}
}
pub fn aspect(&self) -> f32
{
self.cell_w / self.cell_h
}
/// Build billboard-space text quads for a single dialog bubble.
///
/// `anchor` world-space centre of the bubble body
/// `right`/`up` billboard orientation vectors
/// `inner_half_w` half-width of the text area in world units
/// `inner_top_y` y-offset (up-axis) of the top edge of the text area
/// `char_world_h` world-space height of one character cell
/// `line_spacing` extra vertical gap between lines in world units
pub fn build_bubble_text(
&self,
text: &str,
anchor: Vec3,
right: Vec3,
up: Vec3,
inner_half_w: f32,
inner_top_y: f32,
char_world_h: f32,
line_spacing: f32,
) -> Vec<TextVertex>
{
let char_w = char_world_h * self.aspect();
let chars_per_line = ((inner_half_w * 2.0) / char_w).floor() as usize;
if chars_per_line == 0
{
return Vec::new();
}
let lines = word_wrap(text, chars_per_line);
let half_char_h = char_world_h * 0.5;
let half_char_w = char_w * 0.5;
let text_left = -inner_half_w;
let mut verts = Vec::new();
for (row, line) in lines.iter().enumerate()
{
let y = inner_top_y - half_char_h - row as f32 * (char_world_h + line_spacing);
if y < -inner_top_y + half_char_h
{
break;
}
for (col, ch) in line.chars().enumerate()
{
if ch == ' '
{
continue;
}
let code = ch as u32;
if code < FIRST_CHAR || code > LAST_CHAR
{
continue;
}
let g = &self.glyphs[(code - FIRST_CHAR) as usize];
let x = text_left + half_char_w + col as f32 * char_w;
let centre = anchor + right * x + up * y;
let tl = centre - right * half_char_w + up * half_char_h;
let tr = centre + right * half_char_w + up * half_char_h;
let br = centre + right * half_char_w - up * half_char_h;
let bl = centre - right * half_char_w - up * half_char_h;
verts.extend_from_slice(&[
TextVertex { position: tl.to_array(), uv: g.uv_min },
TextVertex {
position: tr.to_array(),
uv: [g.uv_max[0], g.uv_min[1]],
},
TextVertex { position: br.to_array(), uv: g.uv_max },
TextVertex {
position: bl.to_array(),
uv: [g.uv_min[0], g.uv_max[1]],
},
]);
}
}
verts
}
}
fn word_wrap(text: &str, chars_per_line: usize) -> Vec<String>
{
let mut lines: Vec<String> = Vec::new();
let mut current = String::new();
for word in text.split_whitespace()
{
if current.is_empty()
{
current.push_str(word);
}
else if current.len() + 1 + word.len() <= chars_per_line
{
current.push(' ');
current.push_str(word);
}
else
{
lines.push(current.clone());
current = word.to_string();
}
}
if !current.is_empty()
{
lines.push(current);
}
lines
}

View File

@@ -9,7 +9,8 @@ use std::cell::RefCell;
use crate::debug::DebugMode; use crate::debug::DebugMode;
use crate::entity::EntityHandle; use crate::entity::EntityHandle;
use super::{BillboardDrawCall, DrawCall, Renderer, Spotlight}; use super::{BillboardDrawCall, DrawCall, FontAtlas, Renderer, Spotlight};
use super::text_pipeline::TextVertex;
thread_local! { thread_local! {
static GLOBAL_RENDERER: RefCell<Option<Renderer>> = RefCell::new(None); static GLOBAL_RENDERER: RefCell<Option<Renderer>> = RefCell::new(None);
@@ -99,6 +100,13 @@ pub fn set_selected_entity(entity: Option<EntityHandle>)
with_mut(|r| r.selected_entity = entity); with_mut(|r| r.selected_entity = entity);
} }
pub fn with_font_atlas<F, R>(f: F) -> R
where
F: FnOnce(&FontAtlas) -> R,
{
with_ref(|r| f(&r.font_atlas))
}
pub fn render( pub fn render(
view: &glam::Mat4, view: &glam::Mat4,
projection: &glam::Mat4, projection: &glam::Mat4,
@@ -106,6 +114,7 @@ pub fn render(
player_position: glam::Vec3, player_position: glam::Vec3,
draw_calls: &[DrawCall], draw_calls: &[DrawCall],
billboard_calls: &[BillboardDrawCall], billboard_calls: &[BillboardDrawCall],
text_vertices: &[TextVertex],
time: f32, time: f32,
delta_time: f32, delta_time: f32,
debug_mode: DebugMode, debug_mode: DebugMode,
@@ -119,6 +128,7 @@ pub fn render(
player_position, player_position,
draw_calls, draw_calls,
billboard_calls, billboard_calls,
text_vertices,
time, time,
delta_time, delta_time,
debug_mode, debug_mode,

View File

@@ -6,14 +6,18 @@ mod shadow;
mod types; mod types;
pub mod billboard; pub mod billboard;
pub mod font_atlas;
pub mod snow; pub mod snow;
pub mod snow_light; pub mod snow_light;
pub mod text_pipeline;
pub use billboard::{BillboardDrawCall, BillboardPipeline}; pub use billboard::{BillboardDrawCall, BillboardPipeline};
pub use font_atlas::FontAtlas;
pub use global::{ pub use global::{
aspect_ratio, init, init_snow_light_accumulation, render, set_selected_entity, set_snow_depth, aspect_ratio, init, init_snow_light_accumulation, render, set_selected_entity, set_snow_depth,
set_terrain_data, update_spotlights, with_device, with_queue, with_surface_format, set_terrain_data, update_spotlights, with_device, with_font_atlas, with_queue, with_surface_format,
}; };
pub use text_pipeline::TextVertex;
pub use types::{DrawCall, Pipeline, Spotlight, SpotlightRaw, Uniforms, MAX_SPOTLIGHTS}; pub use types::{DrawCall, Pipeline, Spotlight, SpotlightRaw, Uniforms, MAX_SPOTLIGHTS};
use crate::entity::EntityHandle; use crate::entity::EntityHandle;
@@ -38,6 +42,7 @@ pub struct Renderer
pub config: wgpu::SurfaceConfiguration, pub config: wgpu::SurfaceConfiguration,
framebuffer: LowResFramebuffer, framebuffer: LowResFramebuffer,
fullres_depth_view: wgpu::TextureView,
standard_pipeline: wgpu::RenderPipeline, standard_pipeline: wgpu::RenderPipeline,
snow_clipmap_pipeline: wgpu::RenderPipeline, snow_clipmap_pipeline: wgpu::RenderPipeline,
@@ -45,6 +50,8 @@ pub struct Renderer
debug_lines_pipeline: Option<wgpu::RenderPipeline>, debug_lines_pipeline: Option<wgpu::RenderPipeline>,
debug_overlay: Option<debug_overlay::DebugOverlay>, debug_overlay: Option<debug_overlay::DebugOverlay>,
billboard_pipeline: BillboardPipeline, billboard_pipeline: BillboardPipeline,
font_atlas: font_atlas::FontAtlas,
text_pipeline: text_pipeline::TextPipeline,
wireframe_supported: bool, wireframe_supported: bool,
uniform_buffer: wgpu::Buffer, uniform_buffer: wgpu::Buffer,
@@ -148,6 +155,23 @@ impl Renderer
let framebuffer = let framebuffer =
LowResFramebuffer::new(&device, low_res_width, low_res_height, config.format); LowResFramebuffer::new(&device, low_res_width, low_res_height, config.format);
let fullres_depth_texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("Full Res Depth Texture"),
size: wgpu::Extent3d {
width: config.width,
height: config.height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Depth32Float,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
view_formats: &[],
});
let fullres_depth_view =
fullres_depth_texture.create_view(&wgpu::TextureViewDescriptor::default());
let uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor { let uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Uniform Buffer"), label: Some("Uniform Buffer"),
size: (std::mem::size_of::<Uniforms>() * MAX_DRAW_CALLS) as wgpu::BufferAddress, size: (std::mem::size_of::<Uniforms>() * MAX_DRAW_CALLS) as wgpu::BufferAddress,
@@ -502,6 +526,8 @@ impl Renderer
)); ));
let billboard_pipeline = BillboardPipeline::new(&device, config.format); let billboard_pipeline = BillboardPipeline::new(&device, config.format);
let font_atlas = font_atlas::FontAtlas::load(&device, &queue);
let text_pipeline = text_pipeline::TextPipeline::new(&device, config.format, &font_atlas);
let debug_overlay = Some(debug_overlay::DebugOverlay::new(&device, config.format)); let debug_overlay = Some(debug_overlay::DebugOverlay::new(&device, config.format));
@@ -526,12 +552,15 @@ impl Renderer
surface, surface,
config, config,
framebuffer, framebuffer,
fullres_depth_view,
standard_pipeline, standard_pipeline,
snow_clipmap_pipeline, snow_clipmap_pipeline,
wireframe_pipeline, wireframe_pipeline,
debug_lines_pipeline, debug_lines_pipeline,
debug_overlay, debug_overlay,
billboard_pipeline, billboard_pipeline,
font_atlas,
text_pipeline,
wireframe_supported, wireframe_supported,
uniform_buffer, uniform_buffer,
bind_group_layout, bind_group_layout,
@@ -576,6 +605,7 @@ impl Renderer
player_position: glam::Vec3, player_position: glam::Vec3,
draw_calls: &[DrawCall], draw_calls: &[DrawCall],
billboard_calls: &[BillboardDrawCall], billboard_calls: &[BillboardDrawCall],
text_vertices: &[text_pipeline::TextVertex],
time: f32, time: f32,
delta_time: f32, delta_time: f32,
debug_mode: DebugMode, debug_mode: DebugMode,
@@ -954,14 +984,6 @@ impl Renderer
} }
} }
self.billboard_pipeline.render(
&mut encoder,
&self.queue,
&self.framebuffer.view,
&self.framebuffer.depth_view,
billboard_calls,
);
self.queue.submit(std::iter::once(encoder.finish())); self.queue.submit(std::iter::once(encoder.finish()));
let frame = match self.surface.get_current_texture() let frame = match self.surface.get_current_texture()
@@ -1012,6 +1034,50 @@ impl Renderer
} }
self.queue.submit(std::iter::once(blit_encoder.finish())); self.queue.submit(std::iter::once(blit_encoder.finish()));
let mut overlay_encoder =
self.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("Dialog Overlay Encoder"),
});
{
let _depth_clear = overlay_encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Full Res Depth Clear"),
color_attachments: &[],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &self.fullres_depth_view,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(1.0),
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
}),
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
}
self.billboard_pipeline.render(
&mut overlay_encoder,
&self.queue,
&screen_view,
&self.fullres_depth_view,
billboard_calls,
);
let view_proj = (*projection * *view).to_cols_array_2d();
self.text_pipeline.render(
&mut overlay_encoder,
&self.queue,
&screen_view,
&self.fullres_depth_view,
text_vertices,
view_proj,
);
self.queue.submit(std::iter::once(overlay_encoder.finish()));
frame frame
} }

262
src/render/text_pipeline.rs Normal file
View File

@@ -0,0 +1,262 @@
use bytemuck::{Pod, Zeroable};
use wgpu::util::DeviceExt;
use crate::paths;
use super::font_atlas::FontAtlas;
const MAX_TEXT_CHARS: usize = 512;
#[repr(C)]
#[derive(Copy, Clone, Pod, Zeroable)]
pub struct TextVertex
{
pub position: [f32; 3],
pub uv: [f32; 2],
}
impl TextVertex
{
fn desc() -> wgpu::VertexBufferLayout<'static>
{
wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<TextVertex>() as wgpu::BufferAddress,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &[
wgpu::VertexAttribute {
offset: 0,
shader_location: 0,
format: wgpu::VertexFormat::Float32x3,
},
wgpu::VertexAttribute {
offset: std::mem::size_of::<[f32; 3]>() as wgpu::BufferAddress,
shader_location: 1,
format: wgpu::VertexFormat::Float32x2,
},
],
}
}
}
#[repr(C)]
#[derive(Copy, Clone, Pod, Zeroable)]
struct ViewProjUniform
{
matrix: [[f32; 4]; 4],
}
pub struct TextPipeline
{
pipeline: wgpu::RenderPipeline,
vertex_buffer: wgpu::Buffer,
index_buffer: wgpu::Buffer,
uniform_buffer: wgpu::Buffer,
bind_group: wgpu::BindGroup,
}
impl TextPipeline
{
pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat, atlas: &FontAtlas) -> Self
{
let shader_src =
std::fs::read_to_string(&paths::shaders::text()).expect("Failed to read text.wgsl");
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Text Shader"),
source: wgpu::ShaderSource::Wgsl(shader_src.into()),
});
let bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Text Bind Group Layout"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: std::num::NonZeroU64::new(
std::mem::size_of::<ViewProjUniform>() as u64,
),
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
],
});
let uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Text ViewProj Buffer"),
size: std::mem::size_of::<ViewProjUniform>() as wgpu::BufferAddress,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Text Bind Group"),
layout: &bind_group_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: uniform_buffer.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&atlas.texture_view),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::Sampler(&atlas.sampler),
},
],
});
let vertex_buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Text Vertex Buffer"),
size: (MAX_TEXT_CHARS * 4 * std::mem::size_of::<TextVertex>()) as wgpu::BufferAddress,
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let indices: Vec<u16> = (0..MAX_TEXT_CHARS as u16)
.flat_map(|i| {
let b = i * 4;
[b, b + 1, b + 2, b + 2, b + 3, b]
})
.collect();
let index_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Text Index Buffer"),
contents: bytemuck::cast_slice(&indices),
usage: wgpu::BufferUsages::INDEX,
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Text Pipeline Layout"),
bind_group_layouts: &[&bind_group_layout],
immediate_size: 0,
});
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Text Pipeline"),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
buffers: &[TextVertex::desc()],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format,
blend: Some(wgpu::BlendState::ALPHA_BLENDING),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
strip_index_format: None,
front_face: wgpu::FrontFace::Ccw,
cull_mode: None,
polygon_mode: wgpu::PolygonMode::Fill,
unclipped_depth: false,
conservative: false,
},
depth_stencil: Some(wgpu::DepthStencilState {
format: wgpu::TextureFormat::Depth32Float,
depth_write_enabled: false,
depth_compare: wgpu::CompareFunction::LessEqual,
stencil: wgpu::StencilState::default(),
bias: wgpu::DepthBiasState::default(),
}),
multisample: wgpu::MultisampleState {
count: 1,
mask: !0,
alpha_to_coverage_enabled: false,
},
multiview_mask: None,
cache: None,
});
Self {
pipeline,
vertex_buffer,
index_buffer,
uniform_buffer,
bind_group,
}
}
pub fn render(
&self,
encoder: &mut wgpu::CommandEncoder,
queue: &wgpu::Queue,
color_view: &wgpu::TextureView,
depth_view: &wgpu::TextureView,
vertices: &[TextVertex],
view_proj: [[f32; 4]; 4],
)
{
if vertices.is_empty()
{
return;
}
let n_chars = (vertices.len() / 4).min(MAX_TEXT_CHARS);
let used = &vertices[..n_chars * 4];
queue.write_buffer(
&self.uniform_buffer,
0,
bytemuck::cast_slice(&[ViewProjUniform { matrix: view_proj }]),
);
queue.write_buffer(&self.vertex_buffer, 0, bytemuck::cast_slice(used));
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Text Pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: color_view,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
},
depth_slice: None,
})],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: depth_view,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
}),
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
pass.set_pipeline(&self.pipeline);
pass.set_bind_group(0, &self.bind_group, &[]);
pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
pass.set_index_buffer(self.index_buffer.slice(..), wgpu::IndexFormat::Uint16);
pass.draw_indexed(0..(n_chars * 6) as u32, 0, 0..1);
}
}

45
src/shaders/text.wgsl Normal file
View File

@@ -0,0 +1,45 @@
struct Uniforms
{
view_proj: mat4x4<f32>,
}
@group(0) @binding(0)
var<uniform> u: Uniforms;
@group(0) @binding(1)
var glyph_atlas: texture_2d<f32>;
@group(0) @binding(2)
var glyph_sampler: sampler;
struct VertexIn
{
@location(0) position: vec3<f32>,
@location(1) uv: vec2<f32>,
}
struct VertexOut
{
@builtin(position) clip_pos: vec4<f32>,
@location(0) uv: vec2<f32>,
}
@vertex
fn vs_main(in: VertexIn) -> VertexOut
{
var out: VertexOut;
out.clip_pos = u.view_proj * vec4<f32>(in.position, 1.0);
out.uv = in.uv;
return out;
}
@fragment
fn fs_main(in: VertexOut) -> @location(0) vec4<f32>
{
let coverage = textureSample(glyph_atlas, glyph_sampler, in.uv).r;
if coverage < 0.5
{
discard;
}
return vec4<f32>(1.0, 1.0, 1.0, 1.0);
}

2
src/states/mod.rs Normal file
View File

@@ -0,0 +1,2 @@
pub mod player_states;
pub mod state;

View File

@@ -7,7 +7,7 @@ use crate::components::player_states::{
}; };
use crate::entity::EntityHandle; use crate::entity::EntityHandle;
use crate::physics::PhysicsManager; use crate::physics::PhysicsManager;
use crate::state::PlayerState; use crate::states::state::State;
use crate::world::World; use crate::world::World;
pub const LEAP_DURATION: f32 = 0.18; pub const LEAP_DURATION: f32 = 0.18;
@@ -15,7 +15,7 @@ pub const ROLL_DURATION: f32 = 0.42;
const LEAP_SPEED: f32 = 18.0; const LEAP_SPEED: f32 = 18.0;
const ROLL_SPEED: f32 = 14.0; const ROLL_SPEED: f32 = 14.0;
impl PlayerState for IdleState impl State for IdleState
{ {
fn tick_time(&mut self, delta: f32) fn tick_time(&mut self, delta: f32)
{ {
@@ -87,7 +87,7 @@ impl PlayerState for IdleState
} }
} }
impl PlayerState for WalkingState impl State for WalkingState
{ {
fn tick_time(&mut self, delta: f32) fn tick_time(&mut self, delta: f32)
{ {
@@ -204,7 +204,7 @@ impl PlayerState for WalkingState
} }
} }
impl PlayerState for JumpingState impl State for JumpingState
{ {
fn tick_time(&mut self, delta: f32) fn tick_time(&mut self, delta: f32)
{ {
@@ -283,7 +283,7 @@ impl PlayerState for JumpingState
} }
} }
impl PlayerState for FallingState impl State for FallingState
{ {
fn tick_time(&mut self, delta: f32) fn tick_time(&mut self, delta: f32)
{ {
@@ -356,7 +356,7 @@ impl PlayerState for FallingState
} }
} }
impl PlayerState for LeapingState impl State for LeapingState
{ {
fn tick_time(&mut self, delta: f32) fn tick_time(&mut self, delta: f32)
{ {
@@ -430,7 +430,7 @@ impl PlayerState for LeapingState
} }
} }
impl PlayerState for RollingState impl State for RollingState
{ {
fn tick_time(&mut self, delta: f32) fn tick_time(&mut self, delta: f32)
{ {

View File

@@ -4,7 +4,7 @@ use std::collections::HashMap;
use crate::entity::EntityHandle; use crate::entity::EntityHandle;
use crate::world::{Storage, World}; use crate::world::{Storage, World};
pub trait PlayerState pub trait State
{ {
fn tick_time(&mut self, _delta: f32) {} fn tick_time(&mut self, _delta: f32) {}
fn on_enter(&mut self, _world: &mut World, _entity: EntityHandle) {} fn on_enter(&mut self, _world: &mut World, _entity: EntityHandle) {}
@@ -54,7 +54,7 @@ impl StateMachine
} }
} }
pub fn register_state<S: PlayerState + Default + 'static>( pub fn register_state<S: State + Default + 'static>(
&mut self, &mut self,
storage: fn(&mut World) -> &mut Storage<S>, storage: fn(&mut World) -> &mut Storage<S>,
) )

View File

@@ -1,9 +1,14 @@
use glam::Vec3; use glam::Vec3;
use crate::components::camera::CameraTransition;
use crate::components::FollowComponent; use crate::components::FollowComponent;
use crate::entity::EntityHandle;
use crate::physics::PhysicsManager;
use crate::utility::input::InputState; use crate::utility::input::InputState;
use crate::world::{Transform, World}; use crate::world::{Transform, World};
const CAMERA_GROUND_OFFSET: f32 = 2.0;
pub fn camera_view_matrix(world: &World) -> Option<glam::Mat4> pub fn camera_view_matrix(world: &World) -> Option<glam::Mat4>
{ {
let (camera_entity, camera_component) = world.active_camera()?; let (camera_entity, camera_component) = world.active_camera()?;
@@ -66,6 +71,35 @@ pub fn camera_input_system(world: &mut World, input_state: &InputState)
} }
} }
pub fn camera_intent_system(world: &mut World)
{
let follow_entities: Vec<EntityHandle> = world.follow_player_intents.all();
for entity in follow_entities
{
start_camera_following(world, entity);
world.follow_player_intents.remove(entity);
}
let stop_entities: Vec<EntityHandle> = world.stop_following_intents.all();
for entity in stop_entities
{
stop_camera_following(world, entity);
world.stop_following_intents.remove(entity);
}
let transition_entities: Vec<EntityHandle> = world.camera_transition_intents.all();
for entity in transition_entities
{
let duration = world
.camera_transition_intents
.get(entity)
.map(|i| i.duration)
.unwrap_or(0.5);
start_camera_transition(world, entity, duration);
world.camera_transition_intents.remove(entity);
}
}
pub fn camera_follow_system(world: &mut World) pub fn camera_follow_system(world: &mut World)
{ {
let camera_entities: Vec<_> = world.follows.all(); let camera_entities: Vec<_> = world.follows.all();
@@ -109,10 +143,20 @@ pub fn camera_follow_system(world: &mut World)
pub fn camera_noclip_system(world: &mut World, input_state: &InputState, delta: f32) pub fn camera_noclip_system(world: &mut World, input_state: &InputState, delta: f32)
{ {
if !input_state.mouse_captured
{
return;
}
let cameras: Vec<_> = world.cameras.all(); let cameras: Vec<_> = world.cameras.all();
for camera_entity in cameras for camera_entity in cameras
{ {
if world.follows.get(camera_entity).is_some()
{
continue;
}
if let Some(camera) = world.cameras.get(camera_entity) if let Some(camera) = world.cameras.get(camera_entity)
{ {
if !camera.is_active if !camera.is_active
@@ -167,7 +211,7 @@ pub fn camera_noclip_system(world: &mut World, input_state: &InputState, delta:
} }
} }
pub fn start_camera_following(world: &mut World, camera_entity: crate::entity::EntityHandle) fn start_camera_following(world: &mut World, camera_entity: crate::entity::EntityHandle)
{ {
if let Some(camera_transform) = world.transforms.get(camera_entity) if let Some(camera_transform) = world.transforms.get(camera_entity)
{ {
@@ -202,7 +246,7 @@ pub fn start_camera_following(world: &mut World, camera_entity: crate::entity::E
} }
} }
pub fn stop_camera_following(world: &mut World, camera_entity: crate::entity::EntityHandle) fn stop_camera_following(world: &mut World, camera_entity: crate::entity::EntityHandle)
{ {
if let Some(follow) = world.follows.get(camera_entity) if let Some(follow) = world.follows.get(camera_entity)
{ {
@@ -226,3 +270,134 @@ pub fn stop_camera_following(world: &mut World, camera_entity: crate::entity::En
world.follows.remove(camera_entity); world.follows.remove(camera_entity);
} }
} }
pub fn camera_ground_clamp_system(world: &mut World)
{
let Some((camera_entity, _)) = world.active_camera()
else
{
return;
};
if world.follows.get(camera_entity).is_none()
{
return;
}
world.transforms.with_mut(camera_entity, |t| {
let ground_y =
PhysicsManager::get_terrain_height_at(t.position.x, t.position.z).unwrap_or(0.0);
let min_y = ground_y + CAMERA_GROUND_OFFSET;
if t.position.y < min_y
{
t.position.y = min_y;
}
});
}
fn start_camera_transition(world: &mut World, camera_entity: EntityHandle, duration: f32)
{
let Some(camera) = world.cameras.get(camera_entity)
else
{
return;
};
let source_yaw = camera.yaw;
let source_pitch = camera.pitch;
let source_position = world
.transforms
.with(camera_entity, |t| t.position)
.unwrap_or(Vec3::ZERO);
world.camera_transitions.insert(
camera_entity,
CameraTransition {
source_position,
source_yaw,
source_pitch,
elapsed: 0.0,
duration,
},
);
}
pub fn camera_transition_system(world: &mut World, delta: f32)
{
let entities: Vec<EntityHandle> = world.camera_transitions.all();
for entity in entities
{
let finished = {
let Some(transition) = world.camera_transitions.get_mut(entity)
else
{
continue;
};
transition.elapsed += delta;
let t = (transition.elapsed / transition.duration).min(1.0);
let t = smoothstep(t);
let source_position = transition.source_position;
let source_yaw = transition.source_yaw;
let source_pitch = transition.source_pitch;
let finished = t >= 1.0;
world.transforms.with_mut(entity, |transform| {
transform.position = source_position.lerp(transform.position, t);
});
if let Some(camera) = world.cameras.get_mut(entity)
{
camera.yaw = lerp_angle(source_yaw, camera.yaw, t);
camera.pitch = source_pitch + (camera.pitch - source_pitch) * t;
}
if !finished
{
if let Some(transition) = world.camera_transitions.get_mut(entity)
{
let pos = world
.transforms
.with(entity, |tr| tr.position)
.unwrap_or(Vec3::ZERO);
let cam = world.cameras.get(entity);
transition.source_position = pos;
if let Some(cam) = cam
{
transition.source_yaw = cam.yaw;
transition.source_pitch = cam.pitch;
}
}
}
finished
};
if finished
{
world.camera_transitions.remove(entity);
}
}
}
fn smoothstep(t: f32) -> f32
{
t * t * (3.0 - 2.0 * t)
}
fn lerp_angle(from: f32, to: f32, t: f32) -> f32
{
let mut diff = to - from;
while diff > std::f32::consts::PI
{
diff -= std::f32::consts::TAU;
}
while diff < -std::f32::consts::PI
{
diff += std::f32::consts::TAU;
}
from + diff * t
}

View File

@@ -1,7 +1,21 @@
use glam::Vec3; use glam::Vec3;
use crate::components::intent::CameraTransitionIntent;
use crate::entity::EntityHandle;
use crate::world::World; use crate::world::World;
pub fn dialog_camera_transition_system(world: &mut World, camera_entity: EntityHandle)
{
let dialog_active = !world.bubble_tags.all().is_empty();
if dialog_active != world.was_dialog_active
{
world
.camera_transition_intents
.insert(camera_entity, CameraTransitionIntent { duration: 0.8 });
world.was_dialog_active = dialog_active;
}
}
const CAMERA_LAG: f32 = 4.0; const CAMERA_LAG: f32 = 4.0;
const VERTICAL_BIAS: f32 = 0.4; const VERTICAL_BIAS: f32 = 0.4;
const MIN_DISTANCE: f32 = 8.0; const MIN_DISTANCE: f32 = 8.0;
@@ -17,23 +31,20 @@ pub fn dialog_camera_system(world: &mut World, delta: f32)
let player_pos = world.player_position(); let player_pos = world.player_position();
let character_positions: Vec<Vec3> = world let bubble_positions: Vec<Vec3> = world
.bubble_tags .bubble_tags
.all() .all()
.iter() .iter()
.filter_map(|&bubble| { .filter_map(|&bubble| world.transforms.with(bubble, |t| t.position))
let char_entity = world.dialog_bubbles.with(bubble, |b| b.character_entity)?;
world.transforms.with(char_entity, |t| t.position)
})
.collect(); .collect();
if character_positions.is_empty() if bubble_positions.is_empty()
{ {
return; return;
} }
let all_positions: Vec<Vec3> = std::iter::once(player_pos) let all_positions: Vec<Vec3> = std::iter::once(player_pos)
.chain(character_positions.iter().copied()) .chain(bubble_positions.iter().copied())
.collect(); .collect();
let centroid = let centroid =
@@ -63,7 +74,7 @@ pub fn dialog_camera_system(world: &mut World, delta: f32)
t.position = smoothed; t.position = smoothed;
}); });
let look_target = centroid + Vec3::Y * 1.0; let look_target = centroid;
if let Some(camera) = world.cameras.get_mut(camera_entity) if let Some(camera) = world.cameras.get_mut(camera_entity)
{ {

View File

@@ -1,6 +1,7 @@
use glam::{Mat4, Vec3}; use glam::{Mat4, Vec3};
use crate::render::billboard::{BillboardDrawCall, BillboardVertex, BubbleUniforms}; use crate::render::billboard::{BillboardDrawCall, BillboardVertex, BubbleUniforms};
use crate::render::{with_font_atlas, TextVertex};
use crate::world::World; use crate::world::World;
const BUBBLE_WIDTH: f32 = 2.2; const BUBBLE_WIDTH: f32 = 2.2;
@@ -13,13 +14,18 @@ const HEIGHT_OFFSET: f32 = 8.2;
const FILL_COLOR: [f32; 4] = [0.05, 0.05, 0.05, 1.0]; const FILL_COLOR: [f32; 4] = [0.05, 0.05, 0.05, 1.0];
const BORDER_COLOR: [f32; 4] = [1.0, 1.0, 1.0, 1.0]; const BORDER_COLOR: [f32; 4] = [1.0, 1.0, 1.0, 1.0];
const CHAR_WORLD_HEIGHT: f32 = 0.36;
const TEXT_PADDING: f32 = 0.06;
const LINE_SPACING: f32 = 0.01;
pub fn dialog_bubble_render_system( pub fn dialog_bubble_render_system(
world: &World, world: &World,
camera_pos: Vec3, camera_pos: Vec3,
view_proj: Mat4, view_proj: Mat4,
) -> Vec<BillboardDrawCall> ) -> (Vec<BillboardDrawCall>, Vec<TextVertex>)
{ {
let mut calls = Vec::new(); let mut calls = Vec::new();
let mut all_text: Vec<TextVertex> = Vec::new();
for bubble_entity in world.bubble_tags.all() for bubble_entity in world.bubble_tags.all()
{ {
@@ -65,29 +71,16 @@ pub fn dialog_bubble_render_system(
let half_w = BUBBLE_WIDTH * 0.5; let half_w = BUBBLE_WIDTH * 0.5;
let total_down = body_half_h + tail_height; let total_down = body_half_h + tail_height;
// Corners: tl → tr → br → bl (CCW in clip space when billboard faces camera).
let tl = anchor - right * half_w + up * body_half_h; let tl = anchor - right * half_w + up * body_half_h;
let tr = anchor + right * half_w + up * body_half_h; let tr = anchor + right * half_w + up * body_half_h;
let br = anchor + right * half_w - up * total_down; let br = anchor + right * half_w - up * total_down;
let bl = anchor - right * half_w - up * total_down; let bl = anchor - right * half_w - up * total_down;
let vertices = [ let vertices = [
BillboardVertex { BillboardVertex { position: tl.to_array(), uv: [0.0, 0.0] },
position: tl.to_array(), BillboardVertex { position: tr.to_array(), uv: [1.0, 0.0] },
uv: [0.0, 0.0], BillboardVertex { position: br.to_array(), uv: [1.0, 1.0] },
}, BillboardVertex { position: bl.to_array(), uv: [0.0, 1.0] },
BillboardVertex {
position: tr.to_array(),
uv: [1.0, 0.0],
},
BillboardVertex {
position: br.to_array(),
uv: [1.0, 1.0],
},
BillboardVertex {
position: bl.to_array(),
uv: [0.0, 1.0],
},
]; ];
let uniforms = BubbleUniforms { let uniforms = BubbleUniforms {
@@ -103,7 +96,34 @@ pub fn dialog_bubble_render_system(
}; };
calls.push(BillboardDrawCall { vertices, uniforms }); calls.push(BillboardDrawCall { vertices, uniforms });
let text = match world
.dialog_bubbles
.with(bubble_entity, |b| b.current_text.clone())
{
Some(t) => t,
None => continue,
};
let border_world = BORDER_W * BUBBLE_WIDTH.min(BUBBLE_HEIGHT * BODY_FRAC);
let inner_half_w = BUBBLE_WIDTH * 0.5 - border_world - TEXT_PADDING;
let inner_top_y = body_half_h - border_world - TEXT_PADDING;
let text_verts = with_font_atlas(|atlas| {
atlas.build_bubble_text(
&text,
anchor,
right,
up,
inner_half_w,
inner_top_y,
CHAR_WORLD_HEIGHT,
LINE_SPACING,
)
});
all_text.extend(text_verts);
} }
calls (calls, all_text)
} }

View File

@@ -107,8 +107,6 @@ fn spawn_bubble(world: &mut World, character_entity: EntityHandle)
display_time, display_time,
}, },
); );
println!("Dialog bubble spawned for character {character_entity}");
} }
fn despawn_bubbles_for_character(world: &mut World, character_entity: EntityHandle) fn despawn_bubbles_for_character(world: &mut World, character_entity: EntityHandle)
@@ -136,7 +134,6 @@ fn despawn_bubbles_for_character(world: &mut World, character_entity: EntityHand
} }
world.despawn(bubble_entity); world.despawn(bubble_entity);
println!("Dialog bubble despawned for character {character_entity}");
} }
} }
@@ -216,11 +213,6 @@ fn tick_displaying_bubbles(world: &mut World, delta: f32)
world.dialog_bubbles.with_mut(bubble_entity, |b| { world.dialog_bubbles.with_mut(bubble_entity, |b| {
b.phase = DialogPhase::ProjectileInFlight { projectile_entity }; b.phase = DialogPhase::ProjectileInFlight { projectile_entity };
}); });
println!(
"Dialog projectile spawned, correct parry: {:?}",
correct_parry
);
} }
} }
} }
@@ -282,19 +274,11 @@ fn process_outcomes(world: &mut World)
timer: display_time, timer: display_time,
}; };
}); });
println!(
"Dialog advanced: '{}'",
world
.dialog_bubbles
.with(bubble_entity, |b| b.current_text.clone())
.unwrap_or_default()
);
} }
Some(None) => Some(None) =>
{ {
world.despawn(bubble_entity); world.despawn(bubble_entity);
println!("Dialog story finished");
} }
None => None =>

View File

@@ -5,6 +5,11 @@ use crate::world::World;
pub fn player_input_system(world: &mut World, input_state: &InputState) pub fn player_input_system(world: &mut World, input_state: &InputState)
{ {
if !world.camera_is_following()
{
return;
}
let Some((_, camera)) = world.active_camera() let Some((_, camera)) = world.active_camera()
else else
{ {

View File

@@ -1,12 +1,11 @@
pub mod camera; pub mod camera;
pub mod dialog;
pub mod dialog_camera; pub mod dialog_camera;
pub mod dialog_projectile; pub mod dialog_projectile;
pub mod dialog_render; pub mod dialog_render;
pub mod dialog_system;
pub mod follow; pub mod follow;
pub mod input; pub mod input;
pub mod physics_sync; pub mod physics_sync;
pub mod player_states;
pub mod render; pub mod render;
pub mod rotate; pub mod rotate;
pub mod snow; pub mod snow;
@@ -16,13 +15,13 @@ pub mod tree_dissolve;
pub mod trigger; pub mod trigger;
pub use camera::{ pub use camera::{
camera_follow_system, camera_input_system, camera_noclip_system, camera_view_matrix, camera_follow_system, camera_ground_clamp_system, camera_input_system, camera_intent_system,
start_camera_following, camera_noclip_system, camera_transition_system, camera_view_matrix,
}; };
pub use dialog::dialog_system; pub use dialog_camera::{dialog_camera_system, dialog_camera_transition_system};
pub use dialog_camera::dialog_camera_system;
pub use dialog_projectile::dialog_projectile_system; pub use dialog_projectile::dialog_projectile_system;
pub use dialog_render::dialog_bubble_render_system; pub use dialog_render::dialog_bubble_render_system;
pub use dialog_system::dialog_system;
pub use input::player_input_system; pub use input::player_input_system;
pub use physics_sync::physics_sync_system; pub use physics_sync::physics_sync_system;
pub use render::render_system; pub use render::render_system;

View File

@@ -1,12 +1,13 @@
use crate::world::World; use crate::world::World;
pub fn snow_system(world: &mut World, noclip: bool) pub fn snow_system(world: &mut World)
{ {
let camera_pos = world.active_camera_position(); let camera_pos = world.active_camera_position();
let player_pos = world.player_position(); let player_pos = world.player_position();
let is_following = world.camera_is_following();
if let Some(ref mut snow_layer) = world.snow_layer if let Some(ref mut snow_layer) = world.snow_layer
{ {
if !noclip if is_following
{ {
snow_layer.deform_at_position(player_pos, 1.5, 10.0); snow_layer.deform_at_position(player_pos, 1.5, 10.0);
} }

View File

@@ -5,6 +5,7 @@ use crate::components::dialog::{
}; };
use crate::components::dissolve::DissolveComponent; use crate::components::dissolve::DissolveComponent;
use crate::components::follow::FollowComponent; use crate::components::follow::FollowComponent;
use crate::components::intent::{CameraTransitionIntent, FollowPlayerIntent, StopFollowingIntent};
use crate::components::lights::spot::SpotlightComponent; use crate::components::lights::spot::SpotlightComponent;
use crate::components::player_states::{ use crate::components::player_states::{
FallingState, IdleState, JumpingState, LeapingState, RollingState, WalkingState, FallingState, IdleState, JumpingState, LeapingState, RollingState, WalkingState,
@@ -12,13 +13,13 @@ use crate::components::player_states::{
use crate::components::tree_instances::TreeInstancesComponent; use crate::components::tree_instances::TreeInstancesComponent;
use crate::components::trigger::{TriggerComponent, TriggerEvent}; use crate::components::trigger::{TriggerComponent, TriggerEvent};
use crate::components::{ use crate::components::{
CameraComponent, InputComponent, JumpComponent, MeshComponent, MovementComponent, CameraComponent, CameraTransition, InputComponent, JumpComponent, MeshComponent,
PhysicsComponent, RotateComponent, MovementComponent, PhysicsComponent, RotateComponent,
}; };
use crate::debug::DebugMode; use crate::debug::DebugMode;
use crate::entity::{EntityHandle, EntityManager}; use crate::entity::{EntityHandle, EntityManager};
use crate::render::snow::SnowLayer; use crate::render::snow::SnowLayer;
use crate::state::StateMachine; use crate::states::state::StateMachine;
pub use crate::utility::transform::Transform; pub use crate::utility::transform::Transform;
@@ -94,6 +95,7 @@ pub struct World
pub leaping_states: Storage<LeapingState>, pub leaping_states: Storage<LeapingState>,
pub rolling_states: Storage<RollingState>, pub rolling_states: Storage<RollingState>,
pub cameras: Storage<CameraComponent>, pub cameras: Storage<CameraComponent>,
pub camera_transitions: Storage<CameraTransition>,
pub spotlights: Storage<SpotlightComponent>, pub spotlights: Storage<SpotlightComponent>,
pub tree_tags: Storage<()>, pub tree_tags: Storage<()>,
pub dissolves: Storage<DissolveComponent>, pub dissolves: Storage<DissolveComponent>,
@@ -110,9 +112,15 @@ pub struct World
pub projectile_tags: Storage<()>, pub projectile_tags: Storage<()>,
pub dialog_outcomes: Vec<DialogOutcomeEvent>, pub dialog_outcomes: Vec<DialogOutcomeEvent>,
// --- intents (one-frame, consumed after processing) ---
pub follow_player_intents: Storage<FollowPlayerIntent>,
pub stop_following_intents: Storage<StopFollowingIntent>,
pub camera_transition_intents: Storage<CameraTransitionIntent>,
// --- singleton state (not per-entity) --- // --- singleton state (not per-entity) ---
pub snow_layer: Option<SnowLayer>, pub snow_layer: Option<SnowLayer>,
pub debug_mode: DebugMode, pub debug_mode: DebugMode,
pub was_dialog_active: bool,
} }
impl World impl World
@@ -136,6 +144,7 @@ impl World
leaping_states: Storage::new(), leaping_states: Storage::new(),
rolling_states: Storage::new(), rolling_states: Storage::new(),
cameras: Storage::new(), cameras: Storage::new(),
camera_transitions: Storage::new(),
spotlights: Storage::new(), spotlights: Storage::new(),
tree_tags: Storage::new(), tree_tags: Storage::new(),
dissolves: Storage::new(), dissolves: Storage::new(),
@@ -151,8 +160,12 @@ impl World
bubble_tags: Storage::new(), bubble_tags: Storage::new(),
projectile_tags: Storage::new(), projectile_tags: Storage::new(),
dialog_outcomes: Vec::new(), dialog_outcomes: Vec::new(),
follow_player_intents: Storage::new(),
stop_following_intents: Storage::new(),
camera_transition_intents: Storage::new(),
snow_layer: None, snow_layer: None,
debug_mode: DebugMode::default(), debug_mode: DebugMode::default(),
was_dialog_active: false,
} }
} }
@@ -178,6 +191,7 @@ impl World
self.leaping_states.remove(entity); self.leaping_states.remove(entity);
self.rolling_states.remove(entity); self.rolling_states.remove(entity);
self.cameras.remove(entity); self.cameras.remove(entity);
self.camera_transitions.remove(entity);
self.spotlights.remove(entity); self.spotlights.remove(entity);
self.tree_tags.remove(entity); self.tree_tags.remove(entity);
self.dissolves.remove(entity); self.dissolves.remove(entity);
@@ -191,6 +205,9 @@ impl World
self.dialog_projectiles.remove(entity); self.dialog_projectiles.remove(entity);
self.bubble_tags.remove(entity); self.bubble_tags.remove(entity);
self.projectile_tags.remove(entity); self.projectile_tags.remove(entity);
self.follow_player_intents.remove(entity);
self.stop_following_intents.remove(entity);
self.camera_transition_intents.remove(entity);
self.entities.despawn(entity); self.entities.despawn(entity);
} }
@@ -211,6 +228,13 @@ impl World
.unwrap_or(glam::Vec3::ZERO) .unwrap_or(glam::Vec3::ZERO)
} }
pub fn camera_is_following(&self) -> bool
{
self.active_camera()
.map(|(e, _)| self.follows.get(e).is_some())
.unwrap_or(false)
}
pub fn player_position(&self) -> glam::Vec3 pub fn player_position(&self) -> glam::Vec3
{ {
self.player_tags self.player_tags