Rename a few functions and variables to be a bit more Googley.

PiperOrigin-RevId: 523963645
Change-Id: Ife7ed3f44aa83c64dfbdc3ca78ee6de2092b0d63
This commit is contained in:
Saran Tunyasuvunakool
2023-04-13 04:23:41 -07:00
committed by Copybara-Service
parent 2e23594fe8
commit 5646c905cd
5 changed files with 191 additions and 190 deletions
+17 -16
View File
@@ -52,19 +52,20 @@ PYBIND11_MODULE(_simulate, pymodule) {
})) }))
.def( .def(
"renderloop", "renderloop",
[](mujoco::Simulate& simulate) { simulate.renderloop(); }, [](mujoco::Simulate& simulate) { simulate.RenderLoop(); },
py::call_guard<py::gil_scoped_release>()) py::call_guard<py::gil_scoped_release>())
.def( .def(
"load", "load",
[](mujoco::Simulate& simulate, const std::string& path, [](mujoco::Simulate& simulate, const std::string& path,
MjModelWrapper& m, MjDataWrapper& d) { MjModelWrapper& m, MjDataWrapper& d) {
simulate.load(path.c_str(), m.get(), d.get()); simulate.Load(m.get(), d.get(), path.c_str());
}, },
py::call_guard<py::gil_scoped_release>()) py::call_guard<py::gil_scoped_release>())
.def("applyposepertubations", &mujoco::Simulate::applyposepertubations, .def("apply_pose_perturbations",
&mujoco::Simulate::ApplyPosePerturbations,
py::call_guard<py::gil_scoped_release>()) py::call_guard<py::gil_scoped_release>())
.def("applyforceperturbations", .def("apply_force_perturbations",
&mujoco::Simulate::applyforceperturbations, &mujoco::Simulate::ApplyForcePerturbations,
py::call_guard<py::gil_scoped_release>()) py::call_guard<py::gil_scoped_release>())
.def( .def(
@@ -74,18 +75,18 @@ PYBIND11_MODULE(_simulate, pymodule) {
}, },
py::call_guard<py::gil_scoped_release>(), py::call_guard<py::gil_scoped_release>(),
py::return_value_policy::reference) py::return_value_policy::reference)
.def_readonly("ctrlnoisestd", &mujoco::Simulate::ctrlnoisestd, .def_readonly("ctrl_noise_std", &mujoco::Simulate::ctrl_noise_std,
py::call_guard<py::gil_scoped_release>()) py::call_guard<py::gil_scoped_release>())
.def_readonly("ctrlnoiserate", &mujoco::Simulate::ctrlnoiserate, .def_readonly("ctrl_noise_rate", &mujoco::Simulate::ctrl_noise_rate,
py::call_guard<py::gil_scoped_release>()) py::call_guard<py::gil_scoped_release>())
.def_readonly("real_time_index", &mujoco::Simulate::realTimeIndex, .def_readonly("real_time_index", &mujoco::Simulate::real_time_index,
py::call_guard<py::gil_scoped_release>()) py::call_guard<py::gil_scoped_release>())
.def_readwrite("speed_changed", &mujoco::Simulate::speedChanged, .def_readwrite("speed_changed", &mujoco::Simulate::speed_changed,
py::call_guard<py::gil_scoped_release>()) py::call_guard<py::gil_scoped_release>())
.def_readwrite("measured_slowdown", &mujoco::Simulate::measuredSlowdown, .def_readwrite("measured_slowdown", &mujoco::Simulate::measured_slowdown,
py::call_guard<py::gil_scoped_release>()) py::call_guard<py::gil_scoped_release>())
.def_readonly("refresh_rate", &mujoco::Simulate::refreshRate, .def_readonly("refresh_rate", &mujoco::Simulate::refresh_rate,
py::call_guard<py::gil_scoped_release>()) py::call_guard<py::gil_scoped_release>())
.def_readonly("busywait", &mujoco::Simulate::busywait, .def_readonly("busywait", &mujoco::Simulate::busywait,
@@ -140,15 +141,15 @@ PYBIND11_MODULE(_simulate, pymodule) {
.def_property( .def_property(
"load_error", "load_error",
[](mujoco::Simulate& simulate) -> std::string { [](mujoco::Simulate& simulate) -> std::string {
return simulate.loadError; return simulate.load_error;
}, },
[](mujoco::Simulate& simulate, const std::string& error) { [](mujoco::Simulate& simulate, const std::string& error) {
const auto max_length = sizeof_arr(simulate.loadError); const auto max_length = sizeof_arr(simulate.load_error);
std::strncpy(simulate.loadError, error.c_str(), max_length - 1); std::strncpy(simulate.load_error, error.c_str(), max_length - 1);
simulate.loadError[max_length - 1] = '\0'; simulate.load_error[max_length - 1] = '\0';
}); });
pymodule.def("setglfwdlhandle", [](std::uintptr_t dlhandle) { pymodule.def("set_glfw_dlhandle", [](std::uintptr_t dlhandle) {
mujoco::Glfw(reinterpret_cast<void*>(dlhandle)); mujoco::Glfw(reinterpret_cast<void*>(dlhandle));
}); });
} }
+12 -12
View File
@@ -33,7 +33,7 @@ import numpy as np
if not glfw._glfw: # pylint: disable=protected-access if not glfw._glfw: # pylint: disable=protected-access
raise RuntimeError('GLFW dynamic library handle is not available') raise RuntimeError('GLFW dynamic library handle is not available')
else: else:
_simulate.setglfwdlhandle(glfw._glfw._handle) # pylint: disable=protected-access _simulate.set_glfw_dlhandle(glfw._glfw._handle) # pylint: disable=protected-access
# Logarithmically spaced realtime slow-down coefficients (percent). # Logarithmically spaced realtime slow-down coefficients (percent).
PERCENT_REALTIME = ( PERCENT_REALTIME = (
@@ -100,7 +100,7 @@ def _reload(
assert m is not None and d is not None assert m is not None and d is not None
path = load_tuple[2] if len(load_tuple) == 3 else '' path = load_tuple[2] if len(load_tuple) == 3 else ''
simulate.load(path, m, d) simulate.load(m, d, path)
return m, d return m, d
@@ -109,7 +109,7 @@ def _physics_loop(simulate: Simulate, loader: Optional[_InternalLoaderType]):
"""Physics loop for the GUI, to be run in a separate thread.""" """Physics loop for the GUI, to be run in a separate thread."""
m: mujoco.MjModel = None m: mujoco.MjModel = None
d: mujoco.MjData = None d: mujoco.MjData = None
ctrlnoise = np.array([]) ctrl_noise = np.array([])
reload = True reload = True
# CPU-sim synchronization point. # CPU-sim synchronization point.
@@ -131,7 +131,7 @@ def _physics_loop(simulate: Simulate, loader: Optional[_InternalLoaderType]):
result = _reload(simulate, loader) result = _reload(simulate, loader)
if result is not None: if result is not None:
m, d = result m, d = result
ctrlnoise = np.zeros((m.nu,)) ctrl_noise = np.zeros((m.nu,))
reload = False reload = False
@@ -152,19 +152,19 @@ def _physics_loop(simulate: Simulate, loader: Optional[_InternalLoaderType]):
elapsedsim = d.time - syncsim elapsedsim = d.time - syncsim
# Inject noise. # Inject noise.
if simulate.ctrlnoisestd != 0.0: if simulate.ctrl_noise_std != 0.0:
# Convert rate and scale to discrete time (Ornstein–Uhlenbeck). # Convert rate and scale to discrete time (Ornstein–Uhlenbeck).
rate = math.exp(-m.opt.timestep / rate = math.exp(-m.opt.timestep /
max(simulate.ctrlnoiserate, mujoco.mjMINVAL)) max(simulate.ctrl_noise_rate, mujoco.mjMINVAL))
scale = simulate.ctrlnoisestd * math.sqrt(1 - rate * rate) scale = simulate.ctrl_noise_std * math.sqrt(1 - rate * rate)
for i in range(m.nu): for i in range(m.nu):
# Update noise. # Update noise.
ctrlnoise[i] = ( ctrl_noise[i] = (rate * ctrl_noise[i] +
rate * ctrlnoise[i] + scale * mujoco.mju_standardNormal(None)) scale * mujoco.mju_standardNormal(None))
# Apply noise. # Apply noise.
d.ctrl[i] = ctrlnoise[i] d.ctrl[i] = ctrl_noise[i]
# Requested slow-down factor. # Requested slow-down factor.
slowdown = 100 / PERCENT_REALTIME[simulate.real_time_index] slowdown = 100 / PERCENT_REALTIME[simulate.real_time_index]
@@ -183,8 +183,8 @@ def _physics_loop(simulate: Simulate, loader: Optional[_InternalLoaderType]):
# Clear old perturbations, apply new. # Clear old perturbations, apply new.
d.xfrc_applied[:, :] = 0 d.xfrc_applied[:, :] = 0
simulate.applyposepertubations(0) # Move mocap bodies only. simulate.apply_pose_perturbations(0) # Move mocap bodies only.
simulate.applyforceperturbations() simulate.apply_force_perturbations()
# Run single step, let next iteration deal with timing. # Run single step, let next iteration deal with timing.
mujoco.mj_step(m, d) mujoco.mj_step(m, d)
+18 -18
View File
@@ -233,7 +233,7 @@ mjModel* LoadModel(const char* file, mj::Simulate& sim) {
} }
} }
mju::strcpy_arr(sim.loadError, loadError); mju::strcpy_arr(sim.load_error, loadError);
if (!mnew) { if (!mnew) {
std::printf("%s\n", loadError); std::printf("%s\n", loadError);
@@ -265,7 +265,7 @@ void PhysicsLoop(mj::Simulate& sim) {
mjData* dnew = nullptr; mjData* dnew = nullptr;
if (mnew) dnew = mj_makeData(mnew); if (mnew) dnew = mj_makeData(mnew);
if (dnew) { if (dnew) {
sim.load(sim.dropfilename, mnew, dnew); sim.Load(mnew, dnew, sim.dropfilename);
mj_deleteData(d); mj_deleteData(d);
mj_deleteModel(m); mj_deleteModel(m);
@@ -287,7 +287,7 @@ void PhysicsLoop(mj::Simulate& sim) {
mjData* dnew = nullptr; mjData* dnew = nullptr;
if (mnew) dnew = mj_makeData(mnew); if (mnew) dnew = mj_makeData(mnew);
if (dnew) { if (dnew) {
sim.load(sim.filename, mnew, dnew); sim.Load(mnew, dnew, sim.filename);
mj_deleteData(d); mj_deleteData(d);
mj_deleteModel(m); mj_deleteModel(m);
@@ -327,10 +327,10 @@ void PhysicsLoop(mj::Simulate& sim) {
double elapsedSim = d->time - syncSim; double elapsedSim = d->time - syncSim;
// inject noise // inject noise
if (sim.ctrlnoisestd) { if (sim.ctrl_noise_std) {
// convert rate and scale to discrete time (Ornstein–Uhlenbeck) // convert rate and scale to discrete time (Ornstein–Uhlenbeck)
mjtNum rate = mju_exp(-m->opt.timestep / mju_max(sim.ctrlnoiserate, mjMINVAL)); mjtNum rate = mju_exp(-m->opt.timestep / mju_max(sim.ctrl_noise_rate, mjMINVAL));
mjtNum scale = sim.ctrlnoisestd * mju_sqrt(1-rate*rate); mjtNum scale = sim.ctrl_noise_std * mju_sqrt(1-rate*rate);
for (int i=0; i<m->nu; i++) { for (int i=0; i<m->nu; i++) {
// update noise // update noise
@@ -342,7 +342,7 @@ void PhysicsLoop(mj::Simulate& sim) {
} }
// requested slow-down factor // requested slow-down factor
double slowdown = 100 / sim.percentRealTime[sim.realTimeIndex]; double slowdown = 100 / sim.percentRealTime[sim.real_time_index];
// misalignment condition: distance from target sim time is bigger than syncmisalign // misalignment condition: distance from target sim time is bigger than syncmisalign
bool misaligned = bool misaligned =
@@ -350,16 +350,16 @@ void PhysicsLoop(mj::Simulate& sim) {
// out-of-sync (for any reason): reset sync times, step // out-of-sync (for any reason): reset sync times, step
if (elapsedSim < 0 || elapsedCPU.count() < 0 || syncCPU.time_since_epoch().count() == 0 || if (elapsedSim < 0 || elapsedCPU.count() < 0 || syncCPU.time_since_epoch().count() == 0 ||
misaligned || sim.speedChanged) { misaligned || sim.speed_changed) {
// re-sync // re-sync
syncCPU = startCPU; syncCPU = startCPU;
syncSim = d->time; syncSim = d->time;
sim.speedChanged = false; sim.speed_changed = false;
// clear old perturbations, apply new // clear old perturbations, apply new
mju_zero(d->xfrc_applied, 6*m->nbody); mju_zero(d->xfrc_applied, 6*m->nbody);
sim.applyposepertubations(0); // move mocap bodies only sim.ApplyPosePerturbations(0); // move mocap bodies only
sim.applyforceperturbations(); sim.ApplyForcePerturbations();
// run single step, let next iteration deal with timing // run single step, let next iteration deal with timing
mj_step(m, d); mj_step(m, d);
@@ -370,22 +370,22 @@ void PhysicsLoop(mj::Simulate& sim) {
bool measured = false; bool measured = false;
mjtNum prevSim = d->time; mjtNum prevSim = d->time;
double refreshTime = simRefreshFraction/sim.refreshRate; double refreshTime = simRefreshFraction/sim.refresh_rate;
// step while sim lags behind cpu and within refreshTime // step while sim lags behind cpu and within refreshTime
while (Seconds((d->time - syncSim)*slowdown) < mj::Simulate::Clock::now() - syncCPU && while (Seconds((d->time - syncSim)*slowdown) < mj::Simulate::Clock::now() - syncCPU &&
mj::Simulate::Clock::now() - startCPU < Seconds(refreshTime)) { mj::Simulate::Clock::now() - startCPU < Seconds(refreshTime)) {
// measure slowdown before first step // measure slowdown before first step
if (!measured && elapsedSim) { if (!measured && elapsedSim) {
sim.measuredSlowdown = sim.measured_slowdown =
std::chrono::duration<double>(elapsedCPU).count() / elapsedSim; std::chrono::duration<double>(elapsedCPU).count() / elapsedSim;
measured = true; measured = true;
} }
// clear old perturbations, apply new // clear old perturbations, apply new
mju_zero(d->xfrc_applied, 6*m->nbody); mju_zero(d->xfrc_applied, 6*m->nbody);
sim.applyposepertubations(0); // move mocap bodies only sim.ApplyPosePerturbations(0); // move mocap bodies only
sim.applyforceperturbations(); sim.ApplyForcePerturbations();
// call mj_step // call mj_step
mj_step(m, d); mj_step(m, d);
@@ -401,7 +401,7 @@ void PhysicsLoop(mj::Simulate& sim) {
// paused // paused
else { else {
// apply pose perturbation // apply pose perturbation
sim.applyposepertubations(1); // move mocap and dynamic bodies sim.ApplyPosePerturbations(1); // move mocap and dynamic bodies
// run mj_forward, to update rendering and joint sliders // run mj_forward, to update rendering and joint sliders
mj_forward(m, d); mj_forward(m, d);
@@ -420,7 +420,7 @@ void PhysicsThread(mj::Simulate* sim, const char* filename) {
m = LoadModel(filename, *sim); m = LoadModel(filename, *sim);
if (m) d = mj_makeData(m); if (m) d = mj_makeData(m);
if (d) { if (d) {
sim->load(filename, m, d); sim->Load(m, d, filename);
mj_forward(m, d); mj_forward(m, d);
// allocate ctrlnoise // allocate ctrlnoise
@@ -481,7 +481,7 @@ int main(int argc, const char** argv) {
std::thread physicsthreadhandle(&PhysicsThread, sim.get(), filename); std::thread physicsthreadhandle(&PhysicsThread, sim.get(), filename);
// start simulation UI loop (blocking call) // start simulation UI loop (blocking call)
sim->renderloop(); sim->RenderLoop();
physicsthreadhandle.join(); physicsthreadhandle.join();
return 0; return 0;
+119 -119
View File
@@ -138,7 +138,7 @@ const char help_title[] =
//-------------------------------- profiler, sensor, info, watch ----------------------------------- //-------------------------------- profiler, sensor, info, watch -----------------------------------
// init profiler figures // init profiler figures
void profilerinit(mj::Simulate* sim) { void InitializeProfiler(mj::Simulate* sim) {
// set figures to default // set figures to default
mjv_defaultFigure(&sim->figconstraint); mjv_defaultFigure(&sim->figconstraint);
mjv_defaultFigure(&sim->figcost); mjv_defaultFigure(&sim->figcost);
@@ -231,7 +231,7 @@ void profilerinit(mj::Simulate* sim) {
} }
// update profiler figures // update profiler figures
void profilerupdate(mj::Simulate* sim) { void UpdateProfiler(mj::Simulate* sim) {
// update constraint figure // update constraint figure
sim->figconstraint.linepnt[0] = mjMIN(mjMIN(sim->d->solver_iter, mjNSOLVER), mjMAXLINEPNT); sim->figconstraint.linepnt[0] = mjMIN(mjMIN(sim->d->solver_iter, mjNSOLVER), mjMAXLINEPNT);
for (int i=1; i<5; i++) { for (int i=1; i<5; i++) {
@@ -338,7 +338,7 @@ void profilerupdate(mj::Simulate* sim) {
} }
// show profiler figures // show profiler figures
void profilershow(mj::Simulate* sim, mjrRect rect) { void ShowProfiler(mj::Simulate* sim, mjrRect rect) {
mjrRect viewport = { mjrRect viewport = {
rect.left + rect.width - rect.width/4, rect.left + rect.width - rect.width/4,
rect.bottom, rect.bottom,
@@ -356,7 +356,7 @@ void profilershow(mj::Simulate* sim, mjrRect rect) {
// init sensor figure // init sensor figure
void sensorinit(mj::Simulate* sim) { void InitializeSensor(mj::Simulate* sim) {
mjvFigure& figsensor = sim->figsensor; mjvFigure& figsensor = sim->figsensor;
// set figure to default // set figure to default
@@ -386,7 +386,7 @@ void sensorinit(mj::Simulate* sim) {
} }
// update sensor figure // update sensor figure
void sensorupdate(mj::Simulate* sim) { void UpdateSensor(mj::Simulate* sim) {
mjModel* m = sim->m; mjModel* m = sim->m;
mjvFigure& figsensor = sim->figsensor; mjvFigure& figsensor = sim->figsensor;
static const int maxline = 10; static const int maxline = 10;
@@ -436,7 +436,7 @@ void sensorupdate(mj::Simulate* sim) {
} }
// show sensor figure // show sensor figure
void sensorshow(mj::Simulate* sim, mjrRect rect) { void ShowSensor(mj::Simulate* sim, mjrRect rect) {
// constant width with and without profiler // constant width with and without profiler
int width = sim->profiler ? rect.width/3 : rect.width/4; int width = sim->profiler ? rect.width/3 : rect.width/4;
@@ -451,7 +451,7 @@ void sensorshow(mj::Simulate* sim, mjrRect rect) {
} }
// prepare info text // prepare info text
void infotext(mj::Simulate* sim, void UpdateInfoText(mj::Simulate* sim,
char (&title)[mj::Simulate::kMaxFilenameLength], char (&title)[mj::Simulate::kMaxFilenameLength],
char (&content)[mj::Simulate::kMaxFilenameLength], char (&content)[mj::Simulate::kMaxFilenameLength],
double interval) { double interval) {
@@ -507,12 +507,12 @@ void infotext(mj::Simulate* sim,
} }
// sprintf forwarding, to avoid compiler warning in x-macro // sprintf forwarding, to avoid compiler warning in x-macro
void printfield(char (&str)[mjMAXUINAME], void* ptr) { void PrintField(char (&str)[mjMAXUINAME], void* ptr) {
mju::sprintf_arr(str, "%g", *static_cast<mjtNum*>(ptr)); mju::sprintf_arr(str, "%g", *static_cast<mjtNum*>(ptr));
} }
// update watch // update watch
void watch(mj::Simulate* sim) { void UpdateWatch(mj::Simulate* sim) {
// clear // clear
sim->ui0.sect[SECT_WATCH].item[2].multi.nelem = 1; sim->ui0.sect[SECT_WATCH].item[2].multi.nelem = 1;
mju::strcpy_arr(sim->ui0.sect[SECT_WATCH].item[2].multi.name[0], "invalid field"); mju::strcpy_arr(sim->ui0.sect[SECT_WATCH].item[2].multi.name[0], "invalid field");
@@ -525,7 +525,7 @@ void watch(mj::Simulate* sim) {
if (!mju::strcmp_arr(#NAME, sim->field) && \ if (!mju::strcmp_arr(#NAME, sim->field) && \
!mju::strcmp_arr(#TYPE, "mjtNum")) { \ !mju::strcmp_arr(#TYPE, "mjtNum")) { \
if (sim->index >= 0 && sim->index < sim->m->NR * NC) { \ if (sim->index >= 0 && sim->index < sim->m->NR * NC) { \
printfield(sim->ui0.sect[SECT_WATCH].item[2].multi.name[0], sim->d->NAME + sim->index); \ PrintField(sim->ui0.sect[SECT_WATCH].item[2].multi.name[0], sim->d->NAME + sim->index); \
} else { \ } else { \
mju::strcpy_arr(sim->ui0.sect[SECT_WATCH].item[2].multi.name[0], "invalid index"); \ mju::strcpy_arr(sim->ui0.sect[SECT_WATCH].item[2].multi.name[0], "invalid index"); \
} \ } \
@@ -540,7 +540,7 @@ void watch(mj::Simulate* sim) {
//---------------------------------- UI construction ----------------------------------------------- //---------------------------------- UI construction -----------------------------------------------
// make physics section of UI // make physics section of UI
void makephysics(mj::Simulate* sim, int oldstate) { void MakePhysicsSection(mj::Simulate* sim, int oldstate) {
mjOption& opt = sim->m->opt; mjOption& opt = sim->m->opt;
mjuiDef defPhysics[] = { mjuiDef defPhysics[] = {
@@ -608,7 +608,7 @@ void makephysics(mj::Simulate* sim, int oldstate) {
// make rendering section of UI // make rendering section of UI
void makerendering(mj::Simulate* sim, int oldstate) { void MakeRenderingSection(mj::Simulate* sim, int oldstate) {
mjuiDef defRendering[] = { mjuiDef defRendering[] = {
{ {
mjITEM_SECTION, mjITEM_SECTION,
@@ -628,7 +628,7 @@ void makerendering(mj::Simulate* sim, int oldstate) {
mjITEM_SELECT, mjITEM_SELECT,
"Label", "Label",
2, 2,
&(sim->vopt.label), &(sim->opt.label),
"None\nBody\nJoint\nGeom\nSite\nCamera\nLight\nTendon\n" "None\nBody\nJoint\nGeom\nSite\nCamera\nLight\nTendon\n"
"Actuator\nConstraint\nSkin\nSelection\nSel Pnt\nContact\nForce" "Actuator\nConstraint\nSkin\nSelection\nSel Pnt\nContact\nForce"
}, },
@@ -636,7 +636,7 @@ void makerendering(mj::Simulate* sim, int oldstate) {
mjITEM_SELECT, mjITEM_SELECT,
"Frame", "Frame",
2, 2,
&(sim->vopt.frame), &(sim->opt.frame),
"None\nBody\nGeom\nSite\nCamera\nLight\nContact\nWorld" "None\nBody\nGeom\nSite\nCamera\nLight\nContact\nWorld"
}, },
{ {
@@ -703,7 +703,7 @@ void makerendering(mj::Simulate* sim, int oldstate) {
} else { } else {
mju::sprintf_arr(defFlag[0].other, ""); mju::sprintf_arr(defFlag[0].other, "");
} }
defFlag[0].pdata = sim->vopt.flags + i; defFlag[0].pdata = sim->opt.flags + i;
mjui_add(&sim->ui0, defFlag); mjui_add(&sim->ui0, defFlag);
} }
@@ -729,8 +729,8 @@ void makerendering(mj::Simulate* sim, int oldstate) {
// make group section of UI // make group section of UI
void makegroup(mj::Simulate* sim, int oldstate) { void MakeGroupSection(mj::Simulate* sim, int oldstate) {
mjvOption& vopt = sim->vopt; mjvOption& vopt = sim->opt;
mjuiDef defGroup[] = { mjuiDef defGroup[] = {
{mjITEM_SECTION, "Group enable", oldstate, nullptr, "AG"}, {mjITEM_SECTION, "Group enable", oldstate, nullptr, "AG"},
{mjITEM_SEPARATOR, "Geom groups", 1}, {mjITEM_SEPARATOR, "Geom groups", 1},
@@ -783,7 +783,7 @@ void makegroup(mj::Simulate* sim, int oldstate) {
} }
// make joint section of UI // make joint section of UI
void makejoint(mj::Simulate* sim, int oldstate) { void MakeJointSection(mj::Simulate* sim, int oldstate) {
mjuiDef defJoint[] = { mjuiDef defJoint[] = {
{mjITEM_SECTION, "Joint", oldstate, nullptr, "AJ"}, {mjITEM_SECTION, "Joint", oldstate, nullptr, "AJ"},
@@ -803,7 +803,7 @@ void makejoint(mj::Simulate* sim, int oldstate) {
for (int i=0; i<sim->m->njnt && itemcnt<mjMAXUIITEM; i++) for (int i=0; i<sim->m->njnt && itemcnt<mjMAXUIITEM; i++)
if ((sim->m->jnt_type[i]==mjJNT_HINGE || sim->m->jnt_type[i]==mjJNT_SLIDE)) { if ((sim->m->jnt_type[i]==mjJNT_HINGE || sim->m->jnt_type[i]==mjJNT_SLIDE)) {
// skip if joint group is disabled // skip if joint group is disabled
if (!sim->vopt.jointgroup[mjMAX(0, mjMIN(mjNGROUP-1, sim->m->jnt_group[i]))]) { if (!sim->opt.jointgroup[mjMAX(0, mjMIN(mjNGROUP-1, sim->m->jnt_group[i]))]) {
continue; continue;
} }
@@ -832,7 +832,7 @@ void makejoint(mj::Simulate* sim, int oldstate) {
} }
// make control section of UI // make control section of UI
void makecontrol(mj::Simulate* sim, int oldstate) { void MakeControlSection(mj::Simulate* sim, int oldstate) {
mjuiDef defControl[] = { mjuiDef defControl[] = {
{mjITEM_SECTION, "Control", oldstate, nullptr, "AC"}, {mjITEM_SECTION, "Control", oldstate, nullptr, "AC"},
{mjITEM_BUTTON, "Clear all", 2}, {mjITEM_BUTTON, "Clear all", 2},
@@ -851,7 +851,7 @@ void makecontrol(mj::Simulate* sim, int oldstate) {
int itemcnt = 1; int itemcnt = 1;
for (int i=0; i<sim->m->nu && itemcnt<mjMAXUIITEM; i++) { for (int i=0; i<sim->m->nu && itemcnt<mjMAXUIITEM; i++) {
// skip if actuator group is disabled // skip if actuator group is disabled
if (!sim->vopt.actuatorgroup[mjMAX(0, mjMIN(mjNGROUP-1, sim->m->actuator_group[i]))]) { if (!sim->opt.actuatorgroup[mjMAX(0, mjMIN(mjNGROUP-1, sim->m->actuator_group[i]))]) {
continue; continue;
} }
@@ -878,7 +878,7 @@ void makecontrol(mj::Simulate* sim, int oldstate) {
} }
// make model-dependent UI sections // make model-dependent UI sections
void makesections(mj::Simulate* sim) { void MakeUiSections(mj::Simulate* sim) {
// get section open-close state, UI 0 // get section open-close state, UI 0
int oldstate0[NSECT0]; int oldstate0[NSECT0];
for (int i=0; i<NSECT0; i++) { for (int i=0; i<NSECT0; i++) {
@@ -902,24 +902,24 @@ void makesections(mj::Simulate* sim) {
sim->ui1.nsect = 0; sim->ui1.nsect = 0;
// make // make
makephysics(sim, oldstate0[SECT_PHYSICS]); MakePhysicsSection(sim, oldstate0[SECT_PHYSICS]);
makerendering(sim, oldstate0[SECT_RENDERING]); MakeRenderingSection(sim, oldstate0[SECT_RENDERING]);
makegroup(sim, oldstate0[SECT_GROUP]); MakeGroupSection(sim, oldstate0[SECT_GROUP]);
makejoint(sim, oldstate1[SECT_JOINT]); MakeJointSection(sim, oldstate1[SECT_JOINT]);
makecontrol(sim, oldstate1[SECT_CONTROL]); MakeControlSection(sim, oldstate1[SECT_CONTROL]);
} }
//---------------------------------- utility functions --------------------------------------------- //---------------------------------- utility functions ---------------------------------------------
// align and scale view // align and scale view
void alignscale(mj::Simulate* sim) { void AlignAndScaleView(mj::Simulate* sim) {
// use default free camera parameters // use default free camera parameters
mjv_defaultFreeCamera(sim->m, &sim->cam); mjv_defaultFreeCamera(sim->m, &sim->cam);
} }
// copy qpos to clipboard as key // copy qpos to clipboard as key
void copykey(mj::Simulate* sim) { void CopyKey(mj::Simulate* sim) {
char clipboard[5000] = "<key qpos='"; char clipboard[5000] = "<key qpos='";
char buf[200]; char buf[200];
@@ -935,12 +935,12 @@ void copykey(mj::Simulate* sim) {
} }
// millisecond timer, for MuJoCo built-in profiler // millisecond timer, for MuJoCo built-in profiler
mjtNum timer() { mjtNum Timer() {
return Milliseconds(mj::Simulate::Clock::now().time_since_epoch()).count(); return Milliseconds(mj::Simulate::Clock::now().time_since_epoch()).count();
} }
// clear all times // clear all times
void cleartimers(mjData* d) { void ClearTimeres(mjData* d) {
for (int i=0; i<mjNTIMER; i++) { for (int i=0; i<mjNTIMER; i++) {
d->timer[i].duration = 0; d->timer[i].duration = 0;
d->timer[i].number = 0; d->timer[i].number = 0;
@@ -948,7 +948,7 @@ void cleartimers(mjData* d) {
} }
// copy current camera to clipboard as MJCF specification // copy current camera to clipboard as MJCF specification
void copycamera(mj::Simulate* sim) { void CopyCamera(mj::Simulate* sim) {
mjvGLCamera* camera = sim->scn.camera; mjvGLCamera* camera = sim->scn.camera;
char clipboard[500]; char clipboard[500];
@@ -975,7 +975,7 @@ void copycamera(mj::Simulate* sim) {
} }
// update UI 0 when MuJoCo structures change (except for joint sliders) // update UI 0 when MuJoCo structures change (except for joint sliders)
void updatesettings(mj::Simulate* sim) { void UpdateSettings(mj::Simulate* sim) {
// physics flags // physics flags
for (int i=0; i<mjNDISABLE; i++) { for (int i=0; i<mjNDISABLE; i++) {
sim->disable[i] = ((sim->m->opt.disableflags & (1<<i)) !=0); sim->disable[i] = ((sim->m->opt.disableflags & (1<<i)) !=0);
@@ -1026,7 +1026,7 @@ int ComputeFontScale(const mj::PlatformUIAdapter& platform_ui) {
//---------------------------------- UI handlers --------------------------------------------------- //---------------------------------- UI handlers ---------------------------------------------------
// determine enable/disable item state given category // determine enable/disable item state given category
int uiPredicate(int category, void* userdata) { int UiPredicate(int category, void* userdata) {
mj::Simulate* sim = static_cast<mj::Simulate*>(userdata); mj::Simulate* sim = static_cast<mj::Simulate*>(userdata);
switch (category) { switch (category) {
@@ -1045,7 +1045,7 @@ int uiPredicate(int category, void* userdata) {
} }
// set window layout // set window layout
void uiLayout(mjuiState* state) { void UiLayout(mjuiState* state) {
mj::Simulate* sim = static_cast<mj::Simulate*>(state->userdata); mj::Simulate* sim = static_cast<mj::Simulate*>(state->userdata);
mjrRect* rect = state->rect; mjrRect* rect = state->rect;
@@ -1071,15 +1071,15 @@ void uiLayout(mjuiState* state) {
rect[3].height = rect[0].height; rect[3].height = rect[0].height;
} }
void uiModify(mjUI* ui, mjuiState* state, mjrContext* con) { void UiModify(mjUI* ui, mjuiState* state, mjrContext* con) {
mjui_resize(ui, con); mjui_resize(ui, con);
mjr_addAux(ui->auxid, ui->width, ui->maxheight, ui->spacing.samples, con); mjr_addAux(ui->auxid, ui->width, ui->maxheight, ui->spacing.samples, con);
uiLayout(state); UiLayout(state);
mjui_update(-1, -1, ui, state, con); mjui_update(-1, -1, ui, state, con);
} }
// handle UI event // handle UI event
void uiEvent(mjuiState* state) { void UiEvent(mjuiState* state) {
mj::Simulate* sim = static_cast<mj::Simulate*>(state->userdata); mj::Simulate* sim = static_cast<mj::Simulate*>(state->userdata);
mjModel* m = sim->m; mjModel* m = sim->m;
mjData* d = sim->d; mjData* d = sim->d;
@@ -1158,8 +1158,8 @@ void uiEvent(mjuiState* state) {
} }
// modify UI // modify UI
uiModify(&sim->ui0, state, &sim->platform_ui->mjr_context()); UiModify(&sim->ui0, state, &sim->platform_ui->mjr_context());
uiModify(&sim->ui1, state, &sim->platform_ui->mjr_context()); UiModify(&sim->ui1, state, &sim->platform_ui->mjr_context());
} }
// simulation section // simulation section
@@ -1169,9 +1169,9 @@ void uiEvent(mjuiState* state) {
if (m) { if (m) {
mj_resetData(m, d); mj_resetData(m, d);
mj_forward(m, d); mj_forward(m, d);
profilerupdate(sim); UpdateProfiler(sim);
sensorupdate(sim); UpdateSensor(sim);
updatesettings(sim); UpdateSettings(sim);
} }
break; break;
@@ -1180,12 +1180,12 @@ void uiEvent(mjuiState* state) {
break; break;
case 3: // Align case 3: // Align
alignscale(sim); AlignAndScaleView(sim);
updatesettings(sim); UpdateSettings(sim);
break; break;
case 4: // Copy pose case 4: // Copy pose
copykey(sim); CopyKey(sim);
break; break;
case 5: // Adjust key case 5: // Adjust key
@@ -1201,9 +1201,9 @@ void uiEvent(mjuiState* state) {
4 * m->nmocap); 4 * m->nmocap);
mju_copy(d->ctrl, m->key_ctrl + i * m->nu, m->nu); mju_copy(d->ctrl, m->key_ctrl + i * m->nu, m->nu);
mj_forward(m, d); mj_forward(m, d);
profilerupdate(sim); UpdateProfiler(sim);
sensorupdate(sim); UpdateSensor(sim);
updatesettings(sim); UpdateSettings(sim);
} break; } break;
case 7: // Save key case 7: // Save key
@@ -1259,7 +1259,7 @@ void uiEvent(mjuiState* state) {
} }
// copy camera spec to clipboard (as MJCF element) // copy camera spec to clipboard (as MJCF element)
if (it->itemid == 3) { if (it->itemid == 3) {
copycamera(sim); CopyCamera(sim);
} }
} }
@@ -1268,17 +1268,17 @@ void uiEvent(mjuiState* state) {
// remake joint section if joint group changed // remake joint section if joint group changed
if (it->name[0]=='J' && it->name[1]=='o') { if (it->name[0]=='J' && it->name[1]=='o') {
sim->ui1.nsect = SECT_JOINT; sim->ui1.nsect = SECT_JOINT;
makejoint(sim, sim->ui1.sect[SECT_JOINT].state); MakeJointSection(sim, sim->ui1.sect[SECT_JOINT].state);
sim->ui1.nsect = NSECT1; sim->ui1.nsect = NSECT1;
uiModify(&sim->ui1, state, &sim->platform_ui->mjr_context()); UiModify(&sim->ui1, state, &sim->platform_ui->mjr_context());
} }
// remake control section if actuator group changed // remake control section if actuator group changed
if (it->name[0]=='A' && it->name[1]=='c') { if (it->name[0]=='A' && it->name[1]=='c') {
sim->ui1.nsect = SECT_CONTROL; sim->ui1.nsect = SECT_CONTROL;
makecontrol(sim, sim->ui1.sect[SECT_CONTROL].state); MakeControlSection(sim, sim->ui1.sect[SECT_CONTROL].state);
sim->ui1.nsect = NSECT1; sim->ui1.nsect = NSECT1;
uiModify(&sim->ui1, state, &sim->platform_ui->mjr_context()); UiModify(&sim->ui1, state, &sim->platform_ui->mjr_context());
} }
} }
@@ -1323,11 +1323,11 @@ void uiEvent(mjuiState* state) {
case mjKEY_RIGHT: // step forward case mjKEY_RIGHT: // step forward
if (m && !sim->run) { if (m && !sim->run) {
cleartimers(d); ClearTimeres(d);
mj_step(m, d); mj_step(m, d);
profilerupdate(sim); UpdateProfiler(sim);
sensorupdate(sim); UpdateSensor(sim);
updatesettings(sim); UpdateSettings(sim);
} }
break; break;
@@ -1374,14 +1374,14 @@ void uiEvent(mjuiState* state) {
case mjKEY_F6: // cycle frame visualisation case mjKEY_F6: // cycle frame visualisation
if (m) { if (m) {
sim->vopt.frame = (sim->vopt.frame + 1) % mjNFRAME; sim->opt.frame = (sim->opt.frame + 1) % mjNFRAME;
mjui_update(SECT_RENDERING, -1, &sim->ui0, &sim->uistate, &sim->platform_ui->mjr_context()); mjui_update(SECT_RENDERING, -1, &sim->ui0, &sim->uistate, &sim->platform_ui->mjr_context());
} }
break; break;
case mjKEY_F7: // cycle label visualisation case mjKEY_F7: // cycle label visualisation
if (m) { if (m) {
sim->vopt.label = (sim->vopt.label + 1) % mjNLABEL; sim->opt.label = (sim->opt.label + 1) % mjNLABEL;
mjui_update(SECT_RENDERING, -1, &sim->ui0, &sim->uistate, &sim->platform_ui->mjr_context()); mjui_update(SECT_RENDERING, -1, &sim->ui0, &sim->uistate, &sim->platform_ui->mjr_context());
} }
break; break;
@@ -1395,17 +1395,17 @@ void uiEvent(mjuiState* state) {
case '-': // slow down case '-': // slow down
{ {
int numclicks = sizeof(sim->percentRealTime) / sizeof(sim->percentRealTime[0]); int numclicks = sizeof(sim->percentRealTime) / sizeof(sim->percentRealTime[0]);
if (sim->realTimeIndex < numclicks-1 && !state->shift) { if (sim->real_time_index < numclicks-1 && !state->shift) {
sim->realTimeIndex++; sim->real_time_index++;
sim->speedChanged = true; sim->speed_changed = true;
} }
} }
break; break;
case '=': // speed up case '=': // speed up
if (sim->realTimeIndex > 0 && !state->shift) { if (sim->real_time_index > 0 && !state->shift) {
sim->realTimeIndex--; sim->real_time_index--;
sim->speedChanged = true; sim->speed_changed = true;
} }
break; break;
} }
@@ -1456,7 +1456,7 @@ void uiEvent(mjuiState* state) {
mjrRect r = state->rect[3]; mjrRect r = state->rect[3];
mjtNum selpnt[3]; mjtNum selpnt[3];
int selgeom, selskin; int selgeom, selskin;
int selbody = mjv_select(m, d, &sim->vopt, int selbody = mjv_select(m, d, &sim->opt,
static_cast<mjtNum>(r.width)/r.height, static_cast<mjtNum>(r.width)/r.height,
(state->x - r.left)/r.width, (state->x - r.left)/r.width,
(state->y - r.bottom)/r.height, (state->y - r.bottom)/r.height,
@@ -1549,7 +1549,7 @@ void uiEvent(mjuiState* state) {
// Redraw // Redraw
if (state->type == mjEVENT_REDRAW) { if (state->type == mjEVENT_REDRAW) {
sim->render(); sim->Render();
return; return;
} }
} }
@@ -1563,26 +1563,26 @@ Simulate::Simulate(std::unique_ptr<PlatformUIAdapter> platform_ui)
uistate(this->platform_ui->state()) {} uistate(this->platform_ui->state()) {}
//------------------------------------ apply pose perturbations ------------------------------------ //------------------------------------ apply pose perturbations ------------------------------------
void Simulate::applyposepertubations(int flg_paused) { void Simulate::ApplyPosePerturbations(int flg_paused) {
if (this->m != nullptr) { if (this->m != nullptr) {
mjv_applyPerturbPose(this->m, this->d, &this->pert, flg_paused); // move mocap bodies only mjv_applyPerturbPose(this->m, this->d, &this->pert, flg_paused); // move mocap bodies only
} }
} }
//----------------------------------- apply force perturbations ------------------------------------ //----------------------------------- apply force perturbations ------------------------------------
void Simulate::applyforceperturbations() { void Simulate::ApplyForcePerturbations() {
if (this->m != nullptr) { if (this->m != nullptr) {
mjv_applyPerturbForce(this->m, this->d, &this->pert); mjv_applyPerturbForce(this->m, this->d, &this->pert);
} }
} }
//------------------------- Tell the render thread to load a file and wait ------------------------- //------------------------- Tell the render thread to load a file and wait -------------------------
void Simulate::load(const char* file, void Simulate::Load(mjModel* m,
mjModel* mnew, mjData* d,
mjData* dnew) { const char* displayed_filename) {
this->mnew = mnew; this->mnew = m;
this->dnew = dnew; this->dnew = d;
mju::strcpy_arr(this->filename, file); mju::strcpy_arr(this->filename, displayed_filename);
{ {
std::unique_lock<std::mutex> lock(mtx); std::unique_lock<std::mutex> lock(mtx);
@@ -1596,7 +1596,7 @@ void Simulate::load(const char* file,
} }
//------------------------------------- load mjb or xml model -------------------------------------- //------------------------------------- load mjb or xml model --------------------------------------
void Simulate::loadmodel() { void Simulate::LoadOnRenderThread() {
this->m = this->mnew; this->m = this->mnew;
this->d = this->dnew; this->d = this->dnew;
@@ -1617,12 +1617,12 @@ void Simulate::loadmodel() {
// align and scale view unless reloading the same file // align and scale view unless reloading the same file
if (this->filename[0] && if (this->filename[0] &&
mju::strcmp_arr(this->filename, this->previous_filename)) { mju::strcmp_arr(this->filename, this->previous_filename)) {
alignscale(this); AlignAndScaleView(this);
mju::strcpy_arr(this->previous_filename, this->filename); mju::strcpy_arr(this->previous_filename, this->filename);
} }
// update scene // update scene
mjv_updateScene(this->m, this->d, &this->vopt, &this->pert, &this->cam, mjCAT_ALL, &this->scn); mjv_updateScene(this->m, this->d, &this->opt, &this->pert, &this->cam, mjCAT_ALL, &this->scn);
// set window title to model name // set window title to model name
if (this->m->names) { if (this->m->names) {
@@ -1637,12 +1637,12 @@ void Simulate::loadmodel() {
this->ui0.sect[SECT_SIMULATION].item[5].slider.divisions = mjMAX(1, this->m->nkey - 1); this->ui0.sect[SECT_SIMULATION].item[5].slider.divisions = mjMAX(1, this->m->nkey - 1);
// rebuild UI sections // rebuild UI sections
makesections(this); MakeUiSections(this);
// full ui update // full ui update
uiModify(&this->ui0, &this->uistate, &this->platform_ui->mjr_context()); UiModify(&this->ui0, &this->uistate, &this->platform_ui->mjr_context());
uiModify(&this->ui1, &this->uistate, &this->platform_ui->mjr_context()); UiModify(&this->ui1, &this->uistate, &this->platform_ui->mjr_context());
updatesettings(this); UpdateSettings(this);
// clear request // clear request
this->loadrequest = 0; this->loadrequest = 0;
@@ -1656,7 +1656,7 @@ void Simulate::loadmodel() {
float error = mju_abs(mju_log(this->percentRealTime[click]) - desired); float error = mju_abs(mju_log(this->percentRealTime[click]) - desired);
if (error < min_error) { if (error < min_error) {
min_error = error; min_error = error;
this->realTimeIndex = click; this->real_time_index = click;
} }
} }
} }
@@ -1666,7 +1666,7 @@ void Simulate::loadmodel() {
// prepare to render // prepare to render
void Simulate::prepare() { void Simulate::PrepareScene() {
// data for FPS calculation // data for FPS calculation
static std::chrono::time_point<Clock> lastupdatetm; static std::chrono::time_point<Clock> lastupdatetm;
@@ -1682,11 +1682,11 @@ void Simulate::prepare() {
} }
// update scene // update scene
mjv_updateScene(this->m, this->d, &this->vopt, &this->pert, &this->cam, mjCAT_ALL, &this->scn); mjv_updateScene(this->m, this->d, &this->opt, &this->pert, &this->cam, mjCAT_ALL, &this->scn);
// update watch // update watch
if (this->ui0_enable && this->ui0.sect[SECT_WATCH].state) { if (this->ui0_enable && this->ui0.sect[SECT_WATCH].state) {
watch(this); UpdateWatch(this);
mjui_update(SECT_WATCH, -1, &this->ui0, &this->uistate, &this->platform_ui->mjr_context()); mjui_update(SECT_WATCH, -1, &this->ui0, &this->uistate, &this->platform_ui->mjr_context());
} }
@@ -1697,7 +1697,7 @@ void Simulate::prepare() {
// update info text // update info text
if (this->info) { if (this->info) {
infotext(this, this->info_title, this->info_content, interval); UpdateInfoText(this, this->info_title, this->info_content, interval);
} }
// update control // update control
@@ -1707,23 +1707,23 @@ void Simulate::prepare() {
// update profiler // update profiler
if (this->profiler && this->run) { if (this->profiler && this->run) {
profilerupdate(this); UpdateProfiler(this);
} }
// update sensor // update sensor
if (this->sensor && this->run) { if (this->sensor && this->run) {
sensorupdate(this); UpdateSensor(this);
} }
// clear timers once profiler info has been copied // clear timers once profiler info has been copied
cleartimers(this->d); ClearTimeres(this->d);
} }
// render the ui to the window // render the ui to the window
void Simulate::render() { void Simulate::Render() {
if (this->platform_ui->RefreshMjrContext(this->m, 50*(this->font+1))) { if (this->platform_ui->RefreshMjrContext(this->m, 50*(this->font+1))) {
uiModify(&this->ui0, &this->uistate, &this->platform_ui->mjr_context()); UiModify(&this->ui0, &this->uistate, &this->platform_ui->mjr_context());
uiModify(&this->ui1, &this->uistate, &this->platform_ui->mjr_context()); UiModify(&this->ui1, &this->uistate, &this->platform_ui->mjr_context());
} }
// get 3D rectangle and reduced for profiler // get 3D rectangle and reduced for profiler
@@ -1751,8 +1751,8 @@ void Simulate::render() {
} }
// show last loading error // show last loading error
if (this->loadError[0]) { if (this->load_error[0]) {
mjr_overlay(mjFONT_NORMAL, mjGRID_BOTTOMLEFT, rect, this->loadError, 0, mjr_overlay(mjFONT_NORMAL, mjGRID_BOTTOMLEFT, rect, this->load_error, 0,
&this->platform_ui->mjr_context()); &this->platform_ui->mjr_context());
} }
@@ -1774,8 +1774,8 @@ void Simulate::render() {
mjr_render(rect, &this->scn, &this->platform_ui->mjr_context()); mjr_render(rect, &this->scn, &this->platform_ui->mjr_context());
// show last loading error // show last loading error
if (this->loadError[0]) { if (this->load_error[0]) {
mjr_overlay(mjFONT_NORMAL, mjGRID_BOTTOMLEFT, rect, this->loadError, 0, mjr_overlay(mjFONT_NORMAL, mjGRID_BOTTOMLEFT, rect, this->load_error, 0,
&this->platform_ui->mjr_context()); &this->platform_ui->mjr_context());
} }
@@ -1786,8 +1786,8 @@ void Simulate::render() {
} }
// get desired and actual percent-of-real-time // get desired and actual percent-of-real-time
float desiredRealtime = this->percentRealTime[this->realTimeIndex]; float desiredRealtime = this->percentRealTime[this->real_time_index];
float actualRealtime = 100 / this->measuredSlowdown; float actualRealtime = 100 / this->measured_slowdown;
// if running, check for misalignment of more than 10% // if running, check for misalignment of more than 10%
float realtime_offset = mju_abs(actualRealtime - desiredRealtime); float realtime_offset = mju_abs(actualRealtime - desiredRealtime);
@@ -1840,12 +1840,12 @@ void Simulate::render() {
// show profiler // show profiler
if (this->profiler) { if (this->profiler) {
profilershow(this, rect); ShowProfiler(this, rect);
} }
// show sensor // show sensor
if (this->sensor) { if (this->sensor) {
sensorshow(this, smallrect); ShowSensor(this, smallrect);
} }
// take screenshot, save to file // take screenshot, save to file
@@ -1886,15 +1886,15 @@ void Simulate::render() {
void Simulate::renderloop() { void Simulate::RenderLoop() {
// Set timer callback (milliseconds) // Set timer callback (milliseconds)
mjcb_time = timer; mjcb_time = Timer;
// init abstract visualization // init abstract visualization
mjv_defaultCamera(&this->cam); mjv_defaultCamera(&this->cam);
mjv_defaultOption(&this->vopt); mjv_defaultOption(&this->opt);
profilerinit(this); InitializeProfiler(this);
sensorinit(this); InitializeSensor(this);
// make empty scene // make empty scene
mjv_defaultScene(&this->scn); mjv_defaultScene(&this->scn);
@@ -1923,30 +1923,30 @@ void Simulate::renderloop() {
this->ui0.spacing = mjui_themeSpacing(this->spacing); this->ui0.spacing = mjui_themeSpacing(this->spacing);
this->ui0.color = mjui_themeColor(this->color); this->ui0.color = mjui_themeColor(this->color);
this->ui0.predicate = uiPredicate; this->ui0.predicate = UiPredicate;
this->ui0.rectid = 1; this->ui0.rectid = 1;
this->ui0.auxid = 0; this->ui0.auxid = 0;
this->ui1.spacing = mjui_themeSpacing(this->spacing); this->ui1.spacing = mjui_themeSpacing(this->spacing);
this->ui1.color = mjui_themeColor(this->color); this->ui1.color = mjui_themeColor(this->color);
this->ui1.predicate = uiPredicate; this->ui1.predicate = UiPredicate;
this->ui1.rectid = 2; this->ui1.rectid = 2;
this->ui1.auxid = 1; this->ui1.auxid = 1;
// set GUI adapter callbacks // set GUI adapter callbacks
this->uistate.userdata = this; this->uistate.userdata = this;
this->platform_ui->SetEventCallback(uiEvent); this->platform_ui->SetEventCallback(UiEvent);
this->platform_ui->SetLayoutCallback(uiLayout); this->platform_ui->SetLayoutCallback(UiLayout);
// populate uis with standard sections // populate uis with standard sections
this->ui0.userdata = this; this->ui0.userdata = this;
this->ui1.userdata = this; this->ui1.userdata = this;
mjui_add(&this->ui0, defFile); mjui_add(&this->ui0, defFile);
mjui_add(&this->ui0, this->defOption); mjui_add(&this->ui0, this->def_option);
mjui_add(&this->ui0, this->defSimulation); mjui_add(&this->ui0, this->def_simulation);
mjui_add(&this->ui0, this->defWatch); mjui_add(&this->ui0, this->def_watch);
uiModify(&this->ui0, &this->uistate, &this->platform_ui->mjr_context()); UiModify(&this->ui0, &this->uistate, &this->platform_ui->mjr_context());
uiModify(&this->ui1, &this->uistate, &this->platform_ui->mjr_context()); UiModify(&this->ui1, &this->uistate, &this->platform_ui->mjr_context());
// set VSync to initial value // set VSync to initial value
this->platform_ui->SetVSync(this->vsync); this->platform_ui->SetVSync(this->vsync);
@@ -1958,7 +1958,7 @@ void Simulate::renderloop() {
// load model (not on first pass, to show "loading" label) // load model (not on first pass, to show "loading" label)
if (this->loadrequest==1) { if (this->loadrequest==1) {
this->loadmodel(); this->LoadOnRenderThread();
} else if (this->loadrequest>1) { } else if (this->loadrequest>1) {
this->loadrequest = 1; this->loadrequest = 1;
} }
@@ -1967,11 +1967,11 @@ void Simulate::renderloop() {
this->platform_ui->PollEvents(); this->platform_ui->PollEvents();
// prepare to render // prepare to render
this->prepare(); this->PrepareScene();
} // std::lock_guard<std::mutex> (unblocks simulation thread) } // std::lock_guard<std::mutex> (unblocks simulation thread)
// render while simulation is running // render while simulation is running
this->render(); this->Render();
} }
this->exitrequest.store(true); this->exitrequest.store(true);
+25 -25
View File
@@ -40,27 +40,27 @@ class Simulate {
Simulate(std::unique_ptr<PlatformUIAdapter> platform_ui_adapter); Simulate(std::unique_ptr<PlatformUIAdapter> platform_ui_adapter);
// Apply UI pose perturbations to model and data // Apply UI pose perturbations to model and data
void applyposepertubations(int flg_paused); void ApplyPosePerturbations(int flg_paused);
// Apply UI force perturbations to model and data // Apply UI force perturbations to model and data
void applyforceperturbations(); void ApplyForcePerturbations();
// Request that the Simulate UI thread render a new model // Request that the Simulate UI thread render a new model
// optionally delete the old model and data when done // optionally delete the old model and data when done
void load(const char* file, mjModel* m, mjData* d); void Load(mjModel* m, mjData* d, const char* displayed_filename);
// functions below are used by the renderthread // functions below are used by the renderthread
// load mjb or xml model that has been requested by load() // load mjb or xml model that has been requested by load()
void loadmodel(); void LoadOnRenderThread();
// prepare to render // prepare to render
void prepare(); void PrepareScene();
// render the ui to the window // render the ui to the window
void render(); void Render();
// loop to render the UI (must be called from main thread because of MacOS) // loop to render the UI (must be called from main thread because of MacOS)
void renderloop(); void RenderLoop();
// constants // constants
static constexpr int kMaxFilenameLength = 1000; static constexpr int kMaxFilenameLength = 1000;
@@ -95,9 +95,9 @@ class Simulate {
int run = 1; int run = 1;
// atomics for cross-thread messages // atomics for cross-thread messages
std::atomic_int exitrequest = false; std::atomic_int exitrequest = 0;
std::atomic_int droploadrequest = false; std::atomic_int droploadrequest = 0;
std::atomic_int screenshotrequest = false; std::atomic_int screenshotrequest = 0;
std::atomic_int uiloadrequest = 0; std::atomic_int uiloadrequest = 0;
// loadrequest // loadrequest
@@ -107,15 +107,15 @@ class Simulate {
int loadrequest = 0; int loadrequest = 0;
// strings // strings
char loadError[kMaxFilenameLength] = ""; char load_error[kMaxFilenameLength] = "";
char dropfilename[kMaxFilenameLength] = ""; char dropfilename[kMaxFilenameLength] = "";
char filename[kMaxFilenameLength] = ""; char filename[kMaxFilenameLength] = "";
char previous_filename[kMaxFilenameLength] = ""; char previous_filename[kMaxFilenameLength] = "";
// time synchronization // time synchronization
int realTimeIndex; int real_time_index;
bool speedChanged = true; bool speed_changed = true;
float measuredSlowdown = 1.0; float measured_slowdown = 1.0;
// logarithmically spaced realtime slow-down coefficients (percent) // logarithmically spaced realtime slow-down coefficients (percent)
static constexpr float percentRealTime[] = { static constexpr float percentRealTime[] = {
100, 80, 66, 50, 40, 33, 25, 20, 16, 13, 100, 80, 66, 50, 40, 33, 25, 20, 16, 13,
@@ -125,8 +125,8 @@ class Simulate {
}; };
// control noise // control noise
double ctrlnoisestd = 0.0; double ctrl_noise_std = 0.0;
double ctrlnoiserate = 0.0; double ctrl_noise_rate = 0.0;
// watch // watch
char field[mjMAXUITEXT] = "qpos"; char field[mjMAXUITEXT] = "qpos";
@@ -142,7 +142,7 @@ class Simulate {
// abstract visualization // abstract visualization
mjvScene scn = {}; mjvScene scn = {};
mjvCamera cam = {}; mjvCamera cam = {};
mjvOption vopt = {}; mjvOption opt = {};
mjvPerturb pert = {}; mjvPerturb pert = {};
mjvFigure figconstraint = {}; mjvFigure figconstraint = {};
mjvFigure figcost = {}; mjvFigure figcost = {};
@@ -151,9 +151,9 @@ class Simulate {
mjvFigure figsensor = {}; mjvFigure figsensor = {};
// OpenGL rendering and UI // OpenGL rendering and UI
int refreshRate = 60; int refresh_rate = 60;
int windowpos[2] = {0}; int window_pos[2] = {0};
int windowsize[2] = {0}; int window_size[2] = {0};
std::unique_ptr<PlatformUIAdapter> platform_ui; std::unique_ptr<PlatformUIAdapter> platform_ui;
mjuiState& uistate; mjuiState& uistate;
mjUI ui0 = {}; mjUI ui0 = {};
@@ -161,7 +161,7 @@ class Simulate {
// Constant arrays needed for the option section of UI and the UI interface // Constant arrays needed for the option section of UI and the UI interface
// TODO setting the size here is not ideal // TODO setting the size here is not ideal
const mjuiDef defOption[14] = { const mjuiDef def_option[14] = {
{mjITEM_SECTION, "Option", 1, nullptr, "AO"}, {mjITEM_SECTION, "Option", 1, nullptr, "AO"},
{mjITEM_SELECT, "Spacing", 1, &this->spacing, "Tight\nWide"}, {mjITEM_SELECT, "Spacing", 1, &this->spacing, "Tight\nWide"},
{mjITEM_SELECT, "Color", 1, &this->color, "Default\nOrange\nWhite\nBlack"}, {mjITEM_SELECT, "Color", 1, &this->color, "Default\nOrange\nWhite\nBlack"},
@@ -184,7 +184,7 @@ class Simulate {
// simulation section of UI // simulation section of UI
const mjuiDef defSimulation[12] = { const mjuiDef def_simulation[12] = {
{mjITEM_SECTION, "Simulation", 1, nullptr, "AS"}, {mjITEM_SECTION, "Simulation", 1, nullptr, "AS"},
{mjITEM_RADIO, "", 2, &this->run, "Pause\nRun"}, {mjITEM_RADIO, "", 2, &this->run, "Pause\nRun"},
{mjITEM_BUTTON, "Reset", 2, nullptr, " #259"}, {mjITEM_BUTTON, "Reset", 2, nullptr, " #259"},
@@ -194,14 +194,14 @@ class Simulate {
{mjITEM_SLIDERINT, "Key", 3, &this->key, "0 0"}, {mjITEM_SLIDERINT, "Key", 3, &this->key, "0 0"},
{mjITEM_BUTTON, "Load key", 3}, {mjITEM_BUTTON, "Load key", 3},
{mjITEM_BUTTON, "Save key", 3}, {mjITEM_BUTTON, "Save key", 3},
{mjITEM_SLIDERNUM, "Noise scale", 2, &this->ctrlnoisestd, "0 2"}, {mjITEM_SLIDERNUM, "Noise scale", 2, &this->ctrl_noise_std, "0 2"},
{mjITEM_SLIDERNUM, "Noise rate", 2, &this->ctrlnoiserate, "0 2"}, {mjITEM_SLIDERNUM, "Noise rate", 2, &this->ctrl_noise_rate, "0 2"},
{mjITEM_END} {mjITEM_END}
}; };
// watch section of UI // watch section of UI
const mjuiDef defWatch[5] = { const mjuiDef def_watch[5] = {
{mjITEM_SECTION, "Watch", 0, nullptr, "AW"}, {mjITEM_SECTION, "Watch", 0, nullptr, "AW"},
{mjITEM_EDITTXT, "Field", 2, this->field, "qpos"}, {mjITEM_EDITTXT, "Field", 2, this->field, "qpos"},
{mjITEM_EDITINT, "Index", 2, &this->index, "1"}, {mjITEM_EDITINT, "Index", 2, &this->index, "1"},