squash merge efficient-puzzle into main
This commit is contained in:
110
CMakeLists.txt
110
CMakeLists.txt
@ -4,20 +4,48 @@ project(MassSprings)
|
||||
set(CMAKE_CXX_STANDARD 26)
|
||||
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
|
||||
|
||||
if(POLICY CMP0167)
|
||||
cmake_policy(SET CMP0167 NEW)
|
||||
endif()
|
||||
|
||||
option(DISABLE_BACKWARD "Disable backward stacktrace printer" OFF)
|
||||
option(DISABLE_TRACY "Disable the Tracy profiler client" ON)
|
||||
option(DISABLE_TESTS "Disable building and running tests" ON)
|
||||
|
||||
# Headers + Sources
|
||||
set(SOURCES
|
||||
src/backward.cpp
|
||||
src/graph_distances.cpp
|
||||
src/input_handler.cpp
|
||||
src/mass_spring_system.cpp
|
||||
src/octree.cpp
|
||||
src/orbit_camera.cpp
|
||||
src/renderer.cpp
|
||||
src/state_manager.cpp
|
||||
src/threaded_physics.cpp
|
||||
src/user_interface.cpp
|
||||
src/puzzle.cpp
|
||||
)
|
||||
|
||||
# Libraries
|
||||
find_package(raylib REQUIRED)
|
||||
set(LIBS raylib)
|
||||
find_package(Boost REQUIRED)
|
||||
set(LIBS raylib Boost::headers)
|
||||
set(FLAGS "")
|
||||
|
||||
if(NOT DEFINED DISABLE_BACKWARD)
|
||||
if(WIN32)
|
||||
list(APPEND LIBS opengl32 gdi32 winmm)
|
||||
endif()
|
||||
|
||||
include(FetchContent)
|
||||
if(NOT DISABLE_BACKWARD)
|
||||
find_package(Backward REQUIRED)
|
||||
|
||||
list(APPEND LIBS Backward::Backward)
|
||||
list(APPEND FLAGS BACKWARD)
|
||||
endif()
|
||||
|
||||
if(NOT DEFINED DISABLE_TRACY)
|
||||
include(FetchContent)
|
||||
if(NOT DISABLE_TRACY)
|
||||
FetchContent_Declare(tracy
|
||||
GIT_REPOSITORY https://github.com/wolfpld/tracy.git
|
||||
GIT_TAG v0.11.1
|
||||
@ -32,14 +60,10 @@ if(NOT DEFINED DISABLE_TRACY)
|
||||
list(APPEND FLAGS TRACY)
|
||||
endif()
|
||||
|
||||
if(WIN32)
|
||||
list(APPEND LIBS opengl32 gdi32 winmm)
|
||||
endif()
|
||||
|
||||
# Set this after fetching tracy to hide tracy's warnings
|
||||
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")
|
||||
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -ggdb -O0")
|
||||
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -ggdb -Ofast -march=native")
|
||||
|
||||
message("-- CMAKE_C_FLAGS: ${CMAKE_C_FLAGS}")
|
||||
message("-- CMAKE_C_FLAGS_DEBUG: ${CMAKE_C_FLAGS_DEBUG}")
|
||||
@ -48,40 +72,42 @@ message("-- CMAKE_CXX_FLAGS: ${CMAKE_CXX_FLAGS}")
|
||||
message("-- CMAKE_CXX_FLAGS_DEBUG: ${CMAKE_CXX_FLAGS_DEBUG}")
|
||||
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
|
||||
add_executable(masssprings ${SOURCES})
|
||||
target_include_directories(masssprings PRIVATE ${RAYLIB_CPP_INCLUDE_DIR})
|
||||
add_executable(masssprings src/main.cpp ${SOURCES})
|
||||
target_include_directories(masssprings PRIVATE include)
|
||||
target_link_libraries(masssprings PRIVATE ${LIBS})
|
||||
target_compile_definitions(masssprings PRIVATE ${FLAGS})
|
||||
|
||||
# Testing sources
|
||||
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
|
||||
)
|
||||
|
||||
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()
|
||||
|
||||
# LTO
|
||||
if(NOT WIN32)
|
||||
include(CheckIPOSupported)
|
||||
check_ipo_supported(RESULT supported OUTPUT error)
|
||||
if(supported)
|
||||
message(STATUS "IPO / LTO enabled")
|
||||
set_property(TARGET masssprings PROPERTY INTERPROCEDURAL_OPTIMIZATION TRUE)
|
||||
if(USE_TRACY)
|
||||
set_property(TARGET masssprings_tracy PROPERTY INTERPROCEDURAL_OPTIMIZATION TRUE)
|
||||
endif()
|
||||
else()
|
||||
message(STATUS "IPO / LTO not supported: <${error}>")
|
||||
endif()
|
||||
endif()
|
||||
#if(NOT WIN32)
|
||||
include(CheckIPOSupported)
|
||||
check_ipo_supported(RESULT supported OUTPUT error)
|
||||
if(supported)
|
||||
message(STATUS "IPO / LTO enabled")
|
||||
set_property(TARGET masssprings PROPERTY INTERPROCEDURAL_OPTIMIZATION TRUE)
|
||||
else()
|
||||
message(STATUS "IPO / LTO not supported")
|
||||
endif()
|
||||
#endif()
|
||||
10
README.md
10
README.md
@ -5,4 +5,12 @@ The graph layout is calculated iteratively using a mass-spring-system with addit
|
||||
|
||||

|
||||
|
||||
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.
|
||||
@ -1,44 +1,30 @@
|
||||
# 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
|
||||
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
|
||||
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
|
||||
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
|
||||
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
|
||||
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
|
||||
F4503bb..21......21..1111....121221......21..
|
||||
|
||||
# Nine Block (Worse)
|
||||
F45031212........21..121221......bb..1111....
|
||||
|
||||
S:[4x5] G:[0,3] M:[F] B:[{2X2 _ 2x1 _} {_ _ 2x1 _} {1x1 1x1 _ _} {1x2 1x2 2x1 _} {_ _ 2x1 _}]
|
||||
# Nine Blocks
|
||||
S:[4x5] G:[0,3] M:[F] B:[{1x2 1x2 _ _} {_ _ 2x1 _} {1x2 1x2 2x1 _} {_ _ 2X2 _} {1x1 1x1 _ _}]
|
||||
# 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
|
||||
F451412..ba....22..11......1122..1111....1111
|
||||
|
||||
# Klotski
|
||||
F451312bb..12........1221..12..1111..11....11
|
||||
|
||||
S:[4x5] G:[1,4] M:[F] B:[{1x2 _ 2X1 _} {_ 2x2 _ 1x1} {_ _ _ 1x1} {2x2 _ 1x1 1x1} {_ _ 1x1 1x1}]
|
||||
# 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
|
||||
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
|
||||
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
|
||||
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}]
|
||||
16
flake.nix
16
flake.nix
@ -109,6 +109,7 @@ rec {
|
||||
# gnumake
|
||||
cmake
|
||||
ninja
|
||||
# cling
|
||||
# pkg-config
|
||||
# clang-tools
|
||||
# compdb
|
||||
@ -118,6 +119,8 @@ rec {
|
||||
hotspot
|
||||
kdePackages.kcachegrind
|
||||
gdbgui
|
||||
massif-visualizer
|
||||
heaptrack
|
||||
# renderdoc
|
||||
];
|
||||
|
||||
@ -129,11 +132,13 @@ rec {
|
||||
raylib
|
||||
raygui
|
||||
thread-pool
|
||||
boost
|
||||
|
||||
# Debugging
|
||||
tracy-wayland
|
||||
backward-cpp
|
||||
libbfd
|
||||
catch2_3
|
||||
];
|
||||
# ===========================================================================================
|
||||
# Define buildable + installable packages
|
||||
@ -152,8 +157,15 @@ rec {
|
||||
cmakeFlags = [
|
||||
"-DDISABLE_TRACY=On"
|
||||
"-DDISABLE_BACKWARD=On"
|
||||
"-DDISABLE_TESTS=On"
|
||||
];
|
||||
|
||||
hardeningDisable = ["all"];
|
||||
|
||||
preConfigure = ''
|
||||
unset NIX_ENFORCE_NO_NATIVE
|
||||
'';
|
||||
|
||||
installPhase = ''
|
||||
mkdir -p $out/bin
|
||||
cp ./${pname} $out/bin/
|
||||
@ -178,6 +190,7 @@ rec {
|
||||
raylib
|
||||
raygui
|
||||
thread-pool
|
||||
boost
|
||||
];
|
||||
|
||||
cmakeFlags = [
|
||||
@ -295,9 +308,12 @@ rec {
|
||||
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 runperf "${buildRelease} && perf record -g ./cmake-build-release/masssprings && hotspot ./perf.data"
|
||||
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 runtests "${buildDebug} && ./cmake-build-debug/tests"
|
||||
|
||||
abbr -a runclion "clion ./CMakeLists.txt 2>/dev/null 1>&2 & disown;"
|
||||
'';
|
||||
|
||||
@ -19,7 +19,7 @@ struct show_yes_no_message
|
||||
{
|
||||
std::string title;
|
||||
std::string message;
|
||||
std::function<void(void)> on_yes;
|
||||
std::function<void()> on_yes;
|
||||
};
|
||||
|
||||
struct show_save_preset_window
|
||||
|
||||
@ -7,306 +7,431 @@
|
||||
#include <cstddef>
|
||||
#include <format>
|
||||
#include <functional>
|
||||
#include <ranges>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <bits/fs_fwd.h>
|
||||
|
||||
// A state is represented by a string "MWHXYblocks", where M is "R"
|
||||
// (restricted) or "F" (free), W is the board width, H is the board height, X
|
||||
// is the target block x goal, Y is the target block y goal and blocks is an
|
||||
// enumeration of each of the board's cells, with each cell being a 2-letter
|
||||
// or 2-digit block representation (a 3x3 board would have a string
|
||||
// representation with length 5 + 3*3 * 2). The board's cells are enumerated
|
||||
// from top-left to bottom-right with each block's pivot being its top-left
|
||||
// corner.
|
||||
/*
|
||||
* 8x8 board
|
||||
* -> 64 (sizes) * 2 (target) * 2 (movable) blocks = 1 Byte
|
||||
*
|
||||
* 1. Encode the position inside the board (max 64 cells)
|
||||
* -> 64 (slots) * 1 Byte (block) = 64 Byte
|
||||
* 2. Encode the position inside the block (max 64 cells)
|
||||
* -> 64 (blocks) * 2 Byte (size + pos) = 128 Byte
|
||||
* 3. Encode the position inside the block (with 15 block limit)
|
||||
* -> 15 (blocks) * 2 (block) = 30 Byte
|
||||
*
|
||||
* Store board size + restricted: +1 Byte
|
||||
* Store target position: +1 Byte
|
||||
*
|
||||
* => Limit to 15 blocks max and use option 3. (4x uint64_t)
|
||||
*
|
||||
*/
|
||||
class puzzle
|
||||
{
|
||||
public:
|
||||
// A block is represented as a 2-digit string "wh", where w is the block width
|
||||
// and h the block height.
|
||||
// The target block (to remove from the board) is represented as a 2-letter
|
||||
// lower-case string "xy", where x is the block width and y the block height and
|
||||
// width/height are represented by [abcdefghi] (~= [123456789]).
|
||||
// Immovable blocks are represented as a 2-letter upper-case string "XY", where
|
||||
// X is the block width and Y the block height and width/height are represented
|
||||
// by [ABCDEFGHI] (~= [123456789]).
|
||||
/*
|
||||
* A block is represented as uint16_t.
|
||||
* It stores its position, width, height and if it's the target block or immovable.
|
||||
*/
|
||||
class block
|
||||
{
|
||||
public:
|
||||
int x = 0;
|
||||
int y = 0;
|
||||
int width = 0;
|
||||
int height = 0;
|
||||
bool target = false;
|
||||
bool immovable = false;
|
||||
|
||||
public:
|
||||
block(const int _x, const int _y, const int _width, const int _height,
|
||||
const bool _target = false, const bool _immovable = false)
|
||||
: x(_x), y(_y), width(_width), height(_height), target(_target), immovable(_immovable)
|
||||
{
|
||||
if (_x < 0 || _x + _width > MAX_WIDTH || _y < 0 || _y + _height > MAX_HEIGHT) {
|
||||
errln("Block must fit in a 9x9 board!");
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
block(const int _x, const int _y, const std::string& b) : x(_x), y(_y)
|
||||
{
|
||||
if (b.length() != 2) {
|
||||
errln("Block representation must have length 2!");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
if (b == "..") {
|
||||
this->x = 0;
|
||||
this->y = 0;
|
||||
width = 0;
|
||||
height = 0;
|
||||
target = false;
|
||||
return;
|
||||
}
|
||||
|
||||
target = false;
|
||||
constexpr std::array<char, 9> target_chars{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'};
|
||||
for (const char c : target_chars) {
|
||||
if (b.contains(c)) {
|
||||
target = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
immovable = false;
|
||||
constexpr std::array<char, 9> immovable_chars{'A', 'B', 'C', 'D', 'E',
|
||||
'F', 'G', 'H', 'I'};
|
||||
for (const char c : immovable_chars) {
|
||||
if (b.contains(c)) {
|
||||
immovable = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (target) {
|
||||
width = static_cast<int>(b.at(0)) - static_cast<int>('a') + 1;
|
||||
height = static_cast<int>(b.at(1)) - static_cast<int>('a') + 1;
|
||||
} else if (immovable) {
|
||||
width = static_cast<int>(b.at(0)) - static_cast<int>('A') + 1;
|
||||
height = static_cast<int>(b.at(1)) - static_cast<int>('A') + 1;
|
||||
} else {
|
||||
// println("Parsing block string '{}' at ({}, {})", b, _x, _y);
|
||||
width = std::stoi(b.substr(0, 1));
|
||||
height = std::stoi(b.substr(1, 1));
|
||||
}
|
||||
|
||||
if (_x < 0 || _x + width > 9 || _y < 0 || _y + height > 9) {
|
||||
errln("Block must fit in a 9x9 board!");
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
block() = delete;
|
||||
|
||||
auto operator==(const block& other) const -> bool
|
||||
{
|
||||
return x == other.x && y == other.y && width && other.width && target == other.target &&
|
||||
immovable == other.immovable;
|
||||
}
|
||||
|
||||
auto operator!=(const block& other) const -> bool
|
||||
{
|
||||
return !(*this == other);
|
||||
}
|
||||
|
||||
public:
|
||||
[[nodiscard]] auto hash() const -> size_t;
|
||||
[[nodiscard]] auto valid() const -> bool;
|
||||
[[nodiscard]] auto string() const -> std::string;
|
||||
|
||||
// Movement
|
||||
|
||||
[[nodiscard]] auto principal_dirs() const -> int;
|
||||
[[nodiscard]] auto covers(int _x, int _y) const -> bool;
|
||||
[[nodiscard]] auto collides(const block& b) const -> bool;
|
||||
};
|
||||
|
||||
private:
|
||||
// https://en.cppreference.com/w/cpp/iterator/input_iterator.html
|
||||
class block_iterator
|
||||
{
|
||||
public:
|
||||
using difference_type = std::ptrdiff_t;
|
||||
using value_type = block;
|
||||
friend class puzzle;
|
||||
|
||||
private:
|
||||
const puzzle& state;
|
||||
int current_pos;
|
||||
static constexpr uint16_t INVALID = 0x8000;
|
||||
|
||||
static constexpr uint8_t IMMOVABLE_S = 0;
|
||||
static constexpr uint8_t IMMOVABLE_E = 0;
|
||||
static constexpr uint8_t TARGET_S = 1;
|
||||
static constexpr uint8_t TARGET_E = 1;
|
||||
static constexpr uint8_t WIDTH_S = 2;
|
||||
static constexpr uint8_t WIDTH_E = 4;
|
||||
static constexpr uint8_t HEIGHT_S = 5;
|
||||
static constexpr uint8_t HEIGHT_E = 7;
|
||||
static constexpr uint8_t X_S = 8;
|
||||
static constexpr uint8_t X_E = 10;
|
||||
static constexpr uint8_t Y_S = 11;
|
||||
static constexpr uint8_t Y_E = 13;
|
||||
|
||||
/*
|
||||
* Memory layout:
|
||||
*
|
||||
* 154 321 098 765 432 1 0
|
||||
* B0 YYY XXX HHH WWW T I
|
||||
* ---------- -----------
|
||||
* Byte 1 Byte 0
|
||||
*
|
||||
* Store the y-position at the most significant bits to obtain a row-major ordering when comparing reprs.
|
||||
* The block at (0, 0) will be the smallest, the block at (width, height) the largest,
|
||||
* the block at (1, 0) will be smaller than the block at (0, 1), all independent of block size.
|
||||
* Then, the block with size (1, 1) will be smaller than the block with size (2, 2),
|
||||
* the block with size (1, 0) - horizontal - will be smaller than the block with size (0, 1) - vertical.
|
||||
*
|
||||
* To mark if a block is empty, the first B bit is set to 1. This is required,
|
||||
* since otherwise uint16_t{0} would be a valid block. This also makes empty blocks sorted last.
|
||||
*/
|
||||
uint16_t repr;
|
||||
|
||||
public:
|
||||
explicit block_iterator(const puzzle& _state) : state(_state), current_pos(0)
|
||||
{}
|
||||
// Produces an invalid block, for usage with std::array<block, MaxBlocks>
|
||||
block()
|
||||
: repr(INVALID) {}
|
||||
|
||||
block_iterator(const puzzle& _state, const int _current_pos)
|
||||
: state(_state), current_pos(_current_pos)
|
||||
{}
|
||||
explicit block(const uint16_t _repr)
|
||||
: repr(_repr) {}
|
||||
|
||||
auto operator*() const -> block
|
||||
block(const int x, const int y, const int w, const int h, const bool t = false, const bool i = false)
|
||||
: repr(create_repr(x, y, w, h, t, i))
|
||||
{
|
||||
return {current_pos % state.width, current_pos / state.width,
|
||||
state.state.substr(current_pos * 2 + PREFIX, 2)};
|
||||
if (x < 0 || x + w > MAX_WIDTH || y < 0 || y + h > MAX_HEIGHT) {
|
||||
throw std::invalid_argument("Block size out of bounds");
|
||||
}
|
||||
if (t && i) {
|
||||
throw std::invalid_argument("Target block can't be immovable");
|
||||
}
|
||||
}
|
||||
|
||||
auto operator++() -> block_iterator&
|
||||
auto operator==(const block other) const -> bool
|
||||
{
|
||||
do {
|
||||
current_pos++;
|
||||
} while (current_pos < state.width * state.height &&
|
||||
state.state.substr(current_pos * 2 + PREFIX, 2) == "..");
|
||||
return *this;
|
||||
return repr == other.repr;
|
||||
}
|
||||
|
||||
auto operator==(const block_iterator& other) const -> bool
|
||||
auto operator!=(const block other) const -> bool
|
||||
{
|
||||
return state == other.state && current_pos == other.current_pos;
|
||||
return repr != other.repr;
|
||||
}
|
||||
|
||||
auto operator!=(const block_iterator& other) const -> bool
|
||||
auto operator<(const block other) const -> bool
|
||||
{
|
||||
return !(*this == other);
|
||||
return repr < other.repr;
|
||||
}
|
||||
|
||||
auto operator<=(const block other) const -> bool
|
||||
{
|
||||
return repr <= other.repr;
|
||||
}
|
||||
|
||||
auto operator>(const block other) const -> bool
|
||||
{
|
||||
return repr > other.repr;
|
||||
}
|
||||
|
||||
auto operator>=(const block other) const -> bool
|
||||
{
|
||||
return repr >= other.repr;
|
||||
}
|
||||
|
||||
private:
|
||||
[[nodiscard]] static auto create_repr(uint8_t x, uint8_t y, uint8_t w, uint8_t h, bool t = false,
|
||||
bool i = false) -> uint16_t;
|
||||
|
||||
// Repr setters
|
||||
[[nodiscard]] auto set_x(uint8_t x) const -> block;
|
||||
[[nodiscard]] auto set_y(uint8_t y) const -> block;
|
||||
[[nodiscard]] auto set_width(uint8_t width) const -> block;
|
||||
[[nodiscard]] auto set_height(uint8_t height) const -> block;
|
||||
[[nodiscard]] auto set_target(bool target) const -> block;
|
||||
[[nodiscard]] auto set_immovable(bool immovable) const -> block;
|
||||
|
||||
public:
|
||||
[[nodiscard]] auto unpack_repr() const -> std::tuple<uint8_t, uint8_t, uint8_t, uint8_t, bool, bool>;
|
||||
|
||||
// Repr getters
|
||||
[[nodiscard]] auto get_x() const -> uint8_t;
|
||||
[[nodiscard]] auto get_y() const -> uint8_t;
|
||||
[[nodiscard]] auto get_width() const -> uint8_t;
|
||||
[[nodiscard]] auto get_height() const -> uint8_t;
|
||||
[[nodiscard]] auto get_target() const -> bool;
|
||||
[[nodiscard]] auto get_immovable() const -> bool;
|
||||
|
||||
// Util
|
||||
[[nodiscard]] auto valid() const -> bool;
|
||||
[[nodiscard]] auto principal_dirs() const -> uint8_t;
|
||||
[[nodiscard]] auto covers(int _x, int _y) const -> bool;
|
||||
[[nodiscard]] auto collides(block b) const -> bool;
|
||||
};
|
||||
|
||||
public:
|
||||
static constexpr int PREFIX = 5;
|
||||
static constexpr int MIN_WIDTH = 3;
|
||||
static constexpr int MIN_HEIGHT = 3;
|
||||
static constexpr int MAX_WIDTH = 9;
|
||||
static constexpr int MAX_HEIGHT = 9;
|
||||
static constexpr uint8_t MAX_BLOCKS = 15;
|
||||
static constexpr uint8_t MIN_WIDTH = 3;
|
||||
static constexpr uint8_t MIN_HEIGHT = 3;
|
||||
static constexpr uint8_t MAX_WIDTH = 8;
|
||||
static constexpr uint8_t MAX_HEIGHT = 8;
|
||||
|
||||
int width = 0;
|
||||
int height = 0;
|
||||
int target_x = 9;
|
||||
int target_y = 9;
|
||||
bool restricted = false; // Only allow blocks to move in their principal direction
|
||||
std::string state;
|
||||
private:
|
||||
static constexpr uint16_t INVALID = 0x8000;
|
||||
|
||||
static constexpr uint8_t RESTRICTED_S = 0;
|
||||
static constexpr uint8_t RESTRICTED_E = 0;
|
||||
static constexpr uint8_t GOAL_X_S = 1;
|
||||
static constexpr uint8_t GOAL_X_E = 3;
|
||||
static constexpr uint8_t GOAL_Y_S = 4;
|
||||
static constexpr uint8_t GOAL_Y_E = 6;
|
||||
static constexpr uint8_t WIDTH_S = 7;
|
||||
static constexpr uint8_t WIDTH_E = 9;
|
||||
static constexpr uint8_t HEIGHT_S = 10;
|
||||
static constexpr uint8_t HEIGHT_E = 12;
|
||||
static constexpr uint8_t GOAL_S = 13;
|
||||
static constexpr uint8_t GOAL_E = 13;
|
||||
|
||||
struct repr_cooked
|
||||
{
|
||||
/*
|
||||
* Memory layout:
|
||||
*
|
||||
* 1543 210 98 7 654 321 0
|
||||
* B0G HHH WW W YYY XXX R
|
||||
* ---------- -----------
|
||||
* Byte 1 Byte 0
|
||||
*
|
||||
* To mark if a puzzle is empty, the first B bit is set to 1.
|
||||
* An extra bit is used to mark if the board has a goal, because we can't store MAX_WIDTH=8 in 3 bits.
|
||||
*/
|
||||
uint16_t meta;
|
||||
|
||||
// NOTE: For the hashes to work, this array needs to be sorted always.
|
||||
// NOTE: This array might contain empty blocks at the end. The iterator handles this.
|
||||
std::array<uint16_t, MAX_BLOCKS> blocks;
|
||||
|
||||
// repr_cooked() = delete;
|
||||
// repr_cooked(const repr_cooked& copy) = delete;
|
||||
// repr_cooked(repr_cooked&& move) = delete;
|
||||
} __attribute__((packed));
|
||||
|
||||
/**
|
||||
* With gcc, were allowed to acces the members arbitrarily, even if they're not active (not the ones last written):
|
||||
* - https://gcc.gnu.org/onlinedocs/gcc-4.7.1/gcc/Structures-unions-enumerations-and-bit_002dfields-implementation.html#Structures-unions-enumerations-and-bit_002dfields-implementation
|
||||
* - https://gcc.gnu.org/onlinedocs/gcc-4.7.1/gcc/Optimize-Options.html#Type_002dpunning
|
||||
*/
|
||||
union repr_u
|
||||
{
|
||||
// The representation split into meta information and the blocks array
|
||||
repr_cooked cooked;
|
||||
|
||||
// For 15 blocks, we have sizeof(meta) + blocks.size() * sizeof(block) = 2 + 15 * 2 = 32 Bytes
|
||||
std::array<uint64_t, 4> raw;
|
||||
};
|
||||
|
||||
repr_u repr;
|
||||
|
||||
public:
|
||||
puzzle() = delete;
|
||||
// Produces an invalid puzzle, for usage with containers
|
||||
puzzle()
|
||||
: repr(repr_cooked{INVALID, invalid_blocks()}) {}
|
||||
|
||||
puzzle(const int w, const int h, const int tx, const int ty, const bool r)
|
||||
: width(w), height(h), target_x(tx), target_y(ty), restricted(r),
|
||||
state(
|
||||
std::format("{}{}{}{}{}{}", r ? "R" : "F", w, h, tx, ty, std::string(w * h * 2, '.')))
|
||||
explicit puzzle(const uint16_t meta)
|
||||
: repr(repr_cooked{meta, invalid_blocks()}) {}
|
||||
|
||||
// NOTE: This constructor does not sort the blocks and is only for state space generation
|
||||
puzzle(const std::tuple<uint8_t, uint8_t, uint8_t, uint8_t, bool, bool>& meta,
|
||||
const std::array<uint16_t, MAX_BLOCKS>& sorted_blocks)
|
||||
: repr(repr_cooked{create_meta(meta), sorted_blocks}) {}
|
||||
|
||||
puzzle(const uint64_t byte_0, const uint64_t byte_1, const uint64_t byte_2, const uint64_t byte_3)
|
||||
: repr(create_repr(byte_0, byte_1, byte_2, byte_3)) {}
|
||||
|
||||
puzzle(const uint16_t meta, const std::array<uint16_t, MAX_BLOCKS>& blocks)
|
||||
: repr(repr_cooked{meta, blocks}) {}
|
||||
|
||||
puzzle(const uint8_t w, const uint8_t h, const uint8_t tx, const uint8_t ty, const bool r, const bool g)
|
||||
: repr(create_repr(w, h, tx, ty, r, g, invalid_blocks()))
|
||||
{
|
||||
if (w < 1 || w > 9 || h < 1 || h > 9) {
|
||||
errln("State width/height must be in [1, 9]!");
|
||||
exit(1);
|
||||
if (w < MIN_WIDTH || w > MAX_WIDTH || h < MIN_HEIGHT || h > MAX_HEIGHT) {
|
||||
throw std::invalid_argument("Board size out of bounds");
|
||||
}
|
||||
if (tx < 0 || tx >= 9 || ty < 0 || ty >= 9) {
|
||||
if (tx != 9 && ty != 9) {
|
||||
errln("State target must be within the board bounds!");
|
||||
exit(1);
|
||||
}
|
||||
if (tx >= MAX_WIDTH || ty >= MAX_HEIGHT) {
|
||||
throw std::invalid_argument("Goal out of bounds");
|
||||
}
|
||||
}
|
||||
|
||||
puzzle(const int w, const int h, const bool r) : puzzle(w, h, 9, 9, r)
|
||||
{}
|
||||
|
||||
explicit puzzle(const std::string& s)
|
||||
: width(std::stoi(s.substr(1, 1))), height(std::stoi(s.substr(2, 1))),
|
||||
target_x(std::stoi(s.substr(3, 1))), target_y(std::stoi(s.substr(4, 1))),
|
||||
restricted(s.substr(0, 1) == "R"), state(s)
|
||||
puzzle(const uint8_t w, const uint8_t h, const uint8_t tx, const uint8_t ty, const bool r, const bool g,
|
||||
const std::array<uint16_t, MAX_BLOCKS>& b)
|
||||
: repr(create_repr(w, h, tx, ty, r, g, b))
|
||||
{
|
||||
if (width < 1 || width > 9 || height < 1 || height > 9) {
|
||||
errln("State width/height must be in [1, 9]!");
|
||||
exit(1);
|
||||
if (w < MIN_WIDTH || w > MAX_WIDTH || h < MIN_HEIGHT || h > MAX_HEIGHT) {
|
||||
throw std::invalid_argument("Board size out of bounds");
|
||||
}
|
||||
if (target_x < 0 || target_x >= 9 || target_y < 0 || target_y >= 9) {
|
||||
if (target_x != 9 && target_y != 9) {
|
||||
errln("State target must be within the board bounds!");
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
if (static_cast<int>(s.length()) != width * height * 2 + PREFIX) {
|
||||
errln("State representation must have length width * "
|
||||
"height * 2 + {}!",
|
||||
PREFIX);
|
||||
exit(1);
|
||||
if (tx >= MAX_WIDTH || ty >= MAX_HEIGHT) {
|
||||
throw std::invalid_argument("Goal out of bounds");
|
||||
}
|
||||
}
|
||||
|
||||
explicit puzzle(const std::string& string_repr)
|
||||
: repr(create_repr(string_repr)) {}
|
||||
|
||||
public:
|
||||
auto operator==(const puzzle& other) const -> bool
|
||||
{
|
||||
return state == other.state;
|
||||
return repr.raw == other.repr.raw;
|
||||
}
|
||||
|
||||
auto operator!=(const puzzle& other) const -> bool
|
||||
{
|
||||
return !(*this == other);
|
||||
return repr.raw != other.repr.raw;
|
||||
}
|
||||
|
||||
[[nodiscard]] auto begin() const -> block_iterator
|
||||
auto operator<(const puzzle& other) const -> bool
|
||||
{
|
||||
block_iterator it{*this};
|
||||
if (!(*it).valid()) {
|
||||
++it;
|
||||
// Start from MSB and go to LSB. If equal, check the next.
|
||||
for (int i = 3; i >= 0; --i) {
|
||||
if (repr.raw[i] < other.repr.raw[i]) {
|
||||
return true;
|
||||
}
|
||||
if (repr.raw[i] > other.repr.raw[i]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return it;
|
||||
|
||||
// All are equal
|
||||
return false;
|
||||
}
|
||||
|
||||
[[nodiscard]] auto end() const -> block_iterator
|
||||
auto operator<=(const puzzle& other) const -> bool
|
||||
{
|
||||
return {*this, width * height};
|
||||
return *this < other || *this == other;
|
||||
}
|
||||
|
||||
auto operator>(const puzzle& other) const -> bool
|
||||
{
|
||||
return !(*this <= other);
|
||||
}
|
||||
|
||||
auto operator>=(const puzzle& other) const -> bool
|
||||
{
|
||||
return !(*this < other);
|
||||
}
|
||||
|
||||
auto repr_view() const
|
||||
{
|
||||
return std::span<const uint16_t>(repr.cooked.blocks.data(), block_count());
|
||||
}
|
||||
|
||||
auto block_view() const
|
||||
{
|
||||
return std::span<const uint16_t>(repr.cooked.blocks.data(), block_count()) | std::views::transform(
|
||||
[](const uint16_t val)
|
||||
{
|
||||
return block(val);
|
||||
});
|
||||
}
|
||||
|
||||
template <typename T, typename... Rest>
|
||||
static auto hash_combine(std::size_t& seed, const T& v, const Rest&... rest) -> void;
|
||||
|
||||
private:
|
||||
[[nodiscard]] auto get_index(int x, int y) const -> int;
|
||||
[[nodiscard]] static constexpr auto invalid_blocks() -> std::array<uint16_t, MAX_BLOCKS>
|
||||
{
|
||||
std::array<uint16_t, MAX_BLOCKS> blocks;
|
||||
for (size_t i = 0; i < MAX_BLOCKS; ++i) {
|
||||
blocks[i] = block::INVALID;
|
||||
}
|
||||
return blocks;
|
||||
}
|
||||
|
||||
[[nodiscard]] static auto create_meta(const std::tuple<uint8_t, uint8_t, uint8_t, uint8_t, bool, bool>& meta) -> uint16_t;
|
||||
[[nodiscard]] static auto create_repr(uint8_t w, uint8_t h, uint8_t tx, uint8_t ty, bool r, bool g,
|
||||
const std::array<uint16_t, MAX_BLOCKS>& b) -> repr_cooked;
|
||||
|
||||
[[nodiscard]] static auto create_repr(uint64_t byte_0, uint64_t byte_1, uint64_t byte_2,
|
||||
uint64_t byte_3) -> repr_cooked;
|
||||
|
||||
[[nodiscard]] static auto create_repr(const std::string& string_repr) -> repr_cooked;
|
||||
|
||||
// Repr setters
|
||||
[[nodiscard]] auto set_restricted(bool restricted) const -> puzzle;
|
||||
[[nodiscard]] auto set_width(uint8_t width) const -> puzzle;
|
||||
[[nodiscard]] auto set_height(uint8_t height) const -> puzzle;
|
||||
[[nodiscard]] auto set_goal(bool goal) const -> puzzle;
|
||||
[[nodiscard]] auto set_goal_x(uint8_t target_x) const -> puzzle;
|
||||
[[nodiscard]] auto set_goal_y(uint8_t target_y) const -> puzzle;
|
||||
[[nodiscard]] auto set_blocks(std::array<uint16_t, MAX_BLOCKS> blocks) const -> puzzle;
|
||||
|
||||
public:
|
||||
// Repr getters
|
||||
[[nodiscard]] auto unpack_meta() const -> std::tuple<uint8_t, uint8_t, uint8_t, uint8_t, bool, bool>;
|
||||
[[nodiscard]] auto get_restricted() const -> bool;
|
||||
[[nodiscard]] auto get_width() const -> uint8_t;
|
||||
[[nodiscard]] auto get_height() const -> uint8_t;
|
||||
[[nodiscard]] auto get_goal() const -> bool;
|
||||
[[nodiscard]] auto get_goal_x() const -> uint8_t;
|
||||
[[nodiscard]] auto get_goal_y() const -> uint8_t;
|
||||
|
||||
// Util
|
||||
[[nodiscard]] auto hash() const -> size_t;
|
||||
[[nodiscard]] auto has_win_condition() const -> bool;
|
||||
[[nodiscard]] auto won() const -> bool;
|
||||
[[nodiscard]] auto string_repr() const -> std::string;
|
||||
[[nodiscard]] static auto try_parse_string_repr(const std::string& string_repr) -> std::optional<repr_cooked>;
|
||||
[[nodiscard]] auto valid() const -> bool;
|
||||
[[nodiscard]] auto try_get_invalid_reason() const -> std::optional<std::string>;
|
||||
|
||||
// Repr helpers
|
||||
|
||||
[[nodiscard]] auto try_get_block(int x, int y) const -> std::optional<block>;
|
||||
[[nodiscard]] auto block_count() const -> uint8_t;
|
||||
[[nodiscard]] auto goal_reached() const -> bool;
|
||||
[[nodiscard]] auto try_get_block(uint8_t x, uint8_t y) const -> std::optional<block>;
|
||||
[[nodiscard]] auto try_get_target_block() const -> std::optional<block>;
|
||||
[[nodiscard]] auto covers(int x, int y, int w, int h) const -> bool;
|
||||
[[nodiscard]] auto covers(int x, int y) const -> bool;
|
||||
[[nodiscard]] auto covers(const block& b) const -> bool;
|
||||
[[nodiscard]] auto covers(uint8_t x, uint8_t y, uint8_t _w, uint8_t _h) const -> bool;
|
||||
[[nodiscard]] auto covers(uint8_t x, uint8_t y) const -> bool;
|
||||
[[nodiscard]] auto covers(block b) const -> bool;
|
||||
|
||||
// Editing
|
||||
|
||||
[[nodiscard]] auto try_toggle_restricted() const -> std::optional<puzzle>;
|
||||
[[nodiscard]] auto try_set_goal(int x, int y) const -> std::optional<puzzle>;
|
||||
[[nodiscard]] auto try_clear_goal() const -> std::optional<puzzle>;
|
||||
[[nodiscard]] auto toggle_restricted() const -> puzzle;
|
||||
[[nodiscard]] auto try_set_goal(uint8_t x, uint8_t y) const -> std::optional<puzzle>;
|
||||
[[nodiscard]] auto clear_goal() const -> puzzle;
|
||||
[[nodiscard]] auto try_add_column() const -> std::optional<puzzle>;
|
||||
[[nodiscard]] auto try_remove_column() const -> std::optional<puzzle>;
|
||||
[[nodiscard]] auto try_add_row() const -> std::optional<puzzle>;
|
||||
[[nodiscard]] auto try_remove_row() const -> std::optional<puzzle>;
|
||||
[[nodiscard]] auto try_add_block(const block& b) const -> std::optional<puzzle>;
|
||||
[[nodiscard]] auto try_remove_block(int x, int y) const -> std::optional<puzzle>;
|
||||
[[nodiscard]] auto try_toggle_target(int x, int y) const -> std::optional<puzzle>;
|
||||
[[nodiscard]] auto try_toggle_wall(int x, int y) const -> std::optional<puzzle>;
|
||||
[[nodiscard]] auto try_add_block(block b) const -> std::optional<puzzle>;
|
||||
[[nodiscard]] auto try_remove_block(uint8_t x, uint8_t y) const -> std::optional<puzzle>;
|
||||
[[nodiscard]] auto try_toggle_target(uint8_t x, uint8_t y) const -> std::optional<puzzle>;
|
||||
[[nodiscard]] auto try_toggle_wall(uint8_t x, uint8_t y) const -> std::optional<puzzle>;
|
||||
|
||||
// Playing
|
||||
|
||||
[[nodiscard]] auto try_move_block_at(int x, int y, direction dir) const
|
||||
-> std::optional<puzzle>;
|
||||
[[nodiscard]] auto try_move_block_at(uint8_t x, uint8_t y, direction dir) const -> std::optional<puzzle>;
|
||||
|
||||
// Statespace
|
||||
[[nodiscard]] auto try_move_block_at_fast(uint64_t bitmap, uint8_t block_idx,
|
||||
direction dir) const -> std::optional<puzzle>;
|
||||
static auto sorted_replace(std::array<uint16_t, MAX_BLOCKS> blocks, uint8_t idx,
|
||||
uint16_t new_val) -> std::array<uint16_t, MAX_BLOCKS>;
|
||||
auto blocks_bitmap() const -> uint64_t;
|
||||
static inline auto bitmap_set_bit(uint64_t bitmap, uint8_t x, uint8_t y) -> uint64_t;
|
||||
static inline auto bitmap_get_bit(uint64_t bitmap, uint8_t x, uint8_t y) -> bool;
|
||||
static auto bitmap_clear_block(uint64_t bitmap, block b) -> uint64_t;
|
||||
static auto bitmap_check_collision(uint64_t bitmap, block b) -> bool;
|
||||
static auto bitmap_check_collision(uint64_t bitmap, block b, direction dir) -> bool;
|
||||
|
||||
template <typename F>
|
||||
auto for_each_adjacent(F&& callback) const -> void
|
||||
{
|
||||
const uint64_t bitmap = blocks_bitmap();
|
||||
const bool r = get_restricted();
|
||||
for (uint8_t idx = 0; idx < MAX_BLOCKS; idx++) {
|
||||
const block b = block(repr.cooked.blocks[idx]);
|
||||
if (!b.valid()) {
|
||||
break;
|
||||
}
|
||||
if (b.get_immovable()) {
|
||||
continue;
|
||||
}
|
||||
const int dirs = r ? b.principal_dirs() : nor | eas | sou | wes;
|
||||
for (const direction d : {nor, eas, sou, wes}) {
|
||||
if (dirs & d) {
|
||||
if (auto moved = try_move_block_at_fast(bitmap, idx, d)) {
|
||||
callback(*moved);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] auto find_adjacent_puzzles() const -> std::vector<puzzle>;
|
||||
[[nodiscard]] auto explore_state_space() const
|
||||
-> std::pair<std::vector<puzzle>, std::vector<std::pair<size_t, size_t>>>;
|
||||
};
|
||||
|
||||
// Provide hash functions so we can use State and <State, State> as hash-set
|
||||
// keys for masses and springs.
|
||||
template <>
|
||||
struct std::hash<puzzle>
|
||||
// Hash functions for sets and maps
|
||||
|
||||
struct puzzle_hasher
|
||||
{
|
||||
auto operator()(const puzzle& s) const noexcept -> size_t
|
||||
{
|
||||
@ -314,30 +439,44 @@ struct std::hash<puzzle>
|
||||
}
|
||||
};
|
||||
|
||||
template <>
|
||||
struct std::hash<std::pair<puzzle, puzzle>>
|
||||
struct link_hasher
|
||||
{
|
||||
auto operator()(const std::pair<puzzle, puzzle>& s) const noexcept -> size_t
|
||||
{
|
||||
const size_t h1 = std::hash<puzzle>{}(s.first);
|
||||
const size_t h2 = std::hash<puzzle>{}(s.second);
|
||||
|
||||
return h1 + h2 + h1 * h2;
|
||||
// return (h1 ^ h2) + 0x9e3779b9 + (std::min(h1, h2) << 6) + (std::max(h1, h2) >> 2);
|
||||
size_t h = 0;
|
||||
if (s.first < s.second) {
|
||||
puzzle::hash_combine(h, s.first, s.second);
|
||||
} else {
|
||||
puzzle::hash_combine(h, s.second, s.first);
|
||||
}
|
||||
return h;
|
||||
}
|
||||
};
|
||||
|
||||
template <>
|
||||
struct std::equal_to<std::pair<puzzle, puzzle>>
|
||||
struct link_equal_to
|
||||
{
|
||||
auto operator()(const std::pair<puzzle, puzzle>& a,
|
||||
const std::pair<puzzle, puzzle>& b) const noexcept -> bool
|
||||
auto operator()(const std::pair<puzzle, puzzle>& a, const std::pair<puzzle, puzzle>& b) const noexcept -> bool
|
||||
{
|
||||
return (a.first == b.first && a.second == b.second) ||
|
||||
(a.first == b.second && a.second == b.first);
|
||||
return (a.first == b.first && a.second == b.second) || (a.first == b.second && a.second == b.first);
|
||||
}
|
||||
};
|
||||
|
||||
using win_condition = std::function<bool(const puzzle&)>;
|
||||
template <typename T, typename... Rest>
|
||||
auto puzzle::hash_combine(std::size_t& seed, const T& v, const Rest&... rest) -> void
|
||||
{
|
||||
auto h = []<typename HashedType>(const HashedType& val) -> std::size_t
|
||||
{
|
||||
if constexpr (std::is_same_v<std::decay_t<HashedType>, puzzle>) {
|
||||
return puzzle_hasher{}(val);
|
||||
} else if constexpr (std::is_same_v<std::decay_t<HashedType>, std::pair<puzzle, puzzle>>) {
|
||||
return link_hasher{}(val);
|
||||
} else {
|
||||
return std::hash<std::decay_t<HashedType>>{}(val);
|
||||
}
|
||||
};
|
||||
|
||||
seed ^= h(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
|
||||
(hash_combine(seed, rest), ...);
|
||||
}
|
||||
|
||||
#endif
|
||||
@ -6,8 +6,8 @@
|
||||
#include "puzzle.hpp"
|
||||
|
||||
#include <stack>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
#include <boost/unordered/unordered_flat_map.hpp>
|
||||
#include <boost/unordered/unordered_flat_set.hpp>
|
||||
|
||||
class state_manager
|
||||
{
|
||||
@ -16,26 +16,23 @@ private:
|
||||
|
||||
std::string preset_file;
|
||||
size_t current_preset = 0;
|
||||
std::vector<puzzle> preset_states = {puzzle(4, 5, 9, 9, false)};
|
||||
std::vector<std::string> preset_comments = {"Empty"};
|
||||
std::vector<puzzle> preset_states = {puzzle(4, 5, 0, 0, true, false)};
|
||||
std::vector<std::string> preset_comments = {"# Empty"};
|
||||
|
||||
// State storage (store states twice for bidirectional lookup).
|
||||
// Everything else should only store indices to state_pool.
|
||||
|
||||
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
|
||||
std::vector<std::pair<size_t, size_t>>
|
||||
links; // Indices are equal to mass_springs springs indices
|
||||
boost::unordered_flat_map<puzzle, size_t, puzzle_hasher> state_indices; // Maps states to indices
|
||||
std::vector<std::pair<size_t, size_t>> links; // Indices are equal to mass_springs springs indices
|
||||
|
||||
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
|
||||
std::vector<size_t>
|
||||
winning_path; // Ordered list of node indices leading to the nearest solved state
|
||||
std::unordered_set<size_t>
|
||||
path_indices; // For faster lookup if a vertex is part of the path in renderer
|
||||
graph_distances node_target_distances; // Buffered and reused if the graph doesn't change
|
||||
boost::unordered_flat_set<size_t> winning_indices; // Indices of all states where the board is solved
|
||||
std::vector<size_t> 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::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
|
||||
std::vector<size_t> move_history; // Moves between the starting state and the current state
|
||||
boost::unordered_flat_map<size_t, int> visit_counts; // How often each state was visited
|
||||
|
||||
size_t starting_state_index = 0;
|
||||
size_t current_state_index = 0;
|
||||
@ -45,7 +42,8 @@ private:
|
||||
bool edited = false;
|
||||
|
||||
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)
|
||||
{
|
||||
parse_preset_file(_preset_file);
|
||||
load_preset(0);
|
||||
@ -138,10 +136,10 @@ public:
|
||||
[[nodiscard]] auto get_link_count() 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_winning_indices() const -> const std::unordered_set<size_t>&;
|
||||
[[nodiscard]] auto get_visit_counts() const -> const std::unordered_map<size_t, int>&;
|
||||
[[nodiscard]] auto get_winning_indices() const -> const boost::unordered_flat_set<size_t>&;
|
||||
[[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_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_preset() const -> size_t;
|
||||
[[nodiscard]] auto get_preset_count() const -> size_t;
|
||||
|
||||
@ -89,7 +89,7 @@ private:
|
||||
|
||||
grid board_grid =
|
||||
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);
|
||||
|
||||
@ -100,7 +100,7 @@ private:
|
||||
|
||||
std::string message_title;
|
||||
std::string message_message;
|
||||
std::function<void(void)> yes_no_handler;
|
||||
std::function<void()> yes_no_handler;
|
||||
bool ok_message = false;
|
||||
bool yes_no_message = false;
|
||||
bool save_window = false;
|
||||
|
||||
@ -3,20 +3,66 @@
|
||||
|
||||
#include <iostream>
|
||||
#include <raylib.h>
|
||||
#include <raymath.h>
|
||||
|
||||
inline auto operator<<(std::ostream& os, const Vector2& v) -> std::ostream&
|
||||
// Bit shifting + masking
|
||||
|
||||
template <class T>
|
||||
requires std::unsigned_integral<T>
|
||||
auto create_mask(const uint8_t first, const uint8_t last) -> T
|
||||
{
|
||||
os << "(" << v.x << ", " << v.y << ")";
|
||||
return os;
|
||||
// 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;
|
||||
}
|
||||
|
||||
inline auto operator<<(std::ostream& os, const Vector3& v) -> std::ostream&
|
||||
template <class T>
|
||||
requires std::unsigned_integral<T>
|
||||
auto clear_bits(T& bits, const uint8_t first, const uint8_t last) -> void
|
||||
{
|
||||
os << "(" << v.x << ", " << v.y << ", " << v.z << ")";
|
||||
return os;
|
||||
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>
|
||||
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>
|
||||
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;
|
||||
}
|
||||
|
||||
// std::variant visitor
|
||||
|
||||
// https://en.cppreference.com/w/cpp/utility/variant/visit
|
||||
template <class... Ts>
|
||||
struct overloads : Ts...
|
||||
@ -24,6 +70,8 @@ struct overloads : Ts...
|
||||
using Ts::operator()...;
|
||||
};
|
||||
|
||||
// Enums
|
||||
|
||||
enum direction
|
||||
{
|
||||
nor = 1 << 0,
|
||||
@ -67,6 +115,20 @@ enum bg
|
||||
bg_white = 47
|
||||
};
|
||||
|
||||
// Output
|
||||
|
||||
inline auto operator<<(std::ostream& os, const Vector2& v) -> std::ostream&
|
||||
{
|
||||
os << "(" << v.x << ", " << v.y << ")";
|
||||
return os;
|
||||
}
|
||||
|
||||
inline auto operator<<(std::ostream& os, const Vector3& v) -> std::ostream&
|
||||
{
|
||||
os << "(" << v.x << ", " << v.y << ", " << v.z << ")";
|
||||
return os;
|
||||
}
|
||||
|
||||
inline auto ansi_bold_fg(const fg color) -> std::string
|
||||
{
|
||||
return std::format("\033[1;{}m", static_cast<int>(color));
|
||||
@ -81,22 +143,22 @@ inline auto ansi_reset() -> std::string
|
||||
template <typename... Args>
|
||||
auto infoln(std::format_string<Args...> fmt, Args&&... args) -> void
|
||||
{
|
||||
std::cout << std::format("[{}INFO{}]: ", ansi_bold_fg(fg_blue), ansi_reset())
|
||||
<< std::format(fmt, std::forward<Args>(args)...) << std::endl;
|
||||
std::cout << std::format("[{}INFO{}]: ", ansi_bold_fg(fg_blue), ansi_reset()) << std::format(
|
||||
fmt, std::forward<Args>(args)...) << std::endl;
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
auto warnln(std::format_string<Args...> fmt, Args&&... args) -> void
|
||||
{
|
||||
std::cout << std::format("[{}WARNING{}]: ", ansi_bold_fg(fg_yellow), ansi_reset())
|
||||
<< std::format(fmt, std::forward<Args>(args)...) << std::endl;
|
||||
std::cout << std::format("[{}WARNING{}]: ", ansi_bold_fg(fg_yellow), ansi_reset()) << std::format(
|
||||
fmt, std::forward<Args>(args)...) << std::endl;
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
auto errln(std::format_string<Args...> fmt, Args&&... args) -> void
|
||||
{
|
||||
std::cout << std::format("[{}ERROR{}]: ", ansi_bold_fg(fg_red), ansi_reset())
|
||||
<< std::format(fmt, std::forward<Args>(args)...) << std::endl;
|
||||
std::cout << std::format("[{}ERROR{}]: ", ansi_bold_fg(fg_red), ansi_reset()) << std::format(
|
||||
fmt, std::forward<Args>(args)...) << std::endl;
|
||||
}
|
||||
|
||||
#endif
|
||||
@ -162,11 +162,12 @@ auto input_handler::select_block() -> void
|
||||
auto input_handler::start_add_block() -> void
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
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_y = hov_y;
|
||||
has_block_add_xy = true;
|
||||
@ -187,7 +188,8 @@ auto input_handler::clear_add_block() -> void
|
||||
auto input_handler::add_block() -> void
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
@ -276,7 +278,7 @@ auto input_handler::toggle_camera_projection() const -> void
|
||||
auto input_handler::move_block_nor() -> void
|
||||
{
|
||||
const puzzle& current = state.get_current_state();
|
||||
const std::optional<puzzle>& next = current.try_move_block_at(sel_x, sel_y, nor);
|
||||
const std::optional<puzzle>& next = current.try_move_block_at_fast(sel_x, sel_y, nor);
|
||||
if (!next) {
|
||||
return;
|
||||
}
|
||||
@ -288,7 +290,7 @@ auto input_handler::move_block_nor() -> void
|
||||
auto input_handler::move_block_wes() -> void
|
||||
{
|
||||
const puzzle& current = state.get_current_state();
|
||||
const std::optional<puzzle>& next = current.try_move_block_at(sel_x, sel_y, wes);
|
||||
const std::optional<puzzle>& next = current.try_move_block_at_fast(sel_x, sel_y, wes);
|
||||
if (!next) {
|
||||
return;
|
||||
}
|
||||
@ -300,7 +302,7 @@ auto input_handler::move_block_wes() -> void
|
||||
auto input_handler::move_block_sou() -> void
|
||||
{
|
||||
const puzzle& current = state.get_current_state();
|
||||
const std::optional<puzzle>& next = current.try_move_block_at(sel_x, sel_y, sou);
|
||||
const std::optional<puzzle>& next = current.try_move_block_at_fast(sel_x, sel_y, sou);
|
||||
if (!next) {
|
||||
return;
|
||||
}
|
||||
@ -312,7 +314,7 @@ auto input_handler::move_block_sou() -> void
|
||||
auto input_handler::move_block_eas() -> void
|
||||
{
|
||||
const puzzle& current = state.get_current_state();
|
||||
const std::optional<puzzle>& next = current.try_move_block_at(sel_x, sel_y, eas);
|
||||
const std::optional<puzzle>& next = current.try_move_block_at_fast(sel_x, sel_y, eas);
|
||||
if (!next) {
|
||||
return;
|
||||
}
|
||||
@ -323,7 +325,7 @@ auto input_handler::move_block_eas() -> 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
|
||||
@ -332,7 +334,7 @@ auto input_handler::load_previous_preset() -> void
|
||||
return;
|
||||
}
|
||||
|
||||
const auto handler = [&]()
|
||||
const auto handler = [&]
|
||||
{
|
||||
block_add_x = -1;
|
||||
block_add_y = -1;
|
||||
@ -353,7 +355,7 @@ auto input_handler::load_next_preset() -> void
|
||||
return;
|
||||
}
|
||||
|
||||
const auto handler = [&]()
|
||||
const auto handler = [&]
|
||||
{
|
||||
block_add_x = -1;
|
||||
block_add_y = -1;
|
||||
@ -370,7 +372,7 @@ auto input_handler::load_next_preset() -> void
|
||||
|
||||
auto input_handler::goto_starting_state() -> void
|
||||
{
|
||||
const auto handler = [&]()
|
||||
const auto handler = [&]
|
||||
{
|
||||
state.goto_starting_state();
|
||||
sel_x = 0;
|
||||
@ -387,7 +389,7 @@ auto input_handler::populate_graph() const -> void
|
||||
|
||||
auto input_handler::clear_graph() -> void
|
||||
{
|
||||
const auto handler = [&]()
|
||||
const auto handler = [&]
|
||||
{
|
||||
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
|
||||
{
|
||||
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) {
|
||||
return;
|
||||
@ -471,7 +473,7 @@ auto input_handler::remove_board_column() const -> void
|
||||
const puzzle& current = state.get_current_state();
|
||||
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;
|
||||
}
|
||||
|
||||
@ -483,7 +485,7 @@ auto input_handler::add_board_column() const -> void
|
||||
const puzzle& current = state.get_current_state();
|
||||
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;
|
||||
}
|
||||
|
||||
@ -495,7 +497,7 @@ auto input_handler::remove_board_row() const -> void
|
||||
const puzzle& current = state.get_current_state();
|
||||
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;
|
||||
}
|
||||
|
||||
@ -507,7 +509,7 @@ auto input_handler::add_board_row() const -> void
|
||||
const puzzle& current = state.get_current_state();
|
||||
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;
|
||||
}
|
||||
|
||||
@ -528,7 +530,7 @@ auto input_handler::toggle_editing() -> void
|
||||
auto input_handler::clear_goal() const -> void
|
||||
{
|
||||
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) {
|
||||
return;
|
||||
|
||||
70
src/main.cpp
70
src/main.cpp
@ -11,21 +11,14 @@
|
||||
#include "user_interface.hpp"
|
||||
|
||||
#ifdef TRACY
|
||||
#include <tracy/Tracy.hpp>
|
||||
#include <tracy/Tracy.hpp>
|
||||
#endif
|
||||
|
||||
// TODO: Add some popups (my split between input.cpp/gui.cpp makes this ugly)
|
||||
// - Clear graph: Notify that this will clear the visited states and move
|
||||
// history
|
||||
// - Reset state: Notify that this will reset the move count
|
||||
// TODO: Manual movement is now completely broken
|
||||
|
||||
// TODO: Reduce memory usage
|
||||
// - The memory model of the puzzle board is terrible (bitboards?)
|
||||
// TODO: Add state space generation time to debug overlay
|
||||
|
||||
// TODO: Improve solver
|
||||
// - Move discovery is terrible
|
||||
// - Instead of trying each direction for each block, determine the
|
||||
// possible moves more efficiently (requires a different memory model)
|
||||
// - Implement state discovery/enumeration
|
||||
// - Find all possible initial board states (single one for each
|
||||
// possible statespace). Currently wer're just finding all states
|
||||
@ -37,7 +30,18 @@
|
||||
|
||||
// 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.
|
||||
// For profiling explore_state_space
|
||||
auto main2(int argc, char* argv[]) -> int
|
||||
{
|
||||
const puzzle p = puzzle(
|
||||
"S:[4x5] G:[1,3] M:[F] B:[{_ 2X2 _ _} {1x1 _ _ 1x1} {1x2 2x1 _ 1x2} {_ 2x1 _ _} {1x1 2x1 _ 1x1}]");
|
||||
|
||||
for (int i = 0; i < 50; ++i) {
|
||||
auto space = p.explore_state_space();
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
auto main(int argc, char* argv[]) -> int
|
||||
{
|
||||
@ -48,17 +52,17 @@ auto main(int argc, char* argv[]) -> int
|
||||
preset_file = argv[1];
|
||||
}
|
||||
|
||||
#ifdef BACKWARD
|
||||
#ifdef BACKWARD
|
||||
infoln("Backward stack-traces enabled.");
|
||||
#else
|
||||
#else
|
||||
infoln("Backward stack-traces disabled.");
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifdef TRACY
|
||||
#ifdef TRACY
|
||||
infoln("Tracy adapter enabled.");
|
||||
#else
|
||||
#else
|
||||
infoln("Tracy adapter disabled.");
|
||||
#endif
|
||||
#endif
|
||||
|
||||
// RayLib window setup
|
||||
SetTraceLogLevel(LOG_ERROR);
|
||||
@ -89,9 +93,9 @@ auto main(int argc, char* argv[]) -> int
|
||||
|
||||
// Game loop
|
||||
while (!WindowShouldClose()) {
|
||||
#ifdef TRACY
|
||||
#ifdef TRACY
|
||||
FrameMarkStart("MainThread");
|
||||
#endif
|
||||
#endif
|
||||
|
||||
// Time tracking
|
||||
std::chrono::time_point now = std::chrono::high_resolution_clock::now();
|
||||
@ -102,16 +106,16 @@ auto main(int argc, char* argv[]) -> int
|
||||
// Input update
|
||||
input.handle_input();
|
||||
|
||||
// Read positions from physics thread
|
||||
#ifdef TRACY
|
||||
// Read positions from physics thread
|
||||
#ifdef TRACY
|
||||
FrameMarkStart("MainThreadConsumeLock");
|
||||
#endif
|
||||
#endif
|
||||
{
|
||||
#ifdef TRACY
|
||||
#ifdef TRACY
|
||||
std::unique_lock<LockableBase(std::mutex)> lock(physics.state.data_mtx);
|
||||
#else
|
||||
#else
|
||||
std::unique_lock<std::mutex> lock(physics.state.data_mtx);
|
||||
#endif
|
||||
#endif
|
||||
|
||||
ups = physics.state.ups;
|
||||
mass_center = physics.state.mass_center;
|
||||
@ -130,16 +134,15 @@ auto main(int argc, char* argv[]) -> int
|
||||
physics.state.data_consumed_cnd.notify_all();
|
||||
}
|
||||
}
|
||||
#ifdef TRACY
|
||||
#ifdef TRACY
|
||||
FrameMarkEnd("MainThreadConsumeLock");
|
||||
#endif
|
||||
#endif
|
||||
|
||||
// Update the camera after the physics, so target lock is smooth
|
||||
size_t current_index = state.get_current_index();
|
||||
if (masses.size() > current_index) {
|
||||
const mass_spring_system::mass& current_mass = mass_spring_system::mass(masses.at(current_index));
|
||||
camera.update(current_mass.position, mass_center, input.camera_lock,
|
||||
input.camera_mass_center_lock);
|
||||
camera.update(current_mass.position, mass_center, input.camera_lock, input.camera_mass_center_lock);
|
||||
}
|
||||
|
||||
// Rendering
|
||||
@ -153,13 +156,12 @@ auto main(int argc, char* argv[]) -> int
|
||||
}
|
||||
++loop_iterations;
|
||||
|
||||
#ifdef TRACY
|
||||
FrameMark;
|
||||
FrameMarkEnd("MainThread");
|
||||
#endif
|
||||
#ifdef TRACY
|
||||
FrameMark; FrameMarkEnd("MainThread");
|
||||
#endif
|
||||
}
|
||||
|
||||
CloseWindow();
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
@ -5,7 +5,7 @@
|
||||
#include <raymath.h>
|
||||
|
||||
#ifdef TRACY
|
||||
#include <tracy/Tracy.hpp>
|
||||
#include <tracy/Tracy.hpp>
|
||||
#endif
|
||||
|
||||
auto octree::node::child_count() const -> int
|
||||
@ -32,9 +32,8 @@ auto octree::create_empty_leaf(const Vector3& box_min, const Vector3& box_max) -
|
||||
auto octree::get_octant(const int node_idx, const Vector3& pos) const -> int
|
||||
{
|
||||
const node& n = nodes[node_idx];
|
||||
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,
|
||||
(n.box_min.z + n.box_max.z) / 2.0f);
|
||||
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,
|
||||
(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
|
||||
// along all 3 axes, if a position is right of an axis, this bit is set to 1.
|
||||
@ -54,13 +53,11 @@ auto octree::get_octant(const int node_idx, const Vector3& pos) const -> int
|
||||
return octant;
|
||||
}
|
||||
|
||||
auto octree::get_child_bounds(const int node_idx, const int octant) const
|
||||
-> std::pair<Vector3, Vector3>
|
||||
auto octree::get_child_bounds(const int node_idx, const int octant) const -> std::pair<Vector3, Vector3>
|
||||
{
|
||||
const node& n = nodes[node_idx];
|
||||
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,
|
||||
(n.box_min.z + n.box_max.z) / 2.0f);
|
||||
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,
|
||||
(n.box_min.z + n.box_max.z) / 2.0f);
|
||||
|
||||
Vector3 min = Vector3Zero();
|
||||
Vector3 max = Vector3Zero();
|
||||
@ -84,13 +81,11 @@ auto octree::insert(const int node_idx, const int mass_id, const Vector3& pos, c
|
||||
// infoln("Inserting position ({}, {}, {}) into octree at node {} (depth {})", pos.x, pos.y,
|
||||
// pos.z, node_idx, depth);
|
||||
if (depth > MAX_DEPTH) {
|
||||
errln("MAX_DEPTH! node={} box_min=({},{},{}) box_max=({},{},{}) pos=({},{},{})", node_idx,
|
||||
nodes[node_idx].box_min.x, nodes[node_idx].box_min.y, nodes[node_idx].box_min.z,
|
||||
nodes[node_idx].box_max.x, 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);
|
||||
throw std::runtime_error(std::format("MAX_DEPTH! node={} box_min=({},{},{}) box_max=({},{},{}) pos=({},{},{})",
|
||||
node_idx, nodes[node_idx].box_min.x, nodes[node_idx].box_min.y,
|
||||
nodes[node_idx].box_min.z, nodes[node_idx].box_max.x,
|
||||
nodes[node_idx].box_max.y, nodes[node_idx].box_max.z, pos.x, pos.y,
|
||||
pos.z));
|
||||
}
|
||||
|
||||
// NOTE: Do not store a nodes[node_idx] reference as the nodes vector might reallocate during
|
||||
@ -152,12 +147,9 @@ auto octree::insert(const int node_idx, const int mass_id, const Vector3& pos, c
|
||||
|
||||
// Update the center of 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_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.z =
|
||||
(nodes[node_idx].mass_center.z * nodes[node_idx].mass_total + pos.z) / new_mass;
|
||||
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.y = (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;
|
||||
}
|
||||
|
||||
@ -198,4 +190,4 @@ auto octree::calculate_force(const int node_idx, const Vector3& pos) const -> Ve
|
||||
}
|
||||
|
||||
return force;
|
||||
}
|
||||
}
|
||||
1106
src/puzzle.cpp
1106
src/puzzle.cpp
File diff suppressed because it is too large
Load Diff
@ -91,7 +91,7 @@ auto state_manager::parse_preset_file(const std::string& _preset_file) -> bool
|
||||
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")) {
|
||||
if (line.starts_with("S")) {
|
||||
preset_lines.push_back(line);
|
||||
} else if (line.starts_with("#")) {
|
||||
comment_lines.push_back(line);
|
||||
@ -105,10 +105,11 @@ auto state_manager::parse_preset_file(const std::string& _preset_file) -> bool
|
||||
|
||||
preset_states.clear();
|
||||
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()) {
|
||||
preset_states = {puzzle(4, 5, 9, 9, false)};
|
||||
preset_states = {puzzle(4, 5, 0, 0, true, false)};
|
||||
infoln("Preset file \"{}\" contained invalid presets: {}", preset_file, *reason);
|
||||
return false;
|
||||
}
|
||||
@ -135,7 +136,7 @@ auto state_manager::append_preset_file(const std::string& preset_name) -> bool
|
||||
return false;
|
||||
}
|
||||
|
||||
file << "\n# " << preset_name << "\n" << get_current_state().state << std::flush;
|
||||
file << "\n# " << preset_name << "\n" << get_current_state().string_repr() << std::flush;
|
||||
|
||||
infoln("Refreshing presets...");
|
||||
if (parse_preset_file(preset_file)) {
|
||||
@ -189,7 +190,7 @@ auto state_manager::update_current_state(const puzzle& p) -> void
|
||||
move_history.emplace_back(previous_state_index);
|
||||
}
|
||||
|
||||
if (p.won()) {
|
||||
if (p.goal_reached()) {
|
||||
winning_indices.insert(current_state_index);
|
||||
}
|
||||
|
||||
@ -297,6 +298,7 @@ auto state_manager::populate_graph() -> void
|
||||
const puzzle s = get_starting_state();
|
||||
const puzzle p = get_current_state();
|
||||
|
||||
|
||||
// Clear the graph first so we don't add duplicates somehow
|
||||
synced_clear_statespace();
|
||||
|
||||
@ -340,7 +342,7 @@ auto state_manager::populate_winning_indices() -> void
|
||||
{
|
||||
winning_indices.clear();
|
||||
for (const auto& [state, index] : state_indices) {
|
||||
if (state.won()) {
|
||||
if (state.goal_reached()) {
|
||||
winning_indices.insert(index);
|
||||
}
|
||||
}
|
||||
@ -429,12 +431,12 @@ auto state_manager::get_links() const -> const std::vector<std::pair<size_t, siz
|
||||
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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
@ -444,7 +446,7 @@ auto state_manager::get_winning_path() const -> const std::vector<size_t>&
|
||||
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;
|
||||
}
|
||||
|
||||
@ -8,12 +8,11 @@
|
||||
#include <raygui.h>
|
||||
|
||||
#ifdef TRACY
|
||||
#include <tracy/Tracy.hpp>
|
||||
#include <tracy/Tracy.hpp>
|
||||
#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
|
||||
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;
|
||||
y = _y;
|
||||
@ -23,8 +22,7 @@ auto user_interface::grid::update_bounds(const int _x, const int _y, const int _
|
||||
rows = _rows;
|
||||
}
|
||||
|
||||
auto user_interface::grid::update_bounds(const int _x, const int _y, const int _width,
|
||||
const int _height) -> void
|
||||
auto user_interface::grid::update_bounds(const int _x, const int _y, const int _width, const int _height) -> void
|
||||
{
|
||||
x = _x;
|
||||
y = _y;
|
||||
@ -48,19 +46,17 @@ auto user_interface::grid::bounds() const -> Rectangle
|
||||
return bounds;
|
||||
}
|
||||
|
||||
auto user_interface::grid::bounds(const int _x, const int _y, const int _width,
|
||||
const int _height) const -> Rectangle
|
||||
auto user_interface::grid::bounds(const int _x, const int _y, const int _width, const int _height) const -> Rectangle
|
||||
{
|
||||
if (_x < 0 || _x + _width > columns || _y < 0 || _y + _height > rows) {
|
||||
errln("Grid bounds are outside range.");
|
||||
exit(1);
|
||||
throw std::invalid_argument("Grid bounds out of range");
|
||||
}
|
||||
|
||||
const int cell_width = (width - padding) / columns;
|
||||
const int cell_height = (height - padding) / rows;
|
||||
|
||||
return Rectangle(x + _x * cell_width + padding, y + _y * cell_height + padding,
|
||||
_width * cell_width - padding, _height * cell_height - padding);
|
||||
return Rectangle(x + _x * cell_width + padding, y + _y * cell_height + padding, _width * cell_width - padding,
|
||||
_height * cell_height - padding);
|
||||
}
|
||||
|
||||
auto user_interface::grid::square_bounds() const -> Rectangle
|
||||
@ -80,8 +76,7 @@ auto user_interface::grid::square_bounds(const int _x, const int _y, const int _
|
||||
// filled
|
||||
|
||||
if (_x < 0 || _x + _width > columns || _y < 0 || _y + _height > rows) {
|
||||
errln("Grid bounds are outside range.");
|
||||
exit(1);
|
||||
throw std::invalid_argument("Grid bounds out of range");
|
||||
}
|
||||
|
||||
const int available_width = width - padding * (columns + 1);
|
||||
@ -93,10 +88,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 y_offset = (height - grid_height) / 2;
|
||||
|
||||
return Rectangle(x_offset + _x * (cell_size + padding) + padding,
|
||||
y_offset + _y * (cell_size + padding) + padding,
|
||||
_width * cell_size + padding * (_width - 1),
|
||||
_height * cell_size + padding * (_height - 1));
|
||||
return Rectangle(x_offset + _x * (cell_size + padding) + padding, y_offset + _y * (cell_size + padding) + padding,
|
||||
_width * cell_size + padding * (_width - 1), _height * cell_size + padding * (_height - 1));
|
||||
}
|
||||
|
||||
auto user_interface::init() -> void
|
||||
@ -155,19 +148,19 @@ auto user_interface::get_default_style() -> default_style
|
||||
{
|
||||
// Could've iterated over the values, but then it wouldn't be as nice to
|
||||
// access...
|
||||
return {{GuiGetStyle(DEFAULT, BORDER_COLOR_NORMAL), GuiGetStyle(DEFAULT, BASE_COLOR_NORMAL),
|
||||
GuiGetStyle(DEFAULT, TEXT_COLOR_NORMAL), GuiGetStyle(DEFAULT, BORDER_COLOR_FOCUSED),
|
||||
GuiGetStyle(DEFAULT, BASE_COLOR_FOCUSED), GuiGetStyle(DEFAULT, TEXT_COLOR_FOCUSED),
|
||||
GuiGetStyle(DEFAULT, BORDER_COLOR_PRESSED), GuiGetStyle(DEFAULT, BASE_COLOR_PRESSED),
|
||||
GuiGetStyle(DEFAULT, TEXT_COLOR_PRESSED), GuiGetStyle(DEFAULT, BORDER_COLOR_DISABLED),
|
||||
GuiGetStyle(DEFAULT, BASE_COLOR_DISABLED), GuiGetStyle(DEFAULT, TEXT_COLOR_DISABLED)},
|
||||
GuiGetStyle(DEFAULT, BACKGROUND_COLOR),
|
||||
GuiGetStyle(DEFAULT, LINE_COLOR),
|
||||
GuiGetStyle(DEFAULT, TEXT_SIZE),
|
||||
GuiGetStyle(DEFAULT, TEXT_SPACING),
|
||||
GuiGetStyle(DEFAULT, TEXT_LINE_SPACING),
|
||||
GuiGetStyle(DEFAULT, TEXT_ALIGNMENT_VERTICAL),
|
||||
GuiGetStyle(DEFAULT, TEXT_WRAP_MODE)};
|
||||
return {
|
||||
{
|
||||
GuiGetStyle(DEFAULT, BORDER_COLOR_NORMAL), GuiGetStyle(DEFAULT, BASE_COLOR_NORMAL),
|
||||
GuiGetStyle(DEFAULT, TEXT_COLOR_NORMAL), GuiGetStyle(DEFAULT, BORDER_COLOR_FOCUSED),
|
||||
GuiGetStyle(DEFAULT, BASE_COLOR_FOCUSED), GuiGetStyle(DEFAULT, TEXT_COLOR_FOCUSED),
|
||||
GuiGetStyle(DEFAULT, BORDER_COLOR_PRESSED), GuiGetStyle(DEFAULT, BASE_COLOR_PRESSED),
|
||||
GuiGetStyle(DEFAULT, TEXT_COLOR_PRESSED), GuiGetStyle(DEFAULT, BORDER_COLOR_DISABLED),
|
||||
GuiGetStyle(DEFAULT, BASE_COLOR_DISABLED), GuiGetStyle(DEFAULT, TEXT_COLOR_DISABLED)
|
||||
},
|
||||
GuiGetStyle(DEFAULT, BACKGROUND_COLOR), GuiGetStyle(DEFAULT, LINE_COLOR), GuiGetStyle(DEFAULT, TEXT_SIZE),
|
||||
GuiGetStyle(DEFAULT, TEXT_SPACING), GuiGetStyle(DEFAULT, TEXT_LINE_SPACING),
|
||||
GuiGetStyle(DEFAULT, TEXT_ALIGNMENT_VERTICAL), GuiGetStyle(DEFAULT, TEXT_WRAP_MODE)
|
||||
};
|
||||
}
|
||||
|
||||
auto user_interface::set_default_style(const default_style& style) -> void
|
||||
@ -201,15 +194,17 @@ auto user_interface::set_default_style(const default_style& style) -> void
|
||||
auto user_interface::get_component_style(const int component) -> component_style
|
||||
{
|
||||
return {
|
||||
{GuiGetStyle(component, BORDER_COLOR_NORMAL), GuiGetStyle(component, BASE_COLOR_NORMAL),
|
||||
GuiGetStyle(component, TEXT_COLOR_NORMAL), GuiGetStyle(component, BORDER_COLOR_FOCUSED),
|
||||
GuiGetStyle(component, BASE_COLOR_FOCUSED), GuiGetStyle(component, TEXT_COLOR_FOCUSED),
|
||||
GuiGetStyle(component, BORDER_COLOR_PRESSED), GuiGetStyle(component, BASE_COLOR_PRESSED),
|
||||
GuiGetStyle(component, TEXT_COLOR_PRESSED), GuiGetStyle(component, BORDER_COLOR_DISABLED),
|
||||
GuiGetStyle(component, BASE_COLOR_DISABLED), GuiGetStyle(component, TEXT_COLOR_DISABLED)},
|
||||
GuiGetStyle(component, BORDER_WIDTH),
|
||||
GuiGetStyle(component, TEXT_PADDING),
|
||||
GuiGetStyle(component, TEXT_ALIGNMENT)};
|
||||
{
|
||||
GuiGetStyle(component, BORDER_COLOR_NORMAL), GuiGetStyle(component, BASE_COLOR_NORMAL),
|
||||
GuiGetStyle(component, TEXT_COLOR_NORMAL), GuiGetStyle(component, BORDER_COLOR_FOCUSED),
|
||||
GuiGetStyle(component, BASE_COLOR_FOCUSED), GuiGetStyle(component, TEXT_COLOR_FOCUSED),
|
||||
GuiGetStyle(component, BORDER_COLOR_PRESSED), GuiGetStyle(component, BASE_COLOR_PRESSED),
|
||||
GuiGetStyle(component, TEXT_COLOR_PRESSED), GuiGetStyle(component, BORDER_COLOR_DISABLED),
|
||||
GuiGetStyle(component, BASE_COLOR_DISABLED), GuiGetStyle(component, TEXT_COLOR_DISABLED)
|
||||
},
|
||||
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
|
||||
@ -238,13 +233,11 @@ auto user_interface::set_component_style(const int component, const component_st
|
||||
auto user_interface::popup_bounds() -> Rectangle
|
||||
{
|
||||
return Rectangle(static_cast<float>(GetScreenWidth()) / 2.0f - POPUP_WIDTH / 2.0f,
|
||||
static_cast<float>(GetScreenHeight()) / 2.0f - POPUP_HEIGHT / 2.0f,
|
||||
POPUP_WIDTH, POPUP_HEIGHT);
|
||||
static_cast<float>(GetScreenHeight()) / 2.0f - POPUP_HEIGHT / 2.0f, POPUP_WIDTH, POPUP_HEIGHT);
|
||||
}
|
||||
|
||||
auto user_interface::draw_button(const Rectangle bounds, const std::string& label,
|
||||
const Color color, const bool enabled, const int font_size) const
|
||||
-> int
|
||||
auto user_interface::draw_button(const Rectangle bounds, const std::string& label, const Color color,
|
||||
const bool enabled, const int font_size) const -> int
|
||||
{
|
||||
// Save original styling
|
||||
const default_style original_default = get_default_style();
|
||||
@ -275,16 +268,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,
|
||||
const std::string& label, const Color color,
|
||||
const bool enabled, const int font_size) const -> int
|
||||
const std::string& label, const Color color, const bool enabled,
|
||||
const int font_size) const -> int
|
||||
{
|
||||
const Rectangle bounds = menu_grid.bounds(x, y, width, height);
|
||||
return draw_button(bounds, label, color, enabled, font_size);
|
||||
}
|
||||
|
||||
auto user_interface::draw_toggle_slider(const Rectangle bounds, const std::string& off_label,
|
||||
const std::string& on_label, int* active, Color color,
|
||||
bool enabled, int font_size) const -> int
|
||||
const std::string& on_label, int* active, Color color, bool enabled,
|
||||
int font_size) const -> int
|
||||
{
|
||||
// Save original styling
|
||||
const default_style original_default = get_default_style();
|
||||
@ -319,18 +312,16 @@ auto user_interface::draw_toggle_slider(const Rectangle bounds, const std::strin
|
||||
return pressed;
|
||||
}
|
||||
|
||||
auto user_interface::draw_menu_toggle_slider(const int x, const int y, const int width,
|
||||
const int height, const std::string& off_label,
|
||||
const std::string& on_label, int* active,
|
||||
const Color color, const bool enabled,
|
||||
const int font_size) const -> int
|
||||
auto user_interface::draw_menu_toggle_slider(const int x, const int y, const int width, const int height,
|
||||
const std::string& off_label, const std::string& on_label, int* active,
|
||||
const Color color, const bool enabled, const int font_size) const -> int
|
||||
{
|
||||
const Rectangle bounds = menu_grid.bounds(x, y, width, height);
|
||||
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,
|
||||
int max, Color color, bool enabled, int font_size) const -> int
|
||||
auto user_interface::draw_spinner(Rectangle bounds, const std::string& label, int* value, int min, int max, Color color,
|
||||
bool enabled, int font_size) const -> int
|
||||
{
|
||||
// Save original styling
|
||||
const default_style original_default = get_default_style();
|
||||
@ -366,16 +357,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,
|
||||
const std::string& label, int* value, const int min,
|
||||
const int max, const Color color, const bool enabled,
|
||||
const int font_size) const -> int
|
||||
const std::string& label, int* value, const int min, const int max,
|
||||
const Color color, const bool enabled, const int font_size) const -> int
|
||||
{
|
||||
const Rectangle bounds = menu_grid.bounds(x, y, width, height);
|
||||
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,
|
||||
const bool enabled, const int font_size) const -> int
|
||||
auto user_interface::draw_label(const Rectangle bounds, const std::string& text, const Color color, const bool enabled,
|
||||
const int font_size) const -> int
|
||||
{
|
||||
// Save original styling
|
||||
const default_style original_default = get_default_style();
|
||||
@ -405,8 +395,8 @@ auto user_interface::draw_label(const Rectangle bounds, const std::string& text,
|
||||
return pressed;
|
||||
}
|
||||
|
||||
auto user_interface::draw_board_block(const int x, const int y, const int width, const int height,
|
||||
const Color color, const bool enabled) const -> bool
|
||||
auto user_interface::draw_board_block(const int x, const int y, const int width, const int height, const Color color,
|
||||
const bool enabled) const -> bool
|
||||
{
|
||||
component_style s = get_component_style(BUTTON);
|
||||
apply_block_color(s, color);
|
||||
@ -452,18 +442,19 @@ auto user_interface::window_open() const -> bool
|
||||
auto user_interface::draw_menu_header(const Color color) const -> void
|
||||
{
|
||||
int preset = static_cast<int>(state.get_current_preset());
|
||||
draw_menu_spinner(0, 0, 1, 1, "Preset: ", &preset, -1,
|
||||
static_cast<int>(state.get_preset_count()), color, !input.editing);
|
||||
draw_menu_spinner(0, 0, 1, 1, "Preset: ", &preset, -1, static_cast<int>(state.get_preset_count()), color,
|
||||
!input.editing);
|
||||
if (preset > static_cast<int>(state.get_current_preset())) {
|
||||
input.load_next_preset();
|
||||
} else if (preset < static_cast<int>(state.get_current_preset())) {
|
||||
input.load_previous_preset();
|
||||
}
|
||||
|
||||
draw_menu_button(1, 0, 1, 1,
|
||||
std::format("Puzzle: \"{}\"{}", state.get_current_preset_comment().substr(2),
|
||||
state.was_edited() ? " (Modified)" : ""),
|
||||
color);
|
||||
draw_menu_button(1, 0, 1, 1, std::format("{}: {}/{} Blocks",
|
||||
state.was_edited()
|
||||
? "Modified"
|
||||
: std::format("\"{}\"", state.get_current_preset_comment().substr(2)),
|
||||
state.get_current_state().block_count(), puzzle::MAX_BLOCKS), color);
|
||||
|
||||
int editing = input.editing;
|
||||
draw_menu_toggle_slider(2, 0, 1, 1, "Puzzle Mode (Tab)", "Edit Mode (Tab)", &editing, color);
|
||||
@ -474,18 +465,13 @@ auto user_interface::draw_menu_header(const Color color) const -> void
|
||||
|
||||
auto user_interface::draw_graph_info(const Color color) const -> void
|
||||
{
|
||||
draw_menu_button(0, 1, 1, 1,
|
||||
std::format("Found {} States ({} Winning)", state.get_state_count(),
|
||||
state.get_target_count()),
|
||||
color);
|
||||
draw_menu_button(0, 1, 1, 1, std::format("Found {} States ({} Winning)", state.get_state_count(),
|
||||
state.get_target_count()), color);
|
||||
|
||||
draw_menu_button(1, 1, 1, 1, std::format("Found {} Transitions", state.get_link_count()),
|
||||
color);
|
||||
draw_menu_button(1, 1, 1, 1, std::format("Found {} Transitions", state.get_link_count()), color);
|
||||
|
||||
draw_menu_button(2, 1, 1, 1,
|
||||
std::format("{} Moves to Nearest Solution",
|
||||
state.get_path_length() > 0 ? state.get_path_length() - 1 : 0),
|
||||
color);
|
||||
draw_menu_button(2, 1, 1, 1, std::format("{} Moves to Nearest Solution",
|
||||
state.get_path_length() > 0 ? state.get_path_length() - 1 : 0), color);
|
||||
}
|
||||
|
||||
auto user_interface::draw_graph_controls(const Color color) const -> void
|
||||
@ -506,8 +492,7 @@ auto user_interface::draw_graph_controls(const Color color) const -> void
|
||||
}
|
||||
|
||||
int mark_solutions = input.mark_solutions;
|
||||
draw_menu_toggle_slider(2, 2, 1, 1, "Solution Hidden (I)", "Solution Shown (I)",
|
||||
&mark_solutions, color);
|
||||
draw_menu_toggle_slider(2, 2, 1, 1, "Solution Hidden (I)", "Solution Shown (I)", &mark_solutions, color);
|
||||
if (mark_solutions != input.mark_solutions) {
|
||||
input.toggle_mark_solutions();
|
||||
}
|
||||
@ -517,22 +502,20 @@ auto user_interface::draw_graph_controls(const Color color) const -> void
|
||||
auto user_interface::draw_camera_controls(const Color color) const -> void
|
||||
{
|
||||
int lock_camera = input.camera_lock;
|
||||
draw_menu_toggle_slider(0, 3, 1, 1, "Free Camera (L)", "Locked Camera (L)", &lock_camera,
|
||||
color);
|
||||
draw_menu_toggle_slider(0, 3, 1, 1, "Free Camera (L)", "Locked Camera (L)", &lock_camera, color);
|
||||
if (lock_camera != input.camera_lock) {
|
||||
input.toggle_camera_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)",
|
||||
&lock_camera_mass_center, color, input.camera_lock);
|
||||
draw_menu_toggle_slider(1, 3, 1, 1, "Current Block (U)", "Graph Center (U)", &lock_camera_mass_center, color,
|
||||
input.camera_lock);
|
||||
if (lock_camera_mass_center != input.camera_mass_center_lock) {
|
||||
input.toggle_camera_mass_center_lock();
|
||||
}
|
||||
|
||||
int projection = camera.projection == CAMERA_ORTHOGRAPHIC;
|
||||
draw_menu_toggle_slider(2, 3, 1, 1, "Perspective (Alt)", "Orthographic (Alt)", &projection,
|
||||
color);
|
||||
draw_menu_toggle_slider(2, 3, 1, 1, "Perspective (Alt)", "Orthographic (Alt)", &projection, color);
|
||||
if (projection != (camera.projection == CAMERA_ORTHOGRAPHIC)) {
|
||||
input.toggle_camera_projection();
|
||||
}
|
||||
@ -558,10 +541,8 @@ auto user_interface::draw_puzzle_controls(const Color color) const -> void
|
||||
};
|
||||
|
||||
const int visits = state.get_current_visits();
|
||||
draw_menu_button(0, 4, 1, 1,
|
||||
std::format("{} Moves ({}{} Time at this State)", state.get_total_moves(),
|
||||
visits, nth(visits)),
|
||||
color);
|
||||
draw_menu_button(0, 4, 1, 1, std::format("{} Moves ({}{} Time at this State)", state.get_total_moves(), visits,
|
||||
nth(visits)), color);
|
||||
|
||||
if (draw_menu_button(1, 4, 1, 1, "Make Optimal Move (Space)", color, state.has_distances())) {
|
||||
input.goto_optimal_next_state();
|
||||
@ -600,43 +581,40 @@ auto user_interface::draw_edit_controls(const Color color) const -> void
|
||||
}
|
||||
|
||||
// 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);
|
||||
if (free != !current.restricted) {
|
||||
if (free != !current.get_restricted()) {
|
||||
input.toggle_restricted_movement();
|
||||
}
|
||||
|
||||
// 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
|
||||
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);
|
||||
if (columns > current.width) {
|
||||
if (columns > current.get_width()) {
|
||||
input.add_board_column();
|
||||
} else if (columns < current.width) {
|
||||
} else if (columns < current.get_width()) {
|
||||
input.remove_board_column();
|
||||
}
|
||||
|
||||
// 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);
|
||||
if (rows > current.height) {
|
||||
if (rows > current.get_height()) {
|
||||
input.add_board_row();
|
||||
} else if (rows < current.height) {
|
||||
} else if (rows < current.get_height()) {
|
||||
input.remove_board_row();
|
||||
}
|
||||
}
|
||||
|
||||
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),
|
||||
color);
|
||||
draw_menu_button(0, 6, 2, 1, state.get_current_state().string_repr().data(), color);
|
||||
|
||||
if (draw_menu_button(2, 6, 1, 1, "Save as Preset", color)) {
|
||||
if (const std::optional<std::string>& reason =
|
||||
state.get_current_state().try_get_invalid_reason()) {
|
||||
if (const std::optional<std::string>& reason = state.get_current_state().try_get_invalid_reason()) {
|
||||
message_title = "Can't Save Preset";
|
||||
message_message = std::format("Invalid Board: {}.", *reason);
|
||||
ok_message = true;
|
||||
@ -651,8 +629,7 @@ auto user_interface::get_background_color() -> 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
|
||||
{
|
||||
@ -661,8 +638,8 @@ auto user_interface::draw_save_preset_popup() -> void
|
||||
}
|
||||
|
||||
// Returns the pressed button index
|
||||
const int button = GuiTextInputBox(popup_bounds(), "Save as Preset", "Enter Preset Name",
|
||||
"Ok;Cancel", preset_name.data(), 255, nullptr);
|
||||
const int button = GuiTextInputBox(popup_bounds(), "Save as Preset", "Enter Preset Name", "Ok;Cancel",
|
||||
preset_name.data(), 255, nullptr);
|
||||
if (button == 1) {
|
||||
state.append_preset_file(preset_name.data());
|
||||
}
|
||||
@ -678,8 +655,7 @@ auto user_interface::draw_ok_message_box() -> void
|
||||
return;
|
||||
}
|
||||
|
||||
const int button =
|
||||
GuiMessageBox(popup_bounds(), message_title.data(), message_message.data(), "Ok");
|
||||
const int button = GuiMessageBox(popup_bounds(), message_title.data(), message_message.data(), "Ok");
|
||||
if (button == 0 || button == 1) {
|
||||
message_title = "";
|
||||
message_message = "";
|
||||
@ -693,8 +669,7 @@ auto user_interface::draw_yes_no_message_box() -> void
|
||||
return;
|
||||
}
|
||||
|
||||
const int button =
|
||||
GuiMessageBox(popup_bounds(), message_title.data(), message_message.data(), "Yes;No");
|
||||
const int button = GuiMessageBox(popup_bounds(), message_title.data(), message_message.data(), "Yes;No");
|
||||
if (button == 1) {
|
||||
yes_no_handler();
|
||||
}
|
||||
@ -727,37 +702,36 @@ auto user_interface::draw_puzzle_board() -> void
|
||||
{
|
||||
const puzzle& current = state.get_current_state();
|
||||
|
||||
board_grid.update_bounds(0, MENU_HEIGHT, GetScreenWidth() / 2, GetScreenHeight() - MENU_HEIGHT,
|
||||
current.width, current.height);
|
||||
board_grid.update_bounds(0, MENU_HEIGHT, GetScreenWidth() / 2, GetScreenHeight() - MENU_HEIGHT, current.get_width(),
|
||||
current.get_height());
|
||||
|
||||
// Draw outer border
|
||||
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
|
||||
DrawRectangle(bounds.x + BOARD_PADDING, bounds.y + BOARD_PADDING,
|
||||
bounds.width - 2 * BOARD_PADDING, bounds.height - 2 * BOARD_PADDING,
|
||||
current.restricted ? BOARD_COLOR_RESTRICTED : BOARD_COLOR_FREE);
|
||||
DrawRectangle(bounds.x + BOARD_PADDING, bounds.y + BOARD_PADDING, bounds.width - 2 * BOARD_PADDING,
|
||||
bounds.height - 2 * BOARD_PADDING,
|
||||
current.get_restricted() ? BOARD_COLOR_RESTRICTED : BOARD_COLOR_FREE);
|
||||
|
||||
// Draw target opening
|
||||
// TODO: Only draw single direction (in corner) if restricted (use target block principal
|
||||
// direction)
|
||||
const std::optional<puzzle::block> target_block = current.try_get_target_block();
|
||||
const int target_x = current.target_x;
|
||||
const int target_y = current.target_y;
|
||||
if (current.has_win_condition() && target_block) {
|
||||
auto [x, y, width, height] = board_grid.square_bounds(
|
||||
target_x, target_y, target_block.value().width, target_block.value().height);
|
||||
const int target_x = current.get_goal_x();
|
||||
const int target_y = current.get_goal_y();
|
||||
if (current.get_goal() && target_block) {
|
||||
auto [x, y, width, height] = board_grid.square_bounds(target_x, target_y, target_block->get_width(),
|
||||
target_block->get_height());
|
||||
|
||||
const Color opening_color =
|
||||
Fade(current.won() ? BOARD_COLOR_WON : BOARD_COLOR_RESTRICTED, 0.3);
|
||||
const Color opening_color = Fade(current.goal_reached() ? BOARD_COLOR_WON : BOARD_COLOR_RESTRICTED, 0.3);
|
||||
|
||||
if (target_x == 0) {
|
||||
// Left opening
|
||||
DrawRectangle(x - BOARD_PADDING, y, BOARD_PADDING, height, RAYWHITE);
|
||||
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
|
||||
DrawRectangle(x + width, y, BOARD_PADDING, height, RAYWHITE);
|
||||
DrawRectangle(x + width, y, BOARD_PADDING, height, opening_color);
|
||||
@ -767,7 +741,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, opening_color);
|
||||
}
|
||||
if (target_y + target_block.value().height == current.height) {
|
||||
if (target_y + target_block->get_height() == current.get_height()) {
|
||||
// Bottom opening
|
||||
DrawRectangle(x, y + height, width, BOARD_PADDING, RAYWHITE);
|
||||
DrawRectangle(x, y + height, width, BOARD_PADDING, opening_color);
|
||||
@ -794,87 +768,87 @@ auto user_interface::draw_puzzle_board() -> void
|
||||
}
|
||||
|
||||
// Draw blocks
|
||||
for (const puzzle::block& b : current) {
|
||||
for (const puzzle::block b : current.block_view()) {
|
||||
Color c = BLOCK_COLOR;
|
||||
if (b.target) {
|
||||
if (b.get_target()) {
|
||||
c = TARGET_BLOCK_COLOR;
|
||||
} else if (b.immovable) {
|
||||
} else if (b.get_immovable()) {
|
||||
c = WALL_COLOR;
|
||||
}
|
||||
|
||||
if (!b.valid() || b.x < 0 || b.y < 0 || b.width <= 0 || b.height <= 0) {
|
||||
warnln("Iterator returned invalid block for state \"{}\".", current.state);
|
||||
continue;
|
||||
}
|
||||
const auto [x, y, w, h, t, i] = b.unpack_repr();
|
||||
|
||||
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
|
||||
if (input.editing && input.has_block_add_xy) {
|
||||
if (current.covers(input.block_add_x, input.block_add_y) &&
|
||||
input.hov_x >= input.block_add_x && input.hov_y >= 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.block_add_y) {
|
||||
bool collides = false;
|
||||
for (const puzzle::block& b : current) {
|
||||
if (b.collides(puzzle::block(input.block_add_x, input.block_add_y,
|
||||
input.hov_x - input.block_add_x + 1,
|
||||
for (const puzzle::block b : current.block_view()) {
|
||||
if (b.collides(puzzle::block(input.block_add_x, input.block_add_y, input.hov_x - input.block_add_x + 1,
|
||||
input.hov_y - input.block_add_y + 1, false))) {
|
||||
collides = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!collides) {
|
||||
draw_board_block(input.block_add_x, input.block_add_y,
|
||||
input.hov_x - input.block_add_x + 1,
|
||||
draw_board_block(input.block_add_x, input.block_add_y, input.hov_x - input.block_add_x + 1,
|
||||
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
|
||||
if (input.editing) {
|
||||
DrawRectangleLinesEx(board_grid.square_bounds(target_x, target_y, target_block->width, target_block->height), 2.0, TARGET_BLOCK_COLOR);
|
||||
if (input.editing && current.get_goal() && target_block) {
|
||||
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)
|
||||
-> void
|
||||
auto user_interface::draw_graph_overlay(int fps, int ups, size_t mass_count, size_t spring_count) -> void
|
||||
{
|
||||
graph_overlay_grid.update_bounds(GetScreenWidth() / 2, MENU_HEIGHT);
|
||||
debug_overlay_grid.update_bounds(GetScreenWidth() / 2, GetScreenHeight() - 75);
|
||||
|
||||
draw_label(graph_overlay_grid.bounds(0, 0, 1, 1),
|
||||
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, 0, 1, 1), 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, 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);
|
||||
|
||||
// Debug
|
||||
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),
|
||||
BLACK);
|
||||
draw_label(debug_overlay_grid.bounds(0, 2, 1, 1), std::format("Springs: {}", spring_count),
|
||||
BLACK);
|
||||
draw_label(debug_overlay_grid.bounds(0, 1, 1, 1), std::format("Masses: {}", mass_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,
|
||||
const size_t spring_count) -> void
|
||||
auto user_interface::draw(const int fps, const int ups, const size_t mass_count, const size_t spring_count) -> void
|
||||
{
|
||||
const auto visitor = overloads{[&](const show_ok_message& msg)
|
||||
{
|
||||
message_title = msg.title;
|
||||
message_message = msg.message;
|
||||
ok_message = true;
|
||||
},
|
||||
[&](const show_yes_no_message& msg)
|
||||
{
|
||||
message_title = msg.title;
|
||||
message_message = msg.message;
|
||||
yes_no_handler = msg.on_yes;
|
||||
yes_no_message = true;
|
||||
},
|
||||
[&](const show_save_preset_window& msg) { save_window = true; }};
|
||||
const auto visitor = overloads{
|
||||
[&](const show_ok_message& msg)
|
||||
{
|
||||
message_title = msg.title;
|
||||
message_message = msg.message;
|
||||
ok_message = true;
|
||||
},
|
||||
[&](const show_yes_no_message& msg)
|
||||
{
|
||||
message_title = msg.title;
|
||||
message_message = msg.message;
|
||||
yes_no_handler = msg.on_yes;
|
||||
yes_no_message = true;
|
||||
},
|
||||
[&](const show_save_preset_window& msg)
|
||||
{
|
||||
save_window = true;
|
||||
}
|
||||
};
|
||||
|
||||
while (!input.ui_commands.empty()) {
|
||||
const ui_command& cmd = input.ui_commands.front();
|
||||
|
||||
267
test/bits.cpp
Normal file
267
test/bits.cpp
Normal file
@ -0,0 +1,267 @@
|
||||
#include <catch2/catch_test_macros.hpp>
|
||||
#include <catch2/catch_template_test_macros.hpp>
|
||||
#include <cstdint>
|
||||
|
||||
#include "util.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});
|
||||
}
|
||||
Reference in New Issue
Block a user