SuperDex Physics C++ API
Loading...
Searching...
No Matches
reflection.h
Go to the documentation of this file.
1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
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#pragma once
18
20
21/**************************************************************************************************
22 * Mochi Reflection
23 *
24 * Mochi uses a first-party C++ reflection library called Simple Reflection. It is rebranded here
25 * using "MOCHI_" prefixed macros, which usually compile out when mochi headers are included
26 * externally.
27 *
28 * Reflection metadata can be used for things like:
29 * - Serialization
30 * - Automatic UI generation
31 * - Portable type identification
32 * - And more...
33 *
34 * Enum Example:
35 *
36 * enum class MyEnum {
37 * Option1,
38 * Option2,
39 * Count
40 * };
41 *
42 * // Then, in the globl namespace:
43 * MOCHI_ENUM_BEGIN(superdex::MyEnum)
44 * MOCHI_ENUM_ITEM(Option1)
45 * MOCHI_ENUM_ITEM(Option2)
46 * MOCHI_ENUM_COUNT(Count)
47 * MOCHI_ENUM_END()
48 *
49 * Struct Example 1 (declared inside the class):
50 *
51 * struct MyStruct {
52 * int someValue = 0;
53 * DynamicArray<Real3> coords;
54 *
55 * MOCHI_STRUCT_BEGIN(superdex::MyStruct)
56 * MOCHI_FIELD(someValue);
57 * MOCHI_FIELD(coords);
58 * MOCHI_STRUCT_END();
59 * };
60 *
61 * Struct Example 2 (declared outside the class, defined inline):
62 *
63 * struct MyStruct {
64 * int someValue = 0;
65 * DynamicArray<Real3> coords;
66 * };
67 *
68 * // Then, in the global namespace:
69 * MOCHI_STRUCT_BEGIN_EX(superdex::MyStruct)
70 * MOCHI_FIELD(someValue);
71 * MOCHI_FIELD(coords);
72 * MOCHI_STRUCT_END_EX();
73 *
74 * Struct Example 3 (declared outside the class, defined in cpp):
75 *
76 * struct MyStruct {
77 * int someValue = 0;
78 * DynamicArray<Real3> coords;
79 * };
80 *
81 * // Then header global namespace:
82 * MOCHI_STRUCT_DECLARE_EX(superdex::MyStruct)
83 *
84 * // In cpp file global namespace:
85 * MOCHI_STRUCT_DEFINITION_BEGIN_EX(superdex::MyStruct)
86 * MOCHI_FIELD(someValue);
87 * MOCHI_FIELD(coords);
88 * MOCHI_STRUCT_DEFINITION_END_EX();
89 *
90 * Template Example (internal):
91 *
92 * template <class T, int N>
93 * struct MyTemplate {
94 * std::array<T, N> values;
95 *
96 * MOCHI_TEMPLATE_BEGIN(superdex::Template, T, N)
97 * MOCHI_FIELD(values);
98 * MOCHI_TEMPLATE_END();
99 * };
100 *
101 * Attributes Example (they go AFTER that which they describe):
102 *
103 * MOCHI_STRUCT_BEGIN_EX(superdex::MyStruct)
104 * MOCHI_ATTRIBUTE(Description("This string describes the whole class"));
105 * MOCHI_FIELD(someValue) MOCHI_ATTRIBUTE(ReadOnly);
106 * MOCHI_FIELD(coords) MOCHI_ATTRIBUTE(Units("m"));
107 * MOCHI_STRUCT_END_EX();
108 *
109 * Properties and Methods Example (declared inside the class):
110 *
111 * class MyBody {
112 * public:
113 * int GetNodeCount() const;
114 * real GetMass() const;
115 * void SetMass(real mass, Error& error);
116 * Real3 GetCenterOfMass(Error& error) const;
117 * void ApplyForce(Real3 const& force, Error& error);
118 *
119 * MOCHI_STRUCT_BEGIN(superdex::MyBody)
120 * MOCHI_PROPERTY("nodeCount", &MyBody::GetNodeCount);
121 * MOCHI_PROPERTY_WITH_ERROR("mass", &MyBody::GetMass, &MyBody::SetMass);
122 * MOCHI_PROPERTY_WITH_ERROR("centerOfMass", &MyBody::GetCenterOfMass);
123 * MOCHI_METHOD_WITH_ERROR("applyForce(force)", &MyBody::ApplyForce);
124 * MOCHI_STRUCT_END();
125 * };
126 *
127 * MOCHI_PROPERTY exposes a property through a getter and optional setter. Getters must work
128 * on a const object. Without a setter, a property is read-only unless the getter returns a
129 * non-const reference.
130 *
131 * MOCHI_METHOD exposes a callable method. Both macros accept member function pointers or
132 * stateless callables, such as lambdas that take the object as their first argument.
133 *
134 * The _WITH_ERROR variants require <mochi_core/utils/reflection_error.h>. They accept member
135 * or free function pointers, with or without a trailing Error&. They supply a local Error when
136 * needed. If it is set, they throw std::runtime_error with its description. Reflection callers
137 * do not pass the error argument. A plain getter can pair with a setter that takes Error&.
138 *
139 * See @ref SR_Property and @ref SR_Method for more details.
140 */
141
142/**
143 * When MOCHI_USE_REFLECTION is defined to 0, all Mochi reflection macros will compile out. This is
144 * the default so Mochi headers can be included externally without external users taking a
145 * dependency on Simple Reflection. Mochi's build system defins MOCHI_USE_REFLECTION=1 when
146 * compiling Mochi source code, so these features are always available internally.
147 */
148#ifndef MOCHI_USE_REFLECTION
149#define MOCHI_USE_REFLECTION 0
150#endif
151
152#if MOCHI_USE_REFLECTION
153
154#ifdef SIMPLE_REFLECTION_ENABLE
155#if !SIMPLE_REFLECTION_ENABLE
156#error MOCHI_USE_REFLECTION cannot be defined to 1 (true) if SIMPLE_REFLECTION_ENABLE has already been defined to 0 (false).
157#endif
158#else
159#define SIMPLE_REFLECTION_ENABLE 1
160#endif
161
162// Mochi reflection uses only Simple Reflection's picojson/string APIs; the nlohmann::json bridge
163// (SReflect::ToJson/FromJson) is never called. Disabling it keeps the heavy <nlohmann/json.hpp>
164// out of every TU that includes this header. Matches the CMake build (SR_USE_NLOHMANN_JSON=0).
165#ifndef SR_USE_NLOHMANN_JSON
166#define SR_USE_NLOHMANN_JSON 0
167#endif
168
169#ifdef assert_invariant
170#pragma push_macro("assert_invariant")
171#undef assert_invariant
172#define MOCHI_RESTORE_ASSERT_INVARIANT
173#endif
174
175#include <simple_reflection/simple_reflection.h>
176
177#ifdef MOCHI_RESTORE_ASSERT_INVARIANT
178#pragma pop_macro("assert_invariant")
179#undef MOCHI_RESTORE_ASSERT_INVARIANT
180#endif
181
182#define MOCHI_ENUM_BEGIN(name) \
183 IMPL_SR_BeginEnum(name); \
184 [[maybe_unused]] static constexpr int kEnumFirstItemLine = __LINE__ + 1;
185#define MOCHI_ENUM_ITEM(name) IMPL_SR_EnumItem(name)
186#define MOCHI_ENUM_COUNT(name) \
187 static_assert( \
188 static_cast<int>(MyEnum::name) == (__LINE__ - kEnumFirstItemLine), \
189 "Unexpected number of lines in reflection enum definition. Please make sure that every enum value is listed here (one per line).");
190#define MOCHI_ENUM_END() IMPL_SR_EndEnum()
191
192#define MOCHI_STRUCT_BEGIN(name) IMPL_SR_BeginStruct(name, #name)
193#define MOCHI_STRUCT_END() IMPL_SR_EndStruct()
194#define MOCHI_STRUCT(name) MOCHI_STRUCT_BEGIN(name) MOCHI_STRUCT_END()
195#define MOCHI_STRUCT_WITH_BASE(name, base) \
196 MOCHI_STRUCT_BEGIN(name) MOCHI_BASE_CLASS(base) MOCHI_STRUCT_END()
197
198#define MOCHI_STRUCT_BEGIN_EX(name) IMPL_SR_BeginStructEx(name)
199#define MOCHI_STRUCT_END_EX() IMPL_SR_EndStructEx()
200#define MOCHI_STRUCT_EX(name) MOCHI_STRUCT_BEGIN_EX(name) MOCHI_STRUCT_END_EX()
201#define MOCHI_STRUCT_WITH_BASE_EX(name, base) \
202 MOCHI_STRUCT_BEGIN_EX(name) MOCHI_BASE_CLASS(base) MOCHI_STRUCT_END_EX()
203
204#define MOCHI_STRUCT_DECLARE_EX(name) IMPL_SR_DeclareStructEx(name)
205#define MOCHI_STRUCT_DEFINITION_BEGIN_EX(name) IMPL_SR_BeginStructDefinitionEx(name)
206#define MOCHI_STRUCT_DEFINITION_END_EX() IMPL_SR_EndStructDefinitionEx()
207
208#define MOCHI_TEMPLATE_BEGIN(name, ...) IMPL_SR_BeginStructTemplate(name, __VA_ARGS__)
209#define MOCHI_TEMPLATE_END() IMPL_SR_EndStruct()
210#define MOCHI_TEMPLATE(name, ...) MOCHI_TEMPLATE_BEGIN(name, __VA_ARGS__) MOCHI_TEMPLATE_END()
211
212#define MOCHI_FIELD(name) IMPL_SR_Field_Name(name, #name)
213#define MOCHI_FIELD_NAME(realName, customName) IMPL_SR_Field_Name(realName, customName)
214#define MOCHI_REMOVE_FIELD(name) IMPL_SR_RemoveField(name)
215#define MOCHI_REPLACE_FIELD_NAME(realName, fieldNameToReplace) \
216 MOCHI_REMOVE_FIELD(fieldNameToReplace) MOCHI_FIELD_NAME(realName, fieldNameToReplace)
217
218#define MOCHI_PROPERTY(name, ...) IMPL_SR_Property(name, __VA_ARGS__)
219#define MOCHI_METHOD(name, ...) IMPL_SR_Method(name, __VA_ARGS__)
220
221#define MOCHI_BASE_CLASS(name) IMPL_SR_BaseClass(name)
222
223// MOCHI_ATTRIBUTE goes after the thing it describes.
224// See examples in the comment block above.
225#define MOCHI_ATTRIBUTE(...) \
226 { \
227 SReflect::detail::AddAttribute(*myInfo, new ::superdex::attribute::__VA_ARGS__); \
228 }
229
230// MOCHI_ATTRIBUTE_IF adds an attribute conditionally (must be constexpr). Used in templates where
231// the use of the attribute depends on the template parameters.
232#define MOCHI_ATTRIBUTE_IF(condition, ...) \
233 if constexpr (condition) { \
234 MOCHI_ATTRIBUTE(__VA_ARGS__); \
235 }
236
237namespace superdex {
238
239// Base class for all attributes
240using Attribute = SReflect::Attribute;
241
242} // namespace superdex
243
244namespace superdex::attribute {
245
246// [Struct Attribute] Assign a category string to the class/struct, for organization in UI.
247// Example: MOCHI_ATTRIBUTE(Category("text"))
248using Category = SReflect::Attribute_Category;
249
250// [Field Attribute] Marks a 3- or 4-element float field as a linear RGB / RGBA color, so tools can
251// show a color picker rather than numeric drags.
252// Example: MOCHI_ATTRIBUTE(Color)
253using Color = SReflect::Attribute_Color;
254
255// [General Attribute] Add a descriptive string to the struct/field/enum/item.
256// Example: MOCHI_ATTRIBUTE(Description("text"))
257using Description = SReflect::Attribute_Description;
258
259// [General Attribute] Changes how the struct/field/enum/item will appear in UI.
260// Example: MOCHI_ATTRIBUTE(DisplayName("text"))
261using DisplayName = SReflect::Attribute_DisplayName;
262
263// [General Attribute] Do not display the struct/field/enum/item in UI.
264// Example: MOCHI_ATTRIBUTE(HideFromEditor)
265using HideFromEditor = SReflect::Attribute_HideFromEditor;
266
267// [Field Attribute] Indicates that a field should never be serialized/deserialized.
268// Example: MOCHI_ATTRIBUTE(NoSerialize)
269using NoSerialize = SReflect::Attribute_DoNotSerialize;
270
271// [Struct/Field Attribute] Indicates that only fields with non-default values should be serialized.
272// As a field attribute, pass recursive=false to omit the field only when it equals its default,
273// while serializing it in full (all sub-fields shown) when present:
274// MOCHI_ATTRIBUTE(NoSerializeDefaults) // omit defaults, recursing into sub-fields
275// MOCHI_ATTRIBUTE(NoSerializeDefaults(false)) // omit only if the whole field is default
276using NoSerializeDefaults = SReflect::Attribute_DoNotSerializeDefaults;
277
278// [General Attribute] Indicates that something was renamed. Used for backward compatibility.
279// Example: MOCHI_ATTRIBUTE(PreviouslyKnownAs)
280using PreviouslyKnownAs = SReflect::Attribute_PreviouslyKnownAs;
281
282// [Field Attribute] Indicates the legal range of values for a field of signed integer type (any
283// size) Example: MOCHI_ATTRIBUTE(IntRange(-1, 1))
284using IntRange = SReflect::Attribute_IntRange;
285
286// [Field Attribute] Indicates the legal range of values for a field of type float or double.
287// Example: MOCHI_ATTRIBUTE(FloatRange(0_r, 1_r))
288using FloatRange = SReflect::Attribute_FloatRange;
289
290// [Field Attribute] Indicates the legal range of values for a field of unsigned integer type (any
291// size) Example: MOCHI_ATTRIBUTE(UIntRange(0, 1))
292using UIntRange = SReflect::Attribute_UIntRange;
293
294// [Field Attribute] Indicates that the field should appear read-only in tools.
295// Example: MOCHI_ATTRIBUTE(ReadOnly)
296// NOTE: This does not prevent serialization/deserialization.
297using ReadOnly = SReflect::Attribute_ReadOnly;
298
299// [Field Attribute] Indicates the SI unit of measure (short form like "m", "s", "m/s", etc...)
300// Example: MOCHI_ATTRIBUTE(Units("kg"))
301using Units = SReflect::Attribute_Units;
302
303// [Struct Attribute] Suppresses the extraneous-field issue that
304// DeserializeFlags::WarnIfExtraneousFields raises for JSON keys matching no field of this struct.
305// Use for structs that intentionally carry data beyond their reflected schema, so the surrounding
306// document still deserializes strictly. Example: MOCHI_ATTRIBUTE(IgnoreExtraneousFields)
307using IgnoreExtraneousFields = SReflect::Attribute_IgnoreExtraneousFields;
308
309// [Field Attribute] Marks a string field that stores a serialized JSON value: a JSON object/array
310// at this field is stored as its serialized text on load and re-emitted as that JSON value on save
311// (a deserialize/serialize round trip is identity). Applying it to a non-string field fails to
312// deserialize and reports an issue. Example: MOCHI_ATTRIBUTE(JsonString)
313using JsonString = SReflect::Attribute_JsonString;
314
315} // namespace superdex::attribute
316
317#else // if !MOCHI_USE_REFLECTION
318
319// It can be useful to add a semicolon after an attribute because that causes clang-format
320// to keep it on the same line as the thing it modifies. However, the compiler will see this
321// as a stray semicolon within when !MOCHI_USE_REFLECTION. Therefore we suppress the warning
322// within reflection definition blocks.
323#define IMPL_MOCHI_PUSH_IGNORE_EXTRA_SEMI() \
324 MOCHI_WARNING_PUSH() \
325 MOCHI_WARNING_IGNORE_GCC_CLANG(GCC diagnostic ignored "-Wextra-semi")
326
327#define MOCHI_ENUM_BEGIN(name) IMPL_MOCHI_PUSH_IGNORE_EXTRA_SEMI()
328#define MOCHI_ENUM_ITEM(name)
329#define MOCHI_ENUM_COUNT(name)
330#define MOCHI_ENUM_END() MOCHI_WARNING_POP()
331
332#define MOCHI_STRUCT_BEGIN(name) IMPL_MOCHI_PUSH_IGNORE_EXTRA_SEMI()
333#define MOCHI_STRUCT_END() MOCHI_WARNING_POP()
334#define MOCHI_STRUCT(name)
335#define MOCHI_STRUCT_WITH_BASE(name, base)
336
337#define MOCHI_STRUCT_BEGIN_EX(name) IMPL_MOCHI_PUSH_IGNORE_EXTRA_SEMI()
338#define MOCHI_STRUCT_END_EX() MOCHI_WARNING_POP()
339#define MOCHI_STRUCT_EX(name)
340#define MOCHI_STRUCT_WITH_BASE_EX(name, base)
341
342#define MOCHI_STRUCT_DECLARE_EX(name)
343#define MOCHI_STRUCT_DEFINITION_BEGIN_EX(name)
344#define MOCHI_STRUCT_DEFINITION_END_EX()
345
346#define MOCHI_TEMPLATE_BEGIN(name, ...)
347#define MOCHI_TEMPLATE_END()
348#define MOCHI_TEMPLATE(name, ...)
349
350#define MOCHI_BASE_CLASS(name)
351#define MOCHI_FIELD(name)
352#define MOCHI_FIELD_NAME(realName, customName)
353#define MOCHI_REMOVE_FIELD(name)
354#define MOCHI_REPLACE_FIELD_NAME(realName, fieldNameToReplace)
355#define MOCHI_PROPERTY(name, ...)
356#define MOCHI_METHOD(name, ...)
357#define MOCHI_ATTRIBUTE(...)
358#define MOCHI_ATTRIBUTE_IF(condition, ...)
359
360#endif // !MOCHI_USE_REFLECTION
NdArray< uint8_t, 4 > Color
RGBA color representation using 4 bytes (0-255 per channel) in RGBA order.
Definition color.h:33