Repository navigation
Expand file tree
/
Copy pathapp.cc
More file actions
2440 lines (2204 loc) · 81.6 KB
/
Copy pathapp.cc
File metadata and controls
2440 lines (2204 loc) · 81.6 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
// Copyright 2025 DeepMind Technologies Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "studio/app.h"
#include <algorithm>
#include <array>
#include <cfloat>
#include <charconv>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <functional>
#include <ios>
#include <memory>
#include <mutex>
#include <optional>
#include <span>
#include <string>
#include <string_view>
#include <system_error>
#include <thread>
#include <utility>
#include <variant>
#include <vector>
#include <imgui.h>
#include <imgui_internal.h>
#include <implot.h>
#include "webp/encode.h"
#include "webp/types.h"
#include <mujoco/mjrfilament.h>
#include <mujoco/mujoco.h>
#include "render/filament/core/imgui_editor.h"
#include "render/filament/support/imgui_bridge.h"
#include "render/filament/support/renderer.h"
#include "studio/hal/graphics_mode.h"
#include "studio/hal/window.h"
#include "studio/render/model_scene.h"
#include "studio/sim/model_holder.h"
#include "studio/sim/step_control.h"
#include "studio/ux/camera_control.h"
#include "studio/ux/console.h"
#include "studio/ux/file_dialog.h"
#include "studio/ux/gui.h"
#include "studio/ux/gui_helpers.h"
#include "studio/ux/gui_spec.h"
#include "studio/ux/imgui_widgets.h"
#include "studio/ux/interaction.h"
#include "studio/ux/picture_gui.h"
#include "studio/ux/plugin.h"
namespace mujoco::studio {
using PauseState = StepControl::PauseState;
static void ToggleFlag(mjtByte& flag) { flag = flag ? 0 : 1; }
static void ToggleWindow(bool& window) {
window = !window;
ImGui::GetIO().WantSaveIniSettings = true;
}
static void SelectParentPerturb(const mjModel* model, mjvPerturb& perturb) {
if (perturb.select > 0) {
perturb.select = model->body_parentid[perturb.select];
perturb.flexselect = -1;
perturb.skinselect = -1;
if (perturb.select <= 0) {
perturb.active = 0;
}
}
// TODO: update selected element!
}
static std::string CheckPathForFile(const std::filesystem::path& path, std::string_view filename) {
std::filesystem::path resolved = path / filename;
if (std::filesystem::exists(resolved)) {
return resolved.string();
}
resolved += ".xml";
if (std::filesystem::exists(resolved)) {
return resolved.string();
}
return "";
}
// Attempts to find a file with the given name by recursively searching the
// given search paths.
static std::string ResolveFile(std::string_view filename,
const std::vector<std::string>& search_paths) {
if (std::filesystem::exists(filename)) {
return std::string(filename);
}
std::string resolved;
for (const std::string& path : search_paths) {
if (!std::filesystem::exists(path) || !std::filesystem::is_directory(path)) {
continue;
}
resolved = CheckPathForFile(std::filesystem::path(path), filename);
if (!resolved.empty()) {
return resolved;
}
std::vector<std::filesystem::path> entries;
for (const auto& it : std::filesystem::recursive_directory_iterator(path)) {
entries.push_back(it.path());
}
std::sort(entries.begin(), entries.end());
for (const auto& entry : entries) {
resolved = CheckPathForFile(entry, filename);
if (!resolved.empty()) {
return resolved;
}
}
}
return std::string(filename);
}
// Exports the given image (assumed to be RGB888) to a webp file.
static void SaveToWebp(int width, int height, const std::byte* data, const std::string& filename) {
uint8_t* webp = nullptr;
const size_t size = WebPEncodeLosslessRGB(reinterpret_cast<const uint8_t*>(data), width, height,
width * 3, &webp);
std::ofstream file(filename, std::ios::binary);
file.write(reinterpret_cast<const char*>(webp), size);
file.close();
WebPFree(webp);
}
static constexpr const char* ICON_RELOAD_MODEL = ICON_FA_REFRESH;
static constexpr const char* ICON_RESET_MODEL = ICON_FA_UNDO;
static constexpr const char* ICON_UNDO_SPEC = ICON_FA_UNDO;
static constexpr const char* ICON_REDO_SPEC = ICON_FA_REPEAT;
App::App(Config config)
: app_title_(std::move(config.title)), ini_path_(std::move(config.ini_path)) {
Console::Init();
SwitchGraphicsMode(config.width, config.height, config.gfx_mode);
if (config.initial_theme.has_value()) {
ui_.theme = *config.initial_theme;
}
ImPlot::CreateContext();
mj_defaultVFS(&vfs_);
mjv_defaultPerturb(&perturb_);
mjv_defaultCamera(&camera_);
mjv_defaultOption(&vis_options_);
for (int i = 0; i < mjNRNDFLAG; i++) {
render_flags_[i] = (mjRNDSTRING[i][1][0] == '1');
}
std::memset(&plugin_scene_, 0, sizeof(mjvScene));
mjv_makeScene(nullptr, &plugin_scene_, 2000);
profiler_.Clear();
step_control_.SetPreStepCallback([this](const mjModel* m, mjData* d) { PreStep(m, d); });
step_control_.SetPostStepCallback([this](const mjModel* m, mjData* d) { PostStep(m, d); });
LoadSettings();
#ifndef __EMSCRIPTEN__
physics_thread_ = std::thread(&App::PhysicsThreadLoop, this);
#endif
}
App::~App() {
#ifndef __EMSCRIPTEN__
stop_physics_thread_.store(true);
if (physics_thread_.joinable()) {
physics_thread_.join();
}
#endif
// ImGui's autosave is on a timer and covers only state it tracks, so recent
// changes and plugin visibility would be lost. window_ owns the ImGui context
// and outlives this body.
SaveSettings();
if (ImPlot::GetCurrentContext() != nullptr) {
ImPlot::DestroyContext(nullptr);
}
mjv_freeScene(&plugin_scene_);
model_holder_.reset();
mj_deleteVFS(&vfs_);
}
#ifndef __EMSCRIPTEN__
void App::PhysicsThreadLoop() {
while (!stop_physics_thread_.load()) {
{
std::unique_lock<std::mutex> lock(physics_mutex_);
if (tmp_.file_dialog == UiTempState::FileDialog_None) {
UpdatePhysics();
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
#endif
void App::SwitchGraphicsMode(int width, int height, GraphicsMode mode) {
model_scene_.reset();
imgui_bridge_.reset();
renderer_.reset();
window_.reset();
Window::Config window_config;
window_config.gfx_mode = mode;
window_ = std::make_unique<Window>(app_title_, width, height, window_config);
mjrfContextConfig renderer_config;
mjrf_defaultContextConfig(&renderer_config);
renderer_config.native_window = window_->GetNativeWindowHandle();
renderer_config.software_rendering = IsSoftware(mode);
renderer_config.graphics_api =
IsOpenGl(mode) || IsWebGl(mode) ? mjGRAPHICS_API_OPENGL : mjGRAPHICS_API_VULKAN;
renderer_ = std::make_unique<Renderer>(renderer_config);
// Define two render targets: one for rendering to the window, and one for
// RenderToTexture.
mjrfRenderTargetConfig config;
mjrf_defaultRenderTargetConfig(&config);
config.color_format = mjPIXEL_FORMAT_RGB8;
config.depth_format = mjPIXEL_FORMAT_DEPTH32F;
renderer_->CreateRenderTarget("pixels", config);
renderer_->CreateRenderTarget("tmp", config);
imgui_bridge_ = std::make_unique<ImguiBridge>(renderer_->GetContext(), renderer_->GetScene("ux"));
// TODO: Figure out why this breaks on some platforms.
// LoadSettings();
if (ui_.window_width > 0 && ui_.window_height > 0) {
window_->Resize(ui_.window_width, ui_.window_height);
}
}
void App::RequestModelLoad(std::string model_file) { pending_load_ = std::move(model_file); }
void App::RequestModelReload() { pending_reload_ = true; }
void App::InitEmptyModel() {
std::unique_lock<std::mutex> lock(physics_mutex_);
BuildModel(EmptyModel{});
}
void App::LoadModelFromFile(const std::string& filepath) {
std::unique_lock<std::mutex> lock(physics_mutex_);
BuildModel(FileModel{filepath});
}
void App::LoadModelFromBuffer(std::span<const std::byte> buffer, std::string_view content_type,
std::string_view filename) {
std::unique_lock<std::mutex> lock(physics_mutex_);
BuildModel(BufferModel{.buffer = buffer, .content_type = content_type, .name = filename});
}
void App::LoadKeyframe(std::string_view keyframe) {
std::unique_lock<std::mutex> lock(physics_mutex_);
if (!has_model() || !has_data() || model()->nkey <= 0) {
return;
}
const mjModel* m = model();
int id = mj_name2id(m, mjOBJ_KEY, std::string(keyframe).c_str());
if (id >= 0 && id < m->nkey) {
tmp_.key_idx = id;
ResetPhysics();
return;
}
if (!keyframe.empty()) {
int parsed = -1;
auto [ptr, ec] = std::from_chars(keyframe.data(), keyframe.data() + keyframe.size(), parsed);
if (ec == std::errc() && ptr == keyframe.data() + keyframe.size() && parsed >= 0 &&
parsed < m->nkey) {
tmp_.key_idx = parsed;
ResetPhysics();
return;
}
}
}
App::KeyframeSelection App::CaptureKeyframeSelection(bool is_reload) const {
KeyframeSelection saved;
saved.is_reload = is_reload;
saved.key_idx = tmp_.key_idx;
if (is_reload && has_model()) {
const mjModel* m = model_holder_->model();
if (tmp_.key_idx >= 0 && tmp_.key_idx < m->nkey) {
if (const char* name = mj_id2name(m, mjOBJ_KEY, tmp_.key_idx)) {
saved.key_name = name;
}
}
saved.all_old_names.reserve(m->nkey);
for (int k = 0; k < m->nkey; ++k) {
if (const char* name = mj_id2name(m, mjOBJ_KEY, k)) {
saved.all_old_names.push_back(name);
} else {
saved.all_old_names.push_back("");
}
}
}
return saved;
}
void App::RestoreKeyframeSelection(const KeyframeSelection& saved) {
if (!saved.is_reload || !has_model() || saved.key_idx < 0) {
tmp_.key_idx = -1;
return;
}
const mjModel* m = model();
if (!saved.key_name.empty()) {
int id = mj_name2id(m, mjOBJ_KEY, saved.key_name.c_str());
if (id >= 0) {
tmp_.key_idx = id;
return;
}
if (saved.key_idx >= 0 && saved.key_idx < m->nkey &&
mj_id2name(m, mjOBJ_KEY, saved.key_idx) == nullptr) {
tmp_.key_idx = saved.key_idx;
return;
}
tmp_.key_idx = -1;
return;
} else {
if (saved.key_idx >= 0 && saved.key_idx < m->nkey) {
const char* new_name = mj_id2name(m, mjOBJ_KEY, saved.key_idx);
if (new_name == nullptr) {
tmp_.key_idx = saved.key_idx;
return;
}
bool shifted_from_other = false;
for (size_t i = 0; i < saved.all_old_names.size(); ++i) {
if (static_cast<int>(i) != saved.key_idx && saved.all_old_names[i] == new_name) {
shifted_from_other = true;
break;
}
}
if (!shifted_from_other) {
tmp_.key_idx = saved.key_idx;
return;
}
}
tmp_.key_idx = -1;
}
}
void App::UpdateFilePaths(const std::string& resolved_path) {
if (!resolved_path.empty()) {
const std::filesystem::path path(resolved_path);
const std::string base_path = path.parent_path().string() + "/";
const std::string model_name = path.stem().string();
tmp_.last_path[UiTempState::FileDialog_Load] = base_path + model_name + ".xml";
tmp_.last_path[UiTempState::FileDialog_SaveMjb] = base_path + model_name + "_saved.mjb";
tmp_.last_path[UiTempState::FileDialog_SaveXml] = base_path + model_name + "_saved.xml";
tmp_.last_path[UiTempState::FileDialog_PrintModel] = base_path + model_name + "_MJMODEL.TXT";
tmp_.last_path[UiTempState::FileDialog_PrintData] = base_path + model_name + "_MJDATA.TXT";
tmp_.last_path[UiTempState::FileDialog_SaveScreenshot] = base_path + "screenshot.webp";
}
}
void App::SetLoadError(std::string error) {
BuildModel(EmptyModel{});
RecordLoadError(error);
}
void App::RecordLoadError(std::string_view error) {
load_error_ = error;
if (!load_error_.empty()) {
Console::Get().Log(mjLOG_ERROR, load_error_);
}
}
void App::ResetPhysics() {
if (has_model() && has_data()) {
if (tmp_.key_idx >= model()->nkey || tmp_.key_idx < -1) {
tmp_.key_idx = -1;
}
mj_resetDataKeyframe(model(), data(), tmp_.key_idx);
mj_forward(model(), data());
}
ResetHistory(sim_history_, timeline_, has_model() ? model() : nullptr,
has_data() ? data() : nullptr);
timer_prev_ = {};
profiler_.ResetTimers();
}
void App::UpdatePhysics() {
if (!has_model()) {
return;
}
if (tmp_.update_threadpool) {
mju_threadpool(data(), ui_.nthread);
tmp_.update_threadpool = false;
}
bool plugin_stepped = false;
ForEachPlugin<ModelPlugin>([&](auto* plugin) {
if (plugin->do_update) {
if (plugin->do_update(plugin, model(), data())) {
plugin_stepped = true;
}
}
});
bool stepped = plugin_stepped;
if (!plugin_stepped) {
if (step_control_.GetPauseState() != PauseState::kNormalPaused) {
mju_zero(data()->xfrc_applied, 6 * model()->nbody);
mjv_applyPerturbPose(model(), data(), &perturb_, 0);
mjv_applyPerturbForce(model(), data(), &perturb_);
} else {
mjv_applyPerturbPose(model(), data(), &perturb_, 1);
}
StepControl::Status status = step_control_.Advance(model(), data());
if (status == StepControl::Status::kPaused) {
profiler_.Update(model(), data());
} else if (status == StepControl::Status::kOk) {
stepped = true;
} else if (status == StepControl::Status::kAutoReset) {
ResetPhysics();
} else if (status == StepControl::Status::kDiverged) {
// The engine reported the divergence with mju_warning, which adds it to
// the Console.
stepped = true;
}
}
if (stepped) {
profiler_.Update(model(), data());
if (plugin_stepped) {
RecordHistoryFrame(sim_history_, timeline_, model(), data());
}
}
plugin_scene_.ngeom = 0;
ForEachPlugin<ScenePlugin>([&](auto* plugin) {
if (plugin->enhance_scene) {
plugin->enhance_scene(plugin, model(), data(), &plugin_scene_);
}
});
}
void App::PreStep(const mjModel* m, mjData* d) {
ForEachPlugin<ModelPlugin>([&](auto* plugin) {
if (plugin->pre_step) {
plugin->pre_step(plugin, m, d);
}
});
}
void App::PostStep(const mjModel* m, mjData* d) {
ForEachPlugin<ModelPlugin>([&](auto* plugin) {
if (plugin->post_step) {
plugin->post_step(plugin, m, d);
}
});
RecordHistoryFrame(sim_history_, timeline_, m, d);
}
void App::LoadHistory(int offset) {
LoadHistoryFrame(sim_history_, model(), data(), offset);
timeline_.SetHistoryIndex(sim_history_.GetIndex());
step_control_.SetPauseState(StepControl::PauseState::kNormalPaused);
}
void App::ApplyTimelineScrub() {
// The GUI only edits timeline_.history_index; compare it against the
// buffer's own cursor rather than a pre-GUI snapshot. A reset triggered from
// inside the GUI (Reset button, keyframe) re-initialises both to index 0, so
// this avoids a redundant LoadHistory(0), which would also force a pause.
if (timeline_.history_index != sim_history_.GetIndex()) {
LoadHistory(timeline_.history_index);
}
}
bool App::Update() {
const auto now = std::chrono::steady_clock::now();
if (last_frame_time_.time_since_epoch().count() != 0) {
const double dt = std::chrono::duration<double>(now - last_frame_time_).count();
const double fps = dt > 0 ? 1.0 / dt : 0;
fps_ = fps_ > 0 ? 0.9 * fps_ + 0.1 * fps : fps;
}
last_frame_time_ = now;
const Window::Status status = window_->NewFrame();
std::unique_lock<std::mutex> lock(physics_mutex_);
// Execute any operations that could not be performed during the actual
// BuildGui() flow.
if (pending_op_) {
pending_op_();
pending_op_ = nullptr;
}
HandleWindowEvents();
HandleMouseEvents();
HandleKeyboardEvents();
ProcessPendingLoads();
PauseState current_pause = step_control_.GetPauseState();
if (current_pause != last_pause_state_) {
load_error_ = "";
last_pause_state_ = current_pause;
}
#ifdef __EMSCRIPTEN__
// Only update the simulation if a popup window is not open. Note that the
// simulation itself will only update if it is not paused.
if (tmp_.file_dialog == UiTempState::FileDialog_None) {
UpdatePhysics();
}
#endif
return status == Window::Status::kRunning && !tmp_.should_exit;
}
void App::Render() {
const float width = window_->GetWidth();
const float height = window_->GetHeight();
const float scale = window_->GetScale();
const mjrRect viewport = {0, 0, static_cast<int>(width * scale),
static_cast<int>(height * scale)};
if (model_scene_) {
std::unique_lock<std::mutex> lock(physics_mutex_);
model_scene_->Sync(model(), data(), viewport, &vis_options_, &perturb_, &camera_,
{plugin_scene_.geoms, static_cast<size_t>(plugin_scene_.ngeom)});
}
imgui_bridge_->Update();
Renderer::View views[2] = {GetSceneView(), GetUxView()};
renderer_->ResizeRenderTarget(Renderer::kWindowRenderTarget, viewport.width, viewport.height);
auto target = renderer_->GetRenderTargetHandle("pixels");
if (IsHeadless(window_->GetGraphicsMode())) {
renderer_->ResizeRenderTarget(target, viewport.width, viewport.height);
views[0].render_target = target;
views[1].render_target = target;
}
renderer_->Render(views);
window_->EndFrame();
window_->Present(renderer_->GetPixels(target));
}
std::span<const std::byte> App::RenderToTexture(mjvCamera* camera, int width, int height,
mjrDrawMode draw_mode) {
auto target = renderer_->GetRenderTargetHandle("tmp");
renderer_->ResizeRenderTarget(target, width, height);
Renderer::View views[1] = {GetSceneView()};
views[0].draw_mode = draw_mode;
views[0].camera = mjv_camera2GLCamera(model(), data(), camera);
views[0].render_target = target;
renderer_->Render(views);
return renderer_->GetPixels(target);
}
Renderer::View App::GetSceneView() {
Renderer::View view;
view.scene = renderer_->GetSceneHandle("studio");
view.camera = mjv_camera2GLCamera(model(), data(), &camera_);
if (render_flags_[mjRND_SEGMENT]) {
if (render_flags_[mjRND_IDCOLOR]) {
view.draw_mode = mjDRAW_MODE_SEGMENTATION_BY_ID;
} else {
view.draw_mode = mjDRAW_MODE_SEGMENTATION_BY_COLOR;
}
} else if (render_flags_[mjRND_DEPTH]) {
view.draw_mode = mjDRAW_MODE_DEPTH;
} else if (render_flags_[mjRND_WIREFRAME]) {
view.draw_mode = mjDRAW_MODE_WIREFRAME;
} else if (vis_options_.flags[mjVIS_ISLAND]) {
view.draw_mode = mjDRAW_MODE_ISLANDS;
} else {
view.draw_mode = mjDRAW_MODE_DEFAULT;
}
view.haze = render_flags_[mjRND_HAZE];
view.skybox = render_flags_[mjRND_SKYBOX];
view.shadows = render_flags_[mjRND_SHADOW];
view.reflections = render_flags_[mjRND_REFLECTION];
view.post_processing = render_flags_[mjRND_POST_PROCESSING];
if (model()->vis.headlight.active) {
view.headlight = Renderer::View::Headlight();
view.headlight->color[0] = model()->vis.headlight.diffuse[0];
view.headlight->color[1] = model()->vis.headlight.diffuse[1];
view.headlight->color[2] = model()->vis.headlight.diffuse[2];
view.headlight->intensity = model_scene_->GetHeadlightIntensity();
}
return view;
}
Renderer::View App::GetUxView() {
const int width = window_->GetWidth() * window_->GetScale();
const int height = window_->GetHeight() * window_->GetScale();
Renderer::View view;
view.scene = renderer_->GetSceneHandle("ux");
view.shadows = false;
view.reflections = false;
view.post_processing = false;
view.camera.orthographic = true;
view.camera.pos[0] = 0.0f;
view.camera.pos[1] = 0.0f;
view.camera.pos[2] = 1.0f;
view.camera.forward[0] = 0.0f;
view.camera.forward[1] = 0.0f;
view.camera.forward[2] = -1.0f;
view.camera.up[0] = 0.0f;
view.camera.up[1] = 1.0f;
view.camera.up[2] = 0.0f;
view.camera.frustum_top = 0.0f;
view.camera.frustum_near = 0.0f;
view.camera.frustum_far = 1.0f;
view.camera.frustum_center = width / 2.0f;
view.camera.frustum_width = width / 2.0f;
view.camera.frustum_bottom = height;
return view;
}
void App::BuildModel(const BuildModelInfo& info) {
if (std::holds_alternative<RecompileFromSpec>(info)) {
const KeyframeSelection saved_key = CaptureKeyframeSelection(/*is_reload=*/true);
auto tmp_holder = spec_editor_.Compile(&vfs_);
if (tmp_holder->ok()) {
preserve_camera_on_load_ = true;
model_holder_ = std::move(tmp_holder);
tmp_.curr_element = nullptr;
RestoreKeyframeSelection(saved_key);
OnModelLoaded("", model_kind_);
} else {
RecordLoadError(tmp_holder->error());
}
} else if (std::holds_alternative<RecompileModel>(info)) {
const KeyframeSelection saved_key = CaptureKeyframeSelection(/*is_reload=*/true);
tmp_.curr_element = nullptr;
model_holder_->Recompile();
if (!model_holder_->ok()) {
SetLoadError(std::string(model_holder_->error()));
return;
}
RestoreKeyframeSelection(saved_key);
InitModelScene();
ResetHistory(sim_history_, timeline_, has_model() ? model() : nullptr,
has_data() ? data() : nullptr);
timer_prev_ = {};
profiler_.ResetTimers();
} else if (std::holds_alternative<EmptyModel>(info)) {
model_holder_.reset();
tmp_.curr_element = nullptr;
mj_deleteVFS(&vfs_);
mj_defaultVFS(&vfs_);
model_holder_ = ModelHolder::FromSpec(mj_makeSpec(), &vfs_);
tmp_.key_idx = -1;
last_buffer_.clear();
last_content_type_.clear();
OnModelLoaded("", kEmptyModel);
spec_editor_.Reset(*spec());
} else if (std::holds_alternative<FileModel>(info)) {
auto& load = std::get<FileModel>(info);
const std::string resolved_file = ResolveFile(load.filepath, search_paths_);
const KeyframeSelection saved_key = CaptureKeyframeSelection(preserve_camera_on_load_);
model_holder_.reset();
tmp_.curr_element = nullptr;
mj_deleteVFS(&vfs_);
mj_defaultVFS(&vfs_);
model_holder_ = ModelHolder::FromFile(resolved_file, &vfs_);
if (model_holder_->ok()) {
last_buffer_.clear();
last_content_type_.clear();
RestoreKeyframeSelection(saved_key);
OnModelLoaded(load.filepath, kModelFromFile);
if (spec()) {
spec_editor_.Reset(*spec());
} else {
spec_editor_.Reset();
}
UpdateFilePaths(resolved_file);
if (model() && model()->names) {
// Assumes the first string in the model is the name of the model
// itself.
window_->SetTitle(app_title_ + " : " + std::string(model()->names));
} else {
window_->SetTitle(app_title_ + " : " +
std::filesystem::path(load.filepath).stem().string());
}
} else {
SetLoadError(std::string(model_holder_->error()));
// Keep track of the attempted load in case the user fixes the error and
// tries to reload the same file again.
model_path_ = resolved_file;
}
} else if (std::holds_alternative<BufferModel>(info)) {
auto& load = std::get<BufferModel>(info);
const KeyframeSelection saved_key = CaptureKeyframeSelection(preserve_camera_on_load_);
model_holder_.reset();
tmp_.curr_element = nullptr;
mj_deleteVFS(&vfs_);
mj_defaultVFS(&vfs_);
model_holder_ = ModelHolder::FromBuffer(load.buffer, load.content_type, load.name, &vfs_);
if (model_holder_->ok()) {
last_buffer_.assign(load.buffer.begin(), load.buffer.end());
last_content_type_ = std::string(load.content_type);
RestoreKeyframeSelection(saved_key);
OnModelLoaded(load.name, kModelFromFile);
} else {
SetLoadError(std::string(model_holder_->error()));
}
if (spec()) {
spec_editor_.Reset(*spec());
} else {
spec_editor_.Reset();
}
}
}
void App::OnModelLoaded(std::string_view filename, ModelKind model_kind) {
load_error_ = "";
tmp_.curr_element = nullptr;
timer_prev_ = {};
profiler_.Clear();
if (!model_holder_->warning().empty()) {
load_error_ = model_holder_->warning();
}
model_path_ = std::string(filename);
if (model_kind_ == kEmptyModel) {
step_control_.SetPauseState(PauseState::kUnpaused);
}
model_kind_ = model_kind;
if (model_kind_ == kEmptyModel || !load_error_.empty()) {
step_control_.SetPauseState(PauseState::kNormalPaused);
}
// Reset/reinitialize everything that depends on the new mjModel.
mjModel* model = model_holder_->model();
InitModelScene();
ResetPhysics();
if (!preserve_camera_on_load_) {
const int model_cam = model->vis.global.cameraid;
if (model_cam >= 0 && model_cam < model->ncam) {
tmp_.camera_idx = SetCamera(model, &camera_, model_cam);
} else {
mjv_defaultFreeCamera(model, &camera_);
}
}
preserve_camera_on_load_ = false;
// Initialize the speed based on the model's default real-time setting.
float min_error = FLT_MAX;
const float desired = mju_log(100 * model->vis.global.realtime);
for (int i = 0; i < kPercentRealTime.size(); ++i) {
const float speed = std::stof(kPercentRealTime[i]);
const float error = mju_abs(mju_log(speed) - desired);
if (error < min_error) {
min_error = error;
SetSpeedIndex(i);
}
}
ForEachPlugin<ModelPlugin>([&](auto* plugin) {
if (plugin->post_model_loaded) {
plugin->post_model_loaded(plugin, model, model_path_.c_str());
}
});
tmp_.update_threadpool = true;
last_pause_state_ = step_control_.GetPauseState();
}
void App::InitModelScene() {
// Ensure all entities in the scene are removed before populating it again.
model_scene_.reset();
if (has_model()) {
mjrfContext* ctx = renderer_->GetContext();
mjrfScene* scene = renderer_->GetScene("studio");
model_scene_ = std::make_unique<ModelScene>(ctx, scene, model(), DrawTextAt);
}
}
void App::ProcessPendingLoads() {
if (pending_reload_) {
pending_reload_ = false;
if (model_kind_ == kModelFromFile || (model_kind_ == kEmptyModel && !model_path_.empty())) {
pending_load_ = model_path_;
preserve_camera_on_load_ = true;
}
}
// Check to see if we need to load a new model.
if (pending_load_.has_value()) {
std::string load_data = std::move(pending_load_.value());
pending_load_.reset();
if (load_data.empty()) {
BuildModel(EmptyModel{});
} else if (!last_buffer_.empty() && load_data == model_path_) {
BuildModel(BufferModel{last_buffer_, last_content_type_, load_data});
} else {
BuildModel(FileModel(load_data));
}
}
if (recompile_spec_) {
recompile_spec_ = false;
BuildModel(RecompileFromSpec{});
}
// Allow plugins to edit the spec as well.
ForEachPlugin<SpecEditorPlugin>([&](auto* plugin) {
if (plugin->pre_compile) {
if (plugin->pre_compile(plugin, spec(), model(), data(), &camera_)) {
BuildModel(RecompileModel{});
if (plugin->post_compile) {
plugin->post_compile(plugin, spec(), model(), data());
}
};
}
});
// Check plugins to see if we need to load a new model.
ForEachPlugin<ModelPlugin>([&](auto* plugin) {
if (plugin->get_model_to_load) {
char model_name[1000] = "";
char content_type[1000] = "";
int size = 0;
const char* buf = plugin->get_model_to_load(plugin, &size, content_type, sizeof(content_type),
model_name, sizeof(model_name));
if (buf && buf == model_name) {
BuildModel(FileModel(model_name));
} else if (buf && size) {
const std::byte* bytes = reinterpret_cast<const std::byte*>(buf);
BuildModel(BufferModel{{bytes, bytes + size}, content_type, model_name});
}
}
});
}
void App::HandleWindowEvents() {
const std::string drop_file = window_->GetDropFile();
if (!drop_file.empty()) {
RequestModelLoad(drop_file);
}
}
void App::HandleMouseEvents() {
auto& io = ImGui::GetIO();
if (io.WantCaptureMouse) {
return;
}
if (!has_model() || !has_data()) {
return;
}
// Normalize mouse positions and movement to display size.
const float mouse_x = io.MousePos.x / io.DisplaySize.x;
const float mouse_y = io.MousePos.y / io.DisplaySize.y;
const float mouse_dx = io.MouseDelta.x / io.DisplaySize.x;
const float mouse_dy = io.MouseDelta.y / io.DisplaySize.y;
const bool is_mouse_moving = (mouse_dx != 0.0f || mouse_dy != 0.0f);
const bool is_any_mouse_down = ImGui::IsMouseDown(ImGuiMouseButton_Left) ||
ImGui::IsMouseDown(ImGuiMouseButton_Right) ||
ImGui::IsMouseDown(ImGuiMouseButton_Middle);
const bool is_mouse_dragging = is_mouse_moving && is_any_mouse_down;
// If no mouse buttons are down, end any active perturbations.
if (!is_any_mouse_down) {
perturb_.active = 0;
}
// Handle perturbation mouse actions.
if (is_mouse_dragging && io.KeyCtrl) {
if (perturb_.select > 0) {
mjtMouse action = mjMOUSE_NONE;
if (ImGui::IsMouseDown(ImGuiMouseButton_Left)) {
if (io.KeyAlt) {
action = io.KeyShift ? mjMOUSE_MOVE_H : mjMOUSE_MOVE_V;
} else {
action = io.KeyShift ? mjMOUSE_ROTATE_H : mjMOUSE_ROTATE_V;
}
} else if (ImGui::IsMouseDown(ImGuiMouseButton_Right)) {
action = io.KeyShift ? mjMOUSE_MOVE_H : mjMOUSE_MOVE_V;
} else if (ImGui::IsMouseDown(ImGuiMouseButton_Middle)) {
action = mjMOUSE_ZOOM;
}
const mjtPertBit active =
(action == mjMOUSE_MOVE_V || action == mjMOUSE_MOVE_H) ? mjPERT_TRANSLATE : mjPERT_ROTATE;
if (active != perturb_.active) {
InitPerturb(model(), data(), &camera_, &perturb_, active);
}
MovePerturb(model(), data(), &camera_, &perturb_, action, mouse_dx, mouse_dy);
}
}
// Camera drags and wheel (Ctrl drags are left to the perturbation above).
MoveCameraWithMouse(model(), &camera_, tmp_.camera_idx == kFreeCameraIdx, ReadImGuiCameraInput());
// Left double click.
if (ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) {
PickResult picked =
Pick(model(), data(), &camera_, mouse_x, mouse_y, window_->GetAspectRatio(), &vis_options_);
if (picked.body >= 0) {
perturb_.select = picked.body;
perturb_.flexselect = picked.flex;
perturb_.skinselect = picked.skin;
// Select the corresponding element in the spec.
tmp_.curr_element = nullptr;
if (has_spec()) {
mjsElement* element = mjs_firstElement(spec(), mjOBJ_BODY);
while (element) {
if (mjs_getId(element) == picked.body) {
tmp_.curr_element = element;
break;
}
element = mjs_nextElement(spec(), element);
}
}
// Compute the local position of the selected object in the world.
mjtNum tmp[3];
mju_sub3(tmp, picked.point, data()->xpos + 3 * picked.body);
mju_mulMatTVec(perturb_.localpos, data()->xmat + 9 * picked.body, tmp, 3, 3);
} else {
mjv_defaultPerturb(&perturb_);
}
}
// Right double click.
if (ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Right)) {
PickResult picked =
Pick(model(), data(), &camera_, mouse_x, mouse_y, window_->GetAspectRatio(), &vis_options_);
mju_copy3(camera_.lookat, picked.point);
if (picked.body > 0 && io.KeyCtrl) {
// Switch camera to tracking mode and track the selected body.
camera_.type = mjCAMERA_TRACKING;
camera_.trackbodyid = picked.body;
camera_.fixedcamid = -1;
tmp_.camera_idx = kTrackingCameraIdx;
}
}
}
void App::HandleKeyboardEvents() {
if (ImGui::GetIO().WantCaptureKeyboard) {
return;
}
constexpr auto ImGuiMod_CtrlShift = ImGuiMod_Ctrl | ImGuiMod_Shift;
bool is_freecam_wasd = tmp_.camera_idx == kFreeCameraIdx;
// Menu shortcuts.
if (ImGui_IsChordJustPressed(ImGuiKey_O | ImGuiMod_Ctrl)) {
tmp_.file_dialog = UiTempState::FileDialog_Load;
} else if (ImGui_IsChordJustPressed(ImGuiKey_S | ImGuiMod_CtrlShift)) {
tmp_.file_dialog = UiTempState::FileDialog_SaveMjb;
} else if (ImGui_IsChordJustPressed(ImGuiKey_S | ImGuiMod_Ctrl)) {
tmp_.file_dialog = UiTempState::FileDialog_SaveXml;
} else if (ImGui_IsChordJustPressed(ImGuiKey_M | ImGuiMod_Ctrl)) {
tmp_.file_dialog = UiTempState::FileDialog_PrintModel;
} else if (ImGui_IsChordJustPressed(ImGuiKey_D | ImGuiMod_Ctrl)) {
tmp_.file_dialog = UiTempState::FileDialog_PrintData;
} else if (ImGui_IsChordJustPressed(ImGuiKey_P | ImGuiMod_Ctrl)) {
tmp_.file_dialog = UiTempState::FileDialog_SaveScreenshot;
} else if (ImGui_IsChordJustPressed(ImGuiKey_C | ImGuiMod_Ctrl)) {
std::string keyframe = KeyframeToString(model(), data(), false);
MaybeSaveToClipboard(keyframe);
} else if (ImGui_IsChordJustPressed(ImGuiKey_L | ImGuiMod_Ctrl)) {
RequestModelReload();
} else if (ImGui_IsChordJustPressed(ImGuiKey_Q | ImGuiMod_Ctrl)) {
tmp_.should_exit = true;