Move GlobalModel class and functionality into its own file.
We'll need some of this functionality for tests. PiperOrigin-RevId: 853652149 Change-Id: Ib924d886b73784a0f370285e0b82b2ed833e3e77
This commit is contained in:
committed by
Copybara-Service
parent
8f5eb1e4f4
commit
765bd54c7c
@@ -0,0 +1,77 @@
|
||||
// Copyright 2026 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 "xml/xml_global.h"
|
||||
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
#include <mujoco/mujoco.h>
|
||||
#include "xml/xml.h"
|
||||
#include "xml/xml_util.h"
|
||||
|
||||
namespace {
|
||||
|
||||
// global user model class
|
||||
class GlobalModel {
|
||||
public:
|
||||
// deletes current model and takes ownership of model
|
||||
void Set(mjSpec* spec = nullptr);
|
||||
|
||||
// writes XML to string
|
||||
std::string ToXML(const mjModel* m, char* error, int error_sz);
|
||||
|
||||
private:
|
||||
// using raw pointers as GlobalModel needs to be trivially destructible
|
||||
std::mutex* mutex_ = new std::mutex();
|
||||
mjSpec* spec_ = nullptr;
|
||||
};
|
||||
|
||||
std::string GlobalModel::ToXML(const mjModel* m, char* error,
|
||||
int error_sz) {
|
||||
std::lock_guard<std::mutex> lock(*mutex_);
|
||||
if (!spec_) {
|
||||
mjCopyError(error, "No XML model loaded", error_sz);
|
||||
return "";
|
||||
}
|
||||
return WriteXML(m, spec_, error, error_sz);
|
||||
}
|
||||
|
||||
void GlobalModel::Set(mjSpec* spec) {
|
||||
std::lock_guard<std::mutex> lock(*mutex_);
|
||||
if (spec_ != nullptr) {
|
||||
mj_deleteSpec(spec_);
|
||||
}
|
||||
spec_ = spec;
|
||||
}
|
||||
|
||||
|
||||
// returns a single instance of the global model
|
||||
GlobalModel& GetGlobalModel() {
|
||||
static GlobalModel global_model;
|
||||
|
||||
// global variables must be trivially destructible
|
||||
static_assert(std::is_trivially_destructible_v<decltype(global_model)>);
|
||||
return global_model;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void SetGlobalXmlSpec(mjSpec* spec) {
|
||||
GetGlobalModel().Set(spec);
|
||||
}
|
||||
|
||||
std::string GetGlobalXmlSpec(const mjModel* m, char* error, int error_sz) {
|
||||
return GetGlobalModel().ToXML(m, error, error_sz);
|
||||
}
|
||||
Reference in New Issue
Block a user