commit bae6567842490881dc12b5f2ce4d646037848ff8 Author: Erik Simon Date: Sat Sep 5 03:01:11 2026 +0200 Initial commit diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..b588856 --- /dev/null +++ b/.clang-format @@ -0,0 +1,30 @@ +# Matches the style already in game-from-scratch: Allman braces, four spaces, +# namespace bodies indented, pointers bound to the type, aliases aligned. +--- +Language: Cpp +BasedOnStyle: Microsoft + +ColumnLimit: 110 +IndentWidth: 4 +TabWidth: 4 +UseTab: Never + +BreakBeforeBraces: Allman +NamespaceIndentation: All +AccessModifierOffset: -4 + +PointerAlignment: Left +ReferenceAlignment: Left + +# Your existing code writes `Ref window { nullptr }` — space before the +# brace, spaces inside it. Both are non-default and have to be asked for. +Cpp11BracedListStyle: false +SpaceBeforeCpp11BracedList: true + +AlignConsecutiveAssignments: Consecutive +AlignAfterOpenBracket: Align +AllowShortFunctionsOnASingleLine: Inline +AllowShortIfStatementsOnASingleLine: Never +FixNamespaceComments: false +SortIncludes: CaseSensitive +IncludeBlocks: Preserve diff --git a/.clang-tidy b/.clang-tidy new file mode 100644 index 0000000..9bdfb05 --- /dev/null +++ b/.clang-tidy @@ -0,0 +1,17 @@ +# Deliberately narrow. Broad checks (readability-*, cppcoreguidelines-*) fight +# the naming convention and the SDL C API on every line, and a linter that +# cries wolf on every file gets switched off within a week. +Checks: > + bugprone-*, + -bugprone-easily-swappable-parameters, + -bugprone-narrowing-conversions, + performance-*, + modernize-use-nullptr, + modernize-use-override, + modernize-use-using, + misc-*, + -misc-non-private-member-variables-in-classes, + -misc-include-cleaner + +WarningsAsErrors: '' +HeaderFilterRegex: '.*/Source/.*' diff --git a/.envrc b/.envrc new file mode 100644 index 0000000..3550a30 --- /dev/null +++ b/.envrc @@ -0,0 +1 @@ +use flake diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0f973ec --- /dev/null +++ b/.gitignore @@ -0,0 +1,47 @@ +# CMake build directories +cmake-build-*/ +build/ +out/ + +# CLion +.idea/ + +# direnv +.direnv/ + +# Generated by the devShell on entry (see flake.nix) +.clangd + +# Downloaded by cmake/Cpm.cmake when the nix devShell isn't providing it +cmake/CPM.cmake +cpm-package-lock.cmake + +# CMake +CMakeCache.txt +CMakeFiles/ +cmake_install.cmake +compile_commands.json +install_manifest.txt +_deps/ + +# Compiled output +*.o +*.obj +*.so +*.dylib +*.dll +*.a +*.lib +*.exe +*.gch +*.pch + +# ImGui window layout, written at runtime next to the executable +imgui.ini + +# Editors / OS +.vscode/ +*.code-workspace +.DS_Store +*~ +*.swp diff --git a/Assets/.gitkeep b/Assets/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..eae7214 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,139 @@ +cmake_minimum_required(VERSION 4.0) +project(siege_deck CXX) + +set(CMAKE_CXX_STANDARD 26) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) +set(CMAKE_EXPORT_COMPILE_COMMANDS ON) + +if (WIN32) + add_compile_definitions(PLATFORM_WINDOWS) +elseif (UNIX) + add_compile_definitions(PLATFORM_LINUX) +endif () + +list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake) +include(Cpm) + +# --------------------------------------------------------------------------- +# Dependencies +# +# Every entry below is a CPMAddPackage, so this tree configures unchanged on a +# machine with no nix (Windows, CI, a bare checkout) — CPM fetches and builds +# each one from the pinned tag. Inside the devShell, CPM_USE_LOCAL_PACKAGES=ON +# flips each call to try find_package first, and every one of these resolves +# against nixpkgs, so nothing is downloaded or rebuilt. +# +# That only holds because NAME is the find_package name (SDL3, not SDL) and +# VERSION matches what nixpkgs ships. Both paths are pinned to the SAME +# version deliberately: a dependency that differs between "on my machine" and +# "in the nix shell" is the exact bug this setup exists to avoid. Bumping one +# means bumping the other, or waiting for nixpkgs to catch up. +# --------------------------------------------------------------------------- + +set(LIBS) + +# Boost, for pretty type names via boost::typeindex (see Common.h). +# +# Boost::type_index only exists in the modular boost-cmake build CPM pulls; +# nixpkgs' b2-based install exposes only the aggregate Boost::headers. Since +# type_index is header-only, Boost::headers carries it in both worlds. +CPMAddPackage( + NAME Boost + VERSION 1.89.0 + URL "https://github.com/boostorg/boost/releases/download/boost-1.89.0/boost-1.89.0-cmake.tar.xz" + FIND_PACKAGE_ARGUMENTS "CONFIG COMPONENTS headers") +list(APPEND LIBS Boost::headers) + +# Logging. +CPMAddPackage( + NAME spdlog + VERSION 1.17.0 + GITHUB_REPOSITORY gabime/spdlog + GIT_TAG v1.17.0 + FIND_PACKAGE_ARGUMENTS "CONFIG") +list(APPEND LIBS spdlog::spdlog) + +# Windowing, input, 2D rendering. +CPMAddPackage( + NAME SDL3 + VERSION 3.4.14 + GITHUB_REPOSITORY libsdl-org/SDL + GIT_TAG release-3.4.14 + FIND_PACKAGE_ARGUMENTS "CONFIG") +list(APPEND LIBS SDL3::SDL3) + +# Sprite loading (PNG, JPG, ...). +CPMAddPackage( + NAME SDL3_image + VERSION 3.4.4 + GITHUB_REPOSITORY libsdl-org/SDL_image + GIT_TAG release-3.4.4 + FIND_PACKAGE_ARGUMENTS "CONFIG") +list(APPEND LIBS SDL3_image::SDL3_image) + +# Text: gold, wave counters, tower costs, tooltips. +CPMAddPackage( + NAME SDL3_ttf + VERSION 3.2.2 + GITHUB_REPOSITORY libsdl-org/SDL_ttf + GIT_TAG release-3.2.2 + FIND_PACKAGE_ARGUMENTS "CONFIG") +list(APPEND LIBS SDL3_ttf::SDL3_ttf) + +# Audio. +CPMAddPackage( + NAME SDL3_mixer + VERSION 3.2.4 + GITHUB_REPOSITORY libsdl-org/SDL_mixer + GIT_TAG release-3.2.4 + FIND_PACKAGE_ARGUMENTS "CONFIG") +list(APPEND LIBS SDL3_mixer::SDL3_mixer) + +# Vector math. +CPMAddPackage( + NAME glm + VERSION 1.0.3 + GITHUB_REPOSITORY g-truc/glm + GIT_TAG 1.0.3 + FIND_PACKAGE_ARGUMENTS "CONFIG") +list(APPEND LIBS glm::glm) + +# ECS. +CPMAddPackage( + NAME EnTT + VERSION 3.16.0 + GITHUB_REPOSITORY skypjack/entt + GIT_TAG v3.16.0 + FIND_PACKAGE_ARGUMENTS "CONFIG") +list(APPEND LIBS EnTT::EnTT) + +# Debug/tools UI. Not a CPMAddPackage call because upstream ImGui ships no +# CMakeLists at all — see cmake/ImGui.cmake for what that costs. +include(ImGui) +list(APPEND LIBS imgui::imgui) + +# --------------------------------------------------------------------------- +# Target +# --------------------------------------------------------------------------- + +add_executable(${PROJECT_NAME} + Source/Main.cpp + Source/Common.h + Source/Pch.h) + +target_include_directories(${PROJECT_NAME} PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/Source) + +target_link_libraries(${PROJECT_NAME} PRIVATE ${LIBS}) + +target_precompile_headers(${PROJECT_NAME} PRIVATE Source/Pch.h) + +# Assets are looked up relative to the executable, so the same path works from +# the build dir, from CLion's runner, and from an installed copy. +add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy_directory + ${CMAKE_CURRENT_SOURCE_DIR}/Assets + $/Assets) diff --git a/CMakePresets.json b/CMakePresets.json new file mode 100644 index 0000000..8123c70 --- /dev/null +++ b/CMakePresets.json @@ -0,0 +1,34 @@ +{ + "version": 6, + "configurePresets": [ + { + "name": "base", + "hidden": true, + "generator": "Ninja", + "binaryDir": "${sourceDir}/cmake-build-${presetName}", + "cacheVariables": { + "CMAKE_EXPORT_COMPILE_COMMANDS": "ON" + } + }, + { + "name": "debug", + "displayName": "Debug", + "inherits": "base", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Debug" + } + }, + { + "name": "release", + "displayName": "Release", + "inherits": "base", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "RelWithDebInfo" + } + } + ], + "buildPresets": [ + { "name": "debug", "configurePreset": "debug" }, + { "name": "release", "configurePreset": "release" } + ] +} diff --git a/README.md b/README.md new file mode 100644 index 0000000..3c1d1db --- /dev/null +++ b/README.md @@ -0,0 +1,111 @@ +# siege-deck + +A from-scratch tower defense deck-builder in C++26 on SDL3 + +## Getting started + +With direnv: + +```sh +direnv allow # loads the devShell on cd +cmake --preset debug +cmake --build --preset debug +./cmake-build-debug/bin/siege_deck +``` + +Without direnv, prefix commands with `nix develop --command`. + +`siege_deck --frames N` renders N frames and exits, so the smoke test can run +unattended from a script or CI. + +## Layout + +| Path | What it is | +|---------------------|------------------------------------------------------| +| `flake.nix` | devShells: `default` (clang), `gcc` | +| `CMakeLists.txt` | dependency pins + the single executable target | +| `cmake/Cpm.cmake` | CPM bootstrap — nixpkgs copy, else pinned download | +| `cmake/ImGui.cmake` | defines `imgui::imgui` from either nixpkgs or source | +| `Source/` | `Common.h` (vocabulary types), `Pch.h`, `Main.cpp` | +| `Assets/` | copied next to the executable after each build | + +## How dependencies resolve + +Every dependency is declared once, as a `CPMAddPackage` call, and resolves two +different ways depending on where you build: + +- **Inside the devShell** — `CPM_USE_LOCAL_PACKAGES=ON` makes each call try + `find_package` first, and all of them hit nixpkgs. Nothing is downloaded and + nothing is rebuilt; configure takes under a second. +- **Anywhere else** (Windows, CI, a machine without nix) — CPM fetches and + builds each one from its pinned tag. + +Both paths are pinned to the *same* version on purpose. A dependency that +differs between "on my machine" and "in the nix shell" is the class of bug +this arrangement exists to prevent, so bumping one means bumping the other — +or waiting for nixpkgs to catch up. + +Two dependencies don't fit the pattern cleanly, and the comments in +`CMakeLists.txt` and `cmake/ImGui.cmake` explain why: Boost exposes +`Boost::type_index` only in the modular CMake build, so both sides target the +header-only aggregate `Boost::headers` instead; and Dear ImGui ships no +`CMakeLists.txt` upstream at all, so `cmake/ImGui.cmake` builds it by hand +when nixpkgs isn't supplying it. + +## CLion + +CMake reloads need the devShell environment, and CLion has to be told where to +get it. Once per machine: + +1. **Settings → Build, Execution, Deployment → Toolchains**: add a System + toolchain (e.g. `siege-deck (nix)`), then **Add environment → From file** + and choose `cmake/clion-env.sh`. CLion sources that file before every CMake + reload, build, run and debug session, so all of them get the flake's + compiler, CMake, `CMAKE_PREFIX_PATH` and CPM settings. +2. **Settings → Build, Execution, Deployment → CMake**: enable the `debug` and + `release` profiles that come from `CMakePresets.json`, set their toolchain + to the one from step 1, and delete the plain `Debug` profile CLion creates + by itself. That profile shares `cmake-build-debug` with the `debug` preset. + +The file loads the shell through direnv, so run `direnv allow` once in the +checkout first. + +The `intellij-direnv` plugin can't stand in for this. It only merges variables +into Run/Debug configurations, and a CMake reload isn't one, so with the plugin +alone CLion configures with no nix environment at all. It also writes a +snapshot of nix store paths into every run configuration, which goes stale on +the next `nix flake update`. The toolchain environment already covers runs, so +the plugin isn't needed. + +To see what CLion will inherit, sourced the way CLion does it (through your +login shell): + +```sh +"$SHELL" -l -i -c 'source cmake/clion-env.sh 2>/dev/null; command -v cmake; echo $CXX; echo $CPM_CMAKE_PATH' +``` + +### Launching from a terminal + +`nix develop --command clion .` also works, but only because two system-level +breakages were fixed in `~/homelab/hosts/terra/configuration.nix` — neither is +specific to this project, and both made every Toolbox IDE unlaunchable outside +the Toolbox GUI: + +- `programs.nix-ld.libraries` was unset, so nix-ld's minimal default applied + and carried no X11, freetype, wayland or xkbcommon. The bundled JBR died on + `libX11.so.6: cannot open shared object file`. +- `services.envfs.enable` now serves `/bin` and `/usr/bin` from the caller's + PATH, so the `#!/bin/bash` shebang Toolbox writes into its shims resolves. + NixOS ships only `/bin/sh`, so those shims previously failed everywhere. + +Both need a `nixos-rebuild switch` to take effect. This flake deliberately +carries no IDE wrapper of its own. + +### clangd + +The shell regenerates `.clangd` on every entry, pinning the compiler's real +system include paths. Without it clangd cannot find the standard library on +NixOS: those paths are injected by the cc-wrapper through `NIX_CFLAGS_COMPILE` +at compile time, and clangd only ever reads `compile_commands.json`, so the +build succeeds while every `#include <...>` goes red. The file is generated, +gitignored, and rewritten to match whichever shell you entered. diff --git a/Source/Common.h b/Source/Common.h new file mode 100644 index 0000000..a5cbee7 --- /dev/null +++ b/Source/Common.h @@ -0,0 +1,60 @@ +// +// Created by darman on 9/5/26. +// + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +using string = std::string; + +// Type aliases +using int8 = int8_t; +using int16 = int16_t; +using int32 = int32_t; +using int64 = int64_t; + +using uint8 = uint8_t; +using uint16 = uint16_t; +using uint32 = uint32_t; +using uint64 = uint64_t; + +template using Vector = std::vector; +template using Set = std::unordered_set; +template using Map = std::unordered_map; +template using Optional = std::optional; +constexpr std::nullopt_t None = std::nullopt; + +template using Ref = std::shared_ptr; +template constexpr Ref MakeRef(Args&&... args) +{ + return std::make_shared(std::forward(args)...); +} + +template > constexpr Ref MakeRef(T* ptr, D deleter = D()) +{ + return Ref(ptr, std::move(deleter)); +} + +template > using UniqueRef = std::unique_ptr; +template , typename... Args> +constexpr UniqueRef MakeUniqueRef(Args&&... args) +{ + return std::make_unique(std::forward(args)...); +} + +template constexpr string TypeName() +{ + return boost::typeindex::type_id().pretty_name(); +} diff --git a/Source/Main.cpp b/Source/Main.cpp new file mode 100644 index 0000000..7022895 --- /dev/null +++ b/Source/Main.cpp @@ -0,0 +1,6 @@ +#include + +int main(const int argc, char** argv) +{ + std::cout << "Hello World!" << std::endl; +} diff --git a/Source/Pch.h b/Source/Pch.h new file mode 100644 index 0000000..c816bb1 --- /dev/null +++ b/Source/Pch.h @@ -0,0 +1,7 @@ +// +// Created by darman on 9/5/26. +// + +#pragma once + +#include "Common.h" diff --git a/cmake/Cpm.cmake b/cmake/Cpm.cmake new file mode 100644 index 0000000..ef74707 --- /dev/null +++ b/cmake/Cpm.cmake @@ -0,0 +1,34 @@ +# Bootstraps CPM.cmake. +# +# Inside the nix devShell CPM_CMAKE_PATH points at the nixpkgs-provided copy, +# so a fresh configure touches the network zero times. Everywhere else this +# falls back to the pinned release download, byte-identical to that copy +# (verified: both hash to a609e875...), so the two paths cannot diverge. + +set(CPM_DOWNLOAD_VERSION 0.42.3) +set(CPM_DOWNLOAD_HASH + SHA256=a609e875fd532b067174250f6abbc3dac22fe2d64869783fb1e80bda1625c844) + +# CPM caches its own path in CPM_DIRECTORY, and when a later include comes from +# a different path it assumes an enclosing project already loaded CPM, then +# returns without defining CPMAddPackage. The two copies above live at +# different paths (as does every nix store revision of the first), so a build +# dir configured both inside and outside the devShell broke with "Unknown CMake +# command". Nothing loads CPM before the top-level project, so a cached value +# here is always stale. +if (PROJECT_IS_TOP_LEVEL) + unset(CPM_DIRECTORY CACHE) +endif () + +if (DEFINED ENV{CPM_CMAKE_PATH} AND EXISTS "$ENV{CPM_CMAKE_PATH}") + message(STATUS "CPM: using $ENV{CPM_CMAKE_PATH}") + include("$ENV{CPM_CMAKE_PATH}") +else () + set(CPM_DOWNLOAD_LOCATION "${CMAKE_CURRENT_SOURCE_DIR}/cmake/CPM.cmake") + file( + DOWNLOAD + "https://github.com/cpm-cmake/CPM.cmake/releases/download/v${CPM_DOWNLOAD_VERSION}/CPM.cmake" + "${CPM_DOWNLOAD_LOCATION}" + EXPECTED_HASH ${CPM_DOWNLOAD_HASH}) + include("${CPM_DOWNLOAD_LOCATION}") +endif () diff --git a/cmake/ImGui.cmake b/cmake/ImGui.cmake new file mode 100644 index 0000000..22a28e8 --- /dev/null +++ b/cmake/ImGui.cmake @@ -0,0 +1,61 @@ +# Defines the imgui::imgui target. +# +# Dear ImGui is the one dependency the hybrid strategy can't handle uniformly, +# because upstream ships no CMakeLists at all. The two paths differ in more +# than provenance: +# +# nixpkgs — a real CMake package (imgui::imgui), backends already compiled +# in, headers installed flat: . +# upstream — a bare source drop; the backends are loose .cpp files under +# backends/ that every consumer is expected to compile itself. +# +# Both ends up exporting imgui::imgui with backends/ on the include path, so +# game code writes `#include ` either way and never learns +# which one it got. + +find_package(imgui CONFIG QUIET) + +if (imgui_FOUND) + message(STATUS "ImGui: using system package ${imgui_DIR}") + + # nixpkgs can be built with the GLFW/OpenGL3 backends instead of the SDL3 + # ones, in which case linking succeeds and the first ImGui_ImplSDL3_* + # call fails to resolve. Catch that here rather than at link time. + find_path(SD_IMGUI_SDL3_BACKEND imgui_impl_sdl3.h + HINTS ${imgui_INCLUDE_DIRS} PATH_SUFFIXES imgui backends) + if (NOT SD_IMGUI_SDL3_BACKEND) + message(FATAL_ERROR + "The installed Dear ImGui has no SDL3 backend (imgui_impl_sdl3.h). " + "Inside nix this means the imgui override in flake.nix regressed; " + "outside it, rebuild imgui with the SDL3 + SDL3_Renderer backends.") + endif () + + return() +endif () + +message(STATUS "ImGui: building from source via CPM") + +CPMAddPackage( + NAME imgui + GITHUB_REPOSITORY ocornut/imgui + GIT_TAG v1.91.4 + DOWNLOAD_ONLY YES) + +add_library(imgui STATIC + ${imgui_SOURCE_DIR}/imgui.cpp + ${imgui_SOURCE_DIR}/imgui_draw.cpp + ${imgui_SOURCE_DIR}/imgui_tables.cpp + ${imgui_SOURCE_DIR}/imgui_widgets.cpp + ${imgui_SOURCE_DIR}/imgui_demo.cpp + ${imgui_SOURCE_DIR}/backends/imgui_impl_sdl3.cpp + ${imgui_SOURCE_DIR}/backends/imgui_impl_sdlrenderer3.cpp) + +# SYSTEM so ImGui's headers stop tripping this project's own warning flags — +# the nixpkgs path gets that for free, this one has to ask. +target_include_directories(imgui SYSTEM PUBLIC + ${imgui_SOURCE_DIR} + ${imgui_SOURCE_DIR}/backends) + +target_link_libraries(imgui PUBLIC SDL3::SDL3) + +add_library(imgui::imgui ALIAS imgui) diff --git a/cmake/clion-env.sh b/cmake/clion-env.sh new file mode 100644 index 0000000..a045daf --- /dev/null +++ b/cmake/clion-env.sh @@ -0,0 +1,28 @@ +# CLion toolchain environment file: Settings > Build, Execution, Deployment > +# Toolchains > Add environment > From file. CLion sources it before CMake, +# builds, runs and debugging, so all of them see the nix devShell. +# +# The direnv plugin cannot do this on its own: it only writes variables into +# Run/Debug configurations, and a CMake reload is not one. +# +# direnv searches upward for .envrc, so export from this file's directory +# instead of relying on whatever working directory CLion sources it from. +# CLion sources through the user's login shell ($SHELL -l -i -c), which +# shapes the rest: +# - The file's own path has to be found in zsh as well as bash. The zsh +# spelling sits inside eval so other shells never parse it. +# - No shell `cd`. An interactive zsh carries direnv's chpwd hook, which +# loads the env inside the cd subshell and leaves `direnv export` with +# nothing to print. `env -C` changes directory in the child instead. +if [ -n "${BASH_SOURCE:-}" ]; then + _sd_self=$BASH_SOURCE +elif [ -n "${ZSH_VERSION:-}" ]; then + eval '_sd_self=${(%):-%x}' +fi + +if [ -n "${_sd_self:-}" ]; then + eval "$(env -C "$(dirname "$_sd_self")" direnv export bash)" +else + eval "$(direnv export bash)" +fi +unset _sd_self diff --git a/flake.lock b/flake.lock new file mode 100644 index 0000000..bbc6268 --- /dev/null +++ b/flake.lock @@ -0,0 +1,27 @@ +{ + "nodes": { + "nixpkgs": { + "locked": { + "lastModified": 1788404924, + "narHash": "sha256-lhEhY8X5EgkQ/eg6IFz4cc8jRuSYSvnxx1al7d1dvZ0=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "0968519e14f7aa7d3e9b389682bd74d2b51c8ce8", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixos-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "root": { + "inputs": { + "nixpkgs": "nixpkgs" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000..03244e7 --- /dev/null +++ b/flake.nix @@ -0,0 +1,151 @@ +{ + description = "siege-deck — a from-scratch SDL3 tower defense in C++26"; + + # Same channel the NixOS config tracks, so the shell's SDL3/mesa match the + # system's GL/Wayland drivers instead of drifting a release apart. + inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; + + outputs = { self, nixpkgs }: + let + systems = [ "x86_64-linux" ]; + forAllSystems = f: + nixpkgs.lib.genAttrs systems (system: f nixpkgs.legacyPackages.${system}); + + mkGameShell = pkgs: stdenv: + let + lib = pkgs.lib; + + # Dear ImGui in nixpkgs builds ONLY the GLFW + OpenGL3 backends, + # which are dead weight here — this game draws through SDL_Renderer, + # not GL, so the stock package ships no usable impl at all. The + # override swaps them for imgui_impl_sdl3 + imgui_impl_sdlrenderer3 + # and drops the glfw dependency. Headers land flat in include/, so + # it's `#include `, NOT `` — see + # cmake/ImGui.cmake, which papers over that difference for the + # CPM-from-source path. + imgui = pkgs.imgui.override { + IMGUI_BUILD_GLFW_BINDING = false; + IMGUI_BUILD_OPENGL3_BINDING = false; + IMGUI_BUILD_SDL3_BINDING = true; + IMGUI_BUILD_SDL3_RENDERER_BINDING = true; + }; + + # Everything CPM would otherwise download and rebuild from source. + # CPM_USE_LOCAL_PACKAGES (exported below) makes CPMAddPackage try + # find_package first, so inside this shell these are used as-is and + # only what nixpkgs lacks gets fetched. + deps = (with pkgs; [ + sdl3 + sdl3-image + sdl3-ttf + sdl3-mixer + spdlog + glm + entt + boost + ]) ++ [ imgui ]; + + tools = with pkgs; [ + cmake + ninja + pkg-config + + # CPM.cmake itself, so a fresh configure needs no network at all. + cpm-cmake + + # clangd / clang-format / clang-tidy. Kept separate from the + # compiler so the gcc shell below gets the same tooling. + clang-tools + + gdb + ccache + ]; + in + (pkgs.mkShell.override { inherit stdenv; }) { + packages = tools; + buildInputs = deps; + + # CMake's own find_package search path. The cmake setup hook already + # populates this from buildInputs, but spelling it out keeps the + # shell honest if that hook ever changes, and makes it greppable when + # a find_package unexpectedly misses. + CMAKE_PREFIX_PATH = lib.makeSearchPathOutput "dev" "" deps; + + shellHook = '' + # --- CPM: prefer nixpkgs, fall back to downloading ------------- + # The CMakeLists keeps game-from-scratch's CPMAddPackage calls + # verbatim so the tree still configures on a machine without nix + # (Windows, a fresh checkout, CI). These two variables are the only + # thing that changes inside the shell: CPM resolves through + # find_package first, and anything it does have to fetch is cached + # outside the build dir so `rm -rf cmake-build-*` stays cheap. + export CPM_USE_LOCAL_PACKAGES=ON + export CPM_SOURCE_CACHE="''${XDG_CACHE_HOME:-$HOME/.cache}/CPM" + export CPM_CMAKE_PATH="${pkgs.cpm-cmake}/share/cpm/CPM.cmake" + + export CMAKE_GENERATOR=Ninja + + # CMAKE_PREFIX_PATH above lists only direct deps. nixpkgs' own cmake also + # reads NIXPKGS_CMAKE_PREFIX_PATH, which carries propagated ones (fmt for + # spdlog); any other cmake, such as CLion's bundled one, does not, so + # spdlog's find_dependency(fmt) failed there and CPM quietly downloaded + # spdlog instead. Appending it gives every cmake the same search path. + if [ -n "$NIXPKGS_CMAKE_PREFIX_PATH" ]; then + export CMAKE_PREFIX_PATH="$CMAKE_PREFIX_PATH:$NIXPKGS_CMAKE_PREFIX_PATH" + fi + + # --- clangd: teach it where the standard library lives --------- + # On NixOS the C++ system headers are injected by the cc-wrapper + # through NIX_CFLAGS_COMPILE at *compile* time. clangd never sees + # that variable — it only reads compile_commands.json, where the + # flags are absent — so every std include goes red while the build + # itself succeeds. Asking the real compiler for its search list and + # pinning it into .clangd fixes every editor at once (CLion's + # bundled clangd, VS Code, nvim) rather than per-IDE + # --query-driver settings, which CLion in particular makes awkward. + _sd_clangd=$(mktemp) + { + echo "# Generated by the nix devShell on entry. Do not edit; see flake.nix." + echo "CompileFlags:" + echo " Add:" + $CXX -E -x c++ - -v &1 \ + | sed -n '/^#include <\.\.\.>/,/^End of search list/p' \ + | grep '^ ' | sed 's/^ *//' \ + | while read -r dir; do echo " - -isystem$dir"; done + echo " Remove:" + # CLion/CMake hand clangd flags its parser rejects outright. + echo " - -fno-keep-inline-dllexport" + } > "$_sd_clangd" + if ! cmp -s "$_sd_clangd" .clangd; then + mv "$_sd_clangd" .clangd + else + rm -f "$_sd_clangd" + fi + unset _sd_clangd + + echo "siege-deck devshell — $($CXX --version | head -1)" + echo " cmake --preset debug configure (Ninja, compile_commands.json)" + echo " cmake --build --preset debug" + echo " ./cmake-build-debug/bin/siege_deck" + echo + echo " CLion: toolchain environment file cmake/clion-env.sh (README)" + echo " nix develop .#gcc same shell, gcc instead of clang" + ''; + }; + in + { + devShells = forAllSystems (pkgs: { + # clang by default: CLion's bundled clangd parses with clang + # semantics, so building with the same compiler removes the whole + # class of "red in the editor, green in the build" mismatches — worse + # than usual on NixOS, where gcc's include paths are non-standard. + # nixpkgs' clang links libstdc++, so this stays ABI-compatible with + # the nixpkgs-built SDL3/spdlog/imgui above. + default = mkGameShell pkgs pkgs.clangStdenv; + + # Second opinion on diagnostics, and a check that the code isn't + # accidentally leaning on a clang extension. + gcc = mkGameShell pkgs pkgs.stdenv; + }); + }; +}