Fx2D
A C++20 2D rigid-body physics engine
Loading...
Searching...
No Matches
Entity.h
Go to the documentation of this file.
1
2#pragma once
3
4#include <memory>
5#include <stdexcept>
6#include <string>
7
8#include "Fx2D/Geometry.h"
9
10inline bool is_valid_name(const std::string& s) {
11 if (s.empty()) return false;
12 return std::all_of(s.begin(), s.end(), [](unsigned char c) {
13 return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||
14 c == '_';
15 });
16}
17
18// container for visual shape
19struct FxVisualShape : public FxShape {
20 private:
21 FxVec4ui8 m_fillColor{200, 200, 200, 255}; // Fill color (RGBA)
22 FxVec4ui8 m_outlineColor{10, 10, 10, 255}; // Outline color (RGBA)
23 float m_outlineThickness = 2.5f; // Outline thickness in pixels
24 std::string m_fillTexturePath = ""; // File path to texture file (empty = no texture)
25 public:
26 // 1. "Inherit" all of FxShape's ctors
27 using FxShape::FxShape;
28 // 2. Conversion‐style ctor: build a VisualShape from any Shape
29 FxVisualShape(const FxShape& base) : FxShape(base) {}
30 // Method to set a fillColor, outlineColor and texture
31 void set_fillColor(const FxVec4ui8& color) {
32 m_fillColor = color;
33 m_fillTexturePath = "";
34 }
35 void set_outlineColor(const FxVec4ui8& color) { m_outlineColor = color; }
36 void set_outlineThickness(const float& thickness) { m_outlineThickness = thickness; }
37 void set_fillTexture(const std::string& filePath) { m_fillTexturePath = filePath; }
38 // getters for all the attributes
39 const FxVec4ui8& fillColor() const { return m_fillColor; }
40 const std::string& fillTexture() const { return m_fillTexturePath; }
41 const FxVec4ui8& outlineColor() const { return m_outlineColor; }
42 float outlineThickness() const { return m_outlineThickness; }
43};
44
45// container for collision shape
47
48// Class for entity attributes and methods
49class FxEntity {
50 private:
51 // unique identifier assigned by scene or registry
52 uint32_t m_entity_id = 0;
53
54 // unique name for an entity
55 std::string m_name;
56
57 // mass and inertia
58 float _mass = 1.0f;
59 float _inertia = 1.0f; // around center of mass
60 float _inv_mass = 1.0f;
61 float _inv_inertia = 1.0f;
62
63 // store initial state for reset
64 FxVec3f _init_pose{0, 0, 0};
65 FxVec3f _init_velocity{0, 0, 0};
66 FxVec3d m_pose_carry{0, 0, 0};
67 // Constraint-correction residual, separate so it cannot borrow the integration leftover.
68 FxVec3d m_correction_carry{0, 0, 0};
69
70 // visual and collision shapes
71 std::shared_ptr<FxCollisionShape> m_collision;
72 std::shared_ptr<FxVisualShape> m_visual = std::make_shared<FxVisualShape>();
73
74 // total resultant force and moment on the body
75 float m_eff_moment = 0.0f;
76 FxVec2f m_eff_force{0, 0};
77 // What was applied between steps, held for every substep of the next (hold_step_forces).
78 float m_step_moment = 0.0f;
79 FxVec2f m_step_force{0, 0};
80
81 // accumulated impulses for the current step
82 float m_eff_impulse_moment = 0.0f;
83 FxVec2f m_eff_impulse{0, 0};
84
85 // axis aligned bounding box in world coordinates
86 FxArray<float> m_bounding_box{-1.0f, -1.0f, -1.0f, -1.0f};
87
88 // sleep state tracking
89 float m_sleep_timer = 0.0f;
90 bool m_sleeping = false;
91
92 // Broad-phase bookkeeping, owned by FxEntityRegistry. Held on the entity rather than in a
93 // side map because the broad phase reads them once per entity per substep, and a hash
94 // lookup there is pure overhead on a value the entity can just carry.
95 int32_t m_broad_phase_node = -1; // leaf index in the registry's AABB tree, -1 = not in tree
96 int32_t m_packed_index = -1; // position in the registry's packed storage, -1 = unregistered
97
98 // update pose from velocity
99 void __update_pose(const double& step_dt);
100
101 public:
102 // current state (public interface - single precision)
103 FxVec3f pose{0, 0, 0}; // x, y, theta
104 FxVec3f velocity{0, 0, 0}; // velocity along x, y axis and angular velocity along z axis
105
106 // previous pose and velocity for tracking changes (public interface)
109
110 // physics config
111 float elasticity = 0.1f; // restitution mixes by max, so 1.0 made every
112 // unconfigured body a perfect trampoline
113 float vel_damping = 0.0f; // drag: each substep divides velocity by (1 + h * vel_damping)
114 float gravity_scale = 1.0f;
115 float static_friction = 0.0f;
116 float dynamic_friction = 0.0f;
117
118 // entity state
119 bool enabled = true; // If false, entity is skipped in physics updates, collisions, and
120 // rendering
121 bool enable_ccd = false; // If true, speculative contacts are generated for this entity to
122 // prevent tunneling
123 bool is_sensor = false; // Detects overlaps but exchanges no impulses; reported as events
124 int32_t collision_group = 0; // Entities sharing a negative value never collide with each
125 // other; 0 means no group filtering
126
127 // sleep configuration
128 float sleep_threshold_linear = 0.01f; // linear speed below which entity may sleep
129 float sleep_threshold_angular = 0.05f; // angular speed below which entity may sleep
130 float sleep_time_required = 0.5f; // seconds of low motion before sleeping
131 bool is_sleeping() const { return m_sleeping; }
132 void wake() {
133 m_sleeping = false;
134 m_sleep_timer = 0.0f;
135 }
136 void sleep() { m_sleeping = true; }
137 void tick_sleep(float dt); // advance sleep timer; called by FxScene each step
138
139 // contructor with name validation
140 explicit FxEntity(const std::string& entityName);
141
142 // getter for the name and ID
143 const std::string& get_name() const { return m_name; }
144 uint32_t get_entity_id() const { return m_entity_id; }
145 void set_entity_id(uint32_t id) { m_entity_id = id; }
146
147 // Registry-owned broad-phase bookkeeping. These are written by FxEntityRegistry as entities
148 // are added, removed and inserted into the tree; nothing else should set them.
149 int32_t broad_phase_node() const { return m_broad_phase_node; }
150 void set_broad_phase_node(int32_t node) { m_broad_phase_node = node; }
151 int32_t packed_index() const { return m_packed_index; }
152 void set_packed_index(int32_t index) { m_packed_index = index; }
153
154 // resets current state to inital state
155 void reset();
156 // Place the body at a pose and velocity as if it started there: no carried rounding or
157 // pending forces, awake, shapes at the new pose. reset() is this with the initial state.
158 void set_state(const FxVec3f& o_pose, const FxVec3f& o_velocity);
159
160 // methods to set mass and inertia
161 void set_mass(const float& mass);
162 void set_inertia(); // calculate based on shape
163 void set_inertia(const float& inertia);
164 // methods to get mass and inertia
165 float mass() const { return _mass; }
166 float inertia() const { return _inertia; }
167 float inv_mass() const { return _inv_mass; }
168 float inv_inertia() const { return _inv_inertia; }
169
170 // methods to set initial pose and velocity
171 void set_init_pose(const FxVec3f& o_pose);
172 void set_init_velocity(const FxVec3f& o_velocity);
173 // Enable or disable external forces and torques, including effects due to collisions
174 void enable_external_forces(bool enable);
175
176 // clear existing visual and collison shapes and assign new
178 m_visual = std::make_shared<FxVisualShape>(std::move(visual));
179 m_visual->set_world_pose(pose);
180 }
182 m_collision = std::make_shared<FxCollisionShape>(std::move(collision));
183 // Filled here, not left to the first integration: an immovable body may never
184 // integrate at all, and a box still at its {-1,-1,-1,-1} default is rejected by the
185 // broad phase and silently collides with nothing.
186 m_collision->set_world_pose(pose, m_bounding_box);
187 }
188 // getters for visual and collison shapes
189 // By reference: returning by value cost an atomic pair per call, and the broad and narrow
190 // phases call these several times per pair per substep. Valid until the shape is replaced.
191 const std::shared_ptr<FxVisualShape>& visual_geometry() const { return m_visual; }
192 const std::shared_ptr<FxCollisionShape>& collision_geometry() const { return m_collision; }
193 // methods to delete visual and collision shapes
194 void del_visual_geometry() { m_visual.reset(); };
195 void del_collision_geometry() { m_collision.reset(); };
196
197 // collision detection methods
198 // By reference: returning the FxArray by value made every narrow-phase pair allocate.
200 bool aabb_overlap_check(const FxEntity& other) const;
201 bool aabb_overlap_check(const std::shared_ptr<FxEntity>& other) const;
202
203 // apply external influences
204 void apply_torque(float torque);
205 void apply_force(const FxVec2f& force);
206 void apply_force(const FxVec2f& force, const FxVec2f& contact_point);
207 void apply_impulse(const FxVec2f& impulse);
208 void apply_impulse(const FxVec2f& impulse, const FxVec2f& contact_point);
209
210 // Get instantaneous velocity at a specific position
212 FxVec2f velocity_at_local_point(const FxVec2f& local_position) const;
213 // Vector implementations of above
216
217 // Convert local point to world coordinates and vice-versa
218 FxVec2f to_world_frame(const FxVec2f& local_point) const;
219 FxVec2f to_entity_frame(const FxVec2f& world_point) const;
220
221 // resolve the forces and torques and calculate acceleration;
224
225 // Mixed-precision positional correction, returning the delta that landed so prev_pose can
226 // be shifted to match. Sub-ulp corrections are banked in double rather than rounded away.
228
229 // place_shapes = false leaves the shapes where they were: FxScene places them only on a
230 // step's first substep, and later for the pairs it tests (refresh_collision_shape).
231 void step(const FxVec2f& gravity, const double& step_dt, bool place_shapes = true);
232 // FxScene calls this before a step's substeps: forces applied since the last step act on
233 // every substep of this one, while those applied during it, as joint motors do, last one.
235 // Bring the collision shape and bounding box, or every shape, to the current pose.
238
240};
FxShape FxCollisionShape
Definition Entity.h:46
bool is_valid_name(const std::string &s)
Definition Entity.h:10
FxArray< FxVec2f > FxVec2fArray
Definition Math.h:1075
FxVec< uint8_t, 4 > FxVec4ui8
Definition Math.h:422
Fixed-size, aligned value array.
Definition Math.h:638
void set_init_pose(const FxVec3f &o_pose)
void apply_impulse(const FxVec2f &impulse)
int32_t packed_index() const
Definition Entity.h:151
FxVec3f apply_pose_correction(const FxVec3f &delta)
void hold_step_forces()
float gravity_scale
Definition Entity.h:114
void step(const FxVec2f &gravity, const double &step_dt, bool place_shapes=true)
float vel_damping
Definition Entity.h:113
float inv_mass() const
Definition Entity.h:167
bool enable_ccd
Definition Entity.h:121
void reset()
~FxEntity()
Definition Entity.h:239
FxVec2f velocity_at_local_point(const FxVec2f &local_position) const
void set_mass(const float &mass)
const std::shared_ptr< FxCollisionShape > & collision_geometry() const
Definition Entity.h:192
void set_inertia(const float &inertia)
bool aabb_overlap_check(const std::shared_ptr< FxEntity > &other) const
void sleep()
Definition Entity.h:136
float sleep_threshold_linear
Definition Entity.h:128
int32_t broad_phase_node() const
Definition Entity.h:149
float sleep_threshold_angular
Definition Entity.h:129
FxVec2f to_entity_frame(const FxVec2f &world_point) const
void set_packed_index(int32_t index)
Definition Entity.h:152
void apply_force(const FxVec2f &force)
FxVec2fArray velocity_at_local_point(const FxVec2fArray &local_position) const
void refresh_world_shapes()
void set_entity_id(uint32_t id)
Definition Entity.h:145
float mass() const
Definition Entity.h:165
const std::shared_ptr< FxVisualShape > & visual_geometry() const
Definition Entity.h:191
bool is_sensor
Definition Entity.h:123
bool aabb_overlap_check(const FxEntity &other) const
void del_visual_geometry()
Definition Entity.h:194
FxVec2f to_world_frame(const FxVec2f &local_point) const
float inertia() const
Definition Entity.h:166
void set_inertia()
void del_collision_geometry()
Definition Entity.h:195
void set_collision_geometry(FxCollisionShape collision)
Definition Entity.h:181
float sleep_time_required
Definition Entity.h:130
FxVec2fArray velocity_at_world_point(const FxVec2fArray &position) const
float elasticity
Definition Entity.h:111
void enable_external_forces(bool enable)
FxVec3f prev_velocity
Definition Entity.h:108
float dynamic_friction
Definition Entity.h:116
FxVec3f calc_acceleration()
void wake()
Definition Entity.h:132
uint32_t get_entity_id() const
Definition Entity.h:144
FxVec3f pose
Definition Entity.h:103
const FxArray< float > & bounding_box() const
FxEntity(const std::string &entityName)
int32_t collision_group
Definition Entity.h:124
void apply_force(const FxVec2f &force, const FxVec2f &contact_point)
void set_init_velocity(const FxVec3f &o_velocity)
void set_visual_geometry(FxVisualShape visual)
Definition Entity.h:177
FxVec3f calc_acceleration(const FxVec2f &gravity)
const std::string & get_name() const
Definition Entity.h:143
FxVec2f velocity_at_world_point(const FxVec2f &position) const
FxVec3f velocity
Definition Entity.h:104
void set_broad_phase_node(int32_t node)
Definition Entity.h:150
float static_friction
Definition Entity.h:115
FxVec3f prev_pose
Definition Entity.h:107
float inv_inertia() const
Definition Entity.h:168
void refresh_collision_shape()
void tick_sleep(float dt)
void set_state(const FxVec3f &o_pose, const FxVec3f &o_velocity)
void apply_impulse(const FxVec2f &impulse, const FxVec2f &contact_point)
bool is_sleeping() const
Definition Entity.h:131
bool enabled
Definition Entity.h:119
void apply_torque(float torque)
Single-precision 2D vector.
Double-precision three-component vector.
Single-precision three-component vector, including poses.
Unified circle, capsule, polygon, edge, and chain representation.
Definition Geometry.h:46
FxShape()
Definition Geometry.h:86
const std::string & fillTexture() const
Definition Entity.h:40
void set_fillTexture(const std::string &filePath)
Definition Entity.h:37
void set_outlineThickness(const float &thickness)
Definition Entity.h:36
float outlineThickness() const
Definition Entity.h:42
FxVisualShape(const FxShape &base)
Definition Entity.h:29
void set_fillColor(const FxVec4ui8 &color)
Definition Entity.h:31
const FxVec4ui8 & fillColor() const
Definition Entity.h:39
void set_outlineColor(const FxVec4ui8 &color)
Definition Entity.h:35
const FxVec4ui8 & outlineColor() const
Definition Entity.h:41