ira 0.3.0

A general-purpose, code-first game engine.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
use std::ops;

use glam::Vec3;
use rapier3d::{
	data::{Arena, Index},
	dynamics::{
		CCDSolver, ImpulseJointSet, IntegrationParameters, IslandManager, MultibodyJointSet,
		RigidBodyBuilder, RigidBodyHandle, RigidBodySet,
	},
	geometry::{ColliderBuilder, ColliderHandle, ColliderSet, DefaultBroadPhase, NarrowPhase},
	pipeline::PhysicsPipeline,
};

use crate::{
	game::Context,
	packet::{CreateInstance, Packet, UpdateInstance},
	server::InstanceId,
	Body, GpuDrum, GpuModel, Instance, InstanceBuilder,
};

#[cfg(feature = "client")]
use crate::render::model::GpuInstance;

#[derive(Debug, Clone, Copy)]
pub struct BoundingBox {
	pub min: Vec3,
	pub max: Vec3,
}

impl BoundingBox {
	pub fn to_cuboid(&self, scale: Vec3) -> ColliderBuilder {
		ColliderBuilder::cuboid(
			(self.max.x - self.min.x) * 0.5 * scale.x,
			(self.max.y - self.min.y) * 0.5 * scale.y,
			(self.max.z - self.min.z) * 0.5 * scale.z,
		)
	}
}

pub struct PhysicsState {
	pub pipeline: PhysicsPipeline,

	pub integration: IntegrationParameters,
	pub islands: IslandManager,
	pub broad_phase: DefaultBroadPhase,
	pub narrow_phase: NarrowPhase,

	pub impulse_joints: ImpulseJointSet,
	pub multibody_joints: MultibodyJointSet,

	pub ccd_solver: CCDSolver,

	pub rigid_bodies: RigidBodySet,
	pub colliders: ColliderSet,

	pub(crate) steps_since_last_update: u32,
}

impl Default for PhysicsState {
	fn default() -> Self {
		Self {
			pipeline: PhysicsPipeline::new(),
			integration: IntegrationParameters::default(),
			islands: IslandManager::new(),
			broad_phase: DefaultBroadPhase::new(),
			narrow_phase: NarrowPhase::new(),
			impulse_joints: ImpulseJointSet::new(),
			multibody_joints: MultibodyJointSet::new(),
			ccd_solver: CCDSolver::new(),
			rigid_bodies: RigidBodySet::new(),
			colliders: ColliderSet::new(),
			steps_since_last_update: 0,
		}
	}
}

impl PhysicsState {
	pub const GRAVITY: Vec3 = Vec3::new(0.0, -9.81, 0.0);
	pub const TICKS_PER_UPDATE: u32 = 10;

	pub fn step(&mut self) {
		self.pipeline.step(
			&nalgebra::Vector3::from(Self::GRAVITY),
			&self.integration,
			&mut self.islands,
			&mut self.broad_phase,
			&mut self.narrow_phase,
			&mut self.rigid_bodies,
			&mut self.colliders,
			&mut self.impulse_joints,
			&mut self.multibody_joints,
			&mut self.ccd_solver,
			None,
			&(),
			&(),
		);
	}

	/// Adds a new instance to the physics world.
	///
	/// Modifies the provided instance to include the rigid body and collider handles.
	fn add_instance(
		&mut self,
		instance: InstanceBuilder,
		model_id: u32,
		instance_id: u32,
	) -> Instance {
		let mut new_instance = Instance {
			scale: instance.scale,
			collider: None,
			body: Body::Static {
				position: instance.position,
				rotation: instance.rotation,
			},
			model_id,
			instance_id,
		};

		if let Some(body) = instance.rigidbody {
			let body = self.rigid_bodies.insert(body);

			if let Some(collider) = instance.collider {
				new_instance.collider = Some(self.colliders.insert_with_parent(
					collider,
					body,
					&mut self.rigid_bodies,
				));
			}

			new_instance.body = Body::Rigid(body);
		} else if let Some(collider) = instance.collider {
			let (axis, angle) = instance.rotation.to_axis_angle();

			new_instance.collider = Some(
				self.colliders.insert(
					collider
						.position(instance.position.into())
						.rotation((axis * angle).into())
						.mass(1.0),
				),
			);
		}

		new_instance
	}
}

pub trait IndexExt {
	fn to_u128(&self) -> u128;
	fn from_u128(id: u128) -> Self;
}

impl IndexExt for Index {
	fn to_u128(&self) -> u128 {
		let (idx, gen) = self.into_raw_parts();

		(idx as u128) << 32 | gen as u128
	}

	fn from_u128(id: u128) -> Self {
		let idx = (id >> 32) as u32;
		let gen = id as u32;

		Self::from_raw_parts(idx, gen)
	}
}

impl<M> Context<M> {
	pub fn physics_update(&mut self) {
		self.physics.step();
		self.physics.steps_since_last_update += 1;

		for body in self
			.physics
			.islands
			.active_dynamic_bodies()
			.iter()
			.chain(self.physics.islands.active_kinematic_bodies())
		{
			let Some(body) = self.physics.rigid_bodies.get(*body) else {
				continue;
			};

			if body.user_data == u128::MAX {
				continue;
			}

			let instance: InstanceHandle = body.user_data.into();

			#[cfg(feature = "client")]
			if let Some(mut pair) = instance.resolve_mut(&mut self.drum, &mut self.instances) {
				pair.update_gpu(&self.physics);
			}

			#[cfg(feature = "server")]
			{
				if self.physics.steps_since_last_update < PhysicsState::TICKS_PER_UPDATE {
					continue;
				}

				let Some(id) = self.instance_ids.get(&instance) else {
					continue;
				};

				let (position, rotation) = (*body.position()).into();
				let _ = self.packet_tx.send(Packet::UpdateInstance {
					id: *id,
					delta: UpdateInstance {
						position,
						rotation,
						scale: None,
						body: None,
					},
				});
			}
		}

		#[cfg(feature = "server")]
		if self.physics.steps_since_last_update >= PhysicsState::TICKS_PER_UPDATE {
			self.physics.steps_since_last_update = 0;
		}
	}

	/// Adds a new rigidbody and collider to the physics world.
	#[allow(clippy::needless_pass_by_value)]
	pub fn add_rigidbody(
		&mut self,
		rigidbody: RigidBodyBuilder,
		collider: ColliderBuilder,
	) -> (RigidBodyHandle, ColliderHandle) {
		let body = self
			.physics
			.rigid_bodies
			.insert(rigidbody.user_data(u128::MAX).build());

		let collider = self.physics.colliders.insert_with_parent(
			collider.build(),
			body,
			&mut self.physics.rigid_bodies,
		);

		(body, collider)
	}

	/// Adds a new collider to the physics world.
	///
	/// To add a collider with a rigidbody, use [`Context::add_rigidbody`] instead.
	#[allow(clippy::needless_pass_by_value)]
	pub fn add_collider(&mut self, collider: ColliderBuilder) -> ColliderHandle {
		self.physics.colliders.insert(collider.build())
	}

	pub fn remove_instance_local(&mut self, id: InstanceId) -> Option<Instance> {
		let instance = self.handles.remove(&id)?;

		self.instance_ids.remove(&instance);

		let instance = self.instances.remove(*instance)?;

		if let Body::Rigid(handle) = instance.body {
			self.physics.rigid_bodies.remove(
				handle,
				&mut self.physics.islands,
				&mut self.physics.colliders,
				&mut self.physics.impulse_joints,
				&mut self.physics.multibody_joints,
				true,
			);
		} else if let Some(collider) = instance.collider {
			self.physics.colliders.remove(
				collider,
				&mut self.physics.islands,
				&mut self.physics.rigid_bodies,
				true,
			);
		}

		// swap_remove the gpu instance, then update the other instance pointing to the one at the end
		let model = &mut self.drum.models[instance.model_id as usize];

		#[cfg(feature = "client")]
		{
			let _ = model.instances.swap_remove(instance.instance_id as usize);
		}

		// now, we need to know which instance owns that swapped one in O(1)
		model.handles.swap_remove(instance.instance_id as usize);

		// update the instance that was swapped
		let handle = model.handles[instance.instance_id as usize];
		if let Some(other) = self.instances.get_mut(*handle) {
			other.instance_id = instance.instance_id;
		}

		Some(instance)
	}

	#[cfg(not(feature = "server"))]
	pub fn add_instance(&mut self, model_id: u32, instance: InstanceBuilder) {
		let _ = self.packet_tx.send(Packet::CreateInstance {
			id: InstanceId::NONE,
			options: CreateInstance::from_builder(&instance, model_id),
		});
	}

	#[cfg(feature = "server")]
	pub fn add_instance(&mut self, model_id: u32, instance: InstanceBuilder) -> InstanceHandle {
		use std::sync::atomic::Ordering;

		let instance_id = InstanceId::new(self.next_instance_id.fetch_add(1, Ordering::SeqCst));

		let _ = self.packet_tx.send(Packet::CreateInstance {
			id: instance_id,
			options: CreateInstance::from_builder(&instance, model_id),
		});

		let handle = self.add_instance_local(model_id, instance);

		self.instance_ids.insert(handle, instance_id);
		self.handles.insert(instance_id, handle);

		handle
	}

	/// Adds a new instance to the drum and physics world.
	///
	/// If you only want to insert a rigidbody with no model,
	/// use [`Context::add_rigidbody`] or [`Context::add_collider`] instead.
	///
	/// The networked version of this method is [`Context::add_instance`].
	pub fn add_instance_local(
		&mut self,
		model_id: u32,
		mut instance: InstanceBuilder,
	) -> InstanceHandle {
		let model = &mut self.drum.models[model_id as usize];
		let instance_id = model.handles.len() as u32;

		let handle = self.instances.insert_with(|handle| {
			let handle = InstanceHandle::new(handle);
			let (axis, angle) = instance.rotation.to_axis_angle();

			instance.collider = instance
				.collider
				.or_else(|| Some(model.bounds.to_cuboid(instance.scale).mass(1.0)));

			instance.rigidbody = instance.rigidbody.map(|body| {
				body.position(instance.position.into())
					.rotation((axis * angle).into())
					.user_data(handle.into())
			});

			let instance = self.physics.add_instance(instance, model_id, instance_id);

			model.add_gpu_instance(&instance, handle, &self.physics);

			instance
		});

		InstanceHandle::new(handle)
	}
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct InstanceHandle {
	handle: Index,
}

pub struct InstancePair<'d> {
	#[cfg(feature = "client")]
	pub gpu: &'d GpuInstance,
	pub instance: &'d Instance,
}

pub struct InstancePairMut<'d> {
	pub instance: &'d mut Instance,

	#[cfg(feature = "client")]
	pub gpu: &'d mut GpuInstance,
	#[cfg(feature = "client")]
	dirty: &'d mut bool,
}

impl InstancePairMut<'_> {
	pub fn update<F>(&mut self, physics: &mut PhysicsState, update: F)
	where
		F: FnOnce(&mut Instance, &mut PhysicsState),
	{
		update(self.instance, physics);

		self.update_gpu(physics);
	}

	pub fn update_gpu(&mut self, physics: &PhysicsState) {
		#[cfg(feature = "client")]
		{
			*self.gpu = self.instance.to_gpu(physics);
			*self.dirty = true;
		}
	}
}

impl InstanceHandle {
	#[must_use]
	pub fn new(handle: Index) -> Self {
		Self { handle }
	}

	/// Returns the instance associated with the handle.
	///
	/// # Panics
	///
	/// Panics if the handle is invalid.
	#[must_use]
	pub fn resolve<'d>(
		&self,
		drum: &'d GpuDrum,
		instances: &'d Arena<Instance>,
	) -> Option<InstancePair<'d>> {
		let instance = instances.get(self.handle)?;
		#[cfg(feature = "client")]
		let model = drum.models.get(instance.model_id as usize)?;

		Some(InstancePair {
			#[cfg(feature = "client")]
			gpu: model.instances.get(instance.instance_id as usize)?,
			instance,
		})
	}

	/// Returns the instance associated with the handle.
	///
	/// # Panics
	///
	/// Panics if the handle is invalid.
	pub fn resolve_mut<'d>(
		&self,
		drum: &'d mut GpuDrum,
		instances: &'d mut Arena<Instance>,
	) -> Option<InstancePairMut<'d>> {
		let instance = instances.get_mut(self.handle)?;
		#[cfg(feature = "client")]
		let model = drum.models.get_mut(instance.model_id as usize)?;

		Some(InstancePairMut {
			#[cfg(feature = "client")]
			gpu: model.instances.get_mut(instance.instance_id as usize)?,
			#[cfg(feature = "client")]
			dirty: &mut model.dirty,
			instance,
		})
	}

	/// Returns the model associated with the instance.
	///
	/// # Panics
	///
	/// Panics if the handle is invalid.
	#[must_use]
	pub fn resolve_model<'d>(
		&self,
		drum: &'d GpuDrum,
		instances: &Arena<Instance>,
	) -> Option<&'d GpuModel> {
		let instance = instances.get(self.handle)?;

		drum.models.get(instance.model_id as usize)
	}

	/// Returns the model associated with the instance.
	///
	/// # Panics
	///
	/// Panics if the handle is invalid.
	pub fn resolve_model_mut<'d>(
		&self,
		drum: &'d mut GpuDrum,
		instances: &Arena<Instance>,
	) -> Option<&'d mut GpuModel> {
		let instance = instances.get(self.handle)?;

		drum.models.get_mut(instance.model_id as usize)
	}

	/// Updates the instance with the provided closure.
	///
	/// # Examples
	///
	/// ```rust
	/// let instance: InstanceHandle = ...;
	///
	/// instance.update(ctx, |instance, physics| {
	///   instance.rotate_y(physics, 0.1);
	/// });
	/// ```
	pub fn update<F, M>(&self, ctx: &mut Context<M>, update: F)
	where
		F: FnOnce(&mut Instance, &mut PhysicsState),
	{
		let Some(mut pair) = self.resolve_mut(&mut ctx.drum, &mut ctx.instances) else {
			return;
		};

		pair.update(&mut ctx.physics, update);
	}
}

impl From<u128> for InstanceHandle {
	fn from(id: u128) -> Self {
		Self {
			handle: Index::from_u128(id),
		}
	}
}

impl From<InstanceHandle> for u128 {
	fn from(id: InstanceHandle) -> u128 {
		id.handle.to_u128()
	}
}

impl ops::Deref for InstanceHandle {
	type Target = Index;

	fn deref(&self) -> &Self::Target {
		&self.handle
	}
}