Compare commits

..
Author SHA1 Message Date
koka 7b3eb791fe Record beta.144 publication and verified Prism synchronizations
Build Sanctuary / build (push) Canceled after 0s
2026-09-18 18:46:49 +02:00
koka 83c377acc1 Validate beta.144 water, unloaded boundaries and ocean seams
Build Sanctuary / build (push) Canceled after 0s
2026-09-18 18:42:50 +02:00
koka 7eef9454d4 Implement natural pixel water for beta.144; final performance validation pending 2026-09-18 14:44:07 +02:00
37 changed files with 245 additions and 1064 deletions
+16 -14
View File
@@ -1,14 +1,5 @@
# Sanctuary
## beta.145 — PBR de l’eau et reflets pixélisés (livraison locale)
L’eau et le verre rejoignent le PBR natif. L’option expérimentale de reflets
alimente les texels avec le paysage visible selon leurs normales.
[Contrat, vérifications et limites](docs/pbr-ssr.md).
Cette branche intègre un instantané des sources d’eau beta.144 ; elle ne
publie pas le canal et ne synchronise pas Prism.
Sanctuary est une extension gratuite de Minecraft qui transforme le jeu en un
monde flottant d'exploration, de production et de progression collective.
Les joueurs commencent ensemble sur Sanctuary Island et construisent les
@@ -29,10 +20,13 @@ La [vision complète](docs/vision.md) conserve les intentions ; le
L’économie, les claims et les dimensions décrits dans la vision restent
à implémenter.
La version **beta.144** prépare une option d’**eau naturelle pixélisée** :
couleur du biome, trois profils selon le fond et visibilité adaptée en immersion.
La version **beta.144** ajoute une option d’**eau naturelle pixélisée** :
couleur du biome, trois profils selon le fond, vert olive d’étang et visibilité
adaptée en immersion.
Les océans gardent leur couleur native et le profil clair.
[Contrat et vérifications](docs/natural-water-beta144.md). Livraison en cours.
[Contrat et vérifications](docs/natural-water-beta144.md).
La beta.144 est publiée et synchronisée dans **Sanctuary Beta** ;
les 923 fichiers personnels suivis sont conservés.
La version **beta.143** garde le sampler natif de précipitation pour la neige
saisonnière, mais ralentit son rythme : l'accumulation est espacée par un
@@ -40,8 +34,6 @@ facteur 12 et la fonte par le facteur temps réel 72. Les protections existantes
restent inchangées : neige construite, biomes froids, hiver, profils neigeux
et météo Vanilla. Le [ticket](docs/realtime-snow-melt-beta143.md) documente le
contrat et les vérifications.
La beta.143 est publiée et synchronisée dans l’instance Sanctuary Beta ;
les 923 fichiers personnels suivis sont conservés.
La [livraison précédente](docs/clay-workshop-integration-beta110.md) réunit déjà
l’atelier, les œufs et la neige saisonnière dans l’instance **Sanctuary Beta**.
Les [synchronisations antérieures](docs/git-sync-beta092.md) restent documentées.
@@ -52,6 +44,16 @@ La [carte native beta.005](docs/atlas-beta005.md) prend le relais après
l’étude de Xaero et des alternatives libres.
## beta.144 — Eau naturelle pixélisée
Eau claire, légèrement teintée ou vert olive d’étang selon le fond, avec
textures et animation natives. Océans clairs, visibilité sous-marine adaptée,
interrupteur et intensité dans les options Shaders.
[Contrat et mesures](docs/natural-water-beta144.md) ·
[Pack normal](https://git.botsu.net/koka/sanctuary-beta/releases/download/beta.144/Sanctuary-beta.144.mrpack) ·
[Pack de test](https://git.botsu.net/koka/sanctuary-beta/releases/download/beta.144/Sanctuary-Test-beta.144.mrpack) ·
[Tous les livrables](https://git.botsu.net/koka/sanctuary-beta/releases/tag/beta.144).
## beta.143 — Neige saisonnière en temps réel
Accumulation ralentie par un facteur 12 et fonte saisonnière ralentie par le
+103 -15
View File
@@ -29,7 +29,9 @@ vert olive légèrement jaunâtre : le profil étang passe donc de 45 % à 85 %
de mélange, tout en laissant les eaux claires et océaniques natives.
Les surfaces profondes sans fond dans la limite restent donc
claires. Les profils se mélangent aux sommets sur un bloc, sans filtrer les
textures. L’eau sous un toit suit son fond, pas l’éclairage du bâtiment.
textures. Aux bords océaniques, les sommets partagés restent clairs et la
transition occupe le bloc voisin hors océan. L’eau sous un toit suit son fond,
pas l’éclairage du bâtiment.
La ressource client `assets/sanctuary/water_materials.json` accepte deux listes
d’identifiants de blocs, `light` et `pond`, remplaçables par un resource pack.
@@ -44,7 +46,9 @@ et tri des transparences restent natifs. Les calculs de profils sont différés
jusqu’à l’émission d’un sommet visible, puis mutualisés dans la région compilée.
Un test de palette élimine les sections sans eau avant toute copie de biomes.
Les états de blocs viennent des copies natives ; les appartenances océaniques
sont capturées avant l’envoi au worker. Aucun chargement de chunk n’est demandé.
sont capturées avant l’envoi au worker. La présence du terrain est vérifiée dans le cache client avec chargement
désactivé, sans utiliser `ClientLevel.hasChunk` (toujours vrai). Aucun
chargement de chunk n’est demandé par le classificateur.
Un changement de bloc invalide la zone dépendante, huit blocs au-dessus et
un bloc horizontalement. Les reconstructions natives recopient leurs données ;
@@ -68,30 +72,66 @@ sable et boue, support du sable, plantes aquatiques, toit, frontière de section
et changement de biome océan. Une copie personnelle de ressource remplace
réellement les familles de matériaux puis est désactivée.
Les suites graphiques OpenGL et Vulkan ont passé les contrôles de surface,
d’immersion, de fond modifié, d’océan, de ressources, de préférences et de
cascades pendant le développement. La dernière optimisation reconstruit
seulement les sections contenant de l’eau lors du changement d’option.
Sa série de validation finale reste à terminer avant publication.
Les suites graphiques finales OpenGL et Vulkan sont réussies le 18 septembre
2026 (`WATER144_PASS` et `WATER144_EXTRAS_PASS`). Elles couvrent surface,
immersion, fond modifié, priorité océan, toit, plantes, cascades, lave inchangée,
blocs gorgés d’eau, préférences FR/EN et rechargement des ressources/chunks.
Les sommets partagés aux limites océaniques et le repli clair lorsque le cache
client ne contient pas le terrain font l’objet d’assertions supplémentaires.
Aucun autre client de test concurrent n’a été détecté pendant ces séries.
Deux passages ciblés supplémentaires (`WATER144_TEXTURE_PASS`), Vulkan en
1 min 18 s et OpenGL en 1 min 4 s, chargent de vraies textures personnelles
32×32 à deux images animées pour l’eau calme et courante. Grille, animation
visible et retour aux textures natives sont vérifiés après désactivation.
Les fixtures, leurs alpha et les captures restent dans les preuves locales.
### Protocole de performance
Apple M1, macOS, Java 25, 854×480, distance de rendu 6 chunks,
MacBookPro17,1, Apple M1, 8 Gio, macOS 26.5.1 (25F80), Java 25,
fenêtre logique 854×480, cible Retina **1708×960 pixels**, distance de rendu 6 chunks,
ombres 32 blocs / 16 pixels, PBR 50 %, autres effets activés.
VSync désactivée, limite 260 (illimitée), limitation AFK désactivée.
Le mod de test vérifie le limiteur effectif et journalise le mode de présentation.
Pendant les échantillons uniquement, il omet l’attente artificielle de
`FramerateLimiter.limitDisplayFPS`, afin de mesurer sans temporisation
applicative. Cette sonde reste absente du JAR de production. Les temps couvrent
la frame native, présentation comprise, et ne sont pas des temps GPU isolés.
Pour chaque scène : OFF/ON/ON/OFF/ON/OFF/OFF/ON, dix secondes par passage,
avec stabilisation des sections puis quatre secondes de chauffe entre passages.
Le déplacement avance de 120 blocs et laisse les sections se compiler
naturellement, sans vidange artificielle des caches des autres effets.
La scène de déplacement prolonge le bassin hors de la vue initiale : son terrain
est préparé côté serveur de test, puis découvert normalement par le client.
Le vérificateur exige des compilations réelles dans chaque passage en mouvement.
Les moyennes des quatre médianes et P95 par état sont comparées avec les seuils
+5 % et +2 ms. Les temps de compilation de sections sont consignés également.
Les essais courts initiaux ont montré une forte variabilité. Une limitation AFK
à 30 FPS puis des clients Minecraft concurrents dans le chantier PBR/SSR ont
été identifiés. Ces essais restent dans les preuves de développement ; ils
ne valident pas la livraison. La série finale attend la fin du chantier
concurrent, conformément à la demande du créateur. Les résultats ne sont pas
présentés comme acquis, et aucun gain de performance universel n’est promis.
Les essais courts initiaux, les exécutions concurrentes et les vérifications
incomplètes du limiteur restent conservés comme preuves de développement ;
ils ne fondent pas ces résultats. Les séries finales ont été exécutées après
la fin du chantier SSR. Les variations négatives sont du bruit de mesure,
pas une promesse d’accélération. Vulkan reste proche de 120 images/s dans
cette chaîne de présentation, malgré le mode `IMMEDIATE` et l’absence de
limiteur applicatif : les conclusions sont limitées à la machine et aux
conditions ci-dessus.
| Moteur / scène | Médiane OFF → ON (ms) | Variation | P95 OFF → ON (ms) | Δ P95 (ms) |
| --- | --- | ---: | --- | ---: |
| vulkan / mixed | 8.069 → 8.092 | +0.29 % | 9.091 → 9.101 | +0.010 |
| vulkan / large | 8.078 → 8.062 | -0.20 % | 9.126 → 9.114 | -0.012 |
| vulkan / moving | 8.123 → 8.103 | -0.24 % | 9.103 → 9.080 | -0.023 |
| opengl / mixed | 4.545 → 4.407 | -3.02 % | 7.080 → 6.733 | -0.347 |
| opengl / large | 4.879 → 5.110 | +4.73 % | 7.519 → 7.767 | +0.248 |
| opengl / moving | 6.817 → 6.338 | -7.02 % | 10.618 → 9.759 | -0.859 |
Les six comparaisons respectent les seuils : médiane ≤ +5 %, P95 ≤ +2 ms.
Le cas limitant est la grande surface OpenGL (+4,73 %, +0,248 ms).
Les compilations de sections sont mesurées sur le parcours en mouvement :
| Moteur | Sections OFF / ON | Médiane OFF → ON (ms) | P95 OFF → ON (ms) |
| --- | ---: | --- | --- |
| vulkan | 222 / 220 | 1.889 → 2.186 | 4.307 → 4.898 |
| opengl | 222 / 220 | 1.528 → 1.540 | 5.492 → 5.227 |
Pour reproduire, avec Java 25 et un environnement graphique disponible :
@@ -115,7 +155,55 @@ assembleTestPack -x :sanctuary:runGameTest` ; la suite complète non exclue
n’est pas déclarée réussie. Les contrôles natifs de l’eau utilisent le serveur
intégré d’un monde jetable. Aucun essai Windows n’est revendiqué.
La release, le canal et l’instance ne sont pas encore mis à jour.
L’assemblage avec l’exclusion ci-dessus a réussi en 2 min 33 s (126 tâches).
`python3 scripts/pack.py check` réussit. Les cinq archives passent le contrôle
ZIP ; les deux MRpack embarquent exactement le même JAR Sanctuary et déclarent
Fabric API 0.160.5+26.3 avec l’empreinte du manifeste source. L’export MRpack est
exécuté depuis chaque dossier de staging packwiz. Les dépendances imbriquées
Demeure et JEI sont vérifiées par l’assemblage natif du dépôt.
[Release beta.144](https://git.botsu.net/koka/sanctuary-beta/releases/tag/beta.144) publiée depuis
le commit source `83c377acc1b5a4d4137d7a93c397531f77915303` ; tag exact `beta.144`.
Canal packwiz stable : `c8e28d878a55703bdc28fc046242b42b2fcfa9f6`.
Deux synchronisations isolées puis deux synchronisations de l’instance
**Sanctuary Beta** ont réussi, jeu et lanceur fermés. Les secondes passes sont
idempotentes. Un seul JAR Sanctuary est actif, et son SHA-256 correspond
exactement à celui de la release et du manifeste stable.
Les **923 fichiers personnels** suivis (sauvegardes, configurations,
packs, captures et mods non gérés) ont conservé leurs empreintes. Aucun monde
personnel ouvert. Sauvegarde des fichiers remplacés :
`sanctuary-backups/before-beta.144/`.
Les neuf liens publics (cinq livrables, trois captures, manifeste SHA-256)
ont été retéléchargés anonymement et leurs empreintes comparées. Les reçus de
publication, de téléchargement et des quatre synchronisations restent dans
`build/water144-publish.log`, `build/water144-public-downloads.json`,
`build/water144-isolated.json` et `build/water144-prism.json`.
Le checkout initial beta.122 et ses modifications restent préservés.
Les sources sont sur `codex/water-beta144`, dans le worktree isolé.
Les archives vérifiées sont aussi copiées dans `sanctuary-beta/build/`.
Les preuves détaillées restent dans les dossiers ignorés :
`build/water144-*.log`, `build/water144-*-performance.json`,
`build/water144-*-isolation.json` et `build/water144-evidence/`.
## Artefacts vérifiés
| Artefact | Octets | SHA-256 |
| --- | ---: | --- |
| [sanctuary-beta.144.jar](https://git.botsu.net/koka/sanctuary-beta/releases/download/beta.144/sanctuary-beta.144.jar) | 11343257 | `1ddbe941f3262da8a1497ea5df4a992e260b80ae95b341623dd68f8f9729ae88` |
| [Sanctuary-beta.144.mrpack](https://git.botsu.net/koka/sanctuary-beta/releases/download/beta.144/Sanctuary-beta.144.mrpack) | 10483196 | `d5ef5a781f5ee796117210d1f6afc96172461315faee34097323beff541ce6f0` |
| [Sanctuary-Test-beta.144.mrpack](https://git.botsu.net/koka/sanctuary-beta/releases/download/beta.144/Sanctuary-Test-beta.144.mrpack) | 10502119 | `e7cc32ac19ae98ebbe7a9aac3dc08decdf09396c8175b597f87051399ff3812e` |
| [Sanctuary-Template-beta.144.zip](https://git.botsu.net/koka/sanctuary-beta/releases/download/beta.144/Sanctuary-Template-beta.144.zip) | 4354678 | `e510c0040dc9053492715ac91381b7dbc5a6f7c7defbf81e7502d8e18dbb0ee6` |
| [Sanctuary-Prism-auto-update.zip](https://git.botsu.net/koka/sanctuary-beta/releases/download/beta.144/Sanctuary-Prism-auto-update.zip) | 92423 | `c0920823f40d709c14e074d8d949f2cc3681c24140bf86f21c3be345cfc3e1f6` |
## Captures comparatives
Pièces jointes de la release, issues du client Vulkan de validation :
[OFF](https://git.botsu.net/koka/sanctuary-beta/releases/download/beta.144/Sanctuary-beta.144-water-off.png),
[ON](https://git.botsu.net/koka/sanctuary-beta/releases/download/beta.144/Sanctuary-beta.144-water-on.png),
[profil étang en proximité](https://git.botsu.net/koka/sanctuary-beta/releases/download/beta.144/Sanctuary-beta.144-water-pond.png).
Les captures sont exportées à 854×480 ; la cible de présentation mesurée est
1708×960. Le [manifeste SHA-256](https://git.botsu.net/koka/sanctuary-beta/releases/download/beta.144/Sanctuary-beta.144-SHA256SUMS.txt) inclut les cinq
livrables et ces trois captures. Les journaux et échantillons détaillés restent
locaux, dans `build/water144-evidence/` et les reçus `build/water144-*.json`.
+12 -6
View File
@@ -14,13 +14,19 @@ JAR Sanctuary sont des pièces jointes de releases Gitea. Aucun JAR de mod ou
dépendance téléchargée n'entre dans l'historique Git. Le canal Beta est distinct
de l'ancien pack 26.2.
## beta.144 — Eau naturelle pixélisée (préparation)
## beta.144 — Eau naturelle pixélisée
Trois profils de couleur/transparence selon le fond, océans clairs et brume
aquatique adaptée. Le [ticket de livraison](natural-water-beta144.md) décrit
la teinte olive retenue, les contrôles et le protocole de performance.
La publication et la synchronisation attendent la validation finale isolée.
Les textures restent à beta.121 ; Minecraft 26.3 et les dépendances sont conservés.
Trois profils selon le fond, teinte olive d’étang, océans natifs clairs et
brume aquatique adaptée. [Contrat, captures et mesures](natural-water-beta144.md).
[Release beta.144](https://git.botsu.net/koka/sanctuary-beta/releases/tag/beta.144)
publiée depuis `83c377acc1b5a4d4137d7a93c397531f77915303` ; canal
`c8e28d878a55703bdc28fc046242b42b2fcfa9f6`. Deux synchronisations isolées puis deux
dans l’instance Sanctuary Beta réussies et idempotentes. Un seul JAR Sanctuary
actif, identique à l’artefact public. Les 923 fichiers personnels suivis gardent
leurs empreintes ; aucun monde personnel ouvert. Sauvegarde préalable :
`sanctuary-backups/before-beta.144/`. Les cinq livrables et leurs SHA-256 sont
vérifiés dans `sanctuary-beta/build/`. Textures beta.121, Minecraft 26.3 et
dépendances exactes conservés.
## beta.143 — Neige saisonnière en temps réel
-221
View File
@@ -1,221 +0,0 @@
# PBR-SSR — eau, verre et reflets pixélisés
Livraison locale **beta.145**, branche `codex/pbr-ssr`. Socle PBR beta.142 /
suivi beta.143 et copie figée des sources du chantier d’eau beta.144. Minecraft 26.3, API graphique native.
## Contrat
Les reflets colorent les texels de matière sur une grille 16 × 16 liée aux UV,
avec les normales procédurales existantes. Eau et verre sont diélectriques.
L’eau reprend les faces du tessellateur natif (niveaux, pentes, écoulements,
waterlogging), sans modification de géométrie ni simulation de vagues.
Le verre réfléchit aussi sur les zones sans pigment de sa texture. Les pixels
pigmentés conservent leur relief même avec un alpha faible ; l’alpha nul
utilise la normale géométrique.
Les images des normales d’eau sont préparées au chargement du matériau ; leur
séquence suit l’horloge effective des animations de l’atlas, avec interpolation.
Seules les petites tuiles de normales changent sur le GPU, pas le maillage.
Les normales des textures haute résolution sont rééchantillonnées à 16 × 16.
Au-delà de 1 024 images par sprite, un avertissement signale le repli vers
une normale fixe pour borner la mémoire.
L’option FR/EN « Reflets du paysage — expérimental » est OFF initialement,
intensité 50 %, bornée entre 0 et 100. Elle exige le PBR actif. L’eau naturelle
reste indépendante pour ses couleurs, sa transparence et sa brume.
## Pipeline et limites
Couleur et profondeur du paysage sont copiées après les opaques et avant les
transparences, dans les deux chemins natifs. Le chemin classique ferme la passe
opaque avant la copie, puis reprend la transparence native dans une nouvelle
passe. Aucune copie d’attachement Vulkan encore ouvert.
Une profondeur propre sélectionne le récepteur PBR le plus proche devant le
paysage opaque. Une vitre devant l’eau reçoit seule le SSR ; les couches
suivantes conservent leur rendu natif. La profondeur du fond n’est pas utilisée
comme profondeur de surface de l’eau.
8 à 32 pas déterministes adaptés à la longueur écran, puis quatre raffinements maximum, récepteurs jusqu’à
32 blocs et rayons jusqu’à 128 blocs. Pas de bruit aléatoire, historique,
réflexion récursive, réfraction nouvelle, lecture GPU vers CPU ou ajout de
lumière de gameplay. Les objets hors écran ou masqués ne sont pas retrouvés. Les détails fins entre
deux pas peuvent être manqués ; une interpolation finale affine le point
d’intersection sans augmenter le nombre de recherches.
Un échec revient progressivement au rendu existant ; les transparences et les
effets Sanctuary postérieurs à la capture ne figurent pas dans le reflet.
Les reflets sont composés après le SSGI, avant contours, bloom et rayons.
La main et le HUD restent en dehors du traitement. Le PBR conserve son
périmètre Overworld hors immersion et s’efface avec les moteurs externes.
Budget de maillages : 24 Mio de solides, 8 Mio supplémentaires de transparences.
Deux profondeurs plein écran servent aux surfaces PBR ; la couleur de paysage
SSR est allouée seulement à ON/intensité positive. La copie de composition PBR
existante est réutilisée. Aucun buffer de normales plein écran.
La grille visuelle ne signifie pas qu’un seul fragment GPU est exécuté par texel.
## Intégration
Le commit `38f4d6c` apporte le SSR et les récepteurs transparents. Le commit
`0cfd51e` importe une copie contrôlée des sources beta.144 depuis le chantier
`codex/water-beta144`, fondé sur `580b241`. Les empreintes des fichiers ont été
comparées avant et après la copie ; le reçu local est dans
`build/water144-snapshot/manifest.json`. Cette intégration ne prétend pas que
beta.144 a été publiée ou que son benchmark isolé est terminé. Le code de
production de cet instantané est identique à celui du commit
`7eef945` ensuite créé sur la branche d’eau. Les essais ci-dessous portent
sur les sources réunies dans cette branche.
Points d’entrée : `PbrMaterials` et `PbrAnimation` pour les normales animées,
`PbrFluidMesh` pour le tessellateur natif, `PbrTerrain` pour les deux budgets,
`ReflectionSceneMixin` pour la capture opaque, `PixelReflections` et
`pixel_reflections.fsh` pour la sélection et le rayon. Les horloges de sprites
sont référencées faiblement des deux côtés afin de ne pas retenir les anciens
atlas après rechargement.
## Vérifications
Machine : Apple M1, Minecraft 26.3, Java 25, macOS. Mondes plats de test neufs,
graine 122 ; aucune sauvegarde personnelle utilisée. Les captures conservent
le préfixe historique `sanctuary-beta142-shader` du banc de test.
- Client OpenGL 4.1 Metal 90.5, transparence classique : suite SSR réussie avec les sources d’eau
intégrées (`build/ssr145-opengl-final.log`).
- Client Vulkan/MoltenVK : suite SSR avec transparence améliorée réussie
(`build/ssr145-vulkan-final.log`).
- Régression du PBR historique et nouvelles assertions de profils, normales
transparentes, persistance, bornes et traductions SSR : réussies
(`build/ssr145-pbr-regression-retry.log`). Une première tentative interrompue
s’était arrêtée sur un timeout de sémaphore Vulkan ; elle reste un échec
consigné dans `build/ssr145-pbr-regression.log`.
- Suite fonctionnelle eau beta.144 : réussie, y compris profils, fond modifié,
brume, océan, rechargement, préférences, cascades et pack de matériaux
(`build/ssr145-water-functional.log`). Son long benchmark autonome a été
explicitement sauté ; le coût SSR est mesuré séparément ci-dessous.
- Le relief rouge puis bleu produit deux contributions de couleur distinctes
dans le bassin ; caché par un mur opaque, ce changement ne traverse pas le mur.
- Eau animée sans nouvelle analyse de texture, verre transparent devant l’eau,
métal, déplacement minime de caméra, rotation, OFF/zéro, immersion,
rechargement de ressources et redimensionnement sont exercés par assertions.
L’horloge d’eau reste active après rechargement ; les profils sable et étang
restent corrects avec PBR et SSR simultanément actifs.
- Des captures couvrent également les effets combinés, la lune, les angles
rasants, la translation de caméra, la sortie du paysage hors écran, la pierre
rugueuse OFF/ON, des vitres colorées superposées, un écoulement, une cascade
et une dalle gorgée d’eau. Elles ne remplacent pas une inspection
artistique de tous les angles et de tous les packs.
Captures locales OpenGL : [OFF](../build/ssr-evidence/beta145-opengl-final/0000_sanctuary-beta142-shader-ssr-water-off.png),
[ON](../build/ssr-evidence/beta145-opengl-final/0001_sanctuary-beta142-shader-ssr-water-on.png).
Le dossier `build/ssr-evidence/beta145-opengl-final/` contient les autres captures.
Les mêmes cas Vulkan sont conservés dans
`build/ssr-evidence/beta145-vulkan-final/`. Les comparaisons eau, métal et
verre empilé ont été inspectées visuellement. Ces pièces sont ignorées par Git.
## Coût mesuré
1920 × 1080, PBR à 80 %, SSR à 100 % pour accentuer le résultat, VSync OFF,
limite de FPS et réduction AFK désactivées. Chaque scène chauffe 30 ticks par
état avant 80 ticks de mesure, soit 324 à 483 images pour OpenGL et 317 à 477 pour Vulkan. Ordre OFF puis
ON ; il s’agit d’un diagnostic local court, pas d’une campagne statistique.
Le temps de frame mesure `Minecraft.renderFrame`, présentation comprise.
| OpenGL | Médiane OFF / ON (ms) | p95 OFF / ON (ms) | Écart médian |
| --- | --- | --- | --- |
| Petit étang | 7,57 / 9,42 | 10,35 / 12,50 | +1,85 ms |
| Eau dominante | 7,76 / 11,67 | 10,67 / 13,96 | +3,91 ms |
| Construction vitrée | 7,85 / 10,12 | 10,67 / 12,65 | +2,27 ms |
| Vulkan | Médiane OFF / ON (ms) | p95 OFF / ON (ms) | Écart médian |
| --- | --- | --- | --- |
| Petit étang | 7,97 / 10,36 | 8,97 / 11,49 | +2,40 ms |
| Eau dominante | 10,10 / 12,23 | 10,97 / 12,97 | +2,13 ms |
| Construction vitrée | 8,52 / 11,25 | 9,49 / 12,20 | +2,72 ms |
La mesure GPU Vulkan autour de `PixelReflections.render` donne, à ON,
**2,07 / 2,18 ms** (médiane / p95) pour l’étang, **2,56 / 2,63 ms** pour
l’eau dominante et **2,09 / 2,21 ms** pour le verre. À OFF, la sonde mesure
0,03 ms environ. Ce périmètre couvre la copie de composition et le dessin
SSR ; il exclut la capture opaque antérieure et la profondeur partagée PBR.
La sonde utilise les valeurs rendues par la requête native, pas une mesure
GPU du jeu complet.
La requête GPU native ne fournit pas de mesure exploitable sur ce pilote
OpenGL ; ce champ est indisponible, pas nul. Les premiers essais contaminés
par la réduction AFK à 30 FPS sont exclus des résultats retenus.
**L’objectif de surcoût médian inférieur à 2 ms n’est pas respecté dans l’ensemble des
scènes.** L’option reste expérimentale et désactivée par défaut.
À 1080p : profondeurs partagées par le PBR = 15,82 Mio ; copie couleur SSR
supplémentaire = 7,91 Mio, libérée à OFF/zéro. Total de ces cibles à ON :
23,73 Mio. Les maillages observés occupent environ 0,51–0,55 Mio de solides et
1,09–1,21 Mio de transparences, en dessous des plafonds 24 / 8 Mio vérifiés
par assertion. Ces compteurs n’incluent ni la mémoire du moteur, ni la copie
PBR existante, ni les atlas de matériaux de 6,25 Mio chacun ; ce ne sont pas
des mesures de mémoire totale du processus.
## Construction et contrôles généraux
`./gradlew check build` a été exécuté jusqu’au bout : **229 GameTests serveur
réussis sur 252, 23 échecs**, en 8 min 45 s pour la commande complète.
Les échecs concernent les tombes/familiers, le catalogue, deux invariants de
génération, les placements de blocs/progression/construction et les menus
natifs. Les tests concernés et le code de gameplay serveur ne sont pas
modifiés par ce lot. Aucun contre-test de toute la branche de départ n’est
revendiqué. Le journal complet est `build/ssr145-check-build.log` ; le relevé
exhaustif est `build/ssr145-server-failures.json`.
L’assemblage est repris avec `./gradlew check build assemblePack assembleTestPack
-x :sanctuary:runGameTest`, en excluant uniquement cette tâche déjà exécutée.
Cette commande réussit en 2 min 56 s (126 tâches) ; vérification du pack,
compilation, contrôles hors GameTests serveur et assemblages passent. Les
exports MRpack sont produits depuis leurs dossiers packwiz de staging.
L’intégrité ZIP, les métadonnées, les traductions et mixins SSR ainsi que
l’identité du JAR embarqué dans les deux packs sont contrôlées.
Cette exclusion ne transforme pas le contrôle complet en succès.
## Reproduire les essais client
Base de chaque commande :
```sh
./gradlew :sanctuary:runClientGameTest \
-PsanctuaryClientTests=true -PsanctuaryQuickTests=true \
-PsanctuaryPbr134ClientTests=true -PsanctuaryClientNoVsync=true
```
- SSR Vulkan : ajouter `-PsanctuarySsrClientTests=true
-PsanctuaryClientGraphicsBackend=vulkan -PsanctuaryClientImprovedTransparency=true`.
- SSR OpenGL : ajouter `-PsanctuarySsrClientTests=true
-PsanctuaryClientGraphicsBackend=opengl -PsanctuaryClientImprovedTransparency=false`.
- Régression PBR : ajouter uniquement `-PsanctuaryClientGraphicsBackend=vulkan`.
- Profils et rendu de l’eau : ajouter `-PsanctuaryWater144ClientTests=true
-PsanctuaryWater144FunctionalOnly=true -PsanctuaryClientGraphicsBackend=vulkan`.
Le mode fonctionnel saute uniquement le long benchmark autonome beta.144.
Les sondes de temps de frame/GPU et lectures d’images appartiennent au mod
de test ; elles ne sont pas embarquées dans le JAR de production.
## Artefacts locaux
Les archives finales sont rafraîchies depuis le JAR testé, puis revérifiées
(`build/ssr145-artifacts.json`). Aucun tag ni canal n’est publié.
| Artefact | Octets | SHA-256 |
| --- | ---: | --- |
| [sanctuary-beta.145.jar](../mods/sanctuary/build/libs/sanctuary-beta.145.jar) | 11369411 | `55341e2f5c8dcc352190fe96d15e86cd1ee6bb4ea2908441b70491d48f86f608` |
| [Sanctuary-beta.145.mrpack](../build/Sanctuary-beta.145.mrpack) | 10508045 | `8bebe6227cbfe629c714a7c7547640ab5ccfbefaaf211484a93c042cfb42b5c5` |
| [Sanctuary-Test-beta.145.mrpack](../build/Sanctuary-Test-beta.145.mrpack) | 10526966 | `54402ff8414ed1ae0d12b3b97af70c547c44dde2f3aa183712ae3769f99efbe7` |
| [Sanctuary-Template-beta.145.zip](../build/Sanctuary-Template-beta.145.zip) | 4358316 | `226d92362a5ce922b8757b36f30c312081aca5cf73a299b82a221a12f384a95b` |
## Limites de validation
Le banc utilise un relief construit reproductible, pas une montagne générée
représentative de tous les biomes. La validation artistique sur terrain généré,
les textures personnalisées avec ordre/durées/interpolation atypiques et la
stabilité sur un long trajet restent à compléter. Les surfaces peuvent perdre les petits détails entre
les pas SSR et les zones hors écran ne sont jamais reconstruites. Windows,
autres GPU et moteurs graphiques externes ne sont pas validés ici.
Aucune publication de canal ni synchronisation Prism dans cette livraison.
+2 -2
View File
@@ -9,8 +9,8 @@ loom_version=1.17.20
fabric_api_version=0.160.5+26.3
# Release counter: beta.001, .002, .003, ... (see docs/versioning.md).
mod_version=beta.145
pack_version=beta.145
mod_version=beta.144
pack_version=beta.144
resource_pack_version=beta.121
maven_group=fr.koka.sanctuary
jei_version=30.32.0-sanctuary.3
-2
View File
@@ -34,10 +34,8 @@ if (clientRenderTests) {
if (improvedTransparency.isPresent()) {
systemProperty('sanctuary.test.improvedTransparency', improvedTransparency.get())
}
systemProperty('sanctuary.test.ssr', providers.gradleProperty('sanctuarySsrClientTests').getOrElse('false'))
systemProperty('sanctuary.test.water144', providers.gradleProperty('sanctuaryWater144ClientTests').getOrElse('false'))
systemProperty('sanctuary.test.water144ExtrasOnly', providers.gradleProperty('sanctuaryWater144ExtrasOnly').getOrElse('false'))
systemProperty('sanctuary.test.water144FunctionalOnly', providers.gradleProperty('sanctuaryWater144FunctionalOnly').getOrElse('false'))
systemProperty('sanctuary.test.water144PerfOnly', providers.gradleProperty('sanctuaryWater144PerfOnly').getOrElse('false'))
systemProperty('sanctuary.test.pbr142', providers.gradleProperty('sanctuaryPbr142ClientTests').getOrElse('false'))
systemProperty('sanctuary.test.directional141Only', providers.gradleProperty('sanctuaryDirectional141Only').getOrElse('false'))
@@ -57,27 +57,12 @@ public final class Pbr134ClientChecks implements FabricClientGameTest {
for(int p:PbrMaterials.generate(flat,4,4,profile))check((p>>8&0xFFFF)==0x8080,"Flat source has neutral normal");
flat[5]=0xFFFFFFFF;var slope=PbrMaterials.generate(flat,4,4,profile);check((slope[4]>>16&255)<128&&(slope[6]>>16&255)>128,"Height gradients produce opposite normal slopes");
check(PbrMaterials.profile("iron_block").metal()>.8&&PbrMaterials.profile("iron_ore").metal()==0,"Metal block profile does not turn ore host rock into metal");
check(PbrMaterials.family(Blocks.WATER.defaultBlockState())==2&&PbrMaterials.family(Blocks.GLASS.defaultBlockState())==1&&PbrMaterials.family(Blocks.GLASS_PANE.defaultBlockState())==1,"Water and glass receiver families");
check(PbrMaterials.profile("water").metal()==0&&PbrMaterials.profile("glass").metal()==0,"Water and glass stay dielectric");
int[] glass={0x00FFFFFF,0x00000000,0x00000000,0x00FFFFFF};
for(int p:PbrMaterials.generate(glass,2,2,PbrMaterials.profile("glass")))check((p>>8&0xFFFF)==0x8080,"Transparent glass texels fall back to geometric normal");
check(PbrMaterials.profile("oak_planks").roughness()>PbrMaterials.profile("polished_andesite").roughness(),"Wood remains rougher than polished stone");
}
private static void preferences(){try{
var p=FabricLoader.getInstance().getConfigDir().resolve("sanctuary-shaders.json");Files.writeString(p,"{\"ssgi\":true,\"ssgiIntensity\":35,\"bloom\":false}");forgetPreferences();
check(VanillaLight.pbr()&&VanillaLight.pbrIntensity()==80&&VanillaLight.ssgi()&&!VanillaLight.bloom(),"Missing PBR setting defaults ON while preserving explicit old choices");
for(int n:new int[]{-1,0,50,100,101}){VanillaLight.setPbr(true);VanillaLight.setPbrIntensity(n);forgetPreferences();check(VanillaLight.pbr()&&VanillaLight.pbrIntensity()==Math.clamp(n,0,100),"PBR preference persistence/clamp");}
check(!VanillaLight.ssr()&&VanillaLight.ssrIntensity()==50,"Missing SSR defaults OFF at 50 percent");
for(int n:new int[]{-1,0,50,100,101}){VanillaLight.setSsr(true);VanillaLight.setSsrIntensity(n);forgetPreferences();check(VanillaLight.ssr()&&VanillaLight.ssrIntensity()==Math.clamp(n,0,100),"SSR preference persistence/clamp");}
VanillaLight.setSsr(false);VanillaLight.setSsrIntensity(50);forgetPreferences();check(!VanillaLight.ssr(),"SSR OFF persists");
var manager=net.minecraft.client.Minecraft.getInstance().getLanguageManager();var oldLanguage=manager.getSelected();
for(String locale:new String[]{"fr_fr","en_us"}){
manager.setSelected(locale);manager.onResourceManagerReload(net.minecraft.client.Minecraft.getInstance().getResourceManager());
for(String key:new String[]{"ssr","ssr_help","ssr_intensity","ssr_intensity_help","ssr_intensity_value"}){
String full="sanctuary.shaders."+key;check(!net.minecraft.network.chat.Component.translatable(full,50).getString().equals(full),"SSR FR/EN "+full);
}
}
manager.setSelected(oldLanguage);manager.onResourceManagerReload(net.minecraft.client.Minecraft.getInstance().getResourceManager());
VanillaLight.setPbrIntensity(50);
}catch(Exception e){throw new AssertionError(e);}}
private record Delta(int changed,int brighter,int darker,long total){}
@@ -1,156 +0,0 @@
package fr.koka.sanctuary.client.shader;
import static fr.koka.sanctuary.client.shader.PixelShadows122ClientChecks.*;
import net.fabricmc.fabric.api.client.gametest.v1.context.ClientGameTestContext;
import net.fabricmc.fabric.api.client.gametest.v1.context.TestServerContext;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.block.Blocks;
/** Native screenshots on a new development world; source-colour and transparent receiver checks. */
final class PixelReflectionsClientChecks {
static void run(ClientGameTestContext c,TestServerContext server){
c.runOnClient(m->{VanillaLight.setEnabled(true);VanillaLight.setSaturation(100);VanillaLight.setPbr(true);VanillaLight.setPbrIntensity(80);
VanillaLight.setNaturalWater(true);VanillaLight.setWaterIntensity(100);VanillaLight.setSsr(false);VanillaLight.setSsrIntensity(100);VanillaLight.setColoredLights(false);VanillaLight.setSsgi(false);
VanillaLight.setSunshafts(false);VanillaLight.setLensFlare(false);VanillaLight.setBloom(false);VanillaLight.setOreEmission(false);
VanillaLight.setEdgeHighlights(false);VanillaLight.setPixelShadows(false);});
server.runOnServer(s->{
command(s,"time set 6000");
for(int x=-18;x<=18;x++)for(int z=-4;z<=24;z++){
for(int y=65;y<=85;y++)s.overworld().setBlockAndUpdate(new BlockPos(x,y,z),Blocks.AIR.defaultBlockState());
s.overworld().setBlockAndUpdate(new BlockPos(x,64,z),Blocks.STONE.defaultBlockState());
if(z>=3&&z<=18)s.overworld().setBlockAndUpdate(new BlockPos(x,65,z),Blocks.WATER.defaultBlockState());
}
for(int x=-12;x<=12;x++)for(int y=65;y<=77-Math.abs(x)/2;y++)
s.overworld().setBlockAndUpdate(new BlockPos(x,y,19),Blocks.CONCRETE.red().defaultBlockState());
});
camera(c,server,.5,68,0,70);look(c,server,0,12);settle(c);
int analysis=c.computeOnClient(m->ProceduralPbr.waterAnalyses()),updates=c.computeOnClient(m->ProceduralPbr.waterUpdates());
c.waitTicks(20);c.runOnClient(m->check(ProceduralPbr.waterAnalyses()==analysis&&ProceduralPbr.waterUpdates()>updates,"Water normals follow native animation without reanalysis"));
var off=capture(c,"ssr-water-off");
c.runOnClient(m->VanillaLight.setSsr(true));frames(c);var on=capture(c,"ssr-water-on");
dumpLandscape(c);
long changed=changed(off,on);System.out.println("SSR_WATER_DIFF "+changed);
check(changed>100,"SSR changes water receiver pixels: "+changed);
double redSignal=colourSignal(off,on);
server.runOnServer(s->{for(int x=-12;x<=12;x++)for(int y=65;y<=77-Math.abs(x)/2;y++)s.overworld().setBlockAndUpdate(new BlockPos(x,y,19),Blocks.CONCRETE.blue().defaultBlockState());});
settle(c);c.runOnClient(m->VanillaLight.setSsr(false));c.waitTicks(8);var blueOff=capture(c,"ssr-blue-off");
c.runOnClient(m->VanillaLight.setSsr(true));frames(c);var blueOn=capture(c,"ssr-blue-on");double blueSignal=colourSignal(blueOff,blueOn);
System.out.println("SSR_SOURCE_COLOUR red="+redSignal+" blue="+blueSignal);
check(redSignal>blueSignal+3,"Water reflection follows source colour rather than animation: "+redSignal+" / "+blueSignal);
server.runOnServer(s->{for(int x=-12;x<=12;x++)for(int y=65;y<=77-Math.abs(x)/2;y++)s.overworld().setBlockAndUpdate(new BlockPos(x,y,19),Blocks.CONCRETE.red().defaultBlockState());});settle(c);
c.runOnClient(m->VanillaLight.setSsrIntensity(0));c.waitTicks(8);
check(!c.computeOnClient(m->PixelReflections.applied()||PixelReflections.allocated()),"Zero removes SSR contribution and colour allocation");
c.runOnClient(m->VanillaLight.setSsrIntensity(100));frames(c);
for(var bed:new net.minecraft.world.level.block.Block[]{Blocks.SAND,Blocks.MUD}){
server.runOnServer(s->{for(int x=-18;x<=18;x++)for(int z=3;z<=18;z++){s.overworld().setBlockAndUpdate(new BlockPos(x,63,z),Blocks.STONE.defaultBlockState());s.overworld().setBlockAndUpdate(new BlockPos(x,64,z),bed.defaultBlockState());}});
settle(c);frames(c);
c.runOnClient(m->check(NaturalWater.sample(m.level,.5,65.5,8.5).equals(bed==Blocks.SAND?NaturalWater.LIGHT:NaturalWater.POND),"Natural water profile remains independent of PBR and SSR: "+NaturalWater.sample(m.level,.5,65.5,8.5)+" above "+m.level.getBlockState(new BlockPos(0,64,8))));
capture(c,bed==Blocks.SAND?"ssr-sand-profile":"ssr-pond-profile");
}
server.runOnServer(s->{for(int x=-18;x<=18;x++)for(int z=3;z<=18;z++)s.overworld().setBlockAndUpdate(new BlockPos(x,64,z),Blocks.STONE.defaultBlockState());});settle(c);frames(c);
for(float yaw:new float[]{-25,0,25}){look(c,server,yaw,12);frames(c);capture(c,"ssr-water-angle-"+(int)yaw);}
look(c,server,0,2);frames(c);capture(c,"ssr-grazing");
look(c,server,75,12);frames(c);capture(c,"ssr-landscape-offscreen");
camera(c,server,2.5,68,0,70);look(c,server,0,12);settle(c);frames(c);capture(c,"ssr-translated");
camera(c,server,.5,68,0,70);look(c,server,0,12);settle(c);
// A hidden landscape must not leak through an opaque foreground wall.
server.runOnServer(s->{for(int x=-12;x<=12;x++)for(int y=65;y<=78;y++)s.overworld().setBlockAndUpdate(new BlockPos(x,y,18),Blocks.CONCRETE.white().defaultBlockState());});
settle(c);c.runOnClient(m->VanillaLight.setSsr(false));c.waitTicks(8);var coveredOff=capture(c,"ssr-covered-off");
c.runOnClient(m->VanillaLight.setSsr(true));frames(c);var coveredOn=capture(c,"ssr-covered-on");
double coveredSignal=colourSignal(coveredOff,coveredOn);
server.runOnServer(s->{for(int x=-12;x<=12;x++)for(int y=65;y<=77-Math.abs(x)/2;y++)s.overworld().setBlockAndUpdate(new BlockPos(x,y,19),Blocks.CONCRETE.blue().defaultBlockState());});settle(c);
c.runOnClient(m->VanillaLight.setSsr(false));c.waitTicks(8);var hiddenBlueOff=capture(c,"ssr-hidden-blue-off");
c.runOnClient(m->VanillaLight.setSsr(true));frames(c);var hiddenBlueOn=capture(c,"ssr-hidden-blue-on");
double hiddenBlueSignal=colourSignal(hiddenBlueOff,hiddenBlueOn);
check(Math.abs(coveredSignal-hiddenBlueSignal)<1.5,"Hidden landscape colour cannot leak through opaque wall: "+coveredSignal+" / "+hiddenBlueSignal);
server.runOnServer(s->{for(int x=-12;x<=12;x++){
for(int y=65;y<=78;y++)s.overworld().setBlockAndUpdate(new BlockPos(x,y,18),Blocks.AIR.defaultBlockState());
for(int y=65;y<=77-Math.abs(x)/2;y++)s.overworld().setBlockAndUpdate(new BlockPos(x,y,19),Blocks.CONCRETE.red().defaultBlockState());
}});settle(c);frames(c);
benchmark(c,"pond");
look(c,server,0,35);frames(c);benchmark(c,"water-fullscreen");look(c,server,0,12);frames(c);
// The nearest glass layer must replace the water receiver, including alpha-zero glass texels.
server.runOnServer(s->{for(int x=-7;x<=7;x++)for(int z=4;z<=14;z++)s.overworld().setBlockAndUpdate(new BlockPos(x,66,z),Blocks.GLASS.defaultBlockState());});
settle(c);capture(c,"ssr-glass-over-water");
c.runOnClient(m->VanillaLight.setSsr(false));c.waitTicks(8);var glassOff=capture(c,"ssr-glass-off");
c.runOnClient(m->VanillaLight.setSsr(true));frames(c);var glassOn=capture(c,"ssr-glass-on");
check(changed(glassOff,glassOn)>100,"Transparent glass reflects landscape");
benchmark(c,"glass");
server.runOnServer(s->{for(int x=-7;x<=7;x++)for(int z=4;z<=14;z++)s.overworld().setBlockAndUpdate(new BlockPos(x,66,z),Blocks.IRON_BLOCK.defaultBlockState());});
settle(c);c.runOnClient(m->VanillaLight.setSsr(false));c.waitTicks(8);var metalOff=capture(c,"ssr-metal-off");
c.runOnClient(m->VanillaLight.setSsr(true));frames(c);var metalOn=capture(c,"ssr-metal-on");
check(changed(metalOff,metalOn)>100,"Solid PBR reflects landscape");
look(c,server,.00002f,12.00002f);frames(c);var tiny=capture(c,"ssr-metal-tiny-motion");
check(stableMetal(metalOn,tiny),"Tiny camera movement keeps material texels stable");look(c,server,0,12);frames(c);
c.runOnClient(m->{VanillaLight.setPixelShadows(true);VanillaLight.setSsgi(true);VanillaLight.setColoredLights(true);VanillaLight.setBloom(true);VanillaLight.setSunshafts(true);});
frames(c);capture(c,"ssr-combined");
server.runOnServer(s->command(s,"time set 18000"));c.waitTicks(15);frames(c);capture(c,"ssr-moon");
server.runOnServer(s->command(s,"time set 6000"));c.waitTicks(15);frames(c);
c.runOnClient(m->{VanillaLight.setPixelShadows(false);VanillaLight.setSsgi(false);VanillaLight.setColoredLights(false);VanillaLight.setBloom(false);VanillaLight.setSunshafts(false);});
server.runOnServer(s->{for(int x=-7;x<=7;x++)for(int z=4;z<=14;z++)s.overworld().setBlockAndUpdate(new BlockPos(x,66,z),Blocks.STONE.defaultBlockState());});
settle(c);c.runOnClient(m->VanillaLight.setSsr(false));c.waitTicks(8);capture(c,"ssr-rough-stone-off");
c.runOnClient(m->VanillaLight.setSsr(true));frames(c);capture(c,"ssr-rough-stone-on");
// Native panes, sloped water, cascade sides and a waterlogged slab share the receiver pass.
server.runOnServer(s->{
for(int y=66;y<=69;y++)s.overworld().setBlockAndUpdate(new BlockPos(-8,y,8),Blocks.GLASS_PANE.defaultBlockState());
s.overworld().setBlockAndUpdate(new BlockPos(8,69,8),Blocks.WATER.defaultBlockState());
s.overworld().setBlockAndUpdate(new BlockPos(-8,65,10),Blocks.OAK_SLAB.defaultBlockState().setValue(net.minecraft.world.level.block.state.properties.BlockStateProperties.WATERLOGGED,true));
});settle(c);frames(c);capture(c,"ssr-flow-pane-waterlogged");
server.runOnServer(s->{command(s,"fill -3 66 6 3 69 6 glass");command(s,"fill -3 66 8 3 69 8 light_blue_stained_glass");
command(s,"setblock -4 67 6 blue_stained_glass_pane");});
settle(c);c.runOnClient(m->VanillaLight.setSsr(false));c.waitTicks(8);capture(c,"ssr-stacked-coloured-glass-off");
c.runOnClient(m->VanillaLight.setSsr(true));frames(c);capture(c,"ssr-stacked-coloured-glass-on");
camera(c,server,12,64,8,70);look(c,server,0,0);c.waitTicks(15);
c.runOnClient(m->check(!PixelReflections.allocated(),"Immersion suspends and releases SSR"));
camera(c,server,.5,68,0,70);look(c,server,0,12);settle(c);frames(c);
var reload=c.computeOnClient(net.minecraft.client.Minecraft::reloadResourcePacks);c.waitFor(m->reload.isDone()&&m.gui.overlay()==null,1200);reload.join();frames(c);capture(c,"ssr-reloaded");
int reloadedUpdates=c.computeOnClient(m->ProceduralPbr.waterUpdates());c.waitTicks(20);
c.runOnClient(m->check(ProceduralPbr.waterUpdates()>reloadedUpdates,"Reloaded atlas supplies a live native water clock"));
int w=c.computeOnClient(m->m.getWindow().getScreenWidth()),h=c.computeOnClient(m->m.getWindow().getScreenHeight());
c.runOnClient(m->m.getWindow().setWindowed(961,541));c.waitTicks(15);frames(c);capture(c,"ssr-resized");
c.runOnClient(m->m.getWindow().setWindowed(w,h));c.waitTicks(15);frames(c);
c.runOnClient(m->VanillaLight.setPbr(false));c.waitTicks(8);c.runOnClient(m->check(!PixelReflections.allocated(),"PBR OFF releases reflection resources"));
System.out.println("SSR_PASS water; transparent glass; solids; OFF/zero; motion; reload; resize");
}
private static boolean stableMetal(Frame a,Frame b){int changes=0,count=0;
for(int y=a.height()*58/100;y<a.height()*68/100;y++)for(int x=a.width()*3/10;x<a.width()*7/10;x++){
int i=y*a.width()+x,aa=a.pixels()[i],bb=b.pixels()[i];count++;
if(Math.abs((aa>>16&255)-(bb>>16&255))+Math.abs((aa>>8&255)-(bb>>8&255))+Math.abs((aa&255)-(bb&255))>12)changes++;
}return changes<count*.02;
}
private static double colourSignal(Frame a,Frame b){long total=0;int count=0;
for(int y=a.height()/2;y<a.height();y++)for(int x=a.width()/4;x<a.width()*3/4;x++){
int i=y*a.width()+x,aa=a.pixels()[i],bb=b.pixels()[i];total+=(bb>>16&255)-(aa>>16&255)-(bb&255)+(aa&255);count++;
}return total/(double)count;
}
private static void benchmark(ClientGameTestContext c,String name){
c.runOnClient(m->{m.options.enableVsync().set(false);m.options.framerateLimit().set(net.minecraft.client.Options.UNLIMITED_FRAMERATE_CUTOFF);
m.options.inactivityFpsLimit().set(net.minecraft.client.InactivityFpsLimit.MINIMIZED);m.getWindow().setWindowed(1920,1080);});
c.waitTicks(20);frames(c);
c.runOnClient(m->check(m.gameRenderer.mainRenderTarget().width==1920&&m.gameRenderer.mainRenderTarget().height==1080,"Benchmark uses 1080p"));
for(boolean on:new boolean[]{false,true}){
c.runOnClient(m->VanillaLight.setSsr(on));c.waitTicks(30);
c.runOnClient(m->fr.koka.sanctuary.gametest.ReflectionMetrics.start());c.waitTicks(80);
var result=c.computeOnClient(m->fr.koka.sanctuary.gametest.ReflectionMetrics.stop());
c.runOnClient(m->{check(ProceduralPbr.solidBytes()<=24L*1024*1024&&ProceduralPbr.transparentBytes()<=8L*1024*1024,"Mesh memory budgets");
System.out.println("SSR_MEMORY "+name+" enabled="+on+" solid="+ProceduralPbr.solidBytes()+" transparent="+ProceduralPbr.transparentBytes()+" targets="+PixelReflections.targetBytes());});
check(result[0]>=30,"Benchmark has enough frame samples");
System.out.println("SSR_BENCH "+name+" enabled="+on+" count="+result[0]+" medianMs="+result[1]+" p95Ms="+result[2]+" gpuCount="+result[3]+" gpuMedianMs="+result[4]+" gpuP95Ms="+result[5]);
}
}
private static void dumpLandscape(ClientGameTestContext c){
var done=new java.util.concurrent.CompletableFuture<Void>();
c.runOnClient(m->{
var src=PixelReflections.landscape();
var target=new com.mojang.blaze3d.pipeline.TextureTarget("SSR test source",src.getWidth(0),src.getHeight(0),com.mojang.renderpearl.api.GpuFormat.RGBA8_UNORM,null);
com.mojang.blaze3d.systems.RenderSystem.getDevice().createCommandEncoder().copyTextureToTexture(src,target.getColorTexture(),0,0,0,0,0,target.width,target.height);
net.minecraft.client.Screenshot.takeScreenshot(target,image->{try(image){image.writeToFile(java.nio.file.Path.of("screenshots/ssr-opaque-source.png"));done.complete(null);}catch(Exception e){done.completeExceptionally(e);}finally{target.destroyBuffers();}});
});c.waitFor(m->done.isDone(),200);done.join();
}
private static long changed(Frame a,Frame b){long n=0;for(int y=a.height()/2;y<a.height();y++)for(int x=0;x<a.width();x++){
int i=y*a.width()+x,aa=a.pixels()[i],bb=b.pixels()[i];
if(Math.abs((aa>>16&255)-(bb>>16&255))+Math.abs((aa>>8&255)-(bb>>8&255))+Math.abs((aa&255)-(bb&255))>8)n++;
}return n;}
private static void frames(ClientGameTestContext c){int start=c.computeOnClient(m->PixelReflections.frames());c.waitFor(m->PixelReflections.applied()&&ProceduralPbr.ready()&&PixelReflections.frames()>start+8,1200);}
private static void settle(ClientGameTestContext c){c.waitTicks(45);c.waitFor(m->m.levelRenderer.hasRenderedAllSections()&&ProceduralPbr.ready(),1200);c.waitTicks(10);}
}
@@ -155,7 +155,6 @@ public final class PixelShadows122ClientChecks implements FabricClientGameTest {
if(coloredOnly){if(Boolean.getBoolean("sanctuary.test.directional141Only")){DirectionalLights141ClientChecks.run(c,server);return;}ColoredLights139ClientChecks.run(c,server);if(Boolean.getBoolean("sanctuary.test.colored140"))ColoredLights140ClientChecks.run(c,server);if(Boolean.getBoolean("sanctuary.test.directional141"))DirectionalLights141ClientChecks.run(c,server);return;}
if(sunshaftOnly){Sunshafts137ClientChecks.run(c,server);return;}
if(closeupOnly){SsgiCloseup135ClientChecks.run(c,server);Pbr134ClientChecks.run(c,server);return;}
if(Boolean.getBoolean("sanctuary.test.ssr")){PixelReflectionsClientChecks.run(c,server);return;}
if(pbrOnly){Pbr134ClientChecks.run(c,server);return;}
if(ssgiOnly){Ssgi132ClientChecks.run(c,server);return;}
if(bloomOnly){Bloom130ClientChecks.run(c,server);return;}
@@ -26,6 +26,7 @@ final class Water144ClientChecks {
});
camera(c,server,72,125,16,70);c.waitTicks(50);settle(c);
if(Boolean.getBoolean("sanctuary.test.water144ExtrasOnly")){
resourceOverride(c);
camera(c,server,88.5,96.2,8.5,70);look(c,server,0,0);c.waitTicks(20);capture(c,"pond-final-fog");
var green=c.computeOnClient(m->new org.joml.Vector4f(m.gameRenderer.gameRenderState().levelRenderState.cameraRenderState.fogData.color));
enable(c,false);var blue=c.computeOnClient(m->new org.joml.Vector4f(m.gameRenderer.gameRenderState().levelRenderState.cameraRenderState.fogData.color));capture(c,"native-final-fog");
@@ -39,6 +40,11 @@ final class Water144ClientChecks {
check(NaturalWater.sample(m.level,88.5,99.1,8.5).equals(NaturalWater.POND),"Mud pond");
check(NaturalWater.sample(m.level,84.5,99.1,8.5).equals(NaturalWater.POND),"Seagrass is not a floor");
check(NaturalWater.sample(m.level,88.5,110.1,8.5).equals(NaturalWater.CLEAR),"No bed in bounded search uses clear");
var unloaded=new BlockPos(1_000_016,96,1_000_016);
check(!NaturalWater.loaded(m.level,unloaded.getX()>>4,unloaded.getZ()>>4),"Fixture region is unloaded");
var missing=new NaturalWater.Region(m.level,62500,5,62500);
check(missing.corner(null,unloaded,0,0).equals(NaturalWater.CLEAR),"Unavailable biome snapshot forces clear without reading missing terrain");
check(!NaturalWater.loaded(m.level,unloaded.getX()>>4,unloaded.getZ()>>4),"Classification does not load chunks");
var boundary=NaturalWater.sample(m.level,80,99.1,8.5);check(boundary.tint()>.1&&boundary.tint()<.85,"Section boundary mixes profiles");
});
enable(c,false);var off=capture(c,"surface-off");enable(c,true);var on=capture(c,"surface-on");
@@ -66,7 +72,20 @@ final class Water144ClientChecks {
check(Math.abs(pondFog/nativeFog-.4)<.01,"Rendered underwater fog distance matches pond profile");capture(c,"immersed-native");enable(c,true);
camera(c,server,72,125,16,70);
server.runOnServer(s->command(s,"fillbiome 80 88 0 95 104 32 minecraft:ocean"));c.waitTicks(35);settle(c);
c.runOnClient(m->check(NaturalWater.sample(m.level,88.5,99.1,8.5).equals(NaturalWater.CLEAR),"Ocean overrides muddy bed"));capture(c,"ocean-over-mud");
c.runOnClient(m->{
check(NaturalWater.sample(m.level,88.5,99.1,8.5).equals(NaturalWater.CLEAR),"Ocean overrides muddy bed");
boolean found=false;
for(int x=72;x<89;x++){
var p=new BlockPos(x,99,8);
if(!NaturalWater.ocean(m.level,p)&&NaturalWater.ocean(m.level,p.east())){
var left=new NaturalWater.Region(m.level,(x>>4)-1,5,-1);
var right=new NaturalWater.Region(m.level,((x+1)>>4)-1,5,-1);
check(left.corner(null,p,1,0).equals(right.corner(null,p.east(),0,0)),"Ocean edge emits identical shared vertices");
found=true;break;
}
}
check(found,"Native ocean boundary exercised");
});capture(c,"ocean-over-mud");
server.runOnServer(s->command(s,"fillbiome 80 88 0 95 104 32 minecraft:plains"));c.waitTicks(30);
var reload=c.computeOnClient(net.minecraft.client.Minecraft::reloadResourcePacks);c.waitFor(m->reload.isDone()&&m.gui.overlay()==null,1200);reload.join();settle(c);capture(c,"resources-reloaded");
resourceOverride(c);
@@ -82,7 +101,7 @@ final class Water144ClientChecks {
c.runOnClient(m->{VanillaLight.setPbr(true);VanillaLight.setSsgi(true);VanillaLight.setBloom(true);VanillaLight.setOreEmission(true);
VanillaLight.setPixelShadows(true);VanillaLight.setColoredLights(true);VanillaLight.setSunshafts(true);VanillaLight.setLensFlare(true);VanillaLight.setEdgeHighlights(true);});
c.waitTicks(80);capture(c,"combined");
if(!Boolean.getBoolean("sanctuary.test.water144FunctionalOnly"))benchmark(c,server);
benchmark(c,server);
extras(c,server);
System.out.println("WATER144_PASS surface, immersion, beds, ocean, section seam, roof, plants, invalidation, reload, preferences, FR/EN and combined rendering");
}
@@ -113,36 +132,76 @@ final class Water144ClientChecks {
camera(c,server,56.5,102,8.5,70);capture(c,"waterlogged-slab");
System.out.println("WATER144_EXTRAS_PASS falling water, unchanged lava and waterlogged slab");
}
private static net.minecraft.client.renderer.texture.SpriteContents waterSprite(net.minecraft.client.Minecraft m,String name){
return m.getAtlasManager().getAtlasOrThrow(net.minecraft.data.AtlasIds.BLOCKS)
.getSprite(net.minecraft.resources.Identifier.withDefaultNamespace("block/"+name)).contents();
}
private static void resourceOverride(ClientGameTestContext c){
int originalWidth=c.computeOnClient(m->waterSprite(m,"water_still").width());
int originalFrames=c.computeOnClient(m->waterSprite(m,"water_still").getUniqueFrames().size());
var directory=c.computeOnClient(m->m.getResourcePackDirectory().resolve("water144-fixture"));
try{
Files.createDirectories(directory.resolve("assets/sanctuary"));
var mod=net.fabricmc.loader.api.FabricLoader.getInstance().getModContainer("sanctuary").orElseThrow();
Files.copy(mod.findPath("resourcepacks/template/pack.mcmeta").orElseThrow(),directory.resolve("pack.mcmeta"),StandardCopyOption.REPLACE_EXISTING);
var textures=directory.resolve("assets/minecraft/textures/block");Files.createDirectories(textures);
try(var pixels=new com.mojang.blaze3d.platform.NativeImage(32,64,false)){
for(int y=0;y<64;y++)for(int x=0;x<32;x++)pixels.setPixel(x,y,((x/4+y/4+y/32)&1)==0?0xd0ffffff:0x80404040);
for(String name:new String[]{"water_still","water_flow"}){
pixels.writeToFile(textures.resolve(name+".png"));
Files.writeString(textures.resolve(name+".png.mcmeta"),"{\"animation\":{\"frametime\":4,\"frames\":[0,1]}}");
}
}
Files.writeString(directory.resolve("assets/sanctuary/water_materials.json"),"{\"light\":[],\"pond\":[\"minecraft:quartz_block\"]}");
}catch(Exception e){throw new AssertionError(e);}
c.runOnClient(m->{var repo=m.getResourcePackRepository();repo.reload();check(repo.addPack("file/water144-fixture"),"Custom materials pack discovered");});
var future=c.computeOnClient(net.minecraft.client.Minecraft::reloadResourcePacks);c.waitFor(m->future.isDone()&&m.gui.overlay()==null,1200);future.join();settle(c);
c.runOnClient(m->{check(NaturalWater.sample(m.level,56.5,99.1,8.5).equals(NaturalWater.POND),"Resource pack replaces material family");
check(NaturalWater.sample(m.level,88.5,99.1,8.5).equals(NaturalWater.CLEAR),"Replacement removes bundled assignment");});
capture(c,"custom-materials");
c.runOnClient(m->{for(String name:new String[]{"water_still","water_flow"}){
var sprite=waterSprite(m,name);check(sprite.width()==32&&sprite.height()==32&&sprite.getUniqueFrames().size()==2,"Custom pixel grid and animation loaded: "+name);
}});
var first=capture(c,"custom-materials");long animated=0;
for(int i=0;i<8;i++){c.waitTicks(1);animated=Math.max(animated,difference(first,capture(c,"custom-animation-"+i)));}
check(animated>100000,"Custom water animation remains visible");
c.runOnClient(m->m.getResourcePackRepository().removePack("file/water144-fixture"));
var restore=c.computeOnClient(net.minecraft.client.Minecraft::reloadResourcePacks);c.waitFor(m->restore.isDone()&&m.gui.overlay()==null,1200);restore.join();settle(c);
c.runOnClient(m->check(NaturalWater.sample(m.level,88.5,99.1,8.5).equals(NaturalWater.POND),"Disabling custom pack restores defaults"));
c.runOnClient(m->{
check(NaturalWater.sample(m.level,88.5,99.1,8.5).equals(NaturalWater.POND),"Disabling custom pack restores defaults");
check(waterSprite(m,"water_still").width()==originalWidth&&waterSprite(m,"water_still").getUniqueFrames().size()==originalFrames,"Native water texture restored");
});
System.out.println("WATER144_TEXTURE_PASS custom 32px still/flow textures, alpha, two animation frames and restoration");
}
private static void benchmark(ClientGameTestContext c,TestServerContext s){
int oldLimit=c.computeOnClient(m->m.options.framerateLimit().get());
var oldInactivity=c.computeOnClient(m->m.options.inactivityFpsLimit().get());
c.runOnClient(m->{m.options.framerateLimit().set(net.minecraft.client.Options.UNLIMITED_FRAMERATE_CUTOFF);m.options.inactivityFpsLimit().set(net.minecraft.client.InactivityFpsLimit.MINIMIZED);});
c.runOnClient(m->{m.options.framerateLimit().set(net.minecraft.client.Options.UNLIMITED_FRAMERATE_CUTOFF);m.options.inactivityFpsLimit().set(net.minecraft.client.InactivityFpsLimit.MINIMIZED);m.getFramerateLimitTracker().setFramerateLimit(net.minecraft.client.Options.UNLIMITED_FRAMERATE_CUTOFF);});
var results=new LinkedHashMap<String,Object>();
try {
for(String scene:new String[]{"mixed","large","moving"}){
if(scene.equals("large")){s.runOnServer(server->{command(server,"fill 31 94 -17 112 100 -17 glass");command(server,"fill 31 94 48 112 100 48 glass");
command(server,"fill 31 94 -17 31 100 48 glass");command(server,"fill 112 94 -17 112 100 48 glass");
command(server,"fill 32 93 -16 111 93 47 quartz_block");command(server,"fill 32 94 -16 111 94 47 sand");command(server,"fill 32 95 -16 111 99 47 water");});c.waitTicks(50);}
if(scene.equals("moving")){
// Test fixture only: prepare water beyond the initial client view so movement really compiles terrain.
s.runOnServer(server->{
command(server,"forceload add 112 -17 288 48");
for(int x=7;x<=18;x++)for(int z=-2;z<=3;z++)server.overworld().getChunk(x,z);
command(server,"fill 112 94 -17 288 100 -17 glass");command(server,"fill 112 94 48 288 100 48 glass");
command(server,"fill 288 94 -17 288 100 48 glass");
for(int x=112;x<288;x+=16){
command(server,"fill "+x+" 93 -16 "+(x+15)+" 93 47 quartz_block");
command(server,"fill "+x+" 94 -16 "+(x+15)+" 94 47 sand");
command(server,"fill "+x+" 95 -16 "+(x+15)+" 99 47 water");
}
});c.waitTicks(80);
}
camera(c,s,72,125,16,70);settle(c);
for(boolean enabled:new boolean[]{false,true,true,false,true,false,false,true}){
camera(c,s,72,125,16,70);enable(c,enabled);c.waitTicks(80);c.runOnClient(m->Water144Metrics.start());
camera(c,s,72,125,16,70);enable(c,enabled);c.waitTicks(80);c.runOnClient(m->{
check(m.getFramerateLimitTracker().getFramerateLimit()==260&&!m.options.enableVsync().get(),"Uncapped native limiter and VSync disabled");
System.out.println("WATER144_CONDITIONS limit="+m.getFramerateLimitTracker().getFramerateLimit()+" throttle="+m.getFramerateLimitTracker().getThrottleReason()+" renderLimit="+m.gameRenderer.gameRenderState().framerateLimit+" surface="+m.windowSurface().currentConfiguration()+" limiterBypass=true");
Water144Metrics.start();});
if(scene.equals("moving")){
for(int i=0;i<200;i++){final int step=i;c.runOnClient(m->{m.player.setPos(48+step*.6,125,16);m.player.setDeltaMovement(net.minecraft.world.phys.Vec3.ZERO);});c.waitTicks(1);}
}else c.waitTicks(200);
@@ -151,6 +210,6 @@ final class Water144ClientChecks {
}
}
try{Files.writeString(Path.of("water144-performance.json"),new com.google.gson.GsonBuilder().setPrettyPrinting().create().toJson(results));}catch(Exception e){throw new AssertionError(e);}
}finally{c.runOnClient(m->{m.options.framerateLimit().set(oldLimit);m.options.inactivityFpsLimit().set(oldInactivity);});}
}finally{c.runOnClient(m->{m.options.framerateLimit().set(oldLimit);m.getFramerateLimitTracker().setFramerateLimit(oldLimit);m.options.inactivityFpsLimit().set(oldInactivity);});}
}
}
@@ -1,13 +0,0 @@
package fr.koka.sanctuary.gametest;
import java.util.ArrayList;
public final class ReflectionMetrics {
private static final ArrayList<Long> samples=new ArrayList<>(),gpu=new ArrayList<>();
public static volatile boolean recording;
public static synchronized void add(long time){if(recording)samples.add(time);}
public static synchronized void gpu(long ns){if(recording)gpu.add(ns);}
public static synchronized void start(){samples.clear();gpu.clear();recording=true;}
public static synchronized double[] stop(){recording=false;var a=samples.stream().mapToLong(Long::longValue).sorted().toArray();
if(a.length==0)throw new AssertionError("No frame timing samples");
var g=gpu.stream().mapToLong(Long::longValue).sorted().toArray();
return new double[]{a.length,a[a.length/2]/1e6,a[Math.min(a.length-1,(int)(a.length*.95))]/1e6,g.length,g.length==0?-1:g[g.length/2]/1e6,g.length==0?-1:g[Math.min(g.length-1,(int)(g.length*.95))]/1e6};}
}
@@ -1,14 +0,0 @@
package fr.koka.sanctuary.gametest.mixin;
import fr.koka.sanctuary.gametest.ReflectionMetrics;
import net.minecraft.client.Minecraft;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(Minecraft.class)
abstract class ReflectionFrameProbeMixin {
@Unique private long sanctuary$reflectionStart;
@Inject(method="renderFrame",at=@At("HEAD")) private void begin(boolean tick,CallbackInfo ci){if(ReflectionMetrics.recording)sanctuary$reflectionStart=System.nanoTime();}
@Inject(method="renderFrame",at=@At("RETURN")) private void end(boolean tick,CallbackInfo ci){if(ReflectionMetrics.recording)ReflectionMetrics.add(System.nanoTime()-sanctuary$reflectionStart);}
}
@@ -1,24 +0,0 @@
package fr.koka.sanctuary.gametest.mixin;
import com.mojang.blaze3d.systems.TimerQuery;
import fr.koka.sanctuary.client.shader.PixelReflections;
import fr.koka.sanctuary.gametest.ReflectionMetrics;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(value=PixelReflections.class,remap=false)
abstract class ReflectionGpuProbeMixin {
@Unique private static TimerQuery sanctuary$query;
@Unique private static boolean sanctuary$started;
@Inject(method="render",at=@At("HEAD")) private static void begin(CallbackInfo ci){
sanctuary$started=false;
if(!ReflectionMetrics.recording){if(sanctuary$query!=null){sanctuary$query.close();sanctuary$query=null;}return;}
if(sanctuary$query==null)sanctuary$query=new TimerQuery();
if(sanctuary$query.getStatus()==TimerQuery.Status.NOT_RECORDING){
long previous=sanctuary$query.get();if(previous>0)ReflectionMetrics.gpu(previous);
sanctuary$query.beginProfile();sanctuary$started=true;
}
}
@Inject(method="render",at=@At("RETURN")) private static void end(CallbackInfo ci){if(sanctuary$started)sanctuary$query.endProfile();}
}
@@ -1,5 +1,6 @@
package fr.koka.sanctuary.gametest.mixin;
import fr.koka.sanctuary.gametest.Water144Metrics;
import com.llamalad7.mixinextras.injector.wrapoperation.*;
import net.minecraft.client.Minecraft;
import org.spongepowered.asm.mixin.*;
import org.spongepowered.asm.mixin.injection.*;
@@ -7,6 +8,10 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(Minecraft.class)
abstract class Water144FrameProbeMixin {
@Unique private long sanctuary$start;
// Benchmark only: the extracted frame state can retain a 120 FPS limit despite the option/tracker.
@WrapOperation(method="renderFrame",at=@At(value="INVOKE",target="Lnet/minecraft/client/FramerateLimiter;limitDisplayFPS(I)V"))
private void sanctuary$uncapped(int fps,Operation<Void> original){if(!Water144Metrics.recording)original.call(fps);}
@Inject(method="renderFrame",at=@At("HEAD")) private void start(boolean tick,CallbackInfo ci){if(Water144Metrics.recording)sanctuary$start=System.nanoTime();}
@Inject(method="renderFrame",at=@At("RETURN")) private void end(boolean tick,CallbackInfo ci){if(Water144Metrics.recording)Water144Metrics.frame(System.nanoTime()-sanctuary$start);}
}
@@ -10,8 +10,6 @@
"defaultRequire": 1
},
"client": [
"ReflectionFrameProbeMixin",
"ReflectionGpuProbeMixin",
"Colored139LightmapProbeMixin",
"Fourneau094ParticleProbeMixin",
"Tooltip093FontProbeMixin",
@@ -81,7 +81,11 @@ public final class NaturalWater {
}
public static float strength(){return strength;}
public static Profile fogProfile(){return fogFrom.mix(fogTarget,Math.clamp((System.nanoTime()-fogChanged)/500_000_000f,0,1));}
public static boolean ocean(ClientLevel level,BlockPos pos){return level.hasChunk(pos.getX()>>4,pos.getZ()>>4)&&level.getBiome(pos).is(BiomeTags.IS_OCEAN);}
// ClientLevel.hasChunk always returns true; inspect the cache without requesting a chunk.
public static boolean loaded(ClientLevel level,int x,int z){
return level.getChunkSource().getChunk(x,z,net.minecraft.world.level.chunk.status.ChunkStatus.FULL,false)!=null;
}
public static boolean ocean(ClientLevel level,BlockPos pos){return loaded(level,pos.getX()>>4,pos.getZ()>>4)&&level.getBiome(pos).is(BiomeTags.IS_OCEAN);}
private static int classify(java.util.function.Function<BlockPos,BlockState> read,BlockPos pos,Map<Block,Integer> table){
var cursor=pos.mutable();
for(int i=1;i<=DEPTH;i++){
@@ -102,7 +106,7 @@ public final class NaturalWater {
return live(level,bx,by,bz).mix(live(level,bx+1,by,bz),dx).mix(live(level,bx,by,bz+1).mix(live(level,bx+1,by,bz+1),dx),dz);
}
private static Profile live(ClientLevel l,int x,int y,int z){
var p=new BlockPos(x,y,z);if(!l.hasChunk(x>>4,z>>4)||ocean(l,p))return CLEAR;
var p=new BlockPos(x,y,z);if(!loaded(l,x>>4,z>>4)||ocean(l,p))return CLEAR;
return PROFILES[classify(l::getBlockState,p,materials)];
}
/** Owned by a single native section compilation, with ocean data captured before worker submission. */
@@ -120,13 +124,14 @@ public final class NaturalWater {
var copied=new java.util.ArrayList<net.minecraft.core.Holder<net.minecraft.world.level.biome.Biome>>(216);
int qx=(ox>>2)-1,qy=(oy>>2)-1,qz=(oz>>2)-1;
for(int y=0;y<6;y++)for(int z=0;z<6;z++)for(int x=0;x<6;x++)
copied.add(level.hasChunk((qx+x)>>2,(qz+z)>>2)?level.getBiomeManager().getNoiseBiomeAtQuart(qx+x,qy+y,qz+z):null);
copied.add(loaded(level,(qx+x)>>2,(qz+z)>>2)?level.getBiomeManager().getNoiseBiomeAtQuart(qx+x,qy+y,qz+z):null);
biomes=level.getBiomeManager().withDifferentSource((x,y,z)->copied.get(((y-qy)*6+z-qz)*6+x-qx));
}
// A missing biome snapshot also forces clear water at unloaded region edges.
public boolean ocean(int x,int y,int z){
if(oceanKinds==null)oceanKinds=new byte[18*16*18];
int key=((y-oy)*18+z-oz+1)*18+x-ox+1;
int code=oceanKinds[key];if(code==0){var biome=biomes.getBiome(x,y,z);code=biome!=null&&biome.is(BiomeTags.IS_OCEAN)?2:1;oceanKinds[key]=(byte)code;}
int code=oceanKinds[key];if(code==0){var biome=biomes.getBiome(x,y,z);code=biome==null||biome.is(BiomeTags.IS_OCEAN)?2:1;oceanKinds[key]=(byte)code;}
return code==2;
}
private Profile profile(BlockAndTintGetter region,int x,int y,int z){
@@ -140,6 +145,9 @@ public final class NaturalWater {
public Profile corner(BlockAndTintGetter region,BlockPos p,int dx,int dz){
if(ocean(p.getX(),p.getY(),p.getZ()))return CLEAR;
int x=p.getX()+dx-1,y=p.getY(),z=p.getZ()+dz-1;
// Both cells sharing an ocean edge must emit the same clear vertex.
// The one-block transition stays on the non-ocean side, preserving ocean priority.
if(ocean(x,y,z)||ocean(x+1,y,z)||ocean(x,y,z+1)||ocean(x+1,y,z+1))return CLEAR;
return profile(region,x,y,z).mix(profile(region,x+1,y,z),.5f).mix(profile(region,x,y,z+1).mix(profile(region,x+1,y,z+1),.5f),.5f);
}
}
@@ -1,18 +0,0 @@
package fr.koka.sanctuary.client.shader;
import java.lang.ref.WeakReference;
import java.util.Map;
import java.util.WeakHashMap;
import net.minecraft.client.renderer.texture.SpriteContents;
/** References the actual atlas clock, so pause, reload and custom frame durations stay aligned. */
public final class PbrAnimation {
public interface Clock { int sanctuary$frame(); int sanctuary$subFrame(); }
// AnimationState retains its owning sprite; both sides must be weak across atlas reloads.
private static final Map<SpriteContents,WeakReference<Clock>> clocks=new WeakHashMap<>();
private PbrAnimation(){}
public static void register(SpriteContents sprite,SpriteContents.AnimationState state){
if(state!=null)clocks.put(sprite,new WeakReference<>((Clock)state));
}
static Clock clock(SpriteContents sprite){var clock=clocks.get(sprite);return clock==null?null:clock.get();}
}
@@ -1,52 +0,0 @@
package fr.koka.sanctuary.client.shader;
import com.mojang.blaze3d.vertex.VertexConsumer;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.block.FluidRenderer;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.block.state.BlockState;
/** Replays the native fluid tessellator, including slope, flow UVs and waterlogged faces. */
final class PbrFluidMesh implements VertexConsumer {
private final VertexConsumer target;
private final PbrMaterials materials;
private final TextureAtlasSprite[] sprites;
private final float[][] vertices=new float[4][5];
private final int sky;
private int cursor,quads;
private PbrFluidMesh(VertexConsumer target,PbrMaterials materials,TextureAtlasSprite[] sprites,int sky){
this.target=target;this.materials=materials;this.sprites=sprites;this.sky=sky;
}
static int emit(VertexConsumer target,PbrMaterials materials,net.minecraft.client.multiplayer.ClientLevel level,BlockPos pos,BlockState state){
var models=Minecraft.getInstance().getModelManager().getFluidStateModelSet();
var model=models.get(state.getFluidState());
var sink=new PbrFluidMesh(target,materials,new TextureAtlasSprite[]{model.stillMaterial().sprite(),model.flowingMaterial().sprite(),model.overlayMaterial()==null?null:model.overlayMaterial().sprite()},
level.getBrightness(net.minecraft.world.level.LightLayer.SKY,pos.above()));
new FluidRenderer(models).tesselate(level,pos,layer->sink,state,state.getFluidState());
return sink.quads;
}
@Override public void addVertex(float x,float y,float z,int color,float u,float v,int overlay,int light,float nx,float ny,float nz){
vertices[cursor++]=new float[]{x,y,z,u,v};
if(cursor!=4)return;
cursor=0;float cu=0,cv=0;for(var p:vertices){cu+=p[3]*.25f;cv+=p[4]*.25f;}
TextureAtlasSprite sprite=null;
for(var candidate:sprites)if(candidate!=null&&cu>=candidate.getU0()&&cu<=candidate.getU1()&&cv>=candidate.getV0()&&cv<=candidate.getV1()){sprite=candidate;break;}
if(sprite==null)return;
var slot=materials.slot(sprite,net.minecraft.world.level.block.Blocks.WATER.defaultBlockState());
if(slot.empty())return;
for(var p:vertices)target.addVertex(p[0],p[1],p[2]).setColor((Math.round(sky/15f*255)<<24)|(color&0xFFFFFF))
.setUv(p[3],p[4]).setUv3(slot.u((p[3]-sprite.getU0())/(sprite.getU1()-sprite.getU0())),slot.v((p[4]-sprite.getV0())/(sprite.getV1()-sprite.getV0()))+4);
quads++;
}
// FluidRenderer uses the packed overload above. Fail visibly if that native contract changes.
public VertexConsumer addVertex(float x,float y,float z){throw new UnsupportedOperationException("Unpacked fluid vertex");}
public VertexConsumer setColor(int r,int g,int b,int a){return this;}
public VertexConsumer setColor(int c){return this;}
public VertexConsumer setUv(float u,float v){return this;}
public VertexConsumer setUv1(int u,int v){return this;}
public VertexConsumer setUv2(int u,int v){return this;}
public VertexConsumer setUv3(float u,float v){return this;}
public VertexConsumer setNormal(float x,float y,float z){return this;}
public VertexConsumer setLineWidth(float w){return this;}
}
@@ -17,18 +17,10 @@ final class PbrMaterials implements AutoCloseable {
}
private final Map<String,Slot> slots=new HashMap<>();
private final Map<BlockState,Profile> profiles=new IdentityHashMap<>();
private final List<WaterAnimation> animations=new ArrayList<>();
private DynamicTexture atlas;private boolean dirty;private int analyses;
static int family(BlockState state){
String name=BuiltInRegistries.BLOCK.getKey(state.getBlock()).getPath();
return state.getFluidState().is(net.minecraft.tags.FluidTags.WATER)&&state.liquid()?2:
(name.equals("glass")||name.endsWith("_glass")||name.equals("glass_pane")||name.endsWith("_glass_pane"))?1:0;
}
boolean candidate(BlockState state){return !state.isAir();}
boolean candidate(BlockState state){return !state.isAir()&&!state.liquid();}
Profile profile(BlockState state){return profiles.computeIfAbsent(state,s->profile(BuiltInRegistries.BLOCK.getKey(s.getBlock()).getPath()));}
static Profile profile(String name){
if(name.equals("water"))return new Profile(.12f,0);
if(name.contains("glass"))return new Profile(.16f,0);
if(name.equals("iron_block")||name.equals("gold_block")||name.equals("netherite_block")||name.contains("copper")&&!name.contains("ore")&&!name.contains("raw"))
return new Profile(name.contains("oxidized")?.65f:.32f,name.contains("oxidized")?.35f:.85f);
if(name.contains("polished")||name.contains("glazed")||name.equals("diamond_block")||name.equals("emerald_block")||name.equals("ruby_block")||name.equals("sapphire_block"))return new Profile(.42f,0);
@@ -47,13 +39,7 @@ final class PbrMaterials implements AutoCloseable {
int fw=Math.min(image.getWidth(),sprite.contents().width()),fh=Math.min(image.getHeight(),sprite.contents().height());
int[] colors=new int[INNER*INNER];
for(int py=0;py<INNER;py++)for(int px=0;px<INNER;px++)colors[py*INNER+px]=image.getPixel(px*fw/INNER,py*fh/INNER);
int family=family(state);
// Pigmented glass can have low alpha and still carry real texture relief.
// Fully transparent glass texels keep the geometric-normal fallback.
if(family==2||family==1)for(int j=0;j<colors.length;j++)
if(family==2||(colors[j]>>>24)>0)colors[j]|=0xFF000000;
int[] pixels=generate(colors,INNER,INNER,profile);analyses++;
if(family(state)==2)animations.add(new WaterAnimation(sprite,image,profile,x,y));
for(int py=0;py<TILE;py++)for(int px=0;px<TILE;px++)atlas.getPixels().setPixel(x+px,y+py,pixels[Math.clamp(py-2,0,INNER-1)*INNER+Math.clamp(px-2,0,INNER-1)]);
}catch(java.io.IOException e){empty=true;fr.koka.sanctuary.SanctuaryMod.LOGGER.warn("Cannot analyse PBR texture {}",sprite.contents().name(),e);}
var result=new Slot(x,y,empty);slots.put(key,result);dirty=true;return result;
@@ -73,52 +59,7 @@ final class PbrMaterials implements AutoCloseable {
}
private static float height(int color,float fallback){return (color>>>24)<128?fallback:luma(color);}
private static float luma(int c){return ((c>>16&255)*.2126f+(c>>8&255)*.7152f+(c&255)*.0722f)/255;}
DynamicTexture atlas(){
if(dirty){atlas.upload();dirty=false;for(var animation:animations)animation.lastFrame=-1;}
if(atlas!=null)for(var animation:animations)animation.update(atlas);
return atlas;
}
private static final class WaterAnimation {
final TextureAtlasSprite sprite;final int x,y;final int[][] normals;final int[] frames,times;final boolean interpolate;
final NativeImage tile=new NativeImage(TILE,TILE,false);int lastFrame=-1,lastSub=-1,updates;
WaterAnimation(TextureAtlasSprite sprite,NativeImage image,Profile profile,int x,int y)throws java.io.IOException{
this.sprite=sprite;this.x=x;this.y=y;
int w=sprite.contents().width(),h=sprite.contents().height(),columns=image.getWidth()/w,count=columns*(image.getHeight()/h);
// Bound custom resource-pack memory; unsupported huge animations keep their initial normal.
boolean capped=count>1024;
if(capped){fr.koka.sanctuary.SanctuaryMod.LOGGER.warn("PBR water animation {} exceeds 1024 frames; using a fixed normal",sprite.contents().name());count=1;}
normals=new int[count][];
for(int f=0;f<count;f++){
int[] colors=new int[INNER*INNER];
for(int py=0;py<INNER;py++)for(int px=0;px<INNER;px++)colors[py*INNER+px]=image.getPixel((f%columns)*w+px*w/INNER,(f/columns)*h+py*h/INNER)|0xFF000000;
normals[f]=generate(colors,INNER,INNER,profile);
}
var metadata=net.minecraft.client.Minecraft.getInstance().getResourceManager().getResourceOrThrow(BloomMaterials.texture(sprite.contents().name()))
.metadata().getSection(net.minecraft.client.resources.metadata.animation.AnimationMetadataSection.TYPE);
var sequence=new ArrayList<Integer>();var durations=new ArrayList<Integer>();
if(metadata.isPresent()&&!capped){
var m=metadata.get();interpolate=m.interpolatedFrames();
if(m.frames().isPresent())for(var frame:m.frames().get()){
if(frame.index()>=0&&frame.index()<count&&frame.timeOr(m.defaultFrameTime())>0){sequence.add(frame.index());durations.add(frame.timeOr(m.defaultFrameTime()));}
}else for(int f=0;f<count;f++){sequence.add(f);durations.add(m.defaultFrameTime());}
}else interpolate=false;
if(sequence.isEmpty()){sequence.add(0);durations.add(1);}
frames=sequence.stream().mapToInt(Integer::intValue).toArray();times=durations.stream().mapToInt(Integer::intValue).toArray();
}
void update(DynamicTexture atlas){
var clock=PbrAnimation.clock(sprite.contents());int f=clock==null?0:Math.floorMod(clock.sanctuary$frame(),frames.length),sub=clock==null||!interpolate?0:clock.sanctuary$subFrame();
if(f==lastFrame&&sub==lastSub)return;lastFrame=f;lastSub=sub;updates++;
float t=interpolate?Math.clamp(sub/(float)times[f],0,1):0;
int[] a=normals[frames[f]],b=normals[frames[(f+1)%frames.length]];
for(int py=0;py<TILE;py++)for(int px=0;px<TILE;px++){
int i=Math.clamp(py-2,0,INNER-1)*INNER+Math.clamp(px-2,0,INNER-1);
int r=Math.round((a[i]>>16&255)*(1-t)+(b[i]>>16&255)*t),g=Math.round((a[i]>>8&255)*(1-t)+(b[i]>>8&255)*t);
tile.setPixel(px,py,(a[i]&0xFF0000FF)|(r<<16)|(g<<8));
}
com.mojang.blaze3d.systems.RenderSystem.getDevice().createCommandEncoder().writeToTexture(atlas.getTexture(),tile,0,0,x,y);
}
}
int animationUpdates(){return animations.stream().mapToInt(a->a.updates).sum();}
DynamicTexture atlas(){if(dirty){atlas.upload();dirty=false;}return atlas;}
int count(){return slots.size();}int analyses(){return analyses;}
public void close(){if(atlas!=null){atlas.close();atlas=null;}for(var animation:animations)animation.tile.close();animations.clear();slots.clear();profiles.clear();dirty=false;analyses=0;}
public void close(){if(atlas!=null){atlas.close();atlas=null;}slots.clear();profiles.clear();dirty=false;analyses=0;}
}
@@ -25,14 +25,7 @@ final class PbrTerrain implements AutoCloseable {
static final VertexFormat FORMAT=VertexFormat.builder(0).addAttribute("Position",GpuFormat.RGB32_FLOAT)
.addAttribute("Color",GpuFormat.RGBA8_UNORM).addAttribute("UV0",GpuFormat.RG32_FLOAT)
.addAttribute("UV3",GpuFormat.RG32_FLOAT).build();
private final boolean transparent;
private final long maxBytes;
PbrTerrain(){this(false);}
PbrTerrain(boolean transparent){this.transparent=transparent;maxBytes=(transparent?8L:24L)*1024*1024;}
private boolean candidate(net.minecraft.world.level.block.state.BlockState state){
return transparent ? PbrMaterials.family(state)==1||state.getFluidState().is(net.minecraft.tags.FluidTags.WATER)
: materials.candidate(state)&&!state.liquid()&&PbrMaterials.family(state)==0;
}
private static final long MAX_BYTES=24L*1024*1024;
private final Map<Long,Section> sections=new HashMap<>();
final PbrMaterials materials=new PbrMaterials();
private Build building;
@@ -68,7 +61,7 @@ final class PbrTerrain implements AutoCloseable {
if(started++>=4)break;
Section next=active.stream().filter(s->s.dirty).min(Comparator.comparingDouble(s->s.origin.distToCenterSqr(camera))).orElse(null);
if(next==null)break;
if(!next.storage.maybeHas(this::candidate)){releaseEntry(next);next.dirty=false;continue;}
if(!next.storage.maybeHas(materials::candidate)){releaseEntry(next);next.dirty=false;continue;}
building=new Build(next);
}
if(!advance(building,deadline))break;
@@ -80,7 +73,7 @@ final class PbrTerrain implements AutoCloseable {
try(var mesh=done.out.buildOrThrow()){
long size=mesh.vertexBuffer().remaining();
long replaced=done.section.entry==null?0:done.section.entry.vertices.size();
if(bytes-replaced+size<=maxBytes){
if(bytes-replaced+size<=MAX_BYTES){
var buffer=RenderSystem.getDevice().createBuffer(()->"Sanctuary PBR surfaces",GpuBuffer.USAGE_VERTEX|GpuBuffer.USAGE_COPY_DST,mesh.vertexBuffer());
int count=mesh.drawState().indexCount();RenderSystem.getSequentialBuffer(PrimitiveTopology.QUADS).getBuffer(count);
replacement=new Entry(done.section.origin,buffer,count);
@@ -101,13 +94,7 @@ final class PbrTerrain implements AutoCloseable {
var parts=new ArrayList<BlockStateModelPart>();var random=RandomSource.create();
while(build.cursor<4096){
int i=build.cursor++,x=i&15,z=i>>4&15,y=i>>8;var state=build.section.storage.getBlockState(x,y,z);
if(candidate(state)){
if(transparent&&state.getFluidState().is(net.minecraft.tags.FluidTags.WATER)){
int emitted=PbrFluidMesh.emit(build.out,materials,mc.level,build.section.origin.offset(x,y,z),state);
build.quads+=emitted;
if(build.quads>=16384){build.overflow=true;return true;}
}
if(state.liquid() || (transparent&&PbrMaterials.family(state)!=1)){if(System.nanoTime()>=deadline)return build.cursor==4096;continue;}
if(materials.candidate(state)){
var pos=build.section.origin.offset(x,y,z);
parts.clear();random.setSeed(state.getSeed(pos));if(!state.liquid())models.get(state).collectParts(random,parts);
var tintSources=mc.getBlockColors().getTintSources(state);
@@ -129,7 +116,7 @@ final class PbrTerrain implements AutoCloseable {
var p=quad.position(v);float u=UVPair.unpackU(quad.packedUV(v)),tv=UVPair.unpackV(quad.packedUV(v));
float localU=(u-sprite.getU0())/(sprite.getU1()-sprite.getU0()),localV=(tv-sprite.getV0())/(sprite.getV1()-sprite.getV0());
build.out.addVertex(x+p.x()+(float)offset.x,y+p.y()+(float)offset.y,z+p.z()+(float)offset.z)
.setColor(color).setUv(u,tv).setUv3(slot.u(localU),slot.v(localV)+2*PbrMaterials.family(state));
.setColor(color).setUv(u,tv).setUv3(slot.u(localU),slot.v(localV));
}
build.quads++;
}
@@ -146,7 +133,6 @@ final class PbrTerrain implements AutoCloseable {
private void dirty(Section section){if(section!=null){section.revision++;section.dirty=true;}}
private void releaseEntry(Section section){if(section.entry!=null){bytes-=section.entry.vertices.size();section.entry.vertices.close();section.entry=null;}}
private void remove(Section section){if(building!=null&&building.section==section){building.close();building=null;}releaseEntry(section);}
long allocatedBytes(){return bytes;}
int entryCount(){return (int)visible.stream().filter(s->s.entry!=null).count();}
int completed(){return completed;}
boolean building(){return building!=null;}
@@ -1,150 +0,0 @@
package fr.koka.sanctuary.client.shader;
import com.mojang.blaze3d.buffers.Std140Builder;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.renderpearl.api.GpuFormat;
import com.mojang.renderpearl.api.buffers.GpuBuffer;
import com.mojang.renderpearl.api.commands.RenderPassDescriptor;
import com.mojang.renderpearl.api.pipeline.*;
import com.mojang.renderpearl.api.textures.*;
import fr.koka.sanctuary.client.panorama.PanoramaCapture;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.BindGroupLayouts;
import net.minecraft.client.renderer.MappableRingBuffer;
import net.minecraft.client.renderer.RenderPipelines;
import net.minecraft.client.renderer.texture.DynamicTexture;
import net.minecraft.client.renderer.texture.TextureAtlas;
import net.minecraft.resources.Identifier;
import net.minecraft.world.level.material.FogType;
import org.joml.Matrix4f;
import org.joml.Vector3f;
import org.joml.Vector4f;
import java.util.*;
/** Bounded single-bounce landscape reflection. Never samples the target being written. */
public final class PixelReflections {
private static final BindGroupLayout LAYOUT=BindGroupLayout.builder()
.withUniform("ReflectionScene",UniformType.UNIFORM_BUFFER)
.withUniform("OpaqueDepth",UniformType.COMBINED_IMAGE_SAMPLER)
.withUniform("OpaqueColor",UniformType.COMBINED_IMAGE_SAMPLER)
.withUniform("ReceiverDepth",UniformType.COMBINED_IMAGE_SAMPLER)
.withUniform("SceneColor",UniformType.COMBINED_IMAGE_SAMPLER)
.withUniform("BlockAtlas",UniformType.COMBINED_IMAGE_SAMPLER)
.withUniform("MaterialAtlas",UniformType.COMBINED_IMAGE_SAMPLER).build();
private static RenderPipeline pipeline(String name,boolean depth){
var b=RenderPipeline.builder().withLocation(Identifier.parse("sanctuary:pipeline/"+name))
.withVertexShader(Identifier.parse("sanctuary:core/pbr"))
.withFragmentShader(Identifier.parse("sanctuary:core/"+name))
.withBindGroupLayout(BindGroupLayouts.DYNAMIC_TRANSFORMS).withBindGroupLayout(LAYOUT)
.withVertexBinding(0,PbrTerrain.FORMAT).withPrimitiveTopology(PrimitiveTopology.QUADS).withCull(true);
if(depth)b.withDepthStencilState(new DepthStencilState(CompareOp.GREATER_THAN,true));
else b.withColorTargetState(new ColorTargetState(Optional.empty(),GpuFormat.RGBA8_UNORM,ColorTargetState.WRITE_COLOR)).withDepthStencilState(new DepthStencilState(CompareOp.EQUAL,false));
return RenderPipelines.register(b.build());
}
private static final RenderPipeline DEPTH=pipeline("pbr_receiver",true),REFLECT=pipeline("pixel_reflections",false);
private static GpuTexture opaqueDepth,opaqueColor;
private static GpuTextureView opaqueDepthView,opaqueColorView;
private static int width,height;
private static GpuTexture receiver;
private static GpuTextureView receiverView;
private static MappableRingBuffer uniform;
private static Matrix4f vp=new Matrix4f();
private static List<PbrTerrain.Entry> solid=List.of(),transparent=List.of();
private static DynamicTexture solidAtlas,transparentAtlas;
private static boolean captured,ready,applied;
private static int frames;
private PixelReflections(){}
public static boolean eligible(){
var mc=Minecraft.getInstance();
return mc.level!=null&&VanillaLight.active()&&VanillaLight.pbr()&&VanillaLight.pbrIntensity()>0&&!PanoramaCapture.rendering()
&&mc.gameRenderer.gameRenderState().levelRenderState.cameraRenderState.fogType==FogType.NONE
&&mc.gameRenderer.gameRenderState().levelRenderState.skyRenderState.skybox==net.minecraft.world.level.dimension.DimensionType.Skybox.OVERWORLD;
}
public static void beginFrame(){captured=ready=applied=false;if(!eligible())release();}
/** Called only with the opaque render pass closed, on both native transparency paths. */
public static void captureOpaque(){
if(!eligible())return;
var mc=Minecraft.getInstance();var main=mc.gameRenderer.mainRenderTarget();
var device=RenderSystem.getDevice();
int usage=GpuTexture.USAGE_RENDER_ATTACHMENT|GpuTexture.USAGE_TEXTURE_BINDING|GpuTexture.USAGE_COPY_DST|GpuTexture.USAGE_COPY_SRC;
if(opaqueDepth==null||width!=main.width||height!=main.height){
release();width=main.width;height=main.height;
opaqueDepth=device.createTexture(()->"Sanctuary opaque depth",usage,main.getDepthTexture().getFormat(),width,height,1,1);
opaqueDepthView=device.createTextureView(opaqueDepth);
receiver=device.createTexture(()->"Sanctuary nearest PBR surface",usage,main.getDepthTexture().getFormat(),width,height,1,1);
receiverView=device.createTextureView(receiver);
}
boolean enabled=VanillaLight.ssr()&&VanillaLight.ssrIntensity()>0;
if(enabled&&opaqueColor==null){
opaqueColor=device.createTexture(()->"Sanctuary reflection landscape",usage,GpuFormat.RGBA8_UNORM,width,height,1,1);
opaqueColorView=device.createTextureView(opaqueColor);
}else if(!enabled&&opaqueColor!=null){opaqueColorView.close();opaqueColor.close();opaqueColorView=null;opaqueColor=null;}
var encoder=device.createCommandEncoder();
encoder.copyTextureToTexture(main.getDepthTexture(),opaqueDepth,0,0,0,0,0,width,height);
if(enabled)encoder.copyTextureToTexture(main.getColorTexture(),opaqueColor,0,0,0,0,0,width,height);
captured=true;
}
static void prepare(Matrix4f matrix,List<PbrTerrain.Entry> solids,DynamicTexture sa,List<PbrTerrain.Entry> liquids,DynamicTexture ta){
if(!captured)return;
vp.set(matrix);solid=solids;transparent=liquids;solidAtlas=sa;transparentAtlas=ta;
if(uniform==null)uniform=new MappableRingBuffer(()->"Sanctuary reflection parameters",GpuBuffer.USAGE_UNIFORM|GpuBuffer.USAGE_MAP_WRITE,160);
uniform.rotate();try(var map=uniform.currentBuffer().map(false,true)){
Std140Builder.intoBuffer(map.data()).putMat4f(vp).putMat4f(new Matrix4f(vp).invert())
.putVec4(RenderSystem.getDevice().getDeviceInfo().isZZeroToOne()?1:0,VanillaLight.ssrIntensity()/100f,VanillaLight.pbrIntensity()/100f,32)
.putVec4(128,32,0,0);
}
int max=java.util.stream.Stream.concat(solid.stream(),transparent.stream()).mapToInt(PbrTerrain.Entry::indices).max().orElse(0);
RenderSystem.getSequentialBuffer(PrimitiveTopology.QUADS).requestIndexCount(max);
var encoder=RenderSystem.getDevice().createCommandEncoder();
try(var pass=encoder.createRenderPass(RenderPassDescriptor.builder(()->"Sanctuary nearest material")
.withDepthAttachment(receiverView,OptionalDouble.of(0)).build())){
pass.setPipeline(RenderSystem.getCompiledPipeline(DEPTH));
bind(pass,Minecraft.getInstance().gameRenderer.mainRenderTarget().getColorTextureView(),false);
draw(pass,solid,solidAtlas);draw(pass,transparent,transparentAtlas);
}
ready=true;
}
static GpuTextureView depth(){return ready?receiverView:null;}
private static void bind(com.mojang.renderpearl.api.commands.RenderPass pass,GpuTextureView scene,boolean reflection){
var nearest=RenderSystem.getSamplerCache().getClampToEdge(FilterMode.NEAREST);
pass.setUniform("ReflectionScene",uniform.currentBuffer());
pass.setUniform("OpaqueDepth",opaqueDepthView,nearest);
pass.setUniform("OpaqueColor",opaqueColorView!=null?opaqueColorView:scene,nearest);
// Never bind the receiver as a sampled texture while it is attached for depth writes.
pass.setUniform("ReceiverDepth",opaqueDepthView,nearest);
pass.setUniform("SceneColor",scene,nearest);
pass.setUniform("BlockAtlas",Minecraft.getInstance().getTextureManager().getTexture(TextureAtlas.LOCATION_BLOCKS).getTextureView(),nearest);
}
private static void draw(com.mojang.renderpearl.api.commands.RenderPass pass,List<PbrTerrain.Entry> entries,DynamicTexture atlas){
if(atlas==null||entries.isEmpty())return;
pass.setUniform("MaterialAtlas",atlas.getTextureView(),RenderSystem.getSamplerCache().getClampToEdge(FilterMode.NEAREST));
var indices=RenderSystem.getSequentialBuffer(PrimitiveTopology.QUADS);
var camera=Minecraft.getInstance().gameRenderer.gameRenderState().levelRenderState.cameraRenderState;
for(var e:entries){
pass.setIndexBuffer(indices.getBuffer(),indices.type());
var p=e.origin();var offset=new Vector3f((float)(p.getX()-camera.pos.x),(float)(p.getY()-camera.pos.y),(float)(p.getZ()-camera.pos.z));
pass.setUniform("DynamicTransforms",RenderSystem.getDynamicUniforms().writeTransform(new Matrix4f(vp).translate(offset),new Vector4f(1,1,1,1),offset,new Matrix4f()));
pass.setVertexBuffer(0,e.vertices().slice());pass.drawIndexed(e.indices(),1,0,0,0);
}
}
public static void render(){
if(!ready||!VanillaLight.ssr()||VanillaLight.ssrIntensity()==0)return;
var main=Minecraft.getInstance().gameRenderer.mainRenderTarget();
var scene=ProceduralPbr.copyScene();
try(var pass=RenderSystem.getDevice().createCommandEncoder().createRenderPass(()->"Sanctuary pixel reflections",main.getColorTextureView(),Optional.empty(),receiverView,OptionalDouble.empty())){
pass.setPipeline(RenderSystem.getCompiledPipeline(REFLECT));bind(pass,scene,true);
draw(pass,solid,solidAtlas);draw(pass,transparent,transparentAtlas);
}
applied=true;frames++;
}
public static void release(){
if(opaqueColorView!=null){opaqueColorView.close();opaqueColorView=null;}if(opaqueColor!=null){opaqueColor.close();opaqueColor=null;}
if(opaqueDepthView!=null){opaqueDepthView.close();opaqueDepthView=null;}if(opaqueDepth!=null){opaqueDepth.close();opaqueDepth=null;}if(receiverView!=null){receiverView.close();receiverView=null;}
if(receiver!=null){receiver.close();receiver=null;}if(uniform!=null){uniform.close();uniform=null;}
solid=transparent=List.of();solidAtlas=transparentAtlas=null;captured=ready=applied=false;
}
static long targetBytes(){return (long)width*height*((opaqueDepth!=null?4:0)+(receiver!=null?4:0)+(opaqueColor!=null?4:0));}
static GpuTexture landscape(){return opaqueColor;}
static boolean applied(){return applied;}static int frames(){return frames;}
static boolean allocated(){return opaqueColor!=null;}
}
@@ -37,16 +37,15 @@ public final class ProceduralPbr {
.withColorTargetState(new ColorTargetState(Optional.empty(),GpuFormat.RGBA8_UNORM,ColorTargetState.WRITE_COLOR))
.withDepthStencilState(Optional.empty()).build());
private static final PbrTerrain TERRAIN=new PbrTerrain();
private static final PbrTerrain TRANSPARENT=new PbrTerrain(true);
private static final Matrix4f projection=new Matrix4f();
private static TextureTarget source;
private static MappableRingBuffer scene;
private static boolean applied;private static int frames;
private ProceduralPbr(){}
public static void captureProjection(Matrix4f matrix){projection.set(matrix);}
public static void dirtyBlock(BlockPos pos){TERRAIN.dirty(pos);TRANSPARENT.dirty(pos);}
public static void dirtyChunk(int x,int z){TERRAIN.dirtyChunk(x,z);TRANSPARENT.dirtyChunk(x,z);}
public static void dirtySection(int x,int y,int z){if(!fr.koka.sanctuary.client.DynamicLightClient.invalidatingSections()){TERRAIN.dirtySection(x,y,z);TRANSPARENT.dirtySection(x,y,z);}}
public static void dirtyBlock(BlockPos pos){TERRAIN.dirty(pos);}
public static void dirtyChunk(int x,int z){TERRAIN.dirtyChunk(x,z);}
public static void dirtySection(int x,int y,int z){if(!fr.koka.sanctuary.client.DynamicLightClient.invalidatingSections())TERRAIN.dirtySection(x,y,z);}
public static void render(){
applied=false;var mc=Minecraft.getInstance();
if(!VanillaLight.active()||!VanillaLight.pbr()||VanillaLight.pbrIntensity()==0||mc.level==null){release();return;}
@@ -56,11 +55,8 @@ public final class ProceduralPbr {
if(source==null||source.width!=main.width||source.height!=main.height){if(source!=null)source.destroyBuffers();source=new TextureTarget("Sanctuary PBR source",main.width,main.height,GpuFormat.RGBA8_UNORM,null);}
// Padding supplies valid inactive PixelShadows and local-light uniform bindings.
if(scene==null)scene=new MappableRingBuffer(()->"Sanctuary PBR scene",GpuBuffer.USAGE_UNIFORM|GpuBuffer.USAGE_MAP_WRITE,176+ColoredDynamicLights.LIMIT*32);
var solidEntries=TERRAIN.update();var atlas=TERRAIN.materials.atlas();
var transparentEntries=TRANSPARENT.update();var transparentAtlas=TRANSPARENT.materials.atlas();
var entries=new ArrayList<PbrTerrain.Entry>(solidEntries);entries.addAll(transparentEntries);
var entries=TERRAIN.update();var atlas=TERRAIN.materials.atlas();
var vp=new Matrix4f(projection).mul(camera.viewRotationMatrix);var fog=camera.fogData;
PixelReflections.prepare(vp,solidEntries,atlas,transparentEntries,transparentAtlas);
var sun=PixelShadows.sunDirection(sky.sunAngle);boolean lunar=sun.y<=.08f;
if(lunar)sun=PixelShadows.sunDirection(sky.moonAngle);
float moon=sky.moonPhase==null?1:(float)(.5+.5*Math.cos(sky.moonPhase.index()*Math.PI/4));
@@ -80,32 +76,22 @@ public final class ProceduralPbr {
var encoder=RenderSystem.getDevice().createCommandEncoder();
encoder.copyTextureToTexture(main.getColorTexture(),source.getColorTexture(),0,0,0,0,0,main.width,main.height);
var nearest=RenderSystem.getSamplerCache().getClampToEdge(FilterMode.NEAREST);
if((atlas!=null||transparentAtlas!=null)&&!entries.isEmpty())try(var pass=encoder.createRenderPass(()->"Sanctuary PBR materials",main.getColorTextureView(),Optional.empty())){
if(atlas!=null&&!entries.isEmpty())try(var pass=encoder.createRenderPass(()->"Sanctuary PBR materials",main.getColorTextureView(),Optional.empty())){
pass.setPipeline(RenderSystem.getCompiledPipeline(PIPELINE));pass.setUniform("PbrScene",scene.currentBuffer());
pass.setUniform("PixelShadows",shadow?PixelShadows.materialUniforms():scene.currentBuffer());
pass.setUniform("SunDepth",shadow?PixelShadows.materialDepth():main.getDepthTextureView(),nearest);
pass.setUniform("WorldDepth",PixelReflections.depth()!=null?PixelReflections.depth():main.getDepthTextureView(),nearest);pass.setUniform("SceneColor",source.getColorTextureView(),nearest);
pass.setUniform("WorldDepth",main.getDepthTextureView(),nearest);pass.setUniform("SceneColor",source.getColorTextureView(),nearest);
pass.setUniform("BlockAtlas",mc.getTextureManager().getTexture(TextureAtlas.LOCATION_BLOCKS).getTextureView(),nearest);
pass.setUniform("MaterialAtlas",(atlas!=null?atlas:transparentAtlas).getTextureView(),nearest);
pass.setUniform("MaterialAtlas",atlas.getTextureView(),nearest);
if(ColoredLights.directionalReady())ColoredLights.bindDirections(pass);
else{pass.setUniform("ColoredLightScene",scene.currentBuffer());pass.setUniform("LightDirection",source.getColorTextureView(),nearest);pass.setUniform("PreviousDirection",source.getColorTextureView(),nearest);}
pass.setIndexBuffer(indices.getBuffer(),indices.type());
for(int i=0;i<entries.size();i++){var entry=entries.get(i);
pass.setUniform("MaterialAtlas",(i<solidEntries.size()?atlas:transparentAtlas).getTextureView(),nearest);pass.setUniform("DynamicTransforms",transforms.get(i));pass.setVertexBuffer(0,entry.vertices().slice());pass.drawIndexed(entry.indices(),1,0,0,0);}
for(int i=0;i<entries.size();i++){var entry=entries.get(i);pass.setUniform("DynamicTransforms",transforms.get(i));pass.setVertexBuffer(0,entry.vertices().slice());pass.drawIndexed(entry.indices(),1,0,0,0);}
}
applied=true;frames++;
}
static com.mojang.renderpearl.api.textures.GpuTextureView copyScene(){
var main=Minecraft.getInstance().gameRenderer.mainRenderTarget();
RenderSystem.getDevice().createCommandEncoder().copyTextureToTexture(main.getColorTexture(),source.getColorTexture(),0,0,0,0,0,main.width,main.height);
return source.getColorTextureView();
}
public static void release(){TERRAIN.close();TRANSPARENT.close();PixelReflections.release();if(source!=null){source.destroyBuffers();source=null;}if(scene!=null){scene.close();scene=null;}applied=false;}
static long solidBytes(){return TERRAIN.allocatedBytes();}
static long transparentBytes(){return TRANSPARENT.allocatedBytes();}
static int waterUpdates(){return TRANSPARENT.materials.animationUpdates();}
static int waterAnalyses(){return TRANSPARENT.materials.analyses();}
static boolean applied(){return applied;}static boolean ready(){return TERRAIN.settled()&&TRANSPARENT.settled();}
public static void release(){TERRAIN.close();if(source!=null){source.destroyBuffers();source=null;}if(scene!=null){scene.close();scene=null;}applied=false;}
static boolean applied(){return applied;}static boolean ready(){return TERRAIN.settled();}
static boolean allocated(){return source!=null;}static int renderedFrames(){return frames;}
static int terrainEntries(){return TERRAIN.entryCount();}
static int terrainBuilds(){return TERRAIN.completed();}
@@ -26,9 +26,6 @@ public final class ShaderOptionsScreen extends OptionsSubScreen {
list.addBig(OptionInstance.createBoolean("sanctuary.shaders.pbr",OptionInstance.cachedConstantTooltip(
Component.translatable("sanctuary.shaders.pbr_help")),VanillaLight.pbr(),VanillaLight::setPbr));
slider("pbr_intensity",VanillaLight.pbrIntensity(),VanillaLight::setPbrIntensity);
list.addBig(OptionInstance.createBoolean("sanctuary.shaders.ssr",OptionInstance.cachedConstantTooltip(
Component.translatable("sanctuary.shaders.ssr_help")),VanillaLight.ssr(),VanillaLight::setSsr));
slider("ssr_intensity",VanillaLight.ssrIntensity(),VanillaLight::setSsrIntensity);
list.addBig(OptionInstance.createBoolean("sanctuary.shaders.colored_lights",OptionInstance.cachedConstantTooltip(
Component.translatable("sanctuary.shaders.colored_lights_help")),VanillaLight.coloredLights(),VanillaLight::setColoredLights));
list.addBig(OptionInstance.createBoolean("sanctuary.shaders.warm_torches",OptionInstance.cachedConstantTooltip(
@@ -27,8 +27,6 @@ public final class VanillaLight {
int lensFlareIntensity=30;
boolean pbr=true;
int pbrIntensity=80;
boolean ssr=false;
int ssrIntensity=50;
boolean ssgi=true;
boolean coloredLights=true;
boolean warmTorches=false;
@@ -53,7 +51,6 @@ public final class VanillaLight {
if(preferences==null)preferences=new Preferences();
preferences.sunshaftIntensity=Math.clamp(preferences.sunshaftIntensity,0,100);
preferences.lensFlareIntensity=Math.clamp(preferences.lensFlareIntensity,0,100);
preferences.ssrIntensity=Math.clamp(preferences.ssrIntensity,0,100);
preferences.pbrIntensity=Math.clamp(preferences.pbrIntensity,0,100);
preferences.coloredLightIntensity=Math.clamp(preferences.coloredLightIntensity,0,100);
preferences.coloredLightDistance=normalizeColoredLightDistance(preferences.coloredLightDistance);
@@ -91,10 +88,6 @@ public final class VanillaLight {
public static int lensFlareIntensity(){enabled();return preferences.lensFlareIntensity;}
public static void setLensFlare(boolean value){enabled();preferences.lensFlare=value;save();}
public static void setLensFlareIntensity(int value){enabled();preferences.lensFlareIntensity=Math.clamp(value,0,100);save();}
public static boolean ssr(){enabled();return preferences.ssr;}
public static int ssrIntensity(){enabled();return preferences.ssrIntensity;}
public static void setSsr(boolean value){enabled();preferences.ssr=value;save();}
public static void setSsrIntensity(int value){enabled();preferences.ssrIntensity=Math.clamp(value,0,100);save();}
public static boolean pbr(){enabled();return preferences.pbr;}
public static int pbrIntensity(){enabled();return preferences.pbrIntensity;}
public static void setPbr(boolean value){enabled();preferences.pbr=value;save();}
@@ -1,10 +0,0 @@
package fr.koka.sanctuary.mixin.client;
import fr.koka.sanctuary.client.shader.PbrAnimation;
import net.minecraft.client.renderer.texture.SpriteContents;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
@Mixin(SpriteContents.AnimationState.class)
public interface PbrAnimationClockMixin extends PbrAnimation.Clock {
@Accessor("frame") int sanctuary$frame();
@Accessor("subFrame") int sanctuary$subFrame();
}
@@ -1,14 +0,0 @@
package fr.koka.sanctuary.mixin.client;
import fr.koka.sanctuary.client.shader.PbrAnimation;
import net.minecraft.client.renderer.texture.SpriteContents;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(SpriteContents.class)
abstract class PbrAnimationSpriteMixin {
@Inject(method="createAnimationState",at=@At("RETURN"))
private void sanctuary$clock(CallbackInfoReturnable<SpriteContents.AnimationState> ci){
PbrAnimation.register((SpriteContents)(Object)this,ci.getReturnValue());
}
}
@@ -31,7 +31,7 @@ abstract class PixelShadowRendererMixin {
return original.call(buffer, matrix);
}
@Inject(method="renderLevel", at=@At(value="INVOKE", target="Lnet/minecraft/client/renderer/GameRenderer;render3dHud(Lnet/minecraft/client/renderer/state/level/CameraRenderState;Lnet/minecraft/client/renderer/state/level/PlayerRenderState;Lnet/minecraft/client/renderer/state/OptionsRenderState;Z)V"))
private void sanctuary$shadows(CallbackInfo ci) { ColoredLights.prepare(); PixelShadows.render(); ProceduralPbr.render(); ColoredLights.render(); ScreenSpaceGI.render(); fr.koka.sanctuary.client.shader.PixelReflections.render(); EdgeHighlights.render(); Bloom.render(); Sunshafts.render(); }
private void sanctuary$shadows(CallbackInfo ci) { ColoredLights.prepare(); PixelShadows.render(); ProceduralPbr.render(); ColoredLights.render(); ScreenSpaceGI.render(); EdgeHighlights.render(); Bloom.render(); Sunshafts.render(); }
@Inject(method={"close", "setLevel"}, at=@At("HEAD"))
private void sanctuary$close(CallbackInfo ci) { PixelShadows.release(); ProceduralPbr.release(); EdgeHighlights.release(); Bloom.release(); ColoredLights.release(); ScreenSpaceGI.release(); Sunshafts.release(); }
}
@@ -1,41 +0,0 @@
package fr.koka.sanctuary.mixin.client;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.renderpearl.api.commands.RenderPass;
import fr.koka.sanctuary.client.shader.PixelReflections;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.LevelRenderer;
import net.minecraft.client.renderer.chunk.ChunkSectionsToRender;
import net.minecraft.client.renderer.feature.FeatureRenderDispatcher;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.util.Optional;
import java.util.OptionalDouble;
/** Splits only the classic pass; copying an active Vulkan attachment is not legal. */
@Mixin(LevelRenderer.class)
abstract class ReflectionSceneMixin {
@Unique private java.util.function.Consumer<RenderPass> sanctuary$transparency;
@Inject(method="render",at=@At("HEAD"))
private void sanctuary$begin(CallbackInfo ci){sanctuary$transparency=null;PixelReflections.beginFrame();}
@WrapOperation(method="lambda$addMainPass$0",at=@At(value="INVOKE",target="Lnet/minecraft/client/renderer/LevelRenderer;executeClassicTransparency(Lnet/minecraft/client/renderer/chunk/ChunkSectionsToRender;Lnet/minecraft/client/renderer/feature/FeatureRenderDispatcher$PreparedFrame;Lcom/mojang/renderpearl/api/commands/RenderPass;)V"))
private void sanctuary$defer(LevelRenderer self,ChunkSectionsToRender chunks,FeatureRenderDispatcher.PreparedFrame features,RenderPass pass,Operation<Void> original){
if(!PixelReflections.eligible()){original.call(self,chunks,features,pass);return;}
sanctuary$transparency=next->original.call(self,chunks,features,next);
}
@Inject(method="executeOit",at=@At("HEAD"))
private void sanctuary$oit(CallbackInfo ci){PixelReflections.captureOpaque();}
@Inject(method="executeOutline",at=@At("HEAD"))
private void sanctuary$classic(CallbackInfo ci){
var action=sanctuary$transparency;sanctuary$transparency=null;if(action==null)return;
PixelReflections.captureOpaque();var main=Minecraft.getInstance().gameRenderer.mainRenderTarget();
try(var pass=RenderSystem.getDevice().createCommandEncoder().createRenderPass(()->"Sanctuary native transparency",main.getColorTextureView(),Optional.empty(),main.getDepthTextureView(),OptionalDouble.empty())){
RenderSystem.bindDefaultUniforms(pass);action.accept(pass);
}
}
}
@@ -1,9 +1,4 @@
{
"sanctuary.shaders.ssr_intensity_value": "Reflection strength: %s%%",
"sanctuary.shaders.ssr_intensity_help": "Amount of landscape reflected by materials. Zero disables SSR.",
"sanctuary.shaders.ssr": "Landscape reflections — experimental",
"sanctuary.shaders.ssr_help": "Colours material texels with the visible landscape. Requires PBR; off-screen objects cannot be reflected.",
"sanctuary.shaders.ssr_intensity": "Reflection strength",
"sanctuary.graphics.default_vulkan": "Vulkan (default)",
"sanctuary.statuary.clay_ready": "Clay: original model colors.",
"sanctuary.weather.selected": "Real Time weather: %s for %s (%s). The daily forecast resumes at midnight.",
@@ -1,9 +1,4 @@
{
"sanctuary.shaders.ssr_intensity_value": "Intensité des reflets : %s %%",
"sanctuary.shaders.ssr_intensity_help": "Dose de paysage réfléchie par les matériaux. Zéro désactive le SSR.",
"sanctuary.shaders.ssr": "Reflets du paysage — expérimental",
"sanctuary.shaders.ssr_help": "Colore les pixels de matière avec le paysage visible. PBR requis ; les objets hors écran ne sont pas réfléchis.",
"sanctuary.shaders.ssr_intensity": "Intensité des reflets",
"sanctuary.graphics.default_vulkan": "Vulkan (par défaut)",
"sanctuary.statuary.clay_ready": "Argile : couleurs originales du modèle.",
"sanctuary.weather.selected": "Météo Real Time : %s pour la journée du %s (%s). Le tirage quotidien reprend à minuit.",
@@ -95,7 +95,7 @@ vec3 localShine(vec3 n,vec3 v,vec3 l,vec4 material,vec3 albedo){
float geometry=nv/(nv*(1.0-k)+k)*nl/max(nl*(1.0-k)+k,.00001);
// Explicit integer power stays defined even at round-off limits on OpenGL drivers.
float grazing=1.0-vh,grazing2=grazing*grazing;
vec3 f0=mix(vec3(maskUv.y>=4.0?.02:.04),albedo,material.a),fresnel=f0+(1.0-f0)*(grazing2*grazing2*grazing);
vec3 f0=mix(vec3(.04),albedo,material.a),fresnel=f0+(1.0-f0)*(grazing2*grazing2*grazing);
return distribution*geometry*fresnel/max(4.0*nv*nl,.0001)*nl;
}
void main(){
@@ -109,12 +109,11 @@ void main(){
vec3 visible=projected.xyz/projected.w;
if(depth<=0.0||abs(length(visible)-length(relativePosition))>0.035||length(relativePosition)>=PbrParams.w||abs(det)<1e-12)discard;
// Keep atlas derivatives valid after per-fragment depth/alpha rejection.
float family=floor(maskUv.y*.5);
vec4 texel=textureGrad(BlockAtlas,blockUv,tx,ty);if(family<.5&&texel.a<0.99)discard;
vec4 texel=textureGrad(BlockAtlas,blockUv,tx,ty);if(texel.a<0.99)discard;
vec3 tangent=normalize((dx*ty.y-dy*tx.y)/det),bitangent=normalize((dy*tx.x-dx*ty.x)/det);
vec4 material=textureLod(MaterialAtlas,vec2(maskUv.x,maskUv.y-family*2.0),0.0);
vec4 material=textureLod(MaterialAtlas,maskUv,0.0);
// RG stores signed height derivatives; B roughness, A metalness, not transparency.
vec2 slope=(material.rg*255.0-128.0)/127.0*PbrParams.x*(family>1.5?.24:2.0);
vec2 slope=(material.rg*255.0-128.0)/127.0*PbrParams.x*2.0;
vec3 n=normalize(baseNormal+tangent*slope.x+bitangent*slope.y);
// Reject degenerate/interpolated geometry without replacing the native scene with NaNs.
if(any(isnan(n))||any(isinf(n))||dot(relativePosition,relativePosition)<.000001)discard;
@@ -131,10 +130,10 @@ void main(){
if(amount<=0.0001&&localAmount<=0.0001)discard;
vec3 scene=texelFetch(SceneColor,ivec2(gl_FragCoord.xy),0).rgb;vec3 linear=scene*scene;
// Native diffuse light already exists. Apply only the perturbed-normal difference, then add GGX.
float relief=family<.5?(nl-max(dot(baseNormal,l),0.0))*.7:0.0;
float relief=(nl-max(dot(baseNormal,l),0.0))*.7;
vec3 lit=clamp(linear*(1.0+relief*amount),0.0,1.0);
if(localAmount>.0001){
float localRelief=family<.5?(max(dot(n,arrival.xyz),0.0)-max(dot(baseNormal,arrival.xyz),0.0))*.7:0.0;
float localRelief=(max(dot(n,arrival.xyz),0.0)-max(dot(baseNormal,arrival.xyz),0.0))*.7;
lit=clamp(lit*(1.0+localRelief*localAmount),0.0,1.0);
}
vec3 shine=min((specular*amount+localShine(n,v,arrival.xyz,material,albedo)*localAmount)*PbrParams.x*3.0,vec3(0.5));
@@ -1,16 +0,0 @@
#version 330
#extension GL_ARB_separate_shader_objects : require
uniform sampler2D OpaqueDepth;
uniform sampler2D BlockAtlas;
layout(location=0) in vec3 relativePosition;
layout(location=1) in vec2 blockUv;
layout(location=2) in vec2 maskUv;
layout(location=3) in vec4 tint;
void main(){
vec2 dx=dFdx(blockUv),dy=dFdy(blockUv);
if(length(relativePosition)>=32.0)discard;
// Minecraft's world projection uses reverse depth: zero is the far plane.
float opaque=texelFetch(OpaqueDepth,ivec2(gl_FragCoord.xy),0).r;
if(gl_FragCoord.z+0.0000001<opaque)discard;
if(maskUv.y<2.0&&textureGrad(BlockAtlas,blockUv,dx,dy).a<.99)discard;
}
@@ -1,126 +0,0 @@
#version 330
#extension GL_ARB_separate_shader_objects : require
uniform sampler2D OpaqueDepth;
uniform sampler2D OpaqueColor;
uniform sampler2D ReceiverDepth;
uniform sampler2D SceneColor;
uniform sampler2D BlockAtlas;
uniform sampler2D MaterialAtlas;
layout(std140) uniform ReflectionScene {
mat4 ReflectionVP;
mat4 ReflectionInverseVP;
vec4 ReflectionParams; // zero-to-one, strength, normal strength, receiver distance
vec4 ReflectionLimits; // ray distance, steps, reserved
};
layout(location=0) in vec3 relativePosition;
layout(location=1) in vec2 blockUv;
layout(location=2) in vec2 maskUv;
layout(location=3) in vec4 tint;
layout(location=0) out vec4 fragColor;
vec3 reconstruct(vec2 uv,float d){
vec4 p=ReflectionInverseVP*vec4(uv*2.0-1.0,ReflectionParams.x>.5?d:d*2.0-1.0,1);
return p.xyz/p.w;
}
bool sampleRay(vec3 origin,vec3 direction,float t,out vec2 uv,out float gap){
vec3 p=origin+direction*t;vec4 clip=ReflectionVP*vec4(p,1);
if(clip.w<=.001)return false;
uv=clip.xy/clip.w*.5+.5;
if(any(lessThanEqual(uv,vec2(0)))||any(greaterThanEqual(uv,vec2(1))))return false;
float depth=textureLod(OpaqueDepth,uv,0).r;
if(depth<=0.0){gap=-1e6;return true;}
float rayDepth=ReflectionParams.x>.5?clip.z/clip.w:clip.z/clip.w*.5+.5;
gap=depth-rayDepth;return true;
}
vec4 trace(vec3 p,vec3 n,vec3 geometricNormal){
vec3 direction=reflect(normalize(p),n),origin=p+n*.035;
// A perturbed normal must not send the ray back through its own geometric face.
if(dot(direction,geometricNormal)<=.0001)return vec4(0);
vec4 a=ReflectionVP*vec4(origin,1),b=ReflectionVP*vec4(origin+direction*ReflectionLimits.x,1);
if(a.w<=.001)return vec4(0);
float distance=ReflectionLimits.x;
if(b.w<=.01){distance*=clamp((a.w-.01)/(a.w-b.w),0.0,1.0);b=ReflectionVP*vec4(origin+direction*distance,1);}
if(distance<.1)return vec4(0);
// Perspective-correct interpolation spaces the bounded march in screen coordinates.
vec2 start=a.xy/a.w*.5+.5,end=b.xy/b.w*.5+.5,delta=end-start;
float screenLimit=1.0;
if(delta.x>0.0)screenLimit=min(screenLimit,(.9999-start.x)/delta.x);
if(delta.x<0.0)screenLimit=min(screenLimit,(.0001-start.x)/delta.x);
if(delta.y>0.0)screenLimit=min(screenLimit,(.9999-start.y)/delta.y);
if(delta.y<0.0)screenLimit=min(screenLimit,(.0001-start.y)/delta.y);
if(screenLimit<=0.0)return vec4(0);
// Adaptive coarse march: large landscape silhouettes need fewer probes than screen pixels.
// The four refinements and final intersection interpolation preserve a sharp hit colour.
int steps=int(clamp(ceil(length(delta*screenLimit*vec2(textureSize(OpaqueDepth,0)))/128.0),8.0,32.0));
float previous=0.0,oldGap=-1e6;vec2 hit=vec2(0);float gap;
for(int i=1;i<=32;i++){
if(i>steps)break;
float f=float(i)/float(steps)*screenLimit;
float t=(f*distance/b.w)/mix(1.0/a.w,1.0/b.w,f);
vec2 uv;if(!sampleRay(origin,direction,t,uv,gap))return vec4(0);
if(gap>=0.0&&oldGap<0.0){
float lo=previous,hi=t,lowGap=oldGap,highGap=gap;
for(int j=0;j<4;j++){
float mid=(lo+hi)*.5;vec2 q;float delta;
if(!sampleRay(origin,direction,mid,q,delta))return vec4(0);
if(delta>=0.0){hi=mid;highGap=delta;}else{lo=mid;lowGap=delta;}
}
hi=mix(lo,hi,clamp(-lowGap/max(highGap-lowGap,1e-12),0.0,1.0));
if(!sampleRay(origin,direction,hi,hit,gap))return vec4(0);
// A bounded thickness rejects a silhouette jump into unrelated distant geometry.
float thickness=.15+.002*length(origin+direction*hi);
gap=length(origin+direction*hi)-length(reconstruct(hit,textureLod(OpaqueDepth,hit,0).r));
if(abs(gap)>thickness||hi<.08)return vec4(0);
float edge=min(min(hit.x,hit.y),min(1.0-hit.x,1.0-hit.y));
float confidence=smoothstep(0.0,.04,edge)*(1.0-smoothstep(distance*.85,distance,hi))
*(1.0-smoothstep(thickness*.65,thickness,abs(gap)))*smoothstep(.08,.2,hi);
return vec4(hit,hi,confidence);
}
previous=t;oldGap=gap;
}
return vec4(0);
}
void main(){
vec3 dx=dFdx(relativePosition),dy=dFdy(relativePosition);
vec2 mx=dFdx(maskUv),my=dFdy(maskUv),tx=dFdx(blockUv),ty=dFdy(blockUv);
float det=mx.x*my.y-mx.y*my.x;
float family=floor(maskUv.y*.5);
vec2 materialUv=vec2(maskUv.x,maskUv.y-family*2.0);
vec3 base=normalize(cross(dx,dy));if(dot(base,-relativePosition)<0.0)base=-base;
if(abs(det)<1e-14||length(relativePosition)>=ReflectionParams.w)discard;
// The receiver depth attachment rejects hidden and secondary surfaces before ray tracing.
vec4 texel=textureGrad(BlockAtlas,blockUv,tx,ty);if(family<.5&&texel.a<.99)discard;
vec2 center=(floor(materialUv*1280.0)+.5)/1280.0;
vec3 u=(dx*my.y-dy*mx.y)/det,v=(dy*mx.x-dx*my.x)/det;
vec3 point=relativePosition+u*(center.x-materialUv.x)+v*(center.y-materialUv.y);
vec4 material=textureLod(MaterialAtlas,center,0);
vec2 slope=(material.rg*255.0-128.0)/127.0*ReflectionParams.z*(family>1.5?.24:2.0);
vec3 normal=normalize(base+normalize(u)*slope.x+normalize(v)*slope.y);
if(any(isnan(normal))||any(isinf(normal)))discard;
vec4 hit=trace(point,normal,base);if(hit.w<=0.0)discard;
vec3 reflected=textureLod(OpaqueColor,hit.xy,0).rgb;
if(material.b>.3){
vec2 stepUv=vec2(material.b*3.0)/vec2(textureSize(OpaqueColor,0));
float reference=length(reconstruct(hit.xy,textureLod(OpaqueDepth,hit.xy,0).r));
vec3 sum=vec3(0);float weight=0;
for(int i=0;i<4;i++){
vec2 uv=hit.xy+vec2(i%2==0?-1:1,i<2?-1:1)*stepUv;
float d=textureLod(OpaqueDepth,uv,0).r;
if(d>0.0&&abs(length(reconstruct(uv,d))-reference)<.25+reference*.002){sum+=textureLod(OpaqueColor,uv,0).rgb;weight+=1.0;}
}
if(weight>0.0)reflected=sum/weight;
}
float nv=clamp(dot(normal,normalize(-point)),0.0,1.0),grazing=1.0-nv,g2=grazing*grazing;
// Metal tint is sampled at the same texel centre, never at the individual screen fragment.
vec2 localDelta=center-materialUv;
vec2 centerBlock=blockUv+(tx*my.y-ty*mx.y)/det*localDelta.x+(ty*mx.x-tx*my.x)/det*localDelta.y;
vec3 albedo=textureLod(BlockAtlas,centerBlock,0).rgb*tint.rgb;
vec3 f0=mix(vec3(family>1.5?.02:.04),albedo*albedo,material.a);
vec3 fresnel=f0+(1.0-f0)*(g2*g2*grazing);
float fade=(1.0-smoothstep(24.0,32.0,length(point)))*hit.w;
vec3 weight=clamp(fresnel*ReflectionParams.y*(1.0-material.b*material.b)*fade,0.0,.9);
vec3 scene=texelFetch(SceneColor,ivec2(gl_FragCoord.xy),0).rgb;
vec3 result=mix(scene*scene,reflected*reflected,weight);
if(any(isnan(result))||any(isinf(result)))discard;
fragColor=vec4(sqrt(clamp(result,0.0,1.0)),1);
}
@@ -184,9 +184,6 @@
"NaturalSnowEditMixin"
],
"client": [
"client.ReflectionSceneMixin",
"client.PbrAnimationClockMixin",
"client.PbrAnimationSpriteMixin",
"client.PackSelectionScreenMixin",
"client.FourneauFireMixin",
"client.BoatPassengerPickMixin",
+1 -1
View File
@@ -1,6 +1,6 @@
name = "Sanctuary"
author = "KOKA99CAB"
version = "beta.145"
version = "beta.144"
pack-format = "packwiz:1.1.0"
[index]
+3
View File
@@ -12,11 +12,14 @@ backend=log_path.stem
log=log_path.read_text()
rows={key:json.loads(data) for key,data in re.findall(r"WATER144_PERF (\S+) (\[[^\n]+\])",log)}
assert len(rows)==24, ("Incomplete measurements",len(rows))
assert log.count("WATER144_CONDITIONS limit=260 throttle=NONE")==24, "Measurements must be uncapped"
result={"backend":backend,"samples":rows,"scenes":{}}
for scene in ("mixed","large","moving"):
off=[v for k,v in rows.items() if k.startswith(scene+"-false-")]
on=[v for k,v in rows.items() if k.startswith(scene+"-true-")]
assert len(off)==len(on)==4 and all(v[0]>50 for v in off+on)
if scene=="moving":
assert all(v[3]>0 for v in off+on), "Moving scene must compile terrain sections"
median_off=sum(v[1] for v in off)/len(off);median_on=sum(v[1] for v in on)/len(on)
p95_off=sum(v[2] for v in off)/len(off);p95_on=sum(v[2] for v in on)/len(on)
value={"offMedianMs":median_off,"onMedianMs":median_on,"medianIncreasePercent":100*(median_on/median_off-1),"offP95Ms":p95_off,"onP95Ms":p95_on,"p95IncreaseMs":p95_on-p95_off}
-4
View File
@@ -11,7 +11,3 @@ la version exacte du jeu et du moteur Iris.
La beta.144 ajoute l’[eau naturelle](../docs/natural-water-beta144.md) dans
le rendu natif : profils selon le fond, océans clairs et brume sous-marine.
La livraison locale beta.145 ajoute le [PBR de l’eau et du verre ainsi que les
reflets pixélisés](../docs/pbr-ssr.md). SSR désactivé par défaut ; aucune
dépendance graphique externe.