Compare commits

..

4 Commits

Author SHA1 Message Date
Siphonight
dd1bc5ba29 v0.13.1 : bump version (3 endroits) + CHANGELOG patch IA NavMesh 2026-11-16 04:46:18 +01:00
Elden
f8f77590b2 NavMesh : repli cellule sans liens + chute encoche + borne chute gauche
Trois corrections du retour "aucun chemin NavMesh en boucle" (Pixel 8
Pro, v0.12.x : ennemi figé à (1059,25400), joueur 700-1500 px plus bas,
cycle acquisition/abandon) :

1. resolveNavCell (NavMesh + 3 appelants Behaviour) : une entité au BORD
   d'un plancher mappe par round(x/100) sur la colonne du VIDE à côté
   (corps 200 px à cheval) — cellule d'air sans liens, la garde
   !self.links.isEmpty() de Behaviour.refusait alors de calculer le
   chemin : "aucun chemin" immédiat même quand une route existe. Repli
   voisin i±1 même ligne (le plancher sous l'entité) ; sim : 4,9 % des
   positions d'entités touchées, 100 % réparées.

2. Chute en ENCOCHE (branche RIGHT) : le puits de chute peut se
   terminer sur un sol sous la colonne lointaine x+2 alors que x+1
   reste ouvert plus bas ; le bloc 2017 posait x+1 dans ses DEUX
   branches identiques -> atterrissage en plein air, NavPoint cible
   sans lien de marche, descente morte à cet étage (propre : ennemi
   (34,294), puits colonnes 35-36, sol sous 36). La branche LEFT
   gérait déjà le cas (x-2 vs x-1) : branche RIGHT rendue symétrique.

3. Borne chute gauche : x - 2 > 0 -> x - 2 >= 0 (la colonne 2 était
   exclue à tort : x-2 = 0 est dans la grille).

Limites documentées (sim, 452 couples spawner/joueur sur 12 seeds) :
64,4 % de chemins trouvés ; ~6 % nécessitent un "saut par-dessus
muret" non modélisé (classe hétérogène, à arbitrer sur émulateur) ;
~30 % d'isolation réelle (le joueur y va par double saut/wall jump,
IA volontairement plus limitée) — refus assumé, couvert par la
blacklist 15 s + fallback cryopod.
2026-11-16 04:37:09 +01:00
Elden
cfca00c5fd Outils : sim de connectivité NavMesh (repro sans émulateur)
POURQUOI : les remontées "aucun chemin NavMesh" (Pixel 8 Pro) sont
indisable sur émulateur et le gamelog ne montre que le symptôme. Ces
scripts Python reproduisent SANS rendu ni émulateur :
- la génération procédurale (MapManager.loadProceduralMap porté au
  ligne près : java.util.Random, ordre HashMap, connecteurs, verrous,
  solidité, portes) ;
- NavMesh.init (fillIn, liens marche/chute/saut) et getPath (BFS) ;
- le spawn Exterminate (raycast de sol, ±1500 px vertical) ;
- un oracle physique (marche / chute par bord / saut <= 3 lignes) pour
  séparer l'isolation RÉELLE des liens manquants.

Les drapeaux fix_notch / fix_left_bound / _resolve_links reproduisent
exactement le patch NavMesh/Behaviour pour les mesures avant/après.
Résultats cités dans le commentaire de NavMesh.resolveNavCell.
2026-11-16 04:37:09 +01:00
Siphonight
a424aab013 QA v0.13.0 P3 : Laser removeComponent mort retiré + blacklist IA purgée à l'expiration 2026-11-16 03:26:34 +01:00
15 changed files with 1600 additions and 20 deletions

View File

@ -8,6 +8,29 @@ lignée du jeu amont (0.2.2 en 2017, abandonné).
_(vide — prochaine fonctionnalité)_ _(vide — prochaine fonctionnalité)_
## [0.13.1] — 2026-11-16
Patch IA NavMesh : connectivité inter-étages (diagnostic par simulation
`tools/sim/` portée fidèle au moteur — repro du gamelog utilisateur).
### Corrigé
- **« aucun chemin NavMesh » au bord des planchers** (cause dominante du
spam d'acquisition/abandon) : un ennemi 200×200 px à cheval sur le bord
d'un plancher mappe sa cellule de nav dans le VIDE sans aucun lien — le
court-circuit `!self.links.isEmpty()` de `getPath` refusait alors de
calculer un chemin MÊME QUAND UNE ROUTE EXISTAIT (4,9 % des positions
d'entités, 100 % réparables) ; `NavMesh.resolveNavCell` replie sur le
voisin de ligne i±1, utilisée par les 3 sites de mapping de Behaviour
- **Chutes atterrissant en plein air** : la branche RIGHT du bloc FALL
2017 posait le landing dans ses deux branches identiques (code mort) —
landing rerouté sur la colonne qui a un appui (symétrique de LEFT) ;
borne 2017 `x-2 > 0` corrigée (excluait la chute gauche depuis la
colonne 2)
- Sim v0.13.1 : couples spawner/joueur avec chemin 63,1 % → 64,4 %,
positions sans liens 4,9 % → 0 % ; limites documentées (toits de
salles de spawn scellés ~98 % — couverts par la blacklist 15 s ;
« saut par-dessus muret » ~6 % non modélisé)
## [0.13.0] — 2026-11-16 ## [0.13.0] — 2026-11-16
Fonctionnalités + équilibrage (retours du test Android v0.12.x + desktop). Fonctionnalités + équilibrage (retours du test Android v0.12.x + desktop).
@ -547,6 +570,7 @@ et découvre un port Android complet avec HUD tactile.
[0.6.0]: https://gitea.cloudyfy.fr/Siphonight/lost-sector-port/compare/v0.5.0...v0.6.0 [0.6.0]: https://gitea.cloudyfy.fr/Siphonight/lost-sector-port/compare/v0.5.0...v0.6.0
[0.5.0]: https://gitea.cloudyfy.fr/Siphonight/lost-sector-port/compare/v0.4.0...v0.5.0 [0.5.0]: https://gitea.cloudyfy.fr/Siphonight/lost-sector-port/compare/v0.4.0...v0.5.0
[0.13.1]: https://gitea.cloudyfy.fr/Siphonight/lost-sector-port/compare/v0.13.0...v0.13.1
[0.13.0]: https://gitea.cloudyfy.fr/Siphonight/lost-sector-port/compare/v0.12.1...v0.13.0 [0.13.0]: https://gitea.cloudyfy.fr/Siphonight/lost-sector-port/compare/v0.12.1...v0.13.0
[0.12.1]: https://gitea.cloudyfy.fr/Siphonight/lost-sector-port/compare/v0.12.0...v0.12.1 [0.12.1]: https://gitea.cloudyfy.fr/Siphonight/lost-sector-port/compare/v0.12.0...v0.12.1
[0.12.0]: https://gitea.cloudyfy.fr/Siphonight/lost-sector-port/compare/v0.11.0...v0.12.0 [0.12.0]: https://gitea.cloudyfy.fr/Siphonight/lost-sector-port/compare/v0.11.0...v0.12.0

View File

@ -39,8 +39,8 @@ android {
// la constante, la numérotation APK vient d'ici — deux sources qui // la constante, la numérotation APK vient d'ici — deux sources qui
// doivent rester en phase (leçon v0.4.0..v0.11.0 : versionName // doivent rester en phase (leçon v0.4.0..v0.11.0 : versionName
// restée '0.2.2' faute de bump). // restée '0.2.2' faute de bump).
versionCode 14 versionCode 15
versionName '0.13.0' versionName '0.13.1'
} }
compileOptions { compileOptions {

View File

@ -13,7 +13,7 @@ public final class Dethsquare {
* fuite v0.4.0..v0.11.0 sur versionName restée '0.2.2' montre ce que * fuite v0.4.0..v0.11.0 sur versionName restée '0.2.2' montre ce que
* coûte un bump oublié — ce champ ne doit pas suivre le même chemin). * coûte un bump oublié — ce champ ne doit pas suivre le même chemin).
*/ */
public static final String VERSION = "0.13.0"; public static final String VERSION = "0.13.1";
public static Platform PLATFORM; public static Platform PLATFORM;
public static AudioUtils AUDIO; public static AudioUtils AUDIO;

View File

@ -111,9 +111,20 @@ public class NavMesh {
* On signale ici, log throttlé 1/300 frames (politique AGENTS.md), * On signale ici, log throttlé 1/300 frames (politique AGENTS.md),
* et on rend un chemin vide : l'ennemi reste sur place (comportement * et on rend un chemin vide : l'ennemi reste sur place (comportement
* dégradé assumé, PAS de téléportation ni de crash). * dégradé assumé, PAS de téléportation ni de crash).
*
* Résolution des cellules SANS liens (v0.13.0, retour utilisateur
* "aucun chemin NavMesh en boucle" Pixel 8 Pro) : une entité au BORD
* d'un plancher a son corps (200 px = 2 cellules) à cheval sur le
* bord et le vide — round(x/100) mappe alors sur la colonne du VIDE,
* une cellule d'air sans aucun lien ; Behaviour.getPath refusait de
* calculer (garde !self.links.isEmpty()) -> "aucun chemin" immédiat
* MÊME quand un chemin existe. Sim (tools/sim/) : 4,9 % des positions
* d'entités tombent sur une cellule sans liens, 100 % réparables par
* le voisin horizontal i±1 (même ligne) qui EST le plancher sous
* l'entité. On teste donc i-1 puis i+1 avant de renoncer.
*/ */
NavPoint start = getNavPoint(a); NavPoint start = resolveNavCell(a);
NavPoint end = getNavPoint(b); NavPoint end = resolveNavCell(b);
if (start == null || end == null) { if (start == null || end == null) {
if (Time.frameCount % 300 == 0) { if (Time.frameCount % 300 == 0) {
GameLog.d("LS-AI", "getPath : position hors grille NavMesh (a=" + a GameLog.d("LS-AI", "getPath : position hors grille NavMesh (a=" + a
@ -125,6 +136,33 @@ public class NavMesh {
return getPath(start, end); return getPath(start, end);
} }
/**
* Cellule nav d'une position, avec repli horizontal : si la cellule
* mappée (round(x/100), round(y/100)+1) n'a AUCUN lien (air au bord d'un
* plancher, entité en transition), on renvoie le voisin i-1 ou i+1 de la
* MÊME ligne s'il est chaîné — c'est le plancher réellement sous l'entité
* (corps de 200 px = 2 colonnes, cf. getPath(Vector2, Vector2)).
* POURQUOI public : Behaviour.getPath garde son court-circuit
* !self.links.isEmpty() et appelle la surcharge (NavPoint, NavPoint) —
* le repli doit donc être appliqué PAR L'APPELANT, au moment du mapping
* position -> NavPoint, sinon il n'est jamais atteint (sim : 4,9 % des
* positions d'entités sans liens, 100 % réparables par i±1).
* Sans repli valable, on renvoie la cellule d'origine (null incluse) :
* comportement dégradé inchangé.
*/
public static NavPoint resolveNavCell(Vector2 position) {
NavPoint p = getNavPoint(position);
if (p == null || !p.links.isEmpty()) return p;
int i = Math.round(position.x / 100f);
int j = Math.round(position.y / 100f) + 1;
for (int d = -1; d <= 1; d += 2) {
int ni = i + d;
if (ni < 0 || ni >= navPoints.length || j < 0 || j >= navPoints[0].length) continue;
if (!navPoints[ni][j].links.isEmpty()) return navPoints[ni][j];
}
return p;
}
public static NavPoint[] getPath(NavPoint start, NavPoint end) { public static NavPoint[] getPath(NavPoint start, NavPoint end) {
if (start == null || end == null) return new NavPoint[0]; if (start == null || end == null) return new NavPoint[0];
@ -283,6 +321,13 @@ public class NavMesh {
for (int x = 0; x < navPoints.length; x++) { for (int x = 0; x < navPoints.length; x++) {
for (int y = 0; y < navPoints[x].length; y++) { for (int y = 0; y < navPoints[x].length; y++) {
if (navPoints[x][y].type == NavPointType.RIGHT_EDGE || navPoints[x][y].type == NavPointType.SOLO) { if (navPoints[x][y].type == NavPointType.RIGHT_EDGE || navPoints[x][y].type == NavPointType.SOLO) {
/*
* La chute exige 2 colonnes libres (l'ennemi fait 200 px
* de large : son corps chevauche x+1 et x+2) au niveau du
* corps ET de la tête ; x+2 doit exister dans la grille
* pour que le test de paroi ait un sens — addLink garde
* de toute façon les bornes.
*/
if (x + 2 < navPoints.length && !isCollision(solidityMap, x + 1, y) && !isCollision(solidityMap, x + 2, y) && !isCollision(solidityMap, x + 1, y - 1) && if (x + 2 < navPoints.length && !isCollision(solidityMap, x + 1, y) && !isCollision(solidityMap, x + 2, y) && !isCollision(solidityMap, x + 1, y - 1) &&
!isCollision(solidityMap, x + 2, y - 1)) { !isCollision(solidityMap, x + 2, y - 1)) {
int yTemp = y + 1; int yTemp = y + 1;
@ -290,21 +335,44 @@ public class NavMesh {
yTemp++; yTemp++;
} }
yTemp--; yTemp--;
/*
* Atterrissage de la chute (v0.13.0) : le puits peut
* se terminer en ENCOCHE — un sol sous la colonne
* lointaine x+2 alors que x+1 reste ouvert plus bas.
* Le bloc 2017 posait x+1 dans LES DEUX branches
* (code mort if/else identique) : l'atterrissage
* tombait EN PLEIN AIR au-dessus de l'encoche, le
* NavPoint cible n'avait aucun lien de marche ->
* cul-de-sac -> la descente mourait là (prouvé en
* sim : ennemi (34,294), puits colonnes 35-36, sol
* sous 36 seulement). La branche LEFT gérait déjà
* ce cas (x-2 vs x-1) : on rend la branche RIGHT
* symétrique — atterrir sur la colonne qui a un
* appui sous yTemp+1.
*/
int landingX;
if (isCollision(solidityMap, x + 1, yTemp + 1)) { if (isCollision(solidityMap, x + 1, yTemp + 1)) {
addLink(x, y, x + 1, yTemp, LinkType.FALL); landingX = x + 1;
if (yTemp - (y + 1) < 3) {
addLink(x, y, x + 1, yTemp, LinkType.JUMP);
}
} else { } else {
addLink(x, y, x + 1, yTemp, LinkType.FALL); landingX = x + 2;
if (yTemp - (y + 1) < 3) { }
addLink(x, y, x + 1, yTemp, LinkType.JUMP); addLink(x, y, landingX, yTemp, LinkType.FALL);
} if (yTemp - (y + 1) < 3) {
addLink(x, y, landingX, yTemp, LinkType.JUMP);
} }
} }
} }
if (navPoints[x][y].type == NavPointType.LEFT_EDGE || navPoints[x][y].type == NavPointType.SOLO) { if (navPoints[x][y].type == NavPointType.LEFT_EDGE || navPoints[x][y].type == NavPointType.SOLO) {
if (x - 2 > 0 && !isCollision(solidityMap, x - 1, y) && !isCollision(solidityMap, x - 2, y) && !isCollision(solidityMap, x - 1, y - 1) && !isCollision(solidityMap, x - 2, y - 1)) { /*
* Borne corrigée v0.13.0 : `x - 2 > 0` excluait la chute
* vers la gauche depuis la colonne 2 (x-2 = 0 est DANS la
* grille : le corps de l'ennemi, colonnes 2-3, tombe
* bien à travers les colonnes 1-0). La colonne 1 reste
* exclue (x-2 = -1 hors grille = paroi, corps trop
* large pour le puits) — isCollision renvoie vrai hors
* bornes, le test de paroi le refuse seul.
*/
if (x - 2 >= 0 && !isCollision(solidityMap, x - 1, y) && !isCollision(solidityMap, x - 2, y) && !isCollision(solidityMap, x - 1, y - 1) && !isCollision(solidityMap, x - 2, y - 1)) {
int yTemp = y + 1; int yTemp = y + 1;
while (yTemp < navPoints[x].length - 1 && !isCollision(solidityMap, x - 1, yTemp) && !isCollision(solidityMap, x - 2, yTemp)) { while (yTemp < navPoints[x].length - 1 && !isCollision(solidityMap, x - 1, yTemp) && !isCollision(solidityMap, x - 2, yTemp)) {
yTemp++; yTemp++;

View File

@ -270,8 +270,18 @@ public abstract class Behaviour {
path = null; path = null;
return path; return path;
} }
NavPoint self = NavMesh.getNavPoint(transform.position.x, transform.position.y); /*
NavPoint targetNavPoint = NavMesh.getNavPoint(target.position); * resolveNavCell (v0.13.0) : une entité au BORD d'un plancher mappe
* par round(x/100) sur la colonne du VIDE à côté du bord (corps de
* 200 px à cheval) — cellule d'air sans liens -> la garde
* !self.links.isEmpty() ci-dessous refusait de calculer le chemin ->
* "aucun chemin NavMesh" en boucle sans même essayer (retour Pixel
* 8 Pro : ennemi figé à 1059,25400, joueur 1-2 étages plus bas).
* Le repli prend le voisin i±1 de la même ligne = le plancher sous
* l'entité ; sim : 100 % des cas réparés.
*/
NavPoint self = NavMesh.resolveNavCell(transform.position);
NavPoint targetNavPoint = NavMesh.resolveNavCell(target.position);
/* /*
* Hors grille (v0.12.x) : getNavPoint renvoie null pour une position * Hors grille (v0.12.x) : getNavPoint renvoie null pour une position
* hors du graphe. Pas de recalcul ni de NPE — l'ennemi reste sur place * hors du graphe. Pas de recalcul ni de NPE — l'ennemi reste sur place
@ -326,6 +336,9 @@ public abstract class Behaviour {
target = null; target = null;
targetIsObjective = false; targetIsObjective = false;
pathFailStart = 0; pathFailStart = 0;
// QA v0.13.0 P3 : purger la référence au cooldown expire (sinon
// le GameObject joueur reste retenu — bénin mais sale).
// L'expiration est testée à chaque visionCheck ci-dessous.
} }
if (target != null && Time.frameCount % 300 == 0) { if (target != null && Time.frameCount % 300 == 0) {
GameLog.d("LS-AI", transform.gameObject.name + " : aucun chemin NavMesh vers " GameLog.d("LS-AI", transform.gameObject.name + " : aucun chemin NavMesh vers "
@ -379,7 +392,10 @@ public abstract class Behaviour {
} else { } else {
// Cellule courante changée (en marche / chute) : chemin recalcule // Cellule courante changée (en marche / chute) : chemin recalcule
// depuis la cellule réelle vers la MÊME destination. // depuis la cellule réelle vers la MÊME destination.
NavPoint self = NavMesh.getNavPoint(transform.position.x, transform.position.y); // resolveNavCell : même repli que getPath (entité au bord d'un
// plancher -> cellule d'air sans liens -> patrouille jamais
// calculée, cf. Behaviour.getPath).
NavPoint self = NavMesh.resolveNavCell(transform.position);
if (self != null && !self.equals(patrolFrom)) { if (self != null && !self.equals(patrolFrom)) {
patrolFrom = self; patrolFrom = self;
patrolPath = NavMesh.getPath(self, patrolDestination); patrolPath = NavMesh.getPath(self, patrolDestination);
@ -415,7 +431,10 @@ public abstract class Behaviour {
private void choosePatrolDestination() { private void choosePatrolDestination() {
patrolPath = null; patrolPath = null;
patrolDestination = null; patrolDestination = null;
NavPoint self = NavMesh.getNavPoint(transform.position.x, transform.position.y); // resolveNavCell : même repli que getPath (entité au bord d'un
// plancher -> cellule d'air sans liens -> 0 candidat -> pas de
// patrouille, cf. Behaviour.getPath).
NavPoint self = NavMesh.resolveNavCell(transform.position);
if (self == null) return; if (self == null) return;
NavPoint[] candidates = NavMesh.getReachableNavPoints(self, PATROL_RADIUS); NavPoint[] candidates = NavMesh.getReachableNavPoints(self, PATROL_RADIUS);
if (candidates.length == 0) return; if (candidates.length == 0) return;
@ -534,6 +553,9 @@ public abstract class Behaviour {
// Blacklist anti-boucle : ne PAS ré-acquérir le joueur tenu sur la // Blacklist anti-boucle : ne PAS ré-acquérir le joueur tenu sur la
// position injoignable tant que le cooldown court (cf. champ). // position injoignable tant que le cooldown court (cf. champ).
boolean cooldownActive = System.currentTimeMillis() < unreachableTargetCooldown; boolean cooldownActive = System.currentTimeMillis() < unreachableTargetCooldown;
if (!cooldownActive) {
lastUnreachableTargetObj = null; // référence purgée à l'expiration (QA P3)
}
for (GameObject player : players) { for (GameObject player : players) {
float dist = (float) Vector2.distance(transform.position, player.transform.position); float dist = (float) Vector2.distance(transform.position, player.transform.position);
if (cooldownActive && player == lastUnreachableTargetObj) { if (cooldownActive && player == lastUnreachableTargetObj) {

View File

@ -43,11 +43,11 @@ public class Laser extends Script {
@Override @Override
public void onTriggerEnter(Collider other) { public void onTriggerEnter(Collider other) {
if (other.gameObject.getLayer() == solidLayer) { if (other.gameObject.getLayer() == solidLayer) {
gameObject.removeComponent(Collider.class); // QA v0.13.0 P3 : removeComponent suivi d'un destroy immédiat
// est un appel mort (le destroy purge tout) — retiré.
GameObject.destroy(gameObject); GameObject.destroy(gameObject);
} else if (other.gameObject.getTag() != null) { } else if (other.gameObject.getTag() != null) {
if ("projectile-barrier".equals(other.gameObject.getTag())) { if ("projectile-barrier".equals(other.gameObject.getTag())) {
gameObject.removeComponent(Collider.class);
GameObject.destroy(gameObject); GameObject.destroy(gameObject);
} }
for (String tag : targetTags) { for (String tag : targetTags) {

View File

@ -0,0 +1,114 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Catégorisation des échecs de descente : pour chaque seed, TOUS les couples
(cellule debout ennemie AU-DESSUS, cellule debout joueur EN DESSOUS, quasi
verticaux Δx<=8, Δlignes 1..15) comme le scénario du log v0.12.x.
Catégories :
A cible_sans_liens : la cellule du joueur n'a aucun lien (BFS ne peut rien)
B ennemi_sans_liens : la cellule de l'ennemi n'a aucun lien
C descente_bloquee : le plus bas joignable depuis l'ennemi reste AU-DESSUS
de la ligne du joueur (barrière verticale)
D barriere_horizontale : l'ennemi atteint la ligne du joueur mais pas sa
cellule (trou/mur au même niveau)
E ok : chemin trouvé
"""
import sys
sys.path.insert(0, "tools/sim")
from navmesh_connectivity import (load_segments, generate_map, NavMeshSim,
standable)
def categorize_seed(seed, segs, dx_max=8, drop_min=1, drop_max=15, fixes=False):
solid, _, _ = generate_map(seed, segs)
sim = NavMeshSim(solid)
sim.init((20.0, 20.0), fix_notch=fixes, fix_left_bound=fixes)
stand = [(i, j) for i in range(sim.W) for j in range(sim.H) if standable(sim, i, j)]
stand_set = set(stand)
by_col = {}
for (i, j) in stand:
by_col.setdefault(i, []).append(j)
cats = {"A": 0, "B": 0, "C": 0, "D": 0, "E": 0}
details = {"A": [], "B": [], "C": [], "D": []}
drops = {"E": [], "C": [], "D": []}
for (ei, ej) in stand:
for di in range(-dx_max, dx_max + 1):
i2 = ei + di
if i2 < 0 or i2 >= sim.W:
continue
for j2 in by_col.get(i2, []):
if not (drop_min <= j2 - ej <= drop_max):
continue # joueur EN DESSOUS
pn = sim.nav[i2][j2]
en = sim.nav[ei][ej]
if len(pn.links) == 0:
cats["A"] += 1
if len(details["A"]) < 3:
details["A"].append((ecell := (ei, ej), (i2, j2)))
continue
if len(en.links) == 0:
cats["B"] += 1
if len(details["B"]) < 3:
details["B"].append(((ei, ej), (i2, j2)))
continue
path = sim.get_path(en, pn)
if len(path) > 0:
cats["E"] += 1
drops["E"].append(j2 - ej)
continue
reach = sim.reachable(en)
stand_reach = [(p.x // 100, p.y // 100) for p in reach
if (p.x // 100, p.y // 100) in stand_set]
deepest = max((r[1] for r in stand_reach), default=-1)
if deepest < j2:
cats["C"] += 1
drops["C"].append(deepest - ej)
if len(details["C"]) < 4:
details["C"].append(((ei, ej), (i2, j2), deepest - ej))
else:
cats["D"] += 1
if len(details["D"]) < 4:
details["D"].append(((ei, ej), (i2, j2)))
return cats, drops, details
def main():
n_seeds = int(sys.argv[1]) if len(sys.argv) > 1 else 12
fixes = len(sys.argv) > 2 and sys.argv[2] == "fix"
segs = load_segments()
tot = {"A": 0, "B": 0, "C": 0, "D": 0, "E": 0}
dl = {"E": [], "C": [], "D": []}
det = {"A": [], "B": [], "C": [], "D": []}
for k in range(n_seeds):
seed = 1_000_000 + k * 7919
cats, drops, details = categorize_seed(seed, segs, fixes=fixes)
for c in tot:
tot[c] += cats[c]
for c in dl:
dl[c].extend(drops[c])
for c in det:
det[c].extend(details[c][:2])
s = sum(tot.values())
print("couples ennemi-au-dessus/joueur-en-dessous testés : %d%s" % (s, " [FIXES]" if fixes else ""))
for c, label in (("E", "ok"), ("A", "cible_sans_liens"), ("B", "ennemi_sans_liens"),
("C", "descente_bloquee_(verticale)"), ("D", "barriere_horizontale")):
print(" %s %-30s %5d (%.1f%%)" % (c, label, tot[c], 100.0 * tot[c] / s))
for c in ("E", "C", "D"):
if dl[c]:
dl[c].sort()
print(" Δlignes %s : médiane=%d max=%d min=%d" %
(c, dl[c][len(dl[c]) // 2], dl[c][-1], dl[c][0]))
print("\nexemples C (descente bloquée, Δréalisé vs Δdemandé) :")
for d in det["C"][:4]:
print(" ennemi=%s joueur=%s profondeur_atteinte=%d" % (d[0], d[1], d[2]))
print("exemples D (barrière horizontale) :")
for d in det["D"][:4]:
print(" ennemi=%s joueur=%s" % (d[0], d[1]))
print("exemples A (cible sans liens) :")
for d in det["A"][:4]:
print(" ennemi=%s joueur=%s" % (d[0], d[1]))
if __name__ == "__main__":
main()

View File

@ -0,0 +1,798 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Sim de connectivité NavMesh — port fidèle (Python) de :
- MapManager.loadProceduralMap (placement segments + solidité + spawn joueur)
- NavMesh.init (fillIn, walk/fall/jump links) et NavMesh.getPath (BFS)
- ExterminateMission (logique de spawn d'ennemi autour du joueur)
POURQUOI : diagnostiquer "aucun chemin NavMesh" entre étages voisins SANS
émulateur (gamelog v0.12.x Pixel 8 Pro : ennemi y=25400 ne joint jamais le
joueur y=26100-26900). Le port reproduit le code au ligne près ; toute
divergence doit être justifiée par un commentaire.
Usage : python3 tools/sim/navmesh_connectivity.py [nb_seeds]
"""
import os
import sys
import xml.etree.ElementTree as ET
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
SEG_DIR = os.path.join(ROOT, "lost-sector/src/main/resources/maps/procedural/corpus")
TILE_PX = 100 # 1 tuile TMX (16px) * MAP_SCALE 6.25 = 100 px monde
PROC_START = (0, 256) # tuiles (MapManager.PROC_START_POS)
NUM_ROOMS = 16
SEG_SIZE = 16
# ---------------------------------------------------------------- Java Random
MASK48 = (1 << 48) - 1
MULT = 0x5DEECE66D
ADD = 0xB
def s32(v):
v &= 0xFFFFFFFF
return v - 0x100000000 if v >= 0x80000000 else v
class JavaRandom:
def __init__(self, seed):
self.seed = (seed ^ MULT) & MASK48
def next(self, bits):
self.seed = (self.seed * MULT + ADD) & MASK48
return s32(self.seed >> (48 - bits)) if bits < 32 else s32(self.seed)
def next_int(self, bound):
if bound <= 0:
raise ValueError("bound must be positive")
if (bound & -bound) == bound:
return s32((bound * self.next(31)) >> 31)
while True:
bits = self.next(31) & 0x7FFFFFFF
val = bits % bound
if bits - val + (bound - 1) < (1 << 31):
return val
def s_hash(s):
h = 0
for c in s:
h = (h * 31 + ord(c)) & 0xFFFFFFFF
if h >= 0x80000000:
h -= 0x100000000
return h
class JavaHashMap:
"""Ordre d'itération de HashMap<String, V> (capacité 16, spread h^h>>>16)."""
def __init__(self):
self.table = [[] for _ in range(16)]
self.n = 0
def _spread(self, key):
h = s_hash(key) & 0xFFFFFFFF
return h ^ (h >> 16)
def _bucket(self, key):
return self._spread(key) & (len(self.table) - 1)
def put(self, key, value):
if self.n + 1 > len(self.table) * 0.75:
old = self.table
self.table = [[] for _ in range(len(old) * 2)]
for b in old:
for k, v in b:
self.table[self._bucket(k)].append((k, v))
b = self.table[self._bucket(key)]
for i, (k, _) in enumerate(b):
if k == key:
b[i] = (key, value)
return
b.append((key, value))
self.n += 1
def get(self, key):
b = self.table[self._bucket(key)]
for k, v in b:
if k == key:
return v
return None
def contains(self, key):
return self.get(key) is not None
def values(self):
out = []
for b in self.table:
for _, v in b:
out.append(v)
return out
# ---------------------------------------------------------------------- TMX
class TmxMap:
def __init__(self, path):
self.path = path
r = ET.parse(path).getroot()
self.w = int(r.get("width"))
self.h = int(r.get("height"))
self.tw = int(r.get("tilewidth"))
self.th = int(r.get("tileheight"))
self.layers = [] # (name, [gid]) dans l'ordre du fichier
self.objgroups = [] # (name, [obj dict])
for el in r:
if el.tag == "layer":
gids = []
data = el.find("data")
for t in data.findall("tile"):
g = t.get("gid")
if g is None:
g = t.get("id")
gids.append(int(g) if g is not None else 0)
# complète si le fichier n'écrit pas les cases vides
while len(gids) < self.w * self.h:
gids.append(0)
self.layers.append((el.get("name"), gids))
elif el.tag == "objectgroup":
objs = []
for o in el.findall("object"):
objs.append({
"type": o.get("type") or "",
"name": o.get("name") or "",
"x": int(o.get("x")),
"y": int(o.get("y")),
"w": int(o.get("width") or 0),
"h": int(o.get("height") or 0),
})
self.objgroups.append((el.get("name") or "", objs))
def load_segments():
d = {}
for cat in ("spawn", "main", "end", "extract", "lock"):
p = os.path.join(SEG_DIR, cat)
files = sorted(f for f in os.listdir(p) if f.endswith(".tmx"))
d[cat] = [TmxMap(os.path.join(p, f)) for f in files]
return d
class Conn:
def __init__(self, seg_map, obj):
self.map = seg_map
str_ = obj["type"]
self.pos = (obj["x"], obj["y"])
self.connection = None
parts = str_.split("_")
self.side = {"c": "CENTRE", "t": "TOP", "r": "RIGHT",
"b": "BOTTOM", "l": "LEFT"}.get(parts[0], "CENTRE")
self.type = int(parts[1])
if len(parts) >= 3:
self.lock = int(parts[2])
self.side_type = parts[0] + "_" + parts[1]
else:
self.lock = 0
self.side_type = str_
str_ += "_0"
self.str = str_
def is_valid_connection(self, other):
want = {"CENTRE": "CENTRE", "TOP": "BOTTOM", "RIGHT": "LEFT",
"BOTTOM": "TOP", "LEFT": "RIGHT"}[self.side]
return want == other.side and self.type == other.type
def matching_side_type(self):
pre = {"CENTRE": "c_", "TOP": "b_", "RIGHT": "l_",
"BOTTOM": "t_", "LEFT": "r_"}[self.side]
return pre + str(self.type)
class Seg:
def __init__(self, tmx):
self.map = tmx
self.pos = None
self.connectors = []
for name, objs in tmx.objgroups:
if name == "connectors":
for o in objs:
self.connectors.append(Conn(tmx, o))
self.w = tmx.w
self.h = tmx.h
# ------------------------------------------------- génération (MapManager)
def get_rand_obj(arr, rnd):
if len(arr) == 0:
return None
return arr[rnd.next_int(len(arr))]
def get_random_valid_connector(seg, for_main_path, rnd):
valid = []
for c in seg.connectors:
if c.connection is not None:
continue
if for_main_path and c.side == "LEFT":
continue
valid.append(c)
return get_rand_obj(valid, rnd)
def get_random_valid_segment(segments_by_key, key, curr_conn, for_main_path, rnd):
arr = segments_by_key.get(key)
if arr is None or len(arr) == 0:
return None
valid = []
for seg in arr:
if for_main_path:
has_left = any(c.side == "LEFT" for c in seg.connectors)
if curr_conn.side != "RIGHT" and len(seg.connectors) <= 2 and has_left:
continue
valid.append(seg)
return get_rand_obj(valid, rnd)
def add_to_grid(grid, seg):
gx = seg.pos[0] // SEG_SIZE
gy = seg.pos[1] // SEG_SIZE
for x in range(seg.w // SEG_SIZE):
for y in range(seg.h // SEG_SIZE):
grid[gx + x][gy + y] = seg
def generate_map(seed, segs):
"""Port de loadProceduralMap : renvoie (solidity, playerSpawn, segments)."""
rnd = JavaRandom(seed)
spawn_segs_h = JavaHashMap()
main_segs_h = JavaHashMap()
end_segs_h = JavaHashMap()
extract_h = JavaHashMap()
lock_h = JavaHashMap()
def index_into(h, seg, by_str):
for c in seg.connectors:
key = c.str if by_str else c.side_type
lst = h.get(key)
if lst is None:
lst = []
h.put(key, lst)
lst.append(seg)
for m in segs["spawn"]:
index_into(spawn_segs_h, Seg(m), False)
for m in segs["main"]:
index_into(main_segs_h, Seg(m), False)
for m in segs["end"]:
index_into(end_segs_h, Seg(m), False)
for m in segs["extract"]:
index_into(extract_h, Seg(m), False)
for m in segs["lock"]:
index_into(lock_h, Seg(m), True)
W = NUM_ROOMS * SEG_SIZE + (PROC_START[0] // SEG_SIZE) * SEG_SIZE
H = NUM_ROOMS * SEG_SIZE + (PROC_START[1] // SEG_SIZE) * SEG_SIZE
solid = [[0] * H for _ in range(W)]
grid_w = NUM_ROOMS + PROC_START[0] // SEG_SIZE
grid_h = NUM_ROOMS + PROC_START[1] // SEG_SIZE
seg_grid = [[None] * grid_h for _ in range(grid_w)]
rendered = []
curr = None
off_x, off_y = PROC_START
for i in range(NUM_ROOMS):
if i == 0:
lists = spawn_segs_h.values()
chosen_list = get_rand_obj(lists, rnd)
nxt = get_rand_obj(chosen_list, rnd) if chosen_list else None
if nxt is None:
continue
else:
cc = get_random_valid_connector(curr, True, rnd)
if cc is None:
continue
if i == NUM_ROOMS - 1:
nxt = get_random_valid_segment(extract_h, cc.matching_side_type(), cc, True, rnd)
else:
nxt = get_random_valid_segment(main_segs_h, cc.matching_side_type(), cc, True, rnd)
if nxt is None:
continue
valid_next = [c for c in nxt.connectors if cc.is_valid_connection(c)]
nc = get_rand_obj(valid_next, rnd)
cc.connection = nc
nc.connection = cc
if cc.side == "TOP":
off_x += cc.pos[0] // curr.map.tw - nc.pos[0] // nxt.map.tw
off_y -= nxt.h
elif cc.side == "RIGHT":
off_x += curr.w
off_y += cc.pos[1] // curr.map.th - nc.pos[1] // nxt.map.th
elif cc.side == "BOTTOM":
off_x += cc.pos[0] // curr.map.tw - nc.pos[0] // nxt.map.tw
off_y += curr.h
elif cc.side == "LEFT":
off_x -= nxt.w
off_y += cc.pos[1] // curr.map.th - nc.pos[1] // nxt.map.th
nxt.pos = (off_x, off_y)
rendered.append(nxt)
add_to_grid(seg_grid, nxt)
curr = nxt
# verrous sur connecteurs libres
locks_to_render = []
for seg in rendered:
for c in seg.connectors:
if c.connection is not None:
continue
lst = lock_h.get(c.str)
if lst is None:
continue
lt = get_rand_obj(lst, rnd)
if lt is None:
continue
lt.pos = seg.pos
if len(lt.connectors) != 1:
pass # log 2017, aucun effet
c.connection = lt.connectors[0]
lt.connectors[0].connection = c
locks_to_render.append(lt)
rendered.extend(locks_to_render)
player_spawn = None
for seg in rendered:
ox, oy = seg.pos
for name, gids in seg.map.layers:
if name != "main":
continue
for i, g in enumerate(gids):
if g <= 0:
continue
col, row = i % seg.map.w, i // seg.map.w
x, y = col + ox, row + oy
if 0 <= x < W and 0 <= y < H:
solid[x][y] = 1
for gname, objs in seg.map.objgroups:
if gname in ("connectors", "enemies", "spawns"):
continue
for o in objs:
px = (o["x"] + ox * SEG_SIZE) * 6.25
py = (o["y"] + oy * SEG_SIZE) * 6.25
if o["type"] == "player_spawn":
player_spawn = (px, py)
if "door" in o["type"]:
for (dx, dy) in ((0, 0), (1, 0), (0, 4), (1, 4)):
try:
solid[int(px / 100) + dx][int(py / 100) + dy] = 1
except IndexError:
pass
return solid, player_spawn, rendered
# ------------------------------------------------------------ NavMesh (port)
NONE_, PLATFORM, LEFT_EDGE, RIGHT_EDGE, SOLO = 0, 1, 2, 3, 4
WALK, FALL, JUMP = 0, 1, 2
class NP:
__slots__ = ("id", "x", "y", "type", "links", "index")
def __init__(self, i, j, id_):
self.id = id_
self.x = i * 100
self.y = j * 100
self.type = NONE_
self.links = [] # (type, target)
self.index = 0
class NavMeshSim:
def __init__(self, solid_map):
self.solid = solid_map
self.W = len(solid_map)
self.H = len(solid_map[0])
self.count_links = {WALK: 0, FALL: 0, JUMP: 0}
def coll(self, x, y):
return x >= self.W or x < 0 or y >= self.H or y < 0 or self.solid[x][y] == 1
def add_link(self, x1, y1, x2, y2, t):
if x2 < 0 or x2 >= self.W or y2 < 0 or y2 >= self.H:
return
a, b = self.nav[x1][y1], self.nav[x2][y2]
a.links.append((t, b))
b.links.append((t, a))
self.count_links[t] += 2
def fill_in(self, spawn_cell):
solid = self.solid
W, H = self.W, self.H
stack = [spawn_cell]
while stack:
x, y = stack.pop()
if solid[x][y] >= 1:
continue
if solid[x][y] == 0:
solid[x][y] = 2
if x > 0:
stack.append((x - 1, y))
if x < W - 2:
stack.append((x + 1, y))
if y > 0:
stack.append((x, y - 1))
if y < H - 2:
stack.append((x, y + 1))
def init(self, spawn_px, fix_notch=False, fix_left_bound=False, fix_shaft1=False):
self.fill_in((int(spawn_px[0] / 100), int(spawn_px[1] / 100)))
s = self.solid
for i in range(self.W):
for j in range(self.H):
if s[i][j] == 0:
s[i][j] = 1
if s[i][j] == 2:
s[i][j] = 0
self.nav = [[NP(i, j, i * self.H + j) for j in range(self.H)]
for i in range(self.W)]
nav = self.nav
for y in range(self.H):
started = False
for x in range(self.W):
if not started:
if not self.coll(x, y) and self.coll(x, y + 1) and not self.coll(x, y - 1):
nav[x][y].type = LEFT_EDGE
started = True
if started:
if self.coll(x + 1, y + 1) and not self.coll(x + 1, y) \
and nav[x][y].type != LEFT_EDGE:
nav[x][y].type = PLATFORM
self.add_link(x, y, x - 1, y, WALK)
if (not self.coll(x + 1, y + 1)) or self.coll(x + 1, y):
if nav[x][y].type == LEFT_EDGE:
nav[x][y].type = SOLO
else:
nav[x][y].type = RIGHT_EDGE
self.add_link(x, y, x - 1, y, WALK)
started = False
for x in range(self.W):
for y in range(self.H):
if nav[x][y].type in (RIGHT_EDGE, SOLO):
if fix_shaft1:
# puits à 1 colonne : l'ennemi (200px) marche hors du
# bord, son corps déborde sur x+1, il tombe le long
# de la paroi x+2 (même solide) et atterrit sur le
# sol sous x+1
ok = (not self.coll(x + 1, y) and not self.coll(x + 1, y - 1))
cols = (x + 1,)
else:
ok = (x + 2 < self.W and not self.coll(x + 1, y) and not self.coll(x + 2, y)
and not self.coll(x + 1, y - 1) and not self.coll(x + 2, y - 1))
cols = (x + 1, x + 2)
if ok:
yt = y + 1
while yt < self.H - 1 and all(not self.coll(c, yt) for c in cols):
yt += 1
yt -= 1
if not fix_notch:
self.add_link(x, y, x + 1, yt, FALL)
landing = x + 1
else:
# miroir exact de la branche LEFT 2017 : atterrir
# sur la colonne qui a un sol sous yt+1
if self.coll(x + 1, yt + 1):
landing = x + 1
elif len(cols) > 1 and self.coll(x + 2, yt + 1):
landing = x + 2
else:
landing = x + 1
self.add_link(x, y, landing, yt, FALL)
if yt - (y + 1) < 3:
self.add_link(x, y, landing, yt, JUMP)
if nav[x][y].type in (LEFT_EDGE, SOLO):
cond = (x - 2 >= 0) if fix_left_bound else (x - 2 > 0)
if cond and not self.coll(x - 1, y) and not self.coll(x - 2, y) \
and not self.coll(x - 1, y - 1) and not self.coll(x - 2, y - 1):
yt = y + 1
while yt < self.H - 1 and not self.coll(x - 1, yt) and not self.coll(x - 2, yt):
yt += 1
yt -= 1
if self.coll(x - 2, yt + 1):
self.add_link(x, y, x - 2, yt, FALL)
else:
self.add_link(x, y, x - 1, yt, FALL)
if yt - (y + 1) < 3:
landing = (x - 2 if self.coll(x - 2, yt + 1) else x - 1)
self.add_link(x, y, landing, yt, JUMP)
for x in range(self.W):
for y in range(self.H):
if nav[x][y].type in (RIGHT_EDGE, SOLO) and self.coll(x + 1, y):
for i in range(1, 4):
if self.is_jump_landing(x + 1, y - i):
self.add_link(x, y, x + 1, y - i, JUMP)
break
if nav[x][y].type in (LEFT_EDGE, SOLO) and self.coll(x - 1, y):
for i in range(1, 4):
if self.is_jump_landing(x - 1, y - i):
self.add_link(x, y, x - 1, y - i, JUMP)
break
def is_jump_landing(self, x, y):
return not self.coll(x, y) and not self.coll(x, y - 1) and self.coll(x, y, )
def get_nav_point(self, x, y):
i = int(round(x / 100.0))
j = int(round(y / 100.0)) + 1
if i < 0 or i >= self.W or j < 0 or j >= self.H:
return None
return self.nav[i][j]
# ---- BFS (getPath) port exact
def get_path(self, start, end):
if start is None or end is None:
return []
for p in self._altered:
p.index = 0
self._altered = []
end.index = -1
self._altered.append(end)
self._max_index = 0
self._found = False
q = [start]
idx = [1]
while q:
self._do_index(q.pop(0), idx.pop(0), q, idx)
if self._closest.id != end.id:
return []
path = [None] * self._max_index
if self._max_index == 0:
return path
if self._max_index == 1:
path[0] = end
return path
path[self._max_index - 1] = end
for i in range(self._max_index - 2, -1, -1):
for (t, tgt) in path[i + 1].links:
if tgt.index == i + 1 \
and not (tgt.y > path[i + 1].y and t == FALL) \
and not (tgt.y < path[i + 1].y and t == JUMP):
path[i] = tgt
break
return path
def _do_index(self, p, index, q, idx):
if self._found or (p.index > 0 and index >= p.index):
return
if p.index == -1:
p.index = index
self._max_index = index
self._closest = p
self._found = True
self._altered.append(p)
q.clear()
idx.clear()
return
p.index = index
self._altered.append(p)
if index > self._max_index:
self._max_index = index
self._closest = p
for (t, tgt) in p.links:
if not (t == FALL and tgt.y < p.y) and not (t == JUMP and tgt.y > p.y):
if tgt.index <= 0 or index + 1 < tgt.index:
q.append(tgt)
idx.append(index + 1)
# ---- ensemble joignable (direction filtré), pour le diagnostic
def reachable(self, start):
seen = {start}
q = [start]
while q:
p = q.pop()
for (t, tgt) in p.links:
if t == FALL and tgt.y < p.y:
continue
if t == JUMP and tgt.y > p.y:
continue
if tgt not in seen:
seen.add(tgt)
q.append(tgt)
return seen
def is_jump_landing(self, x, y):
return not self.coll(x, y) and not self.coll(x, y - 1) and self.coll(x, y + 1)
NavMeshSim.__init__._orig = None
def _fix_init(cls):
orig = cls.init
def init(self, spawn_px, **kw):
self._altered = []
self._closest = None
self._max_index = 0
self._found = False
orig(self, spawn_px, **kw)
cls.init = init
_fix_init(NavMeshSim)
def standable(sim, i, j):
"""Cellule où une entité 2x2 (ennemi) tient debout : libre + tête libre + sol dessous."""
return not sim.coll(i, j) and not sim.coll(i, j - 1) and sim.coll(i, j + 1)
def ground_row(sim, col, from_row):
for r in range(max(from_row, 0), sim.H):
if sim.coll(col, r):
return r
return None
def exterminate_spawn(sim, player_cell, rnd):
"""Port de la logique de spawn Exterminate : renvoie (pos ennemi, étage sol) ou None."""
pi, pj = player_cell
px, py = pi * 100.0, pj * 100.0 - 100.0 # joueur debout sur le sol pj+1
player_floor_row = pj + 1
player_floor = Physics.raycast(sim, px, py - 5000) # sol de référence du joueur
if player_floor is None:
return None
side = 1.0 if rnd.next_int(2) == 0 else -1.0
fx = max(200.0, px + side * (1500 + rnd.next_int(900) * 1.0))
pos = (fx, py - 150 - rnd.next_int(100))
for attempt in range(6):
s = 1.0 if attempt % 2 == 0 else -1.0
spawn_x = px + s * (1500 + rnd.next_int(900))
if spawn_x < 200:
continue
col = int(spawn_x / 100)
start_row = int((py - 5000) / 100)
r = ground_row(sim, col, start_row)
if r is None:
continue
if abs(r * 100 - player_floor) <= 1500: # player_floor déjà en px
pos = (spawn_x, r * 100 - 100.0)
return pos, r
return None
class Physics:
@staticmethod
def raycast(sim, x, y_start):
col = int(x / 100)
if col < 0 or col >= sim.W:
return None
start_row = int(y_start / 100)
r = ground_row(sim, col, start_row)
return r * 100 if r is not None else None
def fmt_cell(c):
return "(%d,%d)" % (c[0], c[1])
def _resolve_links(sim, np):
"""Fix A (port du fix Java) : cellule sans liens -> voisin i±1 même ligne."""
if np is None or np.links:
return np
i, j = np.x // 100, np.y // 100
for d in (-1, 1):
if 0 <= i + d < sim.W and sim.nav[i + d][j].links:
return sim.nav[i + d][j]
return np
def analyze_seed(seed, segs, verbose=False, use_fallback=False, fixes=False):
solid, tmx_spawn_px, segs_used = generate_map(seed, segs)
# Fidélité ExterminateMission.load() : playerSpawn=(20,20) est posé AVANT
# loadProceduralMap -> NavMesh.init (fillIn) part de la cellule (0,0) ;
# le spawn réel (100, 25700) n'est posé qu'APRES NavMesh.init (l.65-67).
sim = NavMeshSim(solid)
sim.init((20.0, 20.0), fix_notch=fixes, fix_left_bound=fixes)
m, f, j_ = sim.count_links[WALK], sim.count_links[FALL], sim.count_links[JUMP]
# cellules debout
stand = [(i, j) for i in range(sim.W) for j in range(sim.H) if standable(sim, i, j)]
# spawn joueur reel (Exterminate : PROC_START.x*16*6.25+100, PROC_START.y*16*6.25+100)
spawn_px = (100.0, 25700.0)
rnd = JavaRandom(seed * 2654435761 % (1 << 31))
results = []
# échantillon de positions joueur : spawn + 40 cellules debout aléatoires
player_cells = [(int(spawn_px[0] / 100), int(spawn_px[1] / 100) + 1)]
player_cells += [stand[rnd.next_int(len(stand))] for _ in range(40)]
for pc in player_cells:
sp = exterminate_spawn(sim, pc, rnd)
if sp is None:
continue
pos, erow = sp
# mapping FIDELE au jeu : getNavPoint -> round(x/100), j=round(y/100)+1
# (ennemi stabilisé debout : pos.y = erow*100-200 -> j = erow-1)
ecol = int(round(pos[0] / 100.0))
ecell = (ecol, erow - 1)
en = sim.nav[ecell[0]][ecell[1]]
# position du joueur : pos.x quelconque autour de sa cellule (il marche)
pxj = pc[0] * 100 + rnd.next_int(200) - 100
pn = sim.get_nav_point(float(pxj), float(pc[1] * 100 - 100))
if en is None or pn is None:
results.append({"player": pc, "enemy": ecell, "status": "hors_grille"})
continue
if use_fallback:
en = _resolve_links(sim, en)
pn = _resolve_links(sim, pn)
path = sim.get_path(en, pn)
droppx = abs((ecell[1] - pc[1])) * 100
if len(path) > 0:
results.append({"player": pc, "enemy": ecell, "status": "ok",
"len": len(path), "drop": droppx})
else:
reach = sim.reachable(en)
ok_targets = [(c.x // 100, c.y // 100) for c in reach if standable(sim, c.x // 100, c.y // 100)]
break_row = None
if ok_targets:
break_row = max(c[1] for c in ok_targets) # plus bas atteint
results.append({"player": pc, "enemy": ecell, "status": "aucun_chemin",
"drop": droppx, "reach_size": len(reach),
"reach_standable": len(ok_targets),
"reach_bottom": break_row})
return {"seed": seed, "m": m, "f": f, "j": j_, "results": results}
def main():
n_seeds = int(sys.argv[1]) if len(sys.argv) > 1 else 30
mode = sys.argv[2] if len(sys.argv) > 2 else "base" # base | fb | fix
fixes = mode == "fix"
use_fb = mode in ("fb", "fix")
segs = load_segments()
print("segments : spawn=%d main=%d end=%d extract=%d lock=%d [%s]" %
(tuple(len(segs[c]) for c in ("spawn", "main", "end", "extract", "lock")) + (mode,)))
tot = {"ok": 0, "aucun_chemin": 0, "spawn_solide": 0, "hors_grille": 0}
drops_fail, drops_ok = [], []
reach_bottoms = []
link_stats = []
for k in range(n_seeds):
seed = 1_000_000 + k * 7919
r = analyze_seed(seed, segs, use_fallback=use_fb, fixes=fixes)
if "error" in r:
print("seed %d : ERREUR %s" % (seed, r["error"]))
continue
link_stats.append((r["m"], r["f"], r["j"]))
for res in r["results"]:
st = res["status"]
tot[st] = tot.get(st, 0) + 1
if st == "ok":
drops_ok.append(res["drop"])
elif st == "aucun_chemin":
drops_fail.append(res["drop"])
if res.get("reach_bottom") is not None:
reach_bottoms.append(res["reach_bottom"] - res["enemy"][1])
print("\n=== stats sur %d seeds ===" % n_seeds)
if link_stats:
avg = lambda ix: sum(s[ix] for s in link_stats) / len(link_stats)
print("liens moyens : marche=%.0f chute=%.0f saut=%.0f (comptés 2x)" %
(avg(0), avg(1), avg(2)))
print("couples (spawn ennemi, joueur) : %s" % tot)
if drops_ok:
print("chutes RÉUSSIES : n=%d, Δy moyen=%.0f px, max=%.0f" %
(len(drops_ok), sum(drops_ok) / len(drops_ok), max(drops_ok)))
if drops_fail:
print("chutes ÉCHOUÉES : n=%d, Δy moyen=%.0f px" %
(len(drops_fail), sum(drops_fail) / len(drops_fail)))
if reach_bottoms:
reach_bottoms.sort()
print("profondeur max atteignable depuis l'ennemi (Δy vers le bas, px) : "
"médiane=%d max=%d" % (reach_bottoms[len(reach_bottoms) // 2], max(reach_bottoms)))
if __name__ == "__main__":
main()

View File

@ -0,0 +1,73 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Décisif : pour chaque échec du couple spawner (ennemi/joueur réalistes),
le joueur est-il atteignable depuis la cellule nav du SPAWN JOUEUR ?
- NON -> zone isolée même depuis le spawn : refus LÉGITIME (blacklist)
- OUI -> le graphe a les routes mais le départ ennemi/chute rate : réparable
"""
import sys
sys.path.insert(0, "tools/sim")
from navmesh_connectivity import (load_segments, generate_map, NavMeshSim,
standable, exterminate_spawn, JavaRandom,
_resolve_links)
def main():
n_seeds = int(sys.argv[1]) if len(sys.argv) > 1 else 12
fixes = len(sys.argv) > 2 and sys.argv[2] == "fix"
segs = load_segments()
tot = {"ok": 0, "echec_isole": 0, "echec_reparable": 0}
ex_iso, ex_rep = [], []
for k in range(n_seeds):
seed = 1_000_000 + k * 7919
solid, _, _ = generate_map(seed, segs)
sim = NavMeshSim(solid)
sim.init((20.0, 20.0), fix_notch=fixes, fix_left_bound=fixes)
stand = [(i, j) for i in range(sim.W) for j in range(sim.H) if standable(sim, i, j)]
rnd = JavaRandom(seed * 2654435761 % (1 << 31))
player_cells = [(1, 258)] + [stand[rnd.next_int(len(stand))] for _ in range(40)]
# référence : le joueur APRÈS sa chute de spawn — il tombe de (1,258)
# jusqu'au prochain sol de la colonne 1
r = 259
while r < sim.H - 1 and not sim.coll(1, r):
r += 1
spawn_np = _resolve_links(sim, sim.nav[1][r - 1])
spawn_reach = sim.reachable(spawn_np)
spawn_reach_cells = {(p.x // 100, p.y // 100) for p in spawn_reach}
for pc in player_cells:
sp = exterminate_spawn(sim, pc, rnd)
if sp is None:
continue
pos, erow = sp
ecol = int(round(pos[0] / 100.0))
en = _resolve_links(sim, sim.nav[ecol][erow - 1])
pxj = pc[0] * 100 + rnd.next_int(200) - 100
pn = _resolve_links(sim, sim.get_nav_point(float(pxj), float(pc[1] * 100 - 100)))
if en is None or pn is None:
continue
if len(sim.get_path(en, pn)) > 0:
tot["ok"] += 1
continue
if (pn.x // 100, pn.y // 100) in spawn_reach_cells and en in spawn_reach:
tot["echec_reparable"] += 1
if len(ex_rep) < 5:
ex_rep.append((seed, (ecol, erow - 1), (pn.x // 100, pn.y // 100)))
else:
tot["echec_isole"] += 1
if len(ex_iso) < 5:
ex_iso.append((seed, (ecol, erow - 1), (pn.x // 100, pn.y // 100)))
s = sum(tot.values())
tag = " [FIXES]" if fixes else ""
print("couples spawner testés : %d%s" % (s, tag))
print(" ok : %d (%.1f%%)" % (tot["ok"], 100.0 * tot["ok"] / s))
print(" échec ISOLÉ (même le spawn ne joint pas) : %d (%.1f%%)" %
(tot["echec_isole"], 100.0 * tot["echec_isole"] / s))
print(" échec RÉPARABLE (le spawn joint, pas l'ennemi) : %d (%.1f%%)" %
(tot["echec_reparable"], 100.0 * tot["echec_reparable"] / s))
print("exemples isolés :", ex_iso)
print("exemples réparables :", ex_rep)
if __name__ == "__main__":
main()

67
tools/sim/navmesh_diag.py Normal file
View File

@ -0,0 +1,67 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Diagnostic détaillé d'un seed : pourquoi le chemin ennemi->joueur casse."""
import sys
sys.path.insert(0, "tools/sim")
from navmesh_connectivity import (load_segments, generate_map, NavMeshSim,
standable, exterminate_spawn, JavaRandom,
ground_row, LEFT_EDGE, RIGHT_EDGE, SOLO,
PLATFORM, WALK, FALL, JUMP)
def describe(sim, i, j):
n = sim.nav[i][j]
tname = {0: "NONE", 1: "PLATFORM", 2: "LEFT_EDGE", 3: "RIGHT_EDGE", 4: "SOLO"}[n.type]
types = [ {0:"WALK",1:"FALL",2:"JUMP"}[t] + "->(%d,%d)" % (tgt.x//100, tgt.y//100)
for (t, tgt) in n.links ]
return "%s liens=%d %s" % (tname, len(n.links), " ".join(types[:8]))
def main(seed):
segs = load_segments()
solid, _, _ = generate_map(seed, segs)
sim = NavMeshSim(solid)
sim.init((20.0, 20.0))
print("liens :", sim.count_links)
rnd = JavaRandom(42)
stand = [(i, j) for i in range(sim.W) for j in range(sim.H) if standable(sim, i, j)]
pc = (1, 258) # spawn joueur réel
# un joueur au hasard 2 étages plus bas
pc = [c for c in stand if c[1] >= pc[1] + 3][0]
sp = exterminate_spawn(sim, pc, rnd)
pos, erow = sp
ecol = int(pos[0] / 100)
ecell = (ecol, erow - 1)
print("joueur :", pc, "ennemi :", ecell, "Δrow =", pc[1] - ecell[1])
en = sim.nav[ecell[0]][ecell[1]] # ecell EST déjà la cellule nav
print("cellule ennemi :", describe(sim, *ecell))
pn = sim.get_nav_point(float(pc[0]*100), float(pc[1]*100 - 100))
pi2, pj2 = pc[0], pc[1]
print("cellule joueur :", describe(sim, pi2, pj2))
reach = sim.reachable(en)
print("joignables depuis ennemi :", len(reach))
rows = sorted(set(p.y // 100 for p in reach))
print("lignes joignables :", rows[:40])
bottom = max(p.y // 100 for p in reach if standable(sim, p.x//100, p.y//100) or True)
stand_in_reach = [(p.x//100, p.y//100) for p in reach if standable(sim, p.x//100, p.y//100)]
print("debout joignables :", len(stand_in_reach), "plus bas :", max(stand_in_reach, key=lambda c: c[1]) if stand_in_reach else None)
# Géométrie autour de l'ennemi : les bords du sol de l'ennemi
ei, ej = ecell
print("\n-- sol de l'ennemi, ligne %d, colonnes %d±6 --" % (ej, ei))
for x in range(max(0, ei-6), min(sim.W, ei+7)):
if standable(sim, x, ej):
print(" (%d,%d) %s" % (x, ej, describe(sim, x, ej)))
# colonnes : où est le sol sous l'ennemi ?
print("\n-- profil vertical colonne par colonne (%d±6), lignes %d..%d --" % (ei, ej-1, ej+12))
for x in range(max(0, ei-6), min(sim.W, ei+7)):
prof = "".join("#" if sim.coll(x, r) else "." for r in range(ej-1, ej+12))
print(" col %3d : %s" % (x, prof))
if __name__ == "__main__":
main(int(sys.argv[1]) if len(sys.argv) > 1 else 1000000)

View File

@ -0,0 +1,93 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Diagnostic d'un couple ENNEMI plus HAUT que le joueur (scénario du log v0.12.x)."""
import sys
sys.path.insert(0, "tools/sim")
from navmesh_connectivity import (load_segments, generate_map, NavMeshSim,
standable, exterminate_spawn, JavaRandom)
def describe(sim, i, j):
n = sim.nav[i][j]
tname = {0: "NONE", 1: "PLATFORM", 2: "LEFT_EDGE", 3: "RIGHT_EDGE", 4: "SOLO"}[n.type]
return "%s liens=%d" % (tname, len(n.links))
def run(seed, min_drop=700):
segs = load_segments()
solid, _, _ = generate_map(seed, segs)
sim = NavMeshSim(solid)
sim.init((20.0, 20.0))
stand = [(i, j) for i in range(sim.W) for j in range(sim.H) if standable(sim, i, j)]
rnd = JavaRandom(42)
player_cells = [(1, 258)] + [stand[rnd.next_int(len(stand))] for _ in range(60)]
for pc in player_cells:
sp = exterminate_spawn(sim, pc, rnd)
if sp is None:
continue
pos, erow = sp
ecol = int(pos[0] / 100)
ecell = (ecol, erow - 1)
if not standable(sim, *ecell):
continue
en = sim.nav[ecell[0]][ecell[1]]
pn = sim.get_nav_point(float(pc[0] * 100), float(pc[1] * 100 - 100))
drop = (ecell[1] - pc[1]) * 100
# scénario du log : ennemi AU-DESSUS du joueur (lignes : y vers le bas)
# -> drop NÉGATIF ; on garde drop <= -min_drop
if drop > -min_drop:
continue
path = sim.get_path(en, pn)
if len(path) > 0:
continue
print("== seed %d : ennemi %s joueur %s (Δy=%d px) AUCUN CHEMIN ==" % (seed, ecell, pc, drop))
reach = sim.reachable(en)
stand_reach = [(p.x // 100, p.y // 100) for p in reach if standable(sim, p.x // 100, p.y // 100)]
print("joignables=%d debout=%d" % (len(reach), len(stand_reach)))
if stand_reach:
b = max(stand_reach, key=lambda c: c[1])
print("plus bas debout joignable :", b)
# étendue du sol ennemi + ses bords + options de chute
ei, ej = ecell
# trouver l'étendue du plancher de l'ennemi (ligne ej+1 solide)
cols = [x for x in range(sim.W) if standable(sim, x, ej)]
runs = []
cur = [cols[0], cols[0]]
for c in cols[1:]:
if c == cur[1] + 1:
cur[1] = c
else:
runs.append(cur)
cur = [c, c]
runs.append(cur)
print("planchers debout ligne %d (runs) : %s" % (ej, runs))
for (a, b) in runs:
if a <= ei <= b:
print(" run de l'ennemi : [%d..%d]" % (a, b))
for x in range(max(0, a - 3), min(sim.W, b + 4)):
n = sim.nav[x][ej]
extra = ""
if n.type in (2, 3, 4): # LEFT_EDGE/RIGHT_EDGE/SOLO
extra = " " + " ".join(
{0: "WALK", 1: "FALL", 2: "JUMP"}[t] + "->(%d,%d)" % (g.x // 100, g.y // 100)
for (t, g) in n.links)
print(" (%d,%d) %s%s" % (x, ej, describe(sim, x, ej), extra))
# profil vertical aux deux bords
for edge in (a, b):
print(" profil col %d (lignes %d..%d) : %s" % (
edge, ej, min(sim.H, ej + 14),
"".join("#" if sim.coll(edge, r) else "." for r in range(ej, min(sim.H, ej + 14)))))
print(" profil col %d (lignes %d..%d) : %s" % (
edge, ej, min(sim.H, ej + 14),
"".join("#" if sim.coll(edge + (1 if edge == a else -1), r) else "."
for r in range(ej, min(sim.H, ej + 14)))))
# sol du joueur
pi, pj = pc
cols_p = [x for x in range(sim.W) if standable(sim, x, pj)]
print("sol du joueur ligne %d : %d cellules debout, x=%d..%d" % (pj, len(cols_p), min(cols_p), max(cols_p)))
return
if __name__ == "__main__":
run(int(sys.argv[1]) if len(sys.argv) > 1 else 1000000,
int(sys.argv[2]) if len(sys.argv) > 2 else 700)

View File

@ -0,0 +1,80 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Reproduction DIRECTE du log utilisateur v0.12.x (Pixel 8 Pro) :
ennemi (1059.455, 25400.0) -> getNavPoint (11,255)
joueur (56..499, 26100/26900)
Le tout dans le segment de spawn (posé à l'offset (0,256) -> lignes 256..271),
commun aux 4 segments de spawn possibles -> on teste les 4.
"""
import sys
sys.path.insert(0, "tools/sim")
from navmesh_connectivity import load_segments, TmxMap, NavMeshSim, standable
import os
W, H = 256, 512
POS_Y = 256
def build_from_segment(tmx):
solid = [[0] * H for _ in range(W)]
ox, oy = 0, POS_Y
for name, gids in tmx.layers:
if name != "main":
continue
for i, g in enumerate(gids):
if g <= 0:
continue
col, row = i % tmx.w, i // tmx.w
solid[col + ox][row + oy] = 1
# portes du segment (solidité autour des objets "door")
for gname, objs in tmx.objgroups:
if gname in ("connectors", "enemies", "spawns"):
continue
for o in objs:
if "door" in o["type"]:
px = (o["x"] + ox * 16) * 6.25
py = (o["y"] + oy * 16) * 6.25
for (dx, dy) in ((0, 0), (1, 0), (0, 4), (1, 4)):
try:
solid[int(px / 100) + dx][int(py / 100) + dy] = 1
except IndexError:
pass
return solid
ENEMY = (1059.455, 25400.0)
JOUEURS = [(56.25, 26100.0), (499.35, 26100.0), (464.0, 26900.0), (120.0, 26900.0), (432.0, 26900.0)]
def resolve(sim, np, x, y):
if np is not None and not np.links:
i = int(round(x / 100.0)); j = int(round(y / 100.0)) + 1
for d in (-1, 1):
if 0 <= i + d < sim.W and sim.nav[i + d][j].links:
return sim.nav[i + d][j], " (fallback->(%d,%d))" % (i + d, j)
return np, ""
def main():
segs = load_segments()
for tmx in segs["spawn"]:
solid = build_from_segment(tmx)
print("=== segment spawn : %s ===" % os.path.basename(tmx.path))
for fixes in (False, True):
sim = NavMeshSim(solid)
sim.init((20.0, 20.0), fix_notch=fixes, fix_left_bound=fixes)
en, einfo = resolve(sim, sim.get_nav_point(*ENEMY), *ENEMY)
if en is None:
print(" ennemi hors grille !"); continue
out = []
for (px, py) in JOUEURS:
pn, pinfo = resolve(sim, sim.get_nav_point(px, py), px, py)
if pn is None:
out.append("(%d,%d):cible_hors_grille" % (int(px), int(py)))
continue
path = sim.get_path(en, pn)
tag = "OK(len=%d)" % len(path) if len(path) else "aucun_chemin"
out.append("(%d,%d)->%s%s" % (int(px), int(py), tag,
(" [cible fallback->(%d,%d)]" % (pn.x // 100, pn.y // 100)) if pinfo else ""))
print(" fixes=%-5s start=(%d,%d)%s : %s" % (fixes, en.x // 100, en.y // 100,
einfo, " ".join(out)))
if __name__ == "__main__":
main()

111
tools/sim/navmesh_oracle.py Normal file
View File

@ -0,0 +1,111 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Oracle physique vs graphe NavMesh : distinguer l'isolation RÉELLE (l'ennemi
ne peut physiquement pas y aller) des liens manquants (le graphe rate une
route physiquement praticable : marche / chute par bord / saut <=3 lignes).
"""
import sys
sys.path.insert(0, "tools/sim")
from collections import deque
from navmesh_connectivity import load_segments, generate_map, NavMeshSim, standable
def physical_reachable(sim, start, max_jump_up=3, max_jump_dx=2):
"""BFS généreux : marche, chute (bord -> plancher en dessous, dérive ±1 col),
saut (montée <= max_jump_up lignes, décalage <= max_jump_dx colonnes)."""
W, H = sim.W, sim.H
seen = {start}
q = deque([start])
while q:
(i, j) = q.popleft()
# marche : voisins debout même ligne
for d in (-1, 1):
n = (i + d, j)
if 0 <= n[0] < W and n in seen or not (0 <= n[0] < W):
continue
if standable(sim, *n):
seen.add(n)
q.append(n)
# chute : marcher hors du bord -> plancher le plus bas sous les colonnes i, i±1
for d in (0, 1, -1):
c = i + d
if not (0 <= c < W):
continue
# il faut du vide devant au niveau de la tête et du corps (marcher hors bord)
if not sim.coll(c, j):
# descend la colonne c jusqu'au prochain sol
r = j + 1
while r < H - 1 and not sim.coll(c, r):
r += 1
# atterrit sur (c, r-1) si debout
cand = (c, r - 1)
if standable(sim, *cand) and cand not in seen:
seen.add(cand)
q.append(cand)
# saut : montée <= max_jump_up, décalage <= max_jump_dx
for dc in range(-max_jump_dx, max_jump_dx + 1):
for up in range(1, max_jump_up + 1):
n = (i + dc, j - up)
if not (0 <= n[0] < W and n[1] >= 1):
continue
if n in seen:
continue
if standable(sim, *n):
# trajectoire : pas de mur dans la colonne de départ au niveau du corps/tête
if sim.coll(i, j - 1) or sim.coll(i, j - up):
continue
seen.add(n)
q.append(n)
return seen
def main():
n_seeds = int(sys.argv[1]) if len(sys.argv) > 1 else 6
segs = load_segments()
tot = {"phys_ok": 0, "nav_ok": 0, "nav_rate_mais_phys_ok": 0, "isolation_reelle": 0}
exemples = []
for k in range(n_seeds):
seed = 1_000_000 + k * 7919
solid, _, _ = generate_map(seed, segs)
sim = NavMeshSim(solid)
sim.init((20.0, 20.0), fix_notch=True, fix_left_bound=True)
stand = [(i, j) for i in range(sim.W) for j in range(sim.H) if standable(sim, i, j)]
# échantillon de couples quasi-verticaux (ennemi au-dessus, 1..15 lignes)
import random
rnd = random.Random(seed)
pairs = []
for _ in range(400):
(ei, ej) = stand[rnd.randrange(len(stand))]
(pi, pj) = stand[rnd.randrange(len(stand))]
if 1 <= pj - ej <= 15 and abs(pi - ei) <= 10:
pairs.append(((ei, ej), (pi, pj)))
for (e, p) in pairs:
en, pn = sim.nav[e[0]][e[1]], sim.nav[p[0]][p[1]]
nav_ok = len(sim.get_path(en, pn)) > 0
phys = physical_reachable(sim, e)
phys_ok = p in phys
if nav_ok:
tot["nav_ok"] += 1
tot["phys_ok"] += 1
elif phys_ok:
tot["nav_rate_mais_phys_ok"] += 1
if len(exemples) < 6:
exemples.append((seed, e, p))
else:
tot["isolation_reelle"] += 1
tot["phys_ok"] += 0
s = sum(tot.values())
print("couples testés : %d" % s)
print(" nav OK : %d (%.1f%%)" % (tot["nav_ok"], 100.0 * tot["nav_ok"] / s))
print(" nav ÉCHOUÉ mais PHYSIQUEMENT possible : %d (%.1f%%) <- liens manquants" %
(tot["nav_rate_mais_phys_ok"], 100.0 * tot["nav_rate_mais_phys_ok"] / s))
print(" isolation réelle (physiquement absent): %d (%.1f%%)" %
(tot["isolation_reelle"], 100.0 * tot["isolation_reelle"] / s))
print("exemples de liens manquants :")
for (seed, e, p) in exemples:
print(" seed=%d ennemi=%s joueur=%s" % (seed, e, p))
if __name__ == "__main__":
main()

View File

@ -0,0 +1,78 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Test sur cartes COMPLETES dont le segment de spawn est spwn_16x16_a
(signature : étagère pleine largeur à la ligne 255, plancher 256 x0..15).
Positions EXACTES du log v0.12.x :
ennemi (1059.455, 25400) ; joueur (56..499, 26100 / 26900)
"""
import sys
sys.path.insert(0, "tools/sim")
from navmesh_connectivity import (load_segments, generate_map, NavMeshSim,
standable, JavaRandom)
ENEMY = (1059.455, 25400.0)
JOUEURS = [(56.25, 26100.0), (499.35, 26100.0), (464.0, 26900.0),
(120.0, 26900.0), (432.0, 26900.0)]
def resolve(sim, np, x, y):
if np is not None and not np.links:
i = int(round(x / 100.0)); j = int(round(y / 100.0)) + 1
for d in (-1, 1):
if 0 <= i + d < sim.W and sim.nav[i + d][j].links:
return sim.nav[i + d][j], " fb->(%d,%d)" % (i + d, j)
return np, ""
def is_spawn_a(sim):
"""Signature de spwn_16x16_a posé à (0,256) : plancher 256 pleine largeur."""
return all(sim.coll(x, 256) for x in range(0, 16)) and \
all(not sim.coll(x, 255) for x in range(0, 16))
def main():
segs = load_segments()
n_a = 0
agg = {}
tested = 0
for k in range(200):
seed = 1_000_000 + k * 7919
solid, _, _ = generate_map(seed, segs)
sim0 = NavMeshSim([row[:] for row in solid])
# signature sur la solidité BRUTE (avant fill) : col 0..15 ligne 256 solide
if not all(solid[x][256] == 1 for x in range(16)):
continue
n_a += 1
if n_a > 25:
break
for fixes in (False, True):
sim = NavMeshSim([row[:] for row in solid])
sim.init((20.0, 20.0), fix_notch=fixes, fix_left_bound=fixes)
en, einfo = resolve(sim, sim.get_nav_point(*ENEMY), *ENEMY)
key = fixes
agg.setdefault(key, {"ok": 0, "fail": 0, "detail": []})
for (px, py) in JOUEURS:
pn, pinfo = resolve(sim, sim.get_nav_point(px, py), px, py)
if pn is None:
agg[key]["fail"] += 1
continue
path = sim.get_path(en, pn)
tested += 1
if len(path):
agg[key]["ok"] += 1
else:
agg[key]["fail"] += 1
if len(agg[key]["detail"]) < 3 and not fixes:
agg[key]["detail"].append("seed=%d joueur=(%d,%d)" % (seed, px, py))
print("maps avec spawn 'a' testées :", n_a)
for fixes in (False, True):
a = agg.get(fixes, {"ok": 0, "fail": 0})
s = a["ok"] + a["fail"]
print("fixes=%-5s : %d/%d positions joueur atteignables (%.0f%%) %s" %
(fixes, a["ok"], s, 100.0 * a["ok"] / max(s, 1),
a.get("detail", [])))
if __name__ == "__main__":
main()

52
tools/sim/navmesh_zoom.py Normal file
View File

@ -0,0 +1,52 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Zoom géométrique : zone entre l'atterrissage de chute et le joueur."""
import sys
sys.path.insert(0, "tools/sim")
from navmesh_connectivity import (load_segments, generate_map, NavMeshSim,
standable, exterminate_spawn, JavaRandom)
def main(seed, ei, ej, pi, pj):
segs = load_segments()
solid, _, _ = generate_map(seed, segs)
sim = NavMeshSim(solid)
sim.init((20.0, 20.0))
x0, x1 = min(ei, pi) - 2, max(ei, pi) + 2
y0, y1 = min(ej, pj) - 1, max(ej, pj) + 8
print("grille %d..%d x %d..%d ('#'=solide, o=debout, >=bord-droit, <=bord-gauche, S=solo)" % (x0, x1, y0, y1))
header = " " + "".join("%d" % (x % 10) for x in range(x0, x1 + 1))
print(header)
for y in range(y0, y1 + 1):
line = "%4d " % y
for x in range(x0, x1 + 1):
if sim.coll(x, y):
line += "#"
else:
n = sim.nav[x][y]
c = "."
if standable(sim, x, y):
c = "o"
if n.type == 3:
c = ">"
elif n.type == 2:
c = "<"
elif n.type == 4:
c = "S"
line += c
print(line)
# liens dans la zone
print("\nliens des cellules debout de la zone :")
for y in range(y0, y1 + 1):
for x in range(x0, x1 + 1):
if not sim.coll(x, y):
n = sim.nav[x][y]
if n.links:
ls = " ".join({0: "W", 1: "F", 2: "J"}[t] + "(%d,%d)" % (g.x // 100, g.y // 100)
for (t, g) in n.links)
print(" (%d,%d): %s" % (x, y, ls))
if __name__ == "__main__":
seed = int(sys.argv[1])
main(seed, *[int(v) for v in sys.argv[2:6]])