-
-
Notifications
You must be signed in to change notification settings - Fork 331
Expand file tree
/
Copy pathtestbed.rs
More file actions
1629 lines (1478 loc) · 57.2 KB
/
testbed.rs
File metadata and controls
1629 lines (1478 loc) · 57.2 KB
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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![allow(clippy::bad_bit_mask)] // otherwise clippy complains because of TestbedStateFlags::NONE which is 0.
#![allow(clippy::unnecessary_cast)] // allowed for f32 -> f64 cast for the f64 testbed.
use bevy::prelude::*;
use bevy_egui::EguiContextPass;
use std::env;
use std::mem;
use std::num::NonZeroUsize;
use crate::debug_render::{DebugRenderPipelineResource, RapierDebugRenderPlugin};
use crate::graphics::BevyMaterialComponent;
use crate::mouse::{self, track_mouse_state, MainCamera, SceneMouse};
use crate::physics::{DeserializedPhysicsSnapshot, PhysicsEvents, PhysicsSnapshot, PhysicsState};
use crate::plugin::TestbedPlugin;
use crate::save::SerializableTestbedState;
use crate::settings::ExampleSettings;
use crate::ui;
use crate::{graphics::GraphicsManager, harness::RunState};
use bevy::window::PrimaryWindow;
use na::{self, Point2, Point3, Vector3};
use rapier::dynamics::{
ImpulseJointSet, IntegrationParameters, MultibodyJointSet, RigidBodyActivation,
RigidBodyHandle, RigidBodySet,
};
#[cfg(feature = "dim3")]
use rapier::geometry::Ray;
use rapier::geometry::{ColliderHandle, ColliderSet, NarrowPhase};
use rapier::math::{Real, Vector};
use rapier::pipeline::{PhysicsHooks, QueryPipeline};
#[cfg(feature = "dim3")]
use rapier::{control::DynamicRayCastVehicleController, prelude::QueryFilter};
#[cfg(all(feature = "dim2", feature = "other-backends"))]
use crate::box2d_backend::Box2dWorld;
use crate::harness::Harness;
#[cfg(all(feature = "dim3", feature = "other-backends"))]
use crate::physx_backend::PhysxWorld;
use bevy::render::camera::{Camera, ClearColor};
use bevy_egui::EguiContexts;
use bevy_pbr::wireframe::WireframePlugin;
use bevy_pbr::AmbientLight;
#[cfg(feature = "dim2")]
use crate::camera2d::{OrbitCamera, OrbitCameraPlugin};
#[cfg(feature = "dim3")]
use crate::camera3d::{OrbitCamera, OrbitCameraPlugin};
use crate::graphics::BevyMaterial;
// use bevy::render::render_resource::RenderPipelineDescriptor;
const RAPIER_BACKEND: usize = 0;
#[cfg(all(feature = "dim2", feature = "other-backends"))]
const BOX2D_BACKEND: usize = 1;
pub(crate) const PHYSX_BACKEND_PATCH_FRICTION: usize = 1;
pub(crate) const PHYSX_BACKEND_TWO_FRICTION_DIR: usize = 2;
pub fn save_file_path() -> String {
format!("testbed_state_{}.autosave.json", env!("CARGO_CRATE_NAME"))
}
#[derive(Default, PartialEq, Copy, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum RunMode {
Running,
#[default]
Stop,
Step,
}
bitflags::bitflags! {
#[derive(Copy, Clone, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]
pub struct TestbedStateFlags: u32 {
const SLEEP = 1 << 0;
const SUB_STEPPING = 1 << 1;
const SHAPES = 1 << 2;
const JOINTS = 1 << 3;
const AABBS = 1 << 4;
const CONTACT_POINTS = 1 << 5;
const CONTACT_NORMALS = 1 << 6;
const CENTER_OF_MASSES = 1 << 7;
const WIREFRAME = 1 << 8;
const STATISTICS = 1 << 9;
const DRAW_SURFACES = 1 << 10;
}
}
impl Default for TestbedStateFlags {
fn default() -> Self {
TestbedStateFlags::DRAW_SURFACES | TestbedStateFlags::SLEEP
}
}
bitflags::bitflags! {
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct TestbedActionFlags: u32 {
const RESET_WORLD_GRAPHICS = 1 << 0;
const EXAMPLE_CHANGED = 1 << 1;
const RESTART = 1 << 2;
const BACKEND_CHANGED = 1 << 3;
const TAKE_SNAPSHOT = 1 << 4;
const RESTORE_SNAPSHOT = 1 << 5;
const APP_STARTED = 1 << 6;
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
pub enum RapierSolverType {
#[default]
TgsSoft,
TgsSoftNoWarmstart,
PgsLegacy,
}
pub type SimulationBuilders = Vec<(&'static str, fn(&mut Testbed))>;
#[derive(Resource)]
pub struct TestbedState {
pub running: RunMode,
pub draw_colls: bool,
pub highlighted_body: Option<RigidBodyHandle>,
#[cfg(feature = "dim3")]
pub vehicle_controller: Option<DynamicRayCastVehicleController>,
// pub grabbed_object: Option<DefaultBodyPartHandle>,
// pub grabbed_object_constraint: Option<DefaultJointConstraintHandle>,
pub grabbed_object_plane: (Point3<f32>, Vector3<f32>),
pub can_grab_behind_ground: bool,
pub drawing_ray: Option<Point2<f32>>,
pub prev_flags: TestbedStateFlags,
pub flags: TestbedStateFlags,
pub action_flags: TestbedActionFlags,
pub backend_names: Vec<&'static str>,
pub example_names: Vec<&'static str>,
pub selected_example: usize,
pub selected_backend: usize,
pub example_settings: ExampleSettings,
pub solver_type: RapierSolverType,
pub physx_use_two_friction_directions: bool,
pub snapshot: Option<PhysicsSnapshot>,
pub nsteps: usize,
prev_save_data: SerializableTestbedState,
camera_locked: bool, // Used so that the camera can remain the same before and after we change backend or press the restart button.
}
impl TestbedState {
fn save_data(&self, camera: OrbitCamera) -> SerializableTestbedState {
SerializableTestbedState {
running: self.running,
flags: self.flags,
selected_example: self.selected_example,
selected_backend: self.selected_backend,
example_settings: self.example_settings.clone(),
solver_type: self.solver_type,
physx_use_two_friction_directions: self.physx_use_two_friction_directions,
camera,
}
}
pub fn apply_saved_data(&mut self, state: SerializableTestbedState, camera: &mut OrbitCamera) {
self.prev_save_data = state.clone();
self.running = state.running;
self.flags = state.flags;
self.selected_example = state.selected_example;
self.selected_backend = state.selected_backend;
self.example_settings = state.example_settings;
self.solver_type = state.solver_type;
self.physx_use_two_friction_directions = state.physx_use_two_friction_directions;
*camera = state.camera;
}
}
#[derive(Resource)]
struct SceneBuilders(SimulationBuilders);
#[cfg(feature = "other-backends")]
struct OtherBackends {
#[cfg(feature = "dim2")]
box2d: Option<Box2dWorld>,
#[cfg(feature = "dim3")]
physx: Option<PhysxWorld>,
}
struct Plugins(Vec<Box<dyn TestbedPlugin>>);
pub struct TestbedGraphics<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k> {
graphics: &'a mut GraphicsManager,
commands: &'a mut Commands<'d, 'e>,
meshes: &'a mut Assets<Mesh>,
materials: &'a mut Assets<BevyMaterial>,
material_handles: &'a mut Query<'i, 'j, &'k mut BevyMaterialComponent>,
components: &'a mut Query<'b, 'f, &'c mut Transform>,
#[allow(dead_code)] // Dead in 2D but not in 3D.
camera_transform: GlobalTransform,
camera: &'a mut OrbitCamera,
ui_context: &'a mut EguiContexts<'g, 'h>,
keys: &'a ButtonInput<KeyCode>,
mouse: &'a SceneMouse,
}
pub struct Testbed<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k> {
graphics: Option<TestbedGraphics<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k>>,
harness: &'a mut Harness,
state: &'a mut TestbedState,
#[cfg(feature = "other-backends")]
other_backends: &'a mut OtherBackends,
plugins: &'a mut Plugins,
}
pub struct TestbedApp {
builders: SceneBuilders,
graphics: GraphicsManager,
state: TestbedState,
harness: Harness,
#[cfg(feature = "other-backends")]
other_backends: OtherBackends,
plugins: Plugins,
}
impl TestbedApp {
pub fn new_empty() -> Self {
let graphics = GraphicsManager::new();
let flags = TestbedStateFlags::default();
#[allow(unused_mut)]
let mut backend_names = vec!["rapier"];
#[cfg(all(feature = "dim2", feature = "other-backends"))]
backend_names.push("box2d");
#[cfg(all(feature = "dim3", feature = "other-backends"))]
backend_names.push("physx (patch friction)");
#[cfg(all(feature = "dim3", feature = "other-backends"))]
backend_names.push("physx (two friction dir)");
let state = TestbedState {
running: RunMode::Running,
draw_colls: false,
highlighted_body: None,
#[cfg(feature = "dim3")]
vehicle_controller: None,
// grabbed_object: None,
// grabbed_object_constraint: None,
grabbed_object_plane: (Point3::origin(), na::zero()),
can_grab_behind_ground: false,
drawing_ray: None,
snapshot: None,
prev_flags: flags,
flags,
action_flags: TestbedActionFlags::APP_STARTED | TestbedActionFlags::EXAMPLE_CHANGED,
backend_names,
example_names: Vec::new(),
example_settings: ExampleSettings::default(),
selected_example: 0,
selected_backend: RAPIER_BACKEND,
solver_type: RapierSolverType::default(),
physx_use_two_friction_directions: true,
nsteps: 1,
camera_locked: false,
prev_save_data: SerializableTestbedState::default(),
};
let harness = Harness::new_empty();
#[cfg(feature = "other-backends")]
let other_backends = OtherBackends {
#[cfg(feature = "dim2")]
box2d: None,
#[cfg(feature = "dim3")]
physx: None,
};
TestbedApp {
builders: SceneBuilders(Vec::new()),
plugins: Plugins(Vec::new()),
graphics,
state,
harness,
#[cfg(feature = "other-backends")]
other_backends,
}
}
pub fn from_builders(builders: SimulationBuilders) -> Self {
let mut res = TestbedApp::new_empty();
res.set_builders(builders);
res
}
pub fn set_builders(&mut self, builders: SimulationBuilders) {
self.state.example_names = builders.iter().map(|e| e.0).collect();
self.builders = SceneBuilders(builders)
}
pub fn run(self) {
self.run_with_init(|_| {})
}
pub fn run_with_init(mut self, mut init: impl FnMut(&mut App)) {
#[cfg(feature = "profiler_ui")]
puffin_egui::puffin::set_scopes_on(true);
let mut args = env::args();
let mut benchmark_mode = false;
let cmds = [
("--help", Some("-h"), "Print this help message and exit."),
("--pause", None, "Do not start the simulation right away."),
("--bench", None, "Run benchmark mode without rendering."),
(
"--bench-iters <num:u32>",
None,
"Number of frames to run in benchmarking.",
),
];
let usage = |exe_name: &str, err: Option<&str>| {
println!("Usage: {} [OPTION] ", exe_name);
println!();
println!("Options:");
for (long, s, desc) in cmds {
let s_str = if let Some(s) = s {
format!(", {s}")
} else {
String::new()
};
println!(" {long}{s_str} - {desc}",)
}
if let Some(err) = err {
eprintln!("Error: {err}");
}
};
let mut num_bench_iters = 1000;
if args.len() > 1 {
let exname = args.next().unwrap();
while let Some(arg) = args.next() {
match arg.as_str() {
"--help" | "-h" => {
usage(&exname[..], None);
return;
}
"--pause" => {
self.state.running = RunMode::Stop;
}
"--bench" => {
benchmark_mode = true;
}
"--bench-iters" => {
let Some(n) = args.next() else {
usage(
&exname[..],
Some("Missing number of iterations for --bench-iters"),
);
return;
};
let Ok(n) = n.parse::<u32>() else {
usage(
&exname[..],
Some(&format!("Couldn't parse --bench-iters <arg:u32>, got {n}")),
);
return;
};
num_bench_iters = n;
}
// ignore extra arguments
_ => {}
}
}
}
// TODO: move this to dedicated benchmarking code
if benchmark_mode {
use std::fs::File;
use std::io::{BufWriter, Write};
// Don't enter the main loop. We will just step the simulation here.
let mut results = Vec::new();
let builders = mem::take(&mut self.builders.0);
let backend_names = self.state.backend_names.clone();
for builder in builders {
results.clear();
println!("Running benchmark for {}", builder.0);
for (backend_id, backend) in backend_names.iter().enumerate() {
println!("|_ using backend {}", backend);
self.state.selected_backend = backend_id;
self.harness
.physics
.integration_parameters
.num_solver_iterations = NonZeroUsize::new(4).unwrap();
// Init world.
let mut testbed = Testbed {
graphics: None,
state: &mut self.state,
harness: &mut self.harness,
#[cfg(feature = "other-backends")]
other_backends: &mut self.other_backends,
plugins: &mut self.plugins,
};
(builder.1)(&mut testbed);
// Run the simulation.
let mut timings = Vec::new();
for k in 0..num_bench_iters {
{
if self.state.selected_backend == RAPIER_BACKEND {
self.harness.step();
}
#[cfg(all(feature = "dim2", feature = "other-backends"))]
{
if self.state.selected_backend == BOX2D_BACKEND {
self.other_backends.box2d.as_mut().unwrap().step(
&mut self.harness.physics.pipeline.counters,
&self.harness.physics.integration_parameters,
);
self.other_backends.box2d.as_mut().unwrap().sync(
&mut self.harness.physics.bodies,
&mut self.harness.physics.colliders,
);
}
}
#[cfg(all(feature = "dim3", feature = "other-backends"))]
{
if self.state.selected_backend == PHYSX_BACKEND_PATCH_FRICTION
|| self.state.selected_backend == PHYSX_BACKEND_TWO_FRICTION_DIR
{
// println!("Step");
self.other_backends.physx.as_mut().unwrap().step(
&mut self.harness.physics.pipeline.counters,
&self.harness.physics.integration_parameters,
);
self.other_backends.physx.as_mut().unwrap().sync(
&mut self.harness.physics.bodies,
&mut self.harness.physics.colliders,
);
}
}
}
// Skip the first update.
if k > 0 {
timings
.push(self.harness.physics.pipeline.counters.step_time.time_ms());
}
}
results.push(timings);
}
// Write the result as a csv file.
use inflector::Inflector;
let filename = format!("{}.csv", builder.0.to_camel_case());
let mut file = BufWriter::new(File::create(filename).unwrap());
write!(file, "{}", backend_names[0]).unwrap();
for backend in &backend_names[1..] {
write!(file, ",{}", backend).unwrap();
}
writeln!(file).unwrap();
for i in 0..results[0].len() {
write!(file, "{}", results[0][i]).unwrap();
for result in &results[1..] {
write!(file, ",{}", result[i]).unwrap();
}
writeln!(file).unwrap();
}
}
} else {
let title = if cfg!(feature = "dim2") {
"Rapier: 2D demos".to_string()
} else {
"Rapier: 3D demos".to_string()
};
let window_plugin = WindowPlugin {
primary_window: Some(Window {
title,
..Default::default()
}),
..Default::default()
};
let mut app = App::new();
app.insert_resource(ClearColor(Color::from(Srgba::rgb(0.15, 0.15, 0.15))))
.insert_resource(AmbientLight {
brightness: 0.3,
..Default::default()
})
.init_resource::<mouse::SceneMouse>()
.add_plugins(DefaultPlugins.set(window_plugin))
.add_plugins(OrbitCameraPlugin)
.add_plugins(WireframePlugin::default())
.add_plugins(RapierDebugRenderPlugin::default())
.add_plugins(bevy_egui::EguiPlugin {
enable_multipass_for_primary_context: true,
});
#[cfg(target_arch = "wasm32")]
app.add_plugin(bevy_webgl2::WebGL2Plugin);
#[cfg(feature = "other-backends")]
app.insert_non_send_resource(self.other_backends);
app.add_systems(Startup, setup_graphics_environment)
.insert_non_send_resource(self.graphics)
.insert_resource(self.state)
.insert_non_send_resource(self.harness)
.insert_resource(self.builders)
.insert_non_send_resource(self.plugins)
.add_systems(EguiContextPass, update_testbed)
.add_systems(EguiContextPass, egui_focus)
.add_systems(Update, track_mouse_state);
init(&mut app);
app.run();
}
}
}
impl<'g, 'h> TestbedGraphics<'_, '_, '_, '_, '_, '_, 'g, 'h, '_, '_, '_> {
pub fn set_body_color(&mut self, body: RigidBodyHandle, color: [f32; 3]) {
self.graphics
.set_body_color(self.materials, self.material_handles, body, color);
}
pub fn ui_context_mut(&mut self) -> &mut EguiContexts<'g, 'h> {
&mut *self.ui_context
}
pub fn add_body(
&mut self,
handle: RigidBodyHandle,
bodies: &RigidBodySet,
colliders: &ColliderSet,
) {
self.graphics.add_body_colliders(
&mut *self.commands,
&mut *self.meshes,
&mut *self.materials,
&mut *self.components,
handle,
bodies,
colliders,
)
}
pub fn remove_body(&mut self, handle: RigidBodyHandle) {
self.graphics.remove_body_nodes(&mut *self.commands, handle)
}
pub fn add_collider(&mut self, handle: ColliderHandle, colliders: &ColliderSet) {
self.graphics.add_collider(
&mut *self.commands,
&mut *self.meshes,
&mut *self.materials,
handle,
colliders,
)
}
pub fn remove_collider(&mut self, handle: ColliderHandle, colliders: &ColliderSet) {
if let Some(parent_handle) = colliders.get(handle).map(|c| c.parent()) {
self.graphics
.remove_collider_nodes(&mut *self.commands, parent_handle, handle)
}
}
pub fn update_collider(&mut self, handle: ColliderHandle, colliders: &ColliderSet) {
self.remove_collider(handle, colliders);
self.add_collider(handle, colliders);
}
pub fn keys(&self) -> &ButtonInput<KeyCode> {
self.keys
}
pub fn mouse(&self) -> &SceneMouse {
self.mouse
}
#[cfg(feature = "dim3")]
pub fn camera_rotation(&self) -> na::UnitQuaternion<Real> {
let (_, rot, _) = self.camera_transform.to_scale_rotation_translation();
na::Unit::new_unchecked(na::Quaternion::new(
rot.w as Real,
rot.x as Real,
rot.y as Real,
rot.z as Real,
))
}
#[cfg(feature = "dim3")]
pub fn camera_fwd_dir(&self) -> Vector<f32> {
(self.camera_transform * -Vec3::Z).normalize().into()
}
}
impl Testbed<'_, '_, '_, '_, '_, '_, '_, '_, '_, '_, '_> {
pub fn set_number_of_steps_per_frame(&mut self, nsteps: usize) {
self.state.nsteps = nsteps
}
#[cfg(feature = "dim3")]
pub fn set_vehicle_controller(&mut self, controller: DynamicRayCastVehicleController) {
self.state.vehicle_controller = Some(controller);
}
pub fn allow_grabbing_behind_ground(&mut self, allow: bool) {
self.state.can_grab_behind_ground = allow;
}
pub fn integration_parameters_mut(&mut self) -> &mut IntegrationParameters {
&mut self.harness.physics.integration_parameters
}
pub fn physics_state_mut(&mut self) -> &mut PhysicsState {
&mut self.harness.physics
}
pub fn harness_mut(&mut self) -> &mut Harness {
self.harness
}
pub fn example_settings_mut(&mut self) -> &mut ExampleSettings {
&mut self.state.example_settings
}
pub fn set_world(
&mut self,
bodies: RigidBodySet,
colliders: ColliderSet,
impulse_joints: ImpulseJointSet,
multibody_joints: MultibodyJointSet,
) {
self.set_world_with_params(
bodies,
colliders,
impulse_joints,
multibody_joints,
Vector::y() * -9.81,
(),
)
}
pub fn set_world_with_params(
&mut self,
bodies: RigidBodySet,
colliders: ColliderSet,
impulse_joints: ImpulseJointSet,
multibody_joints: MultibodyJointSet,
gravity: Vector<Real>,
hooks: impl PhysicsHooks + 'static,
) {
self.harness.set_world_with_params(
bodies,
colliders,
impulse_joints,
multibody_joints,
gravity,
hooks,
);
self.state
.action_flags
.set(TestbedActionFlags::RESET_WORLD_GRAPHICS, true);
self.state.highlighted_body = None;
#[cfg(feature = "dim3")]
{
self.state.vehicle_controller = None;
}
#[cfg(all(feature = "dim2", feature = "other-backends"))]
{
if self.state.selected_backend == BOX2D_BACKEND {
self.other_backends.box2d = Some(Box2dWorld::from_rapier(
self.harness.physics.gravity,
&self.harness.physics.bodies,
&self.harness.physics.colliders,
&self.harness.physics.impulse_joints,
));
}
}
#[cfg(all(feature = "dim3", feature = "other-backends"))]
{
if self.state.selected_backend == PHYSX_BACKEND_PATCH_FRICTION
|| self.state.selected_backend == PHYSX_BACKEND_TWO_FRICTION_DIR
{
self.other_backends.physx = Some(PhysxWorld::from_rapier(
self.harness.physics.gravity,
&self.harness.physics.integration_parameters,
&self.harness.physics.bodies,
&self.harness.physics.colliders,
&self.harness.physics.impulse_joints,
&self.harness.physics.multibody_joints,
self.state.selected_backend == PHYSX_BACKEND_TWO_FRICTION_DIR,
self.harness.state.num_threads(),
));
}
}
}
pub fn set_graphics_shift(&mut self, shift: Vector<Real>) {
if !self.state.camera_locked {
if let Some(graphics) = &mut self.graphics {
graphics.graphics.gfx_shift = shift;
}
}
}
#[cfg(feature = "dim2")]
pub fn look_at(&mut self, at: Point2<f32>, zoom: f32) {
if !self.state.camera_locked {
if let Some(graphics) = &mut self.graphics {
graphics.camera.center.x = at.x;
graphics.camera.center.y = at.y;
graphics.camera.zoom = zoom;
}
}
}
#[cfg(feature = "dim3")]
pub fn look_at(&mut self, eye: Point3<f32>, at: Point3<f32>) {
if !self.state.camera_locked {
if let Some(graphics) = &mut self.graphics {
graphics.camera.center.x = at.x;
graphics.camera.center.y = at.y;
graphics.camera.center.z = at.z;
let view_dir = eye - at;
graphics.camera.distance = view_dir.norm();
if graphics.camera.distance > 0.0 {
graphics.camera.y = (view_dir.y / graphics.camera.distance).acos();
graphics.camera.x =
(-view_dir.z).atan2(view_dir.x) - std::f32::consts::FRAC_PI_2;
}
}
}
}
pub fn set_initial_body_color(&mut self, body: RigidBodyHandle, color: [f32; 3]) {
if let Some(graphics) = &mut self.graphics {
graphics.graphics.set_initial_body_color(body, color);
}
}
pub fn set_initial_collider_color(&mut self, collider: ColliderHandle, color: [f32; 3]) {
if let Some(graphics) = &mut self.graphics {
graphics
.graphics
.set_initial_collider_color(collider, color);
}
}
pub fn set_body_wireframe(&mut self, body: RigidBodyHandle, wireframe_enabled: bool) {
if let Some(graphics) = &mut self.graphics {
graphics
.graphics
.set_body_wireframe(body, wireframe_enabled);
}
}
// pub fn world(&self) -> &Box<WorldOwner> {
// &self.world
// }
pub fn add_callback<
F: FnMut(Option<&mut TestbedGraphics>, &mut PhysicsState, &PhysicsEvents, &RunState) + 'static,
>(
&mut self,
callback: F,
) {
self.harness.add_callback(callback);
}
pub fn add_plugin(&mut self, mut plugin: impl TestbedPlugin + 'static) {
plugin.init_plugin();
self.plugins.0.push(Box::new(plugin));
}
#[cfg(feature = "dim3")]
fn update_vehicle_controller(&mut self, events: &ButtonInput<KeyCode>) {
if self.state.running == RunMode::Stop {
return;
}
if let Some(vehicle) = &mut self.state.vehicle_controller {
let mut engine_force = 0.0;
let mut steering_angle = 0.0;
for key in events.get_pressed() {
match *key {
KeyCode::ArrowRight => {
steering_angle += -0.7;
}
KeyCode::ArrowLeft => {
steering_angle += 0.7;
}
KeyCode::ArrowUp => {
engine_force += 30.0;
}
KeyCode::ArrowDown => {
engine_force += -30.0;
}
_ => {}
}
}
let wheels = vehicle.wheels_mut();
wheels[0].engine_force = engine_force;
wheels[0].steering = steering_angle;
wheels[1].engine_force = engine_force;
wheels[1].steering = steering_angle;
vehicle.update_vehicle(
self.harness.physics.integration_parameters.dt,
&mut self.harness.physics.bodies,
&self.harness.physics.colliders,
&self.harness.physics.query_pipeline,
QueryFilter::exclude_dynamic().exclude_rigid_body(vehicle.chassis),
);
}
}
fn handle_common_events(&mut self, events: &ButtonInput<KeyCode>) {
// C can be used to write within profiling filter.
if events.pressed(KeyCode::ControlLeft) || events.pressed(KeyCode::ControlRight) {
return;
}
for key in events.get_just_released() {
match *key {
KeyCode::KeyT => {
if self.state.running == RunMode::Stop {
self.state.running = RunMode::Running;
} else {
self.state.running = RunMode::Stop;
}
}
KeyCode::KeyS => self.state.running = RunMode::Step,
KeyCode::KeyR => self
.state
.action_flags
.set(TestbedActionFlags::EXAMPLE_CHANGED, true),
KeyCode::KeyC => {
// Delete 1 collider of 10% of the remaining dynamic bodies.
let mut colliders: Vec<_> = self
.harness
.physics
.bodies
.iter()
.filter(|e| e.1.is_dynamic())
.filter(|e| !e.1.colliders().is_empty())
.map(|e| e.1.colliders().to_vec())
.collect();
colliders.sort_by_key(|co| -(co.len() as isize));
let num_to_delete = (colliders.len() / 10).max(0);
for to_delete in &colliders[..num_to_delete] {
if let Some(graphics) = self.graphics.as_mut() {
graphics.remove_collider(to_delete[0], &self.harness.physics.colliders);
}
self.harness.physics.colliders.remove(
to_delete[0],
&mut self.harness.physics.islands,
&mut self.harness.physics.bodies,
true,
);
}
}
KeyCode::KeyD => {
// Delete 10% of the remaining dynamic bodies.
let dynamic_bodies: Vec<_> = self
.harness
.physics
.bodies
.iter()
.filter(|e| e.1.is_dynamic())
.map(|e| e.0)
.collect();
let num_to_delete = (dynamic_bodies.len() / 10).max(0);
for to_delete in &dynamic_bodies[..num_to_delete] {
if let Some(graphics) = self.graphics.as_mut() {
graphics.remove_body(*to_delete);
}
self.harness.physics.bodies.remove(
*to_delete,
&mut self.harness.physics.islands,
&mut self.harness.physics.colliders,
&mut self.harness.physics.impulse_joints,
&mut self.harness.physics.multibody_joints,
true,
);
}
}
KeyCode::KeyJ => {
// Delete 10% of the remaining impulse_joints.
let impulse_joints: Vec<_> = self
.harness
.physics
.impulse_joints
.iter()
.map(|e| e.0)
.collect();
let num_to_delete = (impulse_joints.len() / 10).max(0);
for to_delete in &impulse_joints[..num_to_delete] {
self.harness.physics.impulse_joints.remove(*to_delete, true);
}
}
KeyCode::KeyA => {
// Delete 10% of the remaining multibody_joints.
let multibody_joints: Vec<_> = self
.harness
.physics
.multibody_joints
.iter()
.map(|e| e.0)
.collect();
let num_to_delete = (multibody_joints.len() / 10).max(0);
for to_delete in &multibody_joints[..num_to_delete] {
self.harness
.physics
.multibody_joints
.remove(*to_delete, true);
}
}
KeyCode::KeyM => {
// Delete one remaining multibody.
let to_delete = self
.harness
.physics
.multibody_joints
.iter()
.next()
.map(|(_, _, _, link)| link.rigid_body_handle());
if let Some(to_delete) = to_delete {
self.harness
.physics
.multibody_joints
.remove_multibody_articulations(to_delete, true);
}
}
_ => {}
}
}
}
// #[cfg(feature = "dim2")]
// fn handle_special_event(&mut self) {}
//
// #[cfg(feature = "dim3")]
// fn handle_special_event(&mut self) {
// use rapier::dynamics::RigidBodyBuilder;
// use rapier::geometry::ColliderBuilder;
//
// if window.is_conrod_ui_capturing_mouse() {
// return;
// }
//
// match event.value {
// WindowEvent::Key(Key::Space, Action::Release, _) => {
// let cam_pos = self.graphics.camera().view_transform().inverse();
// let forward = cam_pos * -Vector::z();
// let vel = forward * 1000.0;
//
// let bodies = &mut self.harness.physics.bodies;
// let colliders = &mut self.harness.physics.colliders;
//
// let collider = ColliderBuilder::cuboid(4.0, 2.0, 0.4).density(20.0).build();
// // let collider = ColliderBuilder::ball(2.0).density(1.0).build();
// let body = RigidBodyBuilder::dynamic()
// .position(cam_pos)
// .linvel(vel.x, vel.y, vel.z)
// .ccd_enabled(true)
// .build();
//
// let body_handle = bodies.insert(body);
// colliders.insert(collider, body_handle, bodies);
// self.graphics.add(window, body_handle, bodies, colliders);
// }
// _ => {}
// }
// }
}
fn draw_contacts(_nf: &NarrowPhase, _colliders: &ColliderSet) {
// use rapier::math::Isometry;
//
// for pair in nf.contact_pairs() {
// for manifold in &pair.manifolds {
// /*
// for contact in &manifold.data.solver_contacts {
// let p = contact.point;
// let n = manifold.data.normal;
//
// use crate::engine::GraphicsWindow;
// window.draw_graphics_line(&p, &(p + n * 0.4), &point![0.5, 1.0, 0.5]);
// }
// */
// for pt in manifold.contacts() {
// let color = if pt.dist > 0.0 {
// point![0.0, 0.0, 1.0]
// } else {
// point![1.0, 0.0, 0.0]