squash merge threaded-physics into main

This commit is contained in:
2026-02-24 18:45:13 +01:00
parent 3e87bbb6a5
commit 8a4e5c1ebf
15 changed files with 553 additions and 466 deletions

View File

@ -3,7 +3,6 @@
#include <raylib.h>
#define BARNES_HUT // Use octree BH instead of uniform grid
// #define WEB // Disables multithreading
// Window
@ -30,19 +29,17 @@ constexpr float ROT_SPEED = 1.0;
constexpr float CAMERA_SMOOTH_SPEED = 15.0;
// Physics Engine
constexpr float SIM_SPEED = 4.0; // How large each update should be
constexpr float TIMESTEP = 1.0 / 90; // Do 90 physics updates per second
constexpr float MASS = 1.0; // Mass spring system
constexpr float SPRING_CONSTANT = 5.0; // Mass spring system
constexpr float DAMPENING_CONSTANT = 1.0; // Mass spring system
constexpr float REST_LENGTH = 2.0; // Mass spring system
constexpr float VERLET_DAMPENING = 0.05; // [0, 1]
constexpr float BH_FORCE = 2.0; // BH: [1.0, 3.0]
constexpr float THETA = 1.0; // Barnes-Hut [0.5, 1.0]
constexpr float SOFTENING = 0.01; // Barnes-Hut [0.01, 1.0]
constexpr float GRID_FORCE = 0.02; // Grid: [0.0, ~0.05]
constexpr float REPULSION_RANGE = 5.0 * REST_LENGTH; // Grid
constexpr int REPULSION_GRID_REFRESH = 5; // Grid rebuild freq
constexpr float TARGET_UPS = 90; // How often to update physics
constexpr float TIMESTEP = 1.0 / TARGET_UPS; // Update interval in seconds
constexpr float SIM_SPEED = 4.0; // How large each update should be
constexpr float MASS = 1.0; // Mass spring system
constexpr float SPRING_CONSTANT = 5.0; // Mass spring system
constexpr float DAMPENING_CONSTANT = 1.0; // Mass spring system
constexpr float REST_LENGTH = 2.0; // Mass spring system
constexpr float VERLET_DAMPENING = 0.05; // [0, 1]
constexpr float BH_FORCE = 2.0; // Barnes-Hut [1.0, 3.0]
constexpr float THETA = 0.9; // Barnes-Hut [0.5, 1.0]
constexpr float SOFTENING = 0.01; // Barnes-Hut [0.01, 1.0]
// Graph Drawing
constexpr float VERTEX_SIZE = 0.5;

View File

@ -1,13 +1,11 @@
#ifndef __INPUT_HPP_
#define __INPUT_HPP_
#include "renderer.hpp"
#include "state.hpp"
class InputHandler {
public:
StateManager &state;
Renderer &renderer;
int hov_x;
int hov_y;
@ -18,10 +16,14 @@ public:
int block_add_x;
int block_add_y;
bool mark_solutions;
bool connect_solutions;
public:
InputHandler(StateManager &_state, Renderer &_renderer)
: state(_state), renderer(_renderer), hov_x(-1), hov_y(-1), sel_x(0),
sel_y(0), has_block_add_xy(false), block_add_x(-1), block_add_y(-1) {}
InputHandler(StateManager &_state)
: state(_state), hov_x(-1), hov_y(-1), sel_x(0), sel_y(0),
has_block_add_xy(false), block_add_x(-1), block_add_y(-1),
mark_solutions(false), connect_solutions(false) {}
InputHandler(const InputHandler &copy) = delete;
InputHandler &operator=(const InputHandler &copy) = delete;

View File

@ -1,19 +1,22 @@
#ifndef __PHYSICS_HPP_
#define __PHYSICS_HPP_
#include <atomic>
#include <condition_variable>
#include <cstddef>
#include <mutex>
#include <queue>
#include <raylib.h>
#include <raymath.h>
#include <unordered_map>
#include <thread>
#include <tracy/Tracy.hpp>
#include <variant>
#include <vector>
#include "config.hpp"
#include "puzzle.hpp"
#ifdef BARNES_HUT
#include "octree.hpp"
#endif
#ifndef WEB
#define BS_THREAD_POOL_NATIVE_EXTENSIONS
#include <BS_thread_pool.hpp>
#endif
@ -41,29 +44,19 @@ public:
class Spring {
public:
int mass_a;
int mass_b;
std::size_t a;
std::size_t b;
public:
Spring(int _mass_a, int _mass_b) : mass_a(_mass_a), mass_b(_mass_b) {}
Spring(std::size_t _a, std::size_t _b) : a(_a), b(_b) {}
public:
auto CalculateSpringForce(Mass &_mass_a, Mass &_mass_b) const -> void;
auto CalculateSpringForce(Mass &_a, Mass &_b) const -> void;
};
class MassSpringSystem {
private:
#ifdef BARNES_HUT
// Barnes-Hut
Octree octree;
#else
// Uniform grid
std::vector<int> mass_indices;
std::vector<int64_t> cell_ids;
int last_build;
int last_masses_count;
int last_springs_count;
#endif
#ifndef WEB
BS::thread_pool<BS::tp::none> threads;
@ -72,19 +65,13 @@ private:
public:
// This is the main ownership of all the states/masses/springs.
std::vector<Mass> masses;
std::unordered_map<State, int> state_masses;
std::vector<Spring> springs;
std::unordered_map<std::pair<State, State>, int> state_springs;
public:
MassSpringSystem() {
#ifndef BARNES_HUT
last_build = REPULSION_GRID_REFRESH;
std::cout << "Using uniform grid repulsion force calculation." << std::endl;
#else
MassSpringSystem()
: threads(std::thread::hardware_concurrency() - 1, SetThreadName) {
std::cout << "Using Barnes-Hut + octree repulsion force calculation."
<< std::endl;
#endif
#ifndef WEB
std::cout << "Thread-Pool: " << threads.get_thread_count() << " threads."
@ -98,21 +85,14 @@ public:
MassSpringSystem &operator=(MassSpringSystem &&move) = delete;
private:
#ifdef BARNES_HUT
static auto SetThreadName(std::size_t idx) -> void;
auto BuildOctree() -> void;
#else
auto BuildUniformGrid() -> void;
#endif
public:
auto AddMass(float mass, bool fixed, const State &state) -> void;
auto AddMass() -> void;
auto GetMass(const State &state) -> Mass &;
auto GetMass(const State &state) const -> const Mass &;
auto AddSpring(const State &massA, const State &massB, float spring_constant,
float dampening_constant, float rest_length) -> void;
auto AddSpring(int a, int b) -> void;
auto Clear() -> void;
@ -123,10 +103,74 @@ public:
auto CalculateRepulsionForces() -> void;
auto VerletUpdate(float delta_time) -> void;
};
#ifndef BARNES_HUT
auto InvalidateGrid() -> void;
#endif
class ThreadedPhysics {
struct AddMass {};
struct AddSpring {
std::size_t a;
std::size_t b;
};
struct ClearGraph {};
using Command = std::variant<AddMass, AddSpring, ClearGraph>;
struct PhysicsState {
TracyLockable(std::mutex, command_mtx);
std::queue<Command> pending_commands;
TracyLockable(std::mutex, data_mtx);
std::condition_variable_any data_ready_cnd;
std::condition_variable_any data_consumed_cnd;
unsigned int ups = 0;
bool data_ready = false;
bool data_consumed = true;
std::vector<Vector3> masses; // Read by renderer
std::vector<std::pair<std::size_t, std::size_t>>
springs; // Read by renderer
std::atomic<bool> running{true};
};
private:
std::thread physics;
public:
PhysicsState state;
public:
ThreadedPhysics() : physics(PhysicsThread, std::ref(state)) {}
ThreadedPhysics(const ThreadedPhysics &copy) = delete;
ThreadedPhysics &operator=(const ThreadedPhysics &copy) = delete;
ThreadedPhysics(ThreadedPhysics &&move) = delete;
ThreadedPhysics &operator=(ThreadedPhysics &&move) = delete;
~ThreadedPhysics() {
state.running = false;
state.data_ready_cnd.notify_all();
state.data_consumed_cnd.notify_all();
physics.join();
}
private:
static auto PhysicsThread(PhysicsState &state) -> void;
public:
auto AddMassCmd() -> void;
auto AddSpringCmd(std::size_t a, std::size_t b) -> void;
auto ClearCmd() -> void;
auto AddMassSpringsCmd(
std::size_t num_masses,
const std::vector<std::pair<std::size_t, std::size_t>> &springs) -> void;
};
// https://en.cppreference.com/w/cpp/utility/variant/visit
template <class... Ts> struct overloads : Ts... {
using Ts::operator()...;
};
#endif

View File

@ -7,7 +7,6 @@
#include <functional>
#include <iostream>
#include <string>
#include <unordered_set>
#include <vector>
enum Direction {
@ -219,8 +218,9 @@ public:
auto GetNextStates() const -> std::vector<State>;
auto Closure() const -> std::pair<std::unordered_set<State>,
std::vector<std::pair<State, State>>>;
auto Closure() const
-> std::pair<std::vector<State>,
std::vector<std::pair<std::size_t, std::size_t>>>;
};
// Provide hash functions so we can use State and <State, State> as hash-set

View File

@ -3,15 +3,17 @@
#include <raylib.h>
#include <raymath.h>
#include <unordered_set>
#include "camera.hpp"
#include "config.hpp"
#include "physics.hpp"
#include "puzzle.hpp"
#include "input.hpp"
#include "state.hpp"
class Renderer {
private:
const StateManager &state;
const InputHandler &input;
const OrbitCamera3D &camera;
RenderTexture render_target;
RenderTexture klotski_target;
@ -25,13 +27,10 @@ private:
Shader instancing_shader;
public:
bool mark_solutions;
bool connect_solutions;
public:
Renderer(const OrbitCamera3D &_camera)
: camera(_camera), transforms_size(0), transforms(nullptr),
mark_solutions(false), connect_solutions(false) {
Renderer(const OrbitCamera3D &_camera, const StateManager &_state,
const InputHandler &_input)
: state(_state), input(_input), camera(_camera), transforms_size(0),
transforms(nullptr) {
render_target = LoadRenderTexture(GetScreenWidth() / 2.0,
GetScreenHeight() - MENU_HEIGHT);
klotski_target = LoadRenderTexture(GetScreenWidth() / 2.0,
@ -61,29 +60,24 @@ public:
}
private:
auto AllocateGraphInstancing(const MassSpringSystem &mass_springs) -> void;
auto AllocateGraphInstancing(std::size_t size) -> void;
auto
ReallocateGraphInstancingIfNecessary(const MassSpringSystem &mass_springs)
-> void;
auto ReallocateGraphInstancingIfNecessary(std::size_t size) -> void;
public:
auto UpdateTextureSizes() -> void;
auto DrawMassSprings(const MassSpringSystem &mass_springs,
const State &current_state, const State &starting_state,
const std::unordered_set<State> &winning_states,
const std::unordered_set<State> &visited_states) -> void;
auto DrawMassSprings(
const std::vector<Vector3> &masses,
const std::vector<std::pair<std::size_t, std::size_t>> &springs) -> void;
auto DrawKlotski(const State &state, int hov_x, int hov_y, int sel_x,
int sel_y, int block_add_x, int block_add_y,
const WinCondition win_condition) -> void;
auto DrawKlotski() -> void;
auto DrawMenu(const MassSpringSystem &mass_springs, int current_preset,
const State &current_state,
const std::unordered_set<State> &winning_states) -> void;
auto DrawMenu(const std::vector<Vector3> &masses,
const std::vector<std::pair<std::size_t, std::size_t>> &springs)
-> void;
auto DrawTextures() -> void;
auto DrawTextures(float ups) -> void;
};
#endif

View File

@ -1,16 +1,21 @@
#ifndef __STATE_HPP_
#define __STATE_HPP_
#include "config.hpp"
#include "physics.hpp"
#include "presets.hpp"
#include "puzzle.hpp"
#include <raymath.h>
#include <unordered_map>
#include <unordered_set>
class StateManager {
public:
MassSpringSystem &mass_springs;
ThreadedPhysics &physics;
std::unordered_map<State, std::size_t> states;
std::unordered_set<State> winning_states;
std::unordered_set<State> visited_states;
int current_preset;
State starting_state;
@ -19,16 +24,13 @@ public:
bool edited = false;
std::unordered_set<State> winning_states;
std::unordered_set<State> visited_states;
public:
StateManager(MassSpringSystem &_mass_springs)
: mass_springs(_mass_springs), current_preset(0),
StateManager(ThreadedPhysics &_physics)
: physics(_physics), current_preset(0),
starting_state(generators[current_preset]()),
current_state(starting_state), previous_state(starting_state),
edited(false) {
mass_springs.AddMass(MASS, false, current_state);
ClearGraph();
}
StateManager(const StateManager &copy) = delete;
@ -55,9 +57,11 @@ public:
auto FindWinningStates() -> void;
auto CurrentGenerator() -> StateGenerator;
auto CurrentGenerator() const -> StateGenerator;
auto CurrentWinCondition() -> WinCondition;
auto CurrentWinCondition() const -> WinCondition;
auto CurrentMassIndex() const -> std::size_t;
};
#endif