Gazebo Sim

API Reference

9.0.0~pre1
components/Model.hh
Go to the documentation of this file.
1/*
2 * Copyright (C) 2018 Open Source Robotics Foundation
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *
16*/
17#ifndef GZ_SIM_COMPONENTS_MODEL_HH_
18#define GZ_SIM_COMPONENTS_MODEL_HH_
19
20#include <string>
21
22#include <sdf/Model.hh>
23#include <sdf/Root.hh>
24
27#include <gz/sim/config.hh>
28
29namespace gz
30{
31namespace sim
32{
33// Inline bracket to help doxygen filtering.
34inline namespace GZ_SIM_VERSION_NAMESPACE {
35namespace serializers
36{
38 {
43 public: static std::ostream &Serialize(std::ostream &_out,
44 const sdf::Model &_model)
45 {
46 sdf::ElementPtr modelElem = _model.Element();
47 if (!modelElem)
48 {
49 gzwarn << "Unable to serialize sdf::Model" << std::endl;
50 return _out;
51 }
52
53 bool skip = false;
54 if (modelElem->HasElement("pose"))
55 {
56 sdf::ElementPtr poseElem = modelElem->GetElement("pose");
57 if (poseElem->HasAttribute("relative_to"))
58 {
59 // Skip serializing models with //pose/@relative_to attribute
60 // since deserialization will fail. This could be a nested model.
61 // see https://github.com/gazebosim/gz-sim/issues/1071
62 // Once https://github.com/gazebosim/sdformat/issues/820 is
63 // resolved, there should be an API that returns sdf::Errors objects
64 // instead of printing console msgs so it would be easier to ignore
65 // specific errors in Deserialize.
66 static bool warned = false;
67 if (!warned)
68 {
69 gzwarn << "Skipping serialization / deserialization for models "
70 << "with //pose/@relative_to attribute."
71 << std::endl;
72 warned = true;
73 }
74 skip = true;
75 }
76 }
77
78 _out << "<?xml version=\"1.0\" ?>"
79 << "<sdf version='" << SDF_PROTOCOL_VERSION << "'>"
80 << (skip ? std::string() : modelElem->ToString(""))
81 << "</sdf>";
82 return _out;
83 }
84
90 sdf::Model &_model)
91 {
92 sdf::Root root;
94
95 sdf::Errors errors = root.LoadSdfString(sdf);
96 if (!root.Model())
97 {
98 gzwarn << "Unable to deserialize sdf::Model" << std::endl;
99 return _in;
100 }
101
102 _model = *root.Model();
103 return _in;
104 }
105 };
106}
107
108namespace components
109{
112 GZ_SIM_REGISTER_COMPONENT("gz_sim_components.Model", Model)
113
114
115 using ModelSdf = Component<sdf::Model,
116 class ModelTag,
117 serializers::SdfModelSerializer>;
118 GZ_SIM_REGISTER_COMPONENT("gz_sim_components.ModelSdf", ModelSdf)
119}
120}
121}
122}
123
124#endif