Compare commits

...

18 Commits

Author SHA1 Message Date
025cbfdf3b move bits functions to separate file + fix missing defaults with disabled program_options on windows 2026-03-05 19:13:44 +01:00
d4f83e11db add .desktop icon to package 2026-03-05 02:05:02 +01:00
db588bd57b fix conditional threadpool include 2026-03-05 02:04:48 +01:00
49e5ed6906 fix windows build 2026-03-04 21:39:39 +01:00
08352dd997 don't pass a reference to a temporary to physics_thread 2026-03-04 21:31:01 +01:00
4e5ca6be6c fix nix build error 2026-03-04 20:47:34 +01:00
a9c102298a enable/disable threadpool from cmake 2026-03-04 20:45:25 +01:00
cc2aee3af4 dummy commit 2026-03-04 20:33:29 +01:00
e0f128f693 dummy commit 2026-03-04 20:29:33 +01:00
3b6919944c add some abbrs to flake + wrap package to set the working dir 2026-03-04 20:28:38 +01:00
c9915852db implement very slow puzzle space exploration 2026-03-04 20:23:16 +01:00
2d111f58da add single state space benchmark + some tests 2026-03-04 19:08:00 +01:00
0a2788c1b4 update flake 2026-03-04 19:07:40 +01:00
7a5013295e fix cross compilation for windows (disable boost.stacktrace + use sqrt instead of rsqrt) 2026-03-02 20:09:49 +01:00
9c48954a78 build octree async and reuse tree from last frame (disabled as it breaks physics) 2026-03-02 18:52:06 +01:00
d62d5c78bf fix bug where interactive movement was using the fast move implementation instead of the interactive one 2026-03-02 14:38:03 +01:00
2a5f1b2ffd update default camera settings 2026-03-02 14:37:41 +01:00
2ef2a29601 squash merge efficient-puzzle into main 2026-03-02 14:37:34 +01:00
38 changed files with 4938 additions and 1539 deletions

3
.gitignore vendored
View File

@ -6,3 +6,6 @@ cmake-build-release
/.gdb_history /.gdb_history
/valgrind.log /valgrind.log
.idea .idea
/perf.data
/perf.data.old
/clusters.puzzle

View File

@ -1,23 +1,60 @@
cmake_minimum_required(VERSION 3.25) cmake_minimum_required(VERSION 3.28)
project(MassSprings) project(MassSprings)
set(CMAKE_CXX_STANDARD 26) set(CMAKE_CXX_STANDARD 26)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON) set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
# Disable boost warning because our cmake/boost are recent enough
if(POLICY CMP0167)
cmake_policy(SET CMP0167 NEW)
endif()
option(DISABLE_THREADPOOL "Disable additional physics threads" OFF)
option(DISABLE_BACKWARD "Disable backward stacktrace printer" OFF)
option(DISABLE_TRACY "Disable the Tracy profiler client" OFF)
option(DISABLE_TESTS "Disable building tests" OFF)
option(DISABLE_BENCH "Disable building benchmarks" OFF)
# Headers + Sources (excluding main.cpp)
set(SOURCES
src/backward.cpp
src/bits.cpp
src/graph_distances.cpp
src/input_handler.cpp
src/load_save.cpp
src/mass_spring_system.cpp
src/octree.cpp
src/orbit_camera.cpp
src/puzzle.cpp
src/renderer.cpp
src/state_manager.cpp
src/threaded_physics.cpp
src/user_interface.cpp
)
# Libraries # Libraries
include(FetchContent)
find_package(raylib REQUIRED) find_package(raylib REQUIRED)
set(LIBS raylib) find_package(Boost COMPONENTS program_options REQUIRED)
set(LIBS raylib Boost::headers Boost::program_options)
set(FLAGS "") set(FLAGS "")
if(NOT DEFINED DISABLE_BACKWARD) if(WIN32)
list(APPEND LIBS opengl32 gdi32 winmm)
endif()
if(NOT DISABLE_THREADPOOL)
list(APPEND FLAGS THREADPOOL)
endif()
if(NOT DISABLE_BACKWARD)
find_package(Backward REQUIRED) find_package(Backward REQUIRED)
list(APPEND LIBS Backward::Backward) list(APPEND LIBS Backward::Backward)
list(APPEND FLAGS BACKWARD) list(APPEND FLAGS BACKWARD)
endif() endif()
if(NOT DEFINED DISABLE_TRACY) if(NOT DISABLE_TRACY)
include(FetchContent)
FetchContent_Declare(tracy FetchContent_Declare(tracy
GIT_REPOSITORY https://github.com/wolfpld/tracy.git GIT_REPOSITORY https://github.com/wolfpld/tracy.git
GIT_TAG v0.11.1 GIT_TAG v0.11.1
@ -32,14 +69,11 @@ if(NOT DEFINED DISABLE_TRACY)
list(APPEND FLAGS TRACY) list(APPEND FLAGS TRACY)
endif() endif()
if(WIN32) # Set this after fetching tracy to hide tracy's warnings.
list(APPEND LIBS opengl32 gdi32 winmm) # We set -Wno-alloc-size-larger-than because it prevents BS::thread_pool from building with current gcc
endif() set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Wfloat-equal -Wundef -Wshadow -Wpointer-arith -Wcast-align -Wno-unused-parameter -Wunreachable-code -Wno-alloc-size-larger-than")
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -ggdb -O0")
# Set this after fetching tracy to hide tracy's warnings set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -ggdb -O3 -ffast-math -march=native")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Wfloat-equal -Wundef -Wshadow -Wpointer-arith -Wcast-align -Wno-unused-parameter -Wunreachable-code")
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -O2 -ggdb") # -fsanitize=address already fails on InitWindow(), -fsanitize=undefined, -fsanitize=leak
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -Ofast")
message("-- CMAKE_C_FLAGS: ${CMAKE_C_FLAGS}") message("-- CMAKE_C_FLAGS: ${CMAKE_C_FLAGS}")
message("-- CMAKE_C_FLAGS_DEBUG: ${CMAKE_C_FLAGS_DEBUG}") message("-- CMAKE_C_FLAGS_DEBUG: ${CMAKE_C_FLAGS_DEBUG}")
@ -48,40 +82,56 @@ message("-- CMAKE_CXX_FLAGS: ${CMAKE_CXX_FLAGS}")
message("-- CMAKE_CXX_FLAGS_DEBUG: ${CMAKE_CXX_FLAGS_DEBUG}") message("-- CMAKE_CXX_FLAGS_DEBUG: ${CMAKE_CXX_FLAGS_DEBUG}")
message("-- CMAKE_CXX_FLAGS_RELEASE: ${CMAKE_CXX_FLAGS_RELEASE}") message("-- CMAKE_CXX_FLAGS_RELEASE: ${CMAKE_CXX_FLAGS_RELEASE}")
# Headers + Sources
include_directories(include)
set(SOURCES
src/backward.cpp
src/graph_distances.cpp
src/input_handler.cpp
src/main.cpp
src/mass_spring_system.cpp
src/octree.cpp
src/orbit_camera.cpp
src/threaded_physics.cpp
src/puzzle.cpp
src/renderer.cpp
src/state_manager.cpp
src/user_interface.cpp
)
# Main target # Main target
add_executable(masssprings ${SOURCES}) add_executable(masssprings src/main.cpp ${SOURCES})
target_include_directories(masssprings PRIVATE ${RAYLIB_CPP_INCLUDE_DIR}) target_include_directories(masssprings PRIVATE include)
target_link_libraries(masssprings PRIVATE ${LIBS}) target_link_libraries(masssprings PRIVATE ${LIBS})
target_compile_definitions(masssprings PRIVATE ${FLAGS}) target_compile_definitions(masssprings PRIVATE ${FLAGS})
# Testing
if(NOT DISABLE_TESTS AND NOT WIN32)
enable_testing()
FetchContent_Declare(Catch2
GIT_REPOSITORY https://github.com/catchorg/Catch2.git
GIT_TAG v3.13.0
)
FetchContent_MakeAvailable(Catch2)
set(TEST_SOURCES
test/bits.cpp
test/bitmap.cpp
test/bitmap_find_first_empty.cpp
# test/puzzle.cpp
)
add_executable(tests ${TEST_SOURCES} ${SOURCES})
target_include_directories(tests PRIVATE include)
target_link_libraries(tests Catch2::Catch2WithMain raylib)
include(Catch)
catch_discover_tests(tests)
endif()
# Benchmarking
if(NOT DISABLE_BENCH AND NOT WIN32)
find_package(benchmark REQUIRED)
set(BENCH_SOURCES
benchmark/state_space.cpp
)
add_executable(benchmarks ${BENCH_SOURCES} ${SOURCES})
target_include_directories(benchmarks PRIVATE include)
target_link_libraries(benchmarks benchmark raylib)
endif()
# LTO # LTO
if(NOT WIN32) include(CheckIPOSupported)
include(CheckIPOSupported) check_ipo_supported(RESULT supported OUTPUT error)
check_ipo_supported(RESULT supported OUTPUT error) if(supported)
if(supported) message(STATUS "IPO / LTO enabled")
message(STATUS "IPO / LTO enabled") set_property(TARGET masssprings PROPERTY INTERPROCEDURAL_OPTIMIZATION TRUE)
set_property(TARGET masssprings PROPERTY INTERPROCEDURAL_OPTIMIZATION TRUE) else()
if(USE_TRACY) message(STATUS "IPO / LTO not supported")
set_property(TARGET masssprings_tracy PROPERTY INTERPROCEDURAL_OPTIMIZATION TRUE)
endif()
else()
message(STATUS "IPO / LTO not supported: <${error}>")
endif()
endif() endif()

View File

@ -5,4 +5,12 @@ The graph layout is calculated iteratively using a mass-spring-system with addit
![](screenshot.png) ![](screenshot.png)
Build and run on NixOS: `nix run git+https://gitea.local.chriphost.de/christoph/cpp-masssprings`. ## Running
Requirements:
- Directory `fonts`
- Directory `shader`
- Preset file `default.puzzle` (optional)
Run `nix run git+https://gitea.local.chriphost.de/christoph/cpp-masssprings` from the working directory containing the listed requirements.

91
benchmark/state_space.cpp Normal file
View File

@ -0,0 +1,91 @@
#include "puzzle.hpp"
#include <benchmark/benchmark.h>
static std::vector<std::string> puzzles = {
// 0: RushHour 1
"S:[6x6] G:[4,2] M:[R] B:[{3x1 _ _ _ _ 1x3} {_ _ _ _ _ _} {_ _ 1x2 2X1 _ _} {_ _ _ 1x2 2x1 _} {1x2 _ 1x2 _ 2x1 _} {_ _ _ 3x1 _ _}]",
// 1: RushHour 2
"S:[6x6] G:[4,2] M:[R] B:[{1x2 3x1 _ _ 1x2 1x3} {_ 3x1 _ _ _ _} {2X1 _ 1x2 1x2 1x2 _} {2x1 _ _ _ _ _} {_ _ _ 1x2 2x1 _} {_ _ _ _ 2x1 _}]",
// 2: RushHour 3
"S:[6x6] G:[4,2] M:[R] B:[{3x1 _ _ 1x2 _ _} {1x2 2x1 _ _ _ 1x2} {_ 2X1 _ 1x2 1x2 _} {2x1 _ 1x2 _ _ 1x2} {_ _ _ 2x1 _ _} {_ 2x1 _ 2x1 _ _}]",
// 3: RushHour 4
"S:[6x6] G:[4,2] M:[R] B:[{1x3 2x1 _ _ 1x2 _} {_ 1x2 1x2 _ _ 1x3} {_ _ _ 2X1 _ _} {3x1 _ _ 1x2 _ _} {_ _ 1x2 _ 2x1 _} {2x1 _ _ 2x1 _ _}]",
// 4: RushHour + Walls 1
"S:[6x6] G:[4,2] M:[R] B:[{1x2 2x1 _ 1*1 _ _} {_ _ _ 1x2 2x1 _} {1x2 2X1 _ _ _ _} {_ _ 1x2 2x1 _ 1x3} {2x1 _ _ _ _ _} {2x1 _ 3x1 _ _ _}]",
// 5: RushHour + Walls 2
"S:[6x6] G:[4,2] M:[R] B:[{2x1 _ _ 1x2 1x2 1*1} {3x1 _ _ _ _ _} {1x2 2X1 _ 1x2 _ _} {_ _ 1x2 _ 2x1 _} {_ _ _ 2x1 _ 1x2} {_ _ 2x1 _ 1*1 _}]",
// 6: Dad's Puzzler
"S:[4x5] G:[0,3] M:[F] B:[{2X2 _ 2x1 _} {_ _ 2x1 _} {1x1 1x1 _ _} {1x2 1x2 2x1 _} {_ _ 2x1 _}]",
// 7: Nine Blocks
"S:[4x5] G:[0,3] M:[F] B:[{1x2 1x2 _ _} {_ _ 2x1 _} {1x2 1x2 2x1 _} {_ _ 2X2 _} {1x1 1x1 _ _}]",
// 8: Quzzle
"S:[4x5] G:[2,0] M:[F] B:[{2X2 _ 2x1 _} {_ _ 1x2 1x2} {_ _ _ _} {1x2 2x1 _ 1x1} {_ 2x1 _ 1x1}]",
// 9: Thin Klotski
"S:[4x5] G:[1,4] M:[F] B:[{1x2 _ 2X1 _} {_ 2x2 _ 1x1} {_ _ _ 1x1} {2x2 _ 1x1 1x1} {_ _ 1x1 1x1}]",
// 10: Fat Klotski
"S:[4x5] G:[1,3] M:[F] B:[{_ 2X2 _ 1x1} {1x1 _ _ 1x2} {1x1 2x2 _ _} {1x1 _ _ _} {1x1 1x1 2x1 _}]",
// 11: Klotski
"S:[4x5] G:[1,3] M:[F] B:[{1x2 2X2 _ 1x2} {_ _ _ _} {1x2 2x1 _ 1x2} {_ 1x1 1x1 _} {1x1 _ _ 1x1}]",
// 12: Century
"S:[4x5] G:[1,3] M:[F] B:[{1x1 2X2 _ 1x1} {1x2 _ _ 1x2} {_ 1x2 _ _} {1x1 _ _ 1x1} {2x1 _ 2x1 _}]",
// 13: Super Century
"S:[4x5] G:[1,3] M:[F] B:[{1x2 1x1 1x1 1x1} {_ 1x2 2X2 _} {1x2 _ _ _} {_ 2x1 _ 1x1} {_ 2x1 _ _}]",
// 14: Supercompo
"S:[4x5] G:[1,3] M:[F] B:[{_ 2X2 _ _} {1x1 _ _ 1x1} {1x2 2x1 _ 1x2} {_ 2x1 _ _} {1x1 2x1 _ 1x1}]",
};
static auto explore_state_space(benchmark::State& state) -> void
{
const puzzle p = puzzle(puzzles[state.range(0)]);
for (auto _ : state) {
auto space = p.explore_state_space();
benchmark::DoNotOptimize(space);
}
}
static auto explore_rush_hour_puzzle_space(benchmark::State& state) -> void
{
// ReSharper disable once CppTooWideScope
constexpr uint8_t max_blocks = 5;
constexpr uint8_t board_width = 4;
constexpr uint8_t board_height = 5;
constexpr uint8_t goal_x = board_width - 1;
constexpr uint8_t goal_y = 2;
constexpr bool restricted = true;
const boost::unordered_flat_set<puzzle::block, block_hasher2, block_equal2> permitted_blocks = {
puzzle::block(0, 0, 2, 1, false, false),
puzzle::block(0, 0, 3, 1, false, false),
puzzle::block(0, 0, 1, 2, false, false),
puzzle::block(0, 0, 1, 3, false, false)
};
const puzzle::block target_block = puzzle::block(0, 0, 2, 1, true, false);
constexpr std::tuple<uint8_t, uint8_t, uint8_t, uint8_t> target_block_pos_range = {
0,
goal_y,
board_width - 1,
goal_y
};
const puzzle p = puzzle(board_width, board_height, goal_x, goal_y, restricted, true);
for (auto _ : state) {
boost::unordered_flat_set<puzzle, puzzle_hasher> result = p.explore_puzzle_space(
permitted_blocks,
target_block,
target_block_pos_range,
max_blocks,
std::nullopt);
benchmark::DoNotOptimize(result);
}
}
BENCHMARK(explore_state_space)->DenseRange(0, puzzles.size() - 1)->Unit(benchmark::kMicrosecond);
BENCHMARK(explore_rush_hour_puzzle_space)->Unit(benchmark::kSecond);
BENCHMARK_MAIN();

View File

@ -1,44 +1,30 @@
# RushHour 1 # RushHour 1
R664231........13................12ba..........1221..12..12..21........31.... S:[6x6] G:[4,2] M:[R] B:[{3x1 _ _ _ _ 1x3} {_ _ _ _ _ _} {_ _ 1x2 2X1 _ _} {_ _ _ 1x2 2x1 _} {1x2 _ 1x2 _ 2x1 _} {_ _ _ 3x1 _ _}]
# RushHour 2 # RushHour 2
R66421231....1213..31........ba..121212..21................1221..........21.. S:[6x6] G:[4,2] M:[R] B:[{1x2 3x1 _ _ 1x2 1x3} {_ 3x1 _ _ _ _} {2X1 _ 1x2 1x2 1x2 _} {2x1 _ _ _ _ _} {_ _ _ 1x2 2x1 _} {_ _ _ _ 2x1 _}]
# RushHour 3 # RushHour 3
R664231....12....1221......12..ba..1212..21..12....12......21......21..21.... S:[6x6] G:[4,2] M:[R] B:[{3x1 _ _ 1x2 _ _} {1x2 2x1 _ _ _ 1x2} {_ 2X1 _ 1x2 1x2 _} {2x1 _ 1x2 _ _ 1x2} {_ _ _ 2x1 _ _} {_ 2x1 _ 2x1 _ _}]
# RushHour 4 # RushHour 4
R66421321....12....1212....13......ba....31....12........12..21..21....21.... S:[6x6] G:[4,2] M:[R] B:[{1x3 2x1 _ _ 1x2 _} {_ 1x2 1x2 _ _ 1x3} {_ _ _ 2X1 _ _} {3x1 _ _ 1x2 _ _} {_ _ 1x2 _ 2x1 _} {2x1 _ _ 2x1 _ _}]
# RushHour + Walls 1 # RushHour + Walls 1
R66421221..AA..........1221..12ba............1221..1321..........21..31...... S:[6x6] G:[4,2] M:[R] B:[{1x2 2x1 _ 1*1 _ _} {_ _ _ 1x2 2x1 _} {1x2 2X1 _ _ _ _} {_ _ 1x2 2x1 _ 1x3} {2x1 _ _ _ _ _} {2x1 _ 3x1 _ _ _}]
# RushHour + Walls 2 # RushHour + Walls 2
R664221....1212AA31..........12ba..12........12..21........21..12....21..AA.. S:[6x6] G:[4,2] M:[R] B:[{2x1 _ _ 1x2 1x2 1*1} {3x1 _ _ _ _ _} {1x2 2X1 _ 1x2 _ _} {_ _ 1x2 _ 2x1 _} {_ _ _ 2x1 _ 1x2} {_ _ 2x1 _ 1*1 _}]
# Dad's Puzzler # Dad's Puzzler
F4503bb..21......21..1111....121221......21.. S:[4x5] G:[0,3] M:[F] B:[{2X2 _ 2x1 _} {_ _ 2x1 _} {1x1 1x1 _ _} {1x2 1x2 2x1 _} {_ _ 2x1 _}]
# Nine Blocks
# Nine Block (Worse) S:[4x5] G:[0,3] M:[F] B:[{1x2 1x2 _ _} {_ _ 2x1 _} {1x2 1x2 2x1 _} {_ _ 2X2 _} {1x1 1x1 _ _}]
F45031212........21..121221......bb..1111....
# Quzzle # Quzzle
F4520bb..21......1212........1221..11..21..11 S:[4x5] G:[2,0] M:[F] B:[{2X2 _ 2x1 _} {_ _ 1x2 1x2} {_ _ _ _} {1x2 2x1 _ 1x1} {_ 2x1 _ 1x1}]
# Thin Klotski # Thin Klotski
F451412..ba....22..11......1122..1111....1111 S:[4x5] G:[1,4] M:[F] B:[{1x2 _ 2X1 _} {_ 2x2 _ 1x1} {_ _ _ 1x1} {2x2 _ 1x1 1x1} {_ _ 1x1 1x1}]
# Klotski
F451312bb..12........1221..12..1111..11....11
# Fat Klotski # Fat Klotski
F4513..bb..1111....121122....11......111121.. S:[4x5] G:[1,3] M:[F] B:[{_ 2X2 _ 1x1} {1x1 _ _ 1x2} {1x1 2x2 _ _} {1x1 _ _ _} {1x1 1x1 2x1 _}]
# Klotski
S:[4x5] G:[1,3] M:[F] B:[{1x2 2X2 _ 1x2} {_ _ _ _} {1x2 2x1 _ 1x2} {_ 1x1 1x1 _} {1x1 _ _ 1x1}]
# Century # Century
F451311bb..1112....12..12....11....1121..21.. S:[4x5] G:[1,3] M:[F] B:[{1x1 2X2 _ 1x1} {1x2 _ _ 1x2} {_ 1x2 _ _} {1x1 _ _ 1x1} {2x1 _ 2x1 _}]
# Super Century # Super Century
F451312111111..12bb..12........21..11....21.. S:[4x5] G:[1,3] M:[F] B:[{1x2 1x1 1x1 1x1} {_ 1x2 2X2 _} {1x2 _ _ _} {_ 2x1 _ 1x1} {_ 2x1 _ _}]
# Supercompo # Supercompo
F4513..bb....11....111221..12..21....1121..11 S:[4x5] G:[1,3] M:[F] B:[{_ 2X2 _ _} {1x1 _ _ 1x1} {1x2 2x1 _ 1x2} {_ 2x1 _ _} {1x1 2x1 _ 1x1}]

6
flake.lock generated
View File

@ -20,11 +20,11 @@
}, },
"nixpkgs": { "nixpkgs": {
"locked": { "locked": {
"lastModified": 1770843696, "lastModified": 1772479524,
"narHash": "sha256-LovWTGDwXhkfCOmbgLVA10bvsi/P8eDDpRudgk68HA8=", "narHash": "sha256-u7nCaNiMjqvKpE+uZz9hE7pgXXTmm5yvdtFaqzSzUQI=",
"owner": "NixOS", "owner": "NixOS",
"repo": "nixpkgs", "repo": "nixpkgs",
"rev": "2343bbb58f99267223bc2aac4fc9ea301a155a16", "rev": "4215e62dc2cd3bc705b0a423b9719ff6be378a43",
"type": "github" "type": "github"
}, },
"original": { "original": {

349
flake.nix
View File

@ -14,21 +14,123 @@ rec {
# Create a shell (and possibly package) for each possible system, not only x86_64-linux # Create a shell (and possibly package) for each possible system, not only x86_64-linux
flake-utils.lib.eachDefaultSystem ( flake-utils.lib.eachDefaultSystem (
system: let system: let
# =========================================================================================
# Define pkgs/stdenvs
# =========================================================================================
pkgs = import nixpkgs { pkgs = import nixpkgs {
inherit system; inherit system;
config.allowUnfree = true; config.allowUnfree = true;
overlays = []; overlays = [];
}; };
inherit (pkgs) lib stdenv;
clangPkgs = import nixpkgs {
inherit system;
config.allowUnfree = true;
overlays = [];
# Use this to change the compiler:
# - GCC: pkgs.stdenv
# - Clang: pkgs.clangStdenv
# NixOS packages are built using GCC by default. Using clang requires a full rebuild/redownload.
config.replaceStdenv = {pkgs}: pkgs.clangStdenv;
};
windowsPkgs = import nixpkgs { windowsPkgs = import nixpkgs {
inherit system; inherit system;
config.allowUnfree = true;
overlays = [];
# Use this to cross compile to a different system
crossSystem = { crossSystem = {
config = "x86_64-w64-mingw32"; config = "x86_64-w64-mingw32";
}; };
config.allowUnfree = true;
}; };
inherit (pkgs) lib stdenv;
# =========================================================================================
# Define shell environment
# =========================================================================================
# Setup the shell when entering the "nix develop" environment (bash script).
shellHook = let
mkCmakeScript = type: let
typeLower = lib.toLower type;
in
pkgs.writers.writeFish "cmake-${typeLower}.fish" ''
cd $FLAKE_PROJECT_ROOT
echo "Removing build directory ./cmake-build-${typeLower}/"
rm -rf ./cmake-build-${typeLower}
echo "Creating build directory"
mkdir cmake-build-${typeLower}
cd cmake-build-${typeLower}
echo "Running cmake"
cmake -G "Ninja" \
-DCMAKE_BUILD_TYPE="${type}" \
..
echo "Linking compile_commands.json"
cd ..
ln -sf ./cmake-build-${typeLower}/compile_commands.json ./compile_commands.json
'';
cmakeDebug = mkCmakeScript "Debug";
cmakeRelease = mkCmakeScript "Release";
mkBuildScript = type: let
typeLower = lib.toLower type;
in
pkgs.writers.writeFish "cmake-build.fish" ''
cd $FLAKE_PROJECT_ROOT/cmake-build-${typeLower}
echo "Running cmake"
NIX_ENFORCE_NO_NATIVE=0 cmake --build . -j$(nproc)
'';
buildDebug = mkBuildScript "Debug";
buildRelease = mkBuildScript "Release";
# Use this to specify commands that should be ran after entering fish shell
initProjectShell = pkgs.writers.writeFish "init-shell.fish" ''
echo "Entering \"${description}\" environment..."
# Determine the project root, used e.g. in cmake scripts
set -g -x FLAKE_PROJECT_ROOT (git rev-parse --show-toplevel)
# C/C++:
abbr -a cmake-debug "${cmakeDebug}"
abbr -a cmake-release "${cmakeRelease}"
abbr -a build-debug "${buildDebug}"
abbr -a build-release "${buildRelease}"
abbr -a debug-clean "${cmakeDebug} && ${buildDebug} && ./cmake-build-debug/masssprings"
abbr -a release-clean "${cmakeRelease} && ${buildRelease} && ./cmake-build-release/masssprings"
abbr -a debug "${buildDebug} && ./cmake-build-debug/masssprings"
abbr -a release "${buildRelease} && ./cmake-build-release/masssprings"
abbr -a run "${buildRelease} && ./cmake-build-release/masssprings"
abbr -a run-clusters "${buildRelease} && ./cmake-build-release/masssprings --output=clusters.puzzle --space=rh --w=6 --h=6 --gx=4 --gy=2 --blocks=4"
abbr -a runtests "${buildDebug} && ./cmake-build-debug/tests"
abbr -a runbenchs "${buildRelease} && sudo cpupower frequency-set --governor performance && ./cmake-build-release/benchmarks; sudo cpupower frequency-set --governor powersave"
abbr -a rungdb "${buildDebug} && gdb --tui ./cmake-build-debug/masssprings"
abbr -a runvalgrind "${buildDebug} && valgrind --leak-check=full --show-reachable=no --show-leak-kinds=definite,indirect,possible --track-origins=no --suppressions=valgrind.supp --log-file=valgrind.log ./cmake-build-debug/masssprings && cat valgrind.log"
abbr -a runperf "${buildRelease} && perf record -g ./cmake-build-release/masssprings && hotspot ./perf.data"
abbr -a runperf-graph "${buildRelease} && perf record -g ./cmake-build-release/benchmarks --benchmark_filter='explore_state_space' && hotspot ./perf.data"
abbr -a runperf-space "${buildRelease} && perf record -g ./cmake-build-release/benchmarks --benchmark_filter='explore_rush_hour_puzzle_space' && hotspot ./perf.data"
abbr -a runtracy "tracy -a 127.0.0.1 &; ${buildRelease} && sudo -E ./cmake-build-release/masssprings"
abbr -a runclion "clion ./CMakeLists.txt 2>/dev/null 1>&2 & disown;"
'';
in
builtins.concatStringsSep "\n" [
# Launch into pure fish shell
''
exec "$(type -p fish)" -C "source ${initProjectShell}"
''
];
# =========================================================================================== # ===========================================================================================
# Define custom dependencies # Define custom dependencies
# =========================================================================================== # ===========================================================================================
@ -98,26 +200,20 @@ rec {
# - Those which are needed on $PATH during the build, for example cmake and pkg-config # - Those which are needed on $PATH during the build, for example cmake and pkg-config
# - Setup hooks, for example makeWrapper # - Setup hooks, for example makeWrapper
# - Interpreters needed by patchShebangs for build scripts (with the --build flag), which can be the case for e.g. perl # - Interpreters needed by patchShebangs for build scripts (with the --build flag), which can be the case for e.g. perl
# NOTE: Do not add compiler here, they are provided by the stdenv
nativeBuildInputs = with pkgs; [ nativeBuildInputs = with pkgs; [
# Languages: # Languages:
binutils # binutils
gcc
# C/C++: # C/C++:
gdb
valgrind
# gnumake
cmake cmake
ninja ninja
# pkg-config gdb
# clang-tools valgrind
# compdb kdePackages.kcachegrind
# pprof
# gprof2dot
perf perf
hotspot hotspot
kdePackages.kcachegrind # heaptrack
gdbgui
# renderdoc # renderdoc
]; ];
@ -129,15 +225,20 @@ rec {
raylib raylib
raygui raygui
thread-pool thread-pool
boost
# Debugging # Debugging/Testing/Profiling
tracy-wayland tracy-wayland
backward-cpp backward-cpp
libbfd libbfd
catch2_3
gbenchmark
]; ];
# =========================================================================================== # ===========================================================================================
# Define buildable + installable packages # Define buildable + installable packages
# =========================================================================================== # ===========================================================================================
package = stdenv.mkDerivation rec { package = stdenv.mkDerivation rec {
inherit buildInputs; inherit buildInputs;
pname = "masssprings"; pname = "masssprings";
@ -147,19 +248,45 @@ rec {
nativeBuildInputs = with pkgs; [ nativeBuildInputs = with pkgs; [
gcc gcc
cmake cmake
# Fix the working directory so the auxiliary files are always available
makeWrapper
]; ];
cmakeFlags = [ cmakeFlags = [
"-DDISABLE_THREADPOOL=Off"
"-DDISABLE_TRACY=On" "-DDISABLE_TRACY=On"
"-DDISABLE_BACKWARD=On" "-DDISABLE_BACKWARD=On"
"-DDISABLE_TESTS=On"
"-DDISABLE_BENCH=On"
]; ];
hardeningDisable = ["all"];
preConfigure = ''
unset NIX_ENFORCE_NO_NATIVE
'';
installPhase = '' installPhase = ''
mkdir -p $out/lib
cp ./${pname} $out/lib/
cp $src/default.puzzle $out/lib/
cp -r $src/fonts $out/lib/fonts
cp -r $src/shader $out/lib/shader
# The wrapper enters the correct working dir, so fonts/shaders/presets are available
mkdir -p $out/bin mkdir -p $out/bin
cp ./${pname} $out/bin/ makeWrapper $out/lib/${pname} $out/bin/${pname} --chdir "$out/lib"
cp $src/default.puzzle $out/bin/
cp -r $src/fonts $out/bin/fonts # Generate a .desktop file
cp -r $src/shader $out/bin/shader mkdir -p $out/share/applications
cat <<INI > $out/share/applications/${pname}.desktop
[Desktop Entry]
Terminal=true
Name=PuzzleSpaces
Exec=$out/bin/${pname} %f
Type=Application
INI
''; '';
}; };
@ -178,12 +305,24 @@ rec {
raylib raylib
raygui raygui
thread-pool thread-pool
# Disable stacktrace since that's platform dependant and won't cross compile to windows
# https://github.com/NixOS/nixpkgs/blob/master/pkgs/development/libraries/boost/generic.nix#L43
(boost.override {
enableShared = false;
extraB2Args = [
"--without-stacktrace"
];
})
]; ];
cmakeFlags = [ cmakeFlags = [
"-DCMAKE_SYSTEM_NAME=Windows" "-DCMAKE_SYSTEM_NAME=Windows"
"-DDISABLE_THREADPOOL=Off"
"-DDISABLE_TRACY=On" "-DDISABLE_TRACY=On"
"-DDISABLE_BACKWARD=On" "-DDISABLE_BACKWARD=On"
"-DDISABLE_TESTS=On"
"-DDISABLE_BENCH=On"
]; ];
installPhase = '' installPhase = ''
@ -205,153 +344,53 @@ rec {
# Provide environment for "nix develop" # Provide environment for "nix develop"
devShells = { devShells = {
default = pkgs.mkShell { default = pkgs.mkShell {
inherit nativeBuildInputs buildInputs; inherit nativeBuildInputs buildInputs shellHook;
name = description; name = description;
# ========================================================================================= # =========================================================================================
# Define environment variables # Define environment variables
# ========================================================================================= # =========================================================================================
# Custom dynamic libraries:
# LD_LIBRARY_PATH = builtins.concatStringsSep ":" [
# # Rust Bevy GUI app:
# # "${pkgs.xorg.libX11}/lib"
# # "${pkgs.xorg.libXcursor}/lib"
# # "${pkgs.xorg.libXrandr}/lib"
# # "${pkgs.xorg.libXi}/lib"
# # "${pkgs.libGL}/lib"
#
# # JavaFX app:
# # "${pkgs.libGL}/lib"
# # "${pkgs.gtk3}/lib"
# # "${pkgs.glib.out}/lib"
# # "${pkgs.xorg.libXtst}/lib"
# ];
# Dynamic libraries from buildinputs: # Dynamic libraries from buildinputs:
LD_LIBRARY_PATH = nixpkgs.lib.makeLibraryPath buildInputs; LD_LIBRARY_PATH = nixpkgs.lib.makeLibraryPath buildInputs;
# =========================================================================================
# Define shell environment
# =========================================================================================
# Setup the shell when entering the "nix develop" environment (bash script).
shellHook = let
mkCmakeScript = type: let
typeLower = lib.toLower type;
in
pkgs.writers.writeFish "cmake-${typeLower}.fish" ''
cd $FLAKE_PROJECT_ROOT
# set -g -x CC ${pkgs.clang}/bin/clang
# set -g -x CXX ${pkgs.clang}/bin/clang++
echo "Removing build directory ./cmake-build-${typeLower}/"
rm -rf ./cmake-build-${typeLower}
echo "Creating build directory"
mkdir cmake-build-${typeLower}
cd cmake-build-${typeLower}
echo "Running cmake"
cmake -G "Ninja" \
-DCMAKE_BUILD_TYPE="${type}" \
..
echo "Linking compile_commands.json"
cd ..
ln -sf ./cmake-build-${typeLower}/compile_commands.json ./compile_commands.json
'';
cmakeDebug = mkCmakeScript "Debug";
cmakeRelease = mkCmakeScript "Release";
mkBuildScript = type: let
typeLower = lib.toLower type;
in
pkgs.writers.writeFish "cmake-build.fish" ''
cd $FLAKE_PROJECT_ROOT/cmake-build-${typeLower}
echo "Running cmake"
NIX_ENFORCE_NO_NATIVE=0 cmake --build . -j$(nproc)
'';
buildDebug = mkBuildScript "Debug";
buildRelease = mkBuildScript "Release";
# Use this to specify commands that should be ran after entering fish shell
initProjectShell = pkgs.writers.writeFish "init-shell.fish" ''
echo "Entering \"${description}\" environment..."
# Determine the project root, used e.g. in cmake scripts
set -g -x FLAKE_PROJECT_ROOT (git rev-parse --show-toplevel)
# C/C++:
abbr -a cmake-debug "${cmakeDebug}"
abbr -a cmake-release "${cmakeRelease}"
abbr -a build-debug "${buildDebug}"
abbr -a build-release "${buildRelease}"
abbr -a debug "${buildDebug} && ./cmake-build-debug/masssprings"
abbr -a release "${buildRelease} && ./cmake-build-release/masssprings"
abbr -a debug-clean "${cmakeDebug} && ${buildDebug} && ./cmake-build-debug/masssprings"
abbr -a release-clean "${cmakeRelease} && ${buildRelease} && ./cmake-build-release/masssprings"
abbr -a rungdb "${buildDebug} && gdb --tui ./cmake-build-debug/masssprings"
abbr -a runtracy "tracy -a 127.0.0.1 &; ${buildRelease} && sudo -E ./cmake-build-release/masssprings"
abbr -a runvalgrind "${buildDebug} && valgrind --leak-check=full --show-reachable=no --show-leak-kinds=definite,indirect,possible --track-origins=no --suppressions=valgrind.supp --log-file=valgrind.log ./cmake-build-debug/masssprings && cat valgrind.log"
abbr -a runclion "clion ./CMakeLists.txt 2>/dev/null 1>&2 & disown;"
'';
in
builtins.concatStringsSep "\n" [
# Launch into pure fish shell
''
exec "$(type -p fish)" -C "source ${initProjectShell} && abbr -a menu '${pkgs.bat}/bin/bat "${initProjectShell}"'"
''
];
}; };
# TODO: Can't get renderdoc in FHS to work # Provide environment with clang stdenv for "nix develop .#clang"
# TODO: Broken. Clang can't find stdlib headers or library headers (raylib, backward, ...).
# Does the clangStdenv not automatically collect the include paths?
clang =
pkgs.mkShell.override {
stdenv = pkgs.clangStdenv;
} {
inherit shellHook;
name = description;
# FHS environment for renderdoc. Access with "nix develop .#renderdoc". nativeBuildInputs = with pkgs; [
# https://ryantm.github.io/nixpkgs/builders/special/fhs-environments cmake
# renderdoc = ninja
# (pkgs.buildFHSEnv { ];
# name = "renderdoc-env";
# buildInputs = with pkgs; [
# targetPkgs = pkgs: # C/C++:
# with pkgs; [ raylib
# # RenderDoc raygui
# renderdoc thread-pool
# boost
# # Build tools
# gcc # Debugging/Testing/Profiling
# cmake backward-cpp
# libbfd
# # Raylib catch2_3
# raylib gbenchmark
# libGL ];
# mesa
# # =========================================================================================
# # X11 # Define environment variables
# libx11 # =========================================================================================
# libxcursor
# libxrandr # Dynamic libraries from buildinputs:
# libxinerama LD_LIBRARY_PATH = nixpkgs.lib.makeLibraryPath buildInputs;
# libxi };
# libxext
# libxfixes
#
# # Wayland
# wayland
# wayland-protocols
# libxkbcommon
# ];
#
# runScript = "fish";
#
# profile = ''
# '';
# }).env;
}; };
} }
); );

69
include/bits.hpp Normal file
View File

@ -0,0 +1,69 @@
#ifndef BITS_HPP_
#define BITS_HPP_
#include "util.hpp"
#include <concepts>
template <class T>
requires std::unsigned_integral<T>
// ReSharper disable once CppRedundantInlineSpecifier
INLINE inline auto create_mask(const uint8_t first, const uint8_t last) -> T
{
// If the mask width is equal the type width return all 1s instead of shifting
// as shifting by type-width is undefined behavior.
if (static_cast<size_t>(last - first + 1) >= sizeof(T) * 8) {
return ~T{0};
}
// Example: first=4, last=7, 7-4+1=4
// 1 << 4 = 0b00010000
// 32 - 1 = 0b00001111
// 31 << 4 = 0b11110000
// Subtracting 1 generates a consecutive mask.
return ((T{1} << (last - first + 1)) - 1) << first;
}
template <class T>
requires std::unsigned_integral<T>
// ReSharper disable once CppRedundantInlineSpecifier
INLINE inline auto clear_bits(T& bits, const uint8_t first, const uint8_t last) -> void
{
const T mask = create_mask<T>(first, last);
bits = bits & ~mask;
}
template <class T, class U>
requires std::unsigned_integral<T> && std::unsigned_integral<U>
// ReSharper disable once CppRedundantInlineSpecifier
INLINE inline auto set_bits(T& bits, const uint8_t first, const uint8_t last, const U value) -> void
{
const T mask = create_mask<T>(first, last);
// Example: first=4, last=6, value=0b1110, bits = 0b 01111110
// mask = 0b 01110000
// bits & ~mask = 0b 00001110
// value << 4 = 0b 11100000
// (value << 4) & mask = 0b 01100000
// (bits & ~mask) | (value << 4) & mask = 0b 01101110
// Insert position: ^^^
// First clear the bits, then | with the value positioned at the insertion point.
// The value may be larger than [first, last], extra bits are ignored.
bits = (bits & ~mask) | ((static_cast<T>(value) << first) & mask);
}
template <class T>
requires std::unsigned_integral<T>
// ReSharper disable once CppRedundantInlineSpecifier
INLINE inline auto get_bits(const T bits, const uint8_t first, const uint8_t last) -> T
{
const T mask = create_mask<T>(first, last);
// We can >> without sign extension because T is unsigned_integral
return (bits & mask) >> first;
}
auto print_bitmap(uint64_t bitmap, uint8_t w, uint8_t h, const std::string& title) -> void;
#endif

View File

@ -3,12 +3,31 @@
#include <raylib.h> #include <raylib.h>
#define THREADPOOL // Enable physics threadpool
// TODO: Using the octree from the last frame completely breaks the physics :/
// #define ASYNC_OCTREE
// Gets set by CMake // Gets set by CMake
// #define THREADPOOL // Enable physics threadpool
// #define BACKWARD // Enable pretty stack traces // #define BACKWARD // Enable pretty stack traces
// #define TRACY // Enable tracy profiling support // #define TRACY // Enable tracy profiling support
#ifdef TRACY
#include <tracy/Tracy.hpp>
#endif
#if defined(_WIN32)
#define NOGDI // All GDI defines and routines
#define NOUSER // All USER defines and routines
#endif
#define BS_THREAD_POOL_NATIVE_EXTENSIONS
// ReSharper disable once CppUnusedIncludeDirective
#include <BS_thread_pool.hpp>
#if defined(_WIN32) // raylib uses these names as function parameters
#undef near
#undef far
#endif
// Window // Window
constexpr int INITIAL_WIDTH = 600; constexpr int INITIAL_WIDTH = 600;
constexpr int INITIAL_HEIGHT = 600; constexpr int INITIAL_HEIGHT = 600;
@ -29,7 +48,7 @@ constexpr float CAMERA_FOV = 90.0;
constexpr float FOV_SPEED = 1.0; constexpr float FOV_SPEED = 1.0;
constexpr float MIN_FOV = 10.0; constexpr float MIN_FOV = 10.0;
constexpr float MAX_FOV = 180.0; constexpr float MAX_FOV = 180.0;
constexpr float CAMERA_DISTANCE = 20.0; constexpr float CAMERA_DISTANCE = 150.0;
constexpr float ZOOM_SPEED = 2.5; constexpr float ZOOM_SPEED = 2.5;
constexpr float MIN_CAMERA_DISTANCE = 2.0; constexpr float MIN_CAMERA_DISTANCE = 2.0;
constexpr float MAX_CAMERA_DISTANCE = 2000.0; constexpr float MAX_CAMERA_DISTANCE = 2000.0;

View File

@ -21,4 +21,4 @@ public:
[[nodiscard]] auto get_shortest_path(size_t source) const -> std::vector<size_t>; [[nodiscard]] auto get_shortest_path(size_t source) const -> std::vector<size_t>;
}; };
#endif #endif

View File

@ -1,5 +1,5 @@
#ifndef INPUT_HPP_ #ifndef INPUT_HANDLER_HPP_
#define INPUT_HPP_ #define INPUT_HANDLER_HPP_
#include "orbit_camera.hpp" #include "orbit_camera.hpp"
#include "state_manager.hpp" #include "state_manager.hpp"
@ -19,7 +19,7 @@ struct show_yes_no_message
{ {
std::string title; std::string title;
std::string message; std::string message;
std::function<void(void)> on_yes; std::function<void()> on_yes;
}; };
struct show_save_preset_window struct show_save_preset_window
@ -78,7 +78,7 @@ public:
// Camera // Camera
bool camera_lock = true; bool camera_lock = true;
bool camera_mass_center_lock = false; bool camera_mass_center_lock = true;
bool camera_panning = false; bool camera_panning = false;
bool camera_rotating = false; bool camera_rotating = false;

15
include/load_save.hpp Normal file
View File

@ -0,0 +1,15 @@
#ifndef LOAD_SAVE_HPP_
#define LOAD_SAVE_HPP_
#include "puzzle.hpp"
#include <string>
auto parse_preset_file(const std::string& preset_file) -> std::pair<std::vector<puzzle>, std::vector<std::string>>;
auto append_preset_file(const std::string& preset_file, const std::string& preset_name, const puzzle& p) -> bool;
auto append_preset_file_quiet(const std::string& preset_file,
const std::string& preset_name,
const puzzle& p,
bool validate) -> bool;
#endif

View File

@ -2,49 +2,14 @@
#define MASS_SPRING_SYSTEM_HPP_ #define MASS_SPRING_SYSTEM_HPP_
#include "octree.hpp" #include "octree.hpp"
#include "util.hpp"
#include "config.hpp" #include "config.hpp"
#include <optional>
#include <raylib.h> #include <raylib.h>
#include <raymath.h>
#ifdef THREADPOOL
#if defined(_WIN32)
#define NOGDI // All GDI defines and routines
#define NOUSER // All USER defines and routines
#endif
#define BS_THREAD_POOL_NATIVE_EXTENSIONS
#include <BS_thread_pool.hpp>
#if defined(_WIN32) // raylib uses these names as function parameters
#undef near
#undef far
#endif
#endif
class mass_spring_system class mass_spring_system
{ {
public: public:
class mass
{
public:
Vector3 position = Vector3Zero();
Vector3 previous_position = Vector3Zero(); // for verlet integration
Vector3 velocity = Vector3Zero();
Vector3 force = Vector3Zero();
public:
mass() = delete;
explicit mass(const Vector3 _position)
: position(_position), previous_position(_position) {}
public:
auto clear_force() -> void;
auto calculate_velocity(float delta_time) -> void;
auto calculate_position(float delta_time) -> void;
auto verlet_update(float delta_time) -> void;
};
class spring class spring
{ {
public: public:
@ -54,61 +19,45 @@ public:
public: public:
spring(const size_t _a, const size_t _b) spring(const size_t _a, const size_t _b)
: a(_a), b(_b) {} : a(_a), b(_b) {}
public:
static auto calculate_spring_force(mass& _a, mass& _b) -> void;
}; };
private:
#ifdef THREADPOOL
BS::thread_pool<> threads;
#endif
public: public:
static constexpr int SMALL_TASK_BLOCK_SIZE = 256;
static constexpr int LARGE_TASK_BLOCK_SIZE = 256;
octree tree; octree tree;
// This is the main ownership of all the states/masses/springs. // This is the main ownership of all the states/masses/springs.
std::vector<mass> masses; std::vector<Vector3> positions;
std::vector<Vector3> previous_positions; // for verlet integration
std::vector<Vector3> velocities;
std::vector<Vector3> forces;
std::vector<spring> springs; std::vector<spring> springs;
public: public:
mass_spring_system() mass_spring_system() {}
#ifdef THREADPOOL
: threads(std::thread::hardware_concurrency() - 1, set_thread_name)
#endif
{
infoln("Using Barnes-Hut + Octree repulsion force calculation.");
#ifdef THREADPOOL
infoln("Thread-pool: {} threads.", threads.get_thread_count());
#else
infoln("Thread-pool: Disabled.");
#endif
}
mass_spring_system(const mass_spring_system& copy) = delete; mass_spring_system(const mass_spring_system& copy) = delete;
auto operator=(const mass_spring_system& copy) -> mass_spring_system& = delete; auto operator=(const mass_spring_system& copy) -> mass_spring_system& = delete;
mass_spring_system(mass_spring_system& move) = delete; mass_spring_system(mass_spring_system& move) = delete;
auto operator=(mass_spring_system&& move) -> mass_spring_system& = delete; auto operator=(mass_spring_system&& move) -> mass_spring_system& = delete;
private:
#ifdef THREADPOOL
static auto set_thread_name(size_t idx) -> void;
#endif
auto build_octree() -> void;
public: public:
auto clear() -> void; auto clear() -> void;
auto add_mass() -> void; auto add_mass() -> void;
auto add_spring(size_t a, size_t b) -> void; auto add_spring(size_t a, size_t b) -> void;
auto clear_forces() -> void; auto clear_forces() -> void;
auto calculate_spring_forces() -> void; auto calculate_spring_force(size_t s) -> void;
auto calculate_repulsion_forces() -> void; auto calculate_spring_forces(std::optional<BS::thread_pool<>* const> thread_pool = std::nullopt) -> void;
auto verlet_update(float delta_time) -> void; auto calculate_repulsion_forces(std::optional<BS::thread_pool<>* const> thread_pool = std::nullopt) -> void;
auto integrate_velocity(size_t m, float dt) -> void;
auto integrate_position(size_t m, float dt) -> void;
auto verlet_update(size_t m, float dt) -> void;
auto update(float dt, std::optional<BS::thread_pool<>* const> thread_pool = std::nullopt) -> void;
auto center_masses() -> void; auto center_masses(std::optional<BS::thread_pool<>* const> thread_pool = std::nullopt) -> void;
}; };
#endif #endif

View File

@ -2,9 +2,10 @@
#define OCTREE_HPP_ #define OCTREE_HPP_
#include <array> #include <array>
#include <vector>
#include <raylib.h> #include <raylib.h>
#include <raymath.h> #include <raymath.h>
#include <vector>
class octree class octree
{ {
@ -31,22 +32,20 @@ public:
public: public:
octree() = default; octree() = default;
octree(const octree& copy) = delete; // octree(const octree& copy) = delete;
auto operator=(const octree& copy) -> octree& = delete; // auto operator=(const octree& copy) -> octree& = delete;
octree(octree&& move) = delete; // octree(octree&& move) = delete;
auto operator=(octree&& move) -> octree& = delete; // auto operator=(octree&& move) -> octree& = delete;
public: public:
auto create_empty_leaf(const Vector3& box_min, const Vector3& box_max) -> int;
[[nodiscard]] auto get_octant(int node_idx, const Vector3& pos) const -> int; [[nodiscard]] auto get_octant(int node_idx, const Vector3& pos) const -> int;
[[nodiscard]] auto get_child_bounds(int node_idx, int octant) const [[nodiscard]] auto get_child_bounds(int node_idx, int octant) const
-> std::pair<Vector3, Vector3>; -> std::pair<Vector3, Vector3>;
auto create_empty_leaf(const Vector3& box_min, const Vector3& box_max) -> int;
auto insert(int node_idx, int mass_id, const Vector3& pos, float mass, int depth) -> void; auto insert(int node_idx, int mass_id, const Vector3& pos, float mass, int depth) -> void;
static auto build_octree(octree& t, const std::vector<Vector3>& positions) -> void;
[[nodiscard]] auto calculate_force(int node_idx, const Vector3& pos) const -> Vector3; [[nodiscard]] auto calculate_force(int node_idx, const Vector3& pos) const -> Vector3;
}; };
#endif #endif

View File

@ -28,4 +28,4 @@ public:
bool mass_center_lock) -> void; bool mass_center_lock) -> void;
}; };
#endif #endif

File diff suppressed because it is too large Load Diff

View File

@ -1,8 +1,8 @@
#ifndef RENDERER_HPP_ #ifndef RENDERER_HPP_
#define RENDERER_HPP_ #define RENDERER_HPP_
#include "orbit_camera.hpp"
#include "config.hpp" #include "config.hpp"
#include "orbit_camera.hpp"
#include "input_handler.hpp" #include "input_handler.hpp"
#include "state_manager.hpp" #include "state_manager.hpp"
#include "user_interface.hpp" #include "user_interface.hpp"
@ -18,7 +18,7 @@ private:
user_interface& gui; user_interface& gui;
const orbit_camera& camera; const orbit_camera& camera;
RenderTexture render_target = RenderTexture graph_target =
LoadRenderTexture(GetScreenWidth() / 2, GetScreenHeight() - MENU_HEIGHT); LoadRenderTexture(GetScreenWidth() / 2, GetScreenHeight() - MENU_HEIGHT);
// TODO: Those should be moved to the user_interface.h // TODO: Those should be moved to the user_interface.h
@ -81,7 +81,7 @@ public:
~renderer() ~renderer()
{ {
UnloadRenderTexture(render_target); UnloadRenderTexture(graph_target);
UnloadRenderTexture(klotski_target); UnloadRenderTexture(klotski_target);
UnloadRenderTexture(menu_target); UnloadRenderTexture(menu_target);

View File

@ -2,12 +2,12 @@
#define STATE_MANAGER_HPP_ #define STATE_MANAGER_HPP_
#include "graph_distances.hpp" #include "graph_distances.hpp"
#include "load_save.hpp"
#include "threaded_physics.hpp" #include "threaded_physics.hpp"
#include "puzzle.hpp" #include "puzzle.hpp"
#include <stack> #include <boost/unordered/unordered_flat_map.hpp>
#include <unordered_map> #include <boost/unordered/unordered_flat_set.hpp>
#include <unordered_set>
class state_manager class state_manager
{ {
@ -16,26 +16,23 @@ private:
std::string preset_file; std::string preset_file;
size_t current_preset = 0; size_t current_preset = 0;
std::vector<puzzle> preset_states = {puzzle(4, 5, 9, 9, false)}; std::vector<puzzle> preset_states = {puzzle(4, 5, 0, 0, true, false)};
std::vector<std::string> preset_comments = {"Empty"}; std::vector<std::string> preset_comments = {"# Empty"};
// State storage (store states twice for bidirectional lookup). // State storage (store states twice for bidirectional lookup).
// Everything else should only store indices to state_pool. // Everything else should only store indices to state_pool.
std::vector<puzzle> state_pool; // Indices are equal to mass_springs mass indices std::vector<puzzle> state_pool; // Indices are equal to mass_springs mass indices
std::unordered_map<puzzle, size_t> state_indices; // Maps states to indices boost::unordered_flat_map<puzzle, size_t, puzzle_hasher> state_indices; // Maps states to indices
std::vector<std::pair<size_t, size_t>> std::vector<std::pair<size_t, size_t>> links; // Indices are equal to mass_springs springs indices
links; // Indices are equal to mass_springs springs indices
graph_distances node_target_distances; // Buffered and reused if the graph doesn't change graph_distances node_target_distances; // Buffered and reused if the graph doesn't change
std::unordered_set<size_t> winning_indices; // Indices of all states where the board is solved boost::unordered_flat_set<size_t> winning_indices; // Indices of all states where the board is solved
std::vector<size_t> std::vector<size_t> winning_path; // Ordered list of node indices leading to the nearest solved state
winning_path; // Ordered list of node indices leading to the nearest solved state boost::unordered_flat_set<size_t> path_indices; // For faster lookup if a vertex is part of the path in renderer
std::unordered_set<size_t>
path_indices; // For faster lookup if a vertex is part of the path in renderer
std::vector<size_t> move_history; // Moves between the starting state and the current state std::vector<size_t> move_history; // Moves between the starting state and the current state
std::unordered_map<size_t, int> visit_counts; // How often each state was visited boost::unordered_flat_map<size_t, int> visit_counts; // How often each state was visited
size_t starting_state_index = 0; size_t starting_state_index = 0;
size_t current_state_index = 0; size_t current_state_index = 0;
@ -45,10 +42,10 @@ private:
bool edited = false; bool edited = false;
public: public:
state_manager(threaded_physics& _physics, const std::string& _preset_file) : physics(_physics) state_manager(threaded_physics& _physics, const std::string& _preset_file)
: physics(_physics), preset_file(_preset_file)
{ {
parse_preset_file(_preset_file); reload_preset_file();
load_preset(0);
} }
state_manager(const state_manager& copy) = delete; state_manager(const state_manager& copy) = delete;
@ -97,15 +94,13 @@ private:
public: public:
// Presets // Presets
auto save_current_to_preset_file(const std::string& preset_comment) -> void;
auto parse_preset_file(const std::string& _preset_file) -> bool; auto reload_preset_file() -> void;
auto append_preset_file(const std::string& preset_name) -> bool;
auto load_preset(size_t preset) -> void; auto load_preset(size_t preset) -> void;
auto load_previous_preset() -> void; auto load_previous_preset() -> void;
auto load_next_preset() -> void; auto load_next_preset() -> void;
// Update current_state // Update current_state
auto update_current_state(const puzzle& p) -> void; auto update_current_state(const puzzle& p) -> void;
auto edit_starting_state(const puzzle& p) -> void; auto edit_starting_state(const puzzle& p) -> void;
auto goto_starting_state() -> void; auto goto_starting_state() -> void;
@ -115,7 +110,6 @@ public:
auto goto_closest_target_state() -> void; auto goto_closest_target_state() -> void;
// Update graph // Update graph
auto populate_graph() -> void; auto populate_graph() -> void;
auto clear_graph_and_add_current(const puzzle& p) -> void; auto clear_graph_and_add_current(const puzzle& p) -> void;
auto clear_graph_and_add_current() -> void; auto clear_graph_and_add_current() -> void;
@ -124,7 +118,6 @@ public:
auto populate_winning_path() -> void; auto populate_winning_path() -> void;
// Index mapping // Index mapping
[[nodiscard]] auto get_index(const puzzle& state) const -> size_t; [[nodiscard]] auto get_index(const puzzle& state) const -> size_t;
[[nodiscard]] auto get_current_index() const -> size_t; [[nodiscard]] auto get_current_index() const -> size_t;
[[nodiscard]] auto get_starting_index() const -> size_t; [[nodiscard]] auto get_starting_index() const -> size_t;
@ -138,10 +131,10 @@ public:
[[nodiscard]] auto get_link_count() const -> size_t; [[nodiscard]] auto get_link_count() const -> size_t;
[[nodiscard]] auto get_path_length() const -> size_t; [[nodiscard]] auto get_path_length() const -> size_t;
[[nodiscard]] auto get_links() const -> const std::vector<std::pair<size_t, size_t>>&; [[nodiscard]] auto get_links() const -> const std::vector<std::pair<size_t, size_t>>&;
[[nodiscard]] auto get_winning_indices() const -> const std::unordered_set<size_t>&; [[nodiscard]] auto get_winning_indices() const -> const boost::unordered_flat_set<size_t>&;
[[nodiscard]] auto get_visit_counts() const -> const std::unordered_map<size_t, int>&; [[nodiscard]] auto get_visit_counts() const -> const boost::unordered_flat_map<size_t, int>&;
[[nodiscard]] auto get_winning_path() const -> const std::vector<size_t>&; [[nodiscard]] auto get_winning_path() const -> const std::vector<size_t>&;
[[nodiscard]] auto get_path_indices() const -> const std::unordered_set<size_t>&; [[nodiscard]] auto get_path_indices() const -> const boost::unordered_flat_set<size_t>&;
[[nodiscard]] auto get_current_visits() const -> int; [[nodiscard]] auto get_current_visits() const -> int;
[[nodiscard]] auto get_current_preset() const -> size_t; [[nodiscard]] auto get_current_preset() const -> size_t;
[[nodiscard]] auto get_preset_count() const -> size_t; [[nodiscard]] auto get_preset_count() const -> size_t;

View File

@ -1,6 +1,8 @@
#ifndef PHYSICS_HPP_ #ifndef PHYSICS_HPP_
#define PHYSICS_HPP_ #define PHYSICS_HPP_
#include "config.hpp"
#include <atomic> #include <atomic>
#include <condition_variable> #include <condition_variable>
#include <mutex> #include <mutex>
@ -11,13 +13,10 @@
#include <variant> #include <variant>
#include <vector> #include <vector>
#ifdef TRACY
#include <tracy/Tracy.hpp>
#endif
class threaded_physics class threaded_physics
{ {
struct add_mass {}; struct add_mass
{};
struct add_spring struct add_spring
{ {
@ -25,24 +24,25 @@ class threaded_physics
size_t b; size_t b;
}; };
struct clear_graph {}; struct clear_graph
{};
using command = std::variant<add_mass, add_spring, clear_graph>; using command = std::variant<add_mass, add_spring, clear_graph>;
struct physics_state struct physics_state
{ {
#ifdef TRACY #ifdef TRACY
TracyLockable(std::mutex, command_mtx); TracyLockable(std::mutex, command_mtx);
#else #else
std::mutex command_mtx; std::mutex command_mtx;
#endif #endif
std::queue<command> pending_commands; std::queue<command> pending_commands;
#ifdef TRACY #ifdef TRACY
TracyLockable(std::mutex, data_mtx); TracyLockable(std::mutex, data_mtx);
#else #else
std::mutex data_mtx; std::mutex data_mtx;
#endif #endif
std::condition_variable_any data_ready_cnd; std::condition_variable_any data_ready_cnd;
std::condition_variable_any data_consumed_cnd; std::condition_variable_any data_consumed_cnd;
Vector3 mass_center = Vector3Zero(); Vector3 mass_center = Vector3Zero();
@ -57,14 +57,17 @@ class threaded_physics
}; };
private: private:
std::optional<BS::thread_pool<>* const> thread_pool;
std::thread physics; std::thread physics;
public: public:
physics_state state; physics_state state;
public: public:
threaded_physics() explicit threaded_physics(
: physics(physics_thread, std::ref(state)) {} const std::optional<BS::thread_pool<>* const> _thread_pool = std::nullopt)
: thread_pool(_thread_pool), physics(physics_thread, std::ref(state), std::ref(thread_pool))
{}
threaded_physics(const threaded_physics& copy) = delete; threaded_physics(const threaded_physics& copy) = delete;
auto operator=(const threaded_physics& copy) -> threaded_physics& = delete; auto operator=(const threaded_physics& copy) -> threaded_physics& = delete;
@ -80,16 +83,19 @@ public:
} }
private: private:
static auto physics_thread(physics_state& state) -> void; #ifdef ASYNC_OCTREE
static auto set_octree_pool_thread_name(size_t idx) -> void;
#endif
static auto physics_thread(physics_state& state,
std::optional<BS::thread_pool<>* const> thread_pool) -> void;
public: public:
auto add_mass_cmd() -> void;
auto add_spring_cmd(size_t a, size_t b) -> void;
auto clear_cmd() -> void; auto clear_cmd() -> void;
auto add_mass_cmd() -> void;
auto add_mass_springs_cmd(size_t num_masses, const std::vector<std::pair<size_t, size_t>>& springs) -> void; auto add_spring_cmd(size_t a, size_t b) -> void;
auto add_mass_springs_cmd(size_t num_masses,
const std::vector<std::pair<size_t, size_t>>& springs) -> void;
}; };
#endif #endif

View File

@ -1,5 +1,5 @@
#ifndef GUI_HPP_ #ifndef USER_INTERFACE_HPP_
#define GUI_HPP_ #define USER_INTERFACE_HPP_
#include "orbit_camera.hpp" #include "orbit_camera.hpp"
#include "config.hpp" #include "config.hpp"
@ -89,7 +89,7 @@ private:
grid board_grid = grid board_grid =
grid(0, MENU_HEIGHT, GetScreenWidth() / 2, GetScreenHeight() - MENU_HEIGHT, grid(0, MENU_HEIGHT, GetScreenWidth() / 2, GetScreenHeight() - MENU_HEIGHT,
state.get_current_state().width, state.get_current_state().height, BOARD_PADDING); state.get_current_state().get_width(), state.get_current_state().get_height(), BOARD_PADDING);
grid graph_overlay_grid = grid(GetScreenWidth() / 2, MENU_HEIGHT, 200, 100, 1, 4, MENU_PAD); grid graph_overlay_grid = grid(GetScreenWidth() / 2, MENU_HEIGHT, 200, 100, 1, 4, MENU_PAD);
@ -100,11 +100,11 @@ private:
std::string message_title; std::string message_title;
std::string message_message; std::string message_message;
std::function<void(void)> yes_no_handler; std::function<void()> yes_no_handler;
bool ok_message = false; bool ok_message = false;
bool yes_no_message = false; bool yes_no_message = false;
bool save_window = false; bool save_window = false;
std::array<char, 256> preset_name = {}; std::array<char, 256> preset_comment = {};
bool help_window = false; bool help_window = false;
public: public:

View File

@ -3,7 +3,77 @@
#include <iostream> #include <iostream>
#include <raylib.h> #include <raylib.h>
#include <raymath.h>
#define INLINE __attribute__((always_inline))
#define PACKED __attribute__((packed))
// std::variant visitor
// https://en.cppreference.com/w/cpp/utility/variant/visit
template <class... Ts>
struct overloads : Ts...
{
using Ts::operator()...;
};
// Enums
enum dir : uint8_t
{
nor = 1 << 0,
eas = 1 << 1,
sou = 1 << 2,
wes = 1 << 3,
};
// Ansi
enum class ctrl : uint8_t
{
reset = 0,
bold_bright = 1,
underline = 4,
inverse = 7,
bold_bright_off = 21,
underline_off = 24,
inverse_off = 27
};
enum class fg : uint8_t
{
black = 30,
red = 31,
green = 32,
yellow = 33,
blue = 34,
magenta = 35,
cyan = 36,
white = 37
};
enum class bg : uint8_t
{
black = 40,
red = 41,
green = 42,
yellow = 43,
blue = 44,
magenta = 45,
cyan = 46,
white = 47
};
inline auto ansi_bold_fg(const fg color) -> std::string
{
return std::format("\033[{};{}m", static_cast<int>(ctrl::bold_bright), static_cast<int>(color));
}
inline auto ansi_reset() -> std::string
{
return std::format("\033[{}m", static_cast<int>(ctrl::reset));
}
// Output
inline auto operator<<(std::ostream& os, const Vector2& v) -> std::ostream& inline auto operator<<(std::ostream& os, const Vector2& v) -> std::ostream&
{ {
@ -17,86 +87,33 @@ inline auto operator<<(std::ostream& os, const Vector3& v) -> std::ostream&
return os; return os;
} }
// https://en.cppreference.com/w/cpp/utility/variant/visit
template <class... Ts>
struct overloads : Ts...
{
using Ts::operator()...;
};
enum direction
{
nor = 1 << 0,
eas = 1 << 1,
sou = 1 << 2,
wes = 1 << 3,
};
enum ctrl
{
reset = 0,
bold_bright = 1,
underline = 4,
inverse = 7,
bold_bright_off = 21,
underline_off = 24,
inverse_off = 27
};
enum fg
{
fg_black = 30,
fg_red = 31,
fg_green = 32,
fg_yellow = 33,
fg_blue = 34,
fg_magenta = 35,
fg_cyan = 36,
fg_white = 37
};
enum bg
{
bg_black = 40,
bg_red = 41,
bg_green = 42,
bg_yellow = 43,
bg_blue = 44,
bg_magenta = 45,
bg_cyan = 46,
bg_white = 47
};
inline auto ansi_bold_fg(const fg color) -> std::string
{
return std::format("\033[1;{}m", static_cast<int>(color));
}
inline auto ansi_reset() -> std::string
{
return "\033[0m";
}
// std::println doesn't work with mingw // std::println doesn't work with mingw
template <typename... Args>
auto traceln(std::format_string<Args...> fmt, Args&&... args) -> void
{
std::cout << std::format("[{}TRACE{}]: ", ansi_bold_fg(fg::cyan), ansi_reset()) << std::format(
fmt, std::forward<Args>(args)...) << std::endl;
}
template <typename... Args> template <typename... Args>
auto infoln(std::format_string<Args...> fmt, Args&&... args) -> void auto infoln(std::format_string<Args...> fmt, Args&&... args) -> void
{ {
std::cout << std::format("[{}INFO{}]: ", ansi_bold_fg(fg_blue), ansi_reset()) std::cout << std::format("[{}INFO{}]: ", ansi_bold_fg(fg::blue), ansi_reset()) << std::format(
<< std::format(fmt, std::forward<Args>(args)...) << std::endl; fmt, std::forward<Args>(args)...) << std::endl;
} }
template <typename... Args> template <typename... Args>
auto warnln(std::format_string<Args...> fmt, Args&&... args) -> void auto warnln(std::format_string<Args...> fmt, Args&&... args) -> void
{ {
std::cout << std::format("[{}WARNING{}]: ", ansi_bold_fg(fg_yellow), ansi_reset()) std::cout << std::format("[{}WARNING{}]: ", ansi_bold_fg(fg::yellow), ansi_reset()) << std::format(
<< std::format(fmt, std::forward<Args>(args)...) << std::endl; fmt, std::forward<Args>(args)...) << std::endl;
} }
template <typename... Args> template <typename... Args>
auto errln(std::format_string<Args...> fmt, Args&&... args) -> void auto errln(std::format_string<Args...> fmt, Args&&... args) -> void
{ {
std::cout << std::format("[{}ERROR{}]: ", ansi_bold_fg(fg_red), ansi_reset()) std::cout << std::format("[{}ERROR{}]: ", ansi_bold_fg(fg::red), ansi_reset()) << std::format(
<< std::format(fmt, std::forward<Args>(args)...) << std::endl; fmt, std::forward<Args>(args)...) << std::endl;
} }
#endif #endif

15
src/bits.cpp Normal file
View File

@ -0,0 +1,15 @@
#include "bits.hpp"
auto print_bitmap(const uint64_t bitmap, const uint8_t w, const uint8_t h, const std::string& title) -> void {
traceln("{}:", title);
traceln("{}", std::string(2 * w - 1, '='));
for (size_t y = 0; y < w; ++y) {
std::cout << " ";
for (size_t x = 0; x < h; ++x) {
std::cout << static_cast<int>(get_bits(bitmap, y * w + x, y * h + x)) << " ";
}
std::cout << "\n";
}
std::cout << std::flush;
traceln("{}", std::string(2 * w - 1, '='));
}

View File

@ -2,10 +2,6 @@
#include <queue> #include <queue>
#ifdef TRACY
#include <tracy/Tracy.hpp>
#endif
auto graph_distances::clear() -> void auto graph_distances::clear() -> void
{ {
distances.clear(); distances.clear();

View File

@ -162,11 +162,12 @@ auto input_handler::select_block() -> void
auto input_handler::start_add_block() -> void auto input_handler::start_add_block() -> void
{ {
const puzzle& current = state.get_current_state(); const puzzle& current = state.get_current_state();
if (!editing || current.try_get_block(hov_x, hov_y) || has_block_add_xy) { if (!editing || current.try_get_block(hov_x, hov_y) || has_block_add_xy || current.block_count() >=
puzzle::MAX_BLOCKS) {
return; return;
} }
if (hov_x >= 0 && hov_x < current.width && hov_y >= 0 && hov_y < current.height) { if (hov_x >= 0 && hov_x < current.get_width() && hov_y >= 0 && hov_y < current.get_height()) {
block_add_x = hov_x; block_add_x = hov_x;
block_add_y = hov_y; block_add_y = hov_y;
has_block_add_xy = true; has_block_add_xy = true;
@ -187,7 +188,8 @@ auto input_handler::clear_add_block() -> void
auto input_handler::add_block() -> void auto input_handler::add_block() -> void
{ {
const puzzle& current = state.get_current_state(); const puzzle& current = state.get_current_state();
if (!editing || current.try_get_block(hov_x, hov_y) || !has_block_add_xy) { if (!editing || current.try_get_block(hov_x, hov_y) || !has_block_add_xy || current.block_count() >=
puzzle::MAX_BLOCKS) {
return; return;
} }
@ -323,7 +325,7 @@ auto input_handler::move_block_eas() -> void
auto input_handler::print_state() const -> void auto input_handler::print_state() const -> void
{ {
infoln("State: \"{}\"", state.get_current_state().state); infoln("State: \"{}\"", state.get_current_state().string_repr());
} }
auto input_handler::load_previous_preset() -> void auto input_handler::load_previous_preset() -> void
@ -332,7 +334,7 @@ auto input_handler::load_previous_preset() -> void
return; return;
} }
const auto handler = [&]() const auto handler = [&]
{ {
block_add_x = -1; block_add_x = -1;
block_add_y = -1; block_add_y = -1;
@ -353,7 +355,7 @@ auto input_handler::load_next_preset() -> void
return; return;
} }
const auto handler = [&]() const auto handler = [&]
{ {
block_add_x = -1; block_add_x = -1;
block_add_y = -1; block_add_y = -1;
@ -370,7 +372,7 @@ auto input_handler::load_next_preset() -> void
auto input_handler::goto_starting_state() -> void auto input_handler::goto_starting_state() -> void
{ {
const auto handler = [&]() const auto handler = [&]
{ {
state.goto_starting_state(); state.goto_starting_state();
sel_x = 0; sel_x = 0;
@ -387,7 +389,7 @@ auto input_handler::populate_graph() const -> void
auto input_handler::clear_graph() -> void auto input_handler::clear_graph() -> void
{ {
const auto handler = [&]() const auto handler = [&]
{ {
state.clear_graph_and_add_current(); state.clear_graph_and_add_current();
}; };
@ -433,7 +435,7 @@ auto input_handler::goto_previous_state() const -> void
auto input_handler::toggle_restricted_movement() const -> void auto input_handler::toggle_restricted_movement() const -> void
{ {
const puzzle& current = state.get_current_state(); const puzzle& current = state.get_current_state();
const std::optional<puzzle>& next = current.try_toggle_restricted(); const std::optional<puzzle>& next = current.toggle_restricted();
if (!editing || !next) { if (!editing || !next) {
return; return;
@ -471,7 +473,7 @@ auto input_handler::remove_board_column() const -> void
const puzzle& current = state.get_current_state(); const puzzle& current = state.get_current_state();
const std::optional<puzzle>& next = current.try_remove_column(); const std::optional<puzzle>& next = current.try_remove_column();
if (!editing || current.width <= puzzle::MIN_WIDTH || !next) { if (!editing || current.get_width() <= puzzle::MIN_WIDTH || !next) {
return; return;
} }
@ -483,7 +485,7 @@ auto input_handler::add_board_column() const -> void
const puzzle& current = state.get_current_state(); const puzzle& current = state.get_current_state();
const std::optional<puzzle>& next = current.try_add_column(); const std::optional<puzzle>& next = current.try_add_column();
if (!editing || current.width >= puzzle::MAX_WIDTH || !next) { if (!editing || current.get_width() >= puzzle::MAX_WIDTH || !next) {
return; return;
} }
@ -495,7 +497,7 @@ auto input_handler::remove_board_row() const -> void
const puzzle& current = state.get_current_state(); const puzzle& current = state.get_current_state();
const std::optional<puzzle>& next = current.try_remove_row(); const std::optional<puzzle>& next = current.try_remove_row();
if (!editing || current.height <= puzzle::MIN_HEIGHT || !next) { if (!editing || current.get_height() <= puzzle::MIN_HEIGHT || !next) {
return; return;
} }
@ -507,7 +509,7 @@ auto input_handler::add_board_row() const -> void
const puzzle& current = state.get_current_state(); const puzzle& current = state.get_current_state();
const std::optional<puzzle>& next = current.try_add_row(); const std::optional<puzzle>& next = current.try_add_row();
if (!editing || current.height >= puzzle::MAX_HEIGHT || !next) { if (!editing || current.get_height() >= puzzle::MAX_HEIGHT || !next) {
return; return;
} }
@ -528,7 +530,7 @@ auto input_handler::toggle_editing() -> void
auto input_handler::clear_goal() const -> void auto input_handler::clear_goal() const -> void
{ {
const puzzle& current = state.get_current_state(); const puzzle& current = state.get_current_state();
const std::optional<puzzle>& next = current.try_clear_goal(); const std::optional<puzzle>& next = current.clear_goal();
if (!editing || !next) { if (!editing || !next) {
return; return;

79
src/load_save.cpp Normal file
View File

@ -0,0 +1,79 @@
#include "load_save.hpp"
#include <fstream>
auto parse_preset_file(const std::string& preset_file) -> std::pair<std::vector<puzzle>, std::vector<std::string>>
{
std::fstream file(preset_file, std::ios::in);
if (!file) {
infoln("Preset file \"{}\" couldn't be opened.", preset_file);
return {};
}
std::string line;
std::vector<std::string> comment_lines;
std::vector<std::string> preset_lines;
while (std::getline(file, line)) {
if (line.starts_with("S")) {
preset_lines.push_back(line);
} else if (line.starts_with("#")) {
comment_lines.push_back(line);
}
}
if (preset_lines.empty() || comment_lines.size() != preset_lines.size()) {
infoln("Preset file \"{}\" couldn't be opened.", preset_file);
return {};
}
std::vector<puzzle> preset_states;
for (const auto& preset : preset_lines) {
// Each char is a bit
const puzzle& p = puzzle(preset);
if (const std::optional<std::string>& reason = p.try_get_invalid_reason()) {
infoln("Preset file \"{}\" contained invalid presets: {}", preset_file, *reason);
return {};
}
preset_states.emplace_back(p);
}
infoln("Loaded {} presets from \"{}\".", preset_lines.size(), preset_file);
return {preset_states, comment_lines};
}
auto append_preset_file(const std::string& preset_file, const std::string& preset_name, const puzzle& p) -> bool
{
infoln(R"(Saving preset "{}" to "{}")", preset_name, preset_file);
if (p.try_get_invalid_reason()) {
return false;
}
std::fstream file(preset_file, std::ios_base::app | std::ios_base::out);
if (!file) {
infoln("Preset file \"{}\" couldn't be opened.", preset_file);
return false;
}
file << "\n# " << preset_name << "\n" << p.string_repr() << std::flush;
return true;
}
auto append_preset_file_quiet(const std::string& preset_file, const std::string& preset_name, const puzzle& p, const bool validate) -> bool
{
if (validate && p.try_get_invalid_reason()) {
return false;
}
std::fstream file(preset_file, std::ios_base::app | std::ios_base::out);
if (!file) {
return false;
}
file << "\n# " << preset_name << "\n" << p.string_repr() << std::flush;
return true;
}

View File

@ -4,62 +4,59 @@
#include "config.hpp" #include "config.hpp"
#include "input_handler.hpp" #include "input_handler.hpp"
#include "mass_spring_system.hpp"
#include "threaded_physics.hpp" #include "threaded_physics.hpp"
#include "renderer.hpp" #include "renderer.hpp"
#include "state_manager.hpp" #include "state_manager.hpp"
#include "user_interface.hpp" #include "user_interface.hpp"
#ifdef TRACY #include <filesystem>
#include <tracy/Tracy.hpp>
#ifndef WIN32
#include <boost/program_options.hpp>
namespace po = boost::program_options;
#endif #endif
// TODO: Add some popups (my split between input.cpp/gui.cpp makes this ugly) // TODO: Implement state discovery/enumeration
// - Clear graph: Notify that this will clear the visited states and move // - Find all possible initial board states (single one for each possible statespace).
// history // Currently wer're just finding all states given the initial state
// - Reset state: Notify that this will reset the move count // - Would allow to generate random puzzles with a certain move count
// TODO: Export cluster to graphviz
// TODO: Reduce memory usage // TODO: Fix naming:
// - The memory model of the puzzle board is terrible (bitboards?) // - Target: The block that has to leave the board to win
// - Goal: The opening in the board for the target
// TODO: Improve solver // - Puzzle (not board or state): A puzzle configuration (width, height, goal_x, goal_y, restricted, goal)
// - Move discovery is terrible // - Block: A puzzle block (x, y, width, height, target, immovable)
// - Instead of trying each direction for each block, determine the // - Puzzle State: A specific puzzle state (width, height, goal_x, goal_y, restricted, goal, blocks)
// possible moves more efficiently (requires a different memory model) // - Cluster: A graph of puzzle states connected by moves, generated from a specific Puzzle State
// - Implement state discovery/enumeration // - Puzzle Space: A number of Clusters generated from a generic Puzzle
// - Find all possible initial board states (single one for each // TODO: Add state space generation time to debug overlay
// possible statespace). Currently wer're just finding all states // TODO: Move selection accordingly when undoing moves (need to diff two states and get the moved blocks)
// given the initial state
// - Would allow to generate random puzzles with a certain move count
// TODO: Move selection accordingly when undoing moves (need to diff two states
// and get the moved blocks)
// TODO: Click states in the graph to display them in the board // TODO: Click states in the graph to display them in the board
// NOTE: Tracy uses a huge amount of memory. For longer testing disable Tracy. #ifdef THREADPOOL
auto set_pool_thread_name(size_t idx) -> void
auto main(int argc, char* argv[]) -> int
{ {
std::string preset_file; BS::this_thread::set_os_thread_name(std::format("worker-{}", idx));
if (argc != 2) { }
preset_file = "default.puzzle";
} else {
preset_file = argv[1];
}
#ifdef BACKWARD BS::thread_pool<> threads(std::thread::hardware_concurrency() - 2, set_pool_thread_name);
infoln("Backward stack-traces enabled."); constexpr std::optional<BS::thread_pool<>* const> thread_pool = &threads;
#else #else
infoln("Backward stack-traces disabled."); constexpr std::optional<BS::thread_pool<>* const> thread_pool = std::nullopt;
#endif #endif
#ifdef TRACY std::string preset_file = "default.puzzle";
infoln("Tracy adapter enabled."); std::string output_file = "clusters.puzzle";
#else int max_blocks = 5;
infoln("Tracy adapter disabled."); int board_width = 6;
#endif int board_height = 6;
int goal_x = 4;
int goal_y = 2;
bool restricted = true;
auto ui_mode() -> int
{
// RayLib window setup // RayLib window setup
SetTraceLogLevel(LOG_ERROR); SetTraceLogLevel(LOG_ERROR);
SetConfigFlags(FLAG_VSYNC_HINT); SetConfigFlags(FLAG_VSYNC_HINT);
@ -69,7 +66,7 @@ auto main(int argc, char* argv[]) -> int
InitWindow(INITIAL_WIDTH * 2, INITIAL_HEIGHT + MENU_HEIGHT, "MassSprings"); InitWindow(INITIAL_WIDTH * 2, INITIAL_HEIGHT + MENU_HEIGHT, "MassSprings");
// Game setup // Game setup
threaded_physics physics; threaded_physics physics(thread_pool);
state_manager state(physics, preset_file); state_manager state(physics, preset_file);
orbit_camera camera; orbit_camera camera;
input_handler input(state, camera); input_handler input(state, camera);
@ -89,9 +86,9 @@ auto main(int argc, char* argv[]) -> int
// Game loop // Game loop
while (!WindowShouldClose()) { while (!WindowShouldClose()) {
#ifdef TRACY #ifdef TRACY
FrameMarkStart("MainThread"); FrameMarkStart("MainThread");
#endif #endif
// Time tracking // Time tracking
std::chrono::time_point now = std::chrono::high_resolution_clock::now(); std::chrono::time_point now = std::chrono::high_resolution_clock::now();
@ -102,16 +99,16 @@ auto main(int argc, char* argv[]) -> int
// Input update // Input update
input.handle_input(); input.handle_input();
// Read positions from physics thread // Read positions from physics thread
#ifdef TRACY #ifdef TRACY
FrameMarkStart("MainThreadConsumeLock"); FrameMarkStart("MainThreadConsumeLock");
#endif #endif
{ {
#ifdef TRACY #ifdef TRACY
std::unique_lock<LockableBase(std::mutex)> lock(physics.state.data_mtx); std::unique_lock<LockableBase(std::mutex)> lock(physics.state.data_mtx);
#else #else
std::unique_lock<std::mutex> lock(physics.state.data_mtx); std::unique_lock<std::mutex> lock(physics.state.data_mtx);
#endif #endif
ups = physics.state.ups; ups = physics.state.ups;
mass_center = physics.state.mass_center; mass_center = physics.state.mass_center;
@ -130,16 +127,15 @@ auto main(int argc, char* argv[]) -> int
physics.state.data_consumed_cnd.notify_all(); physics.state.data_consumed_cnd.notify_all();
} }
} }
#ifdef TRACY #ifdef TRACY
FrameMarkEnd("MainThreadConsumeLock"); FrameMarkEnd("MainThreadConsumeLock");
#endif #endif
// Update the camera after the physics, so target lock is smooth // Update the camera after the physics, so target lock is smooth
size_t current_index = state.get_current_index(); size_t current_index = state.get_current_index();
if (masses.size() > current_index) { if (masses.size() > current_index) {
const mass_spring_system::mass& current_mass = mass_spring_system::mass(masses.at(current_index)); const Vector3& current_mass = masses[current_index];
camera.update(current_mass.position, mass_center, input.camera_lock, camera.update(current_mass, mass_center, input.camera_lock, input.camera_mass_center_lock);
input.camera_mass_center_lock);
} }
// Rendering // Rendering
@ -153,13 +149,200 @@ auto main(int argc, char* argv[]) -> int
} }
++loop_iterations; ++loop_iterations;
#ifdef TRACY #ifdef TRACY
FrameMark; FrameMark;
FrameMarkEnd("MainThread"); FrameMarkEnd("MainThread");
#endif #endif
} }
CloseWindow(); CloseWindow();
return 0; return 0;
}
auto rush_hour_puzzle_space() -> int
{
const boost::unordered_flat_set<puzzle::block, block_hasher2, block_equal2> permitted_blocks = {
puzzle::block(0, 0, 2, 1, false, false),
puzzle::block(0, 0, 3, 1, false, false),
puzzle::block(0, 0, 1, 2, false, false),
puzzle::block(0, 0, 1, 3, false, false)
};
const puzzle::block target_block = puzzle::block(0, 0, 2, 1, true, false);
const std::tuple<uint8_t, uint8_t, uint8_t, uint8_t> target_block_pos_range = {0, goal_y, board_width - 1, goal_y};
infoln("Exploring Rush-Hour puzzle space:");
infoln("- Size: {}x{}", board_width, board_height);
infoln("- Goal: {},{}", goal_x, goal_y);
infoln("- Restricted: {}", restricted);
infoln("- Max Blocks: {}", max_blocks);
infoln("- Target: {}x{}", target_block.get_width(), target_block.get_height());
infoln("- Permitted block sizes:");
std::cout << " ";
for (const puzzle::block b : permitted_blocks) {
std::cout << std::format(" {}x{},", b.get_width(), b.get_height());
}
std::cout << std::endl;
const std::chrono::high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now();
const puzzle p = puzzle(board_width, board_height, goal_x, goal_y, restricted, true);
const boost::unordered_flat_set<puzzle, puzzle_hasher> result = p.explore_puzzle_space(
permitted_blocks,
target_block,
target_block_pos_range,
max_blocks,
thread_pool);
const std::chrono::high_resolution_clock::time_point end = std::chrono::high_resolution_clock::now();
infoln("Found {} different clusters. Took {}s.",
result.size(),
std::chrono::duration_cast<std::chrono::seconds>(end - start).count());
infoln("Sorting clusters...");
std::vector<puzzle> result_sorted{result.begin(), result.end()};
std::ranges::sort(result_sorted, std::ranges::greater{});
// for (const puzzle& _p : result_sorted) {
// traceln("{}", _p.string_repr());
// }
size_t i = 0;
size_t success = 0;
std::filesystem::remove(output_file);
for (const puzzle& _p : result_sorted) {
if (append_preset_file_quiet(output_file, std::format("Cluster {}", i), _p, true)) {
++success;
}
++i;
}
if (success != result_sorted.size()) {
warnln("Saved {} of {} clusters", success, result_sorted.size());
} else {
infoln("Saved {} of {} clusters", success, result_sorted.size());
}
return 0;
}
enum class runmode
{
USER_INTERFACE, RUSH_HOUR_PUZZLE_SPACE, EXIT,
};
auto argparse(const int argc, char* argv[]) -> runmode
{
#ifndef WIN32
po::options_description desc("Allowed options");
desc.add_options() //
("help", "produce help message") //
("presets", po::value<std::string>()->default_value(preset_file), "load presets from file") //
("output", po::value<std::string>()->default_value(output_file), "output file for generated clusters") //
("space", po::value<std::string>()->value_name("rh|klotski"), "generate puzzle space with ruleset") //
("w", po::value<int>()->default_value(board_width)->value_name("[3, 8]"), "board width") //
("h", po::value<int>()->default_value(board_height)->value_name("[3, 8"), "board height") //
("gx", po::value<int>()->default_value(goal_x)->value_name("[0, w-1]"), "board goal horizontal position") //
("gy", po::value<int>()->default_value(goal_y)->value_name("[0, h-1]"), "board goal vertical position") //
("free", "allow free block movement") //
("blocks",
po::value<int>()->default_value(max_blocks)->value_name("[1, 15]"),
"block limit for puzzle space generation") //
;
po::positional_options_description positional;
positional.add("presets", -1);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).options(desc).positional(positional).run(), vm);
po::notify(vm);
if (vm.contains("help")) {
std::cout << desc << std::endl;
return runmode::EXIT;
}
if (vm.contains("output")) {
output_file = vm["output"].as<std::string>();
}
if (vm.contains("w")) {
board_width = vm["w"].as<int>();
board_width = std::max(static_cast<int>(puzzle::MIN_WIDTH),
std::min(board_width, static_cast<int>(puzzle::MAX_WIDTH)));
}
if (vm.contains("h")) {
board_height = vm["h"].as<int>();
board_height = std::max(static_cast<int>(puzzle::MIN_HEIGHT),
std::min(board_height, static_cast<int>(puzzle::MAX_HEIGHT)));
}
if (vm.contains("gx")) {
goal_x = vm["gx"].as<int>();
goal_x = std::max(0, std::min(goal_x, static_cast<int>(puzzle::MAX_WIDTH) - 1));
}
if (vm.contains("gy")) {
goal_y = vm["gy"].as<int>();
goal_y = std::max(0, std::min(goal_y, static_cast<int>(puzzle::MAX_HEIGHT) - 1));
}
if (vm.contains("free")) {
restricted = false;
}
if (vm.contains("blocks")) {
max_blocks = vm["blocks"].as<int>();
max_blocks = std::max(1, std::min(max_blocks, static_cast<int>(puzzle::MAX_BLOCKS)));
}
if (vm.contains("space")) {
const std::string ruleset = vm["space"].as<std::string>();
if (ruleset == "rh") {
return runmode::RUSH_HOUR_PUZZLE_SPACE;
}
if (ruleset == "klotski") {
throw std::runtime_error("Not implemented");
}
}
if (vm.contains("presets")) {
preset_file = vm["presets"].as<std::string>();
}
#endif
return runmode::USER_INTERFACE;
}
auto main(const int argc, char* argv[]) -> int
{
#ifdef BACKWARD
infoln("Backward stack-traces enabled.");
#else
infoln("Backward stack-traces disabled.");
#endif
#ifdef TRACY
infoln("Tracy adapter enabled.");
#else
infoln("Tracy adapter disabled.");
#endif
infoln("Using background thread for physics.");
infoln("Using octree-barnes-hut for graph layout.");
#ifdef THREADPOOL
infoln("Additional thread-pool enabled ({} threads).", threads.get_thread_count());
#else
infoln("Additional thread-pool disabled.");
#endif
switch (argparse(argc, argv)) {
case runmode::USER_INTERFACE:
return ui_mode();
case runmode::RUSH_HOUR_PUZZLE_SPACE:
return rush_hour_puzzle_space();
case runmode::EXIT:
return 0;
};
return 1;
} }

View File

@ -2,66 +2,63 @@
#include "config.hpp" #include "config.hpp"
#include <cfloat> #include <cfloat>
#include <cstring>
#ifdef TRACY auto mass_spring_system::calculate_spring_force(const size_t s) -> void
#include <tracy/Tracy.hpp>
#endif
auto mass_spring_system::mass::clear_force() -> void
{ {
force = Vector3Zero(); const spring _s = springs[s];
const Vector3 a_pos = positions[_s.a];
const Vector3 b_pos = positions[_s.b];
const Vector3 a_vel = velocities[_s.a];
const Vector3 b_vel = velocities[_s.b];
const Vector3 delta_pos = a_pos - b_pos;
const Vector3 delta_vel = a_vel - b_vel;
const float sq_len = Vector3DotProduct(delta_pos, delta_pos);
const float inv_len = 1.0f / sqrt(sq_len);
const float len = sq_len * inv_len;
const float hooke = SPRING_CONSTANT * (len - REST_LENGTH);
const float dampening = DAMPENING_CONSTANT * Vector3DotProduct(delta_vel, delta_pos) * inv_len;
const Vector3 a_force = Vector3Scale(delta_pos, -(hooke + dampening) * inv_len);
const Vector3 b_force = a_force * -1.0f;
forces[_s.a] += a_force;
forces[_s.b] += b_force;
} }
auto mass_spring_system::mass::calculate_velocity(const float delta_time) -> void auto mass_spring_system::integrate_velocity(const size_t m, const float dt) -> void
{ {
const Vector3 acceleration = Vector3Scale(force, 1.0 / MASS); const Vector3 acc = forces[m] / MASS;
const Vector3 temp = Vector3Scale(acceleration, delta_time); velocities[m] += acc * dt;
velocity = Vector3Add(velocity, temp);
} }
auto mass_spring_system::mass::calculate_position(const float delta_time) -> void auto mass_spring_system::integrate_position(const size_t m, const float dt) -> void
{ {
previous_position = position; previous_positions[m] = positions[m];
positions[m] += velocities[m] * dt;
const Vector3 temp = Vector3Scale(velocity, delta_time);
position = Vector3Add(position, temp);
} }
auto mass_spring_system::mass::verlet_update(const float delta_time) -> void auto mass_spring_system::verlet_update(const size_t m, const float dt) -> void
{ {
const Vector3 acceleration = Vector3Scale(force, 1.0 / MASS); const Vector3 acc = (forces[m] / MASS) * dt * dt;
const Vector3 temp_position = position; const Vector3 pos = positions[m];
Vector3 displacement = Vector3Subtract(position, previous_position); Vector3 delta_pos = pos - previous_positions[m];
const Vector3 accel_term = Vector3Scale(acceleration, delta_time * delta_time); delta_pos *= 1.0 - VERLET_DAMPENING; // Minimal dampening
// Minimal dampening positions[m] += delta_pos + acc;
displacement = Vector3Scale(displacement, 1.0 - VERLET_DAMPENING); previous_positions[m] = pos;
position = Vector3Add(Vector3Add(position, displacement), accel_term);
previous_position = temp_position;
}
auto mass_spring_system::spring::calculate_spring_force(mass& _a, mass& _b) -> void
{
// TODO: Use a bungee force here instead of springs, since we already have global repulsion?
const Vector3 delta_position = Vector3Subtract(_a.position, _b.position);
const float current_length = Vector3Length(delta_position);
const Vector3 delta_velocity = Vector3Subtract(_a.velocity, _b.velocity);
const float hooke = SPRING_CONSTANT * (current_length - REST_LENGTH);
const float dampening = DAMPENING_CONSTANT * Vector3DotProduct(delta_velocity, delta_position) / current_length;
const Vector3 force_a = Vector3Scale(delta_position, -(hooke + dampening) / current_length);
const Vector3 force_b = Vector3Scale(force_a, -1.0);
_a.force = Vector3Add(_a.force, force_a);
_b.force = Vector3Add(_b.force, force_b);
} }
auto mass_spring_system::clear() -> void auto mass_spring_system::clear() -> void
{ {
masses.clear(); positions.clear();
previous_positions.clear();
velocities.clear();
forces.clear();
springs.clear(); springs.clear();
tree.nodes.clear(); tree.nodes.clear();
} }
@ -77,24 +74,27 @@ auto mass_spring_system::add_mass() -> void
// }; // };
// position = Vector3Scale(Vector3Normalize(position), REST_LENGTH * 2.0); // position = Vector3Scale(Vector3Normalize(position), REST_LENGTH * 2.0);
masses.emplace_back(Vector3Zero()); positions.emplace_back(Vector3Zero());
previous_positions.emplace_back(Vector3Zero());
velocities.emplace_back(Vector3Zero());
forces.emplace_back(Vector3Zero());
} }
auto mass_spring_system::add_spring(size_t a, size_t b) -> void auto mass_spring_system::add_spring(size_t a, size_t b) -> void
{ {
// Update masses to be located along a random walk when adding the springs // Update masses to be located along a random walk when adding the springs
const mass& mass_a = masses.at(a); const Vector3& mass_a = positions[a];
mass& mass_b = masses.at(b); const Vector3& mass_b = positions[b];
Vector3 offset{ Vector3 offset{static_cast<float>(GetRandomValue(-100, 100)),
static_cast<float>(GetRandomValue(-100, 100)), static_cast<float>(GetRandomValue(-100, 100)), static_cast<float>(GetRandomValue(-100, 100)),
static_cast<float>(GetRandomValue(-100, 100)) static_cast<float>(GetRandomValue(-100, 100))};
};
offset = Vector3Normalize(offset) * REST_LENGTH; offset = Vector3Normalize(offset) * REST_LENGTH;
// If the offset moves the mass closer to the current center of mass, flip it // If the offset moves the mass closer to the current center of mass, flip it
if (!tree.nodes.empty()) { if (!tree.nodes.empty()) {
const Vector3 mass_center_direction = Vector3Subtract(mass_a.position, tree.nodes.at(0).mass_center); const Vector3 mass_center_direction =
Vector3Subtract(positions[a], tree.nodes[0].mass_center);
const float mass_center_distance = Vector3Length(mass_center_direction); const float mass_center_distance = Vector3Length(mass_center_direction);
if (mass_center_distance > 0 && Vector3DotProduct(offset, mass_center_direction) < 0.0f) { if (mass_center_distance > 0 && Vector3DotProduct(offset, mass_center_direction) < 0.0f) {
@ -102,8 +102,8 @@ auto mass_spring_system::add_spring(size_t a, size_t b) -> void
} }
} }
mass_b.position = mass_a.position + offset; positions[b] = mass_a + offset;
mass_b.previous_position = mass_b.position; previous_positions[b] = mass_b;
// infoln("Adding spring: ({}, {}, {})->({}, {}, {})", mass_a.position.x, mass_a.position.y, // infoln("Adding spring: ({}, {}, {})->({}, {}, {})", mass_a.position.x, mass_a.position.y,
// mass_a.position.z, // mass_a.position.z,
@ -114,118 +114,92 @@ auto mass_spring_system::add_spring(size_t a, size_t b) -> void
auto mass_spring_system::clear_forces() -> void auto mass_spring_system::clear_forces() -> void
{ {
#ifdef TRACY #ifdef TRACY
ZoneScoped; ZoneScoped;
#endif
for (auto& m : masses) {
m.clear_force();
}
}
auto mass_spring_system::calculate_spring_forces() -> void
{
#ifdef TRACY
ZoneScoped;
#endif
for (const auto s : springs) {
mass& a = masses.at(s.a);
mass& b = masses.at(s.b);
spring::calculate_spring_force(a, b);
}
}
#ifdef THREADPOOL
auto mass_spring_system::set_thread_name(size_t idx) -> void
{
BS::this_thread::set_os_thread_name(std::format("bh-worker-{}", idx));
}
#endif #endif
auto mass_spring_system::build_octree() -> void memset(forces.data(), 0, forces.size() * sizeof(Vector3));
}
auto mass_spring_system::calculate_spring_forces(
const std::optional<BS::thread_pool<>* const> thread_pool) -> void
{ {
#ifdef TRACY #ifdef TRACY
ZoneScoped; ZoneScoped;
#endif #endif
tree.nodes.clear(); const auto solve_spring_force = [&](const int i) { calculate_spring_force(i); };
tree.nodes.reserve(masses.size() * 2);
// Compute bounding box around all masses if (thread_pool) {
Vector3 min{FLT_MAX, FLT_MAX, FLT_MAX}; (*thread_pool)
Vector3 max{-FLT_MAX, -FLT_MAX, -FLT_MAX}; ->submit_loop(0, springs.size(), solve_spring_force, SMALL_TASK_BLOCK_SIZE)
for (const auto& m : masses) { .wait();
min.x = std::min(min.x, m.position.x); } else {
max.x = std::max(max.x, m.position.x); for (size_t i = 0; i < springs.size(); ++i) {
min.y = std::min(min.y, m.position.y); solve_spring_force(i);
max.y = std::max(max.y, m.position.y); }
min.z = std::min(min.z, m.position.z);
max.z = std::max(max.z, m.position.z);
}
// Pad the bounding box
constexpr float pad = 1.0;
min = Vector3Subtract(min, Vector3Scale(Vector3One(), pad));
max = Vector3Add(max, Vector3Scale(Vector3One(), pad));
// Make it cubic (so subdivisions are balanced)
const float max_extent = std::max({max.x - min.x, max.y - min.y, max.z - min.z});
max = Vector3Add(min, Vector3Scale(Vector3One(), max_extent));
// Root node spans the entire area
const int root = tree.create_empty_leaf(min, max);
for (size_t i = 0; i < masses.size(); ++i) {
tree.insert(root, static_cast<int>(i), masses[i].position, MASS, 0);
} }
} }
auto mass_spring_system::calculate_repulsion_forces() -> void auto mass_spring_system::calculate_repulsion_forces(
const std::optional<BS::thread_pool<>* const> thread_pool) -> void
{ {
#ifdef TRACY #ifdef TRACY
ZoneScoped; ZoneScoped;
#endif #endif
build_octree(); const auto solve_octree = [&](const int i)
auto solve_octree = [&](const int i)
{ {
const Vector3 force = tree.calculate_force(0, masses[i].position); const Vector3 force = tree.calculate_force(0, positions[i]);
masses[i].force = Vector3Add(masses[i].force, force); forces[i] += force;
}; };
// Calculate forces using Barnes-Hut // Calculate forces using Barnes-Hut
#ifdef THREADPOOL if (thread_pool) {
const BS::multi_future<void> loop_future = threads.submit_loop(0, masses.size(), solve_octree, 256); (*thread_pool)
loop_future.wait(); ->submit_loop(0, positions.size(), solve_octree, LARGE_TASK_BLOCK_SIZE)
#else .wait();
for (size_t i = 0; i < masses.size(); ++i) { } else {
solve_octree(i); for (size_t i = 0; i < positions.size(); ++i) {
solve_octree(i);
}
} }
#endif
} }
auto mass_spring_system::verlet_update(const float delta_time) -> void auto mass_spring_system::update(const float dt,
const std::optional<BS::thread_pool<>* const> thread_pool) -> void
{ {
#ifdef TRACY #ifdef TRACY
ZoneScoped; ZoneScoped;
#endif #endif
for (auto& m : masses) { const auto update = [&](const int i) { verlet_update(i, dt); };
m.verlet_update(delta_time);
if (thread_pool) {
(*thread_pool)->submit_loop(0, positions.size(), update, SMALL_TASK_BLOCK_SIZE).wait();
} else {
for (size_t i = 0; i < positions.size(); ++i) {
update(i);
}
} }
} }
auto mass_spring_system::center_masses() -> void auto mass_spring_system::center_masses(const std::optional<BS::thread_pool<>* const> thread_pool)
-> void
{ {
Vector3 mean = Vector3Zero(); Vector3 mean = Vector3Zero();
for (const auto& m : masses) { for (const Vector3& pos : positions) {
mean += m.position; mean += pos;
} }
mean /= static_cast<float>(masses.size()); mean /= static_cast<float>(positions.size());
for (auto& m : masses) { const auto center_mass = [&](const int i) { positions[i] -= mean; };
m.position -= mean;
if (thread_pool) {
(*thread_pool)->submit_loop(0, positions.size(), center_mass, SMALL_TASK_BLOCK_SIZE).wait();
} else {
for (size_t i = 0; i < positions.size(); ++i) {
center_mass(i);
}
} }
} }

View File

@ -1,13 +1,9 @@
#include "octree.hpp" #include "octree.hpp"
#include "config.hpp" #include "config.hpp"
#include "util.hpp"
#include <cfloat>
#include <raymath.h> #include <raymath.h>
#ifdef TRACY
#include <tracy/Tracy.hpp>
#endif
auto octree::node::child_count() const -> int auto octree::node::child_count() const -> int
{ {
int child_count = 0; int child_count = 0;
@ -19,22 +15,11 @@ auto octree::node::child_count() const -> int
return child_count; return child_count;
} }
auto octree::create_empty_leaf(const Vector3& box_min, const Vector3& box_max) -> int
{
node n;
n.box_min = box_min;
n.box_max = box_max;
nodes.emplace_back(n);
return static_cast<int>(nodes.size() - 1);
}
auto octree::get_octant(const int node_idx, const Vector3& pos) const -> int auto octree::get_octant(const int node_idx, const Vector3& pos) const -> int
{ {
const node& n = nodes[node_idx]; const node& n = nodes[node_idx];
auto [cx, cy, cz] = auto [cx, cy, cz] = Vector3((n.box_min.x + n.box_max.x) / 2.0f, (n.box_min.y + n.box_max.y) / 2.0f,
Vector3((n.box_min.x + n.box_max.x) / 2.0f, (n.box_min.y + n.box_max.y) / 2.0f, (n.box_min.z + n.box_max.z) / 2.0f);
(n.box_min.z + n.box_max.z) / 2.0f);
// The octant is encoded as a 3-bit integer "zyx". The node area is split // The octant is encoded as a 3-bit integer "zyx". The node area is split
// along all 3 axes, if a position is right of an axis, this bit is set to 1. // along all 3 axes, if a position is right of an axis, this bit is set to 1.
@ -54,13 +39,11 @@ auto octree::get_octant(const int node_idx, const Vector3& pos) const -> int
return octant; return octant;
} }
auto octree::get_child_bounds(const int node_idx, const int octant) const auto octree::get_child_bounds(const int node_idx, const int octant) const -> std::pair<Vector3, Vector3>
-> std::pair<Vector3, Vector3>
{ {
const node& n = nodes[node_idx]; const node& n = nodes[node_idx];
auto [cx, cy, cz] = auto [cx, cy, cz] = Vector3((n.box_min.x + n.box_max.x) / 2.0f, (n.box_min.y + n.box_max.y) / 2.0f,
Vector3((n.box_min.x + n.box_max.x) / 2.0f, (n.box_min.y + n.box_max.y) / 2.0f, (n.box_min.z + n.box_max.z) / 2.0f);
(n.box_min.z + n.box_max.z) / 2.0f);
Vector3 min = Vector3Zero(); Vector3 min = Vector3Zero();
Vector3 max = Vector3Zero(); Vector3 max = Vector3Zero();
@ -78,19 +61,27 @@ auto octree::get_child_bounds(const int node_idx, const int octant) const
return std::make_pair(min, max); return std::make_pair(min, max);
} }
auto octree::create_empty_leaf(const Vector3& box_min, const Vector3& box_max) -> int
{
node n;
n.box_min = box_min;
n.box_max = box_max;
nodes.emplace_back(n);
return static_cast<int>(nodes.size() - 1);
}
auto octree::insert(const int node_idx, const int mass_id, const Vector3& pos, const float mass, auto octree::insert(const int node_idx, const int mass_id, const Vector3& pos, const float mass,
const int depth) -> void const int depth) -> void
{ {
// infoln("Inserting position ({}, {}, {}) into octree at node {} (depth {})", pos.x, pos.y, // infoln("Inserting position ({}, {}, {}) into octree at node {} (depth {})", pos.x, pos.y,
// pos.z, node_idx, depth); // pos.z, node_idx, depth);
if (depth > MAX_DEPTH) { if (depth > MAX_DEPTH) {
errln("MAX_DEPTH! node={} box_min=({},{},{}) box_max=({},{},{}) pos=({},{},{})", node_idx, throw std::runtime_error(std::format("MAX_DEPTH! node={} box_min=({},{},{}) box_max=({},{},{}) pos=({},{},{})",
nodes[node_idx].box_min.x, nodes[node_idx].box_min.y, nodes[node_idx].box_min.z, node_idx, nodes[node_idx].box_min.x, nodes[node_idx].box_min.y,
nodes[node_idx].box_max.x, nodes[node_idx].box_max.y, nodes[node_idx].box_max.z, nodes[node_idx].box_min.z, nodes[node_idx].box_max.x,
pos.x, pos.y, pos.z); nodes[node_idx].box_max.y, nodes[node_idx].box_max.z, pos.x, pos.y,
pos.z));
// This runs from inside the physics thread so it won't exit cleanly
exit(1);
} }
// NOTE: Do not store a nodes[node_idx] reference as the nodes vector might reallocate during // NOTE: Do not store a nodes[node_idx] reference as the nodes vector might reallocate during
@ -152,15 +143,50 @@ auto octree::insert(const int node_idx, const int mass_id, const Vector3& pos, c
// Update the center of mass // Update the center of mass
const float new_mass = nodes[node_idx].mass_total + mass; const float new_mass = nodes[node_idx].mass_total + mass;
nodes[node_idx].mass_center.x = nodes[node_idx].mass_center.x = (nodes[node_idx].mass_center.x * nodes[node_idx].mass_total + pos.x) / new_mass;
(nodes[node_idx].mass_center.x * nodes[node_idx].mass_total + pos.x) / new_mass; nodes[node_idx].mass_center.y = (nodes[node_idx].mass_center.y * nodes[node_idx].mass_total + pos.y) / new_mass;
nodes[node_idx].mass_center.y = nodes[node_idx].mass_center.z = (nodes[node_idx].mass_center.z * nodes[node_idx].mass_total + pos.z) / new_mass;
(nodes[node_idx].mass_center.y * nodes[node_idx].mass_total + pos.y) / new_mass;
nodes[node_idx].mass_center.z =
(nodes[node_idx].mass_center.z * nodes[node_idx].mass_total + pos.z) / new_mass;
nodes[node_idx].mass_total = new_mass; nodes[node_idx].mass_total = new_mass;
} }
auto octree::build_octree(octree& t, const std::vector<Vector3>& positions) -> void
{
#ifdef TRACY
ZoneScoped;
#endif
t.nodes.clear();
t.nodes.reserve(positions.size() * 2);
// Compute bounding box around all masses
Vector3 min{FLT_MAX, FLT_MAX, FLT_MAX};
Vector3 max{-FLT_MAX, -FLT_MAX, -FLT_MAX};
for (const auto& [x, y, z] : positions) {
min.x = std::min(min.x, x);
max.x = std::max(max.x, x);
min.y = std::min(min.y, y);
max.y = std::max(max.y, y);
min.z = std::min(min.z, z);
max.z = std::max(max.z, z);
}
// Pad the bounding box
constexpr float pad = 1.0;
min = Vector3Subtract(min, Vector3Scale(Vector3One(), pad));
max = Vector3Add(max, Vector3Scale(Vector3One(), pad));
// Make it cubic (so subdivisions are balanced)
const float max_extent = std::max({max.x - min.x, max.y - min.y, max.z - min.z});
max = Vector3Add(min, Vector3Scale(Vector3One(), max_extent));
// Root node spans the entire area
const int root = t.create_empty_leaf(min, max);
for (size_t i = 0; i < positions.size(); ++i) {
t.insert(root, static_cast<int>(i), positions[i], MASS, 0);
}
}
auto octree::calculate_force(const int node_idx, const Vector3& pos) const -> Vector3 auto octree::calculate_force(const int node_idx, const Vector3& pos) const -> Vector3
{ {
if (node_idx < 0) { if (node_idx < 0) {
@ -198,4 +224,4 @@ auto octree::calculate_force(const int node_idx, const Vector3& pos) const -> Ve
} }
return force; return force;
} }

View File

@ -4,10 +4,6 @@
#include <raylib.h> #include <raylib.h>
#include <raymath.h> #include <raymath.h>
#ifdef TRACY
#include <tracy/Tracy.hpp>
#endif
auto orbit_camera::rotate(const Vector2 last_mouse, const Vector2 mouse) -> void auto orbit_camera::rotate(const Vector2 last_mouse, const Vector2 mouse) -> void
{ {
const auto [dx, dy] = Vector2Subtract(mouse, last_mouse); const auto [dx, dy] = Vector2Subtract(mouse, last_mouse);
@ -73,4 +69,4 @@ auto orbit_camera::update(const Vector3& current_target, const Vector3& mass_cen
camera.target = target; camera.target = target;
camera.fovy = fov; camera.fovy = fov;
camera.projection = projection; camera.projection = projection;
} }

File diff suppressed because it is too large Load Diff

View File

@ -5,33 +5,29 @@
#include <raymath.h> #include <raymath.h>
#include <rlgl.h> #include <rlgl.h>
#ifdef TRACY
#include <tracy/Tracy.hpp>
#endif
auto renderer::update_texture_sizes() -> void auto renderer::update_texture_sizes() -> void
{ {
if (!IsWindowResized()) { if (!IsWindowResized()) {
return; return;
} }
UnloadRenderTexture(render_target); UnloadRenderTexture(graph_target);
UnloadRenderTexture(klotski_target); UnloadRenderTexture(klotski_target);
UnloadRenderTexture(menu_target); UnloadRenderTexture(menu_target);
const int width = GetScreenWidth() / 2; const int width = GetScreenWidth() / 2;
const int height = GetScreenHeight() - MENU_HEIGHT; const int height = GetScreenHeight() - MENU_HEIGHT;
render_target = LoadRenderTexture(width, height); graph_target = LoadRenderTexture(width, height);
klotski_target = LoadRenderTexture(width, height); klotski_target = LoadRenderTexture(width, height);
menu_target = LoadRenderTexture(width * 2, MENU_HEIGHT); menu_target = LoadRenderTexture(width * 2, MENU_HEIGHT);
} }
auto renderer::draw_mass_springs(const std::vector<Vector3>& masses) -> void auto renderer::draw_mass_springs(const std::vector<Vector3>& masses) -> void
{ {
#ifdef TRACY #ifdef TRACY
ZoneScoped; ZoneScoped;
#endif #endif
if (masses.size() != state.get_state_count()) { if (masses.size() != state.get_state_count()) {
// Because the physics run in a different thread, it might need time to catch up // Because the physics run in a different thread, it might need time to catch up
@ -40,16 +36,16 @@ auto renderer::draw_mass_springs(const std::vector<Vector3>& masses) -> void
// Prepare connection batching // Prepare connection batching
{ {
#ifdef TRACY #ifdef TRACY
ZoneNamedN(prepare_masses, "PrepareConnectionsBatching", true); ZoneNamedN(prepare_connections, "PrepareConnectionsBatching", true);
#endif #endif
connections.clear(); connections.clear();
connections.reserve(state.get_target_count()); connections.reserve(state.get_target_count());
if (input.connect_solutions) { if (input.connect_solutions) {
for (const size_t& _state : state.get_winning_indices()) { for (const size_t& _state : state.get_winning_indices()) {
const Vector3& current_mass = masses.at(state.get_current_index()); const Vector3& current_mass = masses[state.get_current_index()];
const Vector3& winning_mass = masses.at(_state); const Vector3& winning_mass = masses[_state];
connections.emplace_back(current_mass, winning_mass); connections.emplace_back(current_mass, winning_mass);
DrawLine3D(current_mass, winning_mass, Fade(TARGET_BLOCK_COLOR, 0.5)); DrawLine3D(current_mass, winning_mass, Fade(TARGET_BLOCK_COLOR, 0.5));
} }
@ -58,9 +54,9 @@ auto renderer::draw_mass_springs(const std::vector<Vector3>& masses) -> void
// Prepare cube instancing // Prepare cube instancing
{ {
#ifdef TRACY #ifdef TRACY
ZoneNamedN(prepare_masses, "PrepareMassInstancing", true); ZoneNamedN(prepare_masses, "PrepareMassInstancing", true);
#endif #endif
if (masses.size() < DRAW_VERTICES_LIMIT) { if (masses.size() < DRAW_VERTICES_LIMIT) {
// Don't have to reserve, capacity is already set to DRAW_VERTICES_LIMIT in constructor // Don't have to reserve, capacity is already set to DRAW_VERTICES_LIMIT in constructor
@ -73,12 +69,10 @@ auto renderer::draw_mass_springs(const std::vector<Vector3>& masses) -> void
// Normal vertex // Normal vertex
Color c = VERTEX_COLOR; Color c = VERTEX_COLOR;
if ((input.mark_solutions || input.mark_path) && if ((input.mark_solutions || input.mark_path) && state.get_winning_indices().contains(mass)) {
state.get_winning_indices().contains(mass)) {
// Winning vertex // Winning vertex
c = VERTEX_TARGET_COLOR; c = VERTEX_TARGET_COLOR;
} else if ((input.mark_solutions || input.mark_path) && } else if ((input.mark_solutions || input.mark_path) && state.get_path_indices().contains(mass)) {
state.get_path_indices().contains(mass)) {
// Path vertex // Path vertex
c = VERTEX_PATH_COLOR; c = VERTEX_PATH_COLOR;
} else if (mass == state.get_starting_index()) { } else if (mass == state.get_starting_index()) {
@ -98,21 +92,21 @@ auto renderer::draw_mass_springs(const std::vector<Vector3>& masses) -> void
rlUpdateVertexBuffer(color_vbo_id, colors.data(), colors.size() * sizeof(Color), 0); rlUpdateVertexBuffer(color_vbo_id, colors.data(), colors.size() * sizeof(Color), 0);
} }
BeginTextureMode(render_target); BeginTextureMode(graph_target);
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
BeginMode3D(camera.camera); BeginMode3D(camera.camera);
// Draw springs (batched) // Draw springs (batched)
{ {
#ifdef TRACY #ifdef TRACY
ZoneNamedN(draw_springs, "DrawSprings", true); ZoneNamedN(draw_springs, "DrawSprings", true);
#endif #endif
rlBegin(RL_LINES); rlBegin(RL_LINES);
for (const auto& [from, to] : state.get_links()) { for (const auto& [from, to] : state.get_links()) {
if (masses.size() > from && masses.size() > to) { if (masses.size() > from && masses.size() > to) {
const auto& [ax, ay, az] = masses.at(from); const auto& [ax, ay, az] = masses[from];
const auto& [bx, by, bz] = masses.at(to); const auto& [bx, by, bz] = masses[to];
rlColor4ub(EDGE_COLOR.r, EDGE_COLOR.g, EDGE_COLOR.b, EDGE_COLOR.a); rlColor4ub(EDGE_COLOR.r, EDGE_COLOR.g, EDGE_COLOR.b, EDGE_COLOR.a);
rlVertex3f(ax, ay, az); rlVertex3f(ax, ay, az);
rlVertex3f(bx, by, bz); rlVertex3f(bx, by, bz);
@ -123,17 +117,16 @@ auto renderer::draw_mass_springs(const std::vector<Vector3>& masses) -> void
// Draw masses (instanced) // Draw masses (instanced)
{ {
#ifdef TRACY #ifdef TRACY
ZoneNamedN(draw_masses, "DrawMasses", true); ZoneNamedN(draw_masses, "DrawMasses", true);
#endif #endif
if (masses.size() < DRAW_VERTICES_LIMIT) { if (masses.size() < DRAW_VERTICES_LIMIT) {
// NOTE: I don't know if drawing all this inside a shader would make it // NOTE: I don't know if drawing all this inside a shader would make it
// much faster... The amount of data sent to the GPU would be // much faster... The amount of data sent to the GPU would be
// reduced (just positions instead of matrices), but is this // reduced (just positions instead of matrices), but is this
// noticable for < 100000 cubes? // noticable for < 100000 cubes?
DrawMeshInstanced(cube_instance, vertex_mat, transforms.data(), DrawMeshInstanced(cube_instance, vertex_mat, transforms.data(), masses.size()); // NOLINT(*-narrowing-conversions)
masses.size()); // NOLINT(*-narrowing-conversions)
} }
} }
@ -152,9 +145,8 @@ auto renderer::draw_mass_springs(const std::vector<Vector3>& masses) -> void
// Mark current state // Mark current state
const size_t current_index = state.get_current_index(); const size_t current_index = state.get_current_index();
if (masses.size() > current_index) { if (masses.size() > current_index) {
const Vector3& current_mass = masses.at(current_index); const Vector3& current_mass = masses[current_index];
DrawCube(current_mass, VERTEX_SIZE * 2, VERTEX_SIZE * 2, VERTEX_SIZE * 2, DrawCube(current_mass, VERTEX_SIZE * 2, VERTEX_SIZE * 2, VERTEX_SIZE * 2, VERTEX_CURRENT_COLOR);
VERTEX_CURRENT_COLOR);
} }
EndMode3D(); EndMode3D();
@ -163,9 +155,9 @@ auto renderer::draw_mass_springs(const std::vector<Vector3>& masses) -> void
auto renderer::draw_klotski() const -> void auto renderer::draw_klotski() const -> void
{ {
#ifdef TRACY #ifdef TRACY
ZoneScoped; ZoneScoped;
#endif #endif
BeginTextureMode(klotski_target); BeginTextureMode(klotski_target);
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
@ -177,9 +169,9 @@ auto renderer::draw_klotski() const -> void
auto renderer::draw_menu() const -> void auto renderer::draw_menu() const -> void
{ {
#ifdef TRACY #ifdef TRACY
ZoneScoped; ZoneScoped;
#endif #endif
BeginTextureMode(menu_target); BeginTextureMode(menu_target);
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
@ -194,32 +186,28 @@ auto renderer::draw_textures(const int fps, const int ups, const size_t mass_cou
{ {
BeginDrawing(); BeginDrawing();
DrawTextureRec(menu_target.texture, DrawTextureRec(menu_target.texture, Rectangle(0, 0, menu_target.texture.width, -menu_target.texture.height),
Rectangle(0, 0, menu_target.texture.width, -menu_target.texture.height),
Vector2(0, 0), WHITE); Vector2(0, 0), WHITE);
DrawTextureRec(klotski_target.texture, DrawTextureRec(klotski_target.texture,
Rectangle(0, 0, klotski_target.texture.width, -klotski_target.texture.height), Rectangle(0, 0, klotski_target.texture.width, -klotski_target.texture.height),
Vector2(0, MENU_HEIGHT), WHITE); Vector2(0, MENU_HEIGHT), WHITE);
DrawTextureRec(render_target.texture, DrawTextureRec(graph_target.texture, Rectangle(0, 0, graph_target.texture.width, -graph_target.texture.height),
Rectangle(0, 0, render_target.texture.width, -render_target.texture.height),
Vector2(GetScreenWidth() / 2.0f, MENU_HEIGHT), WHITE); Vector2(GetScreenWidth() / 2.0f, MENU_HEIGHT), WHITE);
// Draw borders // Draw borders
DrawRectangleLinesEx(Rectangle(0, 0, GetScreenWidth(), MENU_HEIGHT), 1.0f, BLACK); DrawRectangleLinesEx(Rectangle(0, 0, GetScreenWidth(), MENU_HEIGHT), 1.0f, BLACK);
DrawRectangleLinesEx( DrawRectangleLinesEx(Rectangle(0, MENU_HEIGHT, GetScreenWidth() / 2.0f, GetScreenHeight() - MENU_HEIGHT), 1.0f,
Rectangle(0, MENU_HEIGHT, GetScreenWidth() / 2.0f, GetScreenHeight() - MENU_HEIGHT), 1.0f, BLACK);
BLACK);
DrawRectangleLinesEx(Rectangle(GetScreenWidth() / 2.0f, MENU_HEIGHT, GetScreenWidth() / 2.0f, DrawRectangleLinesEx(Rectangle(GetScreenWidth() / 2.0f, MENU_HEIGHT, GetScreenWidth() / 2.0f,
GetScreenHeight() - MENU_HEIGHT), GetScreenHeight() - MENU_HEIGHT), 1.0f, BLACK);
1.0f, BLACK);
gui.draw(fps, ups, mass_count, spring_count); gui.draw(fps, ups, mass_count, spring_count);
EndDrawing(); EndDrawing();
} }
auto renderer::render(const std::vector<Vector3>& masses, const int fps, const int ups, auto renderer::render(const std::vector<Vector3>& masses, const int fps, const int ups, const size_t mass_count,
const size_t mass_count, const size_t spring_count) -> void const size_t spring_count) -> void
{ {
update_texture_sizes(); update_texture_sizes();
@ -227,4 +215,4 @@ auto renderer::render(const std::vector<Vector3>& masses, const int fps, const i
draw_klotski(); draw_klotski();
draw_menu(); draw_menu();
draw_textures(fps, ups, mass_count, spring_count); draw_textures(fps, ups, mass_count, spring_count);
} }

View File

@ -2,17 +2,10 @@
#include "graph_distances.hpp" #include "graph_distances.hpp"
#include "util.hpp" #include "util.hpp"
#include <fstream>
#include <ios>
#ifdef TRACY
#include <tracy/Tracy.hpp>
#endif
auto state_manager::synced_try_insert_state(const puzzle& state) -> size_t auto state_manager::synced_try_insert_state(const puzzle& state) -> size_t
{ {
if (state_indices.contains(state)) { if (state_indices.contains(state)) {
return state_indices.at(state); return state_indices[state];
} }
const size_t index = state_pool.size(); const size_t index = state_pool.size();
@ -77,77 +70,27 @@ auto state_manager::synced_clear_statespace() -> void
physics.clear_cmd(); physics.clear_cmd();
} }
auto state_manager::parse_preset_file(const std::string& _preset_file) -> bool auto state_manager::save_current_to_preset_file(const std::string& preset_comment) -> void
{ {
preset_file = _preset_file; if (append_preset_file(preset_file, preset_comment, get_current_state())) {
current_preset = preset_states.size();
std::ifstream file(preset_file); reload_preset_file();
if (!file) {
infoln("Preset file \"{}\" couldn't be loaded.", preset_file);
return false;
} }
std::string line;
std::vector<std::string> comment_lines;
std::vector<std::string> preset_lines;
while (std::getline(file, line)) {
if (line.starts_with("F") || line.starts_with("R")) {
preset_lines.push_back(line);
} else if (line.starts_with("#")) {
comment_lines.push_back(line);
}
}
if (preset_lines.empty() || comment_lines.size() != preset_lines.size()) {
infoln("Preset file \"{}\" couldn't be loaded.", preset_file);
return false;
}
preset_states.clear();
for (const auto& preset : preset_lines) {
const puzzle& p = puzzle(preset);
if (const std::optional<std::string>& reason = p.try_get_invalid_reason()) {
preset_states = {puzzle(4, 5, 9, 9, false)};
infoln("Preset file \"{}\" contained invalid presets: {}", preset_file, *reason);
return false;
}
preset_states.emplace_back(p);
}
preset_comments = comment_lines;
infoln("Loaded {} presets from \"{}\".", preset_lines.size(), preset_file);
return true;
} }
auto state_manager::append_preset_file(const std::string& preset_name) -> bool auto state_manager::reload_preset_file() -> void
{ {
infoln(R"(Saving preset "{}" to "{}")", preset_name, preset_file); const auto [presets, comments] = parse_preset_file(preset_file);
if (!presets.empty()) {
if (get_current_state().try_get_invalid_reason()) { preset_states = presets;
return false; preset_comments = comments;
} }
load_preset(current_preset);
std::ofstream file(preset_file, std::ios_base::app | std::ios_base::out);
if (!file) {
infoln("Preset file \"{}\" couldn't be loaded.", preset_file);
return false;
}
file << "\n# " << preset_name << "\n" << get_current_state().state << std::flush;
infoln("Refreshing presets...");
if (parse_preset_file(preset_file)) {
load_preset(preset_states.size() - 1);
}
return true;
} }
auto state_manager::load_preset(const size_t preset) -> void auto state_manager::load_preset(const size_t preset) -> void
{ {
clear_graph_and_add_current(preset_states.at(preset)); clear_graph_and_add_current(preset_states[preset]);
current_preset = preset; current_preset = preset;
edited = false; edited = false;
} }
@ -189,7 +132,7 @@ auto state_manager::update_current_state(const puzzle& p) -> void
move_history.emplace_back(previous_state_index); move_history.emplace_back(previous_state_index);
} }
if (p.won()) { if (p.goal_reached()) {
winning_indices.insert(current_state_index); winning_indices.insert(current_state_index);
} }
@ -269,8 +212,8 @@ auto state_manager::goto_most_distant_state() -> void
int max_distance = 0; int max_distance = 0;
size_t max_distance_index = 0; size_t max_distance_index = 0;
for (size_t i = 0; i < node_target_distances.distances.size(); ++i) { for (size_t i = 0; i < node_target_distances.distances.size(); ++i) {
if (node_target_distances.distances.at(i) > max_distance) { if (node_target_distances.distances[i] > max_distance) {
max_distance = node_target_distances.distances.at(i); max_distance = node_target_distances.distances[i];
max_distance_index = i; max_distance_index = i;
} }
} }
@ -284,7 +227,7 @@ auto state_manager::goto_closest_target_state() -> void
return; return;
} }
update_current_state(get_state(node_target_distances.nearest_targets.at(current_state_index))); update_current_state(get_state(node_target_distances.nearest_targets[current_state_index]));
} }
auto state_manager::populate_graph() -> void auto state_manager::populate_graph() -> void
@ -301,12 +244,19 @@ auto state_manager::populate_graph() -> void
synced_clear_statespace(); synced_clear_statespace();
// Explore the entire statespace starting from the current state // Explore the entire statespace starting from the current state
const std::chrono::high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now();
const auto& [states, _links] = s.explore_state_space(); const auto& [states, _links] = s.explore_state_space();
synced_insert_statespace(states, _links); synced_insert_statespace(states, _links);
current_state_index = state_indices.at(p); const std::chrono::high_resolution_clock::time_point end = std::chrono::high_resolution_clock::now();
infoln("Explored puzzle. Took {}ms.", std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count());
infoln("State space has size {} with {} transitions.", state_pool.size(), links.size());
current_state_index = state_indices[p];
previous_state_index = current_state_index; previous_state_index = current_state_index;
starting_state_index = state_indices.at(s); starting_state_index = state_indices[s];
// Search for cool stuff // Search for cool stuff
populate_winning_indices(); populate_winning_indices();
@ -340,7 +290,7 @@ auto state_manager::populate_winning_indices() -> void
{ {
winning_indices.clear(); winning_indices.clear();
for (const auto& [state, index] : state_indices) { for (const auto& [state, index] : state_indices) {
if (state.won()) { if (state.goal_reached()) {
winning_indices.insert(index); winning_indices.insert(index);
} }
} }
@ -391,7 +341,7 @@ auto state_manager::get_starting_index() const -> size_t
auto state_manager::get_state(const size_t index) const -> const puzzle& auto state_manager::get_state(const size_t index) const -> const puzzle&
{ {
return state_pool.at(index); return state_pool[index];
} }
auto state_manager::get_current_state() const -> const puzzle& auto state_manager::get_current_state() const -> const puzzle&
@ -429,12 +379,12 @@ auto state_manager::get_links() const -> const std::vector<std::pair<size_t, siz
return links; return links;
} }
auto state_manager::get_winning_indices() const -> const std::unordered_set<size_t>& auto state_manager::get_winning_indices() const -> const boost::unordered_flat_set<size_t>&
{ {
return winning_indices; return winning_indices;
} }
auto state_manager::get_visit_counts() const -> const std::unordered_map<size_t, int>& auto state_manager::get_visit_counts() const -> const boost::unordered_flat_map<size_t, int>&
{ {
return visit_counts; return visit_counts;
} }
@ -444,7 +394,7 @@ auto state_manager::get_winning_path() const -> const std::vector<size_t>&
return winning_path; return winning_path;
} }
auto state_manager::get_path_indices() const -> const std::unordered_set<size_t>& auto state_manager::get_path_indices() const -> const boost::unordered_flat_set<size_t>&
{ {
return path_indices; return path_indices;
} }
@ -466,7 +416,7 @@ auto state_manager::get_preset_count() const -> size_t
auto state_manager::get_current_preset_comment() const -> const std::string& auto state_manager::get_current_preset_comment() const -> const std::string&
{ {
return preset_comments.at(current_preset); return preset_comments[current_preset];
} }
auto state_manager::has_history() const -> bool auto state_manager::has_history() const -> bool

View File

@ -1,6 +1,7 @@
#include "threaded_physics.hpp" #include "threaded_physics.hpp"
#include "config.hpp" #include "config.hpp"
#include "mass_spring_system.hpp" #include "mass_spring_system.hpp"
#include "util.hpp"
#include <chrono> #include <chrono>
#include <raylib.h> #include <raylib.h>
@ -8,20 +9,30 @@
#include <utility> #include <utility>
#include <vector> #include <vector>
#ifdef TRACY #ifdef ASYNC_OCTREE
#include <tracy/Tracy.hpp> auto threaded_physics::set_octree_pool_thread_name(size_t idx) -> void
{
BS::this_thread::set_os_thread_name(std::format("octree-{}", idx));
// traceln("Using thread \"{}\"", BS::this_thread::get_os_thread_name().value_or("INVALID NAME"));
}
#endif #endif
auto threaded_physics::physics_thread(physics_state& state) -> void auto threaded_physics::physics_thread(physics_state& state, const std::optional<BS::thread_pool<>* const> thread_pool) -> void
{ {
#ifdef THREADPOOL
BS::this_thread::set_os_thread_name("physics");
#endif
mass_spring_system mass_springs; mass_spring_system mass_springs;
#ifdef ASYNC_OCTREE
BS::this_thread::set_os_thread_name("physics");
BS::thread_pool<> octree_thread(1, set_octree_pool_thread_name);
std::future<void> octree_future;
octree tree_buffer;
size_t last_mass_count = 0;
infoln("Using asynchronous octree builder.");
#endif
const auto visitor = overloads{ const auto visitor = overloads{
[&](const struct add_mass& am) [&](const struct add_mass&)
{ {
mass_springs.add_mass(); mass_springs.add_mass();
}, },
@ -29,7 +40,7 @@ auto threaded_physics::physics_thread(physics_state& state) -> void
{ {
mass_springs.add_spring(as.a, as.b); mass_springs.add_spring(as.a, as.b);
}, },
[&](const struct clear_graph& cg) [&](const struct clear_graph&)
{ {
mass_springs.clear(); mass_springs.clear();
}, },
@ -66,26 +77,58 @@ auto threaded_physics::physics_thread(physics_state& state) -> void
} }
} }
if (mass_springs.masses.empty()) { if (mass_springs.positions.empty()) {
std::this_thread::sleep_for(std::chrono::milliseconds(1)); std::this_thread::sleep_for(std::chrono::milliseconds(1));
continue; continue;
} }
// Physics update // Physics update
if (physics_accumulator.count() > TIMESTEP) { if (physics_accumulator.count() > TIMESTEP) {
#ifdef ASYNC_OCTREE
// Snapshot the positions so mass_springs is not mutating the vector while the octree is building
std::vector<Vector3> positions = mass_springs.positions;
// Start building the octree for the next physics update.
// Move the snapshot into the closure so it doesn't get captured by reference (don't use [&])
octree_future = octree_thread.submit_task([&tree_buffer, positions = std::move(positions)]()
{
octree::build_octree(tree_buffer, positions);
});
// Rebuild the tree synchronously if we changed the number of masses to not use
// an empty tree from the last frame in the frame where the graph was generated
if (last_mass_count != mass_springs.positions.size()) {
traceln("Rebuilding octree synchronously because graph size changed");
octree::build_octree(mass_springs.tree, mass_springs.positions);
last_mass_count = mass_springs.positions.size();
}
#else
octree::build_octree(mass_springs.tree, mass_springs.positions);
#endif
mass_springs.clear_forces(); mass_springs.clear_forces();
mass_springs.calculate_spring_forces(); mass_springs.calculate_spring_forces(thread_pool);
mass_springs.calculate_repulsion_forces(); mass_springs.calculate_repulsion_forces(thread_pool);
mass_springs.verlet_update(TIMESTEP * SIM_SPEED); mass_springs.update(TIMESTEP * SIM_SPEED, thread_pool);
// This is only helpful if we're drawing a grid at (0, 0, 0). Otherwise, it's just // This is only helpful if we're drawing a grid at (0, 0, 0). Otherwise, it's just
// expensive and yields no benefit since we can lock the camera to the center of mass // expensive and yields no benefit since we can lock the camera to the center of mass
// cheaply. mass_springs.center_masses(); // cheaply.
// mass_springs.center_masses(thread_pool);
++loop_iterations; ++loop_iterations;
physics_accumulator -= std::chrono::duration<double>(TIMESTEP); physics_accumulator -= std::chrono::duration<double>(TIMESTEP);
} }
#ifdef ASYNC_OCTREE
// Wait for the octree to be built
if (octree_future.valid()) {
octree_future.wait();
octree_future = std::future<void>{};
std::swap(mass_springs.tree, tree_buffer);
}
#endif
// Publish the positions for the renderer (copy) // Publish the positions for the renderer (copy)
#ifdef TRACY #ifdef TRACY
FrameMarkStart("PhysicsThreadProduceLock"); FrameMarkStart("PhysicsThreadProduceLock");
@ -114,16 +157,16 @@ auto threaded_physics::physics_thread(physics_state& state) -> void
if (mass_springs.tree.nodes.empty()) { if (mass_springs.tree.nodes.empty()) {
state.mass_center = Vector3Zero(); state.mass_center = Vector3Zero();
} else { } else {
state.mass_center = mass_springs.tree.nodes.at(0).mass_center; state.mass_center = mass_springs.tree.nodes[0].mass_center;
} }
state.masses.clear(); state.masses.clear();
state.masses.reserve(mass_springs.masses.size()); state.masses.reserve(mass_springs.positions.size());
for (const auto& mass : mass_springs.masses) { for (const Vector3& pos : mass_springs.positions) {
state.masses.emplace_back(mass.position); state.masses.emplace_back(pos);
} }
state.mass_count = mass_springs.masses.size(); state.mass_count = mass_springs.positions.size();
state.spring_count = mass_springs.springs.size(); state.spring_count = mass_springs.springs.size();
state.data_ready = true; state.data_ready = true;
@ -131,14 +174,25 @@ auto threaded_physics::physics_thread(physics_state& state) -> void
} }
// Notify the rendering thread that new data is available // Notify the rendering thread that new data is available
state.data_ready_cnd.notify_all(); state.data_ready_cnd.notify_all();
#ifdef TRACY
FrameMarkEnd("PhysicsThreadProduceLock");
FrameMarkEnd("PhysicsThread"); #ifdef TRACY
FrameMarkEnd("PhysicsThreadProduceLock"); FrameMarkEnd("PhysicsThread");
#endif #endif
} }
} }
auto threaded_physics::clear_cmd() -> void
{
{
#ifdef TRACY
std::lock_guard<LockableBase(std::mutex)> lock(state.command_mtx);
#else
std::lock_guard<std::mutex> lock(state.command_mtx);
#endif
state.pending_commands.emplace(clear_graph{});
}
}
auto threaded_physics::add_mass_cmd() -> void auto threaded_physics::add_mass_cmd() -> void
{ {
{ {
@ -163,18 +217,6 @@ auto threaded_physics::add_spring_cmd(const size_t a, const size_t b) -> void
} }
} }
auto threaded_physics::clear_cmd() -> void
{
{
#ifdef TRACY
std::lock_guard<LockableBase(std::mutex)> lock(state.command_mtx);
#else
std::lock_guard<std::mutex> lock(state.command_mtx);
#endif
state.pending_commands.emplace(clear_graph{});
}
}
auto threaded_physics::add_mass_springs_cmd(const size_t num_masses, auto threaded_physics::add_mass_springs_cmd(const size_t num_masses,
const std::vector<std::pair<size_t, size_t>>& springs) -> void const std::vector<std::pair<size_t, size_t>>& springs) -> void
{ {

View File

@ -7,13 +7,8 @@
#define RAYGUI_IMPLEMENTATION #define RAYGUI_IMPLEMENTATION
#include <raygui.h> #include <raygui.h>
#ifdef TRACY auto user_interface::grid::update_bounds(const int _x, const int _y, const int _width, const int _height,
#include <tracy/Tracy.hpp> const int _columns, const int _rows) -> void
#endif
auto user_interface::grid::update_bounds(const int _x, const int _y, const int _width,
const int _height, const int _columns, const int _rows)
-> void
{ {
x = _x; x = _x;
y = _y; y = _y;
@ -23,8 +18,7 @@ auto user_interface::grid::update_bounds(const int _x, const int _y, const int _
rows = _rows; rows = _rows;
} }
auto user_interface::grid::update_bounds(const int _x, const int _y, const int _width, auto user_interface::grid::update_bounds(const int _x, const int _y, const int _width, const int _height) -> void
const int _height) -> void
{ {
x = _x; x = _x;
y = _y; y = _y;
@ -48,19 +42,17 @@ auto user_interface::grid::bounds() const -> Rectangle
return bounds; return bounds;
} }
auto user_interface::grid::bounds(const int _x, const int _y, const int _width, auto user_interface::grid::bounds(const int _x, const int _y, const int _width, const int _height) const -> Rectangle
const int _height) const -> Rectangle
{ {
if (_x < 0 || _x + _width > columns || _y < 0 || _y + _height > rows) { if (_x < 0 || _x + _width > columns || _y < 0 || _y + _height > rows) {
errln("Grid bounds are outside range."); throw std::invalid_argument("Grid bounds out of range");
exit(1);
} }
const int cell_width = (width - padding) / columns; const int cell_width = (width - padding) / columns;
const int cell_height = (height - padding) / rows; const int cell_height = (height - padding) / rows;
return Rectangle(x + _x * cell_width + padding, y + _y * cell_height + padding, return Rectangle(x + _x * cell_width + padding, y + _y * cell_height + padding, _width * cell_width - padding,
_width * cell_width - padding, _height * cell_height - padding); _height * cell_height - padding);
} }
auto user_interface::grid::square_bounds() const -> Rectangle auto user_interface::grid::square_bounds() const -> Rectangle
@ -80,8 +72,7 @@ auto user_interface::grid::square_bounds(const int _x, const int _y, const int _
// filled // filled
if (_x < 0 || _x + _width > columns || _y < 0 || _y + _height > rows) { if (_x < 0 || _x + _width > columns || _y < 0 || _y + _height > rows) {
errln("Grid bounds are outside range."); throw std::invalid_argument("Grid bounds out of range");
exit(1);
} }
const int available_width = width - padding * (columns + 1); const int available_width = width - padding * (columns + 1);
@ -93,10 +84,8 @@ auto user_interface::grid::square_bounds(const int _x, const int _y, const int _
const int x_offset = (width - grid_width) / 2; const int x_offset = (width - grid_width) / 2;
const int y_offset = (height - grid_height) / 2; const int y_offset = (height - grid_height) / 2;
return Rectangle(x_offset + _x * (cell_size + padding) + padding, return Rectangle(x_offset + _x * (cell_size + padding) + padding, y_offset + _y * (cell_size + padding) + padding,
y_offset + _y * (cell_size + padding) + padding, _width * cell_size + padding * (_width - 1), _height * cell_size + padding * (_height - 1));
_width * cell_size + padding * (_width - 1),
_height * cell_size + padding * (_height - 1));
} }
auto user_interface::init() -> void auto user_interface::init() -> void
@ -155,19 +144,19 @@ auto user_interface::get_default_style() -> default_style
{ {
// Could've iterated over the values, but then it wouldn't be as nice to // Could've iterated over the values, but then it wouldn't be as nice to
// access... // access...
return {{GuiGetStyle(DEFAULT, BORDER_COLOR_NORMAL), GuiGetStyle(DEFAULT, BASE_COLOR_NORMAL), return {
GuiGetStyle(DEFAULT, TEXT_COLOR_NORMAL), GuiGetStyle(DEFAULT, BORDER_COLOR_FOCUSED), {
GuiGetStyle(DEFAULT, BASE_COLOR_FOCUSED), GuiGetStyle(DEFAULT, TEXT_COLOR_FOCUSED), GuiGetStyle(DEFAULT, BORDER_COLOR_NORMAL), GuiGetStyle(DEFAULT, BASE_COLOR_NORMAL),
GuiGetStyle(DEFAULT, BORDER_COLOR_PRESSED), GuiGetStyle(DEFAULT, BASE_COLOR_PRESSED), GuiGetStyle(DEFAULT, TEXT_COLOR_NORMAL), GuiGetStyle(DEFAULT, BORDER_COLOR_FOCUSED),
GuiGetStyle(DEFAULT, TEXT_COLOR_PRESSED), GuiGetStyle(DEFAULT, BORDER_COLOR_DISABLED), GuiGetStyle(DEFAULT, BASE_COLOR_FOCUSED), GuiGetStyle(DEFAULT, TEXT_COLOR_FOCUSED),
GuiGetStyle(DEFAULT, BASE_COLOR_DISABLED), GuiGetStyle(DEFAULT, TEXT_COLOR_DISABLED)}, GuiGetStyle(DEFAULT, BORDER_COLOR_PRESSED), GuiGetStyle(DEFAULT, BASE_COLOR_PRESSED),
GuiGetStyle(DEFAULT, BACKGROUND_COLOR), GuiGetStyle(DEFAULT, TEXT_COLOR_PRESSED), GuiGetStyle(DEFAULT, BORDER_COLOR_DISABLED),
GuiGetStyle(DEFAULT, LINE_COLOR), GuiGetStyle(DEFAULT, BASE_COLOR_DISABLED), GuiGetStyle(DEFAULT, TEXT_COLOR_DISABLED)
GuiGetStyle(DEFAULT, TEXT_SIZE), },
GuiGetStyle(DEFAULT, TEXT_SPACING), GuiGetStyle(DEFAULT, BACKGROUND_COLOR), GuiGetStyle(DEFAULT, LINE_COLOR), GuiGetStyle(DEFAULT, TEXT_SIZE),
GuiGetStyle(DEFAULT, TEXT_LINE_SPACING), GuiGetStyle(DEFAULT, TEXT_SPACING), GuiGetStyle(DEFAULT, TEXT_LINE_SPACING),
GuiGetStyle(DEFAULT, TEXT_ALIGNMENT_VERTICAL), GuiGetStyle(DEFAULT, TEXT_ALIGNMENT_VERTICAL), GuiGetStyle(DEFAULT, TEXT_WRAP_MODE)
GuiGetStyle(DEFAULT, TEXT_WRAP_MODE)}; };
} }
auto user_interface::set_default_style(const default_style& style) -> void auto user_interface::set_default_style(const default_style& style) -> void
@ -201,15 +190,17 @@ auto user_interface::set_default_style(const default_style& style) -> void
auto user_interface::get_component_style(const int component) -> component_style auto user_interface::get_component_style(const int component) -> component_style
{ {
return { return {
{GuiGetStyle(component, BORDER_COLOR_NORMAL), GuiGetStyle(component, BASE_COLOR_NORMAL), {
GuiGetStyle(component, TEXT_COLOR_NORMAL), GuiGetStyle(component, BORDER_COLOR_FOCUSED), GuiGetStyle(component, BORDER_COLOR_NORMAL), GuiGetStyle(component, BASE_COLOR_NORMAL),
GuiGetStyle(component, BASE_COLOR_FOCUSED), GuiGetStyle(component, TEXT_COLOR_FOCUSED), GuiGetStyle(component, TEXT_COLOR_NORMAL), GuiGetStyle(component, BORDER_COLOR_FOCUSED),
GuiGetStyle(component, BORDER_COLOR_PRESSED), GuiGetStyle(component, BASE_COLOR_PRESSED), GuiGetStyle(component, BASE_COLOR_FOCUSED), GuiGetStyle(component, TEXT_COLOR_FOCUSED),
GuiGetStyle(component, TEXT_COLOR_PRESSED), GuiGetStyle(component, BORDER_COLOR_DISABLED), GuiGetStyle(component, BORDER_COLOR_PRESSED), GuiGetStyle(component, BASE_COLOR_PRESSED),
GuiGetStyle(component, BASE_COLOR_DISABLED), GuiGetStyle(component, TEXT_COLOR_DISABLED)}, GuiGetStyle(component, TEXT_COLOR_PRESSED), GuiGetStyle(component, BORDER_COLOR_DISABLED),
GuiGetStyle(component, BORDER_WIDTH), GuiGetStyle(component, BASE_COLOR_DISABLED), GuiGetStyle(component, TEXT_COLOR_DISABLED)
GuiGetStyle(component, TEXT_PADDING), },
GuiGetStyle(component, TEXT_ALIGNMENT)}; GuiGetStyle(component, BORDER_WIDTH), GuiGetStyle(component, TEXT_PADDING),
GuiGetStyle(component, TEXT_ALIGNMENT)
};
} }
auto user_interface::set_component_style(const int component, const component_style& style) -> void auto user_interface::set_component_style(const int component, const component_style& style) -> void
@ -238,13 +229,11 @@ auto user_interface::set_component_style(const int component, const component_st
auto user_interface::popup_bounds() -> Rectangle auto user_interface::popup_bounds() -> Rectangle
{ {
return Rectangle(static_cast<float>(GetScreenWidth()) / 2.0f - POPUP_WIDTH / 2.0f, return Rectangle(static_cast<float>(GetScreenWidth()) / 2.0f - POPUP_WIDTH / 2.0f,
static_cast<float>(GetScreenHeight()) / 2.0f - POPUP_HEIGHT / 2.0f, static_cast<float>(GetScreenHeight()) / 2.0f - POPUP_HEIGHT / 2.0f, POPUP_WIDTH, POPUP_HEIGHT);
POPUP_WIDTH, POPUP_HEIGHT);
} }
auto user_interface::draw_button(const Rectangle bounds, const std::string& label, auto user_interface::draw_button(const Rectangle bounds, const std::string& label, const Color color,
const Color color, const bool enabled, const int font_size) const const bool enabled, const int font_size) const -> int
-> int
{ {
// Save original styling // Save original styling
const default_style original_default = get_default_style(); const default_style original_default = get_default_style();
@ -275,16 +264,16 @@ auto user_interface::draw_button(const Rectangle bounds, const std::string& labe
} }
auto user_interface::draw_menu_button(const int x, const int y, const int width, const int height, auto user_interface::draw_menu_button(const int x, const int y, const int width, const int height,
const std::string& label, const Color color, const std::string& label, const Color color, const bool enabled,
const bool enabled, const int font_size) const -> int const int font_size) const -> int
{ {
const Rectangle bounds = menu_grid.bounds(x, y, width, height); const Rectangle bounds = menu_grid.bounds(x, y, width, height);
return draw_button(bounds, label, color, enabled, font_size); return draw_button(bounds, label, color, enabled, font_size);
} }
auto user_interface::draw_toggle_slider(const Rectangle bounds, const std::string& off_label, auto user_interface::draw_toggle_slider(const Rectangle bounds, const std::string& off_label,
const std::string& on_label, int* active, Color color, const std::string& on_label, int* active, Color color, bool enabled,
bool enabled, int font_size) const -> int int font_size) const -> int
{ {
// Save original styling // Save original styling
const default_style original_default = get_default_style(); const default_style original_default = get_default_style();
@ -319,18 +308,16 @@ auto user_interface::draw_toggle_slider(const Rectangle bounds, const std::strin
return pressed; return pressed;
} }
auto user_interface::draw_menu_toggle_slider(const int x, const int y, const int width, auto user_interface::draw_menu_toggle_slider(const int x, const int y, const int width, const int height,
const int height, const std::string& off_label, const std::string& off_label, const std::string& on_label, int* active,
const std::string& on_label, int* active, const Color color, const bool enabled, const int font_size) const -> int
const Color color, const bool enabled,
const int font_size) const -> int
{ {
const Rectangle bounds = menu_grid.bounds(x, y, width, height); const Rectangle bounds = menu_grid.bounds(x, y, width, height);
return draw_toggle_slider(bounds, off_label, on_label, active, color, enabled, font_size); return draw_toggle_slider(bounds, off_label, on_label, active, color, enabled, font_size);
} }
auto user_interface::draw_spinner(Rectangle bounds, const std::string& label, int* value, int min, auto user_interface::draw_spinner(Rectangle bounds, const std::string& label, int* value, int min, int max, Color color,
int max, Color color, bool enabled, int font_size) const -> int bool enabled, int font_size) const -> int
{ {
// Save original styling // Save original styling
const default_style original_default = get_default_style(); const default_style original_default = get_default_style();
@ -366,16 +353,15 @@ auto user_interface::draw_spinner(Rectangle bounds, const std::string& label, in
} }
auto user_interface::draw_menu_spinner(const int x, const int y, const int width, const int height, auto user_interface::draw_menu_spinner(const int x, const int y, const int width, const int height,
const std::string& label, int* value, const int min, const std::string& label, int* value, const int min, const int max,
const int max, const Color color, const bool enabled, const Color color, const bool enabled, const int font_size) const -> int
const int font_size) const -> int
{ {
const Rectangle bounds = menu_grid.bounds(x, y, width, height); const Rectangle bounds = menu_grid.bounds(x, y, width, height);
return draw_spinner(bounds, label, value, min, max, color, enabled, font_size); return draw_spinner(bounds, label, value, min, max, color, enabled, font_size);
} }
auto user_interface::draw_label(const Rectangle bounds, const std::string& text, const Color color, auto user_interface::draw_label(const Rectangle bounds, const std::string& text, const Color color, const bool enabled,
const bool enabled, const int font_size) const -> int const int font_size) const -> int
{ {
// Save original styling // Save original styling
const default_style original_default = get_default_style(); const default_style original_default = get_default_style();
@ -405,8 +391,8 @@ auto user_interface::draw_label(const Rectangle bounds, const std::string& text,
return pressed; return pressed;
} }
auto user_interface::draw_board_block(const int x, const int y, const int width, const int height, auto user_interface::draw_board_block(const int x, const int y, const int width, const int height, const Color color,
const Color color, const bool enabled) const -> bool const bool enabled) const -> bool
{ {
component_style s = get_component_style(BUTTON); component_style s = get_component_style(BUTTON);
apply_block_color(s, color); apply_block_color(s, color);
@ -452,18 +438,19 @@ auto user_interface::window_open() const -> bool
auto user_interface::draw_menu_header(const Color color) const -> void auto user_interface::draw_menu_header(const Color color) const -> void
{ {
int preset = static_cast<int>(state.get_current_preset()); int preset = static_cast<int>(state.get_current_preset());
draw_menu_spinner(0, 0, 1, 1, "Preset: ", &preset, -1, draw_menu_spinner(0, 0, 1, 1, "Preset: ", &preset, -1, static_cast<int>(state.get_preset_count()), color,
static_cast<int>(state.get_preset_count()), color, !input.editing); !input.editing);
if (preset > static_cast<int>(state.get_current_preset())) { if (preset > static_cast<int>(state.get_current_preset())) {
input.load_next_preset(); input.load_next_preset();
} else if (preset < static_cast<int>(state.get_current_preset())) { } else if (preset < static_cast<int>(state.get_current_preset())) {
input.load_previous_preset(); input.load_previous_preset();
} }
draw_menu_button(1, 0, 1, 1, draw_menu_button(1, 0, 1, 1, std::format("{}: {}/{} Blocks",
std::format("Puzzle: \"{}\"{}", state.get_current_preset_comment().substr(2), state.was_edited()
state.was_edited() ? " (Modified)" : ""), ? "Modified"
color); : std::format("\"{}\"", state.get_current_preset_comment().substr(2)),
state.get_current_state().block_count(), puzzle::MAX_BLOCKS), color);
int editing = input.editing; int editing = input.editing;
draw_menu_toggle_slider(2, 0, 1, 1, "Puzzle Mode (Tab)", "Edit Mode (Tab)", &editing, color); draw_menu_toggle_slider(2, 0, 1, 1, "Puzzle Mode (Tab)", "Edit Mode (Tab)", &editing, color);
@ -474,18 +461,13 @@ auto user_interface::draw_menu_header(const Color color) const -> void
auto user_interface::draw_graph_info(const Color color) const -> void auto user_interface::draw_graph_info(const Color color) const -> void
{ {
draw_menu_button(0, 1, 1, 1, draw_menu_button(0, 1, 1, 1, std::format("Found {} States ({} Winning)", state.get_state_count(),
std::format("Found {} States ({} Winning)", state.get_state_count(), state.get_target_count()), color);
state.get_target_count()),
color);
draw_menu_button(1, 1, 1, 1, std::format("Found {} Transitions", state.get_link_count()), draw_menu_button(1, 1, 1, 1, std::format("Found {} Transitions", state.get_link_count()), color);
color);
draw_menu_button(2, 1, 1, 1, draw_menu_button(2, 1, 1, 1, std::format("{} Moves to Nearest Solution",
std::format("{} Moves to Nearest Solution", state.get_path_length() > 0 ? state.get_path_length() - 1 : 0), color);
state.get_path_length() > 0 ? state.get_path_length() - 1 : 0),
color);
} }
auto user_interface::draw_graph_controls(const Color color) const -> void auto user_interface::draw_graph_controls(const Color color) const -> void
@ -506,8 +488,7 @@ auto user_interface::draw_graph_controls(const Color color) const -> void
} }
int mark_solutions = input.mark_solutions; int mark_solutions = input.mark_solutions;
draw_menu_toggle_slider(2, 2, 1, 1, "Solution Hidden (I)", "Solution Shown (I)", draw_menu_toggle_slider(2, 2, 1, 1, "Solution Hidden (I)", "Solution Shown (I)", &mark_solutions, color);
&mark_solutions, color);
if (mark_solutions != input.mark_solutions) { if (mark_solutions != input.mark_solutions) {
input.toggle_mark_solutions(); input.toggle_mark_solutions();
} }
@ -517,22 +498,20 @@ auto user_interface::draw_graph_controls(const Color color) const -> void
auto user_interface::draw_camera_controls(const Color color) const -> void auto user_interface::draw_camera_controls(const Color color) const -> void
{ {
int lock_camera = input.camera_lock; int lock_camera = input.camera_lock;
draw_menu_toggle_slider(0, 3, 1, 1, "Free Camera (L)", "Locked Camera (L)", &lock_camera, draw_menu_toggle_slider(0, 3, 1, 1, "Free Camera (L)", "Locked Camera (L)", &lock_camera, color);
color);
if (lock_camera != input.camera_lock) { if (lock_camera != input.camera_lock) {
input.toggle_camera_lock(); input.toggle_camera_lock();
} }
int lock_camera_mass_center = input.camera_mass_center_lock; int lock_camera_mass_center = input.camera_mass_center_lock;
draw_menu_toggle_slider(1, 3, 1, 1, "Current Block (U)", "Graph Center (U)", draw_menu_toggle_slider(1, 3, 1, 1, "Current Block (U)", "Graph Center (U)", &lock_camera_mass_center, color,
&lock_camera_mass_center, color, input.camera_lock); input.camera_lock);
if (lock_camera_mass_center != input.camera_mass_center_lock) { if (lock_camera_mass_center != input.camera_mass_center_lock) {
input.toggle_camera_mass_center_lock(); input.toggle_camera_mass_center_lock();
} }
int projection = camera.projection == CAMERA_ORTHOGRAPHIC; int projection = camera.projection == CAMERA_ORTHOGRAPHIC;
draw_menu_toggle_slider(2, 3, 1, 1, "Perspective (Alt)", "Orthographic (Alt)", &projection, draw_menu_toggle_slider(2, 3, 1, 1, "Perspective (Alt)", "Orthographic (Alt)", &projection, color);
color);
if (projection != (camera.projection == CAMERA_ORTHOGRAPHIC)) { if (projection != (camera.projection == CAMERA_ORTHOGRAPHIC)) {
input.toggle_camera_projection(); input.toggle_camera_projection();
} }
@ -558,10 +537,8 @@ auto user_interface::draw_puzzle_controls(const Color color) const -> void
}; };
const int visits = state.get_current_visits(); const int visits = state.get_current_visits();
draw_menu_button(0, 4, 1, 1, draw_menu_button(0, 4, 1, 1, std::format("{} Moves ({}{} Time at this State)", state.get_total_moves(), visits,
std::format("{} Moves ({}{} Time at this State)", state.get_total_moves(), nth(visits)), color);
visits, nth(visits)),
color);
if (draw_menu_button(1, 4, 1, 1, "Make Optimal Move (Space)", color, state.has_distances())) { if (draw_menu_button(1, 4, 1, 1, "Make Optimal Move (Space)", color, state.has_distances())) {
input.goto_optimal_next_state(); input.goto_optimal_next_state();
@ -600,43 +577,40 @@ auto user_interface::draw_edit_controls(const Color color) const -> void
} }
// Toggle Restricted/Free Block Movement // Toggle Restricted/Free Block Movement
int free = !current.restricted; int free = !current.get_restricted();
draw_menu_toggle_slider(1, 4, 1, 1, "Restricted (F)", "Free (F)", &free, color); draw_menu_toggle_slider(1, 4, 1, 1, "Restricted (F)", "Free (F)", &free, color);
if (free != !current.restricted) { if (free != !current.get_restricted()) {
input.toggle_restricted_movement(); input.toggle_restricted_movement();
} }
// Clear Goal // Clear Goal
if (draw_menu_button(1, 5, 1, 1, "Clear Goal (X)", color)) { if (draw_menu_button(1, 5, 1, 1, "Clear Goal (X)", color)) {}
}
// Column Count Spinner // Column Count Spinner
int columns = current.width; int columns = current.get_width();
draw_menu_spinner(2, 4, 1, 1, "Cols: ", &columns, puzzle::MIN_WIDTH, puzzle::MAX_WIDTH, color); draw_menu_spinner(2, 4, 1, 1, "Cols: ", &columns, puzzle::MIN_WIDTH, puzzle::MAX_WIDTH, color);
if (columns > current.width) { if (columns > current.get_width()) {
input.add_board_column(); input.add_board_column();
} else if (columns < current.width) { } else if (columns < current.get_width()) {
input.remove_board_column(); input.remove_board_column();
} }
// Row Count Spinner // Row Count Spinner
int rows = current.height; int rows = current.get_height();
draw_menu_spinner(2, 5, 1, 1, "Rows: ", &rows, puzzle::MIN_WIDTH, puzzle::MAX_WIDTH, color); draw_menu_spinner(2, 5, 1, 1, "Rows: ", &rows, puzzle::MIN_WIDTH, puzzle::MAX_WIDTH, color);
if (rows > current.height) { if (rows > current.get_height()) {
input.add_board_row(); input.add_board_row();
} else if (rows < current.height) { } else if (rows < current.get_height()) {
input.remove_board_row(); input.remove_board_row();
} }
} }
auto user_interface::draw_menu_footer(const Color color) -> void auto user_interface::draw_menu_footer(const Color color) -> void
{ {
draw_menu_button(0, 6, 2, 1, std::format("State: \"{}\"", state.get_current_state().state), draw_menu_button(0, 6, 2, 1, state.get_current_state().string_repr().data(), color);
color);
if (draw_menu_button(2, 6, 1, 1, "Save as Preset", color)) { if (draw_menu_button(2, 6, 1, 1, "Save as Preset", color)) {
if (const std::optional<std::string>& reason = if (const std::optional<std::string>& reason = state.get_current_state().try_get_invalid_reason()) {
state.get_current_state().try_get_invalid_reason()) {
message_title = "Can't Save Preset"; message_title = "Can't Save Preset";
message_message = std::format("Invalid Board: {}.", *reason); message_message = std::format("Invalid Board: {}.", *reason);
ok_message = true; ok_message = true;
@ -651,8 +625,7 @@ auto user_interface::get_background_color() -> Color
return GetColor(GuiGetStyle(DEFAULT, BACKGROUND_COLOR)); return GetColor(GuiGetStyle(DEFAULT, BACKGROUND_COLOR));
} }
auto user_interface::help_popup() -> void auto user_interface::help_popup() -> void {}
{}
auto user_interface::draw_save_preset_popup() -> void auto user_interface::draw_save_preset_popup() -> void
{ {
@ -661,14 +634,14 @@ auto user_interface::draw_save_preset_popup() -> void
} }
// Returns the pressed button index // Returns the pressed button index
const int button = GuiTextInputBox(popup_bounds(), "Save as Preset", "Enter Preset Name", const int button = GuiTextInputBox(popup_bounds(), "Save as Preset", "Enter Preset Name", "Ok;Cancel",
"Ok;Cancel", preset_name.data(), 255, nullptr); preset_comment.data(), 255, nullptr);
if (button == 1) { if (button == 1) {
state.append_preset_file(preset_name.data()); state.save_current_to_preset_file(preset_comment.data());
} }
if (button == 0 || button == 1 || button == 2) { if (button == 0 || button == 1 || button == 2) {
save_window = false; save_window = false;
TextCopy(preset_name.data(), "\0"); TextCopy(preset_comment.data(), "\0");
} }
} }
@ -678,8 +651,7 @@ auto user_interface::draw_ok_message_box() -> void
return; return;
} }
const int button = const int button = GuiMessageBox(popup_bounds(), message_title.data(), message_message.data(), "Ok");
GuiMessageBox(popup_bounds(), message_title.data(), message_message.data(), "Ok");
if (button == 0 || button == 1) { if (button == 0 || button == 1) {
message_title = ""; message_title = "";
message_message = ""; message_message = "";
@ -693,8 +665,7 @@ auto user_interface::draw_yes_no_message_box() -> void
return; return;
} }
const int button = const int button = GuiMessageBox(popup_bounds(), message_title.data(), message_message.data(), "Yes;No");
GuiMessageBox(popup_bounds(), message_title.data(), message_message.data(), "Yes;No");
if (button == 1) { if (button == 1) {
yes_no_handler(); yes_no_handler();
} }
@ -727,37 +698,36 @@ auto user_interface::draw_puzzle_board() -> void
{ {
const puzzle& current = state.get_current_state(); const puzzle& current = state.get_current_state();
board_grid.update_bounds(0, MENU_HEIGHT, GetScreenWidth() / 2, GetScreenHeight() - MENU_HEIGHT, board_grid.update_bounds(0, MENU_HEIGHT, GetScreenWidth() / 2, GetScreenHeight() - MENU_HEIGHT, current.get_width(),
current.width, current.height); current.get_height());
// Draw outer border // Draw outer border
const Rectangle bounds = board_grid.square_bounds(); const Rectangle bounds = board_grid.square_bounds();
DrawRectangleRec(bounds, current.won() ? BOARD_COLOR_WON : BOARD_COLOR_RESTRICTED); DrawRectangleRec(bounds, current.goal_reached() ? BOARD_COLOR_WON : BOARD_COLOR_RESTRICTED);
// Draw inner borders // Draw inner borders
DrawRectangle(bounds.x + BOARD_PADDING, bounds.y + BOARD_PADDING, DrawRectangle(bounds.x + BOARD_PADDING, bounds.y + BOARD_PADDING, bounds.width - 2 * BOARD_PADDING,
bounds.width - 2 * BOARD_PADDING, bounds.height - 2 * BOARD_PADDING, bounds.height - 2 * BOARD_PADDING,
current.restricted ? BOARD_COLOR_RESTRICTED : BOARD_COLOR_FREE); current.get_restricted() ? BOARD_COLOR_RESTRICTED : BOARD_COLOR_FREE);
// Draw target opening // Draw target opening
// TODO: Only draw single direction (in corner) if restricted (use target block principal // TODO: Only draw single direction (in corner) if restricted (use target block principal
// direction) // direction)
const std::optional<puzzle::block> target_block = current.try_get_target_block(); const std::optional<puzzle::block> target_block = current.try_get_target_block();
const int target_x = current.target_x; const int target_x = current.get_goal_x();
const int target_y = current.target_y; const int target_y = current.get_goal_y();
if (current.has_win_condition() && target_block) { if (current.get_goal() && target_block) {
auto [x, y, width, height] = board_grid.square_bounds( auto [x, y, width, height] = board_grid.square_bounds(target_x, target_y, target_block->get_width(),
target_x, target_y, target_block.value().width, target_block.value().height); target_block->get_height());
const Color opening_color = const Color opening_color = Fade(current.goal_reached() ? BOARD_COLOR_WON : BOARD_COLOR_RESTRICTED, 0.3);
Fade(current.won() ? BOARD_COLOR_WON : BOARD_COLOR_RESTRICTED, 0.3);
if (target_x == 0) { if (target_x == 0) {
// Left opening // Left opening
DrawRectangle(x - BOARD_PADDING, y, BOARD_PADDING, height, RAYWHITE); DrawRectangle(x - BOARD_PADDING, y, BOARD_PADDING, height, RAYWHITE);
DrawRectangle(x - BOARD_PADDING, y, BOARD_PADDING, height, opening_color); DrawRectangle(x - BOARD_PADDING, y, BOARD_PADDING, height, opening_color);
} }
if (target_x + target_block.value().width == current.width) { if (target_x + target_block->get_width() == current.get_width()) {
// Right opening // Right opening
DrawRectangle(x + width, y, BOARD_PADDING, height, RAYWHITE); DrawRectangle(x + width, y, BOARD_PADDING, height, RAYWHITE);
DrawRectangle(x + width, y, BOARD_PADDING, height, opening_color); DrawRectangle(x + width, y, BOARD_PADDING, height, opening_color);
@ -767,7 +737,7 @@ auto user_interface::draw_puzzle_board() -> void
DrawRectangle(x, y - BOARD_PADDING, width, BOARD_PADDING, RAYWHITE); DrawRectangle(x, y - BOARD_PADDING, width, BOARD_PADDING, RAYWHITE);
DrawRectangle(x, y - BOARD_PADDING, width, BOARD_PADDING, opening_color); DrawRectangle(x, y - BOARD_PADDING, width, BOARD_PADDING, opening_color);
} }
if (target_y + target_block.value().height == current.height) { if (target_y + target_block->get_height() == current.get_height()) {
// Bottom opening // Bottom opening
DrawRectangle(x, y + height, width, BOARD_PADDING, RAYWHITE); DrawRectangle(x, y + height, width, BOARD_PADDING, RAYWHITE);
DrawRectangle(x, y + height, width, BOARD_PADDING, opening_color); DrawRectangle(x, y + height, width, BOARD_PADDING, opening_color);
@ -794,87 +764,87 @@ auto user_interface::draw_puzzle_board() -> void
} }
// Draw blocks // Draw blocks
for (const puzzle::block& b : current) { for (const puzzle::block b : current.block_view()) {
Color c = BLOCK_COLOR; Color c = BLOCK_COLOR;
if (b.target) { if (b.get_target()) {
c = TARGET_BLOCK_COLOR; c = TARGET_BLOCK_COLOR;
} else if (b.immovable) { } else if (b.get_immovable()) {
c = WALL_COLOR; c = WALL_COLOR;
} }
if (!b.valid() || b.x < 0 || b.y < 0 || b.width <= 0 || b.height <= 0) { const auto [x, y, w, h, t, i] = b.unpack_repr();
warnln("Iterator returned invalid block for state \"{}\".", current.state);
continue;
}
draw_board_block(b.x, b.y, b.width, b.height, c, !b.immovable); draw_board_block(x, y, w, h, c, !i);
} }
// Draw block placing // Draw block placing
if (input.editing && input.has_block_add_xy) { if (input.editing && input.has_block_add_xy) {
if (current.covers(input.block_add_x, input.block_add_y) && if (current.covers(input.block_add_x, input.block_add_y) && input.hov_x >= input.block_add_x && input.hov_y >=
input.hov_x >= input.block_add_x && input.hov_y >= input.block_add_y) { input.block_add_y) {
bool collides = false; bool collides = false;
for (const puzzle::block& b : current) { for (const puzzle::block b : current.block_view()) {
if (b.collides(puzzle::block(input.block_add_x, input.block_add_y, if (b.collides(puzzle::block(input.block_add_x, input.block_add_y, input.hov_x - input.block_add_x + 1,
input.hov_x - input.block_add_x + 1,
input.hov_y - input.block_add_y + 1, false))) { input.hov_y - input.block_add_y + 1, false))) {
collides = true; collides = true;
break; break;
} }
} }
if (!collides) { if (!collides) {
draw_board_block(input.block_add_x, input.block_add_y, draw_board_block(input.block_add_x, input.block_add_y, input.hov_x - input.block_add_x + 1,
input.hov_x - input.block_add_x + 1,
input.hov_y - input.block_add_y + 1, PURPLE); input.hov_y - input.block_add_y + 1, PURPLE);
} }
} }
} }
// TODO: In edit mode
// - Clear Goal button doesn't work
// - Toggle Target Block button throws "Grid bounds out of range"
// - Clicking the goal to remove it throws "Grid bounds out of range"
// Draw goal boundaries when editing // Draw goal boundaries when editing
if (input.editing) { if (input.editing && current.get_goal() && target_block) {
DrawRectangleLinesEx(board_grid.square_bounds(target_x, target_y, target_block->width, target_block->height), 2.0, TARGET_BLOCK_COLOR); DrawRectangleLinesEx(
board_grid.square_bounds(target_x, target_y, target_block->get_width(), target_block->get_height()), 2.0,
TARGET_BLOCK_COLOR);
} }
} }
auto user_interface::draw_graph_overlay(int fps, int ups, size_t mass_count, size_t spring_count) auto user_interface::draw_graph_overlay(int fps, int ups, size_t mass_count, size_t spring_count) -> void
-> void
{ {
graph_overlay_grid.update_bounds(GetScreenWidth() / 2, MENU_HEIGHT); graph_overlay_grid.update_bounds(GetScreenWidth() / 2, MENU_HEIGHT);
debug_overlay_grid.update_bounds(GetScreenWidth() / 2, GetScreenHeight() - 75); debug_overlay_grid.update_bounds(GetScreenWidth() / 2, GetScreenHeight() - 75);
draw_label(graph_overlay_grid.bounds(0, 0, 1, 1), draw_label(graph_overlay_grid.bounds(0, 0, 1, 1), std::format("Dist: {:0>7.2f}", camera.distance), BLACK);
std::format("Dist: {:0>7.2f}", camera.distance), BLACK); draw_label(graph_overlay_grid.bounds(0, 1, 1, 1), std::format("FoV: {:0>6.2f}", camera.fov), BLACK);
draw_label(graph_overlay_grid.bounds(0, 1, 1, 1), std::format("FoV: {:0>6.2f}", camera.fov),
BLACK);
draw_label(graph_overlay_grid.bounds(0, 2, 1, 1), std::format("FPS: {:0>3}", fps), LIME); draw_label(graph_overlay_grid.bounds(0, 2, 1, 1), std::format("FPS: {:0>3}", fps), LIME);
draw_label(graph_overlay_grid.bounds(0, 3, 1, 1), std::format("UPS: {:0>3}", ups), ORANGE); draw_label(graph_overlay_grid.bounds(0, 3, 1, 1), std::format("UPS: {:0>3}", ups), ORANGE);
// Debug // Debug
draw_label(debug_overlay_grid.bounds(0, 0, 1, 1), std::format("Physics Debug:"), BLACK); draw_label(debug_overlay_grid.bounds(0, 0, 1, 1), std::format("Physics Debug:"), BLACK);
draw_label(debug_overlay_grid.bounds(0, 1, 1, 1), std::format("Masses: {}", mass_count), draw_label(debug_overlay_grid.bounds(0, 1, 1, 1), std::format("Masses: {}", mass_count), BLACK);
BLACK); draw_label(debug_overlay_grid.bounds(0, 2, 1, 1), std::format("Springs: {}", spring_count), BLACK);
draw_label(debug_overlay_grid.bounds(0, 2, 1, 1), std::format("Springs: {}", spring_count),
BLACK);
} }
auto user_interface::draw(const int fps, const int ups, const size_t mass_count, auto user_interface::draw(const int fps, const int ups, const size_t mass_count, const size_t spring_count) -> void
const size_t spring_count) -> void
{ {
const auto visitor = overloads{[&](const show_ok_message& msg) const auto visitor = overloads{
{ [&](const show_ok_message& msg)
message_title = msg.title; {
message_message = msg.message; message_title = msg.title;
ok_message = true; message_message = msg.message;
}, ok_message = true;
[&](const show_yes_no_message& msg) },
{ [&](const show_yes_no_message& msg)
message_title = msg.title; {
message_message = msg.message; message_title = msg.title;
yes_no_handler = msg.on_yes; message_message = msg.message;
yes_no_message = true; yes_no_handler = msg.on_yes;
}, yes_no_message = true;
[&](const show_save_preset_window& msg) { save_window = true; }}; },
[&](const show_save_preset_window& msg)
{
save_window = true;
}
};
while (!input.ui_commands.empty()) { while (!input.ui_commands.empty()) {
const ui_command& cmd = input.ui_commands.front(); const ui_command& cmd = input.ui_commands.front();

74
test/bitmap.cpp Normal file
View File

@ -0,0 +1,74 @@
// ReSharper disable CppLocalVariableMayBeConst
#include "puzzle.hpp"
#include <random>
#include <catch2/catch_test_macros.hpp>
TEST_CASE("bitmap_is_full all bits set", "[puzzle][board]")
{
puzzle p1(5, 5);
puzzle p2(3, 4);
puzzle p3(5, 4);
puzzle p4(3, 7);
uint64_t bitmap = -1;
REQUIRE(p1.bitmap_is_full(bitmap));
REQUIRE(p2.bitmap_is_full(bitmap));
REQUIRE(p3.bitmap_is_full(bitmap));
REQUIRE(p4.bitmap_is_full(bitmap));
}
TEST_CASE("bitmap_is_full no bits set", "[puzzle][board]")
{
puzzle p1(5, 5);
puzzle p2(3, 4);
puzzle p3(5, 4);
puzzle p4(3, 7);
uint64_t bitmap = 0;
REQUIRE_FALSE(p1.bitmap_is_full(bitmap));
REQUIRE_FALSE(p2.bitmap_is_full(bitmap));
REQUIRE_FALSE(p3.bitmap_is_full(bitmap));
REQUIRE_FALSE(p4.bitmap_is_full(bitmap));
}
TEST_CASE("bitmap_is_full necessary bits set", "[puzzle][board]")
{
puzzle p1(5, 5);
puzzle p2(3, 4);
puzzle p3(5, 4);
puzzle p4(3, 7);
uint64_t bitmap1 = (1ull << 25) - 1; // 5 * 5
uint64_t bitmap2 = (1ull << 12) - 1; // 3 * 4
uint64_t bitmap3 = (1ull << 20) - 1; // 5 * 4
uint64_t bitmap4 = (1ull << 21) - 1; // 3 * 7
REQUIRE(p1.bitmap_is_full(bitmap1));
REQUIRE(p2.bitmap_is_full(bitmap2));
REQUIRE(p3.bitmap_is_full(bitmap3));
REQUIRE(p4.bitmap_is_full(bitmap4));
}
TEST_CASE("bitmap_is_full necessary bits not set", "[puzzle][board]")
{
puzzle p1(5, 5);
puzzle p2(3, 4);
puzzle p3(5, 4);
puzzle p4(3, 7);
uint64_t bitmap1 = (1ull << 25) - 1; // 5 * 5
uint64_t bitmap2 = (1ull << 12) - 1; // 3 * 4
uint64_t bitmap3 = (1ull << 20) - 1; // 5 * 4
uint64_t bitmap4 = (1ull << 21) - 1; // 3 * 7
bitmap1 &= ~(1ull << 12);
bitmap2 &= ~(1ull << 6);
bitmap3 &= ~(1ull << 8);
bitmap4 &= ~(1ull << 18);
REQUIRE_FALSE(p1.bitmap_is_full(bitmap1));
REQUIRE_FALSE(p2.bitmap_is_full(bitmap2));
REQUIRE_FALSE(p3.bitmap_is_full(bitmap3));
REQUIRE_FALSE(p4.bitmap_is_full(bitmap4));
}

View File

@ -0,0 +1,266 @@
// ReSharper disable CppLocalVariableMayBeConst
#include "puzzle.hpp"
#include <random>
#include <catch2/catch_test_macros.hpp>
#include <catch2/generators/catch_generators.hpp>
static auto board_mask(const int w, const int h) -> uint64_t
{
const int cells = w * h;
if (cells == 64) {
return ~0ULL;
}
return (1ULL << cells) - 1ULL;
}
TEST_CASE("Empty board returns (0,0)", "[puzzle][board]")
{
puzzle p(5, 5);
int x = -1, y = -1;
REQUIRE(p.bitmap_find_first_empty(0ULL, x, y));
REQUIRE(x == 0);
REQUIRE(y == 0);
}
TEST_CASE("Full board detection respects width*height only", "[puzzle][board]")
{
auto [w, h] = GENERATE(std::tuple{3, 3}, std::tuple{4, 4}, std::tuple{5, 6}, std::tuple{8, 8});
puzzle p(w, h);
uint64_t mask = board_mask(w, h);
int x = -1, y = -1;
REQUIRE_FALSE(p.bitmap_find_first_empty(mask, x, y));
// Bits outside board should not affect fullness
REQUIRE_FALSE(p.bitmap_find_first_empty(mask | (~mask), x, y));
}
TEST_CASE("Single empty cell at various positions", "[puzzle][board]")
{
auto [w, h] = GENERATE(std::tuple{3, 3}, std::tuple{4, 4}, std::tuple{5, 5}, std::tuple{8, 8});
puzzle p(w, h);
int cells = w * h;
auto empty_index = GENERATE_COPY(values<int>({ 0, cells / 2, cells - 1}));
uint64_t bitmap = board_mask(w, h);
bitmap &= ~(1ULL << empty_index);
int x = -1, y = -1;
REQUIRE(p.bitmap_find_first_empty(bitmap, x, y));
REQUIRE(x == empty_index % w);
REQUIRE(y == empty_index / w);
}
TEST_CASE("Bits outside board are ignored", "[puzzle][board]")
{
puzzle p(3, 3); // 9 cells
uint64_t mask = board_mask(3, 3);
// Board is full
uint64_t bitmap = mask;
// Set extra bits outside 9 cells
bitmap |= (1ULL << 20);
bitmap |= (1ULL << 63);
int x = -1, y = -1;
REQUIRE_FALSE(p.bitmap_find_first_empty(bitmap, x, y));
}
TEST_CASE("First empty found in forward search branch", "[puzzle][branch]")
{
puzzle p(4, 4); // 16 cells
// Only MSB (within board) set
uint64_t bitmap = (1ULL << 15);
int x = -1, y = -1;
REQUIRE(p.bitmap_find_first_empty(bitmap, x, y));
REQUIRE(x == 0);
REQUIRE(y == 0);
}
TEST_CASE("Backward search branch finds gap before MSB cluster", "[puzzle][branch]")
{
puzzle p(4, 4); // 16 cells
// Set bits 15,14,13 but leave 12 empty
uint64_t bitmap = (1ULL << 15) | (1ULL << 14) | (1ULL << 13);
int x = -1, y = -1;
REQUIRE(p.bitmap_find_first_empty(bitmap, x, y));
REQUIRE(x == 0);
REQUIRE(y == 0);
}
TEST_CASE("Rectangular board coordinate mapping", "[puzzle][rect]")
{
puzzle p(5, 3); // 15 cells
int empty_index = 11;
uint64_t bitmap = board_mask(5, 3);
bitmap &= ~(1ULL << empty_index);
int x = -1, y = -1;
REQUIRE(p.bitmap_find_first_empty(bitmap, x, y));
REQUIRE(x == empty_index % 5);
REQUIRE(y == empty_index / 5);
}
TEST_CASE("Non-64-sized board near limit", "[puzzle][limit]")
{
puzzle p(7, 8); // 56 cells
uint64_t mask = board_mask(7, 8);
// Full board should return false
int x = -1, y = -1;
REQUIRE_FALSE(p.bitmap_find_first_empty(mask, x, y));
// Clear highest valid cell
int empty_index = 55;
mask &= ~(1ULL << empty_index);
REQUIRE(p.bitmap_find_first_empty(mask, x, y));
REQUIRE(x == empty_index % 7);
REQUIRE(y == empty_index / 7);
}
// --- Oracle: find first zero bit inside board ---
static auto oracle_find_first_empty(uint64_t bitmap, int w, int h, int& x, int& y) -> bool
{
int cells = w * h;
for (int i = 0; i < cells; ++i) {
if ((bitmap & (1ULL << i)) == 0) {
x = i % w;
y = i / w;
return true;
}
}
return false;
}
TEST_CASE("Oracle validation across board sizes 3x3 to 8x8", "[puzzle][oracle]")
{
auto [w, h] = GENERATE(std::tuple{3, 3}, std::tuple{4, 4}, std::tuple{5, 5}, std::tuple{6, 6}, std::tuple{7, 7},
std::tuple{8, 8}, std::tuple{3, 5}, std::tuple{5, 3}, std::tuple{7, 8}, std::tuple{8, 7});
puzzle p(w, h);
uint64_t mask = board_mask(w, h);
std::mt19937_64 rng(12345);
std::uniform_int_distribution<uint64_t> dist(0, UINT64_MAX);
for (int iteration = 0; iteration < 200; ++iteration) {
uint64_t bitmap = dist(rng);
int ox = -1, oy = -1;
bool oracle_result = oracle_find_first_empty(bitmap, w, h, ox, oy);
int x = -1, y = -1;
bool result = p.bitmap_find_first_empty(bitmap, x, y);
REQUIRE(result == oracle_result);
if (result) {
REQUIRE(x == ox);
REQUIRE(y == oy);
}
}
}
TEST_CASE("Bits set outside board only behaves as empty board", "[puzzle][outside]")
{
puzzle p(3, 3); // 9 cells
uint64_t bitmap = (1ULL << 40) | (1ULL << 63);
int x = -1, y = -1;
REQUIRE(p.bitmap_find_first_empty(bitmap, x, y));
REQUIRE(x == 0);
REQUIRE(y == 0);
}
TEST_CASE("Last valid cell empty stresses upper bound", "[puzzle][boundary]")
{
auto [w, h] = GENERATE(std::tuple{4, 4}, std::tuple{5, 6}, std::tuple{7, 8}, std::tuple{8, 8});
puzzle p(w, h);
int cells = w * h;
uint64_t bitmap = board_mask(w, h);
// Clear last valid bit
bitmap &= ~(1ULL << (cells - 1));
int x = -1, y = -1;
REQUIRE(p.bitmap_find_first_empty(bitmap, x, y));
REQUIRE(x == (cells - 1) % w);
REQUIRE(y == (cells - 1) / w);
}
TEST_CASE("Board sizes between 33 and 63 cells", "[puzzle][midrange]")
{
auto [w, h] = GENERATE(std::tuple{6, 6}, // 36
std::tuple{7, 6}, // 42
std::tuple{7, 7}, // 49
std::tuple{8, 7}, // 56
std::tuple{7, 8} // 56
);
puzzle p(w, h);
int cells = w * h;
for (int index : {31, 32, cells - 2}) {
if (index >= cells) continue;
uint64_t bitmap = board_mask(w, h);
bitmap &= ~(1ULL << index);
int x = -1, y = -1;
REQUIRE(p.bitmap_find_first_empty(bitmap, x, y));
REQUIRE(x == index % w);
REQUIRE(y == index / w);
}
}
TEST_CASE("Multiple holes choose lowest index", "[puzzle][multiple]")
{
puzzle p(5, 5);
uint64_t bitmap = board_mask(5, 5);
// Clear several positions
bitmap &= ~(1ULL << 3);
bitmap &= ~(1ULL << 7);
bitmap &= ~(1ULL << 12);
int x = -1, y = -1;
REQUIRE(p.bitmap_find_first_empty(bitmap, x, y));
// Oracle expectation: index 3
REQUIRE(x == 3 % 5);
REQUIRE(y == 3 / 5);
}

267
test/bits.cpp Normal file
View File

@ -0,0 +1,267 @@
#include <catch2/catch_test_macros.hpp>
#include <catch2/catch_template_test_macros.hpp>
#include <cstdint>
#include "bits.hpp"
// =============================================================================
// Catch2
// =============================================================================
//
// 1. TEST_CASE(name, tags)
// The basic unit of testing in Catch2. Each TEST_CASE is an independent test
// function. The first argument is a descriptive name (must be unique), and
// the second is a string of tags in square brackets (e.g. "[set_bits]")
// used to filter and group tests when running.
//
// 2. SECTION(name)
// Sections allow multiple subtests within a single TEST_CASE. Each SECTION
// runs the TEST_CASE from the top, so any setup code before the SECTION is
// re-executed fresh for every section. This gives each section an isolated
// starting state without needing separate TEST_CASEs or explicit teardown.
// Sections can also be nested.
//
// 3. REQUIRE(expression)
// The primary assertion macro. If the expression evaluates to false, the
// test fails immediately and Catch2 reports the actual values of both sides
// of the comparison (e.g. "0xF5 == 0xF0" on failure). There is also
// CHECK(), which records a failure but continues executing the rest of the
// test; REQUIRE() aborts the current test on failure.
//
// 4. TEMPLATE_TEST_CASE(name, tags, Type1, Type2, ...)
// A parameterised test that is instantiated once for each type listed.
// Inside the test body, the alias `TestType` refers to the current type.
// This avoids duplicating identical logic for uint8_t, uint16_t, uint32_t,
// and uint64_t. Catch2 automatically appends the type name to the test name
// in the output so you can see which instantiation failed.
//
// 5. Tags (e.g. "[create_mask]", "[round-trip]")
// Tags let you selectively run subsets of tests from the command line.
// For example:
// ./tests "[set_bits]" -- runs only tests tagged [set_bits]
// ./tests "~[round-trip]" -- runs everything except [round-trip]
// ./tests "[get_bits],[set_bits]" -- runs tests matching either tag
//
// =============================================================================
// ---------------------------------------------------------------------------
// create_mask
// ---------------------------------------------------------------------------
TEMPLATE_TEST_CASE("create_mask produces correct masks", "[create_mask]",
uint8_t, uint16_t, uint32_t, uint64_t)
{
SECTION("single bit mask at bit 0") {
auto m = create_mask<TestType>(0, 0);
REQUIRE(m == TestType{0b1});
}
SECTION("single bit mask at bit 3") {
auto m = create_mask<TestType>(3, 3);
REQUIRE(m == TestType{0b1000});
}
SECTION("mask spanning bits 0..7 gives 0xFF") {
auto m = create_mask<TestType>(0, 7);
REQUIRE(m == TestType{0xFF});
}
SECTION("mask spanning bits 4..7") {
auto m = create_mask<TestType>(4, 7);
REQUIRE(m == TestType{0xF0});
}
SECTION("full-width mask returns all ones") {
constexpr uint8_t last = sizeof(TestType) * 8 - 1;
auto m = create_mask<TestType>(0, last);
REQUIRE(m == static_cast<TestType>(~TestType{0}));
}
}
TEST_CASE("create_mask 32-bit specific cases", "[create_mask]") {
REQUIRE(create_mask<uint32_t>(0, 15) == 0x0000FFFF);
REQUIRE(create_mask<uint32_t>(0, 31) == 0xFFFFFFFF);
REQUIRE(create_mask<uint32_t>(16, 31) == 0xFFFF0000);
}
// ---------------------------------------------------------------------------
// clear_bits
// ---------------------------------------------------------------------------
TEMPLATE_TEST_CASE("clear_bits zeroes the specified range", "[clear_bits]",
uint8_t, uint16_t, uint32_t, uint64_t)
{
SECTION("clear all bits") {
TestType val = static_cast<TestType>(~TestType{0});
constexpr uint8_t last = sizeof(TestType) * 8 - 1;
clear_bits(val, 0, last);
REQUIRE(val == TestType{0});
}
SECTION("clear lower nibble") {
TestType val = static_cast<TestType>(0xFF);
clear_bits(val, 0, 3);
REQUIRE(val == static_cast<TestType>(0xF0));
}
SECTION("clear upper nibble") {
TestType val = static_cast<TestType>(0xFF);
clear_bits(val, 4, 7);
REQUIRE(val == static_cast<TestType>(0x0F));
}
SECTION("clear single bit") {
TestType val = static_cast<TestType>(0xFF);
clear_bits(val, 0, 0);
REQUIRE(val == static_cast<TestType>(0xFE));
}
SECTION("clearing already-zero bits is a no-op") {
TestType val = TestType{0};
clear_bits(val, 0, 3);
REQUIRE(val == TestType{0});
}
}
// ---------------------------------------------------------------------------
// set_bits
// ---------------------------------------------------------------------------
TEMPLATE_TEST_CASE("set_bits writes value into the specified range", "[set_bits]",
uint8_t, uint16_t, uint32_t, uint64_t)
{
SECTION("set lower nibble on zero") {
TestType val = TestType{0};
set_bits(val, uint8_t{0}, uint8_t{3}, static_cast<TestType>(0xA));
REQUIRE(val == static_cast<TestType>(0x0A));
}
SECTION("set upper nibble on zero") {
TestType val = TestType{0};
set_bits(val, uint8_t{4}, uint8_t{7}, static_cast<TestType>(0xB));
REQUIRE(val == static_cast<TestType>(0xB0));
}
SECTION("set_bits replaces existing bits") {
TestType val = static_cast<TestType>(0xFF);
set_bits(val, uint8_t{0}, uint8_t{3}, static_cast<TestType>(0x5));
REQUIRE(val == static_cast<TestType>(0xF5));
}
SECTION("set single bit to 1") {
TestType val = TestType{0};
set_bits(val, uint8_t{3}, uint8_t{3}, static_cast<TestType>(1));
REQUIRE(val == static_cast<TestType>(0x08));
}
SECTION("set single bit to 0") {
TestType val = static_cast<TestType>(0xFF);
set_bits(val, uint8_t{3}, uint8_t{3}, static_cast<TestType>(0));
REQUIRE(val == static_cast<TestType>(0xF7));
}
SECTION("setting value 0 clears the range") {
TestType val = static_cast<TestType>(0xFF);
set_bits(val, uint8_t{0}, uint8_t{7}, static_cast<TestType>(0));
REQUIRE(val == TestType{0});
}
}
TEST_CASE("set_bits with different value type (U != T)", "[set_bits]") {
uint32_t val = 0;
constexpr uint8_t small_val = 0x3F;
set_bits(val, uint8_t{8}, uint8_t{13}, small_val);
REQUIRE(val == (uint32_t{0x3F} << 8));
}
TEST_CASE("set_bits preserves surrounding bits in 32-bit", "[set_bits]") {
uint32_t val = 0xDEADBEEF;
set_bits(val, uint8_t{8}, uint8_t{15}, uint32_t{0x42});
REQUIRE(val == 0xDEAD42EF);
}
// ---------------------------------------------------------------------------
// get_bits
// ---------------------------------------------------------------------------
TEMPLATE_TEST_CASE("get_bits extracts the specified range", "[get_bits]",
uint8_t, uint16_t, uint32_t, uint64_t)
{
SECTION("get lower nibble") {
TestType val = static_cast<TestType>(0xAB);
auto result = get_bits(val, uint8_t{0}, uint8_t{3});
REQUIRE(result == TestType{0xB});
}
SECTION("get upper nibble") {
TestType val = static_cast<TestType>(0xAB);
auto result = get_bits(val, uint8_t{4}, uint8_t{7});
REQUIRE(result == TestType{0xA});
}
SECTION("get single bit that is set") {
TestType val = static_cast<TestType>(0x08);
auto result = get_bits(val, uint8_t{3}, uint8_t{3});
REQUIRE(result == TestType{1});
}
SECTION("get single bit that is clear") {
TestType val = static_cast<TestType>(0xF7);
auto result = get_bits(val, uint8_t{3}, uint8_t{3});
REQUIRE(result == TestType{0});
}
SECTION("get all bits") {
TestType val = static_cast<TestType>(~TestType{0});
constexpr uint8_t last = sizeof(TestType) * 8 - 1;
auto result = get_bits(val, uint8_t{0}, last);
REQUIRE(result == val);
}
SECTION("get from zero returns zero") {
TestType val = TestType{0};
auto result = get_bits(val, uint8_t{0}, uint8_t{7});
REQUIRE(result == TestType{0});
}
}
TEST_CASE("get_bits 32-bit specific extractions", "[get_bits]") {
constexpr uint32_t val = 0xDEADBEEF;
REQUIRE(get_bits(val, uint8_t{0}, uint8_t{7}) == 0xEF);
REQUIRE(get_bits(val, uint8_t{8}, uint8_t{15}) == 0xBE);
REQUIRE(get_bits(val, uint8_t{16}, uint8_t{23}) == 0xAD);
REQUIRE(get_bits(val, uint8_t{24}, uint8_t{31}) == 0xDE);
}
// ---------------------------------------------------------------------------
// Round-trip: set then get
// ---------------------------------------------------------------------------
TEST_CASE("set_bits then get_bits round-trips correctly", "[round-trip]") {
uint32_t reg = 0;
set_bits(reg, uint8_t{4}, uint8_t{11}, uint32_t{0xAB});
REQUIRE(get_bits(reg, uint8_t{4}, uint8_t{11}) == 0xAB);
REQUIRE(get_bits(reg, uint8_t{0}, uint8_t{3}) == 0x0);
REQUIRE(get_bits(reg, uint8_t{12}, uint8_t{31}) == 0x0);
}
TEST_CASE("multiple set_bits on different ranges", "[round-trip]") {
uint32_t reg = 0;
set_bits(reg, uint8_t{0}, uint8_t{7}, uint32_t{0x01});
set_bits(reg, uint8_t{8}, uint8_t{15}, uint32_t{0x02});
set_bits(reg, uint8_t{16}, uint8_t{23}, uint32_t{0x03});
set_bits(reg, uint8_t{24}, uint8_t{31}, uint32_t{0x04});
REQUIRE(reg == 0x04030201);
}
TEST_CASE("64-bit round-trip", "[round-trip]") {
uint64_t reg = 0;
set_bits(reg, uint8_t{32}, uint8_t{63}, uint64_t{0xCAFEBABE});
REQUIRE(get_bits(reg, uint8_t{32}, uint8_t{63}) == uint64_t{0xCAFEBABE});
REQUIRE(get_bits(reg, uint8_t{0}, uint8_t{31}) == uint64_t{0});
}

1092
test/puzzle.cpp Normal file

File diff suppressed because it is too large Load Diff