From cf558e3e615594cc0f6c160851fb7e8c35a37d20 Mon Sep 17 00:00:00 2001 From: Linkatplug Date: Sat, 5 Dec 2026 06:56:29 +0100 Subject: [PATCH] =?UTF-8?q?Sobri=C3=A9t=C3=A9=20:=20le=20jeu=20dort=20au?= =?UTF-8?q?=20lieu=20de=20tourner,=20et=20ne=20redessine=20que=20ce=20qui?= =?UTF-8?q?=20change?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Le jeu d'origine attend en boucle active : « while (tics < tics_par_image) ; » dans la boucle principale (97 % des passages à l'écran fixe), et dans l'intro « appeler le service du son tant que le compteur d'horloge n'a pas avancé ». - tools/recomp.py repère les boucles d'attente pures (quelques lectures de la mémoire et un saut, sans écriture, appel ni registre d'adresse modifié : 7 dans TUCKER.EXE) et lit runtime/attentes_.txt pour celles qui appellent une fonction (14 dans INTRO.EXE). Il émet WAIT_LOOP() au lieu de POLL() sur leur saut arrière. - rt_wait_loop (machine.c) dort jusqu'au prochain évènement (horloge, minuteur du jeu, image), seul moyen de sortir de ces boucles : même comportement, sans brûler un cœur. L'attente générique de rt_poll dort aussi jusqu'au prochain évènement au lieu de tourner pendant les 2 dernières ms avant chaque image. - host_sdl.c : aucun rendu ni présentation quand l'écran (pixels et palette) n'a pas changé, ni quand la fenêtre est réduite ou cachée ; redessin forcé sur évènement de fenêtre, après le menu et après un changement de réglages. Mesures (i5-14600KF, RTX 5070, fenêtré, chambre de Bud, CPU du processus sur 10 s) : filtre net + pack HD : 19,8 % -> 2,7 % d'un cœur, GPU 1,0 % -> 0,3 % filtre net sans HD : 18,1 % -> 1,2 % filtre xBR + HD : 22,2 % -> 1,9 %, GPU 4,6 % -> 1,5 % intro : 55 % -> 1,1 % fenêtre réduite : 1,1 % RAM inchangée : 166 à 174 Mo (privée 215 à 239 Mo). Co-Authored-By: Claude Opus 5.5 --- docs/ROADMAP.en.md | 9 ++++-- docs/ROADMAP.md | 9 ++++-- runtime/addr_fr.h | 6 ++++ runtime/attentes_intro.txt | 21 +++++++++++++ runtime/cpu.h | 3 ++ runtime/host_headless.c | 2 +- runtime/host_sdl.c | 15 ++++++++- runtime/machine.c | 29 ++++++++++++++++-- runtime/rt.h | 2 +- tools/recomp.py | 63 ++++++++++++++++++++++++++++++++++++-- 10 files changed, 145 insertions(+), 14 deletions(-) create mode 100644 runtime/attentes_intro.txt diff --git a/docs/ROADMAP.en.md b/docs/ROADMAP.en.md index b1fdfe3..6cf8713 100644 --- a/docs/ROADMAP.en.md +++ b/docs/ROADMAP.en.md @@ -111,13 +111,16 @@ It is a game from 1996: it must not bring any machine to its knees, whether Wind | Launcher, now | 0% idle, a few % while animating | 137 MB | 0% idle | | Game (sharp or CRT filter) | ~20% | ~165 MB | 1% | | Game (xBR filter) | ~20% | ~165 MB | 4.6% | +| Game now, still screen (sharp, CRT; HD pack) | 1 to 3% | 166 to 170 MB | 0.3% | +| Game now (xBR filter, HD pack) | ~2% | 170 MB | 1.5% | +| Intro now | ~1% (55% before) | 168 MB | — | - [x] Launcher: the banner slideshow freezes when the window is in the background, while the game runs, and after one minute without input (no more redraws) -- [ ] Game: wait by sleeping instead of spinning (vsync, next tick, the original game's wait +- [x] Game: wait by sleeping instead of spinning (vsync, next tick, the original game's wait loops), target < 5% of one core on a still screen -- [ ] Game: no rendering when nothing changes (still screen, minimized or hidden window) -- [ ] RAM: target < 256 MB for the game, even with an HD pack (load HD backgrounds on demand, free +- [x] Game: no rendering when nothing changes (still screen, minimized or hidden window) +- [x] RAM: target < 256 MB for the game, even with an HD pack (load HD backgrounds on demand, free those of rooms left behind) - [ ] Linux: build with a Makefile or CMake instead of `build.bat` (SDL2 and OpenGL 3.3 are already portable; only `menu.c` and `mods.c` contain Windows-specific code) diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 1c0c8f1..8948aff 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -116,13 +116,16 @@ C'est un jeu de 1996 : il ne doit mettre à genoux aucune machine, ni Windows, n | Launcher, maintenant | 0 % au repos, quelques % en animation | 137 Mo | 0 % au repos | | Jeu (filtre net ou CRT) | ~20 % | ~165 Mo | 1 % | | Jeu (filtre xBR) | ~20 % | ~165 Mo | 4,6 % | +| Jeu maintenant, écran fixe (net, CRT ; pack HD) | 1 à 3 % | 166 à 170 Mo | 0,3 % | +| Jeu maintenant (filtre xBR, pack HD) | ~2 % | 170 Mo | 1,5 % | +| Intro maintenant | ~1 % (55 % avant) | 168 Mo | — | - [x] Launcher : le diaporama du bandeau se fige quand la fenêtre est en arrière-plan, pendant la partie et après une minute sans interaction (plus aucun redessin) -- [ ] Jeu : attendre en dormant au lieu de boucler (attente de la vsync, du prochain tic, des +- [x] Jeu : attendre en dormant au lieu de boucler (attente de la vsync, du prochain tic, des boucles d'attente du jeu d'origine), objectif < 5 % d'un cœur à l'arrêt sur un écran -- [ ] Jeu : pas de rendu quand rien ne change (écran fixe, fenêtre réduite ou masquée) -- [ ] RAM : objectif < 256 Mo pour le jeu, même avec un pack HD (charger les décors HD à la demande, +- [x] Jeu : pas de rendu quand rien ne change (écran fixe, fenêtre réduite ou masquée) +- [x] RAM : objectif < 256 Mo pour le jeu, même avec un pack HD (charger les décors HD à la demande, libérer ceux des lieux quittés) - [ ] Linux : construction par Makefile ou CMake à la place de `build.bat` (SDL2 et OpenGL 3.3 sont déjà portables ; seuls `menu.c` et `mods.c` contiennent du code propre à Windows) diff --git a/runtime/addr_fr.h b/runtime/addr_fr.h index 25fd19a..31eedca 100644 --- a/runtime/addr_fr.h +++ b/runtime/addr_fr.h @@ -61,6 +61,9 @@ #define ADR_TAMPON_PLANCHE 0x46858u /* pointeur : tampon 320 de large où le jeu décode les planches PCX */ #define ADR_TAMPON_PIECE 0x4685cu /* pointeur : tampon de la pièce, 640 de large (pour mémoire) */ #define ADR_DEFILEMENT 0x46854u /* défilement horizontal de la pièce (pour mémoire) */ +/* cadence : la boucle principale attend « while (tics < tics_par_image) ; » (boucle d'attente, WAIT_LOOP) */ +#define ADR_TICS 0x46634u /* dword : +1 à chaque appel de ADR_MINUTEUR_RAPPEL (pour mémoire) */ +#define ADR_TICS_PAR_IMAGE 0x4228cu /* dword : tics par image du jeu (pour mémoire) */ /* souris */ #define ADR_SOURIS_X 0x46880u /* position lue par int 33h fonction 3, en pixels 320×200 (pour mémoire) */ #define ADR_SOURIS_Y 0x46882u @@ -90,3 +93,6 @@ #define INTRO_ADR_CANAL_MUSIQUE 0x35f80u /* poignée du canal de musique */ #define INTRO_ADR_CANAL_NARRATION 0x35f70u /* poignée du flux audio\*.raw (narration) */ #define INTRO_ADR_CANAUX_FX 0x35e14u /* poignées des bruitages (dword par canal, pour mémoire) */ +/* cadence : attentes listées dans attentes_intro.txt (pour mémoire) */ +#define INTRO_ADR_TICS_HORLOGE 0x327b5u /* word : +1 par le gestionnaire d'IRQ 0 de l'intro */ +#define INTRO_FN_SERVICE_SON I_00010483 /* entretien du son, appelé à chaque tour des attentes */ diff --git a/runtime/attentes_intro.txt b/runtime/attentes_intro.txt new file mode 100644 index 0000000..448dc44 --- /dev/null +++ b/runtime/attentes_intro.txt @@ -0,0 +1,21 @@ +# Boucles d'attente de INTRO.EXE (version française) que tools/recomp.py ne peut pas reconnaître seul, +# parce qu'elles appellent une fonction à chaque tour. Adresse = début de la boucle (cible du saut arrière). +# À chaque tour, le runtime dort jusqu'au prochain évènement (horloge, image) au lieu de tourner (WAIT_LOOP). +# Les boucles qui ne font que relire la mémoire sont trouvées automatiquement (voir is_wait_loop). +# +# Toutes de la forme « L: call INTRO_FN_SERVICE_SON ; cmp word [INTRO_ADR_TICS_HORLOGE], n ; jb L » : +# attendre n tics d'horloge (IRQ 0) en entretenant le son. Noms : runtime/addr_fr.h. +1146b # INTRO_ATTENTE_1 n = 2 (sort aussi si une touche est pressée) +11678 # INTRO_ATTENTE_2 n = 2 +11815 # INTRO_ATTENTE_3 n = 2 +11ae1 # INTRO_ATTENTE_4 n = 2 +11c36 # INTRO_ATTENTE_5 n = 2 +11d8b # INTRO_ATTENTE_6 n = 2 +11f5f # INTRO_ATTENTE_7 n = 2 +12096 # INTRO_ATTENTE_8 n = 2 +121cd # INTRO_ATTENTE_9 n = 2 +12304 # INTRO_ATTENTE_10 n = 2 +12567 # INTRO_ATTENTE_11 n = 1 +127b6 # INTRO_ATTENTE_12 n = 1 +128fb # INTRO_ATTENTE_13 n = 2 +12a3b # INTRO_ATTENTE_14 n = 2 diff --git a/runtime/cpu.h b/runtime/cpu.h index 356c386..e907010 100644 --- a/runtime/cpu.h +++ b/runtime/cpu.h @@ -149,6 +149,9 @@ void TRAP(uint32_t addr); extern uint32_t poll_counter; void rt_poll(void); +/* boucle d'attente pure du jeu (repérée par tools/recomp.py) : dort jusqu'au prochain évènement */ +void rt_wait_loop(void); +#define WAIT_LOOP() rt_wait_loop() #define POLL_EVERY 256u #define POLL() do { if (++poll_counter >= POLL_EVERY) rt_poll(); } while (0) diff --git a/runtime/host_headless.c b/runtime/host_headless.c index cf150df..3c16f2c 100644 --- a/runtime/host_headless.c +++ b/runtime/host_headless.c @@ -100,7 +100,7 @@ void host_frame(void) { } void host_pump(void) {} -void host_idle(void) {} +void host_sleep_us(uint64_t us) { vtime += us; } /* temps virtuel : l'attente est instantanée */ void host_audio_lock(void) {} void host_audio_unlock(void) {} int host_key_pop(uint8_t *sc) { (void)sc; return 0; } diff --git a/runtime/host_sdl.c b/runtime/host_sdl.c index 602bb76..f573bf1 100644 --- a/runtime/host_sdl.c +++ b/runtime/host_sdl.c @@ -30,6 +30,7 @@ static int game_h = 240; /* format affiché : 240 (4:3) ou 20 static int swallow_esc_up; /* Échap a fermé le menu : son relâchement ne va pas au jeu */ static char cfg_path[600]; static uint64_t press_until[3]; /* un appui reste visible au moins 80 ms : le jeu lit l'état des boutons à chaque image */ +static int redraw = 1; /* l'image doit être redessinée même si le jeu n'a rien changé */ /* ------------------------------------------------------------------ clavier : SDL → scancodes PC (jeu 1) */ static uint8_t keyq[64]; @@ -109,6 +110,7 @@ static void apply_display(void) { } if (settings.vsync != done_vsync) SDL_GL_SetSwapInterval(settings.vsync ? 1 : 0); hd_set_enabled(settings.hd_pack); + redraw = 1; done_scale = settings.window_scale; done_fmt = settings.aspect_43; done_full = settings.fullscreen; done_vsync = settings.vsync; } @@ -296,14 +298,23 @@ uint64_t host_time_us(void) { } /* ------------------------------------------------------------------ image */ +/* Rien n'est dessiné ni présenté quand la fenêtre est réduite ou cachée, ni quand l'écran du jeu (pixels et + * palette) n'a pas changé depuis la dernière image présentée : un écran fixe ne coûte presque rien. */ void host_frame(void) { static uint32_t px[320 * 200]; static uint8_t mask[320 * 200]; + static uint8_t last_fb[320 * 200], last_dac[768]; uint32_t pal[256]; const uint8_t *src = M + VGA_BASE; float toast = 0; int i, hd_on = 0; HdFrame hf; + if (SDL_GetWindowFlags(win) & (SDL_WINDOW_MINIMIZED | SDL_WINDOW_HIDDEN)) { redraw = 1; return; } + if (!redraw && !toast_t0 && !memcmp(last_fb, src, sizeof last_fb) && !memcmp(last_dac, vga_dac, sizeof last_dac)) + return; + redraw = 0; + memcpy(last_fb, src, sizeof last_fb); + memcpy(last_dac, vga_dac, sizeof last_dac); for (i = 0; i < 256; i++) { uint32_t r = vga_dac[i * 3] & 63, g = vga_dac[i * 3 + 1] & 63, b = vga_dac[i * 3 + 2] & 63; pal[i] = 0xff000000u | (r << 2 | r >> 4) << 16 | (g << 2 | g >> 4) << 8 | (b << 2 | b >> 4); @@ -398,6 +409,7 @@ static void menu_modal(void) { SDL_ShowCursor(SDL_DISABLE); host_audio_lock(); audio_hold = 0; host_audio_unlock(); mb = 0; memset(press_until, 0, sizeof press_until); + redraw = 1; t0 += SDL_GetPerformanceCounter() - start; /* le temps du jeu ne s'est pas écoulé pendant le menu */ } @@ -407,6 +419,7 @@ void host_pump(void) { while (SDL_PollEvent(&e)) { switch (e.type) { case SDL_QUIT: host_quit = 1; break; + case SDL_WINDOWEVENT: redraw = 1; break; /* exposée, redimensionnée, restaurée… */ case SDL_MOUSEMOTION: game_mouse(e.motion.x, e.motion.y); break; case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: { int bit = e.button.button == SDL_BUTTON_LEFT ? 1 : e.button.button == SDL_BUTTON_RIGHT ? 2 : 4; @@ -443,7 +456,7 @@ void host_pump(void) { if (my < 0) my = 0; if (my > 199) my = 199; } -void host_idle(void) { SDL_Delay(1); } +void host_sleep_us(uint64_t us) { SDL_Delay((Uint32)((us + 999) / 1000)); } /* un peu en retard plutôt qu'en avance */ void host_mouse(int *x, int *y, int *b) { uint64_t now = host_time_us(); diff --git a/runtime/machine.c b/runtime/machine.c index a1e77d4..ca6e45d 100644 --- a/runtime/machine.c +++ b/runtime/machine.c @@ -90,6 +90,25 @@ uint32_t poll_counter; static uint64_t next_tick_us, next_frame_us; static uint32_t polls_since_frame; +/* prochain évènement qui peut changer quelque chose pour le jeu : horloge (IRQ 0), minuteur du jeu, + * image suivante (affichage, clavier, souris) */ +static uint64_t next_event_us(void) { + uint64_t t = next_tick_us < next_frame_us ? next_tick_us : next_frame_us; + if (game_timer_fn && next_game_us && next_game_us < t) t = next_game_us; + return t; +} + +/* Boucle d'attente pure du jeu, repérée par tools/recomp.py : elle ne fait que relire la mémoire (par + * exemple « while (tics < tics_par_image) ; » dans la boucle principale). Seul un évènement peut la faire + * sortir : on dort jusqu'au prochain, puis on le traite. Même comportement, sans brûler un cœur. */ +void rt_wait_loop(void) { + if (!in_irq && next_frame_us) { + uint64_t now = host_time_us(), next = next_event_us(); + if (next > now) host_sleep_us(next - now); + } + rt_poll(); +} + void rt_poll(void) { uint64_t now; int guard = 0; @@ -112,9 +131,13 @@ void rt_poll(void) { } if (guard >= 8) next_game_us = now; } - /* Le jeu attend en boucle active (compteur de ticks, retour de balayage) : passé un certain - * nombre de passages sans nouvelle image à produire, on dort un peu au lieu de brûler un cœur. */ - if (++polls_since_frame > 4096 && now + 2000 < next_frame_us) host_idle(); + /* Attente active que le recompilateur n'a pas reconnue (retour de balayage, boucle qui appelle une + * fonction…) : passé un certain nombre de passages sans nouvelle image, on dort jusqu'au prochain + * évènement au lieu de brûler un cœur. */ + if (++polls_since_frame > 4096) { + uint64_t next = next_event_us(); + if (next > now + 1000) host_sleep_us(next - now); + } if (now >= next_frame_us) { uint8_t sc; polls_since_frame = 0; diff --git a/runtime/rt.h b/runtime/rt.h index 6d01daf..d0f561e 100644 --- a/runtime/rt.h +++ b/runtime/rt.h @@ -68,7 +68,7 @@ void ports_out(uint32_t port, uint32_t v, int size); uint64_t host_time_us(void); void host_frame(void); /* appelé ~70 fois par seconde de temps du jeu */ void host_pump(void); -void host_idle(void); +void host_sleep_us(uint64_t us); /* dort au moins us microsecondes (attente du prochain évènement) */ void host_audio_lock(void); void host_audio_unlock(void); diff --git a/tools/recomp.py b/tools/recomp.py index 208ac01..ecd456c 100644 --- a/tools/recomp.py +++ b/tools/recomp.py @@ -102,6 +102,9 @@ class Recompiler: self._cur = 0 self.overrides: set[int] = set() self._fused = -1 + self._insns: dict = {} + self.wait_loops: set[int] = set() # boucles d'attente (WAIT_LOOP) + self.known_waits: set[int] = set() # listées dans runtime/attentes_.txt # ------------------------------------------------------------------ décodage def in_code(self, a: int) -> bool: @@ -274,6 +277,7 @@ class Recompiler: # ------------------------------------------------------------------ traduction def emit_fn(self, entry: int) -> list[str]: insns, labels, _ = self.closure(entry, stop_at_entries=True) + self._insns = insns order = sorted(insns) self._fused = -1 name = f"{self.prefix}_{entry:08x}" + ("_orig" if entry in self.overrides else "") @@ -321,9 +325,49 @@ class Recompiler: if t in self.entries and t != entry: return f"{{ {self.prefix}_{t:08x}(); return; }}" if t <= self._cur: + if t in self.known_waits or self.is_wait_loop(t, self._cur): + self.wait_loops.add(t) + return f"{{ WAIT_LOOP(); goto L_{t:08x}; }}" return f"{{ POLL(); goto L_{t:08x}; }}" return f"goto L_{t:08x};" + def is_wait_loop(self, t: int, end: int) -> bool: + """Boucle d'attente pure : de t au saut arrière en end, au plus 8 instructions qui ne font que lire + la mémoire (mov/movzx/movsx vers un registre, cmp, test) et sauter ; aucune écriture, aucun appel, + aucun calcul, et aucun registre d'adresse modifié dans la boucle (un parcours de liste chaînée avance + tout seul : ce n'est pas une attente). Seul un évènement extérieur (interruption, son) peut la faire + sortir : le runtime dort jusqu'à la prochaine échéance au lieu de tourner (même comportement, sans + brûler un cœur).""" + def fam(r: int) -> str: # eax, ax, al, ah -> ax ; esi, si -> si + n = self.md.reg_name(r).lower() + if len(n) == 3 and n[0] == "e": + n = n[1:] + return n[0] + "x" if len(n) == 2 and n[0] in "abcd" and n[1] in "lhx" else n + a, n, reads, written, addr_regs = t, 0, False, set(), set() + while a <= end: + i = self._insns.get(a) + if i is None or n >= 8: + return False + m, ops = i.mnemonic, i.operands + if m in ("mov", "movzx", "movsx"): + if len(ops) != 2 or ops[0].type != X.X86_OP_REG or ops[0].reg == X.X86_REG_ESP: + return False + written.add(fam(ops[0].reg)) + elif m in ("cmp", "test"): + pass + elif m in JCC or (m == "jmp" and a == end): + if a != end and not (ops and ops[0].type == X.X86_OP_IMM): + return False + else: + return False + for o in ops: + if o.type == X.X86_OP_MEM: + reads = True + addr_regs |= {fam(r) for r in (o.mem.base, o.mem.index) if r} + a += i.size + n += 1 + return reads and a > end and not (written & addr_regs) + def translate(self, i, entry: int, prev) -> list[str]: m = i.mnemonic ops = i.operands @@ -632,6 +676,13 @@ class Recompiler: line = line.split("#")[0].strip() if line: self.overrides.add(int(line, 16)) + # boucles d'attente que la détection automatique ne voit pas (elles appellent une fonction à chaque tour) + wl = os.path.join(os.path.dirname(__file__), "..", "runtime", f"attentes_{mod}.txt") + if os.path.exists(wl): + for line in open(wl, encoding="utf-8"): + line = line.split("#")[0].strip() + if line: + self.known_waits.add(int(line, 16)) self.discover([]) os.makedirs(outdir, exist_ok=True) fns = sorted(self.entries) @@ -655,13 +706,21 @@ class Recompiler: f.write(f" {{0x{e:x}u, {prefix}_{e:08x}}},\n") f.write(f"}};\nconst unsigned {mod}_fn_count = {len(fns)};\n") report = [f"fonctions : {len(fns)}", f"tables de saut : {len(self.tables)}", - f"sauts indirects non résolus : {len(self.unresolved)}"] + f"sauts indirects non résolus : {len(self.unresolved)}", + f"boucles d'attente (WAIT_LOOP) : {len(self.wait_loops)}"] report += [f" {a:#x} {s}" for a, s in sorted(self.unresolved.items())] + report += [f" {a:#x} boucle d'attente" + (" (listée)" if a in self.known_waits else "") + for a in sorted(self.wait_loops)] + missing = sorted(self.known_waits - self.wait_loops) + if missing: + report.append("boucles d'attente listées mais introuvables : " + ", ".join(f"{a:#x}" for a in missing)) + print(report[-1]) report.append(f"instructions non traduites : {len(self.traps)}") report += [f" {a:#x} {s}" for a, s in sorted(self.traps.items())] with open(os.path.join(outdir, "rapport.txt"), "w", encoding="utf-8") as f: f.write("\n".join(report) + "\n") - print("\n".join(report[:3]), f"\ninstructions non traduites : {len(self.traps)}") + print("\n".join(report[:3]), f"\nboucles d'attente : {len(self.wait_loops)}", + f"\ninstructions non traduites : {len(self.traps)}") if __name__ == "__main__":