Major Update - Physique Fixed Update And Thread

Physics process run in a fixed update in a thread
This commit is contained in:
CatChow0 2025-01-17 15:47:09 +01:00
parent 15217a5df8
commit 4ae55e73b2
7 changed files with 142 additions and 114 deletions

View File

@ -144,9 +144,6 @@ void SystemClass::Run()
// Loop until there is a quit message from the window or the user.
done = false;
auto fixedUpdateInterval = std::chrono::milliseconds(16);
auto m_lastFixedUpdateTime = std::chrono::steady_clock::now();
while (!done)
{
// Handle the windows messages.
@ -178,13 +175,6 @@ void SystemClass::Run()
Logger::Get().Log("Failed to process frame", __FILE__, __LINE__, Logger::LogLevel::Error);
done = true;
}
auto now = std::chrono::steady_clock::now();
if (now - m_lastFixedUpdateTime >= fixedUpdateInterval)
{
FixedUpdate();
m_lastFixedUpdateTime = now;
}
}
}
@ -476,9 +466,4 @@ void SystemClass::SendPath(wchar_t* path, std::filesystem::path WFolder)
{
m_Application->SetPath(path);
m_Application->SetWFolder(WFolder);
}
void SystemClass::FixedUpdate()
{
m_Application->GetPhysics()->Update();
}

View File

@ -35,6 +35,12 @@ ApplicationClass::~ApplicationClass()
{
m_ShouldQuit = true;
// Joindre le thread pour s'assurer qu'il se termine correctement
if (m_PhysicsThread.joinable())
{
m_PhysicsThread.join();
}
}
@ -416,6 +422,7 @@ bool ApplicationClass::Initialize(int screenWidth, int screenHeight, HWND hwnd)
m_Physics = new Physics;
m_PhysicsThread = std::thread(&ApplicationClass::PhysicsThreadFunction, this);
}
catch (const std::exception& e)
@ -430,7 +437,6 @@ bool ApplicationClass::Initialize(int screenWidth, int screenHeight, HWND hwnd)
return true;
}
void ApplicationClass::Shutdown()
{
Logger::Get().Log("Shutting down application class", __FILE__, __LINE__, Logger::LogLevel::Shutdown);
@ -785,7 +791,9 @@ bool ApplicationClass::Frame(InputClass* Input)
m_Inputs.m_KeyUp = Input->IsUpArrowPressed();
m_Inputs.m_KeyDown = Input->IsDownArrowPressed();
RenderPhysics(m_Inputs.m_KeyLeft, m_Inputs.m_KeyRight, m_Inputs.m_KeyUp, m_Inputs.m_KeyDown, frameTime);
//RenderPhysics(m_Inputs.m_KeyLeft, m_Inputs.m_KeyRight, m_Inputs.m_KeyUp, m_Inputs.m_KeyDown, frameTime);
// Render the scene to a render texture.
result = RenderSceneToTexture(rotation);
@ -952,8 +960,6 @@ bool ApplicationClass::Render(float rotation, float x, float y, float z, float t
// Generate the view matrix based on the camera's position.
m_Camera->Render();
// Get the world, view, and projection matrices from the camera and d3d objects.
worldMatrix = m_Direct3D->GetWorldMatrix();
@ -1909,8 +1915,6 @@ void ApplicationClass::ConstructFrustum()
bool ApplicationClass::RenderPhysics(bool keyLeft, bool keyRight, bool keyUp, bool keyDown, float deltaTime) {
const float maxSpeed = 50.0f; // Limite de vitesse maximale
const int subSteps = 10; // Nombre de sous-étapes pour la simulation
const float subDeltaTime = deltaTime / subSteps;
for (auto& object : m_object) {
if (object == nullptr) {
@ -1922,91 +1926,99 @@ bool ApplicationClass::RenderPhysics(bool keyLeft, bool keyRight, bool keyUp, bo
continue;
}
for (int step = 0; step < subSteps; ++step) {
// Reset acceleration for the new frame
object->SetAcceleration(XMVectorZero());
object->SetGrounded(false);
// Reset acceleration for the new frame
object->SetAcceleration(XMVectorZero());
object->SetGrounded(false);
for (auto& chunk : m_terrainChunk) {
if (!m_Physics->IsColliding(object, chunk)) {
continue;
}
object->SetVelocity(XMVectorSetY(object->GetVelocity(), 0.0f));
object->SetAcceleration(XMVectorSetY(object->GetAcceleration(), 0.0f));
object->SetGrounded(true);
for (auto& chunk : m_terrainChunk) {
if (!m_Physics->IsColliding(object, chunk)) {
continue;
}
for (auto& object2 : m_object) {
if (object->GetId() == object2->GetId()) {
continue;
}
if (!m_Physics->IsColliding(object, object2)) {
continue;
}
object->SetVelocity(XMVectorZero());
object->SetAcceleration(XMVectorZero());
}
float forceX = 0, forceY = 0, forceZ = 0, forceW = 0;
if (keyLeft) {
forceX = -10.0f;
}
if (keyRight) {
forceX = 10.0f;
}
if (keyUp) {
forceY = 40.0f;
}
if (keyDown && !object->IsGrounded()) {
forceY = -40.0f;
}
XMVECTOR force = XMVectorSet(forceX, forceY, forceZ, forceW);
m_Physics->AddForce(object, force);
object->AddVelocity(subDeltaTime);
XMVECTOR velocity = object->GetVelocity();
float speed = XMVectorGetX(XMVector3Length(velocity));
if (speed > maxSpeed) {
velocity = XMVectorScale(velocity, maxSpeed / speed);
object->SetVelocity(velocity);
}
XMVECTOR position = object->GetPosition();
position = position + object->GetVelocity() * subDeltaTime;
object->SetPosition(position);
m_Physics->ApplyGravity(object, subDeltaTime);
if (XMVectorGetY(object->GetPosition()) < -30.0f) {
XMVECTOR currentPosition = object->GetPosition();
object->SetPosition(XMVectorSetY(currentPosition, 50.0f));
}
object->m_previousPosition = object->GetPosition();
object->SetVelocity(XMVectorSetY(object->GetVelocity(), 0.0f));
object->SetAcceleration(XMVectorSetY(object->GetAcceleration(), 0.0f));
object->SetGrounded(true);
}
for (auto& object2 : m_object) {
if (object->GetId() == object2->GetId()) {
continue;
}
if (!m_Physics->IsColliding(object, object2)) {
continue;
}
object->SetVelocity(XMVectorZero());
object->SetAcceleration(XMVectorZero());
}
float forceX = 0, forceY = 0, forceZ = 0, forceW = 0;
if (keyLeft) {
forceX = -10.0f;
}
if (keyRight) {
forceX = 10.0f;
}
if (keyUp) {
forceY = 40.0f;
}
if (keyDown && !object->IsGrounded()) {
forceY = -40.0f;
}
XMVECTOR force = XMVectorSet(forceX, forceY, forceZ, forceW);
m_Physics->AddForce(object, force);
object->AddVelocity(deltaTime);
XMVECTOR velocity = object->GetVelocity();
float speed = XMVectorGetX(XMVector3Length(velocity));
if (speed > maxSpeed) {
velocity = XMVectorScale(velocity, maxSpeed / speed);
object->SetVelocity(velocity);
}
XMVECTOR position = object->GetPosition();
position = position + object->GetVelocity() * deltaTime;
object->SetPosition(position);
m_Physics->ApplyGravity(object, deltaTime);
if (XMVectorGetY(object->GetPosition()) < -30.0f) {
XMVECTOR currentPosition = object->GetPosition();
object->SetPosition(XMVectorSetY(currentPosition, 50.0f));
}
object->m_previousPosition = object->GetPosition();
}
return true;
}
void ApplicationClass::PhysicsThreadFunction()
{
auto fixedUpdateInterval = std::chrono::milliseconds(1000 / m_PhysicsTickRate);
auto lastTime = std::chrono::steady_clock::now();
while (!m_ShouldQuit)
{
bool result = RenderPhysics(m_Inputs.m_KeyLeft, m_Inputs.m_KeyRight, m_Inputs.m_KeyUp, m_Inputs.m_KeyDown, m_Timer->GetTime());
if (!result)
auto now = std::chrono::steady_clock::now();
if (now - lastTime >= fixedUpdateInterval)
{
Logger::Get().Log("Could not render the physics scene", __FILE__, __LINE__, Logger::LogLevel::Error);
return;
lastTime = now;
float deltaTime = 1.0f / static_cast<float>(m_PhysicsTickRate);
bool result = RenderPhysics(m_Inputs.m_KeyLeft, m_Inputs.m_KeyRight, m_Inputs.m_KeyUp, m_Inputs.m_KeyDown, deltaTime);
if (!result)
{
Logger::Get().Log("Could not render the physics scene", __FILE__, __LINE__, Logger::LogLevel::Error);
return;
}
}
// Attendre un peu pour éviter de surcharger le CPU
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}

View File

@ -34,6 +34,7 @@
#include <WICTextureLoader.h>
#include <comdef.h> // Pour _com_error
#include <chrono>
#include <thread>
/////////////
@ -66,6 +67,8 @@ public:
void Shutdown();
bool Frame(InputClass*);
void PhysicsThreadFunction();
int GetPhysicsTickRate() const { return m_PhysicsTickRate; };
void SetPhysicsTickRate(int physicsTickRate) { m_PhysicsTickRate = physicsTickRate; };
int GetScreenWidth() const;
void SetScreenWidth(int screenWidth);
@ -130,6 +133,9 @@ public:
float GetFrustumTolerance() const { return m_FrustumCullingTolerance; };
void SetFrustumTolerance(float frustumTolerance) { m_FrustumCullingTolerance = frustumTolerance; };
bool GetCanFixedUpdate() const { return CanFixedUpdate; };
void SetCanFixedUpdate(bool canFixedUpdate) { CanFixedUpdate = canFixedUpdate; };
private:
bool Render(float, float, float, float, float);
@ -232,6 +238,9 @@ private :
float m_gravity;
XMVECTOR m_previousPosition;
ImVec2 windowSize;
int m_PhysicsTickRate = 50;
bool CanFixedUpdate = false;
std::thread m_PhysicsThread;
// ------------------------------------------------- //
// ------------------- Culling --------------------- //

View File

@ -4,55 +4,57 @@ Size=400,400
Collapsed=0
[Window][Khaotic Engine]
Pos=1201,27
Size=375,826
Pos=1537,27
Size=375,974
Collapsed=0
DockId=0x00000005,0
[Window][Objects]
Pos=8,27
Size=330,826
Pos=8,516
Size=330,485
Collapsed=0
DockId=0x00000001,1
DockId=0x00000006,0
[Window][Terrain]
Pos=8,27
Size=330,826
Size=330,487
Collapsed=0
DockId=0x00000001,0
DockId=0x00000004,0
[Window][Light]
Pos=1648,27
Size=392,1094
Pos=8,27
Size=330,487
Collapsed=0
DockId=0x00000005,1
DockId=0x00000004,1
[Window][Shader Manager]
Pos=8,27
Size=330,1094
Size=330,487
Collapsed=0
DockId=0x00000001,2
DockId=0x00000004,2
[Window][Engine Settings]
Pos=1201,27
Size=375,826
Pos=1537,27
Size=375,974
Collapsed=0
DockId=0x00000005,1
[Window][DockSpace Demo]
Pos=0,0
Size=1584,861
Size=1920,1009
Collapsed=0
[Window][Render Window]
Pos=340,27
Size=859,826
Size=1195,974
Collapsed=0
DockId=0x00000002,0
[Docking][Data]
DockSpace ID=0xC0DFADC4 Window=0xD0388BC8 Pos=8,27 Size=1568,826 Split=X
DockNode ID=0x00000001 Parent=0xC0DFADC4 SizeRef=330,1094 Selected=0x031DC75C
DockSpace ID=0xC0DFADC4 Window=0xD0388BC8 Pos=8,27 Size=1904,974 Split=X
DockNode ID=0x00000001 Parent=0xC0DFADC4 SizeRef=330,1094 Split=Y Selected=0x393905AB
DockNode ID=0x00000004 Parent=0x00000001 SizeRef=330,487 Selected=0x393905AB
DockNode ID=0x00000006 Parent=0x00000001 SizeRef=330,485 Selected=0x031DC75C
DockNode ID=0x00000003 Parent=0xC0DFADC4 SizeRef=1700,1094 Split=X
DockNode ID=0x00000002 Parent=0x00000003 SizeRef=1655,1094 CentralNode=1 Selected=0x9204953B
DockNode ID=0x00000005 Parent=0x00000003 SizeRef=375,1094 Selected=0x9F035453

View File

@ -477,6 +477,13 @@ void imguiManager::WidgetEngineSettingsWindow(ApplicationClass* app)
app->SetFrustumTolerance(frustumTolerance);
}
// Input To set the Fixed Update Interval
int physicsInterval = app->GetPhysicsTickRate();
if (ImGui::InputInt("Physics Tick Rate", &physicsInterval))
{
app->SetPhysicsTickRate(physicsInterval);
}
ImGui::End();
}

View File

@ -93,12 +93,25 @@ XMVECTOR Object::GetScale()
{
XMFLOAT4X4 matrix;
XMStoreFloat4x4(&matrix, m_scaleMatrix);
float scaleX = XMVectorGetX(XMVector3Length(XMVectorSet(matrix._11, matrix._12, matrix._13, 0.0f)));
float scaleY = XMVectorGetX(XMVector3Length(XMVectorSet(matrix._21, matrix._22, matrix._23, 0.0f)));
float scaleZ = XMVectorGetX(XMVector3Length(XMVectorSet(matrix._31, matrix._32, matrix._33, 0.0f)));
return XMVectorSet(scaleX, scaleY, scaleZ, 0.0f);
// Utiliser des vecteurs pour les lignes de la matrice
XMVECTOR row1 = XMLoadFloat3(reinterpret_cast<XMFLOAT3*>(&matrix._11));
XMVECTOR row2 = XMLoadFloat3(reinterpret_cast<XMFLOAT3*>(&matrix._21));
XMVECTOR row3 = XMLoadFloat3(reinterpret_cast<XMFLOAT3*>(&matrix._31));
// Calculer les longueurs des vecteurs
XMVECTOR scale = XMVectorSet(
XMVectorGetX(XMVector3Length(row1)),
XMVectorGetX(XMVector3Length(row2)),
XMVectorGetX(XMVector3Length(row3)),
0.0f
);
return scale;
}
void Object::SetPosition(XMVECTOR position)
{
XMFLOAT4X4 matrix;

View File

@ -160,7 +160,7 @@ bool Physics::SphereCubeOverlap(Object* cube, Object* sphere)
XMVECTOR position2 = sphere->GetPosition();
XMVECTOR scale1 = cube->GetScale();
XMVECTOR scale2 = sphere->GetScale() / 2;
XMVECTOR scale2 = XMVectorScale(sphere->GetScale(), 0.5f);
XMVECTOR min1 = position1 - scale1;
XMVECTOR max1 = position1 + scale1;