Compare commits

...

No commits in common. "ci-dev" and "main" have entirely different histories.
ci-dev ... main

27 changed files with 1257 additions and 1413 deletions

View File

@ -1,6 +0,0 @@
on: [push]
jobs:
test:
runs-on: docker
steps:
- run: echo All Good

3
.gitignore vendored
View File

@ -1,2 +1 @@
zig-out/ result
zig-cache/

19
agenix-config-module.nix Normal file
View File

@ -0,0 +1,19 @@
{
age.secrets.samsehu_DUCK_DNS_TOKEN = {
file = ./secrets/samsehu_DUCK_DNS_TOKEN.age;
owner = "dynamicdns";
group = "dynamicdns";
};
age.secrets.LLDAP_ADMIN_PASSWORD = {
file = ./secrets/samsehu_LLDAP_ADMIN_PASSWORD.age;
owner = "lldap";
group = "lldap";
};
age.secrets.DEX_ENVIRONMENT_FILE.file = ./secrets/samsehu_DEX_ENVIRONMENT_FILE.age;
age.secrets.OIDC_APP_SECRET_HEADSCALE = {
file = ./secrets/samsehu_OIDC_APP_SECRET_HEADSCALE.age;
owner = "headscale";
group = "headscale";
};
age.secrets.FORGEJO_ACTIONS_RUNNER.file = ./secrets/samsehu_FORGEJO_ACTIONS_RUNNER.age;
}

View File

@ -1,69 +0,0 @@
const std = @import("std");
// Although this function looks imperative, note that its job is to
// declaratively construct a build graph that will be executed by an external
// runner.
pub fn build(b: *std.Build) void {
// Standard target options allows the person running `zig build` to choose
// what target to build for. Here we do not override the defaults, which
// means any target is allowed, and the default is native. Other options
// for restricting supported target set are available.
const target = b.standardTargetOptions(.{});
// Standard optimization options allow the person running `zig build` to select
// between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. Here we do not
// set a preferred release mode, allowing the user to decide how to optimize.
const optimize = b.standardOptimizeOption(.{});
const seizer = b.dependency("seizer", .{
.target = target,
.optimize = optimize,
});
const exe = b.addExecutable(.{
.name = "seizer-solitaire",
.root_source_file = .{ .path = "src/main.zig" },
.target = target,
.optimize = optimize,
});
exe.root_module.addImport("seizer", seizer.module("seizer"));
b.installArtifact(exe);
// additionally generate an HTML file with the wasm module embedded when we use the wasi target
if (target.result.os.tag == .wasi) {
exe.wasi_exec_model = .reactor;
const bundle_webpage_exe = seizer.artifact("bundle-webpage");
const bundle_webpage = b.addRunArtifact(bundle_webpage_exe);
bundle_webpage.addArtifactArg(exe);
const install_html = b.addInstallFile(bundle_webpage.captureStdOut(), "www/seizer-solitaire.html");
b.getInstallStep().dependOn(&install_html.step);
}
const run_cmd = b.addRunArtifact(exe);
run_cmd.step.dependOn(b.getInstallStep());
if (b.args) |args| {
run_cmd.addArgs(args);
}
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
const exe_unit_tests = b.addTest(.{
.root_source_file = .{ .path = "src/main.zig" },
.target = target,
.optimize = optimize,
});
exe_unit_tests.root_module.addImport("seizer", seizer.module("seizer"));
const run_exe_unit_tests = b.addRunArtifact(exe_unit_tests);
// Similar to creating the run step earlier, this exposes a `test` step to
// the `zig build --help` menu, providing a way for the user to request
// running the unit tests.
const test_step = b.step("test", "Run unit tests");
test_step.dependOn(&run_exe_unit_tests.step);
}

View File

@ -1,36 +0,0 @@
.{
.name = "seizer-solitaire",
// This is a [Semantic Version](https://semver.org/).
// In a future version of Zig it will be used for package deduplication.
.version = "0.0.0",
// This field is optional.
// This is currently advisory only; Zig does not yet do anything
// with this value.
//.minimum_zig_version = "0.11.0",
// This field is optional.
// Each dependency must either provide a `url` and `hash`, or a `path`.
// `zig build --fetch` can be used to fetch all dependencies of a package, recursively.
// Once all dependencies are fetched, `zig build` no longer requires
// internet connectivity.
.dependencies = .{
.seizer = .{
.url = "https://github.com/leroycep/seizer/archive/54a39bf2c2f867a2caa69c4a63fa4732ebc7ac71.tar.gz",
.hash = "12208d8ee636719b6b4fbb75014cfaa9aa0d9557d2ca4e160ad245825eaa20849b48",
},
},
.paths = .{
// This makes *all* files, recursively, included in this package. It is generally
// better to explicitly list the files and directories instead, to insure that
// fetching from tarballs, file system paths, and version control all result
// in the same contents hash.
"",
// For example...
//"build.zig",
//"build.zig.zon",
//"src",
//"LICENSE",
//"README.md",
},
}

780
configuration.nix Normal file
View File

@ -0,0 +1,780 @@
# Edit this configuration file to define what should be installed on
# your system. Help is available in the configuration.nix(5) man page, on
# https://search.nixos.org/options and in the NixOS manual (`nixos-help`).
{ config, lib, pkgs, ... }:
{
imports =
[ # Include the results of the hardware scan.
./hardware/samsehu.nix
./samsehu/matrix-conduit.nix
];
# Use the `systemd-boot` boot loader
boot.loader.systemd-boot.enable = true;
# Added following instructions of openzfs configuration
# randomly generated with `head -c4 /dev/urandom | od -A none -t x4`
networking.hostId = "3e52e44f";
boot.supportedFilesystems = [ "zfs" ];
boot.zfs.forceImportRoot = false;
boot.zfs.extraPools = [ "zroot" ];
networking.hostName = "samsehu"; # Define your hostname.
# Pick only one of the below networking options.
networking.networkmanager.enable = true; # Easiest to use and most distros use this by default.
# Set your time zone.
time.timeZone = "America/Denver";
# Select internationalisation properties.
i18n.defaultLocale = "en_US.UTF-8";
# console = {
# font = "Lat2-Terminus16";
# keyMap = "us";
# useXkbConfig = true; # use xkb.options in tty.
# };
# Enable CUPS to print documents.
services.printing.enable = true;
# Enable sound.
sound.enable = true;
hardware.pulseaudio.enable = true;
# Define a user account. Don't forget to set a password with passwd.
users.users.geemili = {
isNormalUser = true;
extraGroups = [ "wheel" ]; # Enable sudo for the user.
packages = with pkgs; [ ];
};
users.users.desttinghim = {
isNormalUser = true;
extraGroups = [ "wheel" ]; # Enable sudo for the user.
packages = with pkgs; [ ];
};
# List packages installed in system profile. To search, run:
# $ nix search wget
environment.systemPackages = with pkgs; [
helix
wget
git
juanfont-headscale.headscale # install to allow debugging/control of headscale using the CLI
# Plugins for cockpit
cockpit-tailscale
cockpit-zfs-manager
];
environment.variables = {
EDITOR = "hx";
VISUAL = "hx";
};
# List services that you want to enable:
# Enable the OpenSSH daemon.
services.openssh = {
enable = true;
settings.PasswordAuthentication = false;
settings.KbdInteractiveAuthentication = false;
settings.PermitRootLogin = "no";
};
services.cockpit = {
enable = true;
openFirewall = true;
settings = {
WebService = {
Origins = "https://cockpit.samsehu.perli.casa wss://cockpit.samsehu.perli.casa";
ProtocolHeader = "X-Forwarded-Proto";
LoginTo = false;
};
};
};
services.udisks2.enable = true;
# Multimedia group
users.groups.multimedia = {};
users.users.lidarr.extraGroups = [ "aria2" ];
users.users.radarr.extraGroups = [ "aria2" ];
users.users.readarr.extraGroups = [ "aria2" ];
users.users.sonarr.extraGroups = [ "aria2" ];
users.users.bazarr.extraGroups = [ "multimedia" "aria2" ];
systemd.tmpfiles.rules = [
"d /zroot/media 0770 - multimedia - -"
];
services.jellyfin = { enable = true; group = "multimedia"; };
services.lidarr = { enable = true; group = "multimedia"; };
services.radarr = { enable = true; group = "multimedia"; };
services.readarr = { enable = true; group = "multimedia"; };
services.sonarr = { enable = true; group = "multimedia"; };
services.bazarr = { enable = true; user = "bazarr"; group = "multimedia"; };
services.prowlarr = { enable = true; };
users.users.komga.extraGroups = [ "multimedia" ];
services.komgaCustom = {
enable = true;
group = "multimedia";
settings = {
spring.security.oauth2.client = {
registration.dex = {
provider = "dex";
client-id = "komga";
client-secret = "insecure_secret";
client-name = "Komga";
scope = "openid,email";
authorization-grant-type = "authorization_code";
redirect-uri = "{baseUrl}/{action}/oauth2/code/{registrationId}";
};
provider.dex = {
user-name-attribute = "sub";
issuer-uri = "https://dex.samsehu.perli.casa";
};
};
};
};
systemd.services."netns@" = {
description = "%I network namespace";
before = [ "network.target" ];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
ExecStart = "${pkgs.iproute}/bin/ip netns add %I";
ExecStop = "${pkgs.iproute}/bin/ip netns del %I";
};
};
systemd.services.wg = {
description = "wg network interface";
bindsTo = [ "netns@wg.service" ];
requires = [ "network-online.target" ];
after = [ "netns@wg.service" ];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
ExecStart = with pkgs; writers.writeBash "wg-up" ''
set -e
# Create wireguard
${iproute}/bin/ip link add wg0 type wireguard
# move to wg network namespace
${iproute}/bin/ip link set wg0 netns wg
# Connect to vpn
${iproute}/bin/ip -n wg address add 10.65.64.220/32 dev wg0
${iproute}/bin/ip -n wg -6 address add fc00:bbbb:bbbb:bb01::2:40db/128 dev wg0
${iproute}/bin/ip netns exec wg ${wireguard-tools}/bin/wg setconf wg0 /var/wireguard-keys/chief-frog.conf
# Open network
${iproute}/bin/ip -n wg link set dev lo up
${iproute}/bin/ip -n wg link set wg0 up
${iproute}/bin/ip -n wg route add default dev wg0
${iproute}/bin/ip -n wg -6 route add default dev wg0
'';
ExecStop = with pkgs; writers.writeBash "wg-down" ''
${iproute}/bin/ip -n wg route del default dev wg0
${iproute}/bin/ip -n wg -6 route del default dev wg0
${iproute}/bin/ip -n wg link del wg0
'';
};
};
services.aria2 = {
enable = true;
extraArguments = "--bt-external-ip=10.65.64.220 --input-file=/var/lib/aria2/aria2.session --save-session-interval=60";
};
systemd.services."aria2" = {
bindsTo = [ "netns@wg.service" ];
requires = [ "network-online.target" ];
after = [ "wg.service" ];
serviceConfig = {
NetworkNamespacePath = "/var/run/netns/wg";
};
};
# reverse proxy the aria2 rpc from the `wg` network namespace to a unix domain socket
systemd.services."aria2-unix-domain-rpc" = {
bindsTo = [ "aria2.service" ];
after = [ "aria2.service" ];
wantedBy = [ "multi-user.target" ];
serviceConfig = {
NetworkNamespacePath = "/var/run/netns/wg";
Type = "simple";
User = config.services.caddy.user;
Group = config.services.caddy.group;
RuntimeDirectory = "aria2";
ExecStart = with pkgs; writers.writeBash "aria2-unix-domain-rpc-listener" ''
set -e
${socat}/bin/socat UNIX-LISTEN:/run/aria2/rpc.sock,reuseaddr,fork TCP:localhost:6800
'';
};
};
systemd.services.dex.serviceConfig = {
StateDirectory = "dex";
WorkingDirectory = "%S/dex";
};
services.dex = {
enable = true;
environmentFile = config.age.secrets.DEX_ENVIRONMENT_FILE.path;
settings = {
issuer = "https://dex.samsehu.perli.casa";
web.http = "127.0.0.1:5556";
storage = {
type = "sqlite3";
config.file = "./dex.db";
};
# services that can get a token from our dex instance
staticClients = [
{
id = "forgejo";
secretEnv = "OIDC_APP_SECRET_FORGEJO";
name = "Forgejo";
redirectURIs = [ "https://git.samsehu.perli.casa/user/oauth2/dex/callback" ];
}
{
id = "headscale";
secretEnv = "OIDC_APP_SECRET_HEADSCALE";
name = "Headscale";
redirectURIs = [ "https://headscale.samsehu.perli.casa/oidc/callback" ];
}
{
id = "nextcloud";
secret = "insecure_secret";
name = "Nextcloud";
redirectURIs = [ "https://nextcloud.samsehu.perli.casa/apps/oidc_login/oidc" "https://nextcloud.samsehu.perli.casa/index.php/apps/oidc_login/oidc" ];
}
{
id = "jellyfin";
secret = "insecure_secret";
name = "Jellyfin";
redirectURIs = [ "https://jellyfin.samsehu.perli.casa/sso/OID/redirect/dex" ];
}
{
id = "komga";
secret = "insecure_secret";
name = "Komga";
redirectURIs = [ "https://komga.samsehu.perli.casa/login/oauth2/code/dex" ];
}
];
# authentication sources
connectors = [
{
type = "ldap";
id = "lldap";
name = "LLDAP";
config = {
host = "127.0.0.1:3890";
insecureNoSSL = true;
insecureSkipVerify = true;
startTLS = false;
bindDN = "uid=Immovable1809,ou=people,dc=samsehu,dc=perli,dc=casa";
bindPW = "$LLDAP_ADMIN_PASSWORD";
userSearch = {
baseDN = "ou=people,dc=samsehu,dc=perli,dc=casa";
username = "uid";
idAttr = "uid";
emailAttr = "mail";
nameAttr = "displayName";
preferredUsernameAttr = "uid";
};
groupSearch = {
baseDN = "ou=groups,dc=samsehu,dc=perli,dc=casa";
filter = "(objectClass=groupOfUniqueNames)";
userMatchers = [
{ userAttr = "DN"; groupAttr = "member"; }
];
nameAttr = "cn";
};
};
}
];
};
};
services.blocky = {
enable = true;
settings = {
ports.dns = 53;
ports.http = 4000;
upstreams = {
# Picks 2 random resolvers and returns answer from fastest one. Read docs for more info.
strategy = "parallel_best";
groups.default = [
# CloudFlare
"https://one.one.one.one/dns-query"
# OpenDNS
"https://doh.opendns.com/dns-query"
# Google
"8.8.8.8"
"8.8.4.4"
"2001:4860:4860::8888"
"2001:4860:4860::8844"
# Comcast/Our ISP
"75.75.75.75"
"75.75.76.76"
];
};
bootstrapDns = {
upstream = "https://one.one.one.one/dns-query";
ips = [ "1.1.1.1" "1.0.0.1" ];
};
blocking = {
blackLists = {
ads = ["https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts"];
};
clientGroupsBlock = {
default = [ "ads" ];
};
};
customDNS = {
rewrite = {
"cockpit.samsehu.perli.casa" = "samsehu.perli.casa";
"git.samsehu.perli.casa" = "samsehu.perli.casa";
"nextcloud.samsehu.perli.casa" = "samsehu.perli.casa";
};
mapping = {
"samsehu.perli.casa" = "192.168.0.69";
};
};
};
};
services.forgejo = {
enable = true;
lfs.enable = true;
settings = {
server.ROOT_URL = "https://git.samsehu.perli.casa/";
server.HTTP_ADDR = "127.0.0.1";
actions.ENABLED = true;
};
};
virtualisation.docker = {
enable = true;
};
services.gitea-actions-runner = {
package = pkgs.forgejo-actions-runner;
instances.default = {
enable = true;
name = "monolith";
url = "https://git.samsehu.perli.casa";
tokenFile = config.age.secrets.FORGEJO_ACTIONS_RUNNER.path;
labels = [ ];
};
};
# lldap LDAP authentication server
users.users.lldap = {
# allocates the `uid` in the range 100-999, which indicates to software like login managers that it should not be displayed to the user.
isSystemUser = true;
group = "lldap";
};
users.groups.lldap = {};
services.lldap = {
enable = true;
settings = {
ldap_base_dn = "dc=samsehu,dc=perli,dc=casa";
# Sets the root administrator's user name
ldap_user_dn = "Immovable1809";
http_host = "127.0.0.1";
};
environment = {
LLDAP_LDAP_USER_PASS_FILE = config.age.secrets.LLDAP_ADMIN_PASSWORD.path;
};
};
# Dynamic DNS through duck dns
users.users.dynamicdns = {
# allocates the `uid` in the range 100-999, which indicates to software like login managers that it should not be displayed to the user.
isSystemUser = true;
group = "dynamicdns";
};
users.groups.dynamicdns = {};
systemd.services.dynamic-dns-updater = {
serviceConfig.User = "dynamicdns";
path = [ pkgs.curl ];
script = "curl --silent --url-query domains=samsehuperli --url-query token@${config.age.secrets.samsehu_DUCK_DNS_TOKEN.path} https://www.duckdns.org/update";
startAt = "hourly";
};
systemd.timers.dynamic-dns-updater = {
timerConfig.RandomizedDelaySec = "15m";
};
systemd.services.dynamic-dns-updater6 = {
serviceConfig.User = "dynamicdns";
path = [ pkgs.curl ];
script = "curl --silent --url-query domains=samsehuperli --url-query token@${config.age.secrets.samsehu_DUCK_DNS_TOKEN.path} --url-query ipv6=$(ip -j -6 addr show scope global | jq -r .[0].addr_info.[0].local) https://www.duckdns.org/update";
startAt = "hourly";
};
systemd.timers.dynamic-dns-updater6 = {
timerConfig.RandomizedDelaySec = "15m";
};
# Next cloud setup
services.nginx.enable = false;
services.nextcloud = {
enable = true;
hostName = "nextcloud.samsehu.perli.casa";
config.adminpassFile = "/var/nextcloud-admin-pass";
config.trustedProxies = [
"100.64.0.3"
];
caching.apcu = true;
# OIDC configuration
extraOptions = {
overwritewebroot = "/";
allow_user_to_change_display_name = false;
lost_password_link = "disabled";
oidc_login_provider_url = "https://dex.samsehu.perli.casa";
oidc_login_client_id = "nextcloud";
oidc_login_client_secret = "insecure_secret";
oidc_login_auto_redirect = true;
oidc_login_end_session_redirect = false;
oidc_login_button_text = "Log in with Dex";
oidc_login_hide_password_form = false;
oidc_login_use_id_token = true;
config.oidc_login_attributes = {
"id" = "preferred_username";
"name" = "name";
"mail" = "mail";
"groups" = "groups";
};
oidc_login_default_group = "oidc";
oidc_login_use_external_storage = true;
oidc_login_scope = "openid profile email groups";
oidc_login_proxy_ldap = false;
oidc_login_disable_registration = false;
oidc_login_redir_fallback = false;
oidc_login_alt_login_page = "assets/login.php";
oidc_login_tls_verify = true;
oidc_create_groups = false;
oidc_login_webdav_enabled = false;
oidc_login_password_authentication = false;
oidc_login_public_key_caching_time = 86400;
oidc_login_min_time_between_jwks_requests = 10;
oidc_login_well_known_caching_time = 86400;
oidc_login_update_avatar = false;
};
# Auto update apps
autoUpdateApps.enable = true;
extraApps = {
oidc_login = pkgs.fetchNextcloudApp {
appName = "OpenID Connect Login";
appVersion = "3.0.2";
sha256 = "sha256-cN5azlThKPKRVip14yfUNR85of5z+N6NVI7sg6pSGQI=";
license = "agpl3Plus";
url = "https://github.com/pulsejet/nextcloud-oidc-login/releases/download/v3.0.2/oidc_login.tar.gz";
};
gpoddersync = pkgs.fetchNextcloudApp {
appName = "Gpodder Sync";
appVersion = "3.8.2";
sha256 = "sha256-eeBvRZUDVIaym0ngfPD2d7aY3SI/7lPWkrYPnqSh5Kw=";
license = "agpl3Plus";
url = "https://github.com/thrillfall/nextcloud-gpodder/releases/download/3.8.2/gpoddersync.tar.gz";
};
};
};
services.phpfpm.pools.nextcloud.settings = {
"listen.owner" = config.services.caddy.user;
"listen.group" = config.services.caddy.group;
};
# Reverse proxy with Caddy
services.caddy = {
enable = true;
globalConfig = ''
email "fresh.car0178@geemili.xyz"
'';
virtualHosts."lldap.samsehu.perli.casa".extraConfig = ''
@connected_via_tailscale remote_ip 100.64.0.0/10 fd7a:115c:a1e0::/48
handle @connected_via_tailscale {
reverse_proxy localhost:17170
}
respond 403
'';
virtualHosts."headscale.samsehu.perli.casa".extraConfig = ''
reverse_proxy localhost:64639
'';
virtualHosts."cockpit.samsehu.perli.casa".extraConfig = ''
@connected_via_tailscale remote_ip 100.64.0.0/10 fd7a:115c:a1e0::/48
handle @connected_via_tailscale {
reverse_proxy localhost:9090
}
respond 403
'';
virtualHosts."git.samsehu.perli.casa".extraConfig = ''
reverse_proxy localhost:3000
'';
virtualHosts."jellyfin.samsehu.perli.casa".extraConfig = ''
reverse_proxy localhost:8096
'';
virtualHosts."nextcloud.samsehu.perli.casa".extraConfig = ''
@connected_via_tailscale remote_ip 100.64.0.0/10 fd7a:115c:a1e0::/48
handle @connected_via_tailscale {
# https://docs.nextcloud.com/server/27/admin_manual/issues/general_troubleshooting.html#service-discovery
redir /.well-known/carddav /remote.php/dav 301
redir /.well-known/caldav /remote.php/dav 301
root * ${config.services.nextcloud.package}
php_fastcgi unix/${config.services.phpfpm.pools.nextcloud.socket} {
root ${config.services.nextcloud.package}
capture_stderr
}
file_server
}
respond 403
'';
virtualHosts."dex.samsehu.perli.casa".extraConfig = ''
reverse_proxy localhost:5556
'';
virtualHosts."aria.samsehu.perli.casa".extraConfig = ''
@connected_via_tailscale remote_ip 100.64.0.0/10 fd7a:115c:a1e0::/48 private_ranges
handle @connected_via_tailscale {
handle /rpc {
reverse_proxy unix//run/aria2/rpc.sock
}
handle /jsonrpc {
reverse_proxy unix//run/aria2/rpc.sock
}
handle_path /ariang* {
root * ${pkgs.ariang}/share/ariang
file_server
}
redir / /ariang/#!/settings/rpc/set?protocol=wss&host=aria.samsehu.perli.casa&port=443&secret=YXJpYTJycGM=&interface=jsonrpc
}
respond 403
'';
virtualHosts."lid.arr.samsehu.perli.casa".extraConfig = ''
@connected_via_tailscale remote_ip 100.64.0.0/10 fd7a:115c:a1e0::/48
handle @connected_via_tailscale {
reverse_proxy localhost:8686
}
respond 403
'';
virtualHosts."rad.arr.samsehu.perli.casa".extraConfig = ''
@connected_via_tailscale remote_ip 100.64.0.0/10 fd7a:115c:a1e0::/48
handle @connected_via_tailscale {
reverse_proxy localhost:7878
}
respond 403
'';
virtualHosts."read.arr.samsehu.perli.casa".extraConfig = ''
@connected_via_tailscale remote_ip 100.64.0.0/10 fd7a:115c:a1e0::/48
handle @connected_via_tailscale {
reverse_proxy localhost:8787
}
respond 403
'';
virtualHosts."son.arr.samsehu.perli.casa".extraConfig = ''
@connected_via_tailscale remote_ip 100.64.0.0/10 fd7a:115c:a1e0::/48
handle @connected_via_tailscale {
reverse_proxy localhost:8989
}
respond 403
'';
virtualHosts."baz.arr.samsehu.perli.casa".extraConfig = ''
@connected_via_tailscale remote_ip 100.64.0.0/10 fd7a:115c:a1e0::/48
handle @connected_via_tailscale {
reverse_proxy localhost:6767
}
respond 403
'';
virtualHosts."prowl.arr.samsehu.perli.casa".extraConfig = ''
@connected_via_tailscale remote_ip 100.64.0.0/10 fd7a:115c:a1e0::/48
handle @connected_via_tailscale {
reverse_proxy localhost:9696
}
respond 403
'';
virtualHosts."komga.samsehu.perli.casa".extraConfig = ''
reverse_proxy localhost:25600
'';
};
# Headscale for access to the network while away from home
users.users.headscale = {
isSystemUser = true;
group = "headscale";
};
users.groups.headscale = {};
services.headscale = {
enable = true;
package = pkgs.juanfont-headscale.headscale;
settings = {
server_url = "https://headscale.samsehu.perli.casa";
listen_addr = "127.0.0.1:64639";
metrics_listen_addr = "127.0.0.1:64640";
tls_cert_path = null;
tls_key_path = null;
dns_config = {
override_local_dns = true;
nameservers = [ "100.64.0.3" ];
magic_dns = true;
base_domain = "ts.samsehu.perli.casa";
restricted_nameservers = {
"samsehu.perli.casa" = [ "100.64.0.3" ];
};
extra_records = [
{ name = "samsehu.perli.casa"; type = "A"; value = "100.64.0.3"; }
{ name = "cockpit.samsehu.perli.casa"; type = "A"; value = "100.64.0.3"; }
{ name = "git.samsehu.perli.casa"; type = "A"; value = "100.64.0.3"; }
{ name = "nextcloud.samsehu.perli.casa"; type = "A"; value = "100.64.0.3"; }
{ name = "lldap.samsehu.perli.casa"; type = "A"; value = "100.64.0.3"; }
{ name = "dex.samsehu.perli.casa"; type = "A"; value = "100.64.0.3"; }
{ name = "jellyfin.samsehu.perli.casa"; type = "A"; value = "100.64.0.3"; }
{ name = "aria.samsehu.perli.casa"; type = "A"; value = "100.64.0.3"; }
{ name = "lid.arr.samsehu.perli.casa"; type = "A"; value = "100.64.0.3"; }
{ name = "rad.arr.samsehu.perli.casa"; type = "A"; value = "100.64.0.3"; }
{ name = "read.arr.samsehu.perli.casa"; type = "A"; value = "100.64.0.3"; }
{ name = "son.arr.samsehu.perli.casa"; type = "A"; value = "100.64.0.3"; }
{ name = "baz.arr.samsehu.perli.casa"; type = "A"; value = "100.64.0.3"; }
{ name = "prowl.arr.samsehu.perli.casa"; type = "A"; value = "100.64.0.3"; }
{ name = "komga.samsehu.perli.casa"; type = "A"; value = "100.64.0.3"; }
];
};
oidc = {
issuer = "https://dex.samsehu.perli.casa";
client_id = "headscale";
client_secret_path = config.age.secrets.OIDC_APP_SECRET_HEADSCALE.path;
scope = [ "openid" "profile" "email" ];
};
acl_policy_path = pkgs.writeText "acl_policy.hujson" ''
{
"groups": {
"group:servers": [
"samsehu",
],
"group:admin": [
"geemili",
"desttinghim",
],
},
"acls": [
{
"action": "accept",
"src": ["group:admin"],
"dst": ["*:*"],
}
],
"ssh": [
{
"action": "accept",
"src": ["group:admin"],
"dst": ["group:servers"],
"users": ["group:admin", "geemili", "desttinghim", "forgejo"],
},
{
"action": "accept",
"src": ["geemili"],
"dst": ["geemili"],
"users": ["geemili"],
},
],
}
'';
};
};
services.tailscale.enable = true;
# Enable automatic upgrades
system.autoUpgrade.enable = true;
system.autoUpgrade.allowReboot = true;
system.autoUpgrade.flake = "git+http://127.0.0.1:3000/Twins/server-configuration.git";
# Enable automatic garbage collection
nix.gc = {
automatic = true;
dates = "weekly";
options = "--delete-older-than 30d";
};
nix.settings.trusted-users = [ "geemili" ];
# Open ports in the firewall.
networking.firewall.enable = true;
networking.firewall.allowedTCPPorts = [
# Blocky DNS
53
# Blocky API
4000
# Caddy HTTP and HTTPS
80
443
];
networking.firewall.allowedUDPPorts = [
# Blocky DNS
53
# mDNS
5353
# Headscale UDP port for STUN protocol
3478
];
# Use systemd-resolved and set networkmanager to allow mdns
services.resolved = {
enable = true;
extraConfig = ''
DNSStubListener=false
'';
};
networking.networkmanager.connectionConfig."connection.mdns" = 2; # 2 == yes
# Copy the NixOS configuration file and link it from the resulting system
# (/run/current-system/configuration.nix). This is useful in case you
# accidentally delete configuration.nix.
# system.copySystemConfiguration = true;
# This option defines the first version of NixOS you have installed on this particular machine,
# and is used to maintain compatibility with application data (e.g. databases) created on older NixOS versions.
#
# Most users should NEVER change this value after the initial install, for any reason,
# even if you've upgraded your system to a new NixOS release.
#
# This value does NOT affect the Nixpkgs version your packages and OS are pulled from,
# so changing it will NOT upgrade your system.
#
# This value being lower than the current NixOS release does NOT mean your system is
# out of date, out of support, or vulnerable.
#
# Do NOT change this value unless you have manually inspected all the changes it would make to your configuration,
# and migrated your data accordingly.
#
# For more information, see `man configuration.nix` or https://nixos.org/manual/nixos/stable/options#opt-system.stateVersion .
system.stateVersion = "23.11"; # Did you read the comment?
}

165
flake.lock Normal file
View File

@ -0,0 +1,165 @@
{
"nodes": {
"agenix": {
"inputs": {
"darwin": "darwin",
"home-manager": "home-manager",
"nixpkgs": [
"nixpkgs"
],
"systems": "systems"
},
"locked": {
"lastModified": 1716561646,
"narHash": "sha256-UIGtLO89RxKt7RF2iEgPikSdU53r6v/6WYB0RW3k89I=",
"owner": "ryantm",
"repo": "agenix",
"rev": "c2fc0762bbe8feb06a2e59a364fa81b3a57671c9",
"type": "github"
},
"original": {
"owner": "ryantm",
"repo": "agenix",
"type": "github"
}
},
"darwin": {
"inputs": {
"nixpkgs": [
"agenix",
"nixpkgs"
]
},
"locked": {
"lastModified": 1700795494,
"narHash": "sha256-gzGLZSiOhf155FW7262kdHo2YDeugp3VuIFb4/GGng0=",
"owner": "lnl7",
"repo": "nix-darwin",
"rev": "4b9b83d5a92e8c1fbfd8eb27eda375908c11ec4d",
"type": "github"
},
"original": {
"owner": "lnl7",
"ref": "master",
"repo": "nix-darwin",
"type": "github"
}
},
"flake-utils": {
"inputs": {
"systems": "systems_2"
},
"locked": {
"lastModified": 1701680307,
"narHash": "sha256-kAuep2h5ajznlPMD9rnQyffWG8EM/C73lejGofXvdM8=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "4022d587cbbfd70fe950c1e2083a02621806a725",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"home-manager": {
"inputs": {
"nixpkgs": [
"agenix",
"nixpkgs"
]
},
"locked": {
"lastModified": 1703113217,
"narHash": "sha256-7ulcXOk63TIT2lVDSExj7XzFx09LpdSAPtvgtM7yQPE=",
"owner": "nix-community",
"repo": "home-manager",
"rev": "3bfaacf46133c037bb356193bd2f1765d9dc82c1",
"type": "github"
},
"original": {
"owner": "nix-community",
"repo": "home-manager",
"type": "github"
}
},
"juanfont-headscale": {
"inputs": {
"flake-utils": "flake-utils",
"nixpkgs": [
"nixpkgs"
]
},
"locked": {
"lastModified": 1702219574,
"narHash": "sha256-sz+uQyyq/5YYDe5I44x5x2nvd48swAhNlInB8KZYvDo=",
"owner": "juanfont",
"repo": "headscale",
"rev": "6049ec758ca46b5c6ee7abba4f3d472fb1e2ffa6",
"type": "github"
},
"original": {
"owner": "juanfont",
"ref": "v0.23.0-alpha2",
"repo": "headscale",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1716633019,
"narHash": "sha256-xim1b5/HZYbWaZKyI7cn9TJCM6ewNVZnesRr00mXeS4=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "9d29cd266cebf80234c98dd0b87256b6be0af44e",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-23.11",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"agenix": "agenix",
"juanfont-headscale": "juanfont-headscale",
"nixpkgs": "nixpkgs"
}
},
"systems": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
},
"systems_2": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
}
},
"root": "root",
"version": 7
}

37
flake.nix Normal file
View File

@ -0,0 +1,37 @@
{
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-23.11";
agenix = {
url = "github:ryantm/agenix";
inputs.nixpkgs.follows = "nixpkgs";
};
juanfont-headscale = {
url = "github:juanfont/headscale/v0.23.0-alpha2";
inputs.nixpkgs.follows = "nixpkgs";
};
};
outputs = { self, nixpkgs, agenix, juanfont-headscale }: {
packages.x86_64-linux = let pkgs = import nixpkgs { system = "x86_64-linux"; }; in rec {
cockpit-tailscale = pkgs.callPackage ./pkgs/cockpit-tailscale.nix {};
cockpit-zfs-manager = pkgs.callPackage ./pkgs/cockpit-zfs-manager.nix {};
};
nixosConfigurations.samsehu = nixpkgs.lib.nixosSystem {
system = "x86_64-linux";
modules = [
({config, pkgs, ...}: {
nixpkgs.overlays = [ (final: prev: {
juanfont-headscale = juanfont-headscale.packages.${prev.system};
cockpit-tailscale = self.packages.${prev.system}.cockpit-tailscale;
cockpit-zfs-manager = self.packages.${prev.system}.cockpit-zfs-manager;
})];
})
./agenix-config-module.nix
./configuration.nix
./services/komga.nix
agenix.nixosModules.default
];
};
};
}

40
hardware/samsehu.nix Normal file
View File

@ -0,0 +1,40 @@
# Do not modify this file! It was generated by nixos-generate-config
# and may be overwritten by future invocations. Please make changes
# to /etc/nixos/configuration.nix instead.
{ config, lib, pkgs, modulesPath, ... }:
{
imports =
[ (modulesPath + "/installer/scan/not-detected.nix")
];
boot.initrd.availableKernelModules = [ "ehci_pci" "ahci" "usbhid" "usb_storage" "sd_mod" "sr_mod" ];
boot.initrd.kernelModules = [ ];
boot.kernelModules = [ "kvm-intel" ];
boot.extraModulePackages = [ ];
fileSystems."/" =
{ device = "/dev/disk/by-uuid/655a7659-3a38-40f9-8a52-55a163c0a000";
fsType = "ext4";
};
fileSystems."/boot" =
{ device = "/dev/disk/by-uuid/92B1-0F03";
fsType = "vfat";
};
swapDevices =
[ { device = "/dev/disk/by-uuid/c99c239b-5121-47e7-bdaa-5ac2daf6b7cf"; }
];
# Enables DHCP on each ethernet and wireless interface. In case of scripted networking
# (the default) this is the recommended approach. When using systemd-networkd it's
# still possible to use this option, but it's recommended to use it in conjunction
# with explicit per-interface declarations with `networking.interfaces.<interface>.useDHCP`.
networking.useDHCP = lib.mkDefault true;
# networking.interfaces.enp3s0.useDHCP = lib.mkDefault true;
# networking.interfaces.wlp0s29u1u6.useDHCP = lib.mkDefault true;
nixpkgs.hostPlatform = lib.mkDefault "x86_64-linux";
hardware.cpu.intel.updateMicrocode = lib.mkDefault config.hardware.enableRedistributableFirmware;
}

View File

@ -0,0 +1,15 @@
{ lib, stdenv, fetchzip }:
stdenv.mkDerivation rec {
pname = "cockpit-tailscale";
version = "0.0.6";
src = fetchzip {
url = "https://github.com/spotsnel/cockpit-tailscale/releases/download/v${version}/cockpit-tailscale-v${version}.tar.gz";
sha256 = "sha256-ESUZdt8GVEToyrv6UP8lOff67LsumdJAY1lXvC3fBaI=";
};
installPhase = ''
mkdir -p $out/share/cockpit
cp -r ${src} $out/share/cockpit/tailscale
'';
}

View File

@ -0,0 +1,17 @@
{ lib, stdenv, fetchFromGitHub }:
stdenv.mkDerivation rec {
pname = "cockpit-zfs-manager";
version = "816af25099fccc46a3bff5f831b39d98ef33d514";
src = fetchFromGitHub {
owner = "leroycep";
repo = "cockpit-zfs-manager";
rev = "${version}";
hash = "sha256-aLdsHHVVG6eJrvh3B4grZkDEbCZyDJjX2PuKkON8UcI=";
};
installPhase = ''
mkdir -p $out/share/cockpit
cp -r ${src}/zfs $out/share/cockpit/zfs
'';
}

View File

@ -0,0 +1,35 @@
# Edit this configuration file to define what should be installed on
# your system. Help is available in the configuration.nix(5) man page, on
# https://search.nixos.org/options and in the NixOS manual (`nixos-help`).
{ config, lib, pkgs, ... }:
let
homeserver-url = "samsehu.perli.casa";
in
{
# configure matrix-conduit as a server to host chat communications with end-to-end encryption
services.matrix-conduit = {
enable = true;
settings.global = {
server_name = "${homeserver-url}";
trusted_servers = [];
};
};
# Reverse proxy with Caddy
services.caddy.virtualHosts."${homeserver-url}" = {
serverAliases = [ "${homeserver-url}:8448" ];
extraConfig = ''
respond /.well-known/matrix/server `{ "m.server": "${homeserver-url}" }` 200
respond /.well-known/matrix/client `{ "m.homeserver": { "base_url": "https://${homeserver-url}" } }` 200
reverse_proxy /_matrix/* localhost:${toString config.services.matrix-conduit.settings.global.port}
'';
};
# Open ports in the firewall.
networking.firewall.allowedTCPPorts = [ 80 443 8448 ];
networking.firewall.allowedUDPPorts = [ 80 443 8448 ];
}

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,7 @@
age-encryption.org/v1
-> ssh-ed25519 yXNDbw n4kYnQIXz7rkvduE9oJ5XRxJfZJTUILuZ0r9s2+rW2g
OtBaRY+mIQrPXS0+rg99u2aElUeguwJPk+yoK5jO+Z0
-> ssh-ed25519 BTX+xA HIqdxxh8HwoDjfznL4caRc7HvkWYwn2S2h3bsHdaIRc
rOFUTg2u/S83YJpJTAzRfVL3rdot+4Z1orEGYV+4J58
--- 8BznEX1nb6xDa74lWVT2fgJo7MzFXLhnapbrU1Cqe70
v\šIµ˜Iì&FÖlŽ¦µg]pƒÁr/s—6±ÍÇck¯ÿm!éTññÔj¿ >(5-¦'•` ªxâ õ:Ø`<60>{ÁIxðw`“a7`

View File

@ -0,0 +1,8 @@
age-encryption.org/v1
-> ssh-ed25519 yXNDbw Juf0JMdCTwIPaPdK2llGdbtWG/4m5sD9iIuuvjM8HgM
EhOuE1WJjVHcf7UZYxCdT0sa78n5bzh6kH7e08oY6x4
-> ssh-ed25519 BTX+xA qBEbn6EWkOEO9PDmJCcYIWrEk652RumOCbaqIt4mVgU
kCFkAXKya+lQctHK+i6f66zemcuqKmI9+cwuJKOpBLg
--- cGf7Y9c6vyaFzKoZubiC3SelLhhm+r/iWAxqjLZWmRw
œLÇqáÅÄÞ°
DCëb‡ÖÐ3ÜßÉß(jÄ„œ&íxWÏn2ÜŸP )—z†œoK]>B6•yYÒ…õvw•%r«jKÇ7

View File

@ -0,0 +1,8 @@
age-encryption.org/v1
-> ssh-ed25519 yXNDbw rq3zM6yBAOw27casxuak0MTrhHXXfQranR8pL0osS3A
6aDqYlDmYLLvxdorIxs4WB24mouWUHqbT5s3qgIx/lA
-> ssh-ed25519 BTX+xA 1zd7nxWxmVfu1yMI4K5McNSV0ULLcZ0fVCGNNXIBw3k
n1clgjKA4UjBRnokQm99x+q9OBi4muPdD70l1XMak4o
--- URplj0eiKdqp222NxhGDYUmz+bho1zxam1hsf7trJ/g
g(ÒÚÅàÑÁÑÕÔ«Ì1ï¡.YÌIqQ³úÓ”<%½-£6¼CEKüv9#Aóö³%@Vì·çˆKWŸ” ‹ï

Binary file not shown.

14
secrets/secrets.nix Normal file
View File

@ -0,0 +1,14 @@
let
geemili_aitxero = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHAVxN0eFU4VyBIQB8/Z5oiAW119xfaCfxl5K7AdfoZ7";
geemili = [ geemili_aitxero ];
samsehu = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIIRkyyUcmLsnX0oo1QzGeyPEqIc/i4ExcZClVoERggl9";
in
{
"samsehu_DUCK_DNS_TOKEN.age".publicKeys = geemili ++ [ samsehu ];
"samsehu_DEX_ENVIRONMENT_FILE.age".publicKeys = geemili ++ [ samsehu ];
"samsehu_OIDC_APP_SECRET_HEADSCALE.age".publicKeys = geemili ++ [ samsehu ];
"samsehu_OIDC_APP_SECRET_FORGEJO.age".publicKeys = geemili ++ [ samsehu ];
"samsehu_LLDAP_ADMIN_PASSWORD.age".publicKeys = geemili ++ [ samsehu ];
"samsehu_FORGEJO_ACTIONS_RUNNER.age".publicKeys = geemili ++ [ samsehu ];
}

111
services/komga.nix Normal file
View File

@ -0,0 +1,111 @@
{ config, pkgs, lib, ... }:
with lib;
let
cfg = config.services.komgaCustom;
settingsFormat = pkgs.formats.yaml {};
in
{
options = {
services.komgaCustom = {
enable = mkEnableOption (lib.mdDoc "Komga, a free and open source comics/mangas media server");
port = mkOption {
type = types.port;
default = 25600;
description = lib.mdDoc ''
The port that Komga will listen on.
'';
};
user = mkOption {
type = types.str;
default = "komga";
description = lib.mdDoc ''
User account under which Komga runs.
'';
};
group = mkOption {
type = types.str;
default = "komga";
description = lib.mdDoc ''
Group under which Komga runs.
'';
};
stateDir = mkOption {
type = types.str;
default = "/var/lib/komga";
description = lib.mdDoc ''
State and configuration directory Komga will use.
'';
};
openFirewall = mkOption {
type = types.bool;
default = false;
description = lib.mdDoc ''
Whether to open the firewall for the port in {option}`services.komga.port`.
'';
};
settings = mkOption {
type = settingsFormat.type;
default = {};
description = lib.mdDoc ''
Configuration for application.yaml, see
<link xlink:href="https://komga.org/docs/installation/configuration"
for supported settings.
'';
};
};
};
config = mkIf cfg.enable {
networking.firewall.allowedTCPPorts = mkIf cfg.openFirewall [ cfg.port ];
users.groups = mkIf (cfg.group == "komga") {
komga = {};
};
users.users = mkIf (cfg.user == "komga") {
komga = {
group = cfg.group;
home = cfg.stateDir;
description = "Komga Daemon user";
isSystemUser = true;
};
};
systemd.services.komgaCustom = {
environment = {
SERVER_PORT = builtins.toString cfg.port;
KOMGA_CONFIGDIR = cfg.stateDir;
};
description = "Komga is a free and open source comics/mangas media server";
wantedBy = [ "multi-user.target" ];
wants = [ "network-online.target" ];
after = [ "network-online.target" ];
serviceConfig = {
User = cfg.user;
Group = cfg.group;
Type = "simple";
Restart = "on-failure";
ExecStartPre = pkgs.writeShellScript "komga-config-setup" ''
ln -sf ${settingsFormat.generate "application.yml" cfg.settings} ${cfg.stateDir}/application.yml
'';
ExecStart = "${pkgs.komga}/bin/komga";
StateDirectory = mkIf (cfg.stateDir == "/var/lib/komga") "komga";
};
};
};
}

View File

@ -1,394 +0,0 @@
pub const Suit = enum(u2) {
clubs = 0b00,
spades = 0b01,
hearts = 0b10,
diamonds = 0b11,
pub fn color(this: @This()) u1 {
return @intCast((@intFromEnum(this) & 0b10) >> 1);
}
};
pub const Card = packed struct(u6) {
suit: Suit,
rank: Rank,
pub const Rank = u4;
};
/// A texture with a regular grid of sprites
pub const TileSheet = struct {
texture: seizer.Texture,
tile_offset: [2]u32,
tile_size: [2]u32,
tile_stride: [2]u32,
pub const InitOptions = struct {
allocator: std.mem.Allocator,
image_file_contents: []const u8,
tile_offset: [2]u32,
tile_size: [2]u32,
tile_stride: [2]u32,
texture_options: seizer.Texture.InitFromFileOptions = .{},
};
pub fn init(options: InitOptions) !@This() {
const texture = try seizer.Texture.initFromFileContents(
options.allocator,
options.image_file_contents,
options.texture_options,
);
return @This(){
.texture = texture,
.tile_offset = options.tile_offset,
.tile_size = options.tile_size,
.tile_stride = options.tile_stride,
};
}
pub fn deinit(this: *@This()) void {
this.texture.deinit();
}
pub fn uvCoordinatesFromTileId(this: @This(), tile_id: u32) seizer.geometry.AABB(f32) {
const texture_sizef = [2]f32{
@floatFromInt(this.texture.size[0]),
@floatFromInt(this.texture.size[1]),
};
const tile_offsetf = [2]f32{
@floatFromInt(this.tile_offset[0]),
@floatFromInt(this.tile_offset[1]),
};
const tile_stridef = [2]f32{
@floatFromInt(this.tile_stride[0]),
@floatFromInt(this.tile_stride[1]),
};
const tile_sizef = [2]f32{
@floatFromInt(this.tile_size[0]),
@floatFromInt(this.tile_size[1]),
};
// add a half to round up
const size_in_tiles = [2]u32{
(@as(u32, @intCast(this.texture.size[0])) + (this.tile_stride[0] / 2)) / this.tile_stride[0],
(@as(u32, @intCast(this.texture.size[1])) + (this.tile_stride[1] / 2)) / this.tile_stride[1],
};
const pos_in_tiles = [2]u32{
tile_id % size_in_tiles[0],
tile_id / size_in_tiles[0],
};
const pos_in_tilesf = [2]f32{
@floatFromInt(pos_in_tiles[0]),
@floatFromInt(pos_in_tiles[1]),
};
const pixel_pos = [2]f32{
pos_in_tilesf[0] * tile_stridef[0] + tile_offsetf[0],
pos_in_tilesf[1] * tile_stridef[1] + tile_offsetf[1],
};
return seizer.geometry.AABB(f32){
.min = .{
pixel_pos[0] / texture_sizef[0],
pixel_pos[1] / texture_sizef[1],
},
.max = .{
(pixel_pos[0] + tile_sizef[0]) / texture_sizef[0],
(pixel_pos[1] + tile_sizef[1]) / texture_sizef[1],
},
};
}
pub fn renderTile(this: @This(), canvas: *seizer.Canvas, tile_id: u32, pos: [2]f32, options: struct {
size: ?[2]f32 = null,
color: [4]u8 = [4]u8{ 0xFF, 0xFF, 0xFF, 0xFF },
}) void {
const uv = this.uvCoordinatesFromTileId(tile_id);
canvas.rect(pos, options.size orelse [2]f32{ @floatFromInt(this.tile_size[0]), @floatFromInt(this.tile_size[1]) }, .{
.texture = this.texture.glTexture,
.uv = uv,
.color = options.color,
});
}
};
test "tilesheet math is exact" {
const tilesheet = TileSheet{
.texture = .{
.glTexture = undefined,
.size = .{ 494, 329 },
},
.tile_offset = .{ 6, 2 },
.tile_size = .{ 20, 29 },
.tile_stride = .{ 33, 33 },
};
try std.testing.expectEqualDeep(seizer.geometry.AABB(f32){
.min = .{
468.0 / 494.0,
35.0 / 329.0,
},
.max = .{
(468.0 + 20.0) / 494.0,
(35.0 + 29.0) / 329.0,
},
}, tilesheet.uvCoordinatesFromTileId(29));
}
/// A texture with a regular grid of sprites
pub const DeckSprites = struct {
tilesheet: TileSheet,
/// Return the tile index for a given card,
mapping: std.AutoHashMapUnmanaged(Card, u32),
blank: u32,
back: u32,
margin: u32,
hand_offset: [2]u32,
pub fn deinit(this: *@This(), gpa: std.mem.Allocator) void {
this.tilesheet.deinit();
this.mapping.deinit(gpa);
}
pub fn getTileForCard(this: @This(), card: Card) u32 {
return this.mapping.get(card) orelse 0;
}
};
pub fn loadSmallCards(gpa: std.mem.Allocator) !DeckSprites {
var tilesheet = try TileSheet.init(.{
.allocator = gpa,
.image_file_contents = @embedFile("./cardsSmall_tilemap.png"),
.tile_offset = .{ 0, 0 },
.tile_size = .{ 16, 16 },
.tile_stride = .{ 17, 17 },
.texture_options = .{
.min_filter = .nearest,
.mag_filter = .nearest,
},
});
errdefer tilesheet.deinit();
var mapping = std.AutoHashMap(Card, u32).init(gpa);
errdefer mapping.deinit();
try mapping.ensureTotalCapacity(52);
const hearts_start_index: u32 = 0;
for (0..13) |rank| {
mapping.putAssumeCapacityNoClobber(
Card{ .suit = .hearts, .rank = @intCast(rank + 1) },
hearts_start_index + @as(u32, @intCast(rank)),
);
}
const diamonds_start_index: u32 = 14;
for (0..13) |rank| {
mapping.putAssumeCapacityNoClobber(
Card{ .suit = .diamonds, .rank = @intCast(rank + 1) },
diamonds_start_index + @as(u32, @intCast(rank)),
);
}
const clubs_start_index: u32 = 28;
for (0..13) |rank| {
mapping.putAssumeCapacityNoClobber(
Card{ .suit = .clubs, .rank = @intCast(rank + 1) },
clubs_start_index + @as(u32, @intCast(rank)),
);
}
const spades_start_index: u32 = 42;
for (0..13) |rank| {
mapping.putAssumeCapacityNoClobber(
Card{ .suit = .spades, .rank = @intCast(rank + 1) },
spades_start_index + @as(u32, @intCast(rank)),
);
}
return DeckSprites{
.tilesheet = tilesheet,
.mapping = mapping.unmanaged,
// TODO: add better graphic for blank card
.blank = 59,
.back = 59,
};
}
pub fn loadMediumCards(gpa: std.mem.Allocator) !DeckSprites {
var tilesheet = try TileSheet.init(.{
.allocator = gpa,
.image_file_contents = @embedFile("./cardsMedium_tilemap.png"),
.tile_offset = .{ 6, 2 },
.tile_size = .{ 20, 29 },
.tile_stride = .{ 33, 33 },
.texture_options = .{
.min_filter = .nearest,
.mag_filter = .nearest,
},
});
errdefer tilesheet.deinit();
var mapping = std.AutoHashMap(Card, u32).init(gpa);
errdefer mapping.deinit();
try mapping.ensureTotalCapacity(52);
const hearts_start_index: u32 = 0;
for (0..13) |rank| {
mapping.putAssumeCapacityNoClobber(
Card{ .suit = .hearts, .rank = @intCast(rank + 1) },
hearts_start_index + @as(u32, @intCast(rank)),
);
}
const diamonds_start_index: u32 = 15;
for (0..13) |rank| {
mapping.putAssumeCapacityNoClobber(
Card{ .suit = .diamonds, .rank = @intCast(rank + 1) },
diamonds_start_index + @as(u32, @intCast(rank)),
);
}
const clubs_start_index: u32 = 30;
for (0..13) |rank| {
mapping.putAssumeCapacityNoClobber(
Card{ .suit = .clubs, .rank = @intCast(rank + 1) },
clubs_start_index + @as(u32, @intCast(rank)),
);
}
const spades_start_index: u32 = 45;
for (0..13) |rank| {
mapping.putAssumeCapacityNoClobber(
Card{ .suit = .spades, .rank = @intCast(rank + 1) },
spades_start_index + @as(u32, @intCast(rank)),
);
}
return DeckSprites{
.tilesheet = tilesheet,
.mapping = mapping.unmanaged,
.blank = 14,
.back = 29,
};
}
pub fn loadLargeCards(gpa: std.mem.Allocator) !DeckSprites {
var tilesheet = try TileSheet.init(.{
.allocator = gpa,
.image_file_contents = @embedFile("./cardsLarge_tilemap.png"),
.tile_offset = .{ 11, 2 },
.tile_size = .{ 41, 60 },
.tile_stride = .{ 65, 65 },
.texture_options = .{
.min_filter = .nearest,
.mag_filter = .nearest,
},
});
errdefer tilesheet.deinit();
var mapping = std.AutoHashMap(Card, u32).init(gpa);
errdefer mapping.deinit();
try mapping.ensureTotalCapacity(52);
const hearts_start_index: u32 = 0;
for (0..13) |rank| {
mapping.putAssumeCapacityNoClobber(
Card{ .suit = .hearts, .rank = @intCast(rank + 1) },
hearts_start_index + @as(u32, @intCast(rank)),
);
}
const diamonds_start_index: u32 = 14;
for (0..13) |rank| {
mapping.putAssumeCapacityNoClobber(
Card{ .suit = .diamonds, .rank = @intCast(rank + 1) },
diamonds_start_index + @as(u32, @intCast(rank)),
);
}
const clubs_start_index: u32 = 28;
for (0..13) |rank| {
mapping.putAssumeCapacityNoClobber(
Card{ .suit = .clubs, .rank = @intCast(rank + 1) },
clubs_start_index + @as(u32, @intCast(rank)),
);
}
const spades_start_index: u32 = 42;
for (0..13) |rank| {
mapping.putAssumeCapacityNoClobber(
Card{ .suit = .spades, .rank = @intCast(rank + 1) },
spades_start_index + @as(u32, @intCast(rank)),
);
}
return DeckSprites{
.tilesheet = tilesheet,
.mapping = mapping.unmanaged,
.blank = 13,
.back = 27,
};
}
pub fn loadSolitaireCards(gpa: std.mem.Allocator) !DeckSprites {
var tilesheet = try TileSheet.init(.{
.allocator = gpa,
.image_file_contents = @embedFile("./solitaire-cards.png"),
.tile_offset = .{ 0, 0 },
.tile_size = .{ 32, 40 },
.tile_stride = .{ 32, 40 },
.texture_options = .{
.min_filter = .nearest,
.mag_filter = .nearest,
},
});
errdefer tilesheet.deinit();
var mapping = std.AutoHashMap(Card, u32).init(gpa);
errdefer mapping.deinit();
try mapping.ensureTotalCapacity(52);
const hearts_start_index: u32 = 0;
for (0..13) |rank| {
mapping.putAssumeCapacityNoClobber(
Card{ .suit = .hearts, .rank = @intCast(rank + 1) },
hearts_start_index + @as(u32, @intCast(rank)),
);
}
const diamonds_start_index: u32 = 14;
for (0..13) |rank| {
mapping.putAssumeCapacityNoClobber(
Card{ .suit = .diamonds, .rank = @intCast(rank + 1) },
diamonds_start_index + @as(u32, @intCast(rank)),
);
}
const clubs_start_index: u32 = 28;
for (0..13) |rank| {
mapping.putAssumeCapacityNoClobber(
Card{ .suit = .clubs, .rank = @intCast(rank + 1) },
clubs_start_index + @as(u32, @intCast(rank)),
);
}
const spades_start_index: u32 = 42;
for (0..13) |rank| {
mapping.putAssumeCapacityNoClobber(
Card{ .suit = .spades, .rank = @intCast(rank + 1) },
spades_start_index + @as(u32, @intCast(rank)),
);
}
return DeckSprites{
.tilesheet = tilesheet,
.mapping = mapping.unmanaged,
.blank = 13,
.back = 27,
.margin = 4,
.hand_offset = .{ 10, 12 },
};
}
const seizer = @import("seizer");
const gl = seizer.gl;
const std = @import("std");

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

View File

@ -1,906 +0,0 @@
pub const main = seizer.main;
const APPNAME = "seizer-solitaire";
var prng: std.rand.DefaultPrng = undefined;
var window_global: seizer.Window = undefined;
var canvas: seizer.Canvas = undefined;
var card_tilemap: ?DeckSprites = null;
var draw_pile: std.ArrayListUnmanaged(Card) = .{};
var draw_pile_exhausted = false;
var drawn_cards: std.ArrayListUnmanaged(Card) = .{};
var stacks: [7]std.ArrayListUnmanaged(Card) = [_]std.ArrayListUnmanaged(Card){.{}} ** 7;
var foundations: [4]std.ArrayListUnmanaged(Card) = [_]std.ArrayListUnmanaged(Card){.{}} ** 4;
var history: std.ArrayListUnmanaged(Snapshot) = .{};
var last_hovered_stack: usize = 0;
var last_hovered_foundation: usize = 0;
var hovered_deck: ?*std.ArrayListUnmanaged(Card) = null;
var hovered_card: usize = 0;
var selected_deck: ?*std.ArrayListUnmanaged(Card) = null;
var selected_card: usize = 0;
var show_menu: bool = false;
var menu_item_selected: u32 = 0;
const MENU_ITEMS = [_][]const u8{
"Continue",
"New Game",
"Quit",
};
var win_count: ?u32 = null;
var win_triggered: bool = false;
var frame_count: u64 = 0;
pub fn init() !void {
prng = std.rand.DefaultPrng.init(@bitCast(std.time.timestamp()));
window_global = try seizer.platform.createWindow(.{
.title = "Seizer Solitaire",
.on_render = render,
.on_destroy = destroy,
});
canvas = try seizer.Canvas.init(seizer.platform.allocator(), .{});
errdefer canvas.deinit();
card_tilemap = try assets.loadSolitaireCards(seizer.platform.allocator());
try resetGame();
try seizer.platform.addButtonInput(.{
.title = "move_up",
.on_event = moveUp,
.default_bindings = &.{
.{ .gamepad = .dpup },
.{ .keyboard = .up },
},
});
try seizer.platform.addButtonInput(.{
.title = "move_down",
.on_event = moveDown,
.default_bindings = &.{
.{ .gamepad = .dpdown },
.{ .keyboard = .down },
},
});
try seizer.platform.addButtonInput(.{
.title = "move_left",
.on_event = moveLeft,
.default_bindings = &.{
.{ .gamepad = .dpleft },
.{ .keyboard = .left },
},
});
try seizer.platform.addButtonInput(.{
.title = "move_right",
.on_event = moveRight,
.default_bindings = &.{
.{ .gamepad = .dpright },
.{ .keyboard = .right },
},
});
try seizer.platform.addButtonInput(.{
.title = "select_or_place",
.on_event = doSelectOrPlace,
.default_bindings = &.{
.{ .gamepad = .a },
.{ .keyboard = .z },
},
});
try seizer.platform.addButtonInput(.{
.title = "deselect",
.on_event = deselect,
.default_bindings = &.{
.{ .gamepad = .b },
.{ .keyboard = .x },
},
});
try seizer.platform.addButtonInput(.{
.title = "toggle_menu",
.on_event = toggleMenu,
.default_bindings = &.{
.{ .gamepad = .start },
.{ .keyboard = .esc },
},
});
try seizer.platform.addButtonInput(.{
.title = "undo",
.on_event = undo,
.default_bindings = &.{
.{ .gamepad = .x },
.{ .keyboard = .a },
},
});
const read_buffer = try seizer.platform.allocator().alloc(u8, @sizeOf(u32));
seizer.platform.readFile(.{
.appname = APPNAME,
.path = "win_count.bin",
.buffer = read_buffer,
.callback = onWinCountRead,
.userdata = read_buffer.ptr,
});
}
fn onWinCountRead(userdata: ?*anyopaque, result: seizer.Platform.FileError![]const u8) void {
const buffer: *[4]u8 = @ptrCast(userdata);
defer seizer.platform.allocator().free(buffer);
if (result) |bytes| {
if (bytes.len >= @sizeOf(u32)) {
win_count = std.mem.readInt(u32, bytes[0..4], .little);
}
} else |_| {}
}
fn onWinCountWritten(userdata: ?*anyopaque, result: seizer.Platform.FileError!void) void {
const buffer: *u32 = @ptrCast(@alignCast(userdata));
defer seizer.platform.allocator().destroy(buffer);
_ = result catch {};
}
fn resetGame() !void {
resetHistory();
draw_pile.deinit(seizer.platform.allocator());
draw_pile_exhausted = false;
drawn_cards.shrinkRetainingCapacity(0);
for (&stacks) |*stack| {
stack.shrinkRetainingCapacity(0);
}
for (&foundations) |*foundation| {
foundation.shrinkRetainingCapacity(0);
}
last_hovered_stack = 0;
last_hovered_foundation = 0;
hovered_deck = null;
hovered_card = 0;
selected_deck = null;
selected_card = 0;
draw_pile = std.ArrayListUnmanaged(Card).fromOwnedSlice(try makeStandardDeck(seizer.platform.allocator()));
prng.random().shuffle(Card, draw_pile.items);
for (&stacks, 0..) |*stack, i| {
for (0..i + 1) |_| {
const drawn_card = draw_pile.pop();
try stack.append(seizer.platform.allocator(), drawn_card);
}
}
win_triggered = false;
}
fn resetHistory() void {
for (history.items) |*snapshot| {
snapshot.deinit();
}
history.shrinkRetainingCapacity(0);
}
fn destroy(window: seizer.Window) void {
_ = window;
for (history.items) |*snapshot| {
snapshot.deinit();
}
history.deinit(seizer.platform.allocator());
draw_pile.deinit(seizer.platform.allocator());
drawn_cards.deinit(seizer.platform.allocator());
for (&stacks) |*stack| {
stack.deinit(seizer.platform.allocator());
}
for (&foundations) |*foundation| {
foundation.deinit(seizer.platform.allocator());
}
if (card_tilemap) |*ct| {
ct.deinit(seizer.platform.allocator());
card_tilemap = null;
}
canvas.deinit();
}
fn render(window: seizer.Window) !void {
if (haveWon() and !win_triggered and win_count != null) {
win_count.? += 1;
const win_count_write_buffer = try seizer.platform.allocator().create(u32);
std.mem.writeInt(u32, std.mem.asBytes(win_count_write_buffer), win_count.?, .little);
seizer.platform.writeFile(.{
.appname = APPNAME,
.path = "win_count.bin",
.data = std.mem.asBytes(win_count_write_buffer),
.callback = onWinCountWritten,
.userdata = win_count_write_buffer,
});
resetHistory();
win_triggered = true;
}
gl.clearColor(0.2, 0.4, 0.2, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT);
canvas.begin(.{
.window_size = window.getSize(),
.framebuffer_size = window.getFramebufferSize(),
});
const scale: u32 = if (canvas.window_size[1] <= 400) 1 else 2;
const scalef: f32 = @floatFromInt(scale);
const tile_size = [2]u32{
card_tilemap.?.tilesheet.tile_size[0] * scale,
card_tilemap.?.tilesheet.tile_size[1] * scale,
};
const margin = card_tilemap.?.margin * scale;
const marginf: f32 = @floatFromInt(card_tilemap.?.margin * scale);
const hand_offset = [2]u32{
card_tilemap.?.hand_offset[0] * scale,
card_tilemap.?.hand_offset[1] * scale,
};
const hand_offsetf = [2]f32{
@floatFromInt(hand_offset[0]),
@floatFromInt(hand_offset[1]),
};
const tile_sizef = [2]f32{ @floatFromInt(tile_size[0]), @floatFromInt(tile_size[1]) };
const space_taken_by_board = [2]f32{
@floatFromInt(2 * margin + 8 * (margin + tile_size[0])),
@floatFromInt(2 * margin + 5 * (margin + tile_size[1])),
};
const board_offset = [2]f32{
@floor((canvas.window_size[0] - space_taken_by_board[0]) / 2),
@floor((canvas.window_size[1] - space_taken_by_board[1]) / 2),
};
if (win_count) |w| {
_ = canvas.printText(
.{
canvas.window_size[0] - board_offset[0] - marginf - hand_offsetf[0],
board_offset[1] + marginf + hand_offsetf[1],
},
"Win Count: {}",
.{w},
.{ .@"align" = .right, .scale = scalef },
);
} else {
const throbber_character: u8 = switch ((frame_count / 5) % 8) {
0 => '-',
1 => '\\',
2 => '|',
3 => '/',
4 => '-',
5 => '\\',
6 => '|',
7 => '/',
else => unreachable,
};
_ = canvas.printText(
.{
canvas.window_size[0] - board_offset[0] - marginf - hand_offsetf[0],
board_offset[1] + marginf + hand_offsetf[1],
},
"Win Count: [{c}]",
.{throbber_character},
.{ .@"align" = .right, .scale = scalef },
);
}
for (&stacks, 0..) |*stack, i| {
const deck_is_selected = selected_deck != null and selected_deck.? == stack;
const deck_is_hovered = hovered_deck != null and hovered_deck.? == stack;
const deck_color = if (deck_is_selected)
[4]u8{ 0xFF, 0xA0, 0xA0, 0xFF }
else if (deck_is_hovered)
[4]u8{ 0xA0, 0xFF, 0xA0, 0xFF }
else
[4]u8{ 0xFF, 0xFF, 0xFF, 0xFF };
var pos = [2]f32{
@floor(@as(f32, @floatFromInt(margin + ((tile_size[0] + margin) * (i + 1))))),
@floor(@as(f32, @floatFromInt(margin + margin + tile_size[1]))),
};
pos[0] += board_offset[0];
pos[1] += board_offset[1];
canvas.rect(pos, tile_sizef, .{ .color = deck_color });
for (stack.items, 0..) |card, j| {
const is_selected = deck_is_selected and j >= selected_card;
const is_hovered = deck_is_hovered and j >= hovered_card;
const color = if (is_selected)
[4]u8{ 0xFF, 0xA0, 0xA0, 0xFF }
else if (is_hovered)
[4]u8{ 0xA0, 0xFF, 0xA0, 0xFF }
else
[4]u8{ 0xFF, 0xFF, 0xFF, 0xFF };
const tile_id = card_tilemap.?.getTileForCard(card);
card_tilemap.?.tilesheet.renderTile(&canvas, tile_id, pos, .{
.size = tile_sizef,
.color = color,
});
pos[1] += @floatFromInt(hand_offset[1]);
}
}
if (haveWon()) {
const offset =
[2]f32{
2 * marginf + tile_sizef[0],
2 * marginf + tile_sizef[1],
};
_ = canvas.writeText(
.{
board_offset[0] + offset[0] + (space_taken_by_board[0] - offset[0]) / 2,
board_offset[1] + offset[1] + (space_taken_by_board[1] - offset[0]) / 2,
},
"You Win!",
.{
.baseline = .middle,
.@"align" = .center,
.scale = 2 * scalef,
},
);
}
for (&foundations, 0..) |*foundation, i| {
const is_hovered = hovered_deck != null and hovered_deck.? == foundation;
const color = if (is_hovered) [4]u8{ 0xA0, 0xFF, 0xA0, 0xFF } else [4]u8{ 0xFF, 0xFF, 0xFF, 0xFF };
var pos = [2]f32{
@floatFromInt(margin),
@floatFromInt(margin + ((margin + tile_size[1]) * (i + 1))),
};
pos[0] += board_offset[0];
pos[1] += board_offset[1];
canvas.rect(pos, tile_sizef, .{ .color = color });
for (foundation.items) |card| {
const tile_id = card_tilemap.?.getTileForCard(card);
card_tilemap.?.tilesheet.renderTile(&canvas, tile_id, pos, .{
.size = tile_sizef,
.color = color,
});
pos[1] -= 0.25 * scalef;
}
}
{
const deck_is_selected = selected_deck != null and selected_deck.? == &drawn_cards;
const deck_is_hovered = hovered_deck != null and hovered_deck.? == &drawn_cards;
var pos = [2]f32{
@floatFromInt(margin + margin + tile_size[0]),
@floatFromInt(margin),
};
pos[0] += board_offset[0];
pos[1] += board_offset[1];
for (drawn_cards.items, 0..) |card, j| {
const is_selected = deck_is_selected and j >= selected_card;
const is_hovered = deck_is_hovered and j >= hovered_card;
const color = if (is_selected)
[4]u8{ 0xFF, 0xA0, 0xA0, 0xFF }
else if (is_hovered)
[4]u8{ 0xA0, 0xFF, 0xA0, 0xFF }
else
[4]u8{ 0xFF, 0xFF, 0xFF, 0xFF };
const tile_id = card_tilemap.?.getTileForCard(card);
card_tilemap.?.tilesheet.renderTile(&canvas, tile_id, pos, .{
.size = tile_sizef,
.color = color,
});
pos[0] += @floatFromInt(hand_offset[0]);
}
}
{
const is_selected = selected_deck != null and selected_deck.? == &draw_pile;
const is_hovered = hovered_deck != null and hovered_deck.? == &draw_pile;
const color = if (is_selected)
[4]u8{ 0xFF, 0xA0, 0xA0, 0xFF }
else if (is_hovered)
[4]u8{ 0xA0, 0xFF, 0xA0, 0xFF }
else
[4]u8{ 0xFF, 0xFF, 0xFF, 0xFF };
var pos = [2]f32{ @floatFromInt(margin), @floatFromInt(margin) };
pos[0] += board_offset[0];
pos[1] += board_offset[1];
canvas.rect(pos, tile_sizef, .{ .color = color });
for (draw_pile.items) |card| {
const tile_id = if (!draw_pile_exhausted) card_tilemap.?.back else card_tilemap.?.getTileForCard(card);
card_tilemap.?.tilesheet.renderTile(&canvas, tile_id, pos, .{
.size = tile_sizef,
.color = color,
});
pos[1] -= 0.25 * scalef;
}
}
if (show_menu) {
canvas.rect(
.{ canvas.window_size[0] / 3, canvas.window_size[1] / 3 },
.{ canvas.window_size[0] / 3, canvas.window_size[1] / 3 },
.{ .color = .{ 0, 0, 0, 0xFF } },
);
const x: f32 = canvas.window_size[0] / 2;
var y: f32 = canvas.window_size[1] / 3 + (canvas.font.lineHeight * scalef);
for (MENU_ITEMS, 0..) |menu_item, i| {
if (i == menu_item_selected) {
const size = canvas.printText(.{ x, y }, "> {s} <", .{menu_item}, .{ .@"align" = .center, .scale = scalef });
y += size[1];
} else {
const size = canvas.writeText(.{ x, y }, menu_item, .{ .@"align" = .center, .scale = scalef });
y += size[1];
}
}
}
canvas.end();
frame_count +%= 1;
}
pub fn haveWon() bool {
if (draw_pile.items.len > 0) return false;
if (drawn_cards.items.len > 0) return false;
for (stacks) |stack| {
if (stack.items.len > 0) return false;
}
return true;
}
pub fn makeStandardDeck(allocator: std.mem.Allocator) ![]Card {
var deck = try allocator.alloc(Card, 52);
errdefer allocator.free(deck);
var next_index: usize = 0;
for (0..4) |suit| {
for (1..14) |rank| {
deck[next_index] = Card{
.suit = @enumFromInt(suit),
.rank = @intCast(rank),
};
next_index += 1;
}
}
return deck;
}
pub fn deselect(pressed: bool) !void {
if (!pressed) return;
if (show_menu) return;
selected_deck = null;
selected_card = 0;
}
pub fn doSelectOrPlace(pressed: bool) !void {
if (!pressed) return;
if (show_menu) {
const menu_item = MENU_ITEMS[menu_item_selected];
if (std.mem.eql(u8, menu_item, "Continue")) {
show_menu = false;
} else if (std.mem.eql(u8, menu_item, "New Game")) {
try resetGame();
show_menu = false;
} else if (std.mem.eql(u8, menu_item, "Quit")) {
window_global.setShouldClose(true);
}
return;
}
if (selected_deck == null) {
if (hovered_deck == &draw_pile and !draw_pile_exhausted) {
resetHistory();
drawn_cards.ensureUnusedCapacity(seizer.platform.allocator(), 3) catch return;
for (0..3) |_| {
if (draw_pile.popOrNull()) |card| drawn_cards.appendAssumeCapacity(card);
}
if (draw_pile.items.len == 0) {
draw_pile_exhausted = true;
}
} else if (hovered_deck == &draw_pile and draw_pile_exhausted) {
selected_deck = hovered_deck;
selected_card = hovered_card;
} else if (hovered_deck == &drawn_cards) {
selected_deck = hovered_deck;
selected_card = hovered_card;
} else {
for (stacks[0..]) |*stack| {
if (hovered_deck != stack) continue;
selected_deck = hovered_deck;
selected_card = hovered_card;
break;
}
}
} else if (hovered_deck == selected_deck) {
var snapshot = try Snapshot.initFromCurrentGlobalState();
const selected_substack = selected_deck.?.items[selected_card..];
// try to move all selected cards into the foundations
var cards_moved = false;
move_cards_to_foundations: for (0..selected_substack.len) |_| {
for (foundations[0..]) |*foundation| {
if (hovered_deck == foundation) break :move_cards_to_foundations;
}
for (foundations[0..]) |*foundation| {
const empty = foundation.items.len == 0;
const ace = selected_deck.?.items[selected_card].rank == 1;
const suit_matches = !empty and foundation.items[foundation.items.len - 1].suit == selected_deck.?.items[selected_deck.?.items.len - 1].suit;
const is_next_rank = !empty and foundation.items[foundation.items.len - 1].rank + 1 == selected_deck.?.items[selected_deck.?.items.len - 1].rank;
if ((empty and ace) or (suit_matches and is_next_rank)) {
foundation.ensureUnusedCapacity(seizer.platform.allocator(), 1) catch continue;
foundation.appendAssumeCapacity(selected_deck.?.pop());
hovered_card = if (hovered_deck.? == &drawn_cards)
hovered_deck.?.items.len -| 1
else
indexOfTopOfStack(hovered_deck.?.items);
cards_moved = true;
break;
}
} else {
break :move_cards_to_foundations;
}
}
if (cards_moved) {
try history.append(seizer.platform.allocator(), snapshot);
} else {
snapshot.deinit();
}
selected_deck = null;
} else {
var cards_moved = false;
var snapshot = try Snapshot.initFromCurrentGlobalState();
if (selected_deck) |selected| move_from_selected_to_hovered: {
const selected_substack = selected.items[selected_card..];
if (selected_substack.len == 0) break :move_from_selected_to_hovered;
const hovered = hovered_deck orelse break :move_from_selected_to_hovered;
if (hovered.items.len == 0) {
for (stacks[0..]) |*stack| {
if (hovered != stack) continue;
hovered.ensureUnusedCapacity(seizer.platform.allocator(), selected_substack.len) catch break :move_from_selected_to_hovered;
hovered.appendSliceAssumeCapacity(selected_substack);
selected.shrinkRetainingCapacity(selected.items.len - selected_substack.len);
hovered_card = indexOfTopOfStack(hovered_deck.?.items);
cards_moved = true;
break :move_from_selected_to_hovered;
}
if (selected_substack.len == 1) {
if (draw_pile_exhausted and hovered == &draw_pile and draw_pile.items.len == 0) {
hovered.ensureUnusedCapacity(seizer.platform.allocator(), 1) catch break :move_from_selected_to_hovered;
hovered.appendAssumeCapacity(selected_deck.?.pop());
hovered_card = indexOfTopOfStack(hovered_deck.?.items);
cards_moved = true;
break :move_from_selected_to_hovered;
} else for (foundations[0..]) |*foundation| {
if (foundation != selected) continue;
const empty = foundation.items.len == 0;
const ace = selected_deck.?.items[selected_card].rank == 1;
const suit_matches = !empty and foundation.items[foundation.items.len - 1].suit == selected_deck.?.items[selected_deck.?.items.len - 1].suit;
const is_next_rank = !empty and foundation.items[foundation.items.len - 1].rank + 1 == selected_deck.?.items[selected_deck.?.items.len - 1].rank;
if ((empty and ace) or (suit_matches and is_next_rank)) {
foundation.ensureUnusedCapacity(seizer.platform.allocator(), 1) catch continue;
foundation.appendAssumeCapacity(selected_deck.?.pop());
hovered_card = indexOfTopOfStack(hovered_deck.?.items);
cards_moved = true;
break :move_from_selected_to_hovered;
}
}
}
break :move_from_selected_to_hovered;
}
if (hovered.items[hovered.items.len - 1].rank - 1 != selected_substack[0].rank or
hovered.items[hovered.items.len - 1].suit.color() == selected_substack[0].suit.color())
{
break :move_from_selected_to_hovered;
}
hovered.ensureUnusedCapacity(seizer.platform.allocator(), selected_substack.len) catch break :move_from_selected_to_hovered;
hovered.appendSliceAssumeCapacity(selected_substack);
selected.shrinkRetainingCapacity(selected.items.len - selected_substack.len);
hovered_card = indexOfTopOfStack(hovered_deck.?.items);
cards_moved = true;
}
if (cards_moved) {
try history.append(seizer.platform.allocator(), snapshot);
} else {
snapshot.deinit();
}
selected_deck = null;
}
}
pub fn moveLeft(pressed: bool) !void {
if (!pressed) return;
if (show_menu) return;
if (hovered_deck == null) {
hovered_deck = &draw_pile;
hovered_card = 0;
} else if (hovered_deck == &draw_pile) {
hovered_deck = &drawn_cards;
hovered_card = drawn_cards.items.len -| 1;
} else if (hovered_deck == &drawn_cards) {
hovered_deck = &draw_pile;
hovered_card = 0;
} else if (hovered_deck == &stacks[0]) {
hovered_deck = &foundations[last_hovered_foundation];
} else {
for (stacks[1..], 1..) |*stack, i| {
if (hovered_deck == stack) {
hovered_deck = &stacks[i - 1];
hovered_card = indexOfTopOfStack(hovered_deck.?.items);
last_hovered_stack = i - 1;
return;
}
}
for (&foundations) |*foundation| {
if (hovered_deck == foundation) {
hovered_deck = &stacks[stacks.len - 1];
hovered_card = indexOfTopOfStack(hovered_deck.?.items);
return;
}
}
}
}
pub fn moveRight(pressed: bool) !void {
if (!pressed) return;
if (show_menu) return;
if (hovered_deck == null) {
hovered_deck = &draw_pile;
hovered_card = 0;
} else if (hovered_deck == &draw_pile) {
hovered_deck = &drawn_cards;
hovered_card = drawn_cards.items.len -| 1;
} else if (hovered_deck == &drawn_cards) {
hovered_deck = &draw_pile;
hovered_card = 0;
} else if (hovered_deck == &stacks[stacks.len - 1]) {
hovered_deck = &foundations[last_hovered_foundation];
} else {
for (stacks[0 .. stacks.len - 1], 0..) |*stack, i| {
if (hovered_deck == stack) {
hovered_deck = &stacks[i + 1];
hovered_card = indexOfTopOfStack(hovered_deck.?.items);
last_hovered_stack = i + 1;
return;
}
}
for (&foundations) |*foundation| {
if (hovered_deck == foundation) {
hovered_deck = &stacks[0];
hovered_card = indexOfTopOfStack(hovered_deck.?.items);
return;
}
}
}
}
pub fn moveUp(pressed: bool) !void {
if (!pressed) return;
if (show_menu) {
if (menu_item_selected == 0) menu_item_selected = MENU_ITEMS.len;
menu_item_selected -= 1;
} else if (hovered_deck == null) {
hovered_deck = &draw_pile;
hovered_card = 0;
} else if (hovered_deck == &draw_pile) {
hovered_deck = &foundations[foundations.len - 1];
last_hovered_foundation = foundations.len - 1;
} else if (hovered_deck == &drawn_cards) {
hovered_deck = &stacks[last_hovered_stack];
hovered_card = indexOfTopOfStack(hovered_deck.?.items);
} else if (hovered_deck == &foundations[0]) {
hovered_deck = &draw_pile;
hovered_card = 0;
} else {
for (stacks[0..]) |*stack| {
if (hovered_deck != stack) continue;
const top_of_stack = indexOfTopOfStack(stack.items);
if (hovered_card > top_of_stack) {
hovered_card -= 1;
return;
}
if (drawn_cards.items.len > 0) {
hovered_deck = &drawn_cards;
hovered_card = drawn_cards.items.len -| 1;
} else {
hovered_deck = &draw_pile;
hovered_card = 0;
}
return;
}
for (foundations[1..], 1..) |*foundation, i| {
if (hovered_deck == foundation) {
hovered_deck = &foundations[i - 1];
last_hovered_foundation = i - 1;
return;
}
}
}
}
pub fn moveDown(pressed: bool) !void {
if (!pressed) return;
if (show_menu) {
menu_item_selected += 1;
menu_item_selected %= @intCast(MENU_ITEMS.len);
} else if (hovered_deck == null) {
hovered_deck = &draw_pile;
hovered_card = 0;
} else if (hovered_deck == &draw_pile) {
hovered_deck = &foundations[0];
last_hovered_foundation = 0;
} else if (hovered_deck == &drawn_cards) {
hovered_deck = &stacks[last_hovered_stack];
hovered_card = indexOfTopOfStack(hovered_deck.?.items);
} else if (hovered_deck == &foundations[foundations.len - 1]) {
hovered_deck = &draw_pile;
hovered_card = 0;
} else {
for (stacks[0..]) |*stack| {
if (hovered_deck != stack) continue;
if (hovered_card < stack.items.len -| 1) {
hovered_card += 1;
return;
}
if (drawn_cards.items.len > 0) {
hovered_deck = &drawn_cards;
hovered_card = drawn_cards.items.len -| 1;
} else {
hovered_deck = &draw_pile;
hovered_card = 0;
}
return;
}
for (foundations[0 .. foundations.len - 1], 0..) |*foundation, i| {
if (hovered_deck == foundation) {
hovered_deck = &foundations[i + 1];
last_hovered_foundation = i + 1;
return;
}
}
}
}
pub fn undo(pressed: bool) !void {
if (!pressed) return;
if (history.popOrNull()) |snapshot_const| {
var snapshot = snapshot_const;
defer snapshot.deinit();
try snapshot.restore();
}
}
pub fn toggleMenu(pressed: bool) !void {
if (!pressed) return;
show_menu = !show_menu;
}
pub fn indexOfTopOfStack(cards: []Card) usize {
if (cards.len < 2) return 0;
var index = cards.len - 1;
while (index > 0) : (index -= 1) {
const prev_card = cards[index];
const card = cards[index - 1];
if (card.suit.color() == prev_card.suit.color()) break;
if (card.rank != prev_card.rank + 1) break;
}
return index;
}
const Snapshot = struct {
draw_pile: []Card,
draw_pile_exhausted: bool,
drawn_cards: []Card,
stacks: [7][]Card,
foundations: [4][]Card,
selected_deck: *std.ArrayListUnmanaged(Card),
selected_card: usize,
pub fn initFromCurrentGlobalState() !Snapshot {
const snapshot_selected_deck = selected_deck orelse return error.InvalidSelectionForSnapshot;
const snapshot_draw_pile = try seizer.platform.allocator().dupe(Card, draw_pile.items);
errdefer seizer.platform.allocator().free(snapshot_draw_pile);
const snapshot_drawn_cards = try seizer.platform.allocator().dupe(Card, drawn_cards.items);
errdefer seizer.platform.allocator().free(snapshot_drawn_cards);
var snapshot_stacks: [7][]Card = undefined;
for (&snapshot_stacks, &stacks) |*snapshot_stack, stack| {
snapshot_stack.* = try seizer.platform.allocator().dupe(Card, stack.items);
}
var snapshot_foundations: [4][]Card = undefined;
for (&snapshot_foundations, &foundations) |*snapshot_foundation, foundation| {
snapshot_foundation.* = try seizer.platform.allocator().dupe(Card, foundation.items);
}
return Snapshot{
.draw_pile = snapshot_draw_pile,
.draw_pile_exhausted = draw_pile_exhausted,
.drawn_cards = snapshot_drawn_cards,
.stacks = snapshot_stacks,
.foundations = snapshot_foundations,
.selected_deck = snapshot_selected_deck,
.selected_card = selected_card,
};
}
pub fn deinit(snapshot: *@This()) void {
seizer.platform.allocator().free(snapshot.draw_pile);
seizer.platform.allocator().free(snapshot.drawn_cards);
for (snapshot.stacks) |stack| {
seizer.platform.allocator().free(stack);
}
for (snapshot.foundations) |foundation| {
seizer.platform.allocator().free(foundation);
}
}
pub fn restore(snapshot: @This()) !void {
// ensure there is enough space for all the cards
try draw_pile.ensureTotalCapacity(seizer.platform.allocator(), snapshot.draw_pile.len);
try drawn_cards.ensureTotalCapacity(seizer.platform.allocator(), snapshot.drawn_cards.len);
for (&snapshot.stacks, &stacks) |snapshot_stack, *stack| {
try stack.ensureTotalCapacity(seizer.platform.allocator(), snapshot_stack.len);
}
for (&snapshot.foundations, &foundations) |snapshot_foundation, *foundation| {
try foundation.ensureTotalCapacity(seizer.platform.allocator(), snapshot_foundation.len);
}
// reset the state
draw_pile.shrinkRetainingCapacity(0);
draw_pile.appendSliceAssumeCapacity(snapshot.draw_pile);
draw_pile_exhausted = snapshot.draw_pile_exhausted;
drawn_cards.shrinkRetainingCapacity(0);
drawn_cards.appendSliceAssumeCapacity(snapshot.drawn_cards);
for (&snapshot.stacks, &stacks) |snapshot_stack, *stack| {
stack.shrinkRetainingCapacity(0);
stack.appendSliceAssumeCapacity(snapshot_stack);
}
for (&snapshot.foundations, &foundations) |snapshot_foundation, *foundation| {
foundation.shrinkRetainingCapacity(0);
foundation.appendSliceAssumeCapacity(snapshot_foundation);
}
selected_deck = null;
selected_card = 0;
hovered_deck = snapshot.selected_deck;
hovered_card = snapshot.selected_card;
}
};
const DeckSprites = assets.DeckSprites;
const Card = assets.Card;
const assets = @import("./assets.zig");
const builtin = @import("builtin");
const seizer = @import("seizer");
const gl = seizer.gl;
const ecs = seizer.flecs;
const std = @import("std");

Binary file not shown.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.4 KiB