Improved particles

master
Mark 2024-01-03 06:37:02 -08:00
parent a9e9b6a8ba
commit a892e4e763
Signed by: Mark
GPG Key ID: C6D63995FE72FD80
14 changed files with 202 additions and 113 deletions

View File

@ -1,6 +1,6 @@
[package]
name = "galactica-behavior"
description = "AI behaviors for Galaictica"
description = "AI behaviors for Galactica"
categories = { workspace = true }
keywords = { workspace = true }
version = { workspace = true }

View File

@ -26,7 +26,7 @@ impl ShipBehavior for Point {
s.controls.guns = false;
s.controls.thrust = false;
let (my_s, my_r) = physics.get_ship_body(&self.handle).unwrap();
let (my_s, my_r) = physics.get_ship_body(self.handle).unwrap();
let my_position = util::rigidbody_position(my_r);
let my_rotation = util::rigidbody_rotation(my_r);
let my_angvel = my_r.angvel();

View File

@ -10,29 +10,26 @@ use galactica_behavior::{behavior, ShipBehavior};
use galactica_constants;
use galactica_content as content;
use galactica_gameobject as object;
use galactica_render::{ObjectSprite, ParticleBuilder, UiSprite};
use galactica_render::{FrameState, ObjectSprite, ParticleBuilder, UiSprite};
use galactica_ui as ui;
use galactica_world::{util, ShipPhysicsHandle, World};
pub struct Game {
pub input: InputStatus,
pub last_update: Instant,
pub player: ShipPhysicsHandle,
input: InputStatus,
last_update: Instant,
player: ShipPhysicsHandle,
paused: bool,
pub time_scale: f32,
time_scale: f32,
start_instant: Instant,
camera: Camera,
system: object::System,
shipbehaviors: Vec<Box<dyn ShipBehavior>>,
playerbehavior: behavior::Player,
content: content::Content,
pub system: object::System,
pub camera: Camera,
world: World,
pub start_instant: Instant,
// TODO: clean this up
pub new_particles: Vec<ParticleBuilder>,
new_particles: Vec<ParticleBuilder>,
}
impl Game {
@ -112,6 +109,10 @@ impl Game {
}
}
pub fn set_camera_aspect(&mut self, v: f32) {
self.camera.aspect = v
}
pub fn process_key(&mut self, state: &ElementState, key: &VirtualKeyCode) {
self.input.process_key(state, key)
}
@ -173,6 +174,17 @@ impl Game {
self.last_update = Instant::now();
}
pub fn get_frame_state(&mut self) -> FrameState {
FrameState {
camera_pos: self.camera.pos,
camera_zoom: self.camera.zoom,
object_sprites: self.get_object_sprites(),
ui_sprites: self.get_ui_sprites(),
new_particles: &mut self.new_particles,
current_time: self.start_instant.elapsed().as_secs_f32(),
}
}
pub fn get_object_sprites(&self) -> Vec<ObjectSprite> {
let mut sprites: Vec<ObjectSprite> = Vec::new();
@ -195,7 +207,7 @@ impl Game {
pub fn get_ui_sprites(&self) -> Vec<UiSprite> {
return ui::build_radar(
&self.content,
&self.player,
self.player,
&self.world,
&self.system,
self.camera.zoom,

View File

@ -27,22 +27,12 @@ fn main() -> Result<()> {
let mut game = game::Game::new(content);
gpu.update_starfield_buffer();
game.camera.aspect = gpu.window_size.width as f32 / gpu.window_size.height as f32;
game.set_camera_aspect(gpu.window_size.width as f32 / gpu.window_size.height as f32);
event_loop.run(move |event, _, control_flow| {
match event {
Event::RedrawRequested(window_id) if window_id == gpu.window().id() => {
match gpu.render(
game.camera.pos,
game.camera.zoom,
&game.get_object_sprites(),
&game.get_ui_sprites(),
// TODO: clean this up, single game data struct
// Game in another crate?
// Shipbehavior needs game state too...
&mut game.new_particles,
game.start_instant,
) {
match gpu.render(game.get_frame_state()) {
Ok(_) => {}
Err(wgpu::SurfaceError::Lost) => gpu.resize(),
Err(wgpu::SurfaceError::OutOfMemory) => *control_flow = ControlFlow::Exit,
@ -81,13 +71,15 @@ fn main() -> Result<()> {
}
WindowEvent::Resized(_) => {
gpu.resize();
game.camera.aspect =
gpu.window_size.width as f32 / gpu.window_size.height as f32;
game.set_camera_aspect(
gpu.window_size.width as f32 / gpu.window_size.height as f32,
);
}
WindowEvent::ScaleFactorChanged { .. } => {
gpu.resize();
game.camera.aspect =
gpu.window_size.width as f32 / gpu.window_size.height as f32;
game.set_camera_aspect(
gpu.window_size.width as f32 / gpu.window_size.height as f32,
);
}
_ => {}
},

View File

@ -72,8 +72,7 @@ impl OutfitStatSum {
#[derive(Debug)]
pub struct OutfitSet {
/// The total sum of the stats this set of outfits provides
/// TODO: this shouldn't be pub
pub stats: OutfitStatSum,
stats: OutfitStatSum,
//pub total_space: content::OutfitSpace,
available_space: content::OutfitSpace,
@ -110,6 +109,10 @@ impl<'a> OutfitSet {
}
}
pub fn stat_sum(&self) -> &OutfitStatSum {
&self.stats
}
/// Add an outfit to this ship.
/// Returns true on success, and false on failure
/// TODO: failure reason enum

View File

@ -1,8 +1,12 @@
struct InstanceInput {
@location(2) position: vec3<f32>,
@location(3) size: f32,
@location(4) expires: f32,
@location(5) texture_index: u32,
@location(2) position: vec2<f32>,
@location(3) velocity: vec2<f32>,
@location(4) rotation_0: vec2<f32>,
@location(5) rotation_1: vec2<f32>,
@location(6) size: f32,
@location(7) created: f32,
@location(8) expires: f32,
@location(9) texture_index: u32,
};
struct VertexInput {
@ -55,6 +59,9 @@ fn vertex_main(
return out;
}
let age = instance.created - global.current_time.x;
let rotation = mat2x2(instance.rotation_0, instance.rotation_1);
var scale: f32 = instance.size / global.camera_zoom.x;
var pos: vec2<f32> = vec2(vertex.position.x, vertex.position.y);
@ -62,14 +69,20 @@ fn vertex_main(
1.0 * scale / global.window_aspect.x,
scale
);
pos = rotation * pos;
var ipos: vec2<f32> = (
vec2(instance.position.x, instance.position.y)
+ (instance.velocity * age)
- global.camera_position
);
var ipos: vec2<f32> = vec2(instance.position.x, instance.position.y) - global.camera_position;
pos = pos + vec2<f32>(
ipos.x / (global.camera_zoom.x/2.0) / global.window_aspect.x,
ipos.y / (global.camera_zoom.x/2.0)
);
out.position = vec4<f32>(pos, 0.0, 1.0) * instance.position.z;
out.position = vec4<f32>(pos, 0.0, 1.0);
return out;
}

View File

@ -0,0 +1,26 @@
use cgmath::Point2;
use crate::{ObjectSprite, ParticleBuilder, UiSprite};
/// Bundles parameters passed to a single call to GPUState::render
pub struct FrameState<'a> {
/// Camera position, in world units
pub camera_pos: Point2<f32>,
/// Height of screen, in world units
pub camera_zoom: f32,
/// World object sprites
pub object_sprites: Vec<ObjectSprite>,
/// UI sprites
pub ui_sprites: Vec<UiSprite>,
/// Particles to create during this frame.
/// this array will be cleared.
pub new_particles: &'a mut Vec<ParticleBuilder>,
// TODO: handle overflow
/// The current time, in seconds
pub current_time: f32,
}

View File

@ -1,8 +1,8 @@
use anyhow::Result;
use bytemuck;
use cgmath::{Deg, EuclideanSpace, Matrix4, Point2, Vector3};
use cgmath::{Deg, EuclideanSpace, Matrix2, Matrix4, Point2, Vector3};
use galactica_constants;
use std::{iter, rc::Rc, time::Instant};
use std::{iter, rc::Rc};
use wgpu;
use winit::{self, dpi::LogicalSize, window::Window};
@ -10,7 +10,7 @@ use crate::{
content,
globaldata::{GlobalData, GlobalDataContent},
pipeline::PipelineBuilder,
sprite::{ObjectSubSprite, ParticleBuilder},
sprite::ObjectSubSprite,
starfield::Starfield,
texturearray::TextureArray,
vertexbuffer::{
@ -18,7 +18,7 @@ use crate::{
types::{ObjectInstance, ParticleInstance, StarfieldInstance, TexturedVertex, UiInstance},
BufferObject, VertexBuffer,
},
ObjectSprite, UiSprite, OPENGL_TO_WGPU_MATRIX,
FrameState, ObjectSprite, UiSprite, OPENGL_TO_WGPU_MATRIX,
};
/// A high-level GPU wrapper. Consumes game state,
@ -456,28 +456,22 @@ impl GPUState {
/// Make an instance for all the game's sprites
/// (Objects and UI)
/// This will Will panic if any X_SPRITE_INSTANCE_LIMIT is exceeded.
fn update_sprite_instances(
&self,
camera_zoom: f32,
camera_pos: Point2<f32>,
objects: &Vec<ObjectSprite>,
ui: &Vec<UiSprite>,
) -> (usize, usize) {
fn update_sprite_instances(&self, framestate: FrameState) -> (usize, usize) {
let mut object_instances: Vec<ObjectInstance> = Vec::new();
// Game coordinates (relative to camera) of ne and sw corners of screen.
// Used to skip off-screen sprites.
let clip_ne = Point2::from((-self.window_aspect, 1.0)) * camera_zoom;
let clip_sw = Point2::from((self.window_aspect, -1.0)) * camera_zoom;
let clip_ne = Point2::from((-self.window_aspect, 1.0)) * framestate.camera_zoom;
let clip_sw = Point2::from((self.window_aspect, -1.0)) * framestate.camera_zoom;
for s in objects {
for s in framestate.object_sprites {
self.push_object_sprite(
camera_zoom,
camera_pos,
framestate.camera_zoom,
framestate.camera_pos,
&mut object_instances,
clip_ne,
clip_sw,
s,
&s,
);
}
@ -495,8 +489,8 @@ impl GPUState {
let mut ui_instances: Vec<UiInstance> = Vec::new();
for s in ui {
self.push_ui_sprite(&mut ui_instances, s);
for s in framestate.ui_sprites {
self.push_ui_sprite(&mut ui_instances, &s);
}
if ui_instances.len() as u64 > galactica_constants::UI_SPRITE_INSTANCE_LIMIT {
@ -525,17 +519,7 @@ impl GPUState {
}
/// Main render function. Draws sprites on a window.
pub fn render(
&mut self,
camera_pos: Point2<f32>,
camera_zoom: f32,
// TODO: clean this up, pass one struct
object_sprites: &Vec<ObjectSprite>,
ui_sprites: &Vec<UiSprite>,
new_particles: &mut Vec<ParticleBuilder>,
start_instant: Instant,
) -> Result<(), wgpu::SurfaceError> {
pub fn render(&mut self, framestate: FrameState) -> Result<(), wgpu::SurfaceError> {
let output = self.surface.get_current_texture()?;
let view = output
.texture
@ -568,16 +552,13 @@ impl GPUState {
timestamp_writes: None,
});
// TODO: handle overflow
let time_now = start_instant.elapsed().as_secs_f32();
// Update global values
self.queue.write_buffer(
&self.global_data.buffer,
0,
bytemuck::cast_slice(&[GlobalDataContent {
camera_position: camera_pos.into(),
camera_zoom: [camera_zoom, 0.0],
camera_position: framestate.camera_pos.into(),
camera_zoom: [framestate.camera_zoom, 0.0],
camera_zoom_limits: [galactica_constants::ZOOM_MIN, galactica_constants::ZOOM_MAX],
window_size: [
self.window_size.width as f32,
@ -590,20 +571,24 @@ impl GPUState {
galactica_constants::STARFIELD_SIZE_MIN,
galactica_constants::STARFIELD_SIZE_MAX,
],
current_time: [time_now, 0.0],
current_time: [framestate.current_time, 0.0],
}]),
);
for i in new_particles.iter() {
// Write all new particles to GPU buffer
for i in framestate.new_particles.iter() {
let texture = self.texture_array.get_texture(i.texture);
self.queue.write_buffer(
&self.vertex_buffers.particle.instances,
ParticleInstance::SIZE * self.vertex_buffers.particle_array_head,
bytemuck::cast_slice(&[ParticleInstance {
position: [i.pos.x, i.pos.y, 1.0],
position: [i.pos.x, i.pos.y],
velocity: i.velocity.into(),
rotation: Matrix2::from_angle(i.angle).into(),
size: i.size,
texture_index: texture.index,
expires: time_now + i.lifetime,
created: framestate.current_time,
expires: framestate.current_time + i.lifetime,
}]),
);
self.vertex_buffers.particle_array_head += 1;
@ -613,11 +598,10 @@ impl GPUState {
self.vertex_buffers.particle_array_head = 0;
}
}
new_particles.clear();
framestate.new_particles.clear();
// Create sprite instances
let (n_object, n_ui) =
self.update_sprite_instances(camera_zoom, camera_pos, object_sprites, ui_sprites);
let (n_object, n_ui) = self.update_sprite_instances(framestate);
// These should match the indices in each shader,
// and should each have a corresponding bind group layout.

View File

@ -7,6 +7,7 @@
//! and the only one external code should interact with.
//! (Excluding data structs, like [`ObjectSprite`])
mod framestate;
mod globaldata;
mod gpustate;
mod pipeline;
@ -15,6 +16,7 @@ mod starfield;
mod texturearray;
mod vertexbuffer;
pub use framestate::FrameState;
use galactica_content as content;
pub use gpustate::GPUState;
pub use sprite::{AnchoredUiPosition, ObjectSprite, ObjectSubSprite, ParticleBuilder, UiSprite};

View File

@ -1,14 +1,19 @@
use crate::content;
use cgmath::{Deg, Point2, Point3};
use cgmath::{Deg, Point2, Point3, Vector2};
/// Instructions to create a new particle
pub struct ParticleBuilder {
/// The texture to use for this particle
pub texture: content::TextureHandle,
// TODO: rotation, velocity
/// This object's center, in world coordinates.
pub pos: Point3<f32>,
pub pos: Point2<f32>,
/// This particle's velocity, in world coordinates
pub velocity: Vector2<f32>,
/// This particle's angle, in world coordinates
pub angle: Deg<f32>,
/// This particle's lifetime, in seconds
pub lifetime: f32,

View File

@ -200,16 +200,25 @@ impl BufferObject for UiInstance {
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
pub struct ParticleInstance {
/// World position of this particle
pub position: [f32; 3],
pub position: [f32; 2],
/// Velocity of this sprite, in world coordinates
pub velocity: [f32; 2],
/// Rotation matrix for this sprite, in world coordinates
pub rotation: [[f32; 2]; 2],
// TODO: docs: particle frames must all have the same size
// TODO: is transparency trimmed? That's not ideal for animated particles!
/// The height of this particle, in world units
pub size: f32,
// TODO: rotation, velocity vector
// TODO: animated sprites
// TODO: texture aspect ratio
/// The time, in seconds, at which this particle was created.
/// Time is kept by a variable in the global uniform.
pub created: f32,
/// The time, in seconds, at which this particle expires.
/// Time is kept by a variable in the global uniform.
pub expires: f32,
@ -228,24 +237,47 @@ impl BufferObject for ParticleInstance {
wgpu::VertexAttribute {
offset: 0,
shader_location: 2,
format: wgpu::VertexFormat::Float32x3,
format: wgpu::VertexFormat::Float32x2,
},
// Velocity
wgpu::VertexAttribute {
offset: mem::size_of::<[f32; 2]>() as wgpu::BufferAddress,
shader_location: 3,
format: wgpu::VertexFormat::Float32x2,
},
// Rotation
wgpu::VertexAttribute {
offset: mem::size_of::<[f32; 4]>() as wgpu::BufferAddress,
shader_location: 4,
format: wgpu::VertexFormat::Float32x2,
},
wgpu::VertexAttribute {
offset: mem::size_of::<[f32; 6]>() as wgpu::BufferAddress,
shader_location: 5,
format: wgpu::VertexFormat::Float32x2,
},
// Size
wgpu::VertexAttribute {
offset: mem::size_of::<[f32; 3]>() as wgpu::BufferAddress,
shader_location: 3,
offset: mem::size_of::<[f32; 8]>() as wgpu::BufferAddress,
shader_location: 6,
format: wgpu::VertexFormat::Float32,
},
// Created
wgpu::VertexAttribute {
offset: mem::size_of::<[f32; 9]>() as wgpu::BufferAddress,
shader_location: 7,
format: wgpu::VertexFormat::Float32,
},
// Expires
wgpu::VertexAttribute {
offset: mem::size_of::<[f32; 4]>() as wgpu::BufferAddress,
shader_location: 4,
offset: mem::size_of::<[f32; 10]>() as wgpu::BufferAddress,
shader_location: 8,
format: wgpu::VertexFormat::Float32,
},
// Texture
wgpu::VertexAttribute {
offset: mem::size_of::<[f32; 5]>() as wgpu::BufferAddress,
shader_location: 5,
offset: mem::size_of::<[f32; 11]>() as wgpu::BufferAddress,
shader_location: 9,
format: wgpu::VertexFormat::Uint32,
},
],

View File

@ -4,10 +4,10 @@ use galactica_gameobject as object;
use galactica_render::{AnchoredUiPosition, UiSprite};
use galactica_world::{util, ShipPhysicsHandle, World};
// TODO: camera as one unit
// TODO: args as one unit
pub fn build_radar(
ct: &content::Content,
player: &ShipPhysicsHandle,
player: ShipPhysicsHandle,
physics: &World,
system: &object::System,
camera_zoom: f32,

View File

@ -27,7 +27,6 @@ impl ShipControls {
}
/// A ship instance in the physics system
/// TODO: Decouple ship data from physics
pub struct ShipWorldObject {
/// TODO
pub physics_handle: ShipPhysicsHandle,
@ -56,17 +55,18 @@ impl ShipWorldObject {
if self.controls.thrust {
r.apply_impulse(
vector![engine_force.x, engine_force.y] * self.ship.outfits.stats.engine_thrust,
vector![engine_force.x, engine_force.y]
* self.ship.outfits.stat_sum().engine_thrust,
true,
);
}
if self.controls.right {
r.apply_torque_impulse(self.ship.outfits.stats.steer_power * -100.0 * t, true);
r.apply_torque_impulse(self.ship.outfits.stat_sum().steer_power * -100.0 * t, true);
}
if self.controls.left {
r.apply_torque_impulse(self.ship.outfits.stats.steer_power * 100.0 * t, true);
r.apply_torque_impulse(self.ship.outfits.stat_sum().steer_power * 100.0 * t, true);
}
for i in self.ship.outfits.iter_guns() {

View File

@ -1,4 +1,4 @@
use cgmath::{Deg, EuclideanSpace, InnerSpace, Matrix2, Point2, Point3, Rad, Vector2};
use cgmath::{Deg, EuclideanSpace, InnerSpace, Matrix2, Point2, Rad, Vector2};
use crossbeam::channel::Receiver;
use nalgebra::vector;
use rand::Rng;
@ -57,12 +57,12 @@ impl<'a> World {
/// Add a projectile fired from a ship
fn add_projectiles(
&mut self,
s: &ShipPhysicsHandle,
s: ShipPhysicsHandle,
p: Vec<(object::Projectile, content::GunPoint)>,
) {
let mut rng = rand::thread_rng();
for (projectile, point) in p {
let r = self.get_ship_body(&s).unwrap().1;
let r = self.get_ship_body(s).unwrap().1;
let ship_pos = util::rigidbody_position(r);
let ship_rot = util::rigidbody_rotation(r);
@ -187,7 +187,7 @@ impl<'a> World {
}
}
for (s, p) in projectiles {
self.add_projectiles(&s, p);
self.add_projectiles(s, p);
}
for s in to_remove {
self.remove_ship(s);
@ -211,18 +211,38 @@ impl<'a> World {
};
if let Some(p) = self.projectiles.get(a) {
if let Some(s) = self.ships.get_mut(b) {
let hit = s.ship.handle_projectile_collision(ct, &p.projectile);
let hit = if let Some(s) = self.ships.get_mut(b) {
s.ship.handle_projectile_collision(ct, &p.projectile)
} else {
false
};
// Stupid re-borrow trick.
// We can't have s be mutable inside this block.
if let Some(s) = self.ships.get(b) {
if hit {
let r = self.get_rigid_body(p.rigid_body);
let pos = util::rigidbody_position(r);
let pr = self.get_rigid_body(p.rigid_body);
let pos = util::rigidbody_position(pr);
let angle: Deg<f32> = util::rigidbody_rotation(pr)
.angle(Vector2 { x: 0.0, y: 1.0 })
.into();
// Match target ship velocity, so impact particles are "sticky".
// Particles will fly off if the ship is spinning fast, but I
// haven't found a good way to fix that.
let (_, sr) = self.get_ship_body(s.physics_handle).unwrap();
let velocity =
sr.velocity_at_point(&nalgebra::Point2::new(pos.x, pos.y));
let velocity = Vector2 {
x: velocity.x,
y: velocity.y,
};
particles.push(ParticleBuilder {
texture: ct.get_texture_handle("particle::blaster"),
pos: Point3 {
x: pos.x,
y: pos.y,
z: 1.0, // TODO:remove z coordinate
},
pos: Point2 { x: pos.x, y: pos.y },
velocity: -velocity,
angle: -angle,
lifetime: 0.1,
size: 10.0,
});
@ -259,7 +279,7 @@ impl<'a> World {
/// Get a ship and its rigidbody from a handle
pub fn get_ship_body(
&self,
s: &ShipPhysicsHandle,
s: ShipPhysicsHandle,
) -> Option<(&objects::ShipWorldObject, &RigidBody)> {
// TODO: handle dead handles
Some((self.ships.get(&s.1)?, self.wrapper.rigid_body_set.get(s.0)?))