Files
XCEngine/engine/src/Components/RigidbodyComponent.cpp

76 lines
2.2 KiB
C++
Raw Normal View History

#include "Components/RigidbodyComponent.h"
#include <algorithm>
#include <cmath>
#include <sstream>
namespace XCEngine {
namespace Components {
namespace {
float SanitizePositiveFinite(float value, float fallback) {
return std::isfinite(value) && value > 0.0f ? value : fallback;
}
float SanitizeNonNegativeFinite(float value, float fallback) {
return std::isfinite(value) && value >= 0.0f ? value : fallback;
}
} // namespace
void RigidbodyComponent::SetMass(float value) {
m_mass = SanitizePositiveFinite(value, 1.0f);
}
void RigidbodyComponent::SetLinearDamping(float value) {
m_linearDamping = SanitizeNonNegativeFinite(value, 0.0f);
}
void RigidbodyComponent::SetAngularDamping(float value) {
m_angularDamping = SanitizeNonNegativeFinite(value, 0.05f);
}
void RigidbodyComponent::Serialize(std::ostream& os) const {
os << "bodyType=" << static_cast<int>(m_bodyType) << ";";
os << "mass=" << m_mass << ";";
os << "linearDamping=" << m_linearDamping << ";";
os << "angularDamping=" << m_angularDamping << ";";
os << "useGravity=" << (m_useGravity ? 1 : 0) << ";";
os << "enableCCD=" << (m_enableCCD ? 1 : 0) << ";";
}
void RigidbodyComponent::Deserialize(std::istream& is) {
std::string token;
while (std::getline(is, token, ';')) {
if (token.empty()) {
continue;
}
const size_t eqPos = token.find('=');
if (eqPos == std::string::npos) {
continue;
}
const std::string key = token.substr(0, eqPos);
const std::string value = token.substr(eqPos + 1);
if (key == "bodyType") {
m_bodyType = static_cast<Physics::PhysicsBodyType>(std::stoi(value));
} else if (key == "mass") {
SetMass(std::stof(value));
} else if (key == "linearDamping") {
SetLinearDamping(std::stof(value));
} else if (key == "angularDamping") {
SetAngularDamping(std::stof(value));
} else if (key == "useGravity") {
m_useGravity = (std::stoi(value) != 0);
} else if (key == "enableCCD") {
m_enableCCD = (std::stoi(value) != 0);
}
}
}
} // namespace Components
} // namespace XCEngine