$darkmode
eigen.hpp
Go to the documentation of this file.
1 /*
2  * Copyright 2020 Robert Bosch GmbH
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  * SPDX-License-Identifier: Apache-2.0
17  */
26 #pragma once
27 
28 #include <Eigen/Geometry> // for Vector3d, Quaterniond, Isometry3d
29 #include <nlohmann/json.hpp> // for adl_serializer<>, json
30 
31 namespace nlohmann {
32 
33 template <>
34 struct adl_serializer<Eigen::Vector3d> {
35  static void to_json(json& j, const Eigen::Vector3d& v) {
36  j = json{
37  {"x", v.x()},
38  {"y", v.y()},
39  {"z", v.z()},
40  };
41  }
42 
43  static void from_json(const json& j, Eigen::Vector3d& v) {
44  v.x() = j["x"].get<double>();
45  v.y() = j["y"].get<double>();
46  v.z() = j["z"].get<double>();
47  }
48 };
49 
50 template <>
51 struct adl_serializer<Eigen::Quaterniond> {
52  static void to_json(json& j, const Eigen::Quaterniond& q) {
53  j = json{
54  {"w", q.w()},
55  {"x", q.x()},
56  {"y", q.y()},
57  {"z", q.z()},
58  };
59  }
60 
61  static void from_json(const json& j, Eigen::Quaterniond& q) {
62  q.w() = j["w"].get<double>();
63  q.x() = j["x"].get<double>();
64  q.y() = j["y"].get<double>();
65  q.z() = j["z"].get<double>();
66  }
67 };
68 
69 template <>
70 struct adl_serializer<Eigen::Isometry3d> {
71  static void to_json(json& j, const Eigen::Isometry3d& o) {
72  Eigen::Vector3d trans = o.translation();
73  j = json{
74  {"translation", trans},
75  {"rotation", Eigen::Quaterniond(o.rotation())},
76  };
77  }
78 
79  static void from_json(const json& j, Eigen::Isometry3d& o) {
80  o.setIdentity();
81  o.linear() = j["rotation"].get<Eigen::Quaterniond>().matrix();
82  o.translation() = j["translation"].get<Eigen::Vector3d>();
83  }
84 };
85 
86 } // namespace nlohmann