euv_core/game/engine3d/physics/
impl.rs1use super::*;
2
3impl RigidBody3D {
5 #[must_use]
17 pub fn dynamic_box(position: Vec3, half_extents: Vec3, mass: f32) -> Self {
18 Self {
19 position,
20 velocity: Vec3::zero(),
21 half_extents,
22 inv_mass: 1.0 / mass.max(0.01),
23 restitution: 0.35,
24 linear_damping: 0.04,
25 grounded: false,
26 }
27 }
28
29 #[must_use]
40 pub fn static_box(position: Vec3, half_extents: Vec3) -> Self {
41 Self {
42 position,
43 velocity: Vec3::zero(),
44 half_extents,
45 inv_mass: 0.0,
46 restitution: 0.25,
47 linear_damping: 0.0,
48 grounded: true,
49 }
50 }
51
52 #[must_use]
62 pub fn world_aabb(&self) -> Aabb3D {
63 let p: Vec3 = self.get_position();
64 let h: Vec3 = self.get_half_extents();
65 Aabb3D::new(p.sub(h), p.add(h))
66 }
67
68 pub fn apply_impulse(&mut self, impulse: Vec3) {
75 let inv_m: f32 = self.get_inv_mass();
76 if inv_m > 0.0 {
77 let next_v: Vec3 = self.get_velocity().add(impulse.scale(inv_m));
78 self.set_velocity(next_v);
79 }
80 }
81}
82
83impl Default for PhysicsWorld3D {
85 fn default() -> Self {
91 Self {
92 gravity: Vec3::new(0.0, -9.81, 0.0),
93 ground_y: 0.0,
94 bodies: Vec::new(),
95 hash_heads: Vec::new(),
96 hash_next: Vec::new(),
97 hash_body: Vec::new(),
98 touched_buckets: Vec::new(),
99 pair_scratch: Vec::new(),
100 }
101 }
102}
103
104impl PhysicsWorld3D {
106 #[inline(always)]
119 #[must_use]
120 fn hash_cell(cx: i32, cy: i32, cz: i32, mask: usize) -> usize {
121 let h: u32 = (cx.wrapping_mul(73_856_093) as u32)
122 ^ (cy.wrapping_mul(19_349_663) as u32)
123 ^ (cz.wrapping_mul(83_492_791) as u32);
124 (h as usize) & mask
125 }
126
127 #[inline(always)]
139 fn resolve_body_pair(bodies: &mut [RigidBody3D], i: usize, j: usize) -> bool {
140 let a: RigidBody3D = bodies[i];
141 let b: RigidBody3D = bodies[j];
142 let inv_sum: f32 = a.get_inv_mass() + b.get_inv_mass();
143 if inv_sum <= 0.0 {
144 return false;
145 }
146 let delta: Vec3 = b.get_position().sub(a.get_position());
147 let ox: f32 =
148 a.get_half_extents().get_x() + b.get_half_extents().get_x() - delta.get_x().abs();
149 let oy: f32 =
150 a.get_half_extents().get_y() + b.get_half_extents().get_y() - delta.get_y().abs();
151 let oz: f32 =
152 a.get_half_extents().get_z() + b.get_half_extents().get_z() - delta.get_z().abs();
153 if ox <= 0.0 || oy <= 0.0 || oz <= 0.0 {
154 return false;
155 }
156 let (normal, pen): (Vec3, f32) = if ox <= oy && ox <= oz {
157 let s: f32 = if delta.get_x() < 0.0 { -1.0 } else { 1.0 };
158 (Vec3::new(s, 0.0, 0.0), ox)
159 } else if oy <= oz {
160 let s: f32 = if delta.get_y() < 0.0 { -1.0 } else { 1.0 };
161 (Vec3::new(0.0, s, 0.0), oy)
162 } else {
163 let s: f32 = if delta.get_z() < 0.0 { -1.0 } else { 1.0 };
164 (Vec3::new(0.0, 0.0, s), oz)
165 };
166 let corr: Vec3 = normal.scale(pen / inv_sum);
167 let a_pos: Vec3 = a.get_position().sub(corr.scale(a.get_inv_mass()));
168 let b_pos: Vec3 = b.get_position().add(corr.scale(b.get_inv_mass()));
169 let rel_v: Vec3 = b.get_velocity().sub(a.get_velocity());
170 let vn: f32 = rel_v.dot(normal);
171 let mut a_vel: Vec3 = a.get_velocity();
172 let mut b_vel: Vec3 = b.get_velocity();
173 if vn < 0.0 {
174 let rest: f32 = a.get_restitution().min(b.get_restitution());
175 let j_imp: f32 = -(1.0 + rest) * vn / inv_sum;
176 let imp: Vec3 = normal.scale(j_imp);
177 a_vel = a_vel.sub(imp.scale(a.get_inv_mass()));
178 b_vel = b_vel.add(imp.scale(b.get_inv_mass()));
179 }
180 bodies[i].set_position(a_pos);
181 bodies[i].set_velocity(a_vel);
182 bodies[j].set_position(b_pos);
183 bodies[j].set_velocity(b_vel);
184 true
185 }
186
187 pub fn add_body(&mut self, body: RigidBody3D) -> usize {
198 let idx: usize = self.get_bodies().len();
199 self.get_mut_bodies().push(body);
200 idx
201 }
202
203 pub fn step(&mut self, dt: f32) -> usize {
214 let step_dt: f32 = dt.clamp(0.0, 0.1);
215 let gravity: Vec3 = self.get_gravity();
216 let ground_y: f32 = self.get_ground_y();
217 let mut collisions: usize = 0;
218 let mut max_extent: f32 = 0.5;
219 let Self {
220 bodies,
221 hash_heads,
222 hash_next,
223 hash_body,
224 touched_buckets,
225 pair_scratch,
226 ..
227 } = self;
228 for body in bodies.iter_mut() {
229 let h: Vec3 = body.get_half_extents();
230 let extent: f32 = h.get_x().max(h.get_y()).max(h.get_z());
231 if extent > max_extent {
232 max_extent = extent;
233 }
234 let inv_m: f32 = body.get_inv_mass();
235 if inv_m <= 0.0 {
236 continue;
237 }
238 let damp: f32 = (1.0 - body.get_linear_damping() * step_dt).clamp(0.0, 1.0);
239 let mut vel: Vec3 = body.get_velocity().add(gravity.scale(step_dt)).scale(damp);
240 let mut pos: Vec3 = body.get_position().add(vel.scale(step_dt));
241 let min_y: f32 = ground_y + h.get_y();
242 let mut grounded: bool = false;
243 if pos.get_y() <= min_y {
244 pos.set_y(min_y);
245 if vel.get_y() < 0.0 {
246 vel.set_y(-vel.get_y() * body.get_restitution());
247 if vel.get_y().abs() < 0.25 {
248 vel.set_y(0.0);
249 }
250 vel.set_x(vel.get_x() * 0.92);
251 vel.set_z(vel.get_z() * 0.92);
252 collisions += 1;
253 }
254 grounded = true;
255 }
256 body.set_position(pos);
257 body.set_velocity(vel);
258 body.set_grounded(grounded);
259 }
260 let count: usize = bodies.len();
261 if count <= 1 {
262 return collisions;
263 }
264 if count <= 16 {
265 for i in 0..count {
266 for j in (i + 1)..count {
267 if Self::resolve_body_pair(bodies.as_mut_slice(), i, j) {
268 collisions += 1;
269 }
270 }
271 }
272 return collisions;
273 }
274 let target_buckets: usize = (count * 4).next_power_of_two().clamp(256, 16_384);
275 if hash_heads.len() != target_buckets {
276 hash_heads.clear();
277 hash_heads.resize(target_buckets, u32::MAX);
278 touched_buckets.clear();
279 } else {
280 for &b in touched_buckets.iter() {
281 hash_heads[b] = u32::MAX;
282 }
283 touched_buckets.clear();
284 }
285 hash_next.clear();
286 hash_body.clear();
287 pair_scratch.clear();
288 let cell_size: f32 = (max_extent * 2.5).max(1.0);
289 let inv_cell: f32 = 1.0 / cell_size;
290 let mask: usize = target_buckets - 1;
291 for (idx, body) in bodies.iter().enumerate() {
292 let p: Vec3 = body.get_position();
293 let h: Vec3 = body.get_half_extents();
294 let min_cx: i32 = ((p.get_x() - h.get_x()) * inv_cell).floor() as i32;
295 let max_cx: i32 = ((p.get_x() + h.get_x()) * inv_cell).floor() as i32;
296 let min_cy: i32 = ((p.get_y() - h.get_y()) * inv_cell).floor() as i32;
297 let max_cy: i32 = ((p.get_y() + h.get_y()) * inv_cell).floor() as i32;
298 let min_cz: i32 = ((p.get_z() - h.get_z()) * inv_cell).floor() as i32;
299 let max_cz: i32 = ((p.get_z() + h.get_z()) * inv_cell).floor() as i32;
300 for cx in min_cx..=max_cx {
301 for cy in min_cy..=max_cy {
302 for cz in min_cz..=max_cz {
303 let bucket: usize = Self::hash_cell(cx, cy, cz, mask);
304 let mut cur: u32 = hash_heads[bucket];
305 if cur == u32::MAX {
306 touched_buckets.push(bucket);
307 } else {
308 while cur != u32::MAX {
309 let other: usize = hash_body[cur as usize] as usize;
310 if other != idx {
311 let pair: (usize, usize) = if other < idx {
312 (other, idx)
313 } else {
314 (idx, other)
315 };
316 pair_scratch.push(pair);
317 }
318 cur = hash_next[cur as usize];
319 }
320 }
321 let entry: u32 = hash_body.len() as u32;
322 hash_body.push(idx as u32);
323 hash_next.push(hash_heads[bucket]);
324 hash_heads[bucket] = entry;
325 }
326 }
327 }
328 }
329 pair_scratch.sort_unstable();
330 pair_scratch.dedup();
331 for &(i, j) in pair_scratch.iter() {
332 if Self::resolve_body_pair(bodies.as_mut_slice(), i, j) {
333 collisions += 1;
334 }
335 }
336 collisions
337 }
338
339 #[must_use]
351 pub fn raycast(&self, ray: &Ray3D, max_distance: f32) -> Option<RayHitPhysics3D> {
352 let mut best: Option<RayHitPhysics3D> = None;
353 let mut best_t: f32 = max_distance.max(0.0);
354 for (idx, body) in self.get_bodies().iter().enumerate() {
355 let aabb: Aabb3D = body.world_aabb();
356 let t: f32 =
357 aabb.intersect_ray_near(ray.get_origin(), ray.get_inv_direction(), 0.001, best_t);
358 if t.is_finite() && t < best_t {
359 best_t = t;
360 let pt: Vec3 = ray.get_origin().add(ray.get_direction().scale(t));
361 best = Some(RayHitPhysics3D::new(idx, t, pt));
362 }
363 }
364 best
365 }
366}