main init
This commit is contained in:
18
.claude/settings.json
Normal file
18
.claude/settings.json
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Edit(~/.claude/skills/neues-projekt/**)",
|
||||
"PowerShell($sp='C:\\\\Users\\\\michi\\\\AppData\\\\Local\\\\Temp\\\\claude\\\\b5680fa1048cb998\\\\9fcb3de5-987d-4281-9ac7-7dba61480c94\\\\scratchpad'; Set-Location \"$sp\\\\Tpl Web\"; '{ \"page\": \"game/index.html\", \"size\": \"1280x800\", \"out\": \"shots\", \"shots\": [ { \"name\": \"menu\", \"wait\": 600 } ] }' | Set-Content -Encoding utf8 shots.json; node D:\\\\Oculusquest\\\\Projekt\\\\_Tools\\\\Itch\\\\itch_screens.mjs shots.json | Select-Object -Last 1)",
|
||||
"PowerShell(foreach\\($p in 'Endless Battlelines','Byte Path','DesktopAnt','SmashFace'\\){ node D:\\\\Oculusquest\\\\Projekt\\\\_Tools\\\\Library\\\\tools\\\\project-check.mjs \"D:\\\\Oculusquest\\\\Projekt\\\\$p\" | Select-String -Pattern '^#|ComfyUI|^- \\(kein|Generator|Grafik|keine|\\\\d+× Synth|Story\\)' | % Line; '' })",
|
||||
"PowerShell(foreach\\($p in 'Byte Path','DesktopAnt','Pipefix'\\){ node D:\\\\Oculusquest\\\\Projekt\\\\_Tools\\\\Library\\\\tools\\\\project-check.mjs \"D:\\\\Oculusquest\\\\Projekt\\\\$p\" | Select-String -Pattern '^#|ComfyUI|^- \\(kein|Generator|Grafik|keine|\\\\d+× Synth|Story|sprite\\)|Generator-Kopie' | % Line; '' })",
|
||||
"Edit(~/.claude/skills/projekt-check/**)",
|
||||
"PowerShell($g='D:\\\\Oculusquest\\\\Projekt\\\\_Tools\\\\ComfyGen'; foreach\\($f in 'generate_audio.py','generate_video.py','generate_voice.py','generate_variants.py'\\){ \"== $f\"; Get-Content \"$g\\\\$f\" -TotalCount 25 | Select-String -Pattern 'workflow|model|ckpt|safetensors|Usage|usage|python|\"\"\"' | select -First 8 | % { $_.Line.Trim\\(\\) } }; \"== README Modelle\"; Select-String -Path \"$g\\\\README.md\" -Pattern 'Modell|model|Workflow|workflow' | select -First 25 | % { $_.Line.Trim\\(\\).Substring\\(0,[Math]::Min\\(170,$_.Line.Trim\\(\\).Length\\)\\) }; try { $s = Invoke-RestMethod http://127.0.0.1:8188/system_stats -TimeoutSec 2; \"== system\"; $s.system.comfyui_version; $s.devices | % { \"$\\($_.name\\) VRAM $\\([math]::Round\\($_.vram_total/1GB,1\\)\\) GB\" } } catch { 'server aus' })",
|
||||
"PowerShell(py -3.12 $c)",
|
||||
"PowerShell(py -3.12 $c 'D:\\\\Oculusquest\\\\Projekt\\\\_Tools\\\\ComfyGen\\\\workflows\\\\Text to Image - Flux Klein.json')",
|
||||
"PowerShell(py -3.12 $c 'D:\\\\Oculusquest\\\\Projekt\\\\_Tools\\\\ComfyGen\\\\workflows\\\\3d modell.json')",
|
||||
"PowerShell(py -3.12 $c --log 20)",
|
||||
"PowerShell($c='D:\\\\Oculusquest\\\\Projekt\\\\_Tools\\\\ComfyGen\\\\comfy_check.py'; py -3.12 $c | Select-Object -First 1; $sp='C:\\\\Users\\\\michi\\\\AppData\\\\Local\\\\Temp\\\\claude\\\\b5680fa1048cb998\\\\9fcb3de5-987d-4281-9ac7-7dba61480c94\\\\scratchpad'; $t = Get-Content 'D:\\\\Oculusquest\\\\Projekt\\\\_Tools\\\\ComfyGen\\\\workflows\\\\Text to Image - Flux Klein.json' -Raw; $t = $t.Replace\\('{{UNET}}','flux-dev-gibtsnicht.safetensors'\\).Replace\\('\"KSamplerSelect\"','\"KSamplerSelectX\"'\\).Replace\\('[\"11\", 0]','[\"99\", 0]'\\); [IO.File]::WriteAllText\\(\"$sp\\\\broken.json\", $t\\); py -3.12 $c \"$sp\\\\broken.json\"; Remove-Item \"$sp\\\\broken.json\")",
|
||||
"Edit(~/.claude/skills/comfyui-workflow-expert/**)"
|
||||
]
|
||||
}
|
||||
}
|
||||
25
Backup/backup-config.json
Normal file
25
Backup/backup-config.json
Normal file
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"source": "D:\\Oculusquest\\Projekt",
|
||||
"target": "\\\\MYCLOUD-NESYFV\\Michael\\Projekte",
|
||||
"targets": [
|
||||
{
|
||||
"id": "q2jr36mi",
|
||||
"name": "MYCLOUD-NESYFV",
|
||||
"path": "\\\\MYCLOUD-NESYFV\\Michael\\Projekte"
|
||||
}
|
||||
],
|
||||
"excludeDirs": [
|
||||
"node_modules",
|
||||
"__pycache__",
|
||||
".gradle",
|
||||
".venv",
|
||||
"venv",
|
||||
".venv-tts",
|
||||
".bin"
|
||||
],
|
||||
"excludeFiles": [
|
||||
"Thumbs.db",
|
||||
"desktop.ini",
|
||||
"~$*"
|
||||
]
|
||||
}
|
||||
27
Backup/backup-projekte.bat
Normal file
27
Backup/backup-projekte.bat
Normal file
@@ -0,0 +1,27 @@
|
||||
@echo off
|
||||
rem ============================================================================
|
||||
rem Backup D:\Oculusquest\Projekt -> \\MYCLOUD-NESYFV\Michael\Projekte
|
||||
rem
|
||||
rem 1. prueft, was neu/geaendert ist und im Backup fehlt (Anzahl, Groesse, pro Projekt)
|
||||
rem 2. fragt nach und kopiert genau das
|
||||
rem
|
||||
rem Im Backup wird NIE etwas geloescht. Dateien, die es hier nicht mehr gibt,
|
||||
rem werden nur angezeigt und bleiben im Backup erhalten.
|
||||
rem
|
||||
rem Nicht gesichert (wird neu erzeugt): node_modules, __pycache__, .gradle, .venv, venv, .venv-tts
|
||||
rem
|
||||
rem Aufruf:
|
||||
rem backup-projekte.bat pruefen, nachfragen, kopieren
|
||||
rem backup-projekte.bat test nur pruefen
|
||||
rem backup-projekte.bat auto pruefen + kopieren ohne Nachfrage (Aufgabenplanung)
|
||||
rem
|
||||
rem Logik: backup-projekte.ps1 · Protokolle: logs\pruefung-*.log, logs\backup-*.log
|
||||
rem ============================================================================
|
||||
setlocal enabledelayedexpansion
|
||||
set "ARGS="
|
||||
for %%a in (%*) do (
|
||||
if /i "%%~a"=="test" set "ARGS=!ARGS! -Test"
|
||||
if /i "%%~a"=="auto" set "ARGS=!ARGS! -Auto"
|
||||
)
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0backup-projekte.ps1" !ARGS!
|
||||
exit /b %ERRORLEVEL%
|
||||
132
Backup/backup-projekte.ps1
Normal file
132
Backup/backup-projekte.ps1
Normal file
@@ -0,0 +1,132 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Backup D:\Oculusquest\Projekt -> \\MYCLOUD-NESYFV\Michael\Projekte, in two steps:
|
||||
1. check: which files are new/changed (missing or outdated in the backup)
|
||||
2. copy exactly those (after asking, unless -Auto)
|
||||
|
||||
Nothing is ever deleted in the backup. Files that exist only in the backup
|
||||
(deleted or renamed locally) are listed and kept.
|
||||
|
||||
Not backed up (regenerable): node_modules, __pycache__, .gradle, .venv, venv, .venv-tts
|
||||
|
||||
.EXAMPLE
|
||||
.\backup-projekte.ps1 check, ask, copy
|
||||
.\backup-projekte.ps1 -Test only check
|
||||
.\backup-projekte.ps1 -Auto check and copy without asking (task scheduler)
|
||||
#>
|
||||
param(
|
||||
[string]$Source,
|
||||
[string]$Target,
|
||||
[switch]$Test,
|
||||
[switch]$Auto
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
# Same settings as the backup in the project dashboard: backup-config.json
|
||||
$cfg = Get-Content (Join-Path $PSScriptRoot 'backup-config.json') -Raw -Encoding UTF8 | ConvertFrom-Json
|
||||
if (-not $Source) { $Source = $cfg.source }
|
||||
if (-not $Target) { $Target = $cfg.target }
|
||||
$logDir = Join-Path $PSScriptRoot 'logs'
|
||||
New-Item -ItemType Directory -Force $logDir | Out-Null
|
||||
$stamp = Get-Date -Format 'yyyy-MM-dd_HH-mm'
|
||||
$checkLog = Join-Path $logDir "pruefung-$stamp.log"
|
||||
$copyLog = Join-Path $logDir "backup-$stamp.log"
|
||||
|
||||
$common = @('/E', '/FFT', '/XJ', '/R:2', '/W:5', '/COPY:DAT', '/DCOPY:T', '/XD') + @($cfg.excludeDirs) + @('/XF') + @($cfg.excludeFiles)
|
||||
# /FFT: NAS timestamps have 2 s precision - without it every file would look changed
|
||||
|
||||
function Format-Size([double]$b) {
|
||||
if ($b -ge 1GB) { return ('{0:N1} GB' -f ($b / 1GB)) }
|
||||
if ($b -ge 1MB) { return ('{0:N0} MB' -f ($b / 1MB)) }
|
||||
return ('{0:N0} KB' -f ($b / 1KB))
|
||||
}
|
||||
|
||||
function Stop-Here([int]$code) {
|
||||
if (-not $Auto) { Write-Host ''; Read-Host 'Enter zum Schliessen' | Out-Null }
|
||||
exit $code
|
||||
}
|
||||
|
||||
Write-Host ''
|
||||
Write-Host " Backup: $Source" -ForegroundColor Cyan
|
||||
Write-Host " nach: $Target" -ForegroundColor Cyan
|
||||
Write-Host ''
|
||||
|
||||
if (-not (Test-Path -LiteralPath $Source)) { Write-Host " FEHLER: Quelle $Source fehlt." -ForegroundColor Red; Stop-Here 1 }
|
||||
if (-not (Test-Path -LiteralPath $Target)) {
|
||||
$share = Split-Path $Target -Parent
|
||||
if (-not (Test-Path -LiteralPath $share)) {
|
||||
Write-Host " FEHLER: MyCloud nicht erreichbar ($share). Eingeschaltet und im Netzwerk?" -ForegroundColor Red
|
||||
Stop-Here 1
|
||||
}
|
||||
New-Item -ItemType Directory $Target | Out-Null
|
||||
}
|
||||
|
||||
# ── 1. check ───────────────────────────────────────────────────────────────
|
||||
Write-Host ' 1/2 Pruefe, was neu ist und im Backup fehlt ...' -ForegroundColor Yellow
|
||||
# /L = list only, /X = also report files that exist only in the backup
|
||||
& robocopy $Source $Target @common /L /X /NJH /NJS /NDL /NP /FP /BYTES /UNILOG:$checkLog | Out-Null
|
||||
if ($LASTEXITCODE -ge 8) { Write-Host " FEHLER bei der Pruefung (robocopy $LASTEXITCODE). Details: $checkLog" -ForegroundColor Red; Stop-Here 1 }
|
||||
|
||||
$copy = New-Object System.Collections.Generic.List[object]
|
||||
$extra = New-Object System.Collections.Generic.List[object]
|
||||
foreach ($line in [IO.File]::ReadAllLines($checkLog)) {
|
||||
$parts = $line.Split("`t") | ForEach-Object { $_.Trim() } | Where-Object { $_ -ne '' }
|
||||
if ($parts.Count -lt 3) { continue }
|
||||
$path = $parts[-1]; $size = 0
|
||||
if (-not [int64]::TryParse($parts[-2], [ref]$size)) { continue }
|
||||
$isExtra = $parts[0] -like '*EXTRA*'
|
||||
$base = if ($isExtra) { $Target } else { $Source }
|
||||
if (-not $path.StartsWith($base, [StringComparison]::OrdinalIgnoreCase)) { continue }
|
||||
$rel = $path.Substring($base.Length).TrimStart('\')
|
||||
# robocopy's class column: "Neue Datei"/"New File" = missing in the backup, otherwise newer/changed
|
||||
$item = [pscustomobject]@{ Project = ($rel -split '\\')[0]; Rel = $rel; Size = $size; New = $parts[0] -match '^(Neue Datei|New File)$' }
|
||||
if ($isExtra) { $extra.Add($item) } else { $copy.Add($item) }
|
||||
}
|
||||
|
||||
$newFiles = @($copy | Where-Object New)
|
||||
$changed = @($copy | Where-Object { -not $_.New })
|
||||
$total = ($copy | Measure-Object Size -Sum).Sum
|
||||
|
||||
Write-Host ''
|
||||
if ($copy.Count -eq 0) {
|
||||
Write-Host ' Alles aktuell - im Backup fehlt nichts.' -ForegroundColor Green
|
||||
} else {
|
||||
Write-Host (" Zu kopieren: {0:N0} Dateien, {1}" -f $copy.Count, (Format-Size $total)) -ForegroundColor White
|
||||
Write-Host (" neu (fehlen im Backup): {0,8:N0} {1}" -f $newFiles.Count, (Format-Size (($newFiles | Measure-Object Size -Sum).Sum)))
|
||||
Write-Host (" geaendert: {0,8:N0} {1}" -f $changed.Count, (Format-Size (($changed | Measure-Object Size -Sum).Sum)))
|
||||
Write-Host ''
|
||||
Write-Host ' Nach Projekt:'
|
||||
$copy | Group-Object Project | ForEach-Object {
|
||||
[pscustomobject]@{ Name = $_.Name; Files = $_.Count; Bytes = ($_.Group | Measure-Object Size -Sum).Sum }
|
||||
} | Sort-Object Bytes -Descending | Select-Object -First 15 | ForEach-Object {
|
||||
Write-Host (" {0,-28} {1,8:N0} Dateien {2,10}" -f $_.Name, $_.Files, (Format-Size $_.Bytes))
|
||||
}
|
||||
}
|
||||
if ($extra.Count) {
|
||||
Write-Host ''
|
||||
Write-Host (" Nur noch im Backup (hier geloescht/umbenannt): {0:N0} Dateien, {1} - bleiben erhalten." -f $extra.Count, (Format-Size (($extra | Measure-Object Size -Sum).Sum))) -ForegroundColor DarkGray
|
||||
}
|
||||
Write-Host ''
|
||||
Write-Host " Vollstaendige Liste: $checkLog" -ForegroundColor DarkGray
|
||||
|
||||
if ($copy.Count -eq 0) { Stop-Here 0 }
|
||||
if ($Test) { Write-Host ''; Write-Host ' Testlauf - es wurde nichts kopiert.' -ForegroundColor Yellow; Stop-Here 0 }
|
||||
|
||||
if (-not $Auto) {
|
||||
Write-Host ''
|
||||
$answer = Read-Host ' Jetzt kopieren? (J/N)'
|
||||
if ($answer -notmatch '^(j|ja|y|yes)$') { Write-Host ' Abgebrochen, nichts kopiert.'; Stop-Here 0 }
|
||||
}
|
||||
|
||||
# ── 2. copy ────────────────────────────────────────────────────────────────
|
||||
Write-Host ''
|
||||
Write-Host ' 2/2 Kopiere neue und geaenderte Dateien ...' -ForegroundColor Yellow
|
||||
& robocopy $Source $Target @common /MT:16 /NDL /NP /TEE /UNILOG:$copyLog
|
||||
$rc = $LASTEXITCODE
|
||||
Write-Host ''
|
||||
if ($rc -ge 8) {
|
||||
Write-Host " FEHLER: Backup unvollstaendig (robocopy $rc). Details: $copyLog" -ForegroundColor Red
|
||||
Stop-Here 1
|
||||
}
|
||||
Write-Host (" Backup fertig: {0:N0} Dateien, {1}. Protokoll: {2}" -f $copy.Count, (Format-Size $total), $copyLog) -ForegroundColor Green
|
||||
Stop-Here 0
|
||||
BIN
Backup/logs/backup-2026-11-10_09-54.log
Normal file
BIN
Backup/logs/backup-2026-11-10_09-54.log
Normal file
Binary file not shown.
BIN
Backup/logs/backup-2026-11-10_10-07.log
Normal file
BIN
Backup/logs/backup-2026-11-10_10-07.log
Normal file
Binary file not shown.
BIN
Backup/logs/backup-2026-11-10_10-17.log
Normal file
BIN
Backup/logs/backup-2026-11-10_10-17.log
Normal file
Binary file not shown.
BIN
Backup/logs/backup-2026-11-10_19-11-main-GallerySwiper.log
Normal file
BIN
Backup/logs/backup-2026-11-10_19-11-main-GallerySwiper.log
Normal file
Binary file not shown.
BIN
Backup/logs/backup-2026-11-11_08-08-main.log
Normal file
BIN
Backup/logs/backup-2026-11-11_08-08-main.log
Normal file
Binary file not shown.
BIN
Backup/logs/backup-2026-11-11_09-13-main-GladiatorIdle.log
Normal file
BIN
Backup/logs/backup-2026-11-11_09-13-main-GladiatorIdle.log
Normal file
Binary file not shown.
BIN
Backup/logs/backup-2026-11-12_00-35-main.log
Normal file
BIN
Backup/logs/backup-2026-11-12_00-35-main.log
Normal file
Binary file not shown.
BIN
Backup/logs/backup-2026-11-12_08-34-q2jr36mi.log
Normal file
BIN
Backup/logs/backup-2026-11-12_08-34-q2jr36mi.log
Normal file
Binary file not shown.
BIN
Backup/logs/backup-2026-11-12_12-08-q2jr36mi.log
Normal file
BIN
Backup/logs/backup-2026-11-12_12-08-q2jr36mi.log
Normal file
Binary file not shown.
BIN
Backup/logs/pruefung-2026-11-08_21-20.log
Normal file
BIN
Backup/logs/pruefung-2026-11-08_21-20.log
Normal file
Binary file not shown.
BIN
Backup/logs/pruefung-2026-11-08_22-01-Familie-Malkano.log
Normal file
BIN
Backup/logs/pruefung-2026-11-08_22-01-Familie-Malkano.log
Normal file
Binary file not shown.
BIN
Backup/logs/pruefung-2026-11-08_22-11.log
Normal file
BIN
Backup/logs/pruefung-2026-11-08_22-11.log
Normal file
Binary file not shown.
BIN
Backup/logs/pruefung-2026-11-08_22-24.log
Normal file
BIN
Backup/logs/pruefung-2026-11-08_22-24.log
Normal file
Binary file not shown.
BIN
Backup/logs/pruefung-2026-11-10_09-52.log
Normal file
BIN
Backup/logs/pruefung-2026-11-10_09-52.log
Normal file
Binary file not shown.
BIN
Backup/logs/pruefung-2026-11-10_10-05.log
Normal file
BIN
Backup/logs/pruefung-2026-11-10_10-05.log
Normal file
Binary file not shown.
BIN
Backup/logs/pruefung-2026-11-10_10-11.log
Normal file
BIN
Backup/logs/pruefung-2026-11-10_10-11.log
Normal file
Binary file not shown.
BIN
Backup/logs/pruefung-2026-11-10_10-25-GladiatorIdle.log
Normal file
BIN
Backup/logs/pruefung-2026-11-10_10-25-GladiatorIdle.log
Normal file
Binary file not shown.
BIN
Backup/logs/pruefung-2026-11-10_19-11-main-GallerySwiper.log
Normal file
BIN
Backup/logs/pruefung-2026-11-10_19-11-main-GallerySwiper.log
Normal file
Binary file not shown.
BIN
Backup/logs/pruefung-2026-11-11_07-45-main.log
Normal file
BIN
Backup/logs/pruefung-2026-11-11_07-45-main.log
Normal file
Binary file not shown.
BIN
Backup/logs/pruefung-2026-11-11_09-13-main-GladiatorIdle.log
Normal file
BIN
Backup/logs/pruefung-2026-11-11_09-13-main-GladiatorIdle.log
Normal file
Binary file not shown.
BIN
Backup/logs/pruefung-2026-11-12_00-12-main.log
Normal file
BIN
Backup/logs/pruefung-2026-11-12_00-12-main.log
Normal file
Binary file not shown.
BIN
Backup/logs/pruefung-2026-11-12_00-34-main.log
Normal file
BIN
Backup/logs/pruefung-2026-11-12_00-34-main.log
Normal file
Binary file not shown.
BIN
Backup/logs/pruefung-2026-11-12_08-32-q2jr36mi.log
Normal file
BIN
Backup/logs/pruefung-2026-11-12_08-32-q2jr36mi.log
Normal file
Binary file not shown.
BIN
Backup/logs/pruefung-2026-11-12_12-05-q2jr36mi.log
Normal file
BIN
Backup/logs/pruefung-2026-11-12_12-05-q2jr36mi.log
Normal file
Binary file not shown.
BIN
Backup/logs/pruefung-2026-11-12_12-10-q2jr36mi.log
Normal file
BIN
Backup/logs/pruefung-2026-11-12_12-10-q2jr36mi.log
Normal file
Binary file not shown.
@@ -0,0 +1 @@
|
||||
|
||||
172
Cleanup/cleanup.ps1
Normal file
172
Cleanup/cleanup.ps1
Normal file
@@ -0,0 +1,172 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Finds regenerable build folders in all projects and (optionally) deletes them.
|
||||
|
||||
.DESCRIPTION
|
||||
Default: only lists what it found (dry run). Nothing is deleted without -Apply.
|
||||
|
||||
Tiers:
|
||||
Cache - always regenerable: node_modules, Unity Library/Temp, .NET bin/obj,
|
||||
Gradle/CMake/Flutter/PyInstaller build, .gradle, __pycache__
|
||||
Release - finished builds: dist, builds (APKs, exe, zip). Rebuildable, but they are versions.
|
||||
Output - raw ComfyUI images in generator output\ folders (adopted assets are already in the project).
|
||||
|
||||
Safety:
|
||||
- A folder is only a candidate when its parent proves the type (package.json, Assets+ProjectSettings,
|
||||
*.csproj/*.sln, build.gradle, CMakeLists.txt, pubspec.yaml, *.spec).
|
||||
- A folder that contains any git-tracked file is skipped.
|
||||
- _Tools is never touched.
|
||||
|
||||
.EXAMPLE
|
||||
.\cleanup.ps1 # list Cache folders
|
||||
.\cleanup.ps1 -Tier Cache,Release # list Cache + Release
|
||||
.\cleanup.ps1 -Apply # delete Cache folders
|
||||
.\cleanup.ps1 -Project GallerySwiper -Apply
|
||||
.\cleanup.ps1 -Project GallerySwiper -Tier Cache,Output -Json # machine-readable (used by project-dashboard)
|
||||
.\cleanup.ps1 -Project X -Tier Cache -Only 'X\node_modules|X\build' -Apply -Json
|
||||
|
||||
Lists (-Tier, -Project, -Only) may also be one string separated by ',' or '|',
|
||||
because powershell.exe -File cannot pass arrays.
|
||||
#>
|
||||
param(
|
||||
[string]$Root = 'D:\Oculusquest\Projekt',
|
||||
[string[]]$Tier = @('Cache'),
|
||||
[string[]]$Project,
|
||||
[string]$Only = '', # restrict -Apply to these paths (relative to Root, as listed)
|
||||
[switch]$Apply,
|
||||
[switch]$Json,
|
||||
[int]$MaxDepth = 8
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if ($Json) { [Console]::OutputEncoding = [Text.Encoding]::UTF8 }
|
||||
|
||||
$Tier = @($Tier | ForEach-Object { $_ -split '[,|]' } | ForEach-Object { $_.Trim() } | Where-Object { $_ })
|
||||
foreach ($t in $Tier) { if (@('Cache', 'Release', 'Output') -notcontains $t) { throw "Unknown tier '$t' (Cache, Release, Output)" } }
|
||||
$Project = @($Project | ForEach-Object { $_ -split '\|' } | ForEach-Object { $_.Trim() } | Where-Object { $_ })
|
||||
$OnlyList = @($Only -split '\|' | ForEach-Object { $_.Trim() } | Where-Object { $_ })
|
||||
|
||||
function Test-Any($dir, [string[]]$patterns) {
|
||||
foreach ($p in $patterns) {
|
||||
if (Get-ChildItem -LiteralPath $dir -Filter $p -Force -ErrorAction SilentlyContinue | Select-Object -First 1) { return $true }
|
||||
}
|
||||
return $false
|
||||
}
|
||||
|
||||
# Returns the tier for a folder, or $null when it is not a candidate.
|
||||
function Get-Tier([IO.DirectoryInfo]$d) {
|
||||
$p = $d.Parent.FullName
|
||||
switch -Regex ($d.Name) {
|
||||
'^node_modules$' { if (Test-Path -LiteralPath "$p\package.json") { return 'Cache' } }
|
||||
'^(Library|Temp)$' { if ((Test-Path -LiteralPath "$p\Assets") -and (Test-Path -LiteralPath "$p\ProjectSettings")) { return 'Cache' } }
|
||||
'^(bin|obj)$' { if (Test-Any $p @('*.csproj', '*.fsproj', '*.vbproj', '*.sln')) { return 'Cache' } }
|
||||
'^build$' {
|
||||
if (Test-Any $p @('build.gradle', 'build.gradle.kts', 'CMakeLists.txt', 'pubspec.yaml', '*.spec')) { return 'Cache' }
|
||||
if ((Test-Path -LiteralPath "$p\Assets") -and (Test-Path -LiteralPath "$p\ProjectSettings")) { return 'Release' }
|
||||
}
|
||||
'^Build$' { if ((Test-Path -LiteralPath "$p\Assets") -and (Test-Path -LiteralPath "$p\ProjectSettings")) { return 'Release' } }
|
||||
'^\.gradle$' { return 'Cache' }
|
||||
'^__pycache__$' { return 'Cache' }
|
||||
'^(dist|builds)$' { return 'Release' }
|
||||
'^output$' { if ((Test-Path -LiteralPath "$p\config.py") -or (Test-Path -LiteralPath "$p\gen.cmd") -or (Test-Any $p @('gen_*.py'))) { return 'Output' } }
|
||||
}
|
||||
return $null
|
||||
}
|
||||
|
||||
function Get-RepoRoot([string]$path) {
|
||||
$cur = $path
|
||||
while ($cur -and $cur.Length -gt $Root.Length) {
|
||||
if (Test-Path -LiteralPath "$cur\.git") { return $cur }
|
||||
$cur = Split-Path $cur -Parent
|
||||
}
|
||||
return $null
|
||||
}
|
||||
|
||||
function Test-Tracked([string]$path) {
|
||||
$repo = Get-RepoRoot (Split-Path $path -Parent)
|
||||
if (-not $repo) { return $false }
|
||||
$rel = $path.Substring($repo.Length + 1)
|
||||
$hit = git -C $repo ls-files -- $rel 2>$null | Select-Object -First 1
|
||||
return [bool]$hit
|
||||
}
|
||||
|
||||
function Get-SizeBytes([string]$path) {
|
||||
# robocopy /L counts fast and copes with long paths
|
||||
$out = robocopy $path "$env:TEMP\__nul__" /L /S /NJH /BYTES /FP /NC /NDL /NFL /XJ /R:0 /W:0 2>$null
|
||||
$line = $out | Where-Object { $_ -match '^\s*Bytes\s*:' } | Select-Object -First 1
|
||||
if ($line -match ':\s*(\d+)') { return [int64]$Matches[1] }
|
||||
return [int64]0
|
||||
}
|
||||
|
||||
$found = New-Object System.Collections.Generic.List[object]
|
||||
|
||||
function Walk([IO.DirectoryInfo]$dir, [int]$depth) {
|
||||
if ($depth -gt $MaxDepth) { return }
|
||||
foreach ($d in (Get-ChildItem -LiteralPath $dir.FullName -Directory -Force -ErrorAction SilentlyContinue)) {
|
||||
if ($d.Name -match '^(\.git|\.venv.*|venv|env)$' -or ($d.Attributes -band [IO.FileAttributes]::ReparsePoint)) { continue }
|
||||
$t = Get-Tier $d
|
||||
if ($t) {
|
||||
$found.Add([pscustomobject]@{ Tier = $t; Dir = $d })
|
||||
continue # never descend into a candidate
|
||||
}
|
||||
Walk $d ($depth + 1)
|
||||
}
|
||||
}
|
||||
|
||||
$projects = Get-ChildItem -LiteralPath $Root -Directory -Force | Where-Object { $_.Name -ne '_Tools' }
|
||||
if ($Project) { $projects = $projects | Where-Object { $Project -contains $_.Name } }
|
||||
foreach ($p in $projects) { Walk $p 1 }
|
||||
|
||||
$rows = foreach ($f in $found) {
|
||||
if ($Tier -notcontains $f.Tier) { continue }
|
||||
$path = $f.Dir.FullName
|
||||
$tracked = Test-Tracked $path
|
||||
[pscustomobject]@{
|
||||
Tier = $f.Tier
|
||||
MB = [math]::Round((Get-SizeBytes $path) / 1MB)
|
||||
Skip = if ($tracked) { 'git-tracked' } else { '' }
|
||||
Path = $path.Substring($Root.Length + 1)
|
||||
}
|
||||
}
|
||||
$rows = @($rows | Sort-Object Tier, @{ e = 'MB'; Descending = $true })
|
||||
|
||||
$todo = @($rows | Where-Object { -not $_.Skip })
|
||||
if ($OnlyList.Count) { $todo = @($todo | Where-Object { $OnlyList -contains $_.Path }) }
|
||||
|
||||
if (-not $Json) {
|
||||
$big = @($rows | Where-Object { $_.MB -ge 1 })
|
||||
$big | Format-Table -AutoSize | Out-String -Width 220 | Write-Host
|
||||
if ($rows.Count -gt $big.Count) { Write-Host ("+ {0} small folders under 1 MB (e.g. __pycache__)" -f ($rows.Count - $big.Count)) }
|
||||
foreach ($t in $Tier) {
|
||||
$gb = [math]::Round((($todo | Where-Object Tier -eq $t | Measure-Object MB -Sum).Sum) / 1024, 2)
|
||||
Write-Host ("{0,-8} {1,7} GB" -f $t, $gb)
|
||||
}
|
||||
Write-Host ("{0} folders deletable, {1} skipped as git-tracked" -f $todo.Count, ($rows.Count - $todo.Count))
|
||||
}
|
||||
|
||||
if (-not $Apply) {
|
||||
if ($Json) { ConvertTo-Json -InputObject @($rows) -Compress } else { Write-Host 'Dry run. Add -Apply to delete.' }
|
||||
exit 0
|
||||
}
|
||||
|
||||
$freeBefore = (Get-PSDrive ($Root.Substring(0, 1))).Free
|
||||
$deleted = @(); $failed = @()
|
||||
foreach ($r in $todo) {
|
||||
$full = Join-Path $Root $r.Path
|
||||
if (-not $Json) { Write-Host "delete $($r.Path)" }
|
||||
# rd with \\?\ prefix handles paths longer than 260 chars (node_modules)
|
||||
# errors (locked files) go to nul; the Test-Path below reports leftovers and the loop continues
|
||||
cmd /c "rd /s /q `"\\?\$full`" 2>nul"
|
||||
if (Test-Path -LiteralPath $full) {
|
||||
$failed += $r.Path
|
||||
if (-not $Json) { Write-Warning "not fully deleted: $($r.Path)" }
|
||||
} else { $deleted += $r.Path }
|
||||
}
|
||||
$freeAfter = (Get-PSDrive ($Root.Substring(0, 1))).Free
|
||||
$freedGB = [math]::Round(($freeAfter - $freeBefore) / 1GB, 2)
|
||||
if ($Json) {
|
||||
ConvertTo-Json -InputObject @{ deleted = @($deleted); failed = @($failed); freedGB = $freedGB } -Compress
|
||||
} else {
|
||||
Write-Host ("Freed {0} GB" -f $freedGB)
|
||||
}
|
||||
exit 0
|
||||
1
ComfyGen
Submodule
1
ComfyGen
Submodule
Submodule ComfyGen added at e7e3bcbbcb
21
Itch/README.md
Normal file
21
Itch/README.md
Normal file
@@ -0,0 +1,21 @@
|
||||
# Itch – Werkzeuge für itch.io-Seiten
|
||||
|
||||
Alles, um ein Projekt auf itch.io zu bringen. Ablauf steuert der Skill **`itchiocreater`**; Ergebnis landet
|
||||
im Projekt unter `docs\itchio\`. Motive für Cover/Banner kommen aus ComfyGen (`gen generate itch_keyart`).
|
||||
|
||||
| Ich brauche … | Werkzeug | Beispiel |
|
||||
|---|---|---|
|
||||
| Cover 630×500, Banner 960×256 + 1920×512, Hintergrund 1920×1200 mit Titel | `itch_images.py` | `py -3.12 itch_images.py --title "X" --tagline "…" --backdrop keyart.png [--cover-art cover.png] [--hero figur.png] [--font f.ttf] [--color "#hex"] --out docs\itchio` |
|
||||
| Echte Screenshots eines HTML-Spiels (automatisch, Headless-Edge) | `itch_screens.mjs` | `node itch_screens.mjs docs\itchio\shots.json` (Format im Dateikopf: Seite, Größe, pro Bild Query/Tasten/Klicks/JS) |
|
||||
| Screenshots eines exe-Spiels, während man spielt | `itch_capture.ps1` | `itch_capture.ps1 -Exe release\Spiel.exe -Every 4 -Count 20` · `-Hotkey` (F9 = Bild, Esc = Ende) · `-Title "Fenstertitel"` |
|
||||
| Screenshots im Rahmen mit Bildunterschrift (Store-Look) | `itch_promo.py` | `py -3.12 itch_promo.py --shots …\screenshots --captions captions.txt --backdrop keyart.png --out …\promo` |
|
||||
| Trailer-MP4 aus Screenshots + Musik (für YouTube-Link) | `itch_trailer.py` | `py -3.12 itch_trailer.py --shots … --music m.mp3 --title "X" --tagline "…" --footer "sn09.itch.io/x" --out trailer.mp4` |
|
||||
| Prüfen vor dem Upload | `itch_check.py` | `py -3.12 itch_check.py docs\itchio --upload release\x-web.zip --upload release\X.exe` |
|
||||
|
||||
Regeln:
|
||||
- Screenshots zeigen immer das **echte Spiel** (itch.io-Regel, sonst irreführend). KI-Bilder nur für Cover,
|
||||
Banner, Hintergrund und den Rahmen der Promo-Bilder.
|
||||
- KI-Offenlegung auf itch.io immer **Yes** (Grafik/Sound mit ComfyUI).
|
||||
- Voraussetzungen: Python 3.12 + Pillow, Node 18+, Microsoft Edge (Screenshots), ffmpeg (Trailer).
|
||||
|
||||
Vorbilder: `GladiatorIdle\docs\itchio\` (vollständig inkl. Trailer, install.html), `Pipefix\docs\itchio\`.
|
||||
94
Itch/itch_capture.ps1
Normal file
94
Itch/itch_capture.ps1
Normal file
@@ -0,0 +1,94 @@
|
||||
<#
|
||||
Screenshots of a running Windows game (exe) for itch.io: starts the game (or uses a running
|
||||
window), then saves the game window every few seconds while you play. Afterwards pick the best.
|
||||
|
||||
D:\Oculusquest\Projekt\_Tools\Itch\itch_capture.ps1 -Exe release\Spiel.exe -Out docs\itchio\screenshots
|
||||
... -Title "Gladiator" use an already running window whose title contains this text
|
||||
... -Every 4 -Count 30 -Delay 8 first shot after 8 s, then every 4 s, 30 shots
|
||||
... -Hotkey instead of a timer: one shot per press of F9 (Esc ends)
|
||||
|
||||
Captures what is on screen in the window rectangle (the window must be visible, not covered).
|
||||
Files: raw_001.png, raw_002.png, ... (existing ones are kept, numbering continues).
|
||||
#>
|
||||
param(
|
||||
[string]$Exe,
|
||||
[string]$Title,
|
||||
[string]$Out = 'docs\itchio\screenshots',
|
||||
[int]$Every = 4,
|
||||
[int]$Count = 20,
|
||||
[int]$Delay = 8,
|
||||
[switch]$Hotkey
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
Add-Type @'
|
||||
using System; using System.Runtime.InteropServices;
|
||||
public static class W32 {
|
||||
[StructLayout(LayoutKind.Sequential)] public struct RECT { public int L, T, R, B; }
|
||||
[DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr h, out RECT r);
|
||||
[DllImport("dwmapi.dll")] public static extern int DwmGetWindowAttribute(IntPtr h, int a, out RECT r, int s);
|
||||
[DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h);
|
||||
[DllImport("user32.dll")] public static extern short GetAsyncKeyState(int k);
|
||||
[DllImport("user32.dll")] public static extern bool SetProcessDPIAware();
|
||||
}
|
||||
'@
|
||||
[W32]::SetProcessDPIAware() | Out-Null
|
||||
|
||||
New-Item -ItemType Directory -Force $Out | Out-Null
|
||||
$proc = $null
|
||||
if ($Exe) {
|
||||
$exePath = (Resolve-Path $Exe).Path
|
||||
$proc = Start-Process $exePath -WorkingDirectory (Split-Path $exePath) -PassThru
|
||||
"Gestartet: $exePath - warte auf das Fenster ..."
|
||||
}
|
||||
function Find-Window {
|
||||
if ($proc) { $proc.Refresh(); if ($proc.MainWindowHandle -ne 0) { return $proc.MainWindowHandle } }
|
||||
if ($Title) {
|
||||
$p = Get-Process | Where-Object { $_.MainWindowHandle -ne 0 -and $_.MainWindowTitle -like "*$Title*" } | Select-Object -First 1
|
||||
if ($p) { return $p.MainWindowHandle }
|
||||
}
|
||||
if ($proc) { # launchers: the window may belong to a child process with the same name
|
||||
$p = Get-Process -Name $proc.ProcessName -ErrorAction SilentlyContinue | Where-Object MainWindowHandle -ne 0 | Select-Object -First 1
|
||||
if ($p) { return $p.MainWindowHandle }
|
||||
}
|
||||
return [IntPtr]::Zero
|
||||
}
|
||||
$h = [IntPtr]::Zero
|
||||
for ($i = 0; $i -lt 60 -and $h -eq [IntPtr]::Zero; $i++) { Start-Sleep -Milliseconds 500; $h = Find-Window }
|
||||
if ($h -eq [IntPtr]::Zero) { throw 'Kein Spielfenster gefunden (-Exe oder -Title angeben).' }
|
||||
|
||||
$n = (Get-ChildItem $Out -Filter 'raw_*.png' -ErrorAction SilentlyContinue | Measure-Object).Count
|
||||
function Snap {
|
||||
$r = New-Object W32+RECT
|
||||
# DWM bounds exclude the invisible resize border of Windows 10/11 windows
|
||||
if ([W32]::DwmGetWindowAttribute($h, 9, [ref]$r, 16) -ne 0) { [W32]::GetWindowRect($h, [ref]$r) | Out-Null }
|
||||
$w = $r.R - $r.L; $hh = $r.B - $r.T
|
||||
if ($w -lt 50 -or $hh -lt 50) { return }
|
||||
$bmp = New-Object System.Drawing.Bitmap $w, $hh
|
||||
$g = [System.Drawing.Graphics]::FromImage($bmp)
|
||||
$g.CopyFromScreen($r.L, $r.T, 0, 0, $bmp.Size)
|
||||
$script:n++
|
||||
$file = Join-Path $Out ('raw_{0:000}.png' -f $script:n)
|
||||
$bmp.Save($file, [System.Drawing.Imaging.ImageFormat]::Png)
|
||||
$g.Dispose(); $bmp.Dispose()
|
||||
" $file ($w x $hh)"
|
||||
}
|
||||
|
||||
[W32]::SetForegroundWindow($h) | Out-Null
|
||||
if ($Hotkey) {
|
||||
'F9 = Screenshot, Esc = fertig. Spiel jetzt im Vordergrund lassen.'
|
||||
while ($true) {
|
||||
if ([W32]::GetAsyncKeyState(0x78) -band 1) { Snap } # F9
|
||||
if ([W32]::GetAsyncKeyState(0x1B) -band 0x8000) { break } # Esc
|
||||
Start-Sleep -Milliseconds 30
|
||||
}
|
||||
} else {
|
||||
"Erster Screenshot in $Delay s, dann alle $Every s ($Count Stück). Einfach spielen."
|
||||
Start-Sleep -Seconds $Delay
|
||||
for ($i = 0; $i -lt $Count; $i++) {
|
||||
if ($proc -and $proc.HasExited -and (Find-Window) -eq [IntPtr]::Zero) { 'Spiel beendet.'; break }
|
||||
Snap
|
||||
Start-Sleep -Seconds $Every
|
||||
}
|
||||
}
|
||||
"Fertig: $script:n Screenshots in $((Resolve-Path $Out).Path) - die besten 5-8 behalten, Rest loeschen."
|
||||
101
Itch/itch_check.py
Normal file
101
Itch/itch_check.py
Normal file
@@ -0,0 +1,101 @@
|
||||
"""Pre-flight check of an itch.io package folder (docs/itchio) before uploading.
|
||||
|
||||
py -3.12 itch_check.py docs/itchio [--upload release/game-web.zip] [--upload release/Game.exe]
|
||||
|
||||
Checks: cover size/ratio, banner/background, screenshot count and size, description.html
|
||||
(no <script>, size, links), README fields filled, uploads exist (zip has index.html at the top,
|
||||
size limits). Prints OK / WARN / FEHLT lines - short on purpose.
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
import zipfile
|
||||
|
||||
from PIL import Image
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("folder")
|
||||
ap.add_argument("--upload", action="append", default=[])
|
||||
a = ap.parse_args()
|
||||
f = a.folder
|
||||
out = []
|
||||
ok = lambda s: out.append("OK " + s)
|
||||
warn = lambda s: out.append("WARN " + s)
|
||||
miss = lambda s: out.append("FEHLT " + s)
|
||||
|
||||
def img(name):
|
||||
p = os.path.join(f, name)
|
||||
return Image.open(p).size if os.path.exists(p) else None
|
||||
|
||||
c = img("cover.png")
|
||||
if not c:
|
||||
miss("cover.png (630x500)")
|
||||
elif c[0] < 315 or abs(c[0] / c[1] - 630 / 500) > 0.03:
|
||||
warn(f"cover.png {c[0]}x{c[1]} - empfohlen 630x500 (mind. 315x250, Verhältnis 1.26)")
|
||||
else:
|
||||
ok(f"cover.png {c[0]}x{c[1]}")
|
||||
for n in ("banner_960x256.png", "background_1920x1200.jpg"):
|
||||
(ok if img(n) else warn)(n + ("" if img(n) else " fehlt (nur für Edit theme)"))
|
||||
|
||||
shots = []
|
||||
for d in ("screenshots", "promo", "screens"):
|
||||
p = os.path.join(f, d)
|
||||
if os.path.isdir(p):
|
||||
shots += [os.path.join(p, x) for x in os.listdir(p) if x.lower().endswith((".png", ".jpg", ".gif")) and not x.startswith("raw_")]
|
||||
raws = [x for d in ("screenshots",) if os.path.isdir(os.path.join(f, d)) for x in os.listdir(os.path.join(f, d)) if x.startswith("raw_")]
|
||||
if len(shots) < 3:
|
||||
miss(f"Screenshots: {len(shots)} (mind. 3, gut 5-8)")
|
||||
else:
|
||||
small = [os.path.basename(s) for s in shots if Image.open(s).size[0] < 1280]
|
||||
big = [os.path.basename(s) for s in shots if os.path.getsize(s) > 3 * 1024 * 1024]
|
||||
ok(f"{len(shots)} Screenshots")
|
||||
if small:
|
||||
warn("klein (<1280 breit): " + ", ".join(small[:5]))
|
||||
if big:
|
||||
warn("über 3 MB (itch-Limit ok, aber langsam): " + ", ".join(big[:5]))
|
||||
if raws:
|
||||
warn(f"{len(raws)} raw_*.png aus itch_capture noch nicht aussortiert")
|
||||
|
||||
desc = os.path.join(f, "description.html")
|
||||
if not os.path.exists(desc):
|
||||
miss("description.html")
|
||||
else:
|
||||
t = open(desc, encoding="utf-8-sig").read()
|
||||
body = re.sub(r"(?is)^.*<body[^>]*>|</body>.*$", "", t)
|
||||
if re.search(r"<script|<iframe|<style", body, re.I):
|
||||
warn("description.html: <script>/<iframe>/<style> - itch entfernt das")
|
||||
if len(re.sub(r"<[^>]+>", "", t)) < 400:
|
||||
warn("description.html sehr kurz")
|
||||
if re.search(r"TODO|XXX|\{\{", t):
|
||||
warn("description.html enthält Platzhalter")
|
||||
ok(f"description.html ({len(t)} Zeichen)")
|
||||
|
||||
readme = os.path.join(f, "README.md")
|
||||
if not os.path.exists(readme):
|
||||
miss("README.md (Felder für Edit game)")
|
||||
else:
|
||||
t = open(readme, encoding="utf-8-sig").read()
|
||||
holes = re.findall(r"\|\s*([^|\n]+?)\s*\|\s*(?:_[^_]*_|…|TODO|\?)\s*\|", t)
|
||||
(warn("README: offene Felder: " + ", ".join(h.strip("* ") for h in holes[:8])) if holes else ok("README.md Felder ausgefüllt"))
|
||||
|
||||
for u in a.upload:
|
||||
if not os.path.exists(u):
|
||||
miss(f"Upload {u}")
|
||||
continue
|
||||
mb = os.path.getsize(u) / 1024 / 1024
|
||||
if u.lower().endswith(".zip"):
|
||||
with zipfile.ZipFile(u) as z:
|
||||
names = z.namelist()
|
||||
if "index.html" not in names:
|
||||
warn(f"{u}: kein index.html auf oberster Ebene (für Browser-Spiele nötig)")
|
||||
if len(names) > 1000:
|
||||
warn(f"{u}: {len(names)} Dateien (itch: max. 1000 für HTML-Spiele)")
|
||||
(warn if mb > 1000 else ok)(f"Upload {os.path.basename(u)} {mb:.1f} MB" + (" - über 1 GB: butler nötig" if mb > 1000 else ""))
|
||||
|
||||
print("\n".join(out))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
141
Itch/itch_images.py
Normal file
141
Itch/itch_images.py
Normal file
@@ -0,0 +1,141 @@
|
||||
"""itch.io page images from one backdrop picture + the game title.
|
||||
|
||||
py -3.12 itch_images.py --title "Pipefix" --tagline "Lay the pipes. Beat the flow." \
|
||||
--backdrop sprite-generator/output/backdrop_raw_00001_.png --out docs/itchio \
|
||||
[--font Assets/Fonts/PressStart2P-Regular.ttf] [--text-font ...] [--color "#d9a441"] \
|
||||
[--hero game/assets/Sprites/player.png] [--cover-art sprite-generator/output/itch_cover_raw_00001_.png]
|
||||
|
||||
Writes cover.png (630x500), banner_960x256.png, banner_1920x512.png, background_1920x1200.jpg.
|
||||
--cover-art: own picture for the cover (otherwise the backdrop). Title on the cover at the top,
|
||||
so the motif should leave the upper third calm. Use --cover-plain to keep the cover without text.
|
||||
Without --font a Windows system font (Segoe UI Black / Arial Bold) is used.
|
||||
Generalised from Pipefix/docs/itchio/make_images.py (that one also frames a board screenshot).
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
|
||||
from PIL import Image, ImageDraw, ImageEnhance, ImageFilter, ImageFont
|
||||
|
||||
SYSTEM_FONTS = [r"C:\Windows\Fonts\seguibl.ttf", r"C:\Windows\Fonts\arialbd.ttf"]
|
||||
SYSTEM_TEXT = [r"C:\Windows\Fonts\segoeui.ttf", r"C:\Windows\Fonts\arial.ttf"]
|
||||
|
||||
|
||||
def first_existing(paths):
|
||||
for p in paths:
|
||||
if p and os.path.exists(p):
|
||||
return p
|
||||
raise SystemExit("no font found - pass --font")
|
||||
|
||||
|
||||
def hex_rgb(s):
|
||||
s = s.lstrip("#")
|
||||
return tuple(int(s[i:i + 2], 16) for i in (0, 2, 4))
|
||||
|
||||
|
||||
def cover_crop(img, w, h):
|
||||
k = max(w / img.width, h / img.height)
|
||||
img = img.resize((round(img.width * k), round(img.height * k)), Image.LANCZOS)
|
||||
x, y = (img.width - w) // 2, (img.height - h) // 2
|
||||
return img.crop((x, y, x + w, y + h))
|
||||
|
||||
|
||||
def backdrop(src, w, h, dark=0.55, blur=0):
|
||||
img = cover_crop(src, w, h)
|
||||
if blur:
|
||||
img = img.filter(ImageFilter.GaussianBlur(blur))
|
||||
img = ImageEnhance.Brightness(img).enhance(dark)
|
||||
vig = Image.new("L", (w, h), 0)
|
||||
ImageDraw.Draw(vig).ellipse((-w * 0.25, -h * 0.35, w * 1.25, h * 1.35), fill=255)
|
||||
vig = vig.filter(ImageFilter.GaussianBlur(min(w, h) * 0.18))
|
||||
return Image.composite(img, Image.new("RGB", (w, h), (0, 0, 0)), vig)
|
||||
|
||||
|
||||
def fit_font(path, text, size, max_w):
|
||||
while size > 8:
|
||||
f = ImageFont.truetype(path, size)
|
||||
if f.getbbox(text)[2] <= max_w:
|
||||
return f
|
||||
size -= 2
|
||||
return ImageFont.truetype(path, size)
|
||||
|
||||
|
||||
def title(draw, xy, text, font, color, anchor="mm"):
|
||||
size = font.size
|
||||
off = max(2, size // 12)
|
||||
shadow = (12, 8, 4)
|
||||
dark = tuple(c // 3 for c in color)
|
||||
x, y = xy
|
||||
draw.text((x + off, y + off), text, font=font, fill=shadow, anchor=anchor)
|
||||
draw.text((x, y + off // 2), text, font=font, fill=dark, anchor=anchor)
|
||||
draw.text((x, y), text, font=font, fill=color, anchor=anchor, stroke_width=max(1, size // 24), stroke_fill=shadow)
|
||||
|
||||
|
||||
def text(draw, xy, s, font, fill=(230, 225, 215), anchor="mm"):
|
||||
draw.text((xy[0] + 2, xy[1] + 2), s, font=font, fill=(10, 8, 6), anchor=anchor)
|
||||
draw.text(xy, s, font=font, fill=fill, anchor=anchor)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--title", required=True)
|
||||
ap.add_argument("--tagline", default="")
|
||||
ap.add_argument("--backdrop", required=True)
|
||||
ap.add_argument("--out", default=".")
|
||||
ap.add_argument("--font")
|
||||
ap.add_argument("--text-font")
|
||||
ap.add_argument("--color", default="#4fd8ff")
|
||||
ap.add_argument("--hero", help="transparent PNG placed bottom-left on cover and banner")
|
||||
ap.add_argument("--cover-art", help="own picture for the cover (default: backdrop)")
|
||||
ap.add_argument("--cover-plain", action="store_true", help="cover without title/tagline")
|
||||
a = ap.parse_args()
|
||||
|
||||
os.makedirs(a.out, exist_ok=True)
|
||||
src = Image.open(a.backdrop).convert("RGB")
|
||||
tfont = first_existing([a.font] + SYSTEM_FONTS)
|
||||
xfont = first_existing([a.text_font, a.font] + SYSTEM_TEXT)
|
||||
color = hex_rgb(a.color)
|
||||
hero = Image.open(a.hero).convert("RGBA") if a.hero else None
|
||||
|
||||
def place_hero(img, size, xy):
|
||||
if hero:
|
||||
h = hero.copy()
|
||||
h.thumbnail((size, size), Image.LANCZOS)
|
||||
img.alpha_composite(h, xy)
|
||||
|
||||
# cover 630x500
|
||||
w, h = 630, 500
|
||||
csrc = Image.open(a.cover_art).convert("RGB") if a.cover_art else src
|
||||
img = backdrop(csrc, w, h, 1.0 if a.cover_art else 0.7).convert("RGBA")
|
||||
if not a.cover_art:
|
||||
place_hero(img, 220, (30, h - 250))
|
||||
if not a.cover_plain:
|
||||
if a.cover_art: # darken the top behind the title, keep the motif bright
|
||||
shade = Image.new("L", (w, h), 0)
|
||||
ImageDraw.Draw(shade).rectangle((0, 0, w, int(h * 0.42)), fill=150)
|
||||
shade = shade.filter(ImageFilter.GaussianBlur(40))
|
||||
img = Image.composite(Image.new("RGBA", (w, h), (0, 0, 0, 255)), img, shade)
|
||||
d = ImageDraw.Draw(img)
|
||||
ty = 80 if a.cover_art else 150
|
||||
title(d, (w // 2, ty), a.title, fit_font(tfont, a.title, 80, w - 60), color)
|
||||
if a.tagline:
|
||||
text(d, (w // 2, ty + 72), a.tagline, fit_font(xfont, a.tagline, 30, w - 60))
|
||||
img.convert("RGB").save(os.path.join(a.out, "cover.png"), optimize=True)
|
||||
|
||||
# banners
|
||||
for bw, bh in ((960, 256), (1920, 512)):
|
||||
k = bh / 256
|
||||
img = backdrop(src, bw, bh, 0.6).convert("RGBA")
|
||||
place_hero(img, round(200 * k), (round(24 * k), round(40 * k)))
|
||||
left = round((250 if hero else 40) * k)
|
||||
d = ImageDraw.Draw(img)
|
||||
title(d, (left, round(100 * k)), a.title, fit_font(tfont, a.title, round(70 * k), bw - left - 40), color, anchor="lm")
|
||||
if a.tagline:
|
||||
text(d, (left + 2, round(170 * k)), a.tagline, fit_font(xfont, a.tagline, round(32 * k), bw - left - 40), anchor="lm")
|
||||
img.convert("RGB").save(os.path.join(a.out, f"banner_{bw}x{bh}.png"), optimize=True)
|
||||
|
||||
backdrop(src, 1920, 1200, 0.45, blur=3).save(os.path.join(a.out, "background_1920x1200.jpg"), quality=86)
|
||||
print("ok ->", os.path.abspath(a.out))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
84
Itch/itch_promo.py
Normal file
84
Itch/itch_promo.py
Normal file
@@ -0,0 +1,84 @@
|
||||
"""Promo screenshots: real game screenshots framed on a (ComfyUI) backdrop with a short caption -
|
||||
the store look. The game image itself is never altered.
|
||||
|
||||
py -3.12 itch_promo.py --shots docs/itchio/screenshots --captions docs/itchio/captions.txt \
|
||||
--backdrop sprite-generator/output/itch_keyart_raw_00001_.png --out docs/itchio/promo \
|
||||
[--size 1920x1080] [--font C:/Windows/Fonts/seguibl.ttf] [--color "#4fd8ff"]
|
||||
|
||||
captions.txt: one line per screenshot, "file.png | Caption text" (files without a line are skipped).
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
|
||||
from PIL import Image, ImageDraw, ImageEnhance, ImageFilter, ImageFont
|
||||
|
||||
SYSTEM_FONTS = [r"C:\Windows\Fonts\seguibl.ttf", r"C:\Windows\Fonts\arialbd.ttf"]
|
||||
|
||||
|
||||
def hex_rgb(s):
|
||||
s = s.lstrip("#")
|
||||
return tuple(int(s[i:i + 2], 16) for i in (0, 2, 4))
|
||||
|
||||
|
||||
def cover_crop(img, w, h):
|
||||
k = max(w / img.width, h / img.height)
|
||||
img = img.resize((round(img.width * k), round(img.height * k)), Image.LANCZOS)
|
||||
x, y = (img.width - w) // 2, (img.height - h) // 2
|
||||
return img.crop((x, y, x + w, y + h))
|
||||
|
||||
|
||||
def fit_font(path, text, size, max_w):
|
||||
while size > 10:
|
||||
f = ImageFont.truetype(path, size)
|
||||
if f.getbbox(text)[2] <= max_w:
|
||||
return f
|
||||
size -= 2
|
||||
return ImageFont.truetype(path, size)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--shots", required=True)
|
||||
ap.add_argument("--captions", required=True)
|
||||
ap.add_argument("--backdrop", required=True)
|
||||
ap.add_argument("--out", required=True)
|
||||
ap.add_argument("--size", default="1920x1080")
|
||||
ap.add_argument("--font")
|
||||
ap.add_argument("--color", default="#4fd8ff")
|
||||
a = ap.parse_args()
|
||||
|
||||
W, H = map(int, a.size.lower().split("x"))
|
||||
font_path = a.font if a.font and os.path.exists(a.font) else next(p for p in SYSTEM_FONTS if os.path.exists(p))
|
||||
accent = hex_rgb(a.color)
|
||||
bg = cover_crop(Image.open(a.backdrop).convert("RGB"), W, H).filter(ImageFilter.GaussianBlur(6))
|
||||
bg = ImageEnhance.Brightness(bg).enhance(0.45)
|
||||
os.makedirs(a.out, exist_ok=True)
|
||||
|
||||
lines = [l.split("|", 1) for l in open(a.captions, encoding="utf-8-sig").read().splitlines() if "|" in l]
|
||||
for i, (fname, caption) in enumerate(lines, 1):
|
||||
fname, caption = fname.strip(), caption.strip()
|
||||
shot = Image.open(os.path.join(a.shots, fname)).convert("RGB")
|
||||
top = int(H * 0.19) # caption band
|
||||
maxw, maxh = int(W * 0.86), H - top - int(H * 0.06)
|
||||
k = min(maxw / shot.width, maxh / shot.height)
|
||||
shot = shot.resize((round(shot.width * k), round(shot.height * k)), Image.LANCZOS)
|
||||
img = bg.copy().convert("RGBA")
|
||||
x, y = (W - shot.width) // 2, top
|
||||
# shadow + thin accent frame
|
||||
sh = Image.new("RGBA", (shot.width + 80, shot.height + 80), (0, 0, 0, 0))
|
||||
ImageDraw.Draw(sh).rectangle((40, 40, 40 + shot.width, 40 + shot.height), fill=(0, 0, 0, 190))
|
||||
img.alpha_composite(sh.filter(ImageFilter.GaussianBlur(22)), (x - 40 + 10, y - 40 + 16))
|
||||
ImageDraw.Draw(img).rectangle((x - 4, y - 4, x + shot.width + 3, y + shot.height + 3), outline=accent, width=4)
|
||||
img.paste(shot, (x, y))
|
||||
d = ImageDraw.Draw(img)
|
||||
f = fit_font(font_path, caption, int(H * 0.07), int(W * 0.9))
|
||||
cy = top // 2
|
||||
d.text((W // 2 + 3, cy + 3), caption, font=f, fill=(0, 0, 0), anchor="mm")
|
||||
d.text((W // 2, cy), caption, font=f, fill=(255, 255, 255), anchor="mm", stroke_width=2, stroke_fill=(0, 0, 0))
|
||||
out = os.path.join(a.out, f"promo_{i:02d}.png")
|
||||
img.convert("RGB").save(out, optimize=True)
|
||||
print(out)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
86
Itch/itch_screens.mjs
Normal file
86
Itch/itch_screens.mjs
Normal file
@@ -0,0 +1,86 @@
|
||||
// Real screenshots of an HTML game for itch.io - headless Edge over the DevTools protocol,
|
||||
// no Playwright needed. Each shot loads the page fresh (own query string), runs its steps
|
||||
// (keys, clicks, JS, waits) and saves a PNG at the exact size.
|
||||
//
|
||||
// node D:\Oculusquest\Projekt\_Tools\Itch\itch_screens.mjs docs\itchio\shots.json
|
||||
//
|
||||
// shots.json (paths relative to the json file's project = cwd):
|
||||
// {
|
||||
// "page": "game/index.html", // or "release/x.html", or "http://localhost:5173/"
|
||||
// "size": "1920x1080", // viewport = image size
|
||||
// "out": "docs/itchio/screenshots",
|
||||
// "shots": [
|
||||
// { "name": "01_menu", "wait": 1500 },
|
||||
// { "name": "02_play", "query": "?play&level=3", "steps": [
|
||||
// { "key": "ArrowRight", "hold": 900 }, { "key": " " }, { "click": [960, 540] },
|
||||
// { "eval": "Kit.audio && 0" }, { "wait": 700 } ] }
|
||||
// ]
|
||||
// }
|
||||
// Step "key": name as in KeyboardEvent.key; "hold" ms keeps it pressed. "eval" runs JS in the
|
||||
// page (e.g. set a level, give coins - only to reach a real scene faster, never to fake one).
|
||||
import { spawn } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
|
||||
const specFile = process.argv[2];
|
||||
if (!specFile) { console.error('usage: node itch_screens.mjs <shots.json>'); process.exit(2); }
|
||||
const spec = JSON.parse(fs.readFileSync(specFile, 'utf8').replace(/^/, '')); // PowerShell writes a BOM
|
||||
const root = process.cwd();
|
||||
const [W, H] = (spec.size || '1920x1080').split('x').map(Number);
|
||||
const outDir = path.resolve(root, spec.out || 'docs/itchio/screenshots');
|
||||
fs.mkdirSync(outDir, { recursive: true });
|
||||
const pageUrl = /^https?:/.test(spec.page) ? spec.page : pathToFileURL(path.resolve(root, spec.page)).href;
|
||||
|
||||
const EDGE = ['C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe', 'C:/Program Files/Microsoft/Edge/Application/msedge.exe'].find(fs.existsSync);
|
||||
if (!EDGE) { console.error('Microsoft Edge nicht gefunden'); process.exit(1); }
|
||||
const PORT = 9300 + Math.floor(Math.random() * 500);
|
||||
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||
const KEYCODES = { ArrowLeft: 37, ArrowUp: 38, ArrowRight: 39, ArrowDown: 40, Enter: 13, Escape: 27, ' ': 32, Tab: 9, Shift: 16, Control: 17 };
|
||||
const codeOf = k => k === ' ' ? 'Space' : k.startsWith('Arrow') || k.length > 1 ? k : /[a-z]/i.test(k) ? 'Key' + k.toUpperCase() : /\d/.test(k) ? 'Digit' + k : k;
|
||||
|
||||
const prof = fs.mkdtempSync(path.join(os.tmpdir(), 'itchshots-'));
|
||||
const edge = spawn(EDGE, ['--headless=new', `--remote-debugging-port=${PORT}`, `--user-data-dir=${prof}`, '--allow-file-access-from-files',
|
||||
'--autoplay-policy=no-user-gesture-required', '--hide-scrollbars', '--mute-audio', `--window-size=${W},${H}`, 'about:blank']);
|
||||
const cleanup = () => { try { edge.kill(); } catch {} setTimeout(() => fs.rmSync(prof, { recursive: true, force: true }), 500); };
|
||||
|
||||
try {
|
||||
let targets;
|
||||
for (let i = 0; i < 60 && !targets; i++) { try { targets = await (await fetch(`http://127.0.0.1:${PORT}/json/list`)).json(); } catch { await sleep(200); } }
|
||||
const ws = new WebSocket(targets.find(t => t.type === 'page').webSocketDebuggerUrl);
|
||||
await new Promise(r => ws.addEventListener('open', r));
|
||||
let id = 0; const pending = {}; const errors = [];
|
||||
ws.addEventListener('message', ev => {
|
||||
const m = JSON.parse(ev.data);
|
||||
if (m.id && pending[m.id]) { pending[m.id](m); delete pending[m.id]; }
|
||||
if (m.method === 'Runtime.exceptionThrown') errors.push(m.params.exceptionDetails.exception?.description || m.params.exceptionDetails.text);
|
||||
});
|
||||
const send = (method, params = {}) => new Promise(r => { const i = ++id; pending[i] = r; ws.send(JSON.stringify({ id: i, method, params })); });
|
||||
await send('Runtime.enable');
|
||||
await send('Emulation.setDeviceMetricsOverride', { width: W, height: H, deviceScaleFactor: 1, mobile: false });
|
||||
|
||||
const key = async (k, type) => send('Input.dispatchKeyEvent', { type, key: k, code: codeOf(k), windowsVirtualKeyCode: KEYCODES[k] ?? k.toUpperCase().charCodeAt(0), text: type === 'keyDown' && k.length === 1 ? k : undefined });
|
||||
for (const shot of spec.shots) {
|
||||
errors.length = 0;
|
||||
await send('Page.navigate', { url: pageUrl + (shot.query || '') });
|
||||
await sleep(shot.load ?? 1200);
|
||||
for (const s of shot.steps || []) {
|
||||
if (s.wait) await sleep(s.wait);
|
||||
if (s.key) { await key(s.key, 'keyDown'); await sleep(s.hold ?? 60); await key(s.key, 'keyUp'); }
|
||||
if (s.click) for (const type of ['mousePressed', 'mouseReleased']) await send('Input.dispatchMouseEvent', { type, x: s.click[0], y: s.click[1], button: 'left', clickCount: 1 });
|
||||
if (s.eval) await send('Runtime.evaluate', { expression: s.eval, awaitPromise: true });
|
||||
if (s.after) await sleep(s.after);
|
||||
}
|
||||
await sleep(shot.wait ?? 300);
|
||||
const r = await send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false });
|
||||
const file = path.join(outDir, `${shot.name}.png`);
|
||||
fs.writeFileSync(file, Buffer.from(r.result.data, 'base64'));
|
||||
console.log(`${shot.name}.png${errors.length ? ` (Fehler im Spiel: ${errors[0].split('\n')[0]})` : ''}`);
|
||||
}
|
||||
ws.close();
|
||||
console.log(`Fertig: ${spec.shots.length} Screenshots in ${outDir} (${W}x${H})`);
|
||||
} catch (e) {
|
||||
console.error('FAIL', e.message || e);
|
||||
process.exitCode = 1;
|
||||
} finally { cleanup(); }
|
||||
122
Itch/itch_trailer.py
Normal file
122
Itch/itch_trailer.py
Normal file
@@ -0,0 +1,122 @@
|
||||
"""Trailer (MP4, 1920x1080) from screenshots: slow Ken-Burns move per image, soft cross-fades,
|
||||
music, end card with title + tagline + footer. Generalised from GladiatorIdle/docs/itchio/make_trailer.py.
|
||||
Upload to YouTube, put the link into itch.io "Gameplay video or trailer". Needs ffmpeg in PATH.
|
||||
|
||||
py -3.12 itch_trailer.py --shots docs/itchio/screenshots --music game/assets/Audio/music_game.mp3 \
|
||||
--title "PIPEFIX" --tagline "Lay the pipes. Beat the flow." --footer "sn09.itch.io/pipefix" \
|
||||
--out docs/itchio/trailer.mp4 [--order 01_menu,03_play,...] [--secs 3.2] [--card-bg background_1920x1200.jpg]
|
||||
[--font C:/Windows/Fonts/seguibl.ttf] [--color "#4fd8ff"]
|
||||
Without --order all PNG/JPG in --shots are used in name order.
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFont, ImageFilter
|
||||
|
||||
FADE, FPS = 0.6, 30
|
||||
|
||||
|
||||
def hex_rgb(s):
|
||||
s = s.lstrip("#")
|
||||
return tuple(int(s[i:i + 2], 16) for i in (0, 2, 4))
|
||||
|
||||
|
||||
def fit(path, text, size, max_w):
|
||||
while size > 12:
|
||||
f = ImageFont.truetype(path, size)
|
||||
if f.getbbox(text)[2] <= max_w:
|
||||
return f
|
||||
size -= 4
|
||||
return ImageFont.truetype(path, size)
|
||||
|
||||
|
||||
def end_card(path, a, first_shot):
|
||||
src = a.card_bg or first_shot
|
||||
im = Image.open(src).convert("RGB")
|
||||
k = max(1920 / im.width, 1080 / im.height)
|
||||
im = im.resize((round(im.width * k), round(im.height * k)), Image.LANCZOS)
|
||||
im = im.crop(((im.width - 1920) // 2, (im.height - 1080) // 2, (im.width - 1920) // 2 + 1920, (im.height - 1080) // 2 + 1080))
|
||||
im = Image.blend(im.filter(ImageFilter.GaussianBlur(4)), Image.new("RGB", im.size, (0, 0, 0)), 0.6)
|
||||
d = ImageDraw.Draw(im)
|
||||
bold = a.font if a.font and os.path.exists(a.font) else r"C:\Windows\Fonts\seguibl.ttf"
|
||||
regular = r"C:\Windows\Fonts\segoeui.ttf"
|
||||
rows = [(a.title, fit(bold, a.title, 150, 1700), 400, hex_rgb(a.color)),
|
||||
(a.tagline, fit(bold, a.tagline, 56, 1700), 560, (240, 236, 228)),
|
||||
(a.footer, fit(regular, a.footer, 40, 1700), 780, (200, 196, 188))]
|
||||
for txt, f, y, col in rows:
|
||||
if not txt:
|
||||
continue
|
||||
d.text((964, y + 4), txt, font=f, fill=(0, 0, 0), anchor="mm")
|
||||
d.text((960, y), txt, font=f, fill=col, anchor="mm")
|
||||
im.save(path)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--shots", required=True)
|
||||
ap.add_argument("--music")
|
||||
ap.add_argument("--title", required=True)
|
||||
ap.add_argument("--tagline", default="")
|
||||
ap.add_argument("--footer", default="")
|
||||
ap.add_argument("--out", required=True)
|
||||
ap.add_argument("--order")
|
||||
ap.add_argument("--secs", type=float, default=3.2)
|
||||
ap.add_argument("--card-bg")
|
||||
ap.add_argument("--font")
|
||||
ap.add_argument("--color", default="#4fd8ff")
|
||||
a = ap.parse_args()
|
||||
|
||||
if a.order:
|
||||
names = [n.strip() for n in a.order.split(",") if n.strip()]
|
||||
imgs = []
|
||||
for n in names:
|
||||
p = next((os.path.join(a.shots, n + e) for e in ("", ".png", ".jpg") if os.path.isfile(os.path.join(a.shots, n + e))), None)
|
||||
if not p:
|
||||
raise SystemExit(f"fehlt: {n}")
|
||||
imgs.append(p)
|
||||
else:
|
||||
imgs = sorted(os.path.join(a.shots, f) for f in os.listdir(a.shots) if f.lower().endswith((".png", ".jpg")))
|
||||
if not imgs:
|
||||
raise SystemExit("keine Screenshots")
|
||||
|
||||
dur = a.secs
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
card = os.path.join(t, "end.png")
|
||||
end_card(card, a, imgs[0])
|
||||
clips = []
|
||||
for i, p in enumerate(imgs + [card]):
|
||||
c = os.path.join(t, f"c{i:02d}.mp4")
|
||||
frames = int((dur + FADE) * FPS)
|
||||
z = "if(eq(on,0),1.0,min(zoom+0.0009,1.12))" if i % 2 == 0 else "if(eq(on,0),1.12,max(zoom-0.0009,1.0))"
|
||||
vf = (f"scale=3840:2160:force_original_aspect_ratio=increase,crop=3840:2160,"
|
||||
f"zoompan=z='{z}':x='iw/2-(iw/zoom/2)':y='ih/2-(ih/zoom/2)':d={frames}:s=1920x1080:fps={FPS},format=yuv420p")
|
||||
subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-loop", "1", "-i", p, "-vf", vf, "-frames:v", str(frames),
|
||||
"-c:v", "libx264", "-preset", "medium", "-crf", "18", c], check=True)
|
||||
clips.append(c)
|
||||
args = ["ffmpeg", "-y", "-loglevel", "error"]
|
||||
for c in clips:
|
||||
args += ["-i", c]
|
||||
filt, last, off = [], "[0:v]", dur
|
||||
for i in range(1, len(clips)):
|
||||
out = f"[v{i}]"
|
||||
filt.append(f"{last}[{i}:v]xfade=transition=fade:duration={FADE}:offset={off:.2f}{out}")
|
||||
last, off = out, off + dur
|
||||
total = off + FADE
|
||||
if len(clips) == 1:
|
||||
filt, last = ["[0:v]null[v0]"], "[v0]"
|
||||
if a.music:
|
||||
args += ["-i", a.music, "-filter_complex",
|
||||
";".join(filt) + f";[{len(clips)}:a]atrim=0:{total:.2f},afade=t=in:d=1,afade=t=out:st={max(0, total - 2.5):.2f}:d=2.5[a]",
|
||||
"-map", last, "-map", "[a]", "-c:a", "aac", "-b:a", "192k", "-shortest"]
|
||||
else:
|
||||
args += ["-filter_complex", ";".join(filt), "-map", last]
|
||||
args += ["-c:v", "libx264", "-preset", "medium", "-crf", "18", "-pix_fmt", "yuv420p", a.out]
|
||||
os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True)
|
||||
subprocess.run(args, check=True)
|
||||
print("ok", a.out, f"{total:.0f} s")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
81
Library/PROJEKTE.md
Normal file
81
Library/PROJEKTE.md
Normal file
@@ -0,0 +1,81 @@
|
||||
# Projektübersicht – was gibt es, was taugt als Vorbild
|
||||
|
||||
Stand 2026-11-10, alle Ordner unter `D:\Oculusquest\Projekt`. Für Status/Priorität gilt das Projekt-Dashboard
|
||||
(`.dashboard.json`); diese Liste sagt, **wo man abschreiben kann**.
|
||||
|
||||
## HTML-/Web-Spiele (Vanilla JS, Canvas)
|
||||
|
||||
| Projekt | Was | Vorbild für |
|
||||
|---|---|---|
|
||||
| **Pipefix** | Rohr-Puzzle, 100+ Level | ganze Release-Kette: `launcher\` (WebView2-exe), `build-web.mjs`, `build.ps1`, `docs\itchio\` (+ `make_images.py`), `docs\firebase\` (Online-Highscores), Tutorial-Seiten, Lautstärke-Regler → Grundlage von `web/template` |
|
||||
| **Byte Path** | Kachel-Rätsel, 24 Level | Simulation ohne DOM (`game\engine.js`, läuft in Node), Level als ASCII-Karten, **Löser** `tools\solve.js` (A*) + `tools\verify.js`, Synth-Sounds, Demo-Modus `?demo` |
|
||||
| **Boulder Bound** | Felsbrocken-Puzzle | `game\selftest.js` (Selbsttest im Spiel), kompakte Level-Datei |
|
||||
| YouGreedyPig, kochbuch, RecycleBoy-master | kleine HTML-Seiten/Spiele | – |
|
||||
| Particle Panic | leer (geplant?) | – |
|
||||
|
||||
## Mobile (Vite + Capacitor)
|
||||
|
||||
| Projekt | Was | Vorbild für |
|
||||
|---|---|---|
|
||||
| **XP-Battleship** | Idle-Shooter, TS, Play Store | Werbung/UMP, IAP, Haptik, Audio, robuster Spielstand (→ `mobile/kit`), Firebase-Auth + Cloud-Save + Bestenliste (`src\online.ts`), Skilltree, i18n, Playwright-Tests, `RELEASE-CHECKLIST.md`, Store-Screenshots |
|
||||
| **Atlas Legends** | GPS-Spiel, React + Tailwind + Leaflet | Karten (Leaflet + Cluster), Google-Login, Gilden, Bestenliste, Benachrichtigungen, `hooks\useGpsTracking.js` |
|
||||
| SuryoyoGo - Kopie | Vorgänger von Atlas Legends | – |
|
||||
| **GallerySwiper** | Foto-Aufräum-App, React Native (Expo) | Store-Veröffentlichung (`docs\PUBLISH_GUIDE.md`, `release-notes\`), Store-Screenshots `design-gen\`, große `translations.ts` |
|
||||
|
||||
## C++ (TinyForge-Engine: SDL3, OpenGL, Dear ImGui, GLM, EnTT)
|
||||
|
||||
| Projekt | Was | Hinweis |
|
||||
|---|---|---|
|
||||
| **TinyWold** | Dorf-Simulation, Ursprung der Engine | `docs\architecture.md`, Tests/Audits ohne Fenster |
|
||||
| **AquaNova** | Aquarium-Spiel | neueste Engine-Änderungen (Shader, Bundle); `CLAUDE.md` mit erprobten Arbeitsregeln |
|
||||
| aqfresh | Neustart von AquaNova | sauberste `CLAUDE.md`-Vorlage für C++-Spiele |
|
||||
| AquaNovaAndroid | Android-Port | Engine stark abgewandelt |
|
||||
| Slot Machine | Spielautomat + Arduino-Tasten (`firmware\`) | Hardware-Anbindung, `release.bat`, `package_usb.bat` |
|
||||
|
||||
**Neues C++-Spiel:** `Engine\` + `ThirdParty\` + `CMakePresets.json` aus **AquaNova** kopieren (neuester Stand),
|
||||
`CLAUDE.md`-Aufbau von **aqfresh** übernehmen. Die Kopien sind absichtlich getrennt (kein gemeinsames
|
||||
Modul), Fixes werden von Hand übertragen – siehe `aqfresh\CLAUDE.md` „Where this came from“.
|
||||
Build: PowerShell, nie Bash (`cmake --preset mingw-release`).
|
||||
|
||||
## C# / .NET (Windows)
|
||||
|
||||
| Projekt | Was | Vorbild für |
|
||||
|---|---|---|
|
||||
| **GladiatorIdle** | MonoGame-3D-Spiel | `Core\LocalizationManager.cs` + `Languages\*.json`, `Core\AppSettings.cs`, `Core\SoundManager.cs`, `Core\NameVoice.cs` (Stimme), Playtest-Bots, `.gim`-Modelle (ModelTools) |
|
||||
| **DesktopAnt** | Desktop-Haustier (WinForms) | `Core\LayeredWindow.cs` (transparente Fenster), `Core\WindowHelper.cs` (andere Fenster finden), `Core\Highscores.cs`, `Physics\Physics.cs` |
|
||||
| Desktop - Playmode | Physik-Sandkasten (WinForms, .NET Framework 4.8) | Physik, Chemie/Optik/Elektronik-Werkstatt, Spiel auf Taskleiste/Fensterkanten; Schwester von DesktopAnt |
|
||||
| BilderDashboard | Foto-Dashboard (Node + C#-Launcher) | Node-Server + exe-Launcher, `thumbnailer\` |
|
||||
| ProjectDashboard (`_Tools`) | Projektverwaltung | dito, `.dashboard.json`-Format |
|
||||
| PowerBackupPro_Clean | Backup-Suite | mehrere Tools in einer `.sln` |
|
||||
| FotoAlbum | A4-Fotoalben (WPF) | PDF-/Druck-Layout |
|
||||
| ReminderOrganizer, DataOrganizer | WPF-Tools | – |
|
||||
| MobileConnector | Handy per ADB (WPF) | ADB-Anbindung |
|
||||
| YourlifeisGame | Lebens-Simulation (WinForms, .NET 9, NAudio) | Pflicht-Mehrsprachigkeit `L.t("key")` (Regeln in `CLAUDE.md`), Sprite-Manifest |
|
||||
| Defend the Castle, The Chaos Haus | Unity | – |
|
||||
|
||||
## Android nativ / Flutter
|
||||
|
||||
| Projekt | Was | Vorbild für |
|
||||
|---|---|---|
|
||||
| **MyRecipeStore** | Rezepte offline | Kotlin + Compose + Room + DataStore + AdMob |
|
||||
| **StorageFlow** | Speicher-Manager | Kotlin + Compose + Hilt + Room |
|
||||
| DesktopAntMobile, PopPop Balloons | Android-Spiele (Gradle) | – |
|
||||
| Atlas of Legends | Flutter + Firebase Mobile-Spiel | Dart-/Flutter-Struktur, ausführliche `CLAUDE.md` |
|
||||
|
||||
## Python
|
||||
|
||||
| Projekt | Was | Vorbild für |
|
||||
|---|---|---|
|
||||
| Endless Battlelines | Pygame-Auto-Battler | alles prozedural (Sprites aus Primitiven, Synth-Audio), PyInstaller-exe |
|
||||
| TimeLens | Foto-/Video-Suche (EXIF), Web-UI | große Sammlungen indizieren |
|
||||
| TevionScanner | Treiber-Ersatz Dia-Scanner | Geräte-Ansteuerung |
|
||||
| MicroCam | USB-Mikroskop-Tool | Kamera, exe-Paket |
|
||||
| Soundclick | Sound-Gerät/Treiber | – |
|
||||
| Familie-Malkano | A4-Buch aus ComfyUI-Bildern | Druck-Layout mit ComfyUI |
|
||||
| VideoStudio, Stammbaum | klein | `_Tools\Video\make_video.py` für Foto-Videos |
|
||||
|
||||
## Sonstiges
|
||||
|
||||
- AlbionOnlineDash – Node-Dashboard für ein Online-Spiel.
|
||||
- CatMaus (Electron), CatMaus 2 – JS-Spiel mit WAV-Sounds.
|
||||
- Arduino Projekte – `.ino` + PlatformIO (`KlopfSchloss`).
|
||||
111
Library/README.md
Normal file
111
Library/README.md
Normal file
@@ -0,0 +1,111 @@
|
||||
# Library – Vorlagen und Code-Bausteine für neue Projekte
|
||||
|
||||
`D:\Oculusquest\Projekt\_Tools\Library` ist der Startpunkt für **jedes neue Projekt**.
|
||||
Grafik/Sound/3D kommen weiter aus `ComfyGen` (Katalog `_Tools\README.md`), hier liegt der **Code**:
|
||||
fertige Projekt-Gerüste und erprobte Bausteine, herausgelöst aus Pipefix, Byte Path und XP-Battleship.
|
||||
|
||||
**Claude: bei „neues Projekt / neues Spiel“ zuerst diese Datei lesen, dann `PROJEKTE.md`
|
||||
(welches bestehende Projekt ist das beste Vorbild).**
|
||||
|
||||
## Neues Projekt in einem Befehl
|
||||
|
||||
```powershell
|
||||
D:\Oculusquest\Projekt\_Tools\Library\new-project.ps1 -Name "Particle Panic" # HTML-Spiel
|
||||
D:\Oculusquest\Projekt\_Tools\Library\new-project.ps1 -Name "Star Miner" -Type mobile # Android-App
|
||||
```
|
||||
|
||||
Legt `D:\Oculusquest\Projekt\<Name>\` an: Vorlage mit ersetzten Namen, Kit-Kopie, `sprite-generator\`
|
||||
(ComfyGen, `ASSETS_DIR` schon richtig), Asset-Ordner, `.gitignore`, `README.md`, `CLAUDE.md`,
|
||||
`.dashboard.json` (Status „Aktiv“ im Projekt-Dashboard), `git init` (ohne Commit).
|
||||
Optionen: `-Root <Ordner>` · `-NoGit` · `-NoGenerator` · `-Force` (Ordner existiert schon, fast leer).
|
||||
|
||||
## Welche Vorlage?
|
||||
|
||||
| Projektart | Vorlage | Ergebnis | Vorbild |
|
||||
|---|---|---|---|
|
||||
| 2D-Spiel für PC + Browser + itch.io | `webgame` | `game/index.html` (Doppelklick), `release\<Name>.exe`, `<slug>.html`, `<slug>-web.zip` | Pipefix, Byte Path, Boulder Bound |
|
||||
| Mobile-Spiel/App für Android (Werbung, Käufe) | `mobile` | Vite + TS + Capacitor, `npm start` / `npm run android` | XP-Battleship |
|
||||
| 3D-/Engine-Spiel C++ | – (kopieren) | TinyForge-Engine kopieren, siehe `PROJEKTE.md` | AquaNova, TinyWold |
|
||||
| Windows-Desktop-Tool | – (kopieren) | WinForms/WPF, siehe `PROJEKTE.md` | DesktopAnt, BilderDashboard |
|
||||
| Android nativ (Kotlin/Compose) | – (kopieren) | siehe `PROJEKTE.md` | MyRecipeStore, StorageFlow |
|
||||
|
||||
## Vorlage `webgame` – HTML-Canvas-Spiel ohne Build-Schritt
|
||||
|
||||
```
|
||||
game/index.html Seite, HUD, Overlays, Touch-Pad, Fensterknöpfe (nur in der exe)
|
||||
game/game.js Demo-Spiel (Orbs sammeln, 60 s) mit Menü, Pause, Speichern, Sound, Highscores,
|
||||
Sprachknopf (English/Deutsch) und Credits-Zeile (© Jahr Michael Media + Discord)
|
||||
game/lang.js alle Texte, Englisch + Deutsch (L.t('key'), data-i18n="key")
|
||||
game/kit/ Kopie von web/kit
|
||||
launcher/ WebView2-Fenster: eine exe, Spiel eingebettet, randlos, F11/Alt+Enter
|
||||
build-web.mjs alles in EINE HTML-Datei (Skripte inline, Assets als data:-URI)
|
||||
build.ps1 exe + html + zip (itch.io); app.ico automatisch aus Sprites\icon.png
|
||||
docs/firebase/ Online-Highscores einrichten (Regeln + Anleitung)
|
||||
docs/itchio/ Felder-Tabelle + description.html
|
||||
```
|
||||
|
||||
Getestet (2026-11-10): Anlegen, `build.ps1` (exe 64 MB, html, zip), Headless-Edge-Test von
|
||||
`game/index.html` und der Ein-Datei-Version (Menü, Bewegen, Pause, Speichern, eingebettete Assets).
|
||||
|
||||
### web/kit – Bausteine (klassische Skripte, globales `Kit`, laufen unter `file://`)
|
||||
|
||||
| Datei | Inhalt |
|
||||
|---|---|
|
||||
| `kit-core.js` | `Kit.$`, `Kit.asset` (data:-URI im Release), `Kit.loadBytes`, `Kit.images` (mit `img.ok`), `Kit.store(prefix)` (sicheres localStorage), `Kit.saveSlot` (Version, Defaults-Merge, Backup, `failed()`), `Kit.rng(seed)`, `clamp/lerp/pick/shuffle`, `Kit.fmt` (1.23M) |
|
||||
| `kit-audio.js` | `Kit.createAudio({prefix, files, throttle})`: `sfx`, `music` (Wechsel mit Fade), `loop`, `toggleMute`, `setVolume`, `duck`, Synth `tone/noise/arp` als Platzhalter; entsperrt sich beim ersten Klick/Tastendruck, Android-Hintergrund-Fix |
|
||||
| `kit-loop.js` | `Kit.loop({step, update, render})` fester Takt + Interpolation, pausiert bei verstecktem Tab; `Kit.fit(app, {canvases})` feste Designgröße auf Fenster skaliert, scharf auf HiDPI; `Kit.toCanvas` |
|
||||
| `kit-input.js` | `Kit.input({keys, onPress})`: Tasten → Aktionen, `down/latest/consume`, Touch-Knöpfe per `data-action` |
|
||||
| `kit-host.js` | `Kit.host`: `exe`, `fullscreen/minimize/quit`, `dragArea` – Gegenstück zum Launcher |
|
||||
| `kit-scores.js` | `Kit.scores({url})`: Firebase-REST `top(n)` / `submit({name,score,level})`, offline ohne URL; `Kit.cleanName`, `Kit.badName` (Schimpfwortfilter) |
|
||||
| `kit-fx.js` | `Kit.fx()`: Partikel, schwebende Texte, Screenshake; `Kit.ease`, `Kit.tween` |
|
||||
| `kit-i18n.js` | `Kit.i18n(window.LANG, {prefix})`: `t(key, vars)`, `set/next` (merkt Wahl), `apply()` füllt `data-i18n`, `-html`, `-title`, `-placeholder`; Start = gespeicherte Wahl → Browsersprache → en |
|
||||
|
||||
### tools (Library-weit)
|
||||
|
||||
- `tools/project-check.mjs` – Kurzbericht über ein bestehendes Projekt (~20 Zeilen, < 1 s): Stack, große Dateien,
|
||||
Kit-Stand (veraltet / im Projekt geändert), selbst gebaute Dinge, die ein Kit schon kann, Library-Kandidaten,
|
||||
ComfyUI-Nutzen (Generator da?, App-Icon, gezeichnete Grafik, Synth-Töne statt Sounds, Story → Stimmen, Server an/aus),
|
||||
Hygiene (git, README, CLAUDE.md, .gitignore, Release älter als Code, TODOs, Tests).
|
||||
`node D:\Oculusquest\Projekt\_Tools\Library\tools\project-check.mjs <Projekt> [--all]` · genutzt vom Skill `projekt-check`.
|
||||
|
||||
### itch.io
|
||||
|
||||
Werkzeuge für die itch.io-Seite (Cover/Banner, Screenshots, Promo-Bilder, Trailer, Prüfung) liegen in
|
||||
`_Tools\Itch\` (README dort); den ganzen Ablauf macht der Skill `itchiocreater`.
|
||||
|
||||
## Vorlage `mobile` – Vite + TypeScript + Capacitor
|
||||
|
||||
Demo: Orb antippen → Münze, Vibration, Sound; „2x coins (ad)“ zeigt Rewarded-Werbung (Browser: Attrappe).
|
||||
Texte in `src/lang.ts` (Englisch + Deutsch, 🌐-Knopf), Credits-Zeile unten, App-Icon-Anleitung im README.
|
||||
Getestet (2026-11-10): Anlegen, `npm install`, `npm run build` (tsc strict + vite), Laden im Headless-Edge.
|
||||
|
||||
### mobile/kit – Bausteine (ES-Module, nach `src/kit/` kopiert)
|
||||
|
||||
| Datei | Inhalt |
|
||||
|---|---|
|
||||
| `audio.ts` | `configureAudio`, `initAudio`, `playMusic`, `playSfx` (Throttle, erstes Abspielen nicht stumm), `toggleMute`, `setVolumes`, `duckMusic`, `suspendAudio/resumeAudio` |
|
||||
| `save.ts` | `createSaveStore<T>({key, version, defaults, normalize, migrate})` mit Backup-Slot + `failed()`; Helfer `arr`, `num`, `rec` (RTDB-/NaN-Reparatur); `offlineSeconds` |
|
||||
| `haptics.ts` | `hapticLight` (gedrosselt), `hapticMedium`, `hapticHeavy`, `toggleHaptics` |
|
||||
| `ads.ts` | `configureAds({testing, rewarded})`, `initAds` (UMP-Einwilligung zuerst), `showRewarded(placement)` mit Watchdog, `needsPrivacyOptions`/`showPrivacyOptions` |
|
||||
| `iap.ts` | `configureIap({nonConsumable})`, `purchase` → `owned`/`failed`/`pending`, `productPrice`, `restorePurchases` |
|
||||
| `i18n.ts` | `createI18n({en, de}, key)` → `t("key", {n})`, Gerätesprache, `setLang` |
|
||||
| `lifecycle.ts` | `onBack` (Stapel, sonst minimieren), `onPause` (hier speichern!), `onResume`, `exitApp` |
|
||||
|
||||
## Regeln
|
||||
|
||||
- **Kit-Dateien im Projekt nicht verändern.** Fehler/Erweiterung → hier in `web/kit` bzw. `mobile/kit`
|
||||
ändern (Version im Kopf hochzählen), dann im Projekt `new-project.ps1 -UpdateKit -Path <Projekt>`.
|
||||
Projekte bekommen eine **Kopie** (nicht Verweis), weil Release-Builds alles einbetten müssen und ein
|
||||
Library-Update kein fertiges Spiel unbemerkt ändern soll.
|
||||
- Was sich in einem Projekt bewährt und allgemein ist (z. B. Achievement-System, Tutorial-Overlay,
|
||||
Level-Löser), hierher übernehmen und in die Tabellen oben eintragen.
|
||||
- Vorlagen-Platzhalter: `{{NAME}}` (Anzeigename), `{{SLUG}}` (klein, nur a–z0–9), `{{IDENT}}`
|
||||
(C#-Name, PascalCase), `{{DATE}}`, `{{YEAR}}`. Dateien, die eine IDE in der Library nicht anfassen soll,
|
||||
heißen `*.template` (z. B. `Launcher.csproj.template`) – das Skript entfernt die Endung.
|
||||
- Nichts in `web/template` oder `mobile/template` bauen/installieren (kein `obj/`, `node_modules/`).
|
||||
|
||||
## Ideen für später
|
||||
|
||||
- C++: TinyForge-Engine als eigene Vorlage (`-Type cpp`), sobald eine Kopie als „Stand“ festgelegt ist.
|
||||
- web/kit: Achievements, Tutorial-Seiten, Level-Auswahl-Raster.
|
||||
- Gemeinsamer Store-Screenshot-Generator (GallerySwiper `design-gen\store_screens.py`, XP-Battleship `scripts\store-screenshots.mjs`).
|
||||
114
Library/mobile/kit/ads.ts
Normal file
114
Library/mobile/kit/ads.ts
Normal file
@@ -0,0 +1,114 @@
|
||||
// Kit ads (v1) - AdMob rewarded ads with Google UMP consent (EEA/UK).
|
||||
// From _Tools\Library\mobile\kit (XP-Battleship/src/ads.ts). Needs @capacitor-community/admob.
|
||||
//
|
||||
// configureAds({ testing: false, rewarded: { revive: "ca-app-pub-xxx/yyy", double: "..." } });
|
||||
// await initAds(); // at boot (native only, no-op on web)
|
||||
// if (await showRewarded("revive")) grant();
|
||||
// if (needsPrivacyOptions()) show an "Ad settings" button -> showPrivacyOptions()
|
||||
//
|
||||
// Consent gathering is inert until a GDPR message AND a privacy-options form are published for
|
||||
// the app in the AdMob console. TESTING must be false in the Play-Store build.
|
||||
|
||||
import { Capacitor } from "@capacitor/core";
|
||||
import { resumeAudio, suspendAudio } from "./audio";
|
||||
|
||||
const TEST_REWARDED_ID = "ca-app-pub-3940256099942544/5224354917"; // Google's official test unit
|
||||
|
||||
const cfg: { testing: boolean; rewarded: Record<string, string> } = { testing: true, rewarded: {} };
|
||||
|
||||
export function configureAds(c: { testing: boolean; rewarded: Record<string, string> }): void {
|
||||
cfg.testing = c.testing;
|
||||
cfg.rewarded = c.rewarded;
|
||||
}
|
||||
|
||||
let initialized = false;
|
||||
let adShowing = false;
|
||||
let privacyOptionsRequired = false;
|
||||
|
||||
/** Fails open on purpose (no network, no published message) - only an explicit
|
||||
* canRequestAds:false (user declined) disables ads. */
|
||||
async function gatherConsent(): Promise<boolean> {
|
||||
const { AdMob, AdmobConsentStatus } = await import("@capacitor-community/admob");
|
||||
try {
|
||||
let info = await AdMob.requestConsentInfo();
|
||||
if (info.isConsentFormAvailable && info.status === AdmobConsentStatus.REQUIRED) {
|
||||
info = await AdMob.showConsentForm();
|
||||
}
|
||||
// enum not re-exported from the plugin entry point - compare the string value
|
||||
privacyOptionsRequired = String(info.privacyOptionsRequirementStatus) === "REQUIRED";
|
||||
return info.canRequestAds !== false;
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
export function needsPrivacyOptions(): boolean {
|
||||
return privacyOptionsRequired;
|
||||
}
|
||||
|
||||
/** Google requires this entry point to stay reachable after the first consent decision. */
|
||||
export async function showPrivacyOptions(): Promise<void> {
|
||||
if (!Capacitor.isNativePlatform()) return;
|
||||
const { AdMob } = await import("@capacitor-community/admob");
|
||||
await AdMob.showPrivacyOptionsForm();
|
||||
}
|
||||
|
||||
/** True while an ad covers the game - pause the game loop. */
|
||||
export function isAdShowing(): boolean {
|
||||
return adShowing;
|
||||
}
|
||||
|
||||
export async function initAds(): Promise<void> {
|
||||
if (!Capacitor.isNativePlatform() || initialized) return;
|
||||
if (!(await gatherConsent())) return; // consent BEFORE any ad request
|
||||
const { AdMob } = await import("@capacitor-community/admob");
|
||||
await AdMob.initialize({ initializeForTesting: cfg.testing });
|
||||
initialized = true;
|
||||
}
|
||||
|
||||
/** Resolves true if the reward was earned. On web (dev) always grants after a short delay. */
|
||||
export async function showRewarded(placement: string): Promise<boolean> {
|
||||
if (!Capacitor.isNativePlatform()) {
|
||||
await new Promise((r) => setTimeout(r, 600));
|
||||
return true;
|
||||
}
|
||||
if (!initialized) {
|
||||
// a transient failure at boot must not disable ads for the whole session
|
||||
await initAds().catch(() => {});
|
||||
if (!initialized) return false;
|
||||
}
|
||||
const adId = cfg.testing ? TEST_REWARDED_ID : cfg.rewarded[placement];
|
||||
if (!adId) return false;
|
||||
const { AdMob, RewardAdPluginEvents } = await import("@capacitor-community/admob");
|
||||
// the ad is a native activity above the WebView: the page never sees visibilitychange
|
||||
adShowing = true;
|
||||
suspendAudio();
|
||||
try {
|
||||
await AdMob.prepareRewardVideoAd({ adId });
|
||||
return await new Promise<boolean>((resolve) => {
|
||||
let rewarded = false;
|
||||
let settled = false;
|
||||
const subs: Array<Promise<{ remove: () => Promise<void> }>> = [];
|
||||
// single exit, runs once - a path that never clears adShowing freezes the game for good
|
||||
const done = (result: boolean): void => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(watchdog);
|
||||
for (const s of subs) void s.then((h) => h.remove()).catch(() => {});
|
||||
adShowing = false;
|
||||
resumeAudio();
|
||||
resolve(result);
|
||||
};
|
||||
subs.push(AdMob.addListener(RewardAdPluginEvents.Rewarded, () => { rewarded = true; }));
|
||||
subs.push(AdMob.addListener(RewardAdPluginEvents.Dismissed, () => done(rewarded)));
|
||||
subs.push(AdMob.addListener(RewardAdPluginEvents.FailedToShow, () => done(rewarded)));
|
||||
// backstop for a Dismissed event the SDK never delivers - un-freezes, never cuts an ad short
|
||||
const watchdog = setTimeout(() => done(rewarded), 300_000);
|
||||
AdMob.showRewardVideoAd().catch(() => done(false));
|
||||
});
|
||||
} catch {
|
||||
adShowing = false;
|
||||
resumeAudio();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
196
Library/mobile/kit/audio.ts
Normal file
196
Library/mobile/kit/audio.ts
Normal file
@@ -0,0 +1,196 @@
|
||||
// Kit audio (v1) - WebAudio music + SFX for Vite/Capacitor apps. From _Tools\Library\mobile\kit.
|
||||
// Generalised from XP-Battleship/src/audio.ts. Everything is best effort: missing files or a
|
||||
// locked AudioContext never throw.
|
||||
//
|
||||
// configureAudio({ base: "/assets/audio/", storageKey: "mygame", preload: ["sfx_click"],
|
||||
// throttle: { sfx_laser: 90 } });
|
||||
// initAudio(); // from the first user gesture (autoplay policy)
|
||||
// playMusic("music_game"); playSfx("sfx_click", 0.8); toggleMute(); setVolumes(0.35, 1);
|
||||
|
||||
interface AudioConfig {
|
||||
base: string;
|
||||
ext: string;
|
||||
storageKey: string;
|
||||
preload: string[];
|
||||
throttle: Record<string, number>;
|
||||
}
|
||||
|
||||
const cfg: AudioConfig = { base: "/assets/audio/", ext: ".mp3", storageKey: "app", preload: [], throttle: {} };
|
||||
|
||||
let ctx: AudioContext | null = null;
|
||||
let musicGain: GainNode | null = null;
|
||||
let sfxGain: GainNode | null = null;
|
||||
let musicSource: AudioBufferSourceNode | null = null;
|
||||
let currentMusic: string | null = null;
|
||||
let muted = false;
|
||||
let musicVol = 0.35;
|
||||
let sfxVol = 1;
|
||||
|
||||
const buffers = new Map<string, AudioBuffer>();
|
||||
const loading = new Map<string, Promise<AudioBuffer | null>>();
|
||||
const lastPlayed = new Map<string, number>();
|
||||
|
||||
function muteKey(): string {
|
||||
return `${cfg.storageKey}_muted`;
|
||||
}
|
||||
|
||||
export function configureAudio(c: Partial<AudioConfig>): void {
|
||||
Object.assign(cfg, c);
|
||||
try {
|
||||
muted = localStorage.getItem(muteKey()) === "1";
|
||||
} catch {
|
||||
muted = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Suspend while hidden, resume on return - Android otherwise leaves the context suspended
|
||||
// after backgrounding, silencing the game for good.
|
||||
document.addEventListener("visibilitychange", () => {
|
||||
if (!ctx) return;
|
||||
if (document.hidden) void ctx.suspend().catch(() => {});
|
||||
else void ctx.resume().catch(() => {});
|
||||
});
|
||||
|
||||
function loadBuffer(name: string): Promise<AudioBuffer | null> {
|
||||
if (!ctx) return Promise.resolve(null);
|
||||
const done = buffers.get(name);
|
||||
if (done) return Promise.resolve(done);
|
||||
const inflight = loading.get(name); // parallel callers share one fetch
|
||||
if (inflight) return inflight;
|
||||
const p = (async (): Promise<AudioBuffer | null> => {
|
||||
try {
|
||||
const res = await fetch(`${cfg.base}${name}${cfg.ext}`);
|
||||
if (!res.ok) return null;
|
||||
const buf = await ctx!.decodeAudioData(await res.arrayBuffer());
|
||||
buffers.set(name, buf);
|
||||
return buf;
|
||||
} catch {
|
||||
return null;
|
||||
} finally {
|
||||
loading.delete(name);
|
||||
}
|
||||
})();
|
||||
loading.set(name, p);
|
||||
return p;
|
||||
}
|
||||
|
||||
/** Call from a user gesture. Safe to call repeatedly. */
|
||||
export function initAudio(): void {
|
||||
if (ctx) {
|
||||
void ctx.resume().catch(() => {});
|
||||
return;
|
||||
}
|
||||
try {
|
||||
ctx = new AudioContext();
|
||||
musicGain = ctx.createGain();
|
||||
musicGain.gain.value = muted ? 0 : musicVol;
|
||||
musicGain.connect(ctx.destination);
|
||||
sfxGain = ctx.createGain();
|
||||
sfxGain.gain.value = muted ? 0 : sfxVol;
|
||||
sfxGain.connect(ctx.destination);
|
||||
for (const n of cfg.preload) void loadBuffer(n);
|
||||
} catch {
|
||||
ctx = null;
|
||||
}
|
||||
}
|
||||
|
||||
export function playMusic(name: string): void {
|
||||
if (!ctx || !musicGain || currentMusic === name) return;
|
||||
currentMusic = name;
|
||||
void ctx.resume().catch(() => {});
|
||||
void loadBuffer(name).then((buf) => {
|
||||
if (!ctx || !musicGain || currentMusic !== name) return; // another track requested meanwhile
|
||||
if (!buf) {
|
||||
currentMusic = null; // allow a retry later
|
||||
return;
|
||||
}
|
||||
musicSource?.stop();
|
||||
const src = ctx.createBufferSource();
|
||||
src.buffer = buf;
|
||||
src.loop = true;
|
||||
src.connect(musicGain);
|
||||
src.start();
|
||||
musicSource = src;
|
||||
});
|
||||
}
|
||||
|
||||
export function stopMusic(): void {
|
||||
currentMusic = null;
|
||||
musicSource?.stop();
|
||||
musicSource = null;
|
||||
}
|
||||
|
||||
export function playSfx(name: string, volume = 1): void {
|
||||
if (!ctx || !sfxGain || muted) return;
|
||||
// mobile browsers suspend the context between plays far more readily than desktop
|
||||
void ctx.resume().catch(() => {});
|
||||
const gap = cfg.throttle[name] ?? 0;
|
||||
const now = performance.now();
|
||||
if (gap && now - (lastPlayed.get(name) ?? 0) < gap) return;
|
||||
lastPlayed.set(name, now);
|
||||
const buf = buffers.get(name);
|
||||
if (buf) {
|
||||
playBuffer(buf, volume);
|
||||
return;
|
||||
}
|
||||
// not preloaded: decode once, THEN play - otherwise the first use of a rare clip is silent
|
||||
void loadBuffer(name).then((decoded) => {
|
||||
if (decoded && ctx && sfxGain && !muted) playBuffer(decoded, volume);
|
||||
});
|
||||
}
|
||||
|
||||
function playBuffer(buf: AudioBuffer, volume: number): void {
|
||||
if (!ctx || !sfxGain) return;
|
||||
const src = ctx.createBufferSource();
|
||||
src.buffer = buf;
|
||||
const g = ctx.createGain();
|
||||
g.gain.value = volume;
|
||||
src.connect(g);
|
||||
g.connect(sfxGain);
|
||||
src.start();
|
||||
}
|
||||
|
||||
/** Hard pause (rewarded ad showing, app hidden). */
|
||||
export function suspendAudio(): void {
|
||||
if (ctx) void ctx.suspend().catch(() => {});
|
||||
}
|
||||
|
||||
export function resumeAudio(): void {
|
||||
if (ctx && !document.hidden) void ctx.resume().catch(() => {});
|
||||
}
|
||||
|
||||
export function isMuted(): boolean {
|
||||
return muted;
|
||||
}
|
||||
|
||||
export function toggleMute(): boolean {
|
||||
muted = !muted;
|
||||
try {
|
||||
localStorage.setItem(muteKey(), muted ? "1" : "0");
|
||||
} catch {
|
||||
// storage unavailable - setting lasts for this session only
|
||||
}
|
||||
applyGains();
|
||||
return muted;
|
||||
}
|
||||
|
||||
export function setVolumes(music: number, sfx: number): void {
|
||||
musicVol = music;
|
||||
sfxVol = sfx;
|
||||
applyGains();
|
||||
}
|
||||
|
||||
function applyGains(): void {
|
||||
if (musicGain) musicGain.gain.value = muted ? 0 : musicVol;
|
||||
if (sfxGain) sfxGain.gain.value = muted ? 0 : sfxVol;
|
||||
}
|
||||
|
||||
/** Fade music out under a big moment; unduck targets the CURRENT volume/mute state. */
|
||||
export function duckMusic(on: boolean): void {
|
||||
if (!ctx || !musicGain) return;
|
||||
void ctx.resume().catch(() => {});
|
||||
const now = ctx.currentTime;
|
||||
musicGain.gain.cancelScheduledValues(now);
|
||||
musicGain.gain.setValueAtTime(musicGain.gain.value, now);
|
||||
musicGain.gain.linearRampToValueAtTime(on ? 0 : muted ? 0 : musicVol, now + (on ? 0.15 : 0.3));
|
||||
}
|
||||
58
Library/mobile/kit/haptics.ts
Normal file
58
Library/mobile/kit/haptics.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
// Kit haptics (v1) - vibration pulses, silent no-op outside the native app.
|
||||
// From _Tools\Library\mobile\kit (XP-Battleship/src/haptics.ts). Needs @capacitor/haptics.
|
||||
|
||||
import { Capacitor } from "@capacitor/core";
|
||||
import { Haptics, ImpactStyle } from "@capacitor/haptics";
|
||||
|
||||
let storageKey = "app_haptics_off";
|
||||
let off = false;
|
||||
|
||||
/** Per-device preference (like mute) - not part of the save / cloud sync. */
|
||||
export function configureHaptics(key: string): void {
|
||||
storageKey = `${key}_haptics_off`;
|
||||
try {
|
||||
off = localStorage.getItem(storageKey) === "1";
|
||||
} catch {
|
||||
off = false;
|
||||
}
|
||||
}
|
||||
|
||||
export function isHapticsEnabled(): boolean {
|
||||
return !off;
|
||||
}
|
||||
|
||||
export function toggleHaptics(): boolean {
|
||||
off = !off;
|
||||
try {
|
||||
localStorage.setItem(storageKey, off ? "1" : "0");
|
||||
} catch {
|
||||
// session only
|
||||
}
|
||||
return !off;
|
||||
}
|
||||
|
||||
async function impact(style: ImpactStyle): Promise<void> {
|
||||
if (!Capacitor.isNativePlatform() || off) return;
|
||||
try {
|
||||
await Haptics.impact({ style });
|
||||
} catch {
|
||||
// unsupported device
|
||||
}
|
||||
}
|
||||
|
||||
let lastLight = 0;
|
||||
/** Frequent events - throttled so fast gameplay does not become constant buzzing. */
|
||||
export function hapticLight(throttleMs = 150): void {
|
||||
const now = performance.now();
|
||||
if (now - lastLight < throttleMs) return;
|
||||
lastLight = now;
|
||||
void impact(ImpactStyle.Light);
|
||||
}
|
||||
|
||||
export function hapticMedium(): void {
|
||||
void impact(ImpactStyle.Medium);
|
||||
}
|
||||
|
||||
export function hapticHeavy(): void {
|
||||
void impact(ImpactStyle.Heavy);
|
||||
}
|
||||
46
Library/mobile/kit/i18n.ts
Normal file
46
Library/mobile/kit/i18n.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
// Kit i18n (v1) - tiny translation helper. From _Tools\Library\mobile\kit.
|
||||
//
|
||||
// const en = { hello: "Hello {name}!", coins: "{n} coins" };
|
||||
// const de: Partial<typeof en> = { hello: "Hallo {name}!" }; // missing keys fall back to en
|
||||
// export const { t, lang, setLang, langs } = createI18n({ en, de }, "mygame_lang");
|
||||
// t("hello", { name: "Ana" })
|
||||
//
|
||||
// Language: saved choice, else the device language if available, else the first dictionary.
|
||||
// setLang() saves and reloads the page (all UI re-renders from scratch).
|
||||
|
||||
export function createI18n<D extends Record<string, string>>(
|
||||
dicts: { [lang: string]: Partial<D> } & { en: D },
|
||||
storageKey: string
|
||||
) {
|
||||
const langs = Object.keys(dicts);
|
||||
const pick = (): string => {
|
||||
try {
|
||||
const saved = localStorage.getItem(storageKey);
|
||||
if (saved && langs.includes(saved)) return saved;
|
||||
} catch {
|
||||
// storage unavailable
|
||||
}
|
||||
const device = (navigator.language || "en").slice(0, 2).toLowerCase();
|
||||
return langs.includes(device) ? device : langs[0];
|
||||
};
|
||||
const lang = pick();
|
||||
const dict = dicts[lang] as Partial<D>;
|
||||
|
||||
function t(key: keyof D & string, vars?: Record<string, string | number>): string {
|
||||
let s = (dict[key] ?? dicts.en[key] ?? key) as string;
|
||||
if (vars) for (const [k, v] of Object.entries(vars)) s = s.split(`{${k}}`).join(String(v));
|
||||
return s;
|
||||
}
|
||||
|
||||
function setLang(l: string): void {
|
||||
if (!langs.includes(l)) return;
|
||||
try {
|
||||
localStorage.setItem(storageKey, l);
|
||||
} catch {
|
||||
// session only
|
||||
}
|
||||
location.reload();
|
||||
}
|
||||
|
||||
return { t, lang, setLang, langs };
|
||||
}
|
||||
99
Library/mobile/kit/iap.ts
Normal file
99
Library/mobile/kit/iap.ts
Normal file
@@ -0,0 +1,99 @@
|
||||
// Kit IAP (v1) - Google Play one-off purchases via cordova-plugin-purchase (CdvPurchase v13).
|
||||
// From _Tools\Library\mobile\kit (XP-Battleship/src/iap.ts). Native only; on web every call
|
||||
// resolves to "not bought".
|
||||
//
|
||||
// configureIap({ nonConsumable: ["premium_ship_1", "remove_ads"] });
|
||||
// const owned = await restorePurchases(); // every app start
|
||||
// const r = await purchase("remove_ads"); // "owned" | "failed" | "pending"
|
||||
// productPrice("remove_ads") ?? "2,99 €" // Play's localized price, or your fallback
|
||||
//
|
||||
// SKUs must exist as ACTIVE in-app products in the Play Console. Purchases only work in builds
|
||||
// installed from Play (internal test track and up) - sideloaded debug builds get an empty store.
|
||||
|
||||
import { Capacitor } from "@capacitor/core";
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
type Cdv = any; // runtime global from the plugin
|
||||
|
||||
let skus: string[] = [];
|
||||
export function configureIap(c: { nonConsumable: string[] }): void {
|
||||
skus = c.nonConsumable;
|
||||
}
|
||||
|
||||
function cdv(): Cdv | null {
|
||||
return (window as unknown as Record<string, unknown>).CdvPurchase ?? null;
|
||||
}
|
||||
|
||||
let initPromise: Promise<boolean> | null = null;
|
||||
|
||||
function ensureStore(): Promise<boolean> {
|
||||
if (!Capacitor.isNativePlatform() || !cdv() || !skus.length) return Promise.resolve(false);
|
||||
if (!initPromise) {
|
||||
initPromise = (async (): Promise<boolean> => {
|
||||
const { store, ProductType, Platform } = cdv();
|
||||
store.register(skus.map((id) => ({ id, type: ProductType.NON_CONSUMABLE, platform: Platform.GOOGLE_PLAY })));
|
||||
store.when().approved((tx: Cdv) => tx.finish()); // Play already guarantees payment
|
||||
store.error(() => { initPromise = null; }); // billing disconnect: re-register next call
|
||||
await store.initialize([Platform.GOOGLE_PLAY]);
|
||||
return true;
|
||||
})().catch(() => {
|
||||
// never cache a failure: one offline launch must not disable buying for the session
|
||||
initPromise = null;
|
||||
return false;
|
||||
});
|
||||
}
|
||||
return initPromise;
|
||||
}
|
||||
|
||||
/** `pending` = Play accepted the order but ownership has not arrived yet. Do NOT report it as
|
||||
* a failure - that is how paying customers get told "not completed" and ask for refunds. */
|
||||
export type PurchaseResult = "owned" | "failed" | "pending";
|
||||
|
||||
export async function purchase(sku: string): Promise<PurchaseResult> {
|
||||
if (!(await ensureStore())) return "failed";
|
||||
const { store, Platform } = cdv();
|
||||
try {
|
||||
const offer = store.get(sku, Platform.GOOGLE_PLAY)?.getOffer();
|
||||
if (!offer) return "failed";
|
||||
const err = await offer.order();
|
||||
if (err) return "failed"; // cancelled or declined
|
||||
const t0 = Date.now();
|
||||
while (Date.now() - t0 < 60_000) {
|
||||
if (store.get(sku, Platform.GOOGLE_PLAY)?.owned) return "owned";
|
||||
await new Promise((r) => setTimeout(r, 400));
|
||||
}
|
||||
try {
|
||||
await store.restorePurchases();
|
||||
if (store.get(sku, Platform.GOOGLE_PLAY)?.owned) return "owned";
|
||||
} catch {
|
||||
// offline
|
||||
}
|
||||
return "pending";
|
||||
} catch {
|
||||
return "failed";
|
||||
}
|
||||
}
|
||||
|
||||
/** Play's localized price ("2,99 €", "$3.49"), or null while unknown. */
|
||||
export function productPrice(sku: string): string | null {
|
||||
if (!Capacitor.isNativePlatform() || !cdv()) return null;
|
||||
try {
|
||||
const { store, Platform } = cdv();
|
||||
const product = store.get(sku, Platform.GOOGLE_PLAY);
|
||||
return product?.getOffer()?.pricingPhases?.[0]?.price ?? product?.pricing?.price ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** SKUs the player owns (restore flow - run on every app start). */
|
||||
export async function restorePurchases(): Promise<string[]> {
|
||||
if (!(await ensureStore())) return [];
|
||||
const { store, Platform } = cdv();
|
||||
try {
|
||||
await store.restorePurchases();
|
||||
} catch {
|
||||
// offline - Play's local cache still answers below
|
||||
}
|
||||
return skus.filter((sku) => store.get(sku, Platform.GOOGLE_PLAY)?.owned);
|
||||
}
|
||||
53
Library/mobile/kit/lifecycle.ts
Normal file
53
Library/mobile/kit/lifecycle.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
// Kit lifecycle (v1) - Android back button and app pause/resume. From _Tools\Library\mobile\kit.
|
||||
// Needs @capacitor/app. On web: back = Escape key, pause/resume = visibilitychange.
|
||||
//
|
||||
// onBack(() => closeTopPanel() || confirmExit()); // return true when handled
|
||||
// onPause(() => { persist(); }); onResume(() => { ... });
|
||||
// exitApp();
|
||||
|
||||
import { Capacitor } from "@capacitor/core";
|
||||
import { App } from "@capacitor/app";
|
||||
|
||||
const backHandlers: Array<() => boolean> = [];
|
||||
|
||||
/** Handlers run newest first; the first that returns true stops the chain.
|
||||
* If none handles it, the app is minimised (Android convention) instead of closed. */
|
||||
export function onBack(fn: () => boolean): () => void {
|
||||
backHandlers.push(fn);
|
||||
return () => {
|
||||
const i = backHandlers.indexOf(fn);
|
||||
if (i >= 0) backHandlers.splice(i, 1);
|
||||
};
|
||||
}
|
||||
|
||||
function runBack(): void {
|
||||
for (let i = backHandlers.length - 1; i >= 0; i--) if (backHandlers[i]()) return;
|
||||
if (Capacitor.isNativePlatform()) void App.minimizeApp().catch(() => {});
|
||||
}
|
||||
|
||||
if (Capacitor.isNativePlatform()) {
|
||||
void App.addListener("backButton", runBack);
|
||||
} else {
|
||||
addEventListener("keydown", (e) => {
|
||||
if (e.key === "Escape") runBack();
|
||||
});
|
||||
}
|
||||
|
||||
/** App goes to background: SAVE HERE - Android may kill the process without another event. */
|
||||
export function onPause(fn: () => void): void {
|
||||
if (Capacitor.isNativePlatform()) void App.addListener("pause", fn);
|
||||
document.addEventListener("visibilitychange", () => {
|
||||
if (document.hidden) fn();
|
||||
});
|
||||
}
|
||||
|
||||
export function onResume(fn: () => void): void {
|
||||
if (Capacitor.isNativePlatform()) void App.addListener("resume", fn);
|
||||
document.addEventListener("visibilitychange", () => {
|
||||
if (!document.hidden) fn();
|
||||
});
|
||||
}
|
||||
|
||||
export function exitApp(): void {
|
||||
if (Capacitor.isNativePlatform()) void App.exitApp();
|
||||
}
|
||||
112
Library/mobile/kit/save.ts
Normal file
112
Library/mobile/kit/save.ts
Normal file
@@ -0,0 +1,112 @@
|
||||
// Kit save (v1) - versioned localStorage save with backup slot. From _Tools\Library\mobile\kit.
|
||||
// Generalised from XP-Battleship/src/game/save.ts (lessons: cloud/RTDB drops empty arrays,
|
||||
// NaN poisons everything, a truncated write must not wipe progress, failures must be visible).
|
||||
//
|
||||
// interface Save { v: number; coins: number; owned: string[]; stats: { runs: number } }
|
||||
// const saves = createSaveStore<Save>({
|
||||
// key: "mygame_save", version: 2,
|
||||
// defaults: () => ({ v: 2, coins: 0, owned: [], stats: { runs: 0 } }),
|
||||
// normalize: (s, d) => ({ ...s, coins: num(s.coins, d.coins), owned: arr(s.owned, d.owned),
|
||||
// stats: { ...d.stats, ...s.stats } }),
|
||||
// migrate: (s, from) => { if (from < 2) { /* repair */ } return s; },
|
||||
// });
|
||||
// const save = saves.load(); ... saves.persist(save); if (saves.failed()) showWarningOnce();
|
||||
|
||||
/** Coerce to an array. RTDB drops empty arrays and returns sparse ones as key-indexed objects. */
|
||||
export function arr<T>(v: unknown, fallback: T[]): T[] {
|
||||
if (Array.isArray(v)) return v as T[];
|
||||
if (v && typeof v === "object") return Object.values(v as Record<string, T>);
|
||||
return fallback;
|
||||
}
|
||||
|
||||
/** Number that must stay a finite number. */
|
||||
export function num(v: unknown, fallback: number): number {
|
||||
return typeof v === "number" && Number.isFinite(v) ? v : fallback;
|
||||
}
|
||||
|
||||
/** Shallow merge of a nested record over its defaults (stats, settings, ...). */
|
||||
export function rec<T extends object>(v: unknown, fallback: T): T {
|
||||
return { ...fallback, ...(v && typeof v === "object" && !Array.isArray(v) ? (v as Partial<T>) : {}) };
|
||||
}
|
||||
|
||||
export interface SaveStoreOptions<T extends { v: number }> {
|
||||
key: string;
|
||||
version: number;
|
||||
defaults: () => T;
|
||||
/** Fill a partial save (local OR cloud) out to a complete one. Default: shallow merge. */
|
||||
normalize?: (parsed: Partial<T>, defaults: T) => T;
|
||||
/** Repair saves from older versions; `from` is the stored version (1 if never stamped). */
|
||||
migrate?: (s: T, from: number) => T;
|
||||
/** Every Nth persist() also writes the backup slot. */
|
||||
backupEvery?: number;
|
||||
}
|
||||
|
||||
export interface SaveStore<T> {
|
||||
load(): T;
|
||||
persist(data: T): void;
|
||||
/** Normalize foreign data (cloud copy) the same way as a local load. */
|
||||
normalize(parsed: Partial<T>): T;
|
||||
clear(): void;
|
||||
failed(): boolean;
|
||||
}
|
||||
|
||||
export function createSaveStore<T extends { v: number }>(o: SaveStoreOptions<T>): SaveStore<T> {
|
||||
const backupKey = `${o.key}_bak`;
|
||||
const every = o.backupEvery ?? 12;
|
||||
let since = 0;
|
||||
let saveFailed = false;
|
||||
|
||||
function normalize(parsed: Partial<T>): T {
|
||||
const d = o.defaults();
|
||||
const from = num(parsed.v, 1);
|
||||
let s = o.normalize ? o.normalize(parsed, d) : ({ ...d, ...parsed } as T);
|
||||
if (from < o.version && o.migrate) s = o.migrate(s, from);
|
||||
s.v = o.version;
|
||||
return s;
|
||||
}
|
||||
|
||||
function readSlot(key: string): T | null {
|
||||
try {
|
||||
const raw = localStorage.getItem(key);
|
||||
if (!raw) return null;
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
if (!parsed || typeof parsed !== "object") return null;
|
||||
return normalize(parsed as Partial<T>);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
load: () => readSlot(o.key) ?? readSlot(backupKey) ?? o.defaults(),
|
||||
persist(data: T): void {
|
||||
try {
|
||||
const json = JSON.stringify(data);
|
||||
localStorage.setItem(o.key, json);
|
||||
if (++since >= every) {
|
||||
since = 0;
|
||||
localStorage.setItem(backupKey, json);
|
||||
}
|
||||
} catch {
|
||||
saveFailed = true; // quota / storage disabled - caller tells the player once
|
||||
}
|
||||
},
|
||||
normalize,
|
||||
clear(): void {
|
||||
try {
|
||||
localStorage.removeItem(o.key);
|
||||
localStorage.removeItem(backupKey); // a deletion that left the backup would resurrect it
|
||||
} catch {
|
||||
// storage unavailable
|
||||
}
|
||||
},
|
||||
failed: () => saveFailed,
|
||||
};
|
||||
}
|
||||
|
||||
/** Offline earnings. Pass the timestamp captured at BOOT, not save.lastSeen read later -
|
||||
* autosave restamps lastSeen within seconds and the gain silently becomes zero. */
|
||||
export function offlineSeconds(since: number, capHours = 8): number {
|
||||
const elapsed = (Date.now() - num(since, Date.now())) / 1000;
|
||||
return Math.min(Math.max(elapsed, 0), capHours * 3600);
|
||||
}
|
||||
17
Library/mobile/template/.gitignore
vendored
Normal file
17
Library/mobile/template/.gitignore
vendored
Normal file
@@ -0,0 +1,17 @@
|
||||
node_modules/
|
||||
dist/
|
||||
sprite-generator/output/
|
||||
sprite-generator/__pycache__/
|
||||
*.log
|
||||
|
||||
# build artefacts
|
||||
*.aab
|
||||
*.apk
|
||||
android/app/build/
|
||||
android/build/
|
||||
android/.gradle/
|
||||
|
||||
# signing (never commit)
|
||||
android/keystore.properties
|
||||
*.jks
|
||||
*.keystore
|
||||
26
Library/mobile/template/CLAUDE.md
Normal file
26
Library/mobile/template/CLAUDE.md
Normal file
@@ -0,0 +1,26 @@
|
||||
# {{NAME}}
|
||||
|
||||
Vite + TypeScript + Capacitor (Android), angelegt aus `D:\Oculusquest\Projekt\_Tools\Library` (Vorlage `mobile`).
|
||||
Aufbau und Befehle: `README.md`.
|
||||
|
||||
## Spielkonzept
|
||||
|
||||
<!-- KONZEPT: wird beim Anlegen (Skill neues-projekt) ausgefüllt, danach aktuell halten -->
|
||||
|
||||
## Arbeitsweise
|
||||
|
||||
- Antworten auf Deutsch, knapp. Code und Kommentare auf Englisch.
|
||||
- **Jeder sichtbare Text** steht in `src/lang.ts`, immer **Englisch und Deutsch**; im Code nur `t("key")`.
|
||||
- **Credits bleiben drin:** „© Jahr Michael Media“ + Discord-Link (`CREDITS` in `src/main.ts`) sichtbar,
|
||||
später z. B. im Einstellungs-/Info-Bildschirm; README ebenso.
|
||||
- `src/kit/` ist eine Kopie aus `_Tools\Library\mobile\kit`. Änderungen **dort** machen, dann
|
||||
`new-project.ps1 -UpdateKit -Path .`.
|
||||
- Vor jedem „fertig“: `npm run typecheck` muss sauber sein.
|
||||
- Alles Native (Werbung, Käufe, Vibration) ist im Browser eine Attrappe – Logik so bauen, dass `npm start` voll spielbar ist.
|
||||
- Spielstand: jedes neue Feld in `defaults()` UND in `normalize` absichern (`num`, `arr`); bei
|
||||
Formänderung `version` hoch + `migrate`.
|
||||
- Kleine Dateien mit sprechenden Namen (`src/game/*.ts`, `src/ui/*.ts`), kein `main.ts` mit 5000 Zeilen.
|
||||
- Grafik/Sound nur über `sprite-generator/` (ComfyGen, Katalog `_Tools\README.md`), Stilblock aus dem
|
||||
Spielkonzept. App-Icon: `gen adopt --size 1024 icon` → `public/assets/Sprites/icon.png`; Android-Icons siehe README.
|
||||
- Git nur lokal (kein Remote). Commit nur, wenn Michael es sagt.
|
||||
- Referenzprojekt mit allem (Cloud-Save, Bestenliste, Skilltree, Store-Screenshots): `D:\Oculusquest\Projekt\XP-Battleship`.
|
||||
55
Library/mobile/template/README.md
Normal file
55
Library/mobile/template/README.md
Normal file
@@ -0,0 +1,55 @@
|
||||
# {{NAME}}
|
||||
|
||||
Mobile-Spiel/App: Vite + TypeScript, Android über Capacitor. Angelegt am {{DATE}} aus `_Tools\Library` (Vorlage `mobile`).
|
||||
Sprachen: Englisch, Deutsch (Gerätesprache, 🌐-Knopf schaltet um).
|
||||
|
||||
© {{YEAR}} Michael Media · Discord: https://discord.gg/Ej4JPmCZva
|
||||
|
||||
## Erste Schritte
|
||||
|
||||
```powershell
|
||||
npm install
|
||||
npm start # Browser, http://localhost:5173 (Werbung/Kauf/Vibration = Attrappen)
|
||||
npx cap add android # einmal: erzeugt android\
|
||||
npm run android # bauen, sync, Android Studio öffnen
|
||||
```
|
||||
|
||||
## App-Icon
|
||||
|
||||
1. `cd sprite-generator` → `gen generate icon` → `gen adopt --size 1024 icon` (→ `public/assets/Sprites/icon.png`, auch Browser-Favicon).
|
||||
2. Android: Datei als `assets\icon-only.png` (1024×1024) ablegen, dann
|
||||
`npx @capacitor/assets generate --android --iconBackgroundColor "#0b0f1a"` (erzeugt alle mipmap-Icons).
|
||||
|
||||
## Aufbau
|
||||
|
||||
```
|
||||
index.html, src/main.ts Einstieg
|
||||
src/lang.ts alle sichtbaren Texte, Englisch + Deutsch → t("key")
|
||||
src/kit/ Bausteine aus _Tools\Library\mobile\kit – hier NICHT ändern
|
||||
audio.ts Musik + SFX (WebAudio), Mute, Ducking
|
||||
save.ts Spielstand mit Version, Backup-Slot, arr()/num()-Reparatur
|
||||
haptics.ts Vibration (nur nativ)
|
||||
ads.ts AdMob Rewarded + UMP-Einwilligung (EU)
|
||||
iap.ts Play-Käufe (einmalig, nicht verbrauchbar)
|
||||
i18n.ts Übersetzungen t("key", {n})
|
||||
lifecycle.ts Zurück-Taste, Pause/Resume (beim Pausieren speichern!)
|
||||
public/assets/ Sprites/, Audio/ – von sprite-generator (ComfyGen adopt)
|
||||
sprite-generator/ gen generate <name>, gen adopt <name>, gen generate_audio <name>
|
||||
```
|
||||
|
||||
## Vor dem Play-Store-Release
|
||||
|
||||
- `configureAds({ testing: false, ... })` mit echten Anzeigenblock-IDs; AdMob-App-ID in
|
||||
`android/app/src/main/AndroidManifest.xml` (`com.google.android.gms.ads.APPLICATION_ID`).
|
||||
- In der AdMob-Konsole DSGVO-Nachricht **und** Datenschutzoptionen veröffentlichen (sonst bleibt UMP stumm),
|
||||
Knopf „Werbe-Einstellungen“ zeigen, wenn `needsPrivacyOptions()`.
|
||||
- IAP-Produkte in der Play Console aktiv; Käufe nur in Builds aus Play (interner Test reicht).
|
||||
- `versionCode`/`versionName` in `android/app/build.gradle` + `version` in `package.json` erhöhen.
|
||||
- Signier-Schlüssel (`*.jks`, `keystore.properties`) nie committen – siehe `.gitignore`.
|
||||
|
||||
Ausführliche Checkliste aus der Praxis: `D:\Oculusquest\Projekt\XP-Battleship\RELEASE-CHECKLIST.md`.
|
||||
|
||||
## Kit aktualisieren
|
||||
|
||||
Verbesserungen an `src/kit/*` gehören nach `D:\Oculusquest\Projekt\_Tools\Library\mobile\kit`, dann:
|
||||
`D:\Oculusquest\Projekt\_Tools\Library\new-project.ps1 -UpdateKit -Path .`
|
||||
12
Library/mobile/template/capacitor.config.json
Normal file
12
Library/mobile/template/capacitor.config.json
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"appId": "com.michaelmedia.{{SLUG}}",
|
||||
"appName": "{{NAME}}",
|
||||
"webDir": "dist",
|
||||
"server": {
|
||||
"androidScheme": "https"
|
||||
},
|
||||
"android": {
|
||||
"captureInput": true,
|
||||
"webContentsDebuggingEnabled": false
|
||||
}
|
||||
}
|
||||
26
Library/mobile/template/index.html
Normal file
26
Library/mobile/template/index.html
Normal file
@@ -0,0 +1,26 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover" />
|
||||
<meta name="theme-color" content="#0b0f1a" />
|
||||
<link rel="icon" href="/assets/Sprites/icon.png" />
|
||||
<title>{{NAME}}</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app">
|
||||
<header id="hud">
|
||||
<span><span id="lCoins">Coins</span> <b id="coins">0</b></span>
|
||||
<span class="grow"></span>
|
||||
<button id="bLang" type="button">🌐</button>
|
||||
<button id="bMute" type="button">Sound</button>
|
||||
</header>
|
||||
<canvas id="cv"></canvas>
|
||||
<footer>
|
||||
<button id="bAd" type="button">2x coins (ad)</button>
|
||||
</footer>
|
||||
<p class="credits" id="credits"></p>
|
||||
</div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
27
Library/mobile/template/package.json
Normal file
27
Library/mobile/template/package.json
Normal file
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "{{SLUG}}",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"start": "vite",
|
||||
"build": "tsc --noEmit && vite build",
|
||||
"preview": "vite preview --port 5174",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"android": "npm run build && npx cap sync android && npx cap open android",
|
||||
"cap:sync": "npm run build && npx cap sync"
|
||||
},
|
||||
"dependencies": {
|
||||
"@capacitor-community/admob": "^8.0.0",
|
||||
"@capacitor/android": "^8.3.0",
|
||||
"@capacitor/app": "^8.1.1",
|
||||
"@capacitor/cli": "^8.3.0",
|
||||
"@capacitor/core": "^8.3.0",
|
||||
"@capacitor/haptics": "^8.0.2",
|
||||
"cordova-plugin-purchase": "^13.18.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"typescript": "^5.5.0",
|
||||
"vite": "^5.4.0"
|
||||
}
|
||||
}
|
||||
26
Library/mobile/template/src/lang.ts
Normal file
26
Library/mobile/template/src/lang.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
// {{NAME}} - all visible texts, English + German (kit/i18n.ts). A new text always gets BOTH
|
||||
// languages; German may leave a key out only by mistake (it then falls back to English).
|
||||
import { createI18n } from "./kit/i18n";
|
||||
|
||||
const en = {
|
||||
lang_self: "English",
|
||||
coins: "Coins",
|
||||
sound_on: "Sound on",
|
||||
sound_off: "Sound off",
|
||||
double_ad: "2x coins (ad)",
|
||||
};
|
||||
|
||||
const de: Partial<typeof en> = {
|
||||
lang_self: "Deutsch",
|
||||
coins: "Münzen",
|
||||
sound_on: "Sound an",
|
||||
sound_off: "Sound aus",
|
||||
double_ad: "2x Münzen (Werbung)",
|
||||
};
|
||||
|
||||
export const { t, lang, setLang, langs } = createI18n({ en, de }, "{{SLUG}}_lang");
|
||||
|
||||
/** Next language (one button cycles through all); reloads the page. */
|
||||
export function nextLang(): void {
|
||||
setLang(langs[(langs.indexOf(lang) + 1) % langs.length]);
|
||||
}
|
||||
100
Library/mobile/template/src/main.ts
Normal file
100
Library/mobile/template/src/main.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
// {{NAME}} - entry. Demo from the Library template: tap the orb for coins, watch an ad to
|
||||
// double them. Replace the demo; keep the wiring (save, audio, haptics, ads, lifecycle,
|
||||
// texts via t() from lang.ts, credits line).
|
||||
import "./style.css";
|
||||
import { configureAudio, initAudio, playMusic, playSfx, toggleMute, isMuted } from "./kit/audio";
|
||||
import { createSaveStore, num } from "./kit/save";
|
||||
import { configureHaptics, hapticLight } from "./kit/haptics";
|
||||
import { configureAds, initAds, showRewarded } from "./kit/ads";
|
||||
import { onBack, onPause } from "./kit/lifecycle";
|
||||
import { t, lang, nextLang } from "./lang";
|
||||
|
||||
const ID = "{{SLUG}}";
|
||||
// Credits (standard for every app); external links open in the system browser
|
||||
const DISCORD = "https://discord.gg/Ej4JPmCZva";
|
||||
const CREDITS = `© {{YEAR}} Michael Media · <a href="${DISCORD}" target="_blank" rel="noopener">Discord</a>`;
|
||||
|
||||
// ---- save -------------------------------------------------------------------------------
|
||||
interface Save {
|
||||
v: number;
|
||||
coins: number;
|
||||
taps: number;
|
||||
}
|
||||
const saves = createSaveStore<Save>({
|
||||
key: `${ID}_save`,
|
||||
version: 1,
|
||||
defaults: () => ({ v: 1, coins: 0, taps: 0 }),
|
||||
normalize: (s, d) => ({ ...d, ...s, coins: num(s.coins, d.coins), taps: num(s.taps, d.taps) }),
|
||||
});
|
||||
const save = saves.load();
|
||||
setInterval(() => saves.persist(save), 5000);
|
||||
onPause(() => saves.persist(save));
|
||||
|
||||
// ---- services ---------------------------------------------------------------------------
|
||||
configureAudio({ base: "/assets/Audio/", storageKey: ID, preload: ["sfx_tap", "music_game"], throttle: { sfx_tap: 50 } });
|
||||
configureHaptics(ID);
|
||||
// Ad unit ids from the AdMob console; testing:true uses Google's test unit (set false for release)
|
||||
configureAds({ testing: true, rewarded: { double: "" } });
|
||||
void initAds();
|
||||
|
||||
// ---- view -------------------------------------------------------------------------------
|
||||
const $ = <T extends HTMLElement>(id: string) => document.getElementById(id) as T;
|
||||
const cv = $<HTMLCanvasElement>("cv");
|
||||
const ctx = cv.getContext("2d")!;
|
||||
let W = 0, H = 0;
|
||||
function fit(): void {
|
||||
const r = cv.getBoundingClientRect(), k = devicePixelRatio || 1;
|
||||
W = r.width; H = r.height;
|
||||
cv.width = Math.round(W * k); cv.height = Math.round(H * k);
|
||||
ctx.setTransform(k, 0, 0, k, 0, 0);
|
||||
}
|
||||
addEventListener("resize", fit);
|
||||
fit();
|
||||
|
||||
let pulse = 0;
|
||||
cv.addEventListener("pointerdown", (e) => {
|
||||
initAudio();
|
||||
playMusic("music_game");
|
||||
const r = cv.getBoundingClientRect();
|
||||
const x = e.clientX - r.left, y = e.clientY - r.top;
|
||||
if (Math.hypot(x - W / 2, y - H / 2) < Math.min(W, H) * 0.22) {
|
||||
save.coins += 1; save.taps += 1; pulse = 1;
|
||||
playSfx("sfx_tap"); hapticLight();
|
||||
hud();
|
||||
}
|
||||
});
|
||||
|
||||
$("bAd").onclick = async () => {
|
||||
initAudio();
|
||||
if (await showRewarded("double")) { save.coins *= 2; saves.persist(save); hud(); }
|
||||
};
|
||||
$("bMute").onclick = () => { initAudio(); toggleMute(); hud(); };
|
||||
$("bLang").onclick = nextLang;
|
||||
onBack(() => false); // nothing to close -> app minimises
|
||||
|
||||
// static texts (language is fixed per page load - nextLang() reloads)
|
||||
document.documentElement.lang = lang;
|
||||
$("lCoins").textContent = t("coins");
|
||||
$("bAd").textContent = t("double_ad");
|
||||
$("bLang").textContent = `🌐 ${t("lang_self")}`;
|
||||
$("credits").innerHTML = CREDITS;
|
||||
|
||||
function hud(): void {
|
||||
$("coins").textContent = String(save.coins);
|
||||
$("bMute").textContent = isMuted() ? t("sound_off") : t("sound_on");
|
||||
}
|
||||
|
||||
function frame(): void {
|
||||
pulse *= 0.9;
|
||||
ctx.clearRect(0, 0, W, H);
|
||||
const r = Math.min(W, H) * 0.2 * (1 + pulse * 0.12);
|
||||
const g = ctx.createRadialGradient(W / 2, H / 2, r * 0.1, W / 2, H / 2, r);
|
||||
g.addColorStop(0, "#bff3ff"); g.addColorStop(1, "#1a6d9a");
|
||||
ctx.fillStyle = g;
|
||||
ctx.beginPath(); ctx.arc(W / 2, H / 2, r, 0, Math.PI * 2); ctx.fill();
|
||||
ctx.fillStyle = "#8b97bd"; ctx.font = "12px system-ui"; ctx.textAlign = "center";
|
||||
ctx.fillText(`v${__APP_VERSION__}`, W / 2, H - 10);
|
||||
requestAnimationFrame(frame);
|
||||
}
|
||||
hud();
|
||||
frame();
|
||||
20
Library/mobile/template/src/style.css
Normal file
20
Library/mobile/template/src/style.css
Normal file
@@ -0,0 +1,20 @@
|
||||
:root {
|
||||
--bg: #0b0f1a; --panel: #141b2d; --line: #2a3658; --text: #e3e9ff; --accent: #4fd8ff;
|
||||
/* safe areas (notch, gesture bar) */
|
||||
--sat: env(safe-area-inset-top); --sab: env(safe-area-inset-bottom);
|
||||
}
|
||||
* { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
|
||||
html, body { margin: 0; height: 100%; overflow: hidden; background: var(--bg); color: var(--text);
|
||||
font: 16px/1.4 system-ui, sans-serif; user-select: none; -webkit-user-select: none; touch-action: manipulation; }
|
||||
#app { display: flex; flex-direction: column; height: 100%; padding: calc(8px + var(--sat)) 12px calc(8px + var(--sab)); gap: 8px; }
|
||||
#hud, footer { display: flex; justify-content: space-between; align-items: center; gap: 8px; }
|
||||
#hud b { color: var(--accent); font-variant-numeric: tabular-nums; }
|
||||
canvas { flex: 1; width: 100%; min-height: 0; border-radius: 12px; background: #050913; display: block; }
|
||||
button { font: inherit; color: var(--text); background: var(--panel); border: 1px solid var(--line);
|
||||
border-radius: 10px; padding: 10px 16px; }
|
||||
button:active { transform: scale(.97); }
|
||||
footer button { flex: 1; }
|
||||
.grow { flex: 1; }
|
||||
/* credits (standard for every app: © year Michael Media + Discord) */
|
||||
.credits { margin: 0; text-align: center; font-size: 12px; color: #8b97bd; }
|
||||
.credits a { color: var(--accent); text-decoration: none; }
|
||||
2
Library/mobile/template/src/vite-env.d.ts
vendored
Normal file
2
Library/mobile/template/src/vite-env.d.ts
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
/// <reference types="vite/client" />
|
||||
declare const __APP_VERSION__: string;
|
||||
15
Library/mobile/template/tsconfig.json
Normal file
15
Library/mobile/template/tsconfig.json
Normal file
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noEmit": true,
|
||||
"isolatedModules": true,
|
||||
"skipLibCheck": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
11
Library/mobile/template/vite.config.ts
Normal file
11
Library/mobile/template/vite.config.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { defineConfig } from "vite";
|
||||
|
||||
// The version shown in-game comes from package.json. Keep versionName in
|
||||
// android/app/build.gradle in step - a bug report is only useful if it names a build.
|
||||
const pkg = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8")) as { version: string };
|
||||
|
||||
export default defineConfig({
|
||||
define: { __APP_VERSION__: JSON.stringify(pkg.version) },
|
||||
build: { target: "es2020" },
|
||||
});
|
||||
135
Library/new-project.ps1
Normal file
135
Library/new-project.ps1
Normal file
@@ -0,0 +1,135 @@
|
||||
<#
|
||||
Creates a new project from a Library template, or refreshes the kit copy in an existing one.
|
||||
|
||||
New project (folder D:\Oculusquest\Projekt\<Name>):
|
||||
.\new-project.ps1 -Name "Particle Panic" # HTML game (default)
|
||||
.\new-project.ps1 -Name "Star Miner" -Type mobile # Vite + TS + Capacitor
|
||||
options: -Root <parent folder> -NoGit -NoGenerator -Force (allow an existing EMPTY-ish folder)
|
||||
|
||||
Refresh kit files after improving them in the Library:
|
||||
.\new-project.ps1 -UpdateKit -Path D:\Oculusquest\Projekt\Pipefix2
|
||||
|
||||
Placeholders in template files: {{NAME}} {{SLUG}} {{IDENT}} {{DATE}} {{YEAR}}
|
||||
#>
|
||||
param(
|
||||
[string]$Name,
|
||||
[ValidateSet('webgame', 'mobile')][string]$Type = 'webgame',
|
||||
[string]$Root = 'D:\Oculusquest\Projekt',
|
||||
[string]$Path,
|
||||
[switch]$UpdateKit,
|
||||
[switch]$NoGit,
|
||||
[switch]$NoGenerator,
|
||||
[switch]$Force
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$lib = $PSScriptRoot
|
||||
$comfyTemplate = Join-Path (Split-Path $lib -Parent) 'ComfyGen\template'
|
||||
$utf8 = New-Object System.Text.UTF8Encoding($false)
|
||||
|
||||
function KitTarget([string]$dir, [string]$kind) {
|
||||
if ($kind -eq 'mobile') { return Join-Path $dir 'src\kit' }
|
||||
return Join-Path $dir 'game\kit'
|
||||
}
|
||||
|
||||
function Copy-Kit([string]$dir, [string]$kind) {
|
||||
$src = Join-Path $lib "$(if ($kind -eq 'mobile') { 'mobile' } else { 'web' })\kit"
|
||||
$dst = KitTarget $dir $kind
|
||||
New-Item -ItemType Directory -Force $dst | Out-Null
|
||||
$files = Get-ChildItem $src -File
|
||||
foreach ($f in $files) { Copy-Item $f.FullName (Join-Path $dst $f.Name) -Force }
|
||||
"Kit -> $dst ($($files.Count) Dateien: $(($files | ForEach-Object Name) -join ', '))"
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------- update kit only
|
||||
if ($UpdateKit) {
|
||||
if (-not $Path) { $Path = (Get-Location).Path }
|
||||
$Path = (Resolve-Path $Path).Path
|
||||
if (Test-Path (Join-Path $Path 'game\kit')) { $kind = 'webgame' }
|
||||
elseif (Test-Path (Join-Path $Path 'src\kit')) { $kind = 'mobile' }
|
||||
else { throw "Kein game\kit oder src\kit in $Path gefunden." }
|
||||
Copy-Kit $Path $kind
|
||||
'Unterschiede pruefen: git diff -- ' + $(if ($kind -eq 'mobile') { 'src/kit' } else { 'game/kit' })
|
||||
exit 0
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------- new project
|
||||
if (-not $Name) { throw 'Parameter -Name fehlt (z. B. -Name "Particle Panic").' }
|
||||
$slug = ($Name.ToLowerInvariant() -replace '[^a-z0-9]', '')
|
||||
if (-not $slug) { throw "Aus '$Name' laesst sich kein Kurzname bilden (nur a-z, 0-9)." }
|
||||
$ident = (($Name -split '[^A-Za-z0-9]+') | Where-Object { $_ } | ForEach-Object { $_.Substring(0, 1).ToUpperInvariant() + $_.Substring(1) }) -join ''
|
||||
if ($ident -match '^[0-9]') { $ident = 'G' + $ident }
|
||||
|
||||
$dest = Join-Path $Root $Name
|
||||
if (Test-Path $dest) {
|
||||
$existing = Get-ChildItem $dest -Force | Where-Object { $_.Name -notin '.claude', '.dashboard.json' }
|
||||
if ($existing -and -not $Force) { throw "$dest existiert und ist nicht leer. Anderer Name oder -Force." }
|
||||
}
|
||||
New-Item -ItemType Directory -Force $dest | Out-Null
|
||||
|
||||
$tpl = Join-Path $lib "$(if ($Type -eq 'mobile') { 'mobile' } else { 'web' })\template"
|
||||
# copy file by file, skipping build output an editor may have created inside the template
|
||||
$skip = '\\(bin|obj|node_modules|dist|release)(\\|$)'
|
||||
Get-ChildItem $tpl -Recurse -File -Force | Where-Object { $_.FullName.Substring($tpl.Length) -notmatch $skip } | ForEach-Object {
|
||||
# *.template = file an IDE must not pick up inside the Library (e.g. Launcher.csproj.template)
|
||||
$target = Join-Path $dest ($_.FullName.Substring($tpl.Length + 1) -replace '\.template$', '')
|
||||
New-Item -ItemType Directory -Force (Split-Path $target -Parent) | Out-Null
|
||||
Copy-Item $_.FullName $target -Force
|
||||
}
|
||||
|
||||
# placeholders
|
||||
$now = Get-Date
|
||||
$map = @{
|
||||
'{{NAME}}' = $Name; '{{SLUG}}' = $slug; '{{IDENT}}' = $ident
|
||||
'{{DATE}}' = $now.ToString('yyyy-MM-dd'); '{{YEAR}}' = $now.ToString('yyyy')
|
||||
}
|
||||
$textExt = '.html', '.js', '.mjs', '.ts', '.css', '.json', '.md', '.ps1', '.cs', '.csproj', '.py', '.txt', '.gitignore'
|
||||
Get-ChildItem $dest -Recurse -File -Force | Where-Object { $textExt -contains $_.Extension -or $_.Name -eq '.gitignore' } | ForEach-Object {
|
||||
$t = [IO.File]::ReadAllText($_.FullName, $utf8)
|
||||
$n = $t
|
||||
foreach ($k in $map.Keys) { $n = $n.Replace($k, $map[$k]) }
|
||||
if ($n -ne $t) { [IO.File]::WriteAllText($_.FullName, $n, $utf8) }
|
||||
}
|
||||
|
||||
Copy-Kit $dest $Type
|
||||
|
||||
# asset folders (ComfyGen adopt writes to ASSETS_DIR\Sprites and \Audio)
|
||||
$assetRel = if ($Type -eq 'mobile') { 'public\assets' } else { 'game\assets' }
|
||||
foreach ($sub in 'Sprites', 'Audio', 'Fonts') { New-Item -ItemType Directory -Force (Join-Path $dest "$assetRel\$sub") | Out-Null }
|
||||
|
||||
# sprite generator (ComfyGen project)
|
||||
if (-not $NoGenerator -and (Test-Path $comfyTemplate)) {
|
||||
$gen = Join-Path $dest 'sprite-generator'
|
||||
New-Item -ItemType Directory -Force $gen | Out-Null
|
||||
Get-ChildItem $comfyTemplate -File | ForEach-Object { Copy-Item $_.FullName $gen -Force }
|
||||
$cfgFile = Join-Path $gen 'config.py'
|
||||
$parts = ($assetRel -split '\\' | ForEach-Object { '"' + $_ + '"' }) -join ', '
|
||||
$cfg = [IO.File]::ReadAllText($cfgFile, $utf8)
|
||||
$cfg = [regex]::Replace($cfg, '(?m)^ASSETS_DIR\s*=.*$', "ASSETS_DIR = os.path.join(PROJECT_ROOT, $parts)")
|
||||
[IO.File]::WriteAllText($cfgFile, $cfg, $utf8)
|
||||
"Generator -> $gen (ASSETS_DIR = $assetRel)"
|
||||
}
|
||||
|
||||
# project dashboard entry
|
||||
$dash = Join-Path $dest '.dashboard.json'
|
||||
if (-not (Test-Path $dash)) {
|
||||
$d = [ordered]@{ status = 'active'; priority = 'medium'; notes = "Vorlage $Type aus _Tools\Library"; tags = @($Type);
|
||||
tasks = @(); thumbnail = ''; start = ''; updatedAt = $now.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss.fffZ') }
|
||||
[IO.File]::WriteAllText($dash, ($d | ConvertTo-Json -Depth 3), $utf8)
|
||||
}
|
||||
|
||||
# git (init only - the first commit is up to the user)
|
||||
if (-not $NoGit -and (Get-Command git -ErrorAction SilentlyContinue) -and -not (Test-Path (Join-Path $dest '.git'))) {
|
||||
git -C $dest init -q -b main 2>$null
|
||||
if ($LASTEXITCODE -ne 0) { git -C $dest init -q }
|
||||
'git init (noch kein Commit)'
|
||||
}
|
||||
|
||||
''
|
||||
"Fertig: $dest (Typ $Type, Kurzname $slug, Ident $ident)"
|
||||
if ($Type -eq 'webgame') {
|
||||
" Spielen: $dest\game\index.html"
|
||||
" Release: cd `"$dest`"; .\build.ps1"
|
||||
} else {
|
||||
" cd `"$dest`"; npm install; npm start"
|
||||
" Android: npx cap add android; npm run android"
|
||||
}
|
||||
268
Library/tools/project-check.mjs
Normal file
268
Library/tools/project-check.mjs
Normal file
@@ -0,0 +1,268 @@
|
||||
// Project check: short report for the "projekt-check" skill - so Claude reads ~40 lines instead
|
||||
// of the code. Stack, size, biggest files, kit status vs Library, re-implementations of kit
|
||||
// features, Library candidates, hygiene (git, README, CLAUDE.md, release age, TODOs, credits/Discord).
|
||||
// node D:\Oculusquest\Projekt\_Tools\Library\tools\project-check.mjs [projectPath] [--all]
|
||||
// --all lists every finding instead of the top entries.
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const LIB = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const args = process.argv.slice(2);
|
||||
const ALL = args.includes('--all');
|
||||
const root = path.resolve(args.find(a => !a.startsWith('--')) || process.cwd());
|
||||
const name = path.basename(root);
|
||||
const TOP = ALL ? 1e9 : 6;
|
||||
|
||||
const SKIP = /^(node_modules|\.git|dist|build|builds|bin|obj|out|target|Library|Temp|Logs|output|release|publish.*|\.gradle|\.idea|\.vscode|\.vs|__pycache__|\.venv.*|venv|env|\.expo|\.cache|\.claude|ThirdParty|third_party|vendor|Packages|coverage|test-results|playwright-report|_archiv|archive|backup)$/i;
|
||||
const SRC = /\.(js|mjs|cjs|ts|tsx|jsx|cs|cpp|cc|hpp|h|py|kt|java|dart|gd|html|css|ps1)$/i;
|
||||
|
||||
// ---- walk ---------------------------------------------------------------------------------
|
||||
const files = [];
|
||||
(function walk(dir, depth) {
|
||||
let ents = [];
|
||||
try { ents = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
|
||||
for (const e of ents) {
|
||||
const p = path.join(dir, e.name);
|
||||
if (e.isDirectory()) {
|
||||
if (depth < 8 && !SKIP.test(e.name) && !(e.name === 'android' && fs.existsSync(path.join(root, 'capacitor.config.json')))) walk(p, depth + 1);
|
||||
} else if (SRC.test(e.name) && files.length < 6000) {
|
||||
let st; try { st = fs.statSync(p); } catch { continue; }
|
||||
if (st.size > 3e6) continue; // generated bundles, data dumps
|
||||
files.push({ p, rel: path.relative(root, p), size: st.size, mtime: st.mtimeMs });
|
||||
}
|
||||
}
|
||||
})(root, 0);
|
||||
|
||||
const isKit = f => /(^|\\)(game|src)\\kit\\/.test(f.rel);
|
||||
const isGen = f => /(^|\\)(sprite-?gen(erator)?|spritegenerator|design-gen|tools?|scripts?|tests?)\\/i.test(f.rel);
|
||||
for (const f of files) {
|
||||
try { f.text = fs.readFileSync(f.p, 'utf8'); } catch { f.text = ''; }
|
||||
f.lines = f.text ? f.text.split('\n').length : 0;
|
||||
}
|
||||
const own = files.filter(f => !isKit(f));
|
||||
const code = own.filter(f => !/\.(html|css)$/i.test(f.rel) || f.lines > 300); // big inline-script html counts
|
||||
|
||||
// ---- stack --------------------------------------------------------------------------------
|
||||
const has = p => fs.existsSync(path.join(root, p));
|
||||
const pkg = (() => { try { return JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')); } catch { return null; } })();
|
||||
const deps = pkg ? { ...pkg.dependencies, ...pkg.devDependencies } : {};
|
||||
const ext = {};
|
||||
for (const f of code) { const e = path.extname(f.rel).slice(1).toLowerCase(); ext[e] = (ext[e] || 0) + f.lines; }
|
||||
const stack = [];
|
||||
if (deps['@capacitor/core']) stack.push('Capacitor');
|
||||
if (deps.vite) stack.push('Vite');
|
||||
if (deps.react) stack.push('React');
|
||||
if (deps.electron) stack.push('Electron');
|
||||
if (deps.expo) stack.push('Expo');
|
||||
if (has('game/index.html') || (has('index.html') && !pkg)) stack.push('HTML-Spiel');
|
||||
if (files.some(f => /\.csproj$/i.test(f.rel)) || own.some(f => f.rel.endsWith('.cs'))) stack.push('.NET');
|
||||
if (has('CMakeLists.txt')) stack.push('C++/CMake');
|
||||
if (has('pubspec.yaml')) stack.push('Flutter');
|
||||
if (has('ProjectSettings')) stack.push('Unity');
|
||||
if (own.some(f => f.rel.endsWith('.py')) && !stack.length) stack.push('Python');
|
||||
const kind = has('game/kit') || stack.includes('HTML-Spiel') ? 'web' : deps['@capacitor/core'] ? 'mobile' : null;
|
||||
|
||||
// ---- kit status ---------------------------------------------------------------------------
|
||||
const hash = s => createHash('sha1').update(s.replace(/\r\n/g, '\n')).digest('hex');
|
||||
const ver = s => +((s.match(/\(v(\d+)\)/) || [])[1] || 0);
|
||||
const kitLines = [];
|
||||
for (const [projDir, libDir] of [['game/kit', 'web/kit'], ['src/kit', 'mobile/kit']]) {
|
||||
const pd = path.join(root, projDir), ld = path.join(LIB, libDir);
|
||||
if (!fs.existsSync(pd)) continue;
|
||||
const libFiles = fs.readdirSync(ld);
|
||||
const st = { same: 0, old: [], changed: [], missing: [], extra: [] };
|
||||
for (const f of libFiles) {
|
||||
const pf = path.join(pd, f);
|
||||
if (!fs.existsSync(pf)) { st.missing.push(f); continue; }
|
||||
const a = fs.readFileSync(pf, 'utf8'), b = fs.readFileSync(path.join(ld, f), 'utf8');
|
||||
if (hash(a) === hash(b)) st.same++;
|
||||
else if (ver(a) < ver(b)) st.old.push(`${f} v${ver(a)}→v${ver(b)}`);
|
||||
else st.changed.push(f);
|
||||
}
|
||||
for (const f of fs.readdirSync(pd)) if (!libFiles.includes(f)) st.extra.push(f);
|
||||
kitLines.push(`${projDir}: ${st.same} aktuell` +
|
||||
(st.old.length ? ` · VERALTET ${st.old.join(', ')}` : '') +
|
||||
(st.changed.length ? ` · IM PROJEKT GEÄNDERT ${st.changed.join(', ')} (→ in Library übernehmen?)` : '') +
|
||||
(st.missing.length ? ` · fehlt ${st.missing.join(', ')}` : '') +
|
||||
(st.extra.length ? ` · nur hier ${st.extra.join(', ')}` : ''));
|
||||
}
|
||||
|
||||
// ---- own code doing what the kit already does ---------------------------------------------
|
||||
const REINVENT = kind === 'mobile' ? [
|
||||
[/new AudioContext|webkitAudioContext/, 'eigenes WebAudio', 'kit/audio.ts'],
|
||||
[/localStorage\.setItem\([^)]*save/i, 'eigener Spielstand', 'kit/save.ts createSaveStore'],
|
||||
[/AdMob\./, 'AdMob direkt', 'kit/ads.ts'],
|
||||
[/CdvPurchase|store\.register\(/, 'Käufe direkt', 'kit/iap.ts'],
|
||||
[/Haptics\.impact/, 'Haptics direkt', 'kit/haptics.ts'],
|
||||
[/addListener\(\s*["']backButton/, 'Zurück-Taste direkt', 'kit/lifecycle.ts'],
|
||||
] : [
|
||||
[/new \(?window\.AudioContext|new AudioContext|webkitAudioContext/, 'eigenes WebAudio', 'Kit.createAudio'],
|
||||
[/localStorage\.(get|set)Item/, 'localStorage direkt', 'Kit.store / Kit.saveSlot'],
|
||||
[/firebasedatabase\.app|firebaseio\.com/, 'Firebase-REST direkt', 'Kit.scores'],
|
||||
[/chrome\.webview/, 'WebView2-Bridge direkt', 'Kit.host'],
|
||||
[/requestAnimationFrame\(/, 'eigene Spielschleife', 'Kit.loop'],
|
||||
[/devicePixelRatio/, 'eigene HiDPI-Skalierung', 'Kit.fit / Kit.setRes'],
|
||||
[/addEventListener\(\s*['"]keydown/, 'eigene Tastatur-Abfrage', 'Kit.input'],
|
||||
];
|
||||
const reinvent = [];
|
||||
if (kind) {
|
||||
const web = code.filter(f => /\.(js|mjs|ts|tsx|jsx|html)$/i.test(f.rel) && !isGen(f));
|
||||
for (const [re, what, use] of REINVENT) {
|
||||
// a file that already calls the kit piece is fine (e.g. Kit.input + one keydown for a text field)
|
||||
const usesKit = new RegExp(use.split(' ')[0].replace(/^kit\//, 'kit/').replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/\\\.ts$/, ''));
|
||||
const hits = web.filter(f => re.test(f.text) && !usesKit.test(f.text)).map(f => f.rel);
|
||||
if (hits.length) reinvent.push(`${what} in ${hits.slice(0, 3).join(', ')}${hits.length > 3 ? ` +${hits.length - 3}` : ''} → ${use}`);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Library candidates: generic-looking modules ------------------------------------------
|
||||
const GENERIC = [
|
||||
[/achiev/i, 'Achievements', null], [/tutorial|onboard/i, 'Tutorial', null], [/solve|solver/i, 'Level-Löser', null],
|
||||
[/verify|selftest/i, 'Selbsttest/Verifier', null], [/i18n|lang|locali|translat/i, 'Übersetzung', kind === 'mobile' ? 'i18n.ts' : null],
|
||||
[/leaderboard|highscore|scores?\b/i, 'Bestenliste', 'Kit.scores'], [/audio|sound|music/i, 'Audio', 'Kit.createAudio / audio.ts'],
|
||||
[/save|storage|persist/i, 'Speichern', 'Kit.saveSlot / save.ts'], [/particle|fx|tween|ease|juice/i, 'Effekte', 'Kit.fx'],
|
||||
[/input|controls?|keys?\b|gamepad/i, 'Eingabe', 'Kit.input'], [/online|cloud|auth|firebase/i, 'Online/Cloud', null],
|
||||
[/mission|daily|quest/i, 'Missionen/Daily', null], [/settings?|options|config/i, 'Einstellungen', null],
|
||||
[/wiki|help/i, 'Hilfe/Wiki', null], [/debug|devshot|cheat/i, 'Debug-Werkzeug', null],
|
||||
[/number|format/i, 'Zahlenformat', 'Kit.fmt'], [/rng|random/i, 'Zufall', 'Kit.rng'],
|
||||
[/window|layered/i, 'Fenster-Helfer (Desktop)', null], [/screenshot|store.?screen|itch|make_images/i, 'Store-/itch-Bilder', '_Tools/Itch'],
|
||||
];
|
||||
const cands = [];
|
||||
for (const f of own) {
|
||||
if (isKit(f) || f.lines < 40 || /(^|\\)(sprite-?gen(erator)?|spritegenerator|design-gen)\\/i.test(f.rel)) continue;
|
||||
const base = path.basename(f.rel, path.extname(f.rel));
|
||||
const g = GENERIC.find(([re]) => re.test(base));
|
||||
if (!g) continue;
|
||||
cands.push(`${f.rel} (${f.lines} Z.) ${g[1]}: ${g[2] ? `Library hat ${g[2]} – vergleichen` : 'FEHLT in Library → Kandidat'}`);
|
||||
}
|
||||
cands.sort((a, b) => (b.includes('FEHLT') - a.includes('FEHLT')));
|
||||
|
||||
// ---- hygiene ------------------------------------------------------------------------------
|
||||
const git = (...a) => { try { return execFileSync('git', ['-C', root, ...a], { encoding: 'utf8', timeout: 8000, stdio: ['ignore', 'pipe', 'ignore'] }).trim(); } catch { return null; } };
|
||||
const issues = [];
|
||||
const isRepo = git('rev-parse', '--is-inside-work-tree') === 'true';
|
||||
if (!isRepo) issues.push('kein git-Repository');
|
||||
else {
|
||||
const dirty = (git('status', '--porcelain') || '').split('\n').filter(Boolean).length;
|
||||
const last = git('log', '-1', '--format=%cr');
|
||||
// no remote check: local git is enough (Michael's decision)
|
||||
if (dirty) issues.push(`${dirty} ungesicherte Änderungen (letzter Commit ${last || '–'})`);
|
||||
const tracked = (git('ls-files', '-z') || '').split('\0').filter(Boolean);
|
||||
const big = tracked.map(t => { try { return [t, fs.statSync(path.join(root, t)).size]; } catch { return [t, 0]; } })
|
||||
.filter(([, s]) => s > 10e6).sort((a, b) => b[1] - a[1]);
|
||||
if (big.length) issues.push(`große Dateien in git: ${big.slice(0, 3).map(([t, s]) => `${t} ${(s / 1e6).toFixed(0)} MB`).join(', ')}`);
|
||||
}
|
||||
for (const f of ['README.md', 'CLAUDE.md', '.gitignore']) if (!has(f)) issues.push(`${f} fehlt`);
|
||||
// credits standard: "Michael Media" + Discord link visible in the app (source or language files)
|
||||
{
|
||||
const appSrc = own.filter(f => !isGen(f) && !/(^|\\)docs\\/i.test(f.rel));
|
||||
let langText = '';
|
||||
for (const d of ['Languages', 'lang', 'locales', 'i18n']) {
|
||||
if (!has(d)) continue;
|
||||
try { for (const n of fs.readdirSync(path.join(root, d))) if (n.endsWith('.json')) langText += fs.readFileSync(path.join(root, d, n), 'utf8'); } catch { /* unreadable */ }
|
||||
}
|
||||
const inApp = re => re.test(langText) || appSrc.some(f => re.test(f.text));
|
||||
const discordInApp = inApp(/discord\.gg\//i);
|
||||
if (!inApp(/michael\s*media/i)) issues.push('Credits fehlen im Spiel ("© Jahr Michael Media")');
|
||||
if (!discordInApp) issues.push('Discord-Link fehlt im Spiel (https://discord.gg/Ej4JPmCZva)');
|
||||
if (has('README.md') && !/michael\s*media/i.test(fs.readFileSync(path.join(root, 'README.md'), 'utf8'))) issues.push('README ohne "Michael Media"');
|
||||
}
|
||||
if (!has('.dashboard.json')) issues.push('.dashboard.json fehlt (Projekt-Dashboard)');
|
||||
if (pkg && Object.keys(deps).length && !has('node_modules')) issues.push('node_modules fehlt (npm install)');
|
||||
if (has('.gitignore')) {
|
||||
const gi = fs.readFileSync(path.join(root, '.gitignore'), 'utf8');
|
||||
for (const [dir, pat] of [['node_modules', /node_modules/], ['sprite-generator/output', /output/], ['release', /release/], ['bin', /\bbin\b/]]) {
|
||||
if (has(dir.split('/')[0]) && has(dir) && !pat.test(gi)) issues.push(`${dir}/ nicht in .gitignore`);
|
||||
}
|
||||
}
|
||||
// generator: own copy of the ComfyGen scripts?
|
||||
for (const g of ['sprite-generator', 'Spritegenerator', 'design-gen', 'sprite-gen']) {
|
||||
if (!has(g)) continue;
|
||||
const gen = path.join(root, g);
|
||||
const cmd = path.join(gen, 'gen.cmd');
|
||||
const usesTools = fs.existsSync(cmd) && /_Tools\\ComfyGen/i.test(fs.readFileSync(cmd, 'utf8'));
|
||||
const pyCount = fs.readdirSync(gen).filter(f => f.endsWith('.py')).length;
|
||||
if (!usesTools && pyCount > 3) issues.push(`${g}: eigene Generator-Kopie (${pyCount} .py) statt _Tools\\ComfyGen`);
|
||||
}
|
||||
// ---- ComfyUI: could graphics / sound / icon come from ComfyGen? ------------------------------
|
||||
const comfy = [];
|
||||
{
|
||||
const MEDIA_IMG = /\.(png|jpe?g|webp|gif|bmp)$/i, MEDIA_SND = /\.(mp3|ogg|wav|flac)$/i;
|
||||
let imgs = 0, snds = 0, icon = false;
|
||||
(function walk(dir, depth) {
|
||||
let ents = [];
|
||||
try { ents = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
|
||||
for (const e of ents) {
|
||||
if (e.isDirectory()) {
|
||||
if (depth < 7 && !SKIP.test(e.name) && !/^(sprite-?gen(erator)?|spritegenerator|design-gen|docs|screenshots|android|ios)$/i.test(e.name)) walk(path.join(dir, e.name), depth + 1);
|
||||
} else if (MEDIA_IMG.test(e.name)) { imgs++; if (/^(app[_-]?)?icon|^ic_launcher|^logo/i.test(e.name)) icon = true; }
|
||||
else if (MEDIA_SND.test(e.name)) snds++;
|
||||
else if (/\.ico$/i.test(e.name)) icon = true;
|
||||
}
|
||||
})(root, 0);
|
||||
const genDir = ['sprite-generator', 'Spritegenerator', 'design-gen', 'sprite-gen'].find(has);
|
||||
const app = code.filter(f => !isGen(f));
|
||||
const count = re => app.reduce((n, f) => n + (f.text.match(re) || []).length, 0);
|
||||
const drawn = count(/\b(fillRect|strokeRect|arc|ellipse|bezierCurveTo|FillRectangle|FillEllipse|DrawRectangle|DrawEllipse|pygame\.draw\.\w+|DrawCircle|DrawRect)\s*\(/g);
|
||||
const synth = count(/createOscillator|\btone\(|OscillatorNode|winsound\.Beep|Console\.Beep|pygame\.sndarray|SineWave|SignalGenerator/g);
|
||||
const voiceText = app.some(f => /\b(dialog|dialogue|story|narrat|speech|voice)\b/i.test(f.rel));
|
||||
if (!genDir) comfy.push(`kein ComfyGen-Generator – \`_Tools\\ComfyGen\\template\` → \`sprite-generator\\\` (gen generate/adopt/generate_audio)`);
|
||||
else {
|
||||
let prompts = 0, audio = 0;
|
||||
try { prompts = (fs.readFileSync(path.join(root, genDir, 'prompts.py'), 'utf8').match(/^\s*\(\s*["']/gm) || []).length; } catch { /* none */ }
|
||||
try { audio = (fs.readFileSync(path.join(root, genDir, fs.readdirSync(path.join(root, genDir)).find(n => /^audio.*\.py$/i.test(n)) || 'audio.py'), 'utf8').match(/^\s*\(\s*["']/gm) || []).length; } catch { /* none */ }
|
||||
comfy.push(`Generator ${genDir}: ${prompts} Bild-Prompts, ${audio} Audio-Einträge · im Projekt ${imgs} Bilder, ${snds} Sounds`);
|
||||
}
|
||||
if (!icon) comfy.push('kein App-Icon → `gen generate icon` + `gen adopt --size 512 icon`');
|
||||
if (drawn > 40 && imgs < 10) comfy.push(`Grafik meist gezeichnet (${drawn} Zeichenbefehle, ${imgs} Bilder) → Sprites/Hintergründe per ComfyUI`);
|
||||
if (snds === 0 && (synth || stack.some(s => /HTML|Capacitor|Unity|C\+\+|Python/.test(s)))) comfy.push(`keine Sounddateien${synth ? ` (${synth}× Synth-Ton im Code)` : ''} → Musik/SFX mit \`gen generate_audio\``);
|
||||
else if (synth > 5 && snds < 5) comfy.push(`${synth}× Synth-Ton, nur ${snds} Sounddateien → echte SFX per \`gen generate_audio\``);
|
||||
if (voiceText) comfy.push('Story/Dialog-Dateien gefunden → Erzählstimmen mit `gen generate_voice` möglich');
|
||||
// is the server up? (only informative, 800 ms)
|
||||
try { const r = await fetch('http://127.0.0.1:8188/system_stats', { signal: AbortSignal.timeout(800) }); comfy.push(`ComfyUI-Server: ${r.ok ? 'läuft' : 'antwortet nicht richtig'}`); }
|
||||
catch { comfy.push('ComfyUI-Server: aus (bei Bedarf `D:\\ComfyUI` starten)'); }
|
||||
}
|
||||
|
||||
// release older than the code
|
||||
const newestSrc = Math.max(0, ...own.filter(f => !isGen(f)).map(f => f.mtime));
|
||||
for (const d of ['release', 'dist']) {
|
||||
const dp = path.join(root, d);
|
||||
if (!fs.existsSync(dp)) continue;
|
||||
let newest = 0;
|
||||
(function w(x, depth) { for (const e of fs.readdirSync(x, { withFileTypes: true })) { const p = path.join(x, e.name); if (e.isDirectory()) { if (depth < 3) w(p, depth + 1); } else newest = Math.max(newest, fs.statSync(p).mtimeMs); } })(dp, 0);
|
||||
const days = (newestSrc - newest) / 864e5;
|
||||
if (newest && days > 1) issues.push(`${d}/ ist ${Math.round(days)} Tage älter als der Code (neu bauen?)`);
|
||||
}
|
||||
const todo = own.reduce((n, f) => n + (f.text.match(/\b(TODO|FIXME|HACK|XXX)\b/g) || []).length, 0);
|
||||
const logs = code.filter(f => /\.(js|ts|tsx|jsx)$/.test(f.rel) && !isGen(f)).reduce((n, f) => n + (f.text.match(/console\.log\(/g) || []).length, 0);
|
||||
if (todo) issues.push(`${todo}× TODO/FIXME im Code`);
|
||||
if (logs > 10) issues.push(`${logs}× console.log`);
|
||||
const testDir = ['tests', 'test', 'tools', '__tests__'].some(has) || own.some(f => /\.(test|spec)\.|selftest|verify/i.test(f.rel));
|
||||
if (!testDir && code.length > 5) issues.push('keine Tests/Selbsttests gefunden');
|
||||
if (kind === 'web' && !has('game/kit') && !has('kit')) issues.push('nutzt web/kit nicht (Vorlage webgame: Release-Kette, Highscores, exe)');
|
||||
if (kind === 'mobile' && !has('src/kit')) issues.push('nutzt mobile/kit nicht');
|
||||
|
||||
// ---- report -------------------------------------------------------------------------------
|
||||
const total = code.reduce((n, f) => n + f.lines, 0);
|
||||
const big = [...code].filter(f => !isGen(f)).sort((a, b) => b.lines - a.lines).filter(f => f.lines > 800);
|
||||
const out = [];
|
||||
out.push(`# ${name} [${stack.join(', ') || '?'}] ${code.length} Dateien, ${total.toLocaleString('de-DE')} Zeilen (${Object.entries(ext).sort((a, b) => b[1] - a[1]).slice(0, 4).map(([e, n]) => `${e} ${n}`).join(', ')})`);
|
||||
if (big.length) out.push(`Groß (>800 Z., aufteilen?): ${big.slice(0, TOP).map(f => `${f.rel} ${f.lines}`).join(' · ')}`);
|
||||
if (kitLines.length) out.push('Kit: ' + kitLines.join(' | '));
|
||||
const ORIGIN = { 'xp-battleship': 'mobile/kit', pipefix: 'web/kit + web/template', 'byte path': 'web/kit (Audio, Eingabe, Loop)' };
|
||||
if (ORIGIN[name.toLowerCase()]) out.push(`Hinweis: Ursprung von ${ORIGIN[name.toLowerCase()]} – Umstellung aufs Kit nur bei Bedarf, eher Neues von hier in die Library holen.`);
|
||||
if (comfy.length) { out.push('ComfyUI:'); for (const c of comfy) out.push('- ' + c); }
|
||||
if (reinvent.length) { out.push('Selbst gebaut, Kit kann es:'); for (const r of reinvent.slice(0, TOP)) out.push('- ' + r); }
|
||||
if (cands.length && !kind) {
|
||||
// stacks without a Library kit (C++, C#, Kotlin, Python): one line, details with --all
|
||||
const missing = cands.filter(c => c.includes('FEHLT'));
|
||||
const groups = [...new Set(missing.map(c => c.split(': ')[0].replace(/^.*\) /, '')))];
|
||||
out.push(`Library hat kein Kit für ${stack.join('/') || 'diesen Stack'}: ${missing.length} allgemein wirkende Module (${groups.slice(0, 6).join(', ')}), z. B. ${missing.slice(0, 3).map(c => c.split(' (')[0]).join(', ')}${ALL ? '' : ' (--all = Liste)'}`);
|
||||
if (ALL) for (const c of cands) out.push('- ' + c);
|
||||
} else if (cands.length) { out.push('Library-Kandidaten:'); for (const c of cands.slice(0, TOP)) out.push('- ' + c); if (cands.length > TOP) out.push(` (+${cands.length - TOP} weitere, --all)`); }
|
||||
if (issues.length) { out.push('Hygiene:'); for (const i of issues) out.push('- ' + i); }
|
||||
if (!reinvent.length && !cands.length && !issues.length) out.push('Keine Auffälligkeiten.');
|
||||
console.log(out.join('\n'));
|
||||
157
Library/web/kit/kit-audio.js
Normal file
157
Library/web/kit/kit-audio.js
Normal file
@@ -0,0 +1,157 @@
|
||||
/* Kit audio (v1) - WebAudio for HTML games. From _Tools\Library\web\kit. Needs kit-core.js.
|
||||
|
||||
const audio = Kit.createAudio({
|
||||
prefix: 'mygame', // localStorage keys mygame.muted / .music / .sfx
|
||||
dir: 'assets/Audio/', ext: '.mp3', // where ComfyGen adopt_audio puts the files
|
||||
files: ['sfx_click', 'sfx_win', 'music_game'],
|
||||
throttle: { sfx_step: 60 }, // optional min gap in ms per clip
|
||||
});
|
||||
audio.sfx('sfx_click') play once (silent if missing / not decoded yet)
|
||||
audio.music('music_game') loop as music (switching tracks fades the old one)
|
||||
const h = audio.loop('sfx_flow', 0.5); h.stop() looping effect
|
||||
audio.tone(880, 0.1) / audio.noise(0.2) synth fallback sounds, no files needed
|
||||
audio.toggleMute() / audio.setVolume(music, sfx) / audio.muted / audio.musicVol / audio.sfxVol
|
||||
|
||||
Best effort everywhere: missing files, a blocked AudioContext or no WebAudio never throw.
|
||||
The context is created on the first pointer/key press (autoplay policy) - nothing to call. */
|
||||
(function (root) {
|
||||
'use strict';
|
||||
const Kit = (root.Kit = root.Kit || {});
|
||||
|
||||
Kit.createAudio = (opt = {}) => {
|
||||
const st = Kit.store(opt.prefix || 'kit');
|
||||
const dir = opt.dir || 'assets/Audio/', ext = opt.ext || '.mp3';
|
||||
const files = opt.files || [], throttle = opt.throttle || {};
|
||||
let ctx = null, musicGain = null, sfxGain = null, musicSrc = null, musicName = null, wantMusic = null;
|
||||
const buffers = {}, loading = {}, last = {};
|
||||
const api = {
|
||||
muted: st.get('muted', false),
|
||||
musicVol: st.get('music', 0.35),
|
||||
sfxVol: st.get('sfx', 0.8),
|
||||
};
|
||||
// slider 0..1 -> gain; squared so the low end of a slider is fine-grained
|
||||
const g = v => (api.muted ? 0 : v * v);
|
||||
|
||||
function unlock() {
|
||||
if (ctx) { if (ctx.state === 'suspended') ctx.resume().catch(() => {}); return; }
|
||||
try {
|
||||
ctx = new (root.AudioContext || root.webkitAudioContext)();
|
||||
musicGain = ctx.createGain(); musicGain.gain.value = g(api.musicVol); musicGain.connect(ctx.destination);
|
||||
sfxGain = ctx.createGain(); sfxGain.gain.value = g(api.sfxVol); sfxGain.connect(ctx.destination);
|
||||
for (const n of files) load(n);
|
||||
if (wantMusic) api.music(wantMusic);
|
||||
} catch (e) { ctx = null; }
|
||||
}
|
||||
if (typeof document !== 'undefined') {
|
||||
for (const ev of ['pointerdown', 'keydown', 'touchstart']) addEventListener(ev, unlock, { capture: true, passive: true });
|
||||
// Android leaves a context suspended after backgrounding unless it is resumed by hand
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
if (!ctx) return;
|
||||
if (document.hidden) ctx.suspend().catch(() => {}); else ctx.resume().catch(() => {});
|
||||
});
|
||||
}
|
||||
|
||||
function load(name) {
|
||||
if (!ctx) return Promise.resolve(null);
|
||||
if (buffers[name]) return Promise.resolve(buffers[name]);
|
||||
if (loading[name]) return loading[name];
|
||||
return (loading[name] = Kit.loadBytes(Kit.asset(dir + name + ext))
|
||||
.then(b => ctx.decodeAudioData(b))
|
||||
.then(buf => (buffers[name] = buf))
|
||||
.catch(() => null)
|
||||
.finally(() => { delete loading[name]; }));
|
||||
}
|
||||
|
||||
function start(buf, vol, loop, bus) {
|
||||
const src = ctx.createBufferSource();
|
||||
src.buffer = buf; src.loop = loop;
|
||||
const gn = ctx.createGain(); gn.gain.value = vol;
|
||||
src.connect(gn).connect(bus);
|
||||
src.start();
|
||||
src.gainNode = gn;
|
||||
return src;
|
||||
}
|
||||
function fadeStop(src) {
|
||||
if (!src || !ctx) return;
|
||||
try { src.gainNode.gain.setTargetAtTime(0, ctx.currentTime, 0.08); src.stop(ctx.currentTime + 0.4); } catch (e) { /* stopped */ }
|
||||
}
|
||||
|
||||
api.sfx = (name, vol = 1) => {
|
||||
if (!ctx || api.muted) return;
|
||||
if (ctx.state === 'suspended') ctx.resume().catch(() => {});
|
||||
const gap = throttle[name] || 0, now = performance.now();
|
||||
if (gap && now - (last[name] || 0) < gap) return;
|
||||
last[name] = now;
|
||||
// first use of a clip that is still decoding: play it once it is ready instead of dropping it
|
||||
if (buffers[name]) start(buffers[name], vol, false, sfxGain);
|
||||
else load(name).then(b => { if (b && !api.muted) start(b, vol, false, sfxGain); });
|
||||
};
|
||||
|
||||
api.loop = (name, vol = 1) => {
|
||||
const h = { src: null, stopped: false, stop() { h.stopped = true; fadeStop(h.src); h.src = null; } };
|
||||
if (!ctx) return h;
|
||||
load(name).then(b => { if (b && !h.stopped) h.src = start(b, vol, true, sfxGain); });
|
||||
return h;
|
||||
};
|
||||
|
||||
api.music = name => {
|
||||
wantMusic = name;
|
||||
if (!ctx || musicName === name) return;
|
||||
musicName = name;
|
||||
load(name).then(b => {
|
||||
if (!b || musicName !== name) { if (!b && musicName === name) musicName = null; return; }
|
||||
fadeStop(musicSrc);
|
||||
musicSrc = start(b, 1, true, musicGain);
|
||||
});
|
||||
};
|
||||
api.stopMusic = () => { wantMusic = null; musicName = null; fadeStop(musicSrc); musicSrc = null; };
|
||||
|
||||
function apply() {
|
||||
if (musicGain) musicGain.gain.value = g(api.musicVol);
|
||||
if (sfxGain) sfxGain.gain.value = g(api.sfxVol);
|
||||
}
|
||||
api.toggleMute = () => { api.muted = !api.muted; st.set('muted', api.muted); apply(); return api.muted; };
|
||||
api.setVolume = (music, sfx) => {
|
||||
if (music != null) { api.musicVol = Kit.clamp(+music || 0, 0, 1); st.set('music', api.musicVol); }
|
||||
if (sfx != null) { api.sfxVol = Kit.clamp(+sfx || 0, 0, 1); st.set('sfx', api.sfxVol); }
|
||||
if (api.muted && (music > 0 || sfx > 0)) { api.muted = false; st.set('muted', false); }
|
||||
apply();
|
||||
};
|
||||
// duck music under a big moment (ramped, no clicks)
|
||||
api.duck = (on, secs = 0.2) => {
|
||||
if (!ctx || !musicGain) return;
|
||||
const t = ctx.currentTime;
|
||||
musicGain.gain.cancelScheduledValues(t);
|
||||
musicGain.gain.setValueAtTime(musicGain.gain.value, t);
|
||||
musicGain.gain.linearRampToValueAtTime(on ? 0 : g(api.musicVol), t + secs);
|
||||
};
|
||||
api.suspend = () => { if (ctx) ctx.suspend().catch(() => {}); };
|
||||
api.resume = () => { if (ctx && !document.hidden) ctx.resume().catch(() => {}); };
|
||||
api.unlock = unlock;
|
||||
|
||||
// ---- synth (placeholder sounds until ComfyGen clips exist) --------------------------
|
||||
api.tone = (freq, dur = 0.1, type = 'square', vol = 0.3, slide = 0, delay = 0) => {
|
||||
if (!ctx || api.muted) return;
|
||||
const t = ctx.currentTime + delay;
|
||||
const o = ctx.createOscillator(), gn = ctx.createGain();
|
||||
o.type = type; o.frequency.setValueAtTime(freq, t);
|
||||
if (slide) o.frequency.exponentialRampToValueAtTime(Math.max(30, freq + slide), t + dur);
|
||||
gn.gain.setValueAtTime(vol, t); gn.gain.exponentialRampToValueAtTime(0.001, t + dur);
|
||||
o.connect(gn).connect(sfxGain); o.start(t); o.stop(t + dur + 0.02);
|
||||
};
|
||||
api.noise = (dur = 0.2, vol = 0.3, cutoff = 1200, delay = 0) => {
|
||||
if (!ctx || api.muted) return;
|
||||
const t = ctx.currentTime + delay, len = Math.floor(ctx.sampleRate * dur);
|
||||
const buf = ctx.createBuffer(1, len, ctx.sampleRate), d = buf.getChannelData(0);
|
||||
for (let i = 0; i < len; i++) d[i] = (Math.random() * 2 - 1) * (1 - i / len);
|
||||
const src = ctx.createBufferSource(), f = ctx.createBiquadFilter(), gn = ctx.createGain();
|
||||
src.buffer = buf; f.type = 'lowpass'; f.frequency.value = cutoff; gn.gain.value = vol;
|
||||
src.connect(f).connect(gn).connect(sfxGain); src.start(t);
|
||||
};
|
||||
// little arpeggio: audio.arp([523, 659, 784], 0.12)
|
||||
api.arp = (freqs, step = 0.08, type = 'square', vol = 0.18) =>
|
||||
freqs.forEach((f, i) => api.tone(f, step * 1.6, type, vol, 0, i * step));
|
||||
|
||||
return api;
|
||||
};
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
142
Library/web/kit/kit-core.js
Normal file
142
Library/web/kit/kit-core.js
Normal file
@@ -0,0 +1,142 @@
|
||||
/* Kit core (v1) - from D:\Oculusquest\Projekt\_Tools\Library\web\kit.
|
||||
Do not fork this copy inside a project: improve it in the Library and re-copy with
|
||||
new-project.ps1 -UpdateKit. Classic script (no ES module) so the game also runs from file://.
|
||||
|
||||
Kit.$(id) document.getElementById
|
||||
Kit.asset(path) path, or the data: URI the single-file build embedded
|
||||
Kit.loadBytes(url) ArrayBuffer (works for data: URIs and files)
|
||||
Kit.images(names, dir, ext) { name: Image } - img.ok is true once loaded
|
||||
Kit.store(prefix) safe localStorage JSON get/set/del
|
||||
Kit.saveSlot(key, defaults, opt) versioned save with backup copy + defaults merge
|
||||
Kit.rng(seed) seeded random() in [0,1) (mulberry32)
|
||||
Kit.clamp / lerp / shuffle / pick / fmt
|
||||
*/
|
||||
(function (root) {
|
||||
'use strict';
|
||||
const Kit = (root.Kit = root.Kit || {});
|
||||
Kit.version = 1;
|
||||
Kit.$ = id => document.getElementById(id);
|
||||
|
||||
// ---- assets ---------------------------------------------------------------------------
|
||||
// build-web.mjs puts every asset into window.KIT_ASSETS as a data: URI, so the release
|
||||
// HTML works from file:// and on any web host without a folder next to it.
|
||||
Kit.asset = path => (root.KIT_ASSETS && root.KIT_ASSETS[path]) || path;
|
||||
|
||||
Kit.loadBytes = url => {
|
||||
if (url.startsWith('data:')) {
|
||||
const bin = atob(url.slice(url.indexOf(',') + 1));
|
||||
const buf = new Uint8Array(bin.length);
|
||||
for (let i = 0; i < bin.length; i++) buf[i] = bin.charCodeAt(i);
|
||||
return Promise.resolve(buf.buffer);
|
||||
}
|
||||
return fetch(url).then(r => (r.ok ? r.arrayBuffer() : Promise.reject(new Error(r.status + ' ' + url))));
|
||||
};
|
||||
|
||||
// Missing images are fine: draw a fallback shape while !img.ok.
|
||||
Kit.images = (names, dir = 'assets/Sprites/', ext = '.png') => {
|
||||
const out = {};
|
||||
for (const n of names) {
|
||||
const im = new Image();
|
||||
im.ok = false;
|
||||
im.onload = () => { im.ok = true; };
|
||||
im.src = Kit.asset(dir + n + ext);
|
||||
out[n] = im;
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
// ---- storage --------------------------------------------------------------------------
|
||||
// Every access is wrapped: private mode, blocked storage or a full quota must not crash.
|
||||
Kit.store = prefix => {
|
||||
const p = prefix ? prefix + '.' : '';
|
||||
return {
|
||||
get(k, d) {
|
||||
try { const v = localStorage.getItem(p + k); return v == null ? d : JSON.parse(v); } catch (e) { return d; }
|
||||
},
|
||||
set(k, v) {
|
||||
try { localStorage.setItem(p + k, JSON.stringify(v)); return true; } catch (e) { return false; }
|
||||
},
|
||||
del(k) { try { localStorage.removeItem(p + k); } catch (e) { /* ignore */ } },
|
||||
};
|
||||
};
|
||||
|
||||
/* Save slot for game progress.
|
||||
const slot = Kit.saveSlot('mygame.save', () => ({ level: 1, best: {} }), { version: 2, migrate })
|
||||
let save = slot.load(); ... slot.save(save);
|
||||
- defaults() is a function so every load gets fresh nested objects.
|
||||
- Loaded data is merged over defaults (one level deep for plain objects), so fields added
|
||||
in a later version exist in old saves.
|
||||
- migrate(data, fromVersion) runs when the stored version is older; return the data.
|
||||
- Every backupEvery-th save also writes a backup; a corrupt primary falls back to it.
|
||||
- slot.failed() turns true once a write failed - tell the player once. */
|
||||
Kit.saveSlot = (key, defaults, opt = {}) => {
|
||||
const version = opt.version || 1, every = opt.backupEvery || 10;
|
||||
let since = 0, failed = false;
|
||||
const isObj = v => v && typeof v === 'object' && !Array.isArray(v);
|
||||
function merge(d, s) {
|
||||
const out = Object.assign({}, d, s);
|
||||
for (const k of Object.keys(d)) if (isObj(d[k]) && isObj(s[k])) out[k] = Object.assign({}, d[k], s[k]);
|
||||
return out;
|
||||
}
|
||||
function read(k) {
|
||||
try {
|
||||
const raw = localStorage.getItem(k);
|
||||
if (!raw) return null;
|
||||
const parsed = JSON.parse(raw);
|
||||
if (!isObj(parsed)) return null;
|
||||
const from = typeof parsed._v === 'number' ? parsed._v : 1;
|
||||
let s = merge(defaults(), parsed);
|
||||
if (from < version && opt.migrate) s = opt.migrate(s, from) || s;
|
||||
s._v = version;
|
||||
return s;
|
||||
} catch (e) { return null; }
|
||||
}
|
||||
return {
|
||||
load() { return read(key) || read(key + '.bak') || Object.assign(defaults(), { _v: version }); },
|
||||
save(data) {
|
||||
data._v = version;
|
||||
try {
|
||||
const json = JSON.stringify(data);
|
||||
localStorage.setItem(key, json);
|
||||
if (++since >= every) { since = 0; localStorage.setItem(key + '.bak', json); }
|
||||
return true;
|
||||
} catch (e) { failed = true; return false; }
|
||||
},
|
||||
clear() { try { localStorage.removeItem(key); localStorage.removeItem(key + '.bak'); } catch (e) { /* ignore */ } },
|
||||
failed: () => failed,
|
||||
};
|
||||
};
|
||||
|
||||
// ---- math / random --------------------------------------------------------------------
|
||||
Kit.rng = seed => {
|
||||
let a = seed >>> 0 || 1;
|
||||
return () => {
|
||||
a = (a + 0x6d2b79f5) | 0;
|
||||
let t = Math.imul(a ^ (a >>> 15), 1 | a);
|
||||
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
};
|
||||
Kit.clamp = (v, lo, hi) => (v < lo ? lo : v > hi ? hi : v);
|
||||
Kit.lerp = (a, b, t) => a + (b - a) * t;
|
||||
Kit.pick = (arr, rnd = Math.random) => arr[Math.floor(rnd() * arr.length)];
|
||||
Kit.shuffle = (arr, rnd = Math.random) => {
|
||||
for (let i = arr.length - 1; i > 0; i--) {
|
||||
const j = Math.floor(rnd() * (i + 1));
|
||||
[arr[i], arr[j]] = [arr[j], arr[i]];
|
||||
}
|
||||
return arr;
|
||||
};
|
||||
// 1234567 -> "1.23M" (idle games); below 10 000 plain with thousands separator
|
||||
Kit.fmt = n => {
|
||||
if (!Number.isFinite(n)) return '0';
|
||||
const a = Math.abs(n);
|
||||
if (a < 1e4) return Math.round(n).toLocaleString('en-US');
|
||||
const units = ['K', 'M', 'B', 'T', 'Qa', 'Qi'];
|
||||
let u = -1, v = a;
|
||||
while (v >= 1000 && u < units.length - 1) { v /= 1000; u++; }
|
||||
return (n < 0 ? '-' : '') + (v >= 100 ? v.toFixed(0) : v >= 10 ? v.toFixed(1) : v.toFixed(2)) + units[u];
|
||||
};
|
||||
|
||||
if (typeof module !== 'undefined' && module.exports) module.exports = Kit;
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
72
Library/web/kit/kit-fx.js
Normal file
72
Library/web/kit/kit-fx.js
Normal file
@@ -0,0 +1,72 @@
|
||||
/* Kit fx (v1) - small juice helpers for canvas games. From _Tools\Library\web\kit.
|
||||
|
||||
const fx = Kit.fx();
|
||||
fx.burst(x, y, '#ffd83a', 16, 180) particles (count, speed px/s)
|
||||
fx.float(x, y, '+10', '#fff') rising, fading text
|
||||
fx.shake(8) screen shake strength in px (decays)
|
||||
fx.update(dt) in loop update
|
||||
fx.apply(ctx) ... draw world ... ctx.restore() (apply saves + offsets for shake)
|
||||
fx.draw(ctx) particles + texts on top
|
||||
Kit.tween(from, to, t, Kit.ease.outBack) */
|
||||
(function (root) {
|
||||
'use strict';
|
||||
const Kit = (root.Kit = root.Kit || {});
|
||||
|
||||
Kit.ease = {
|
||||
linear: t => t,
|
||||
outQuad: t => 1 - (1 - t) * (1 - t),
|
||||
inOutQuad: t => (t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2),
|
||||
outCubic: t => 1 - Math.pow(1 - t, 3),
|
||||
outBack: t => 1 + 2.70158 * Math.pow(t - 1, 3) + 1.70158 * Math.pow(t - 1, 2),
|
||||
outElastic: t => (t === 0 || t === 1 ? t : Math.pow(2, -10 * t) * Math.sin((t * 10 - 0.75) * (2 * Math.PI / 3)) + 1),
|
||||
};
|
||||
Kit.tween = (a, b, t, ease = Kit.ease.outQuad) => a + (b - a) * ease(Math.max(0, Math.min(1, t)));
|
||||
|
||||
Kit.fx = () => {
|
||||
const parts = [], texts = [];
|
||||
let shake = 0;
|
||||
return {
|
||||
burst(x, y, color = '#fff', n = 14, speed = 160, life = 0.6) {
|
||||
for (let i = 0; i < n; i++) {
|
||||
const a = Math.random() * Math.PI * 2, v = speed * (0.4 + Math.random() * 0.8);
|
||||
parts.push({ x, y, vx: Math.cos(a) * v, vy: Math.sin(a) * v, life, max: life, color, r: 2 + Math.random() * 2.5 });
|
||||
}
|
||||
},
|
||||
float(x, y, text, color = '#fff', size = 18) { texts.push({ x, y, text, color, size, life: 0.9, max: 0.9 }); },
|
||||
shake(px) { shake = Math.max(shake, px); },
|
||||
update(dt) {
|
||||
for (let i = parts.length - 1; i >= 0; i--) {
|
||||
const p = parts[i];
|
||||
p.life -= dt; if (p.life <= 0) { parts.splice(i, 1); continue; }
|
||||
p.x += p.vx * dt; p.y += p.vy * dt; p.vx *= 0.96; p.vy = p.vy * 0.96 + 220 * dt;
|
||||
}
|
||||
for (let i = texts.length - 1; i >= 0; i--) {
|
||||
const t = texts[i];
|
||||
t.life -= dt; if (t.life <= 0) { texts.splice(i, 1); continue; }
|
||||
t.y -= 40 * dt;
|
||||
}
|
||||
shake = Math.max(0, shake - 40 * dt);
|
||||
},
|
||||
apply(ctx) {
|
||||
ctx.save();
|
||||
if (shake > 0) ctx.translate((Math.random() * 2 - 1) * shake, (Math.random() * 2 - 1) * shake);
|
||||
},
|
||||
draw(ctx) {
|
||||
for (const p of parts) {
|
||||
ctx.globalAlpha = p.life / p.max;
|
||||
ctx.fillStyle = p.color;
|
||||
ctx.beginPath(); ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2); ctx.fill();
|
||||
}
|
||||
ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
|
||||
for (const t of texts) {
|
||||
ctx.globalAlpha = Math.min(1, t.life / t.max * 2);
|
||||
ctx.font = `bold ${t.size}px system-ui, sans-serif`;
|
||||
ctx.lineWidth = 4; ctx.strokeStyle = 'rgba(0,0,0,.6)'; ctx.strokeText(t.text, t.x, t.y);
|
||||
ctx.fillStyle = t.color; ctx.fillText(t.text, t.x, t.y);
|
||||
}
|
||||
ctx.globalAlpha = 1;
|
||||
},
|
||||
clear() { parts.length = 0; texts.length = 0; shake = 0; },
|
||||
};
|
||||
};
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
39
Library/web/kit/kit-host.js
Normal file
39
Library/web/kit/kit-host.js
Normal file
@@ -0,0 +1,39 @@
|
||||
/* Kit host (v1) - window control for the desktop exe (WebView2 launcher) and the browser.
|
||||
From _Tools\Library\web\kit.
|
||||
|
||||
Kit.host.exe true inside the launcher (Launcher.csproj); <html> gets class "exe"
|
||||
Kit.host.fullscreen() exe: toggle borderless-maximised; browser: Fullscreen API
|
||||
Kit.host.minimize() / Kit.host.quit() exe only (no-ops in the browser)
|
||||
Kit.host.dragArea(el) mousedown on el itself drags the window, double-click = fullscreen
|
||||
|
||||
The launcher draws no title bar; put minimise/fullscreen/close buttons into the page and
|
||||
show them only for html.exe (template: #winctl). */
|
||||
(function (root) {
|
||||
'use strict';
|
||||
const Kit = (root.Kit = root.Kit || {});
|
||||
const wv = root.chrome && root.chrome.webview;
|
||||
const send = c => { if (wv) wv.postMessage(c); };
|
||||
|
||||
const host = {
|
||||
exe: !!wv,
|
||||
send,
|
||||
fullscreen() {
|
||||
if (wv) return send('maximize');
|
||||
if (document.fullscreenElement) document.exitFullscreen().catch(() => {});
|
||||
else document.documentElement.requestFullscreen().catch(() => {});
|
||||
},
|
||||
minimize: () => send('minimize'),
|
||||
quit: () => send('quit'),
|
||||
dragArea(el) {
|
||||
if (!wv) return;
|
||||
el.addEventListener('mousedown', e => { if (e.button === 0 && e.target === el) send('drag'); });
|
||||
el.addEventListener('dblclick', e => { if (e.target === el) send('maximize'); });
|
||||
},
|
||||
};
|
||||
Kit.host = host;
|
||||
if (wv && typeof document !== 'undefined') document.documentElement.classList.add('exe');
|
||||
// F11 in the browser: same toggle as the exe (the launcher handles F11 / Alt+Enter itself)
|
||||
if (!wv && typeof addEventListener !== 'undefined') {
|
||||
addEventListener('keydown', e => { if (e.key === 'F11') { e.preventDefault(); host.fullscreen(); } });
|
||||
}
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
62
Library/web/kit/kit-i18n.js
Normal file
62
Library/web/kit/kit-i18n.js
Normal file
@@ -0,0 +1,62 @@
|
||||
/* Kit i18n (v1) - texts in several languages for HTML games. From _Tools\Library\web\kit.
|
||||
Needs kit-core.js. Dictionaries live in game/lang.js (a script, not JSON: file:// cannot fetch).
|
||||
|
||||
game/lang.js: window.LANG = { en: { play: 'Play', score: 'Score {n}' }, de: { play: 'Spielen' } };
|
||||
const L = Kit.i18n(window.LANG, { prefix: 'mygame' });
|
||||
L.t('score', { n: 5 }) "Score 5" - missing key: English, then the key itself (visible = easy to spot)
|
||||
L.lang / L.langs current language / ['en', 'de']
|
||||
L.set('de') switch + remember; re-fills data-i18n elements, calls onChange listeners
|
||||
L.next() cycle to the next language (one "English / Deutsch" button)
|
||||
L.apply(root) fills [data-i18n="key"] (text), [data-i18n-html] (HTML), [data-i18n-title],
|
||||
[data-i18n-placeholder]; runs once at start and after every set()
|
||||
L.onChange(fn) re-render menus/HUD after a switch
|
||||
Start language: saved choice, else browser language if there is a dictionary, else the first one. */
|
||||
(function (root) {
|
||||
'use strict';
|
||||
const Kit = (root.Kit = root.Kit || {});
|
||||
|
||||
Kit.i18n = (dicts, opt = {}) => {
|
||||
const langs = Object.keys(dicts || {});
|
||||
if (!langs.length) throw new Error('Kit.i18n: no dictionaries (game/lang.js loaded?)');
|
||||
const st = Kit.store(opt.prefix || 'kit');
|
||||
const fallback = dicts.en ? 'en' : langs[0];
|
||||
const listeners = [];
|
||||
const browser = (typeof navigator !== 'undefined' && (navigator.language || '').slice(0, 2).toLowerCase()) || '';
|
||||
const saved = st.get('lang', null);
|
||||
const api = {
|
||||
langs,
|
||||
lang: langs.includes(saved) ? saved : langs.includes(browser) ? browser : fallback,
|
||||
};
|
||||
|
||||
api.t = (key, vars) => {
|
||||
let s = dicts[api.lang]?.[key] ?? dicts[fallback]?.[key] ?? key;
|
||||
if (vars) for (const [k, v] of Object.entries(vars)) s = s.split(`{${k}}`).join(String(v));
|
||||
return s;
|
||||
};
|
||||
|
||||
api.apply = (scope = typeof document !== 'undefined' ? document : null) => {
|
||||
if (!scope) return;
|
||||
for (const el of scope.querySelectorAll('[data-i18n]')) el.textContent = api.t(el.dataset.i18n);
|
||||
for (const el of scope.querySelectorAll('[data-i18n-html]')) el.innerHTML = api.t(el.dataset.i18nHtml);
|
||||
for (const el of scope.querySelectorAll('[data-i18n-title]')) el.title = api.t(el.dataset.i18nTitle);
|
||||
for (const el of scope.querySelectorAll('[data-i18n-placeholder]')) el.placeholder = api.t(el.dataset.i18nPlaceholder);
|
||||
if (typeof document !== 'undefined') document.documentElement.lang = api.lang;
|
||||
};
|
||||
|
||||
api.set = l => {
|
||||
if (!langs.includes(l) || l === api.lang) return;
|
||||
api.lang = l;
|
||||
st.set('lang', l);
|
||||
api.apply();
|
||||
for (const fn of listeners) fn(l);
|
||||
};
|
||||
api.next = () => api.set(langs[(langs.indexOf(api.lang) + 1) % langs.length]);
|
||||
api.onChange = fn => { listeners.push(fn); };
|
||||
|
||||
if (typeof document !== 'undefined') {
|
||||
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => api.apply());
|
||||
else api.apply();
|
||||
}
|
||||
return api;
|
||||
};
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
73
Library/web/kit/kit-input.js
Normal file
73
Library/web/kit/kit-input.js
Normal file
@@ -0,0 +1,73 @@
|
||||
/* Kit input (v1) - keyboard + touch buttons mapped to actions. From _Tools\Library\web\kit.
|
||||
|
||||
const input = Kit.input({
|
||||
keys: { ArrowUp: 'up', w: 'up', ArrowDown: 'down', s: 'down', ArrowLeft: 'left', a: 'left',
|
||||
ArrowRight: 'right', d: 'right', ' ': 'action', p: 'pause', Escape: 'pause', m: 'mute' },
|
||||
onPress(action, e) {}, // first press only (no key repeat)
|
||||
onRelease(action) {},
|
||||
});
|
||||
input.down('left') is it held right now?
|
||||
input.latest(['up','right','down','left']) most recently pressed of these that is still held
|
||||
input.consume('action') true once per press (polling style inside update())
|
||||
|
||||
Touch buttons: any element with data-action="left" works like the key (pointer capture,
|
||||
so sliding off the button releases it). Typing into <input>/<textarea> is ignored.
|
||||
Keys are matched case-insensitively for letters. */
|
||||
(function (root) {
|
||||
'use strict';
|
||||
const Kit = (root.Kit = root.Kit || {});
|
||||
|
||||
Kit.input = (opt = {}) => {
|
||||
const map = {};
|
||||
for (const [k, a] of Object.entries(opt.keys || {})) map[k.length === 1 ? k.toLowerCase() : k] = a;
|
||||
const held = [], pressed = new Set();
|
||||
const api = {};
|
||||
|
||||
function press(a, e) {
|
||||
const i = held.indexOf(a);
|
||||
if (i >= 0) return; // already held (key repeat)
|
||||
held.push(a); pressed.add(a);
|
||||
opt.onPress && opt.onPress(a, e);
|
||||
}
|
||||
function release(a) {
|
||||
const i = held.indexOf(a);
|
||||
if (i < 0) return;
|
||||
held.splice(i, 1);
|
||||
opt.onRelease && opt.onRelease(a);
|
||||
}
|
||||
const typing = e => e.target && /^(INPUT|TEXTAREA|SELECT)$/.test(e.target.tagName);
|
||||
const keyOf = e => (e.key.length === 1 ? e.key.toLowerCase() : e.key);
|
||||
|
||||
addEventListener('keydown', e => {
|
||||
if (typing(e)) return;
|
||||
const a = map[keyOf(e)];
|
||||
if (!a) return;
|
||||
e.preventDefault();
|
||||
if (!e.repeat) press(a, e);
|
||||
});
|
||||
addEventListener('keyup', e => { const a = map[keyOf(e)]; if (a) release(a); });
|
||||
addEventListener('blur', () => { while (held.length) release(held[held.length - 1]); });
|
||||
|
||||
api.bindButtons = (scope = document) => {
|
||||
scope.querySelectorAll('[data-action]').forEach(b => {
|
||||
if (b._kitBound) return;
|
||||
b._kitBound = true;
|
||||
const a = b.dataset.action;
|
||||
b.addEventListener('pointerdown', e => { e.preventDefault(); b.setPointerCapture(e.pointerId); press(a, e); });
|
||||
b.addEventListener('pointerup', () => release(a));
|
||||
b.addEventListener('pointercancel', () => release(a));
|
||||
b.addEventListener('contextmenu', e => e.preventDefault());
|
||||
});
|
||||
};
|
||||
if (typeof document !== 'undefined') {
|
||||
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => api.bindButtons());
|
||||
else api.bindButtons();
|
||||
}
|
||||
|
||||
api.down = a => held.includes(a);
|
||||
api.latest = list => { for (let i = held.length - 1; i >= 0; i--) if (list.includes(held[i])) return held[i]; return null; };
|
||||
api.consume = a => pressed.delete(a);
|
||||
api.clear = () => { held.length = 0; pressed.clear(); };
|
||||
return api;
|
||||
};
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
75
Library/web/kit/kit-loop.js
Normal file
75
Library/web/kit/kit-loop.js
Normal file
@@ -0,0 +1,75 @@
|
||||
/* Kit loop + view (v1) - from _Tools\Library\web\kit. Needs kit-core.js.
|
||||
|
||||
Game loop with a fixed simulation step and smooth rendering:
|
||||
const loop = Kit.loop({
|
||||
step: 1000 / 60, // ms per update (fixed: deterministic, replayable)
|
||||
update(dt) { ... }, // dt = step in seconds
|
||||
render(alpha, now) { ... }, // alpha 0..1 between the last two updates (interpolate)
|
||||
});
|
||||
loop.start(); loop.pause(); loop.resume(); loop.paused
|
||||
Pauses itself while the tab is hidden; a long hitch is capped (no spiral of death).
|
||||
|
||||
Fixed-size layout scaled to the window (sharp canvases on hi-DPI screens):
|
||||
Kit.fit(Kit.$('app'), { canvases: [[cv, 960, 540]], onFit(scale) {} })
|
||||
#app is laid out at its natural pixel size and scaled with CSS transform to fill the
|
||||
window; every listed canvas gets a backing store of size * scale * devicePixelRatio
|
||||
and a matching ctx transform, so you always draw in design pixels (960 x 540). */
|
||||
(function (root) {
|
||||
'use strict';
|
||||
const Kit = (root.Kit = root.Kit || {});
|
||||
|
||||
Kit.loop = opt => {
|
||||
const step = opt.step || 1000 / 60, maxFrame = opt.maxFrame || 250;
|
||||
let acc = 0, last = 0, raf = 0, running = false;
|
||||
const api = { paused: false, ticks: 0 };
|
||||
function frame(now) {
|
||||
raf = requestAnimationFrame(frame);
|
||||
let d = now - last; last = now;
|
||||
if (api.paused || document.hidden) { acc = 0; opt.render && opt.render(1, now); return; }
|
||||
if (d > maxFrame) d = maxFrame;
|
||||
acc += d;
|
||||
while (acc >= step) { acc -= step; api.ticks++; opt.update && opt.update(step / 1000); if (api.paused) { acc = 0; break; } }
|
||||
opt.render && opt.render(acc / step, now);
|
||||
}
|
||||
api.start = () => { if (running) return api; running = true; last = performance.now(); raf = requestAnimationFrame(frame); return api; };
|
||||
api.stop = () => { running = false; cancelAnimationFrame(raf); };
|
||||
api.pause = () => { api.paused = true; };
|
||||
api.resume = () => { api.paused = false; acc = 0; last = performance.now(); };
|
||||
return api;
|
||||
};
|
||||
|
||||
Kit.setRes = (cv, w, h, k) => {
|
||||
cv.width = Math.round(w * k);
|
||||
cv.height = Math.round(h * k);
|
||||
cv.style.width = w + 'px';
|
||||
cv.style.height = h + 'px';
|
||||
const c = cv.getContext('2d');
|
||||
c.setTransform(k, 0, 0, k, 0, 0);
|
||||
return c;
|
||||
};
|
||||
|
||||
Kit.fit = (app, opt = {}) => {
|
||||
const margin = opt.margin == null ? 0.96 : opt.margin, min = opt.min || 0.3, max = opt.max || 4;
|
||||
const canvases = opt.canvases || [];
|
||||
app.style.transformOrigin = 'center center';
|
||||
function fit() {
|
||||
app.style.transform = 'none';
|
||||
const w = app.offsetWidth, h = app.offsetHeight;
|
||||
const sc = Kit.clamp(Math.min(innerWidth * margin / w, innerHeight * margin / h), min, max);
|
||||
app.style.transform = `scale(${sc})`;
|
||||
const k = sc * (root.devicePixelRatio || 1);
|
||||
for (const [cv, cw, ch] of canvases) Kit.setRes(cv, cw, ch, k);
|
||||
opt.onFit && opt.onFit(sc);
|
||||
}
|
||||
addEventListener('resize', fit);
|
||||
if (document.fonts) document.fonts.ready.then(fit);
|
||||
fit();
|
||||
return fit;
|
||||
};
|
||||
|
||||
// Screen position (mouse/touch event) -> design pixels of a canvas laid out by Kit.fit.
|
||||
Kit.toCanvas = (cv, e, w, h) => {
|
||||
const r = cv.getBoundingClientRect();
|
||||
return { x: (e.clientX - r.left) * (w / r.width), y: (e.clientY - r.top) * (h / r.height) };
|
||||
};
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
64
Library/web/kit/kit-scores.js
Normal file
64
Library/web/kit/kit-scores.js
Normal file
@@ -0,0 +1,64 @@
|
||||
/* Kit scores (v1) - online highscores via Firebase Realtime Database REST (no SDK, no login).
|
||||
From _Tools\Library\web\kit. Rules to install: template docs/firebase/database.rules.json.
|
||||
|
||||
const scores = Kit.scores({ url: 'https://<project>-default-rtdb.europe-west1.firebasedatabase.app' });
|
||||
if (scores.enabled) {
|
||||
const rows = await scores.top(10); // [{ key, name, score, level, time }] best first
|
||||
const key = await scores.submit({ name, score, level }); // key of the new entry or null
|
||||
}
|
||||
Kit.cleanName(s) -> trimmed, max 20 chars, no control chars / angle brackets
|
||||
Kit.badName(s) -> true for slurs/insults (also l33t spelling); block on entry, hide in lists
|
||||
|
||||
Without a url (or with the placeholder) scores.enabled is false and both calls resolve to
|
||||
[] / null - the game runs offline. The rules only check format and range: anyone can post a
|
||||
fake score by hand. Real protection needs a server check (Cloud Function). */
|
||||
(function (root) {
|
||||
'use strict';
|
||||
const Kit = (root.Kit = root.Kit || {});
|
||||
|
||||
const BAD_WORDS = ['nigg', 'niga', 'neger', 'negro', 'kike', 'fag', 'cunt', 'fuck', 'fick', 'hitler', 'nazi',
|
||||
'siegheil', 'kkk', 'whore', 'hure', 'fotze', 'wichs', 'schwuchtel', 'spast', 'retard', 'slut', 'bitch',
|
||||
'kanake', 'zigeuner', 'judensau'];
|
||||
Kit.cleanName = s => String(s || '').replace(/[\u0000-\u001f<>]/g, '').trim().slice(0, 20);
|
||||
Kit.badName = s => {
|
||||
const norm = String(s || '').toLowerCase()
|
||||
.replace(/[1!|]/g, 'i').replace(/3/g, 'e').replace(/0/g, 'o').replace(/[4@]/g, 'a')
|
||||
.replace(/[5$]/g, 's').replace(/7/g, 't').replace(/ph/g, 'f')
|
||||
.replace(/[^a-zäöüß]/g, '');
|
||||
return BAD_WORDS.some(w => norm.includes(w));
|
||||
};
|
||||
|
||||
Kit.scores = (opt = {}) => {
|
||||
const url = (opt.url || '').replace(/\/+$/, '');
|
||||
const path = opt.path || 'highscores';
|
||||
const enabled = /^https:\/\/.+firebase(io|database)\.(com|app)$/.test(url);
|
||||
return {
|
||||
enabled,
|
||||
async top(n = 10) {
|
||||
if (!enabled) return [];
|
||||
// fetch spare rows: filtered names must not leave the list short
|
||||
const q = new URLSearchParams({ orderBy: '"score"', limitToLast: String(n + 15) });
|
||||
const res = await fetch(`${url}/${path}.json?${q}`, { cache: 'no-store' });
|
||||
if (!res.ok) throw new Error('scores ' + res.status);
|
||||
const data = (await res.json()) || {};
|
||||
return Object.entries(data)
|
||||
.map(([key, v]) => Object.assign({ key }, v))
|
||||
.filter(v => typeof v.name === 'string' && typeof v.score === 'number' && !Kit.badName(v.name))
|
||||
.sort((a, b) => b.score - a.score || (a.time || 0) - (b.time || 0))
|
||||
.slice(0, n);
|
||||
},
|
||||
async submit({ name, score, level = 1 }) {
|
||||
name = Kit.cleanName(name);
|
||||
if (!enabled || !name || !(score > 0) || Kit.badName(name)) return null;
|
||||
try {
|
||||
const res = await fetch(`${url}/${path}.json`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name, score: Math.floor(score), level: Math.floor(level), time: { '.sv': 'timestamp' } }),
|
||||
});
|
||||
return res.ok ? (await res.json()).name : null;
|
||||
} catch (e) { return null; }
|
||||
},
|
||||
};
|
||||
};
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
7
Library/web/template/.gitignore
vendored
Normal file
7
Library/web/template/.gitignore
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
release/
|
||||
launcher/bin/
|
||||
launcher/obj/
|
||||
sprite-generator/output/
|
||||
sprite-generator/__pycache__/
|
||||
node_modules/
|
||||
*.log
|
||||
28
Library/web/template/CLAUDE.md
Normal file
28
Library/web/template/CLAUDE.md
Normal file
@@ -0,0 +1,28 @@
|
||||
# {{NAME}}
|
||||
|
||||
HTML-Canvas-Spiel ohne Build-Schritt, angelegt aus `D:\Oculusquest\Projekt\_Tools\Library` (Vorlage `webgame`).
|
||||
Aufbau und Befehle: `README.md`.
|
||||
|
||||
## Spielkonzept
|
||||
|
||||
<!-- KONZEPT: wird beim Anlegen (Skill neues-projekt) ausgefüllt, danach aktuell halten -->
|
||||
|
||||
## Arbeitsweise
|
||||
|
||||
- Antworten auf Deutsch, knapp. Code und Kommentare auf Englisch, Dokumentation für Michael auf Deutsch.
|
||||
- **Jeder sichtbare Text** steht in `game/lang.js`, immer **Englisch und Deutsch**; im Code nur `t('key')`,
|
||||
in `index.html` `data-i18n="key"`. Kein fest eingebauter Text in `game.js`.
|
||||
- **Credits bleiben drin:** Menü zeigt „© Jahr Michael Media“ + Discord-Link (`CREDITS` in `game.js`),
|
||||
README ebenso, exe-Eigenschaften (Company/Copyright) in `launcher/Launcher.csproj`.
|
||||
- `game/kit/` ist eine Kopie aus `_Tools\Library\web\kit`. Fehlt dort etwas oder ist ein Fehler drin:
|
||||
**in der Library** ändern, dann `new-project.ps1 -UpdateKit -Path .` – nie nur hier.
|
||||
- Spiel muss per Doppelklick auf `game/index.html` laufen (`file://`): keine ES-Module, kein fetch auf
|
||||
lokale JSON-Dateien (Daten als `.js`, die ein globales Objekt setzen).
|
||||
- Kleine Dateien mit sprechenden Namen, sobald `game.js` über ~1500 Zeilen wächst (z. B. `levels.js`,
|
||||
`render.js`, `ui.js`), alle als `<script src>` in `index.html` (build-web.mjs bettet sie ein).
|
||||
- Reine Spiellogik ohne DOM in eigene Datei (wie `Byte Path\game\engine.js`), damit Node-Tests/Löser sie nutzen können.
|
||||
- Grafik und Sound nur über `sprite-generator/` (ComfyGen, Katalog `_Tools\README.md`), Stilblock aus dem
|
||||
Spielkonzept für alle Prompts. App-Icon = `game/assets/Sprites/icon.png` (`gen adopt --size 512 icon`).
|
||||
Fehlt ein Bild, zeichnet das Spiel eine Ersatzform (`drawSprite` mit Fallback-Farbe) – nie abstürzen.
|
||||
- Git nur lokal (kein Remote). Commit nur, wenn Michael es sagt.
|
||||
- Release prüfen: `.\build.ps1 -Web`, dann `release\{{SLUG}}.html` per Doppelklick testen.
|
||||
50
Library/web/template/README.md
Normal file
50
Library/web/template/README.md
Normal file
@@ -0,0 +1,50 @@
|
||||
# {{NAME}}
|
||||
|
||||
HTML-Spiel (Canvas, kein Build-Schritt). Angelegt am {{DATE}} aus `_Tools\Library` (Vorlage `webgame`).
|
||||
Sprachen: Englisch, Deutsch (im Menü umschaltbar).
|
||||
|
||||
© {{YEAR}} Michael Media · Discord: https://discord.gg/Ej4JPmCZva
|
||||
|
||||
## Spielen / Entwickeln
|
||||
|
||||
`game/index.html` im Browser öffnen (Doppelklick reicht, kein Server). `index.html?play` überspringt das Menü.
|
||||
|
||||
| Taste | Wirkung |
|
||||
|---|---|
|
||||
| Pfeile / WASD, Tippen | bewegen |
|
||||
| P / Esc | Pause |
|
||||
| M | Sound an/aus |
|
||||
| R | neu starten |
|
||||
| F11 | Vollbild |
|
||||
|
||||
## Aufbau
|
||||
|
||||
```
|
||||
game/
|
||||
index.html Seite, HUD, Overlays (Styles inline)
|
||||
game.js das Spiel
|
||||
lang.js alle sichtbaren Texte, Englisch + Deutsch (L.t('key') / data-i18n="key")
|
||||
kit/ Bausteine aus _Tools\Library\web\kit – hier NICHT ändern (siehe unten)
|
||||
assets/ Sprites/ (icon.png = App-Icon), Audio/, Fonts/ – von sprite-generator (ComfyGen adopt)
|
||||
launcher/ Windows-Fenster (WebView2) → {{IDENT}}.exe
|
||||
sprite-generator/ ComfyGen-Projekt: gen generate <name>, gen adopt <name>, gen generate_audio <name>
|
||||
docs/firebase/ Online-Highscores einrichten
|
||||
docs/itchio/ itch.io-Seite
|
||||
build-web.mjs → release/{{SLUG}}.html (alles in einer Datei)
|
||||
build.ps1 → release/{{IDENT}}.exe + {{SLUG}}.html + {{SLUG}}-web.zip
|
||||
```
|
||||
|
||||
## Release
|
||||
|
||||
```powershell
|
||||
.\build.ps1 # exe + html + zip
|
||||
.\build.ps1 -Web # nur html + zip
|
||||
```
|
||||
|
||||
## Kit aktualisieren
|
||||
|
||||
Verbesserungen an `game/kit/*` gehören in `D:\Oculusquest\Projekt\_Tools\Library\web\kit`. Danach hier:
|
||||
|
||||
```powershell
|
||||
D:\Oculusquest\Projekt\_Tools\Library\new-project.ps1 -UpdateKit -Path .
|
||||
```
|
||||
54
Library/web/template/build-web.mjs
Normal file
54
Library/web/template/build-web.mjs
Normal file
@@ -0,0 +1,54 @@
|
||||
// Builds release/{{SLUG}}.html: the whole game in ONE file. Local <script src> and
|
||||
// <link rel="stylesheet"> are inlined, every file under game/assets is embedded as a data: URI
|
||||
// (window.KIT_ASSETS, read by Kit.asset). Works by double-click (file://) and on any host
|
||||
// (itch.io, webspace). From _Tools\Library\web\template.
|
||||
// node build-web.mjs
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const root = path.dirname(fileURLToPath(import.meta.url));
|
||||
const game = path.join(root, 'game');
|
||||
const MIME = {
|
||||
'.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.gif': 'image/gif',
|
||||
'.svg': 'image/svg+xml', '.mp3': 'audio/mpeg', '.ogg': 'audio/ogg', '.wav': 'audio/wav',
|
||||
'.ttf': 'font/ttf', '.otf': 'font/otf', '.woff2': 'font/woff2', '.json': 'application/json',
|
||||
};
|
||||
|
||||
function walk(dir) {
|
||||
if (!fs.existsSync(dir)) return [];
|
||||
return fs.readdirSync(dir, { withFileTypes: true }).flatMap(e =>
|
||||
e.isDirectory() ? walk(path.join(dir, e.name)) : [path.join(dir, e.name)]);
|
||||
}
|
||||
|
||||
const assets = {};
|
||||
let bytes = 0;
|
||||
for (const file of walk(path.join(game, 'assets'))) {
|
||||
const mime = MIME[path.extname(file).toLowerCase()];
|
||||
if (!mime) continue;
|
||||
const rel = path.relative(game, file).split(path.sep).join('/');
|
||||
const buf = fs.readFileSync(file);
|
||||
bytes += buf.length;
|
||||
assets[rel] = `data:${mime};base64,${buf.toString('base64')}`;
|
||||
}
|
||||
|
||||
let html = fs.readFileSync(path.join(game, 'index.html'), 'utf8');
|
||||
const local = p => !/^(https?:)?\/\//.test(p) && !p.startsWith('data:');
|
||||
// "</script" inside an inlined file would end the tag early
|
||||
const safe = s => s.replace(/<\/script/gi, '<\\/script');
|
||||
|
||||
html = html.replace(/<link\s+rel="stylesheet"\s+href="([^"]+)"\s*\/?>/g, (m, p) =>
|
||||
local(p) ? `<style>\n${fs.readFileSync(path.join(game, p), 'utf8')}\n</style>` : m);
|
||||
html = html.replace(/<script\s+src="([^"]+)"\s*><\/script>/g, (m, p) =>
|
||||
local(p) ? `<script>\n${safe(fs.readFileSync(path.join(game, p), 'utf8'))}\n</script>` : m);
|
||||
// static references in CSS / HTML attributes
|
||||
html = html.replace(/url\((['"]?)(assets\/[^'")]+)\1\)/g, (m, q, p) => (assets[p] ? `url('${assets[p]}')` : m));
|
||||
html = html.replace(/(src|href)="(assets\/[^"]+)"/g, (m, a, p) => (assets[p] ? `${a}="${assets[p]}"` : m));
|
||||
// everything the scripts load at runtime: must come before the first other <script>
|
||||
html = html.replace('<script>', () => `<script>window.KIT_ASSETS = ${JSON.stringify(assets)};</script>\n<script>`);
|
||||
|
||||
const out = path.join(root, 'release', '{{SLUG}}.html');
|
||||
fs.mkdirSync(path.dirname(out), { recursive: true });
|
||||
fs.writeFileSync(out, html);
|
||||
const mb = n => (n / 1024 / 1024).toFixed(1);
|
||||
console.log(`Fertig: ${out} (${mb(fs.statSync(out).size)} MB, ${Object.keys(assets).length} Assets, ${mb(bytes)} MB roh)`);
|
||||
41
Library/web/template/build.ps1
Normal file
41
Library/web/template/build.ps1
Normal file
@@ -0,0 +1,41 @@
|
||||
# Builds everything into release\:
|
||||
# {{IDENT}}.exe one self-contained file (.NET runtime + game embedded, WebView2 window)
|
||||
# {{SLUG}}.html whole game in one HTML file
|
||||
# {{SLUG}}-web.zip upload package for itch.io & co (the page as index.html)
|
||||
# Needs .NET 8+ SDK and Node. The PC running the exe needs the Edge WebView2 Runtime (Win 10/11 has it).
|
||||
# .\build.ps1 all .\build.ps1 -Web only HTML + zip .\build.ps1 -Exe only exe
|
||||
param([switch]$Web, [switch]$Exe)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$root = $PSScriptRoot
|
||||
$out = Join-Path $root 'release'
|
||||
if (-not $Web -and -not $Exe) { $Web = $true; $Exe = $true }
|
||||
New-Item -ItemType Directory -Force $out | Out-Null
|
||||
|
||||
if ($Exe) {
|
||||
# app icon from game\assets\Sprites\icon.png (once; delete launcher\app.ico to redo)
|
||||
$ico = Join-Path $root 'launcher\app.ico'
|
||||
$png = Join-Path $root 'game\assets\Sprites\icon.png'
|
||||
if (-not (Test-Path $ico) -and (Test-Path $png)) {
|
||||
py -3.12 -c "import sys; from PIL import Image; Image.open(sys.argv[1]).convert('RGBA').save(sys.argv[2], sizes=[(16,16),(24,24),(32,32),(48,48),(64,64),(128,128),(256,256)])" $png $ico
|
||||
}
|
||||
$pub = Join-Path $env:TEMP '{{SLUG}}-publish'
|
||||
Remove-Item $pub -Recurse -Force -ErrorAction SilentlyContinue
|
||||
dotnet publish (Join-Path $root 'launcher\Launcher.csproj') -c Release -o $pub --nologo
|
||||
if ($LASTEXITCODE -ne 0) { throw "dotnet publish failed ($LASTEXITCODE)" }
|
||||
Copy-Item (Join-Path $pub '{{IDENT}}.exe') $out -Force
|
||||
Remove-Item $pub -Recurse -Force
|
||||
$exeFile = Get-Item (Join-Path $out '{{IDENT}}.exe')
|
||||
"Fertig: $($exeFile.FullName) ($([math]::Round($exeFile.Length / 1MB, 1)) MB)"
|
||||
}
|
||||
|
||||
if ($Web) {
|
||||
node (Join-Path $root 'build-web.mjs')
|
||||
if ($LASTEXITCODE -ne 0) { throw "web build failed ($LASTEXITCODE)" }
|
||||
$tmp = Join-Path $env:TEMP '{{SLUG}}-web'
|
||||
Remove-Item $tmp -Recurse -Force -ErrorAction SilentlyContinue
|
||||
New-Item -ItemType Directory $tmp | Out-Null
|
||||
Copy-Item (Join-Path $out '{{SLUG}}.html') (Join-Path $tmp 'index.html')
|
||||
Compress-Archive -Path (Join-Path $tmp 'index.html') -DestinationPath (Join-Path $out '{{SLUG}}-web.zip') -Force
|
||||
Remove-Item $tmp -Recurse -Force
|
||||
"Fertig: $(Join-Path $out '{{SLUG}}-web.zip')"
|
||||
}
|
||||
26
Library/web/template/docs/firebase/README.md
Normal file
26
Library/web/template/docs/firebase/README.md
Normal file
@@ -0,0 +1,26 @@
|
||||
# Online-Highscores (Firebase Realtime Database)
|
||||
|
||||
Das Spiel spricht die Datenbank über die REST-API an (`game/kit/kit-scores.js`), ohne SDK und ohne Login.
|
||||
Solange `DB_URL` in `game/game.js` leer ist, läuft alles offline (keine Namenseingabe, keine Liste).
|
||||
|
||||
## Einrichten (einmal, ~5 Minuten)
|
||||
|
||||
1. [Firebase-Konsole](https://console.firebase.google.com/) → **Projekt hinzufügen** (Name z. B. `{{SLUG}}`, Analytics aus).
|
||||
2. **Build → Realtime Database → Datenbank erstellen** → Standort **europe-west1** → „Im gesperrten Modus starten“.
|
||||
3. Tab **Regeln**: alles durch den Inhalt von `database.rules.json` ersetzen → **Veröffentlichen**.
|
||||
4. Die URL oben im Tab **Daten** (`https://<projekt>-default-rtdb.europe-west1.firebasedatabase.app`)
|
||||
in `game/game.js` bei `DB_URL` eintragen.
|
||||
|
||||
## Was die Regeln erlauben
|
||||
|
||||
- Lesen: nur `highscores` (sortiert/begrenzt nach `score`).
|
||||
- Schreiben: nur **neue** Einträge unter `highscores` – bestehende können nicht geändert/gelöscht werden.
|
||||
- Jeder Eintrag hat genau `name` (1–20 Zeichen), `score` (1–10 000 000), `level` (1–999), `time` (Server-Zeit).
|
||||
|
||||
## Grenzen
|
||||
|
||||
Punkte lassen sich per Hand-Request fälschen; die Regeln prüfen nur Format und Bereich. Echter Schutz
|
||||
bräuchte eine Server-Prüfung (Cloud Function). Einträge löschen: Konsole → **Daten** → `highscores` →
|
||||
Eintrag → ⋮ / Papierkorb. Schimpfwort-Namen blockt `Kit.badName` bei der Eingabe und blendet sie in der Liste aus.
|
||||
|
||||
Referenz im Einsatz: `D:\Oculusquest\Projekt\Pipefix\docs\firebase\`.
|
||||
19
Library/web/template/docs/firebase/database.rules.json
Normal file
19
Library/web/template/docs/firebase/database.rules.json
Normal file
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"rules": {
|
||||
".read": false,
|
||||
".write": false,
|
||||
"highscores": {
|
||||
".read": true,
|
||||
".indexOn": ["score"],
|
||||
"$entry": {
|
||||
".write": "!data.exists()",
|
||||
".validate": "newData.hasChildren(['name', 'score', 'level', 'time'])",
|
||||
"name": { ".validate": "newData.isString() && newData.val().length >= 1 && newData.val().length <= 20" },
|
||||
"score": { ".validate": "newData.isNumber() && newData.val() > 0 && newData.val() <= 10000000" },
|
||||
"level": { ".validate": "newData.isNumber() && newData.val() >= 1 && newData.val() <= 999" },
|
||||
"time": { ".validate": "newData.val() == now" },
|
||||
"$other": { ".validate": false }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
38
Library/web/template/docs/itchio/README.md
Normal file
38
Library/web/template/docs/itchio/README.md
Normal file
@@ -0,0 +1,38 @@
|
||||
# itch.io-Seite einrichten
|
||||
|
||||
Bilder erzeugen (Cover, Banner, Hintergrund) aus einem Hintergrundbild und dem Titel:
|
||||
|
||||
```
|
||||
py -3.12 D:\Oculusquest\Projekt\_Tools\Itch\itch_images.py --title "{{NAME}}" --tagline "…" --backdrop <bild.png> --out docs\itchio
|
||||
```
|
||||
|
||||
Upload-Dateien: `.\build.ps1` → `release\{{SLUG}}-web.zip` (Browser) und `release\{{IDENT}}.exe` (Windows).
|
||||
|
||||
## Felder unter „Edit game“
|
||||
|
||||
| Feld | Eintrag |
|
||||
|---|---|
|
||||
| Title | `{{NAME}}` |
|
||||
| Project URL | `{{SLUG}}` |
|
||||
| Short description or tagline | _ein Satz_ |
|
||||
| Classification | Games |
|
||||
| Kind of project | **HTML** |
|
||||
| Release status | Released |
|
||||
| Pricing | z. B. „No payments“ oder „Donation“ |
|
||||
| Uploads | `release/{{SLUG}}-web.zip` → „This file will be played in the browser“ · optional `release/{{IDENT}}.exe` → Windows |
|
||||
| Viewport dimensions | `1120 × 720` (oder passend zum Seitenverhältnis von `#app`) |
|
||||
| Frame options | ✅ Fullscreen button · Mobile friendly nur wenn Touch getestet |
|
||||
| Description | Inhalt von `description.html` (im Browser öffnen, Strg+A, kopieren, einfügen) |
|
||||
| Genre / Tags | passend, max. 10 Tags |
|
||||
| AI generation disclosure | **Yes** – Grafik/Sound mit KI erzeugt (ComfyUI, Flux, Stable Audio) |
|
||||
| Input methods | Keyboard, Mouse, Touchscreen (falls getestet) |
|
||||
| Cover image | `cover.png` (630×500) |
|
||||
| Screenshots | 3–5 Stück, 1920×1080 oder Spielgröße |
|
||||
|
||||
## Seiten-Design („Edit theme“)
|
||||
|
||||
- Banner: `banner_960x256.png` (oder `banner_1920x512.png`)
|
||||
- Background: `background_1920x1200.jpg`, Repeat aus, oben mittig
|
||||
- Farben passend zum Spiel (`:root` in `game/index.html`)
|
||||
|
||||
Referenz im Einsatz: `D:\Oculusquest\Projekt\Pipefix\docs\itchio\`.
|
||||
28
Library/web/template/docs/itchio/description.html
Normal file
28
Library/web/template/docs/itchio/description.html
Normal file
@@ -0,0 +1,28 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head><meta charset="utf-8"><title>{{NAME}} - itch.io description</title></head>
|
||||
<body style="max-width:720px;margin:40px auto;font:16px/1.5 system-ui,sans-serif">
|
||||
<!-- Open in a browser, Ctrl+A, copy, paste into the itch.io "Description" field.
|
||||
Placeholder text - the itchiocreater skill writes the real one. -->
|
||||
<h2>🎮 {{NAME}}</h2>
|
||||
<p><strong>One sentence that sells the game.</strong> Two or three more that say what you do and why it is fun.</p>
|
||||
|
||||
<h3>✨ Features</h3>
|
||||
<ul>
|
||||
<li>⭐ <strong>Feature one</strong> – …</li>
|
||||
<li>⭐ <strong>Feature two</strong> – …</li>
|
||||
<li>🏆 <strong>Online highscores</strong></li>
|
||||
</ul>
|
||||
|
||||
<h3>🕹️ Controls</h3>
|
||||
<p>⌨️ <strong>Arrows / WASD</strong> move · <strong>P / Esc</strong> pause · <strong>M</strong> sound · <strong>F11</strong> fullscreen</p>
|
||||
|
||||
<h3>🌍 Languages</h3>
|
||||
<p>English, Deutsch (switch in the menu).</p>
|
||||
|
||||
<h3>💬 Community</h3>
|
||||
<p>Feedback and ideas are welcome on <a href="https://discord.gg/Ej4JPmCZva">Discord</a>.</p>
|
||||
|
||||
<p><em>© {{YEAR}} Michael Media. Graphics, music and sound were created with the help of AI tools (ComfyUI).</em></p>
|
||||
</body>
|
||||
</html>
|
||||
228
Library/web/template/game/game.js
Normal file
228
Library/web/template/game/game.js
Normal file
@@ -0,0 +1,228 @@
|
||||
/* {{NAME}} - game. Demo content from the Library template: collect orbs, dodge the red ones,
|
||||
60 seconds. Replace the "game" section; keep the frame (menus, save, audio, scores, loop,
|
||||
texts via L.t() from lang.js, credits line in the menu). */
|
||||
(function () {
|
||||
'use strict';
|
||||
const $ = Kit.$;
|
||||
const W = 960, H = 540; // design size of the canvas
|
||||
const ID = '{{SLUG}}'; // localStorage prefix
|
||||
|
||||
// Paste the Firebase Realtime Database URL here to switch online highscores on
|
||||
// (docs/firebase/README.md). Empty = offline.
|
||||
const DB_URL = '';
|
||||
|
||||
// Credits (standard for every game): shown in the menu, links open in the normal browser
|
||||
const DISCORD = 'https://discord.gg/Ej4JPmCZva';
|
||||
const CREDITS = `© {{YEAR}} Michael Media · <a href="${DISCORD}" target="_blank" rel="noopener">Discord</a>`;
|
||||
|
||||
// ---------------------------------------------------------------- services
|
||||
const L = Kit.i18n(window.LANG, { prefix: ID }); // texts: lang.js, English + German
|
||||
const t = L.t;
|
||||
const store = Kit.store(ID);
|
||||
const slot = Kit.saveSlot(ID + '.save', () => ({ best: 0, games: 0, name: '', tutorialSeen: false }));
|
||||
let save = slot.load();
|
||||
const audio = Kit.createAudio({
|
||||
prefix: ID,
|
||||
files: ['sfx_click', 'sfx_pickup', 'sfx_hit', 'sfx_win', 'music_game'], // assets/Audio/*.mp3
|
||||
throttle: { sfx_pickup: 50 },
|
||||
});
|
||||
const scores = Kit.scores({ url: DB_URL });
|
||||
const IMG = Kit.images(['player', 'orb', 'bad']); // assets/Sprites/*.png
|
||||
const fx = Kit.fx();
|
||||
const input = Kit.input({
|
||||
keys: {
|
||||
ArrowUp: 'up', w: 'up', ArrowDown: 'down', s: 'down', ArrowLeft: 'left', a: 'left', ArrowRight: 'right', d: 'right',
|
||||
p: 'pause', Escape: 'pause', m: 'mute', Enter: 'ok', ' ': 'ok', r: 'restart',
|
||||
},
|
||||
onPress(a) {
|
||||
if (a === 'pause') togglePause();
|
||||
else if (a === 'mute') toggleMute();
|
||||
else if (a === 'restart' && mode !== 'menu') newGame();
|
||||
else if (a === 'ok') { const b = overlay.querySelector('button.primary'); if (b && !b.disabled) b.click(); }
|
||||
},
|
||||
});
|
||||
|
||||
// sound with synth fallback while no ComfyGen clips exist
|
||||
const SFX = {
|
||||
click() { audio.sfx('sfx_click'); },
|
||||
pickup() { audio.sfx('sfx_pickup'); audio.tone(880, 0.06, 'square', 0.12); audio.tone(1320, 0.08, 'square', 0.1, 0, 0.05); },
|
||||
hit() { audio.sfx('sfx_hit'); audio.noise(0.25, 0.3, 900); },
|
||||
over() { audio.sfx('sfx_win'); audio.arp([523, 659, 784, 1046], 0.09); },
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------- view
|
||||
const cv = $('cv');
|
||||
let ctx = cv.getContext('2d');
|
||||
Kit.fit($('app'), { canvases: [[cv, W, H]], onFit() { ctx = cv.getContext('2d'); } });
|
||||
Kit.host.dragArea(document.body);
|
||||
|
||||
// ---------------------------------------------------------------- game state
|
||||
let mode = 'menu'; // menu | play | pause | over
|
||||
let g = null;
|
||||
function newGame() {
|
||||
g = { x: W / 2, y: H / 2, r: 18, vx: 0, vy: 0, score: 0, time: 60, orbs: [], spawn: 0, flash: 0, target: null };
|
||||
fx.clear();
|
||||
mode = 'play';
|
||||
hideOverlay();
|
||||
loop.resume();
|
||||
audio.music('music_game');
|
||||
hud();
|
||||
}
|
||||
|
||||
function spawnOrb() {
|
||||
const bad = Math.random() < Math.min(0.45, 0.15 + (60 - g.time) / 120);
|
||||
g.orbs.push({ x: 40 + Math.random() * (W - 80), y: 40 + Math.random() * (H - 80), r: bad ? 16 : 12, bad, t: 0 });
|
||||
}
|
||||
|
||||
function update(dt) {
|
||||
fx.update(dt);
|
||||
if (mode !== 'play') return;
|
||||
// move: keys, or pointer target on touch / mouse
|
||||
const ax = (input.down('right') ? 1 : 0) - (input.down('left') ? 1 : 0);
|
||||
const ay = (input.down('down') ? 1 : 0) - (input.down('up') ? 1 : 0);
|
||||
const SPEED = 340;
|
||||
if (ax || ay) { g.target = null; const l = Math.hypot(ax, ay); g.vx = ax / l * SPEED; g.vy = ay / l * SPEED; }
|
||||
else if (g.target) {
|
||||
const dx = g.target.x - g.x, dy = g.target.y - g.y, l = Math.hypot(dx, dy);
|
||||
if (l < 6) { g.target = null; g.vx = g.vy = 0; } else { g.vx = dx / l * SPEED; g.vy = dy / l * SPEED; }
|
||||
} else { g.vx *= 0.8; g.vy *= 0.8; }
|
||||
g.x = Kit.clamp(g.x + g.vx * dt, g.r, W - g.r);
|
||||
g.y = Kit.clamp(g.y + g.vy * dt, g.r, H - g.r);
|
||||
|
||||
g.spawn -= dt;
|
||||
if (g.spawn <= 0) { spawnOrb(); g.spawn = 0.55; }
|
||||
for (let i = g.orbs.length - 1; i >= 0; i--) {
|
||||
const o = g.orbs[i];
|
||||
o.t += dt;
|
||||
if (o.t > 6) { g.orbs.splice(i, 1); continue; }
|
||||
if (Math.hypot(o.x - g.x, o.y - g.y) < o.r + g.r) {
|
||||
g.orbs.splice(i, 1);
|
||||
if (o.bad) { g.score = Math.max(0, g.score - 25); g.flash = 0.25; fx.shake(10); fx.burst(o.x, o.y, '#ff5a5a', 20); fx.float(o.x, o.y, '-25', '#ff8a8a'); SFX.hit(); }
|
||||
else { g.score += 10; fx.burst(o.x, o.y, '#4fd8ff', 12); fx.float(o.x, o.y, '+10', '#bff3ff'); SFX.pickup(); }
|
||||
}
|
||||
}
|
||||
g.flash = Math.max(0, g.flash - dt);
|
||||
g.time -= dt;
|
||||
if (g.time <= 0) { g.time = 0; gameOver(); }
|
||||
hud();
|
||||
}
|
||||
|
||||
// pointer: move towards the tap / click
|
||||
cv.addEventListener('pointerdown', e => {
|
||||
if (mode !== 'play') return;
|
||||
g.target = Kit.toCanvas(cv, e, W, H);
|
||||
});
|
||||
cv.addEventListener('pointermove', e => { if (mode === 'play' && e.buttons) g.target = Kit.toCanvas(cv, e, W, H); });
|
||||
|
||||
// ---------------------------------------------------------------- drawing
|
||||
function drawSprite(name, x, y, size, fallbackColor) {
|
||||
const im = IMG[name];
|
||||
if (im && im.ok) ctx.drawImage(im, x - size / 2, y - size / 2, size, size);
|
||||
else { ctx.fillStyle = fallbackColor; ctx.beginPath(); ctx.arc(x, y, size / 2, 0, Math.PI * 2); ctx.fill(); }
|
||||
}
|
||||
|
||||
function render(alpha, now) {
|
||||
ctx.fillStyle = '#0a1020';
|
||||
ctx.fillRect(0, 0, W, H);
|
||||
// grid backdrop
|
||||
ctx.strokeStyle = '#ffffff0d'; ctx.lineWidth = 1;
|
||||
for (let x = 0; x <= W; x += 40) { ctx.beginPath(); ctx.moveTo(x + 0.5, 0); ctx.lineTo(x + 0.5, H); ctx.stroke(); }
|
||||
for (let y = 0; y <= H; y += 40) { ctx.beginPath(); ctx.moveTo(0, y + 0.5); ctx.lineTo(W, y + 0.5); ctx.stroke(); }
|
||||
if (!g) return;
|
||||
fx.apply(ctx);
|
||||
for (const o of g.orbs) {
|
||||
const pulse = 1 + Math.sin(now / 160 + o.x) * 0.08, fade = o.t > 5 ? 6 - o.t : 1;
|
||||
ctx.globalAlpha = Math.max(0, fade);
|
||||
drawSprite(o.bad ? 'bad' : 'orb', o.x, o.y, o.r * 2 * pulse, o.bad ? '#ff4a4a' : '#4fd8ff');
|
||||
}
|
||||
ctx.globalAlpha = 1;
|
||||
drawSprite('player', g.x, g.y, g.r * 2, '#ffd83a');
|
||||
fx.draw(ctx);
|
||||
ctx.restore();
|
||||
if (g.flash > 0) { ctx.fillStyle = `rgba(255,60,60,${g.flash})`; ctx.fillRect(0, 0, W, H); }
|
||||
}
|
||||
|
||||
const loop = Kit.loop({ step: 1000 / 60, update, render }).start();
|
||||
|
||||
// ---------------------------------------------------------------- HUD + menus
|
||||
function hud() {
|
||||
$('hScore').textContent = Kit.fmt(g ? g.score : 0);
|
||||
$('hTime').textContent = g ? Math.ceil(g.time) : 60;
|
||||
$('hBest').textContent = Kit.fmt(save.best);
|
||||
$('bMute').textContent = audio.muted ? t('sound_off') : t('sound_on');
|
||||
}
|
||||
const overlay = $('overlay');
|
||||
function card(html) { overlay.innerHTML = `<div class="card">${html}</div>`; overlay.classList.remove('hide'); }
|
||||
function hideOverlay() { overlay.classList.add('hide'); overlay.innerHTML = ''; }
|
||||
const esc = s => String(s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
||||
|
||||
function boardHtml() { return scores.enabled ? `<ol class="board" id="board"><li class="muted">${t('loading')}</li></ol>` : ''; }
|
||||
async function fillBoard(myKey) {
|
||||
const el = $('board');
|
||||
if (!el) return;
|
||||
try {
|
||||
const rows = await scores.top(10);
|
||||
el.innerHTML = rows.length
|
||||
? rows.map((r, i) => `<li class="${r.key === myKey ? 'me' : ''}"><span>${i + 1}.</span><span class="nm">${esc(r.name)}</span><span>${Kit.fmt(r.score)}</span></li>`).join('')
|
||||
: `<li class="muted">${t('no_scores')}</li>`;
|
||||
} catch (e) { el.innerHTML = `<li class="muted">${t('scores_offline')}</li>`; }
|
||||
}
|
||||
|
||||
function showMenu() {
|
||||
mode = 'menu';
|
||||
const nameField = scores.enabled ? `<div><input id="name" maxlength="20" placeholder="${esc(t('name_placeholder'))}" value="${esc(save.name)}"></div>` : '';
|
||||
card(`<h1>{{NAME}}</h1><p>${t('menu_text')}</p>
|
||||
${nameField}<button class="primary" id="bStart">${t('play')}</button>
|
||||
<div class="row"><button id="bLang" title="English / Deutsch">🌐 ${t('lang_self')}</button></div>
|
||||
${boardHtml()}<p class="credits">${CREDITS}</p>`);
|
||||
$('bLang').onclick = () => { SFX.click(); L.next(); };
|
||||
const name = $('name'), start = $('bStart');
|
||||
if (name) {
|
||||
const check = () => { const n = Kit.cleanName(name.value); start.disabled = !n || Kit.badName(n); };
|
||||
name.addEventListener('input', check); check();
|
||||
name.addEventListener('keydown', e => { if (e.key === 'Enter' && !start.disabled) start.click(); });
|
||||
setTimeout(() => name.focus(), 50);
|
||||
}
|
||||
start.onclick = () => {
|
||||
if (name) { save.name = Kit.cleanName(name.value); slot.save(save); }
|
||||
SFX.click(); newGame();
|
||||
};
|
||||
fillBoard();
|
||||
}
|
||||
|
||||
async function gameOver() {
|
||||
mode = 'over';
|
||||
SFX.over();
|
||||
const newBest = g.score > save.best;
|
||||
save.best = Math.max(save.best, g.score);
|
||||
save.games++;
|
||||
slot.save(save);
|
||||
hud();
|
||||
card(`<h1>${t('time_up')}</h1><p>${t('score_line', { score: Kit.fmt(g.score) })}${newBest ? t('new_best') : ''}</p>
|
||||
<button class="primary" id="bAgain">${t('again')}</button> <button id="bMenu">${t('menu')}</button>${boardHtml()}`);
|
||||
$('bAgain').onclick = () => { SFX.click(); newGame(); };
|
||||
$('bMenu').onclick = () => { SFX.click(); showMenu(); };
|
||||
const key = await scores.submit({ name: save.name, score: g.score, level: 1 });
|
||||
fillBoard(key);
|
||||
}
|
||||
|
||||
function togglePause() {
|
||||
if (mode === 'play') {
|
||||
mode = 'pause'; loop.pause();
|
||||
card(`<h1>${t('pause')}</h1><button class="primary" id="bGo">${t('continue')}</button> <button id="bQuit">${t('menu')}</button>`);
|
||||
$('bGo').onclick = togglePause;
|
||||
$('bQuit').onclick = showMenu;
|
||||
} else if (mode === 'pause') { mode = 'play'; hideOverlay(); loop.resume(); }
|
||||
}
|
||||
function toggleMute() { audio.toggleMute(); hud(); }
|
||||
$('bMute').onclick = toggleMute;
|
||||
$('bPause').onclick = togglePause;
|
||||
addEventListener('blur', () => { if (mode === 'play') togglePause(); });
|
||||
// language switch: static texts update themselves (data-i18n), menus are drawn again
|
||||
L.onChange(() => { hud(); if (mode === 'menu') showMenu(); });
|
||||
|
||||
if (slot.failed()) console.warn('save failed');
|
||||
hud();
|
||||
// dev: index.html?play skips the menu
|
||||
if (new URLSearchParams(location.search).has('play')) newGame(); else showMenu();
|
||||
})();
|
||||
103
Library/web/template/game/index.html
Normal file
103
Library/web/template/game/index.html
Normal file
@@ -0,0 +1,103 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
<title>{{NAME}}</title>
|
||||
<link rel="icon" href="assets/Sprites/icon.png">
|
||||
<style>
|
||||
:root {
|
||||
--bg: #0b0f1a; --panel: #141b2d; --line: #2a3658; --text: #e3e9ff; --dim: #8b97bd;
|
||||
--accent: #4fd8ff; --good: #6dff9e; --warn: #ff6b6b;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
html, body { margin: 0; height: 100%; overflow: hidden; background: var(--bg); color: var(--text);
|
||||
font: 16px/1.4 "Segoe UI", system-ui, sans-serif; user-select: none; -webkit-user-select: none;
|
||||
touch-action: none; }
|
||||
body { display: flex; align-items: center; justify-content: center;
|
||||
background: radial-gradient(circle at 50% 30%, #18234a 0%, var(--bg) 70%); }
|
||||
|
||||
/* fixed design size, scaled to the window by Kit.fit */
|
||||
#app { position: relative; width: 960px; display: flex; flex-direction: column; gap: 10px; }
|
||||
#hud { display: flex; gap: 10px; align-items: center; }
|
||||
.chip { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 6px 12px; }
|
||||
.chip b { color: var(--accent); font-variant-numeric: tabular-nums; }
|
||||
.grow { flex: 1; }
|
||||
#stage { position: relative; border: 2px solid var(--line); border-radius: 10px; overflow: hidden; background: #000; }
|
||||
canvas { display: block; }
|
||||
|
||||
button { font: inherit; color: var(--text); background: var(--panel); border: 1px solid var(--line);
|
||||
border-radius: 8px; padding: 6px 12px; cursor: pointer; }
|
||||
button:hover { border-color: var(--accent); }
|
||||
button.primary { background: var(--accent); color: #04121a; border-color: var(--accent); font-weight: 700; padding: 10px 26px; }
|
||||
button:disabled { opacity: .45; cursor: default; }
|
||||
|
||||
/* overlays (menus) */
|
||||
#overlay { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center;
|
||||
background: rgba(5, 8, 16, .72); backdrop-filter: blur(3px); }
|
||||
#overlay.hide { display: none; }
|
||||
.card { background: var(--panel); border: 1px solid var(--line); border-radius: 14px; padding: 26px 34px;
|
||||
min-width: 360px; text-align: center; box-shadow: 0 20px 60px #0008; }
|
||||
.card h1 { margin: 0 0 6px; font-size: 40px; letter-spacing: .06em; color: var(--accent); }
|
||||
.card p { color: var(--dim); margin: 6px 0 16px; }
|
||||
.card input { font: inherit; width: 220px; padding: 8px 10px; border-radius: 8px; border: 1px solid var(--line);
|
||||
background: #0b1222; color: var(--text); text-align: center; margin-bottom: 14px; }
|
||||
.board { list-style: none; padding: 0; margin: 16px 0 0; text-align: left; font-variant-numeric: tabular-nums; }
|
||||
.board li { display: flex; gap: 10px; padding: 2px 0; }
|
||||
.board li .nm { flex: 1; } .board li.me { color: var(--good); }
|
||||
.muted { color: var(--dim); font-size: 13px; }
|
||||
.card .row { display: flex; gap: 8px; justify-content: center; margin-top: 14px; }
|
||||
/* credits (standard for every game: © year Michael Media + Discord) */
|
||||
.credits { margin: 18px 0 0; font-size: 12px; color: var(--dim); }
|
||||
.credits a { color: var(--accent); text-decoration: none; }
|
||||
.credits a:hover { text-decoration: underline; }
|
||||
|
||||
/* touch pad: only on touch screens */
|
||||
#pad { position: absolute; left: 18px; bottom: 18px; display: none; grid-template-columns: repeat(3, 64px); gap: 6px; }
|
||||
#pad button { height: 64px; font-size: 22px; opacity: .7; }
|
||||
@media (pointer: coarse) { #pad { display: grid; } }
|
||||
|
||||
/* window buttons: only inside the exe (html.exe set by kit-host.js) */
|
||||
#winctl { position: fixed; top: 8px; right: 8px; display: none; gap: 6px; z-index: 10; }
|
||||
html.exe #winctl { display: flex; }
|
||||
#winctl button { width: 34px; height: 30px; padding: 0; opacity: .75; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="winctl">
|
||||
<button onclick="Kit.host.minimize()" data-i18n-title="win_min">–</button>
|
||||
<button onclick="Kit.host.fullscreen()" data-i18n-title="win_full">▢</button>
|
||||
<button onclick="Kit.host.quit()" data-i18n-title="win_close">✕</button>
|
||||
</div>
|
||||
|
||||
<div id="app">
|
||||
<div id="hud">
|
||||
<div class="chip"><span data-i18n="hud_score">Score</span> <b id="hScore">0</b></div>
|
||||
<div class="chip"><span data-i18n="hud_time">Time</span> <b id="hTime">60</b></div>
|
||||
<div class="chip"><span data-i18n="hud_best">Best</span> <b id="hBest">0</b></div>
|
||||
<div class="grow"></div>
|
||||
<button id="bMute" title="M">Sound</button>
|
||||
<button id="bPause" title="P / Esc" data-i18n="pause">Pause</button>
|
||||
</div>
|
||||
<div id="stage">
|
||||
<canvas id="cv"></canvas>
|
||||
<div id="pad">
|
||||
<span></span><button data-action="up">▲</button><span></span>
|
||||
<button data-action="left">◀</button><button data-action="down">▼</button><button data-action="right">▶</button>
|
||||
</div>
|
||||
<div id="overlay" class="hide"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="kit/kit-core.js"></script>
|
||||
<script src="kit/kit-audio.js"></script>
|
||||
<script src="kit/kit-loop.js"></script>
|
||||
<script src="kit/kit-input.js"></script>
|
||||
<script src="kit/kit-host.js"></script>
|
||||
<script src="kit/kit-scores.js"></script>
|
||||
<script src="kit/kit-fx.js"></script>
|
||||
<script src="kit/kit-i18n.js"></script>
|
||||
<script src="lang.js"></script>
|
||||
<script src="game.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
41
Library/web/template/game/lang.js
Normal file
41
Library/web/template/game/lang.js
Normal file
@@ -0,0 +1,41 @@
|
||||
/* {{NAME}} - all visible texts, English + German. Used via L.t('key') in game.js and
|
||||
data-i18n="key" in index.html (kit-i18n.js). A new text always gets BOTH languages.
|
||||
Values may contain simple HTML (<b>, <br>) and {placeholders}. */
|
||||
window.LANG = {
|
||||
en: {
|
||||
lang_self: 'English',
|
||||
hud_score: 'Score', hud_time: 'Time', hud_best: 'Best',
|
||||
sound_on: 'Sound on', sound_off: 'Sound off', pause: 'Pause',
|
||||
win_min: 'Minimise', win_full: 'Fullscreen (F11)', win_close: 'Close',
|
||||
menu_text: 'Collect the blue orbs, avoid the red ones.<br>Arrows / WASD or tap to move.',
|
||||
name_placeholder: 'Your name',
|
||||
play: 'Play',
|
||||
loading: 'loading…',
|
||||
no_scores: 'No scores yet - be the first!',
|
||||
scores_offline: 'Highscores offline',
|
||||
time_up: 'Time!',
|
||||
score_line: 'Score <b>{score}</b>',
|
||||
new_best: ' - new best!',
|
||||
again: 'Again',
|
||||
menu: 'Menu',
|
||||
continue: 'Continue',
|
||||
},
|
||||
de: {
|
||||
lang_self: 'Deutsch',
|
||||
hud_score: 'Punkte', hud_time: 'Zeit', hud_best: 'Rekord',
|
||||
sound_on: 'Sound an', sound_off: 'Sound aus', pause: 'Pause',
|
||||
win_min: 'Minimieren', win_full: 'Vollbild (F11)', win_close: 'Schließen',
|
||||
menu_text: 'Sammle die blauen Kugeln, weiche den roten aus.<br>Pfeile / WASD oder tippen zum Bewegen.',
|
||||
name_placeholder: 'Dein Name',
|
||||
play: 'Spielen',
|
||||
loading: 'lädt…',
|
||||
no_scores: 'Noch keine Punkte – sei der Erste!',
|
||||
scores_offline: 'Bestenliste offline',
|
||||
time_up: 'Zeit um!',
|
||||
score_line: 'Punkte <b>{score}</b>',
|
||||
new_best: ' – neuer Rekord!',
|
||||
again: 'Nochmal',
|
||||
menu: 'Menü',
|
||||
continue: 'Weiter',
|
||||
},
|
||||
};
|
||||
42
Library/web/template/launcher/Launcher.csproj.template
Normal file
42
Library/web/template/launcher/Launcher.csproj.template
Normal file
@@ -0,0 +1,42 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!-- {{NAME}} desktop window: shows the HTML game in WebView2. game\** is embedded as
|
||||
resources (game/...) and served from https://{{SLUG}}.game/ - one exe, nothing unpacked.
|
||||
Build with ..\build.ps1. From _Tools\Library\web\template. -->
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net8.0-windows</TargetFramework>
|
||||
<UseWindowsForms>true</UseWindowsForms>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<AssemblyName>{{IDENT}}</AssemblyName>
|
||||
<RootNamespace>{{IDENT}}</RootNamespace>
|
||||
<ApplicationHighDpiMode>PerMonitorV2</ApplicationHighDpiMode>
|
||||
<Product>{{NAME}}</Product>
|
||||
<Company>Michael Media</Company>
|
||||
<Copyright>(c) {{YEAR}} Michael Media</Copyright>
|
||||
<Version>1.0.0</Version>
|
||||
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
|
||||
<SelfContained>true</SelfContained>
|
||||
<PublishSingleFile>true</PublishSingleFile>
|
||||
<EnableCompressionInSingleFile>true</EnableCompressionInSingleFile>
|
||||
<IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract>
|
||||
<DebugType>none</DebugType>
|
||||
<SatelliteResourceLanguages>de</SatelliteResourceLanguages>
|
||||
<NoWarn>$(NoWarn);MSB3277</NoWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
<!-- build.ps1 creates app.ico from game\assets\Sprites\icon.png -->
|
||||
<PropertyGroup Condition="Exists('app.ico')">
|
||||
<ApplicationIcon>app.ico</ApplicationIcon>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.2903.40" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="..\game\**\*.*" LogicalName="game/%(RecursiveDir)%(Filename)%(Extension)" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
175
Library/web/template/launcher/Program.cs
Normal file
175
Library/web/template/launcher/Program.cs
Normal file
@@ -0,0 +1,175 @@
|
||||
using System.Diagnostics;
|
||||
using System.Reflection;
|
||||
using Microsoft.Web.WebView2.Core;
|
||||
using Microsoft.Web.WebView2.WinForms;
|
||||
|
||||
namespace {{IDENT}};
|
||||
|
||||
static class Program
|
||||
{
|
||||
[STAThread]
|
||||
static void Main()
|
||||
{
|
||||
ApplicationConfiguration.Initialize();
|
||||
Application.Run(new MainForm());
|
||||
}
|
||||
}
|
||||
|
||||
// One borderless window with WebView2. The game files are embedded resources ("game/<path>")
|
||||
// and answered from https://{{SLUG}}.game/<path> via WebResourceRequested.
|
||||
// localStorage (saves, settings) lives in %LOCALAPPDATA%\{{IDENT}}\WebView2.
|
||||
// The page talks to the window with chrome.webview.postMessage("maximize"|"minimize"|"quit"|"drag")
|
||||
// - see kit-host.js. From _Tools\Library\web\template.
|
||||
sealed class MainForm : Form
|
||||
{
|
||||
const string AppName = "{{NAME}}";
|
||||
const string Host = "https://{{SLUG}}.game/";
|
||||
const double Aspect = 16.0 / 10.0; // start window width / height
|
||||
const string WebView2Download = "https://go.microsoft.com/fwlink/p/?LinkId=2124703";
|
||||
static readonly string DataDir = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "{{IDENT}}");
|
||||
|
||||
readonly WebView2 web = new() { Dock = DockStyle.Fill, Visible = false, DefaultBackgroundColor = Color.FromArgb(11, 15, 26) };
|
||||
readonly Label status = new()
|
||||
{
|
||||
Dock = DockStyle.Fill,
|
||||
TextAlign = ContentAlignment.MiddleCenter,
|
||||
Font = new Font("Segoe UI", 12f),
|
||||
ForeColor = Color.FromArgb(160, 160, 160),
|
||||
Text = $"Starte {AppName} …",
|
||||
};
|
||||
[System.Runtime.InteropServices.DllImport("user32.dll")] static extern bool ReleaseCapture();
|
||||
[System.Runtime.InteropServices.DllImport("user32.dll")] static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
|
||||
const int WM_NCLBUTTONDOWN = 0xA1, HTCAPTION = 2;
|
||||
|
||||
public MainForm()
|
||||
{
|
||||
Text = AppName;
|
||||
Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath);
|
||||
BackColor = Color.FromArgb(11, 15, 26);
|
||||
FormBorderStyle = FormBorderStyle.None; // the page draws its own window buttons
|
||||
// Start large: 88 % of the screen height, centred on the screen with the mouse.
|
||||
var wa = Screen.FromPoint(Cursor.Position).WorkingArea;
|
||||
int h = (int)(wa.Height * 0.88);
|
||||
int w = Math.Min((int)(h * Aspect), (int)(wa.Width * 0.92));
|
||||
StartPosition = FormStartPosition.Manual;
|
||||
Bounds = new Rectangle(wa.X + (wa.Width - w) / 2, wa.Y + (wa.Height - h) / 2, w, h);
|
||||
KeyPreview = true;
|
||||
Controls.Add(web);
|
||||
Controls.Add(status);
|
||||
Shown += async (_, _) => await StartAsync();
|
||||
}
|
||||
|
||||
async Task StartAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(DataDir);
|
||||
var args = "--autoplay-policy=no-user-gesture-required";
|
||||
// GAME_DEBUG_PORT=9333 opens the DevTools protocol (automated tests)
|
||||
if (int.TryParse(Environment.GetEnvironmentVariable("GAME_DEBUG_PORT"), out var dbg))
|
||||
args += $" --remote-debugging-port={dbg}";
|
||||
var env = await CoreWebView2Environment.CreateAsync(null, Path.Combine(DataDir, "WebView2"),
|
||||
new CoreWebView2EnvironmentOptions(args));
|
||||
await web.EnsureCoreWebView2Async(env);
|
||||
var core = web.CoreWebView2;
|
||||
core.Settings.IsStatusBarEnabled = false;
|
||||
core.Settings.AreDefaultContextMenusEnabled = false;
|
||||
core.Settings.IsZoomControlEnabled = false;
|
||||
core.Settings.AreBrowserAcceleratorKeysEnabled = false;
|
||||
#if DEBUG
|
||||
core.Settings.AreDevToolsEnabled = true;
|
||||
#else
|
||||
core.Settings.AreDevToolsEnabled = false;
|
||||
#endif
|
||||
core.AddWebResourceRequestedFilter(Host + "*", CoreWebView2WebResourceContext.All);
|
||||
core.WebResourceRequested += (_, e) => e.Response = Serve(core.Environment, e.Request.Uri);
|
||||
// links with target=_blank open in the normal browser
|
||||
core.NewWindowRequested += (_, e) =>
|
||||
{
|
||||
e.Handled = true;
|
||||
if (e.Uri.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
|
||||
try { Process.Start(new ProcessStartInfo(e.Uri) { UseShellExecute = true }); } catch { }
|
||||
};
|
||||
core.NavigationStarting += (_, e) => { if (!e.Uri.StartsWith(Host)) e.Cancel = true; };
|
||||
core.WebMessageReceived += (_, e) =>
|
||||
{
|
||||
switch (e.TryGetWebMessageAsString())
|
||||
{
|
||||
case "maximize": ToggleFullscreen(); break;
|
||||
case "minimize": WindowState = FormWindowState.Minimized; break;
|
||||
case "quit": Close(); break;
|
||||
case "drag":
|
||||
if (WindowState == FormWindowState.Normal && (MouseButtons & MouseButtons.Left) != 0)
|
||||
{
|
||||
ReleaseCapture();
|
||||
SendMessage(Handle, WM_NCLBUTTONDOWN, HTCAPTION, IntPtr.Zero);
|
||||
}
|
||||
break;
|
||||
}
|
||||
};
|
||||
web.Source = new Uri(Host + "index.html");
|
||||
web.Visible = true;
|
||||
status.Visible = false;
|
||||
}
|
||||
catch (WebView2RuntimeNotFoundException)
|
||||
{
|
||||
status.Text = $"Es fehlt die „Microsoft Edge WebView2 Runtime“.\n\nHier klicken zum Herunterladen, danach {AppName} neu starten.";
|
||||
status.Cursor = Cursors.Hand;
|
||||
status.Click += (_, _) => { try { Process.Start(new ProcessStartInfo(WebView2Download) { UseShellExecute = true }); } catch { } };
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
status.Text = $"{AppName} konnte nicht starten:\n\n" + ex.Message;
|
||||
status.ForeColor = Color.FromArgb(220, 60, 60);
|
||||
}
|
||||
}
|
||||
|
||||
// Resource names from %(RecursiveDir) contain backslashes - map "game/a/b.png" -> real name.
|
||||
static readonly Dictionary<string, string> Resources = Assembly.GetExecutingAssembly()
|
||||
.GetManifestResourceNames()
|
||||
.ToDictionary(n => n.Replace('\\', '/'), n => n, StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
static CoreWebView2WebResourceResponse Serve(CoreWebView2Environment env, string uri)
|
||||
{
|
||||
var path = Uri.UnescapeDataString(new Uri(uri).AbsolutePath.TrimStart('/'));
|
||||
if (path.Length == 0) path = "index.html";
|
||||
var stream = Resources.TryGetValue("game/" + path, out var name)
|
||||
? Assembly.GetExecutingAssembly().GetManifestResourceStream(name) : null;
|
||||
if (stream == null) return env.CreateWebResourceResponse(null, 404, "Not Found", "");
|
||||
var mem = new MemoryStream();
|
||||
stream.CopyTo(mem);
|
||||
mem.Position = 0;
|
||||
return env.CreateWebResourceResponse(mem, 200, "OK",
|
||||
$"Content-Type: {Mime(path)}\nContent-Length: {mem.Length}\nCache-Control: no-cache");
|
||||
}
|
||||
|
||||
static string Mime(string path) => Path.GetExtension(path).ToLowerInvariant() switch
|
||||
{
|
||||
".html" => "text/html; charset=utf-8",
|
||||
".js" or ".mjs" => "text/javascript",
|
||||
".css" => "text/css",
|
||||
".json" => "application/json",
|
||||
".png" => "image/png",
|
||||
".jpg" or ".jpeg" => "image/jpeg",
|
||||
".webp" => "image/webp",
|
||||
".svg" => "image/svg+xml",
|
||||
".mp3" => "audio/mpeg",
|
||||
".ogg" => "audio/ogg",
|
||||
".wav" => "audio/wav",
|
||||
".ttf" => "font/ttf",
|
||||
".otf" => "font/otf",
|
||||
".woff2" => "font/woff2",
|
||||
_ => "application/octet-stream",
|
||||
};
|
||||
|
||||
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
|
||||
{
|
||||
if (keyData == Keys.F11 || keyData == (Keys.Alt | Keys.Enter)) { ToggleFullscreen(); return true; }
|
||||
return base.ProcessCmdKey(ref msg, keyData);
|
||||
}
|
||||
|
||||
// Borderless window: maximised = covers the whole screen incl. taskbar.
|
||||
void ToggleFullscreen() =>
|
||||
WindowState = WindowState == FormWindowState.Maximized ? FormWindowState.Normal : FormWindowState.Maximized;
|
||||
}
|
||||
360
ModelTools/fbx2gim/Program.cs
Normal file
360
ModelTools/fbx2gim/Program.cs
Normal file
@@ -0,0 +1,360 @@
|
||||
// fbx2gim – Mixamo-Figur (FBX mit Skelett) + Bewegungen (FBX ohne Skin) → .gim fürs Spiel.
|
||||
//
|
||||
// fbx2gim <figur.fbx> <bemalt.pcol|bemalt.glb|-> <ausgabe.gim> name=bewegung.fbx [name=bewegung.fbx ...]
|
||||
// fbx2gim --info <datei> zeigt Netze, Knochen, Bewegungen
|
||||
// fbx2gim --obj <figur.fbx> <aus.obj> [textur.png] Netz als OBJ für Mixamo (z. B. Meshy-FBX, die Mixamo ablehnt)
|
||||
//
|
||||
// Die Farbe: Mixamo gibt das Netz ohne Farbe zurück (und mit eigener Punktreihenfolge). Jeder Punkt
|
||||
// holt sie sich vom nächstgelegenen Punkt des bemalten Modells (paint_mesh), nachdem beide auf
|
||||
// dieselbe Größe gebracht sind. "-": keine Punktfarben – hat die Figur eine eingebettete Textur
|
||||
// (z. B. Meshy), kommt die Farbe aus ihr (UVs + JPG/PNG werden mitgeschrieben), sonst grau.
|
||||
//
|
||||
// Format (.gim, little endian, Strings wie BinaryWriter):
|
||||
// "GIM2"
|
||||
// int boneCount; je Knochen: string name, int parent (-1 = Wurzel), 10 float Ruhe-Lokal (T xyz, R xyzw, S xyz),
|
||||
// byte hasOffset, 16 float Offset (Netz → Knochen, Zeilenvektor-Konvention wie XNA)
|
||||
// int vertexCount; je Punkt: 3 float Pos, 3 float Normale, 2 float UV, 4 byte RGBA, 4 byte Knochen, 4 float Gewichte
|
||||
// int indexCount; int[] Indizes
|
||||
// int clipCount; je Clip: string name, float fps, int frames, frames × boneCount × 10 float (T, R, S lokal)
|
||||
// int textureBytes; Bilddatei (JPG/PNG) oder 0
|
||||
using System.Numerics;
|
||||
using System.Text;
|
||||
using Assimp;
|
||||
using AMatrix = Assimp.Matrix4x4;
|
||||
using NMatrix = System.Numerics.Matrix4x4;
|
||||
using NQuat = System.Numerics.Quaternion;
|
||||
|
||||
static class Fbx2Gim
|
||||
{
|
||||
const float FPS = 30;
|
||||
|
||||
static Scene Load(string path, bool pivots = false)
|
||||
{
|
||||
var ctx = new AssimpContext();
|
||||
ctx.SetConfig(new Assimp.Configs.FBXPreservePivotsConfig(pivots));
|
||||
return ctx.ImportFile(path, PostProcessSteps.Triangulate | PostProcessSteps.JoinIdenticalVertices | PostProcessSteps.LimitBoneWeights | PostProcessSteps.FlipUVs);
|
||||
}
|
||||
|
||||
static NMatrix ToN(AMatrix a) => new(a.A1, a.B1, a.C1, a.D1, a.A2, a.B2, a.C2, a.D2, a.A3, a.B3, a.C3, a.D3, a.A4, a.B4, a.C4, a.D4);
|
||||
|
||||
static int Main(string[] args)
|
||||
{
|
||||
if (args.Length >= 2 && args[0] == "--info") { Info(Load(args[1])); return 0; }
|
||||
if (args.Length >= 3 && args[0] == "--obj") return ToObj(args[1], args[2], args.Length > 3 ? args[3] : null);
|
||||
// --tex=<bild>: Textur, falls die Figur keine eingebettete hat (z. B. Mixamo-FBX aus einer OBJ)
|
||||
string? texFile = args.FirstOrDefault(x => x.StartsWith("--tex="))?[6..];
|
||||
args = args.Where(x => !x.StartsWith("--tex=")).ToArray();
|
||||
if (args.Length < 4) { Console.WriteLine("fbx2gim <figur.fbx> <bemalt.glb|-> <ausgabe.gim> name=bewegung.fbx ..."); return 1; }
|
||||
|
||||
var skin = Load(args[0]);
|
||||
var mesh = skin.Meshes.OrderByDescending(m => m.VertexCount).First();
|
||||
|
||||
// ── Knochen: alle Knoten, die Knochen sind oder Knochen enthalten (Eltern vor Kindern)
|
||||
var boneNames = new HashSet<string>(mesh.Bones.Select(b => b.Name));
|
||||
var nodes = new List<Node>();
|
||||
bool Needed(Node n) => boneNames.Contains(n.Name) || n.Children.Any(Needed);
|
||||
void Walk(Node n) { if (n != skin.RootNode && Needed(n)) nodes.Add(n); foreach (var c in n.Children) Walk(c); }
|
||||
Walk(skin.RootNode);
|
||||
var index = nodes.Select((n, i) => (n.Name, i)).ToDictionary(p => p.Name, p => p.i);
|
||||
var parent = nodes.Select(n => n.Parent != null && index.TryGetValue(n.Parent.Name, out int p) ? p : -1).ToArray();
|
||||
var rest = nodes.Select(n => Trs(ToN(n.Transform))).ToArray();
|
||||
var offsets = new NMatrix?[nodes.Count];
|
||||
foreach (var b in mesh.Bones) offsets[index[b.Name]] = ToN(b.OffsetMatrix);
|
||||
|
||||
// ── Punkte, Gewichte (höchstens 4), Normalen
|
||||
int vc = mesh.VertexCount;
|
||||
var pos = mesh.Vertices.Select(v => new Vector3(v.X, v.Y, v.Z)).ToArray();
|
||||
var bi = new byte[vc * 4];
|
||||
var bw = new float[vc * 4];
|
||||
var inf = new List<(int b, float w)>[vc];
|
||||
for (int i = 0; i < vc; i++) inf[i] = new();
|
||||
foreach (var b in mesh.Bones)
|
||||
foreach (var w in b.VertexWeights) inf[w.VertexID].Add((index[b.Name], w.Weight));
|
||||
for (int i = 0; i < vc; i++)
|
||||
{
|
||||
var top = inf[i].OrderByDescending(x => x.w).Take(4).ToList();
|
||||
float sum = top.Sum(x => x.w);
|
||||
for (int k = 0; k < top.Count; k++) { bi[i * 4 + k] = (byte)top[k].b; bw[i * 4 + k] = sum > 0 ? top[k].w / sum : 0; }
|
||||
if (top.Count == 0) { bi[i * 4] = 0; bw[i * 4] = 1; }
|
||||
}
|
||||
var idx = mesh.GetIndices().ToArray();
|
||||
var nrm = new Vector3[vc];
|
||||
for (int t = 0; t < idx.Length; t += 3)
|
||||
{
|
||||
var a = pos[idx[t]]; var b2 = pos[idx[t + 1]]; var c = pos[idx[t + 2]];
|
||||
var fn = Vector3.Cross(b2 - a, c - a);
|
||||
nrm[idx[t]] += fn; nrm[idx[t + 1]] += fn; nrm[idx[t + 2]] += fn;
|
||||
}
|
||||
for (int i = 0; i < vc; i++) nrm[i] = nrm[i].LengthSquared() > 0 ? Vector3.Normalize(nrm[i]) : Vector3.UnitY;
|
||||
if (mesh.HasNormals) // mitgelieferte Normalen (keine Kanten an UV-Nähten)
|
||||
for (int i = 0; i < vc; i++) { var n = mesh.Normals[i]; var v = new Vector3(n.X, n.Y, n.Z); if (v.LengthSquared() > 0) nrm[i] = Vector3.Normalize(v); }
|
||||
|
||||
// ── Textur (eingebettet) und UVs
|
||||
var uv = new Vector2[vc];
|
||||
if (mesh.HasTextureCoords(0)) for (int i = 0; i < vc; i++) { var t = mesh.TextureCoordinateChannels[0][i]; uv[i] = new Vector2(t.X, t.Y); }
|
||||
byte[] tex = Array.Empty<byte>();
|
||||
if (mesh.HasTextureCoords(0) && skin.TextureCount > 0)
|
||||
{
|
||||
var mat = skin.Materials[mesh.MaterialIndex];
|
||||
string want = mat.HasTextureDiffuse ? mat.TextureDiffuse.FilePath : "";
|
||||
var et = want.StartsWith('*') && int.TryParse(want[1..], out int ti) && ti < skin.TextureCount ? skin.Textures[ti]
|
||||
: skin.Textures.FirstOrDefault(t => t.Filename == want) ?? skin.Textures[0];
|
||||
if (et.IsCompressed) tex = et.CompressedData;
|
||||
Console.WriteLine($" Textur: {et.Filename} ({tex.Length / 1024} KB, {et.CompressedFormatHint})");
|
||||
}
|
||||
|
||||
if (tex.Length == 0 && texFile != null && File.Exists(texFile) && mesh.HasTextureCoords(0))
|
||||
{
|
||||
tex = File.ReadAllBytes(texFile);
|
||||
Console.WriteLine($" Textur aus Datei: {texFile} ({tex.Length / 1024} KB)");
|
||||
}
|
||||
byte grey = tex.Length > 0 ? (byte)255 : (byte)180;
|
||||
var col = args[1] == "-" ? Enumerable.Repeat(new byte[] { grey, grey, grey, 255 }, vc).ToArray() : Colours(pos, args[1]);
|
||||
|
||||
// ── Bewegungen
|
||||
var clips = new List<(string name, float[][] frames)>();
|
||||
foreach (var spec in args.Skip(3))
|
||||
{
|
||||
int eq = spec.IndexOf('=');
|
||||
string name = spec[..eq], file = spec[(eq + 1)..];
|
||||
// Mit Hilfsknoten laden: FBX-Knochen haben Vor-Drehungen (PreRotation), die Spuren hängen an
|
||||
// eigenen Knoten "<knochen>_$AssimpFbx$_Rotation". Der lokale Knochen ist das Produkt der
|
||||
// ganzen Kette vom Knochen bis (ohne) zum Elternknochen.
|
||||
var sc = Load(file, pivots: true);
|
||||
if (sc.AnimationCount == 0) { Console.WriteLine($" {name}: keine Bewegung in {file}"); continue; }
|
||||
var anim = sc.Animations[0];
|
||||
double tps = anim.TicksPerSecond > 0 ? anim.TicksPerSecond : FPS;
|
||||
// glTF: Assimp liefert die Zeiten in Millisekunden, meldet aber eine falsche Tick-Rate
|
||||
if (file.EndsWith(".glb", StringComparison.OrdinalIgnoreCase) || file.EndsWith(".gltf", StringComparison.OrdinalIgnoreCase)) tps = 1000;
|
||||
int frames = Math.Max(1, (int)Math.Round(anim.DurationInTicks / tps * FPS) + 1);
|
||||
var chan = anim.NodeAnimationChannels.ToDictionary(c => c.NodeName);
|
||||
var byName = new Dictionary<string, Node>();
|
||||
void W2(Node n) { byName[n.Name] = n; foreach (var c in n.Children) W2(c); }
|
||||
W2(sc.RootNode);
|
||||
var chains = new List<Node>?[nodes.Count];
|
||||
int found = 0;
|
||||
for (int b = 0; b < nodes.Count; b++)
|
||||
{
|
||||
if (!byName.TryGetValue(nodes[b].Name, out var n)) continue;
|
||||
string? stop = parent[b] >= 0 ? nodes[parent[b]].Name : null;
|
||||
var chain = new List<Node>();
|
||||
for (var x = n; x != null && x.Name != stop && x != sc.RootNode; x = x.Parent) chain.Add(x);
|
||||
chains[b] = chain; found++;
|
||||
}
|
||||
// Ruhelage der Kette in der Bewegungsdatei (ohne Spuren), für die Hüfte
|
||||
var restChain = new float[nodes.Count][];
|
||||
for (int b = 0; b < nodes.Count; b++)
|
||||
if (chains[b] is { } ch0) { var m0 = NMatrix.Identity; foreach (var x in ch0) m0 *= ToN(x.Transform); restChain[b] = Trs(m0); }
|
||||
var data = new float[frames][];
|
||||
for (int f = 0; f < frames; f++)
|
||||
{
|
||||
double t = f / FPS * tps;
|
||||
var fr = data[f] = new float[nodes.Count * 10];
|
||||
for (int b = 0; b < nodes.Count; b++)
|
||||
{
|
||||
float[] trs = rest[b];
|
||||
if (chains[b] is { } chain)
|
||||
{
|
||||
var m = NMatrix.Identity;
|
||||
foreach (var x in chain) // Kind zuerst: Zeilenvektor-Konvention
|
||||
m *= chan.TryGetValue(x.Name, out var ch) ? Mat(Sample(ch, t, Trs(ToN(x.Transform)))) : ToN(x.Transform);
|
||||
var a = Trs(m);
|
||||
// Übertragen auf diese Figur (die Bewegung darf von einer anderen Mixamo-Figur stammen):
|
||||
// Drehung aus der Bewegung, Knochenlängen und Maßstab von der Figur, die Hüfte bewegt
|
||||
// sich im Verhältnis der Hüfthöhen.
|
||||
trs = (float[])rest[b].Clone();
|
||||
trs[3] = a[3]; trs[4] = a[4]; trs[5] = a[5]; trs[6] = a[6];
|
||||
if (parent[b] < 0)
|
||||
{
|
||||
var r0 = restChain[b];
|
||||
float k = MathF.Abs(r0[1]) > 1e-6f ? rest[b][1] / r0[1] : 1;
|
||||
for (int i = 0; i < 3; i++) trs[i] = rest[b][i] + (a[i] - r0[i]) * k;
|
||||
}
|
||||
}
|
||||
Array.Copy(trs, 0, fr, b * 10, 10);
|
||||
}
|
||||
}
|
||||
Console.WriteLine($" {name}: {frames} Bilder ({frames / FPS:0.00} s), {chan.Count} Spuren, {found}/{nodes.Count} Knochen gefunden");
|
||||
clips.Add((name, data));
|
||||
}
|
||||
|
||||
// ── schreiben
|
||||
using (var w = new BinaryWriter(File.Create(args[2]), Encoding.UTF8))
|
||||
{
|
||||
w.Write(Encoding.ASCII.GetBytes("GIM2"));
|
||||
w.Write(nodes.Count);
|
||||
for (int b = 0; b < nodes.Count; b++)
|
||||
{
|
||||
w.Write(nodes[b].Name); w.Write(parent[b]);
|
||||
foreach (var x in rest[b]) w.Write(x);
|
||||
w.Write((byte)(offsets[b].HasValue ? 1 : 0));
|
||||
var o = offsets[b] ?? NMatrix.Identity;
|
||||
foreach (var x in new[] { o.M11, o.M12, o.M13, o.M14, o.M21, o.M22, o.M23, o.M24, o.M31, o.M32, o.M33, o.M34, o.M41, o.M42, o.M43, o.M44 }) w.Write(x);
|
||||
}
|
||||
w.Write(vc);
|
||||
for (int i = 0; i < vc; i++)
|
||||
{
|
||||
w.Write(pos[i].X); w.Write(pos[i].Y); w.Write(pos[i].Z);
|
||||
w.Write(nrm[i].X); w.Write(nrm[i].Y); w.Write(nrm[i].Z);
|
||||
w.Write(uv[i].X); w.Write(uv[i].Y);
|
||||
w.Write(col[i]);
|
||||
w.Write(bi, i * 4, 4);
|
||||
for (int k = 0; k < 4; k++) w.Write(bw[i * 4 + k]);
|
||||
}
|
||||
w.Write(idx.Length);
|
||||
foreach (var i in idx) w.Write(i);
|
||||
w.Write(clips.Count);
|
||||
foreach (var (name, frames) in clips)
|
||||
{
|
||||
w.Write(name); w.Write(FPS); w.Write(frames.Length);
|
||||
foreach (var fr in frames) foreach (var x in fr) w.Write(x);
|
||||
}
|
||||
w.Write(tex.Length); w.Write(tex);
|
||||
}
|
||||
var lo = pos.Aggregate(Vector3.Min); var hi = pos.Aggregate(Vector3.Max);
|
||||
Console.WriteLine($"{args[2]}: {nodes.Count} Knochen, {vc} Punkte, {idx.Length / 3} Dreiecke, {clips.Count} Clips, Größe {lo} … {hi}, " +
|
||||
$"{new FileInfo(args[2]).Length / 1024} KB");
|
||||
return 0;
|
||||
}
|
||||
|
||||
static NMatrix Mat(float[] t) =>
|
||||
NMatrix.CreateScale(t[7], t[8], t[9]) * NMatrix.CreateFromQuaternion(new NQuat(t[3], t[4], t[5], t[6])) * NMatrix.CreateTranslation(t[0], t[1], t[2]);
|
||||
|
||||
static float[] Trs(NMatrix m)
|
||||
{
|
||||
NMatrix.Decompose(m, out var s, out var r, out var t);
|
||||
return new[] { t.X, t.Y, t.Z, r.X, r.Y, r.Z, r.W, s.X, s.Y, s.Z };
|
||||
}
|
||||
|
||||
static float[] Sample(NodeAnimationChannel ch, double t, float[] fallback)
|
||||
{
|
||||
var o = (float[])fallback.Clone();
|
||||
if (ch.PositionKeyCount > 0)
|
||||
{
|
||||
var (a, b, f) = Find(ch.PositionKeys.Select(k => k.Time).ToList(), t);
|
||||
var p = Vector3.Lerp(V(ch.PositionKeys[a].Value), V(ch.PositionKeys[b].Value), f);
|
||||
o[0] = p.X; o[1] = p.Y; o[2] = p.Z;
|
||||
}
|
||||
if (ch.RotationKeyCount > 0)
|
||||
{
|
||||
var (a, b, f) = Find(ch.RotationKeys.Select(k => k.Time).ToList(), t);
|
||||
var q = NQuat.Normalize(NQuat.Slerp(Q(ch.RotationKeys[a].Value), Q(ch.RotationKeys[b].Value), f));
|
||||
o[3] = q.X; o[4] = q.Y; o[5] = q.Z; o[6] = q.W;
|
||||
}
|
||||
if (ch.ScalingKeyCount > 0)
|
||||
{
|
||||
var (a, b, f) = Find(ch.ScalingKeys.Select(k => k.Time).ToList(), t);
|
||||
var s = Vector3.Lerp(V(ch.ScalingKeys[a].Value), V(ch.ScalingKeys[b].Value), f);
|
||||
o[7] = s.X; o[8] = s.Y; o[9] = s.Z;
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
static (int, int, float) Find(List<double> times, double t)
|
||||
{
|
||||
if (times.Count == 1 || t <= times[0]) return (0, 0, 0);
|
||||
for (int i = 1; i < times.Count; i++)
|
||||
if (times[i] >= t) return (i - 1, i, (float)((t - times[i - 1]) / Math.Max(1e-9, times[i] - times[i - 1])));
|
||||
return (times.Count - 1, times.Count - 1, 0);
|
||||
}
|
||||
|
||||
static Vector3 V(Vector3D v) => new(v.X, v.Y, v.Z);
|
||||
static NQuat Q(Assimp.Quaternion q) => new(q.X, q.Y, q.Z, q.W);
|
||||
|
||||
/// Farbe je Punkt vom nächstgelegenen Punkt des bemalten Modells (beide auf Füße/Mitte/Höhe normiert).
|
||||
static byte[][] Colours(Vector3[] pos, string painted)
|
||||
{
|
||||
Vector3[] src; byte[][] cols;
|
||||
if (painted.EndsWith(".pcol", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
// paint_mesh: int Anzahl, je Punkt 3 float + 4 byte RGBA
|
||||
using var r = new BinaryReader(File.OpenRead(painted));
|
||||
int n = r.ReadInt32();
|
||||
src = new Vector3[n]; cols = new byte[n][];
|
||||
for (int i = 0; i < n; i++) { src[i] = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()); cols[i] = r.ReadBytes(4); }
|
||||
}
|
||||
else
|
||||
{
|
||||
var m = Load(painted).Meshes.OrderByDescending(x => x.VertexCount).First();
|
||||
src = m.Vertices.Select(v => new Vector3(v.X, v.Y, v.Z)).ToArray();
|
||||
cols = m.VertexColorChannels[0].Select(c => new[] { B(c.R), B(c.G), B(c.B), (byte)255 }).ToArray();
|
||||
}
|
||||
var a = Normalize(pos); var b = Normalize(src);
|
||||
// Gitter für die Suche
|
||||
const float CELL = 0.03f;
|
||||
var grid = new Dictionary<(int, int, int), List<int>>();
|
||||
(int, int, int) Key(Vector3 p) => ((int)MathF.Floor(p.X / CELL), (int)MathF.Floor(p.Y / CELL), (int)MathF.Floor(p.Z / CELL));
|
||||
for (int i = 0; i < b.Length; i++) { var k = Key(b[i]); if (!grid.TryGetValue(k, out var l)) grid[k] = l = new(); l.Add(i); }
|
||||
var result = new byte[pos.Length][];
|
||||
double far = 0;
|
||||
Parallel.For(0, a.Length, i =>
|
||||
{
|
||||
var (x, y, z) = Key(a[i]);
|
||||
int best = -1; float bd = float.MaxValue;
|
||||
for (int r = 1; r <= 8 && best < 0; r++)
|
||||
for (int dx = -r; dx <= r; dx++) for (int dy = -r; dy <= r; dy++) for (int dz = -r; dz <= r; dz++)
|
||||
if (grid.TryGetValue((x + dx, y + dy, z + dz), out var l))
|
||||
foreach (int j in l) { float d = Vector3.DistanceSquared(a[i], b[j]); if (d < bd) { bd = d; best = j; } }
|
||||
result[i] = best >= 0 ? cols[best] : new byte[] { 128, 128, 128, 255 };
|
||||
if (best >= 0) lock (result) far = Math.Max(far, Math.Sqrt(bd));
|
||||
});
|
||||
Console.WriteLine($" Farbe aus {painted}: {src.Length} Punkte, größter Abstand {far:0.000} (Höhe = 1)");
|
||||
return result;
|
||||
}
|
||||
|
||||
static byte B(float f) => (byte)Math.Clamp((int)MathF.Round(f * 255), 0, 255);
|
||||
|
||||
static Vector3[] Normalize(Vector3[] p)
|
||||
{
|
||||
var lo = p.Aggregate(Vector3.Min); var hi = p.Aggregate(Vector3.Max);
|
||||
float h = hi.Y - lo.Y;
|
||||
var c = new Vector3((lo.X + hi.X) / 2, lo.Y, (lo.Z + hi.Z) / 2);
|
||||
return p.Select(v => (v - c) / h).ToArray();
|
||||
}
|
||||
|
||||
/// Netz (mit UVs) als OBJ + MTL für Mixamo: ohne Skelett, Punkte verschweißt. Optional die Textur
|
||||
/// (PNG/JPG) daneben; die MTL verweist auf sie.
|
||||
static int ToObj(string input, string output, string? texture)
|
||||
{
|
||||
var ctx = new AssimpContext();
|
||||
var s = ctx.ImportFile(input, PostProcessSteps.Triangulate | PostProcessSteps.JoinIdenticalVertices);
|
||||
var inv = System.Globalization.CultureInfo.InvariantCulture;
|
||||
string name = Path.GetFileNameWithoutExtension(output);
|
||||
using (var w = new StreamWriter(output))
|
||||
{
|
||||
w.WriteLine($"mtllib {name}.mtl");
|
||||
int baseV = 1;
|
||||
foreach (var m in s.Meshes)
|
||||
{
|
||||
foreach (var v in m.Vertices) w.WriteLine(string.Format(inv, "v {0} {1} {2}", v.X, v.Y, v.Z));
|
||||
bool uv = m.HasTextureCoords(0);
|
||||
if (uv) foreach (var t in m.TextureCoordinateChannels[0]) w.WriteLine(string.Format(inv, "vt {0} {1}", t.X, t.Y));
|
||||
w.WriteLine("usemtl skin");
|
||||
foreach (var f in m.Faces)
|
||||
{
|
||||
if (f.IndexCount != 3) continue;
|
||||
var ix = f.Indices;
|
||||
w.WriteLine(uv ? $"f {ix[0] + baseV}/{ix[0] + baseV} {ix[1] + baseV}/{ix[1] + baseV} {ix[2] + baseV}/{ix[2] + baseV}"
|
||||
: $"f {ix[0] + baseV} {ix[1] + baseV} {ix[2] + baseV}");
|
||||
}
|
||||
baseV += m.VertexCount;
|
||||
}
|
||||
}
|
||||
using (var w = new StreamWriter(Path.Combine(Path.GetDirectoryName(Path.GetFullPath(output))!, name + ".mtl")))
|
||||
{
|
||||
w.WriteLine("newmtl skin"); w.WriteLine("Kd 1 1 1");
|
||||
if (texture != null) w.WriteLine("map_Kd " + Path.GetFileName(texture));
|
||||
}
|
||||
Console.WriteLine($"{output}: {s.Meshes.Sum(m => m.VertexCount)} Punkte, {s.Meshes.Sum(m => m.FaceCount)} Dreiecke");
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void Info(Scene s)
|
||||
{
|
||||
Console.WriteLine($"meshes {s.MeshCount} anims {s.AnimationCount}");
|
||||
foreach (var m in s.Meshes) Console.WriteLine($" mesh {m.Name} v{m.VertexCount} f{m.FaceCount} bones {m.BoneCount} colors {m.HasVertexColors(0)}");
|
||||
foreach (var a in s.Animations) Console.WriteLine($" anim {a.Name} {a.DurationInTicks / a.TicksPerSecond:0.00}s ch {a.NodeAnimationChannelCount}: " + string.Join(", ", a.NodeAnimationChannels.Take(6).Select(c => $"{c.NodeName} p{c.PositionKeyCount} r{c.RotationKeyCount}")));
|
||||
void P(Node n, int d) { Console.WriteLine(new string(' ', d) + n.Name); foreach (var c in n.Children) P(c, d + 1); }
|
||||
P(s.RootNode, 0);
|
||||
}
|
||||
}
|
||||
BIN
ModelTools/fbx2gim/bin/Release/net9.0/win-x64/AssimpNet.dll
Normal file
BIN
ModelTools/fbx2gim/bin/Release/net9.0/win-x64/AssimpNet.dll
Normal file
Binary file not shown.
BIN
ModelTools/fbx2gim/bin/Release/net9.0/win-x64/assimp.dll
Normal file
BIN
ModelTools/fbx2gim/bin/Release/net9.0/win-x64/assimp.dll
Normal file
Binary file not shown.
@@ -0,0 +1,47 @@
|
||||
{
|
||||
"runtimeTarget": {
|
||||
"name": ".NETCoreApp,Version=v9.0/win-x64",
|
||||
"signature": ""
|
||||
},
|
||||
"compilationOptions": {},
|
||||
"targets": {
|
||||
".NETCoreApp,Version=v9.0": {},
|
||||
".NETCoreApp,Version=v9.0/win-x64": {
|
||||
"fbx2gim/1.0.0": {
|
||||
"dependencies": {
|
||||
"AssimpNet": "5.0.0-beta1"
|
||||
},
|
||||
"runtime": {
|
||||
"fbx2gim.dll": {}
|
||||
}
|
||||
},
|
||||
"AssimpNet/5.0.0-beta1": {
|
||||
"runtime": {
|
||||
"lib/netstandard1.3/AssimpNet.dll": {
|
||||
"assemblyVersion": "5.0.0.0",
|
||||
"fileVersion": "5.0.0.0"
|
||||
}
|
||||
},
|
||||
"native": {
|
||||
"runtimes/win-x64/native/assimp.dll": {
|
||||
"fileVersion": "5.0.0.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"libraries": {
|
||||
"fbx2gim/1.0.0": {
|
||||
"type": "project",
|
||||
"serviceable": false,
|
||||
"sha512": ""
|
||||
},
|
||||
"AssimpNet/5.0.0-beta1": {
|
||||
"type": "package",
|
||||
"serviceable": true,
|
||||
"sha512": "sha512-oiUmn2KNaLThdbr6oT461uyCwclsqfZ0UB36vqkAUm8ttBWjKOCBmtp9V+X6xDGZmQaJe9YknW5eoyATTikUNQ==",
|
||||
"path": "assimpnet/5.0.0-beta1",
|
||||
"hashPath": "assimpnet.5.0.0-beta1.nupkg.sha512"
|
||||
}
|
||||
}
|
||||
}
|
||||
BIN
ModelTools/fbx2gim/bin/Release/net9.0/win-x64/fbx2gim.dll
Normal file
BIN
ModelTools/fbx2gim/bin/Release/net9.0/win-x64/fbx2gim.dll
Normal file
Binary file not shown.
BIN
ModelTools/fbx2gim/bin/Release/net9.0/win-x64/fbx2gim.exe
Normal file
BIN
ModelTools/fbx2gim/bin/Release/net9.0/win-x64/fbx2gim.exe
Normal file
Binary file not shown.
BIN
ModelTools/fbx2gim/bin/Release/net9.0/win-x64/fbx2gim.pdb
Normal file
BIN
ModelTools/fbx2gim/bin/Release/net9.0/win-x64/fbx2gim.pdb
Normal file
Binary file not shown.
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"runtimeOptions": {
|
||||
"tfm": "net9.0",
|
||||
"framework": {
|
||||
"name": "Microsoft.NETCore.App",
|
||||
"version": "9.0.0"
|
||||
},
|
||||
"configProperties": {
|
||||
"System.Reflection.Metadata.MetadataUpdater.IsSupported": false,
|
||||
"System.Runtime.Serialization.EnableUnsafeBinaryFormatterSerialization": false
|
||||
}
|
||||
}
|
||||
}
|
||||
14
ModelTools/fbx2gim/fbx2gim.csproj
Normal file
14
ModelTools/fbx2gim/fbx2gim.csproj
Normal file
@@ -0,0 +1,14 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<PlatformTarget>x64</PlatformTarget>
|
||||
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
|
||||
<SelfContained>false</SelfContained>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AssimpNet" Version="5.0.0-beta1" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,4 @@
|
||||
// <autogenerated />
|
||||
using System;
|
||||
using System.Reflection;
|
||||
[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(".NETCoreApp,Version=v9.0", FrameworkDisplayName = ".NET 9.0")]
|
||||
@@ -0,0 +1,22 @@
|
||||
//------------------------------------------------------------------------------
|
||||
// <auto-generated>
|
||||
// This code was generated by a tool.
|
||||
//
|
||||
// Changes to this file may cause incorrect behavior and will be lost if
|
||||
// the code is regenerated.
|
||||
// </auto-generated>
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
using System;
|
||||
using System.Reflection;
|
||||
|
||||
[assembly: System.Reflection.AssemblyCompanyAttribute("fbx2gim")]
|
||||
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
|
||||
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
|
||||
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
|
||||
[assembly: System.Reflection.AssemblyProductAttribute("fbx2gim")]
|
||||
[assembly: System.Reflection.AssemblyTitleAttribute("fbx2gim")]
|
||||
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
|
||||
|
||||
// Generated by the MSBuild WriteCodeFragment class.
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
70bc7440b7ff345739c2422e8a07f1a4c95ea01a8f507814314c874ba066dea5
|
||||
@@ -0,0 +1,18 @@
|
||||
is_global = true
|
||||
build_property.TargetFramework = net9.0
|
||||
build_property.TargetFrameworkIdentifier = .NETCoreApp
|
||||
build_property.TargetFrameworkVersion = v9.0
|
||||
build_property.TargetPlatformMinVersion =
|
||||
build_property.UsingMicrosoftNETSdkWeb =
|
||||
build_property.ProjectTypeGuids =
|
||||
build_property.InvariantGlobalization =
|
||||
build_property.PlatformNeutralAssembly =
|
||||
build_property.EnforceExtendedAnalyzerRules =
|
||||
build_property.EntryPointFilePath =
|
||||
build_property._SupportedPlatformList = Linux,macOS,Windows
|
||||
build_property.RootNamespace = fbx2gim
|
||||
build_property.ProjectDir = D:\Oculusquest\Projekt\_Tools\ModelTools\fbx2gim\
|
||||
build_property.EnableComHosting =
|
||||
build_property.EnableGeneratedComInterfaceComImportInterop =
|
||||
build_property.EffectiveAnalysisLevelStyle = 9.0
|
||||
build_property.EnableCodeStyleSeverity =
|
||||
@@ -0,0 +1,8 @@
|
||||
// <auto-generated/>
|
||||
global using System;
|
||||
global using System.Collections.Generic;
|
||||
global using System.IO;
|
||||
global using System.Linq;
|
||||
global using System.Net.Http;
|
||||
global using System.Threading;
|
||||
global using System.Threading.Tasks;
|
||||
BIN
ModelTools/fbx2gim/obj/Debug/net9.0/win-x64/fbx2gim.assets.cache
Normal file
BIN
ModelTools/fbx2gim/obj/Debug/net9.0/win-x64/fbx2gim.assets.cache
Normal file
Binary file not shown.
Binary file not shown.
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user