Showing posts with label unit test. Show all posts
Showing posts with label unit test. Show all posts

Thursday, April 18, 2024

32-bit

Bion, jusqu'ici mon laptop tient bon, mais il a un truc un peu spécial qu'il vaut mieux que je documente pour mon moi-du-futur: il continue de faire tourner certains programmes en 32-bit alors que c'est un ubuntu 64-bit. Lors de mes premiers pas dans l'espace d'adressage gigantesque d'AMéDée64, le double support 32/64, c'était la règle, mais ça fait quelques années déjà qu'on y est plus.

Or, mon environnement de tests automatiques pour libgeds s'efforce de faire croire au code qu'il est sur une DS en ajoutant de la mémoire valide ici où là pour que les écritures dans les registres n'échouent pas. Ruse qui ne marche qu'avec un système 32-bit pour une raison qu'il faudra que je demande à mon moi-du-passé de me documenter.

When AMD64 support had been introduced in Ubuntu systems, the default was to ensure the system could run both 32-bit and 64-bit executables. That means 2 copies of the standard libraries, 2 copies of many libraries, etc. Nowadays, your default Linux distributor has dropped 32-bit distros and the 64-bit distros have been updated so that they only feature 64-bit binaries. So the CPU can still run 32-bit thing, the kernel can still run 32-bit processes, but the support libraries are missing. That means when I e.g. try to use 2009-old SchismTracker to export a .xm of a soundtrack, I get a puzzling error message.

En plus de ça, l'outil que j'utilise pour éditer les musiques du jeu (SchismTracker) a laissé tomber le support des fichiers .XM pour ne plus produire que des .IT ... alors que je m'en sers essentiellement pour convertir les .IT du frangin en .XMs :P ... Je promène donc avec moi un répertoire de binaires 32-bits lui permettant de continuer de tourner mais il faut pour celà que l'OS lui-même ait quand-même quelques outils et configurations sous la main pour exécuter du 32 bits. Faute de quoi, le shell persistera à nous dire

-bash: /home/grizzly/bin32/schismTracker: no such file or directory

alors qu'il est bel et bien là (ouais, pas terrible, les codes d'erreur pour le coup).

Comme linaro vient de me faire le coup, je profite que je suis pas à pas un petit howto sur stackoverflow pour me laisser un topo de voyageur temporel...

Of course, the binary alone is not enough: I have noah-arch-ived a few mandatory libraries that the application will use, like libXxf86misc.so, but these are not the "support" libraries. When I mean by that is C and C++ runtime, ia32 elf loading libraries (yup, your kernel typically doesn't know how to do that alone and needs a shared library to load executables into memory ^^"). So for future self and geeks-in-training reading this, here are the commands I typically use


sudo dpkg --add-architecture i386 # there is more than x86_64, you know
sudo apt-get update
# accidentally did an apt-get upgrade...
sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386
# that was enough for me.
# sudo apt-get install multiarch-support # might be needed otherwise...
sudo apt-get install libz1g:i386 # was needed later on for linaro building newlib

edit: does it sound convoluted to use 2 different versions of SchismTracker when you could just use some XM-targetting software to create the music in first place ? Well, you should ask Nina Kalinina to tell you how *she* makes music ready for GBA playback ;-)

Sunday, October 22, 2023

done transition on looping animation

I've been crawling on the dark side of hobby game development lately. Dark because it mostly involved too much hex numbers and too little pixels to feed enjoyment while doing it. Dark because it implied admitting that I have not been paying enough attention to things like "whether unit test still pass" and "whether it might be the right time to merge that into default". Things that make the difference between coding and coding as a job. Now I have to repay that attention debt, right after the buggy-tool debt and even before I can look at that memory leakage debt. Given how long it took, how little motivation I had to do it more than 1h per day, I wonder whether I shouldn't have opted for something less useful but more enjoyable first...

Anyway, I went on with cherry-picking bits of the 'newmap' branch that ought to have been on independent branches and merged into default long ago until I finally identified the fix that stabilizes on what pages animations are actually loaded.

Y'a les jours où le développement de jeux, c'est fun. Puis il y a les jours où le programme supposé anticiper les défauts du moteur de jeu vous crache de l'hexadécimal à la figure. Tout ça parce que j'avais espéré pouvoir remonter dans le temps avant la décision "allez, on va faire évoluer le moteur de jeu pour qu'il puisse supporter plus de pentes, plus de types de sol et encore plus de folies!" ... parce que je n'avais pas pris la peine de vérifier que la modification juste avant ("allez, on va autoriser la fuuusiooon de fichiers graphiques au moment du chargement pour permettre d'avoir un monde 2") ne cassait rien de ces fameux tests automatiques.

Et encore: l'hexadécimal, il a presque fallu aller le chercher dans les boyaux de la bête qui se contentait sinon de nous roter un "transition sur fin d'animation en boucle". Eh oui. Et j'avais beau reprendre les fichiers dans mon éditeur, vérifier à coup de MD5 que j'utilisais les bons, vérifier l'état du GobTransition dans le débuggeur, rien ne parvenait à expliquer comment l'animation d'inkjet se retrouvait tout à coup avec une boucle.

I have small scribbled characters and notes about it all over my yearly notebook, but I thought it might be worth another "big picture" sketch page to summarize all the things I had forgotten about my own code and re-discovered while working on this specific bug.

Like how you can load two files in the sprdo helper tool to see which animation #543 truly is ... I should have remembered that earlier on. As soon as I noticed that the the commands I could see in the debugger were not matching what they should (they were ending with a 'LOOP' command, just to start with. I tried comparing them with the line above, the room above, but I should really have just compared them with the next page ^^". Then I've been distracted by that "meds+4" extra token on some files, but it was just a hint for Level Editor. I guess that would have been obvious if I had refreshed memories of "world 2" by reading my own blog posts again. But for some reason, I only thought about that tag now, when blogging about how I eventually figured out that I was missing some fix written long ago, but not merged on "default" ^^".

Au final, ce que j'aurais du faire, c'est comparer cette animation incompréhensible à celle se trouvant au même emplacement, mais sur la page *suivante* dans mon fichier school.spr ... parce qu'il me manquait sur la branche que je cherchais à corriger un malheureux patch corrigeant un décalage d'une position au moment d'enregistrer les animations du fichier supplémentaire à côté du fichier de base :P

Saturday, July 22, 2023

DS Ram Leakage in TestNScripts

I had thought that fixing 'slope unit-tests' in addition to 'wall unit tests' would mean my fixes to get the scorpeye behaving as intended. That would mean the 'summer code review' would be over and the 'summer game dev' could start. Well, that was hoping too much, because there's actually one more test that, for some reason, doesn't show up in ./testme --list but still exists and is important: TestNScripts. This one loads the real .cmd files of SchoolRush and checks parsing went fine. And it does not only check one of them: it will reload many scripts in the same "engine", the way the game does.


while (ntests < n) {
   TestBench tc;
   for (uint i=0; i < REDO; i++) {
       printf("== R%i/%i redo%i ", ntests, n, i);
       tc.ResetEngineResources();
       ParseScript(tc, scripts[rand()%nscripts], __FUNCTION__);
       tc.CheckEngine();
   }
   ntests++;
   tc.Over();
}

No assertion failure here, instead one of the trickiest things to track: memory exhaustion. So it's time for me to learn how to use my tracking tools again. I even left documentation for my future self back in the past (thanks, past self ^^). Once again, the problem arise also in 'default'... looks like I had been over-optimistic in September 2021 when I merged sprites overlay into default.

Well, at least if gives me hope this time: on the 'newmap branch', the forgotten test terminates with 'Out of DS memory'. I managed to get a log of what is allocated at that time, but it would require filtering what has leaked from last ParseScript, and what belongs to the current, interrupted because there's no more memory, running ParseScript. Hopefully, when the bug occurs on default, it gives me a nice 'halt because of leakage' and not a 'out of DS memory' condition. 

  • [done] understand why the new branch gets so high on memory consumption
  • [todo] make sure .spr and .cmd files in fakeroot/ are working fine (despite they now need bilou.spr and school.spr)
  • [todo] that should be the job of UnitTest.mk

edit: dummy! dummy! dummy! ... the 'DS Ram Usage' statistics in those tests is a lie! when it says 95% used, it doesn't mean you'd use 95% of the NDS 4MiB of RAM to play the script. It means that the dummy-allocator-that-never-recycle-memory used 95% of its storage to process the script. Should parsing become more complex (e.g. because we're loading one more file, or creating more intermediate structures), the memory used by the script will grow while the true RAM usage on the NDS would stay roughly the same.

Eeet ouaip. Je me suis donc morfondu un bon morceau de l'été sur le fait que mon moteur de jeu faisait péter sa consommation de mémoire. En tout cas, ça a sérieusement refroidi mon appétit pour le dévelopement de jeu après les heures de boulot. Trouver le problème, ça demandait de se plonger dans une montagne de données et les outils d'il-y-a-longtemps pour comprendre où était la fuite... Sauf qu'en vrai il n'y avait pas de fuite. Tout ça, c'était juste un ou deux messages d'erreur mal nommés qui me faisaient croire que la lecture des scripts prenait plus de 4MB de mémoire (tout ce que la DS a, en somme), sauf que l'environnement de test pour faire tourner les niveaux de mes jeux DS sur PC n'est pas prévu pour qu'on joue, mais pour qu'on trouve les erreurs. 

Donc contrairement à un système de gestion de mémoire ordinaire, quand on lui "rend" un bloc de mémoire il ne le réutilise jamais. La mémoire qu'il fournit à la demande est toujours de la mémoire qui n'a jamais servi pour une autre tâche dans le niveau, et c'est elle qui finissait par faire défaut. Vous me permettrez de croire que si vous avez envie d'en savoir plus, vous êtes aussi en mesure de lire l'Anglais?

If I want to have an estimate of the memory it would take on the NDS, I'd have to keep track of individual allocs and frees and see whether they reach some maximum at a new alloc. (2023-10-23)

What is that one-time allocator ? well, maybe you've heard of bottom-up allocator, where you just keep track of one position in memory: the top-of-used-area, and everything above the top is unused memory. Of course, as soon as you free things out-of-order compared to how you allocated them, that allocator is no longer enough. You would like at least a list of freed-blocks-that-could-further-reduce-top in case the block at the top is eventually freed. Well, the one-time allocator does not even do that. Any byte of one-time memory can be allocated exactly only once. If freed, it is "painted" as free and will remain like that until the ongoing test terminates. 

That is silly as far as memory management is concerned, but it means if some block has not benn freed when the test terminates, you know what role this memory had when it failed. There can't be any tricky-as-hell case where "yeah, that memory had been used for A and then freed, but then it has been re-allocated for B. So maybe B is wrong or maybe something still had a reference of when it was used for A". Sometimes it truly helps. When I'm not misguided by my past self with lying error messages.

Thursday, July 20, 2023

class AppleWalls : public WallTest, UsingApple

So I had managed to get shell/walls interaction mostly fixed. I thought it would be wise to get it run 'unit tests' to ensure nothing got broken by the fix, but it would do more than a few seconds of tests before failing. In Walls/Walk test , a fairly recent addition to MapTests.cpp, for which I do not seem to have any commit where that test is a success.

The test failure will produce patterns such as

--(120,0)+<-508,0>:[-224,0]     's/7f.f, S/fe08.0, '
--(118,0)+<-512,0>     's/7f.f, S/fe08.0, '
--(116,0)+<-516,0>     's/7f.f, S/fe08.0, '

--(114,0)+<-520,0>:[-232,0]     's/77.f, S/fdf8.0, '
--(112,0)     's/77.f, S/fdf8.0, '
--(110,0):[-240,0]     's/77.f, S/fdf8.0, '
--(108,0)     's/77.f, S/fdf8.0, '
--(106,0):[-248,0]     's/6f.f, S/fdf8.0, '
--(104,0)     's/6f.f, S/fdf8.0, '
--(103,0)+<248,0>:[0,0]     's/6f.f, S/fdf8.0, '

which I, too, find cryptic. I should at least inform future self that they are from saved "last state" array, dumped on exception like assert failure during the test.
  • (%{x}, %{y}) is used to report new coordinates
  • <%{vx}, %{vy}> is used to report a new speed
  • [%{dx}, %{dy}] is used to report new delayed step

Together with the arena layout defined by walls1, it can start making sense. For instance, x=104 is the lowest valid position before entering the two-# "wall" of the upper platform, where the Gob-under-test is walking. Granted, this is arcane and confusing, and it would deserve a review fix even if it is only for me. Possibly even more confusing are the `s/%x.%x` codes reported between quotes afterwards. These are generated from ChiefInspector::report() call from the WalkerController.

  • lowercase s indicates that there has been a change of tile considered in doslopes(). hex values are the coordinates of the hotspot used to decide that.
  • uppercase S indicates that doslopes() reported we're on sloped ground. hex values are the speed defined during doslopes().

Even with that wrong report of sloped ground fixed, I still have my 'follower' capable of entering walls. It happens when we stop next to the wall, but do not cancel the 'step value still needed'. More investigation needed.

With some break getspeed and cond BREAKNO (x >> 8) < 105 && cdata[GOB_XSPEED] == -520 in an epic gdb session, I could trace precisely what happens, one GobController call after another, and how the speed, delayed steps and the like where further processed.

The issue turned to be linked to the 'maxmove computation', an engine feature added in 2020 that scans the animation commands ahead of think() calls, so that we don't ask doslopes() to check for something different than what we'll actually do, else the vertical move and the horizontal move won't match and we'll end up out of the slope. The code that decides what to do when we detect a move must be cancelled assumes that the motion debt stored in the 'delayed step' variable has already been validated by controllers. In case of failure, we're safe to move *at least there*.

That was true with the "school rush" engine, where it was helpful to ensure we actually get close enough to the walls for the testpoints to work as intended. It is no longer true if maxmove shortened some of it. How precisely this can be fixed still has needed a bit more time to be figured out.

PS: while looking for the 'inspector codes' in my 2020-notepad, I got my eyes caught by a character stating "this is contemporary to maxmove introduction"... The line below reads "hopefully, no need to tweak things (how many loops are allowed while processing animation instructions, btw) too much. All it takes is building an animation list with enough 'I_MOVETO(+1, *)' commands before it loops."

PPS: of course, fixing things here broke things there, but mostly because code was wrongly assuming that some things (like vertical position or FAIL counter)

Tuesday, September 28, 2021

just another breakpoint in the wall

Since last week, I've been tweaking the state machine of my meka-tester trying to make it better mimmic the behaviour of Bilou when it gets into the walls. I finally get the kind of error I wanted, but it makes little sense.

. . .  Well, I initially wanted to tell you about how it suddenly hops into the wall, 4 pixels further than it was without ever seeing the 'building up' delayed move explain anything of that. but I feel so tired. s/4f.f, S/ffe6.0 ... I'd have to dig up my notebook (page 14) to decode what that means. I just can't. my eyes don't want to look at the screen anymore. See you later.

Pendant près de deux semaines, j'ai fait des essais et des ajustements pour avoir un meka-apple qui reproduise les bugs et-vlan-me-n'là-dans-l'mur que je rencontre systématiquement dès que j'essaie de jouer dans le nouveau niveau de mon fiston. J'ai fini par y parvenir, mais on ne peut pas dire que ça m'aide à comprendre ce qui se passe. Une téléportation de 4 pixels d'un coup, alors que tout semblait aller bien jusque là...

Un peu de repos, un peu d'astuce, et j'ai des pistes pour améliorer la situation. Mais alors que je refais un essai dans "Dreams.nds", je me rends compte que le problème est toujours là. Et il est très facile à reproduire manette en main sur ce niveau, en plus. Est-ce que j'ai tenté de faire du unit-testing trop tôt ?

<later> over the week, I managed to identify some issues and possibly fix some, but it is still possible (and actually easy) to trigger. 

It makes me feel like I tried to unit-test the issue too early. Maybe what I actually need is a way to get a bunch of data out of the emulator, and monitor them when I'm done reproducing the issue.

Let's see what we would need ...

Je change d'approche, du coup : il existe dans l'organisation de mes jeux une classe indépendante du Game Engine, mais qui a accès aux objets du Game Script et qui peut exécuter une méthode à chaque frame, le HUD. Si je fais tourner mon niveau dans un émulateur avec débuggeur, et si je rajoute un break pointau cas où Bilou serait arrivé dans un mur, je devrais pouvoir creuser le problème.

  • [done] access game object position and variables.
  • [done] record them, e.g. in the GameObjectState structure defined in unit-tests
  • [done] check whether game object got into a wall (cando(0,0, PLAYER_THRU)
  • [done] switch to 'investigation' mode when we're in a wall
  • track state changes and controllers reports (through a custom inspector)

edit:A class deriving from iHud met all the criterion above. If I'm okay with using ddd to inspect the content of the last GameObjectState array, I can start investigating ...

Sauf que ça n'a pas été si simple. Même en ré-important le code des tests qui enregistre les mouvements des dernières seconde de jeu, l'information restait trop sommaire pour pouvoir retracer pas à pas ce qui ne "marchait" pas au cœur de la fonction do-slopes.
Mais Murad-dib m'a sauvé la mise  (oui, depuis qu'on est allé voir Dune avec les collègues, je me suis replongé dans le bouquin.) Et si comme lui je balayais de la main toutes les règles et les conventions (du c++, ici, pas du C.H.O.M.)... si je prenais avant chaque appel à bilan.PlaY Une copie de la mémoire contenant l'objet 'Bilou' ... je pourrais en cas de mur réappeler 'play' sur la copie ! le moteur de jeu est ainsi fait qu'il n'y verrait que du feu, et je pourrais faire mon débugging pas à pas en étant sûr que je suis dans un cas où le bug va se manifester

It wasn't quite sufficient, unfortunately. Hopefully, I was reading Dune again, and going through the moment when Muad'Dib decides to break all the rules so he could get victory, I realised that I could go for Muad'dibugging too: create an empty GameObject in addition to the real one for Bilou, and memcpy a snapshot of the current state before every 'play()' call. If we turn out to end up in a wall, I could just call 'play()' on the copied state to reproduce step-by-step what the first one had encountered.

Of course, that goes against all established rules about how to deal with C++ instances, and make the 'NOCOPY(GameObject);' macro look like a fool. But it worked.

And at last, on 2021-10-13, 22:**, I think I nailed that stuck-in-the-wall bug that had been since my kid drew his pyramid level.
 

Saturday, September 11, 2021

Wall walk test.

If I want to have An understanding of what causes Bilou to get into walls when he arrives straight into it, I need to find a way to reproduce that at will. I have to update my slopS unit tests to cover that new scenario.

The difficulty with that setup is that the mecha will have to keep walking towards the wall for some frames, and only then try to turn back. Scripting a fake game pad controller to force the mecha to do that sure won't be the easiest path to follow. But I have a plan.

ouais. Bon. 'faudra que je le traduise, lui

Let's have a second mecha that is walking "normally" on one large floor while another one, the Gob-Under-Test is tracking its position and tries to follow it, just like Berry Bats would do, except "walking". That should work, right ?

Well, reality is hitting me hard, here. I haven't managed to get the test cycle work properly. I'm caught in the process of navigating the history and running because even with the obvious sorted out, my new test gets a "memory is leaking" warning and the former 'slopes' test isn't working either.

I think from now on, I'll use the 'default' branch as a way to track what is properly passing automated tests and what isn't. Good news, commit 6ab9f8ca2931 dating from this year (April 13rd) pass the slopes tests.

Caveats when doing things like this:

  • Makefile does not detect whether I change devkitpro version, so things that used to work years ago on an older devkit may fail to build nowadays and you'll have to manually clean output/*.o
  • some tests depend on fakreoot/*.cmd, which is not automatically re-populated from SchoolTests/efsroot/ or AppleAssault/efsroot/. and in SchoolTests, the files are generated from SchoolTest/cmd/, which does not occur if you just rebuild unit tests.

18731874

edit: I identified a commit at which the TestBasicSlopes started failing. Surprisingly, it was not a side-effect or whatever: the commit directly does


       if ((cspeed&cp) && !cdata[0]) continue;// this testpoint only works with speed
-      if ((chkflr&cp) && !(checks[pos] & F_FLOOR)) {
+      if ((chkflr&cp) && (checks[pos] & F_FALLTHRU)) {
        if (isi) isi->TestPoint(xtile, ytile, pos, checks[pos], "floor");
        cdata[GOB_TESTPOINTS]|=cp;
       }

Which cannot have no effect on how testpoints behave in the slope tests. But if we compare how monsters in the green zone behave before (1873) and after (1874) this commit, it is clear that it has desirable effects. So I'm now sure I have to fix the tests, not the way testpoints are handled. 

edit++: okay. The leaking object was a 'builder' helper used by the GobState objets. The builder is a std::* object temporarily used while e.g. collecting transitions from a given state before they got 'flattened' into an array for the 'running' part. The array, just like GobStates are allocated in the 'tank', a larger memory chunk meant to host many small objects that all have the same lifetime: one level.

In the 'slope' tests, each state was used to spawn a GameObject using that state for the test. There were no transitions: we first use a forward-moving mecha to check things are fine when moving forward with the Forward state, and then a distinct backwards-moving-mecha. But for my new test, I need transitions. That means that I won't spawn for every states. That means some states are not 'frozen' into the tank, and hence still hold references to std::* objects like vectors or strings. These are the leaking ones. Let's get cracking!

Sunday, May 24, 2020

Toujours dans les pentes ...

Eh oui ... on a passé la mi-mai, et je suis toujours occupé à faire tourner ces tests automatiques des pentes et à corriger l'algorithme doslopes et son intégration.

J'avais introduit un mécanisme "maxMove()" pour pouvoir obliger l'algorithme doslopes à ne pas essayer d'aller plus loin que ce que l'animation permettrait. Dans le cas contraire, il y a un désaccord entre le mouvement vertical prévu et le mouvement effectué, ce qui conduit le personnage à finir en l'air ou encastré dans le sol.

S'en est suivi une refonte de selfmove pour qu'il puisse retenir s'il y a eu un maximum appliqué (et forcer le même maximum au moment de la lecture de l'animation). Puis je me suis rendu compte que tout ça ignorait superbement les décisions du type "il ne peut y avoir aucun déplacement là-tout-de-suite", avec à nouveau des déplacement incohérents. J'essaie de le corriger, et du coup tout bloque à la première pause.

Bref, J.L.N me demandait si j'avais déjà commencé à faire des niveaux pour la pyramide, mais j'ai l'impression que ce n'est pas pour tout de suite.

edit: trouvé. Un excès de zèle au moment de lire l'animation...
edit++: les tests passent! il était temps! Je suis dessus depuis la mi-janvier... et à 23 minutes près, j'y était encore en Juin!

Sunday, April 12, 2020

Mekappleman

Le rythme 'confinement' me laisse paradoxalement moins de temps pour bilouter que mon rythme habituel. Malgré l'absence des activités de fin de journée des enfants, malgré l'absence de trajets en voiture. Entre les repas qui sont rallongés (intervention parentale oblige), les ballades de santé qui se transforment en promène-le-gamin, les mises au lit plus tardives et les débuts de soirées amputés d'un jt pour se tenir un minimum informé ...

Bref, dans tout ça, j'ai quand-même fait tourner un pseudo-dumblador sur le terrain simulé pour tester les pentes du nouveau moteur de jeu. Et je me suis retrouvé bloqué. Dans certains conditions, le code de gestion des pentes le fait entrer dans le sol plutôt que de le faire monter sur la pente. En cause, le mécanisme qui permet de 'mettre en attente' un déplacement le temps que l'animation soit prête pour un déplacement (qui peut être de plusieurs pixels d'un coup).

Some claim they can start new hobbies while they are covid-confined. I had a hobby already before, but not having to drive the car to the office and back doesn't really give me free time. Just more time tending the kids. But well, I still managed to find some time to have mecha-blador walking in virtual level and try new slopes for the revised game engine. Then I got stuck...

From times to times, slopes-handling code would makes mecha-blador enter the ground rather than climb up the slope. The cause turned out to be the trick allowing to delay a move until the animation could follow it (which may require we move several pixels at once). The tricky part is that dumblador animation mixes move-to and delay instructions. Trying to validate fixes in such conditions doesn't feel appealing, so I instead picked back the Appleman, who's walking animation is using only MOVETOs.


Là où ça se complique, c'est que le DumbBlador mélange ce genre de déplacement et des pauses. Difficile de s'assurer que les correctifs fonctionneront pour tous dans ces conditions. J'ai donc ressorti un personnage à l'animation 'plus simple', inspiré de l'Appleman.

J'ai aussi revu le mécanisme qui capture l'évolution des personnages, me basant sur l'idée que si ça ne t'aide pas à trouver les erreurs, ce n'est pas un unit test. Jusque là, testme BasicSlopesTests pouvait juste me dire que ça n'allait pas, et à quelles coordonnées le meka s'était arrêté. Le reste, c'était à faire dans le débuggeur.

Now, if I want it to be unit-tests like, it has to be useful to identify what goes wrong. So far, testme would just tell me at what coordinates the meka-sprite ended up. Everything else was to be done in the debugger. A new GameObjectState class can now collect information about how coordinates evolve and and what 'debug signals' controllers sent to InspectorWidget. Granted, $/ffff0001 is crude, but I can tell it is sent by doSlopes, which failed with (-1, 1) motion. It could actually be post-processed by a PERL script.

C'est un début, mais c'est clairement perfectible. J'ai donc un nouvel objet GameObjectState destiné à capturer tout ce qu'il faut savoir du meka pour les besoins des tests (à la discrétion du programme de test) et un ensemble de ces objets en guise d'historique (plutôt que 2 tableaux de coordonnées et un de vitesses). J'ai pu aussi intercepter les rapports destinés au ChiefInspector (relai vers l'InspectorWidget) et les capturer dans les GameObjectState correspondant. C'est un peu  
laborieux à décoder, mais ça devrait réduire tout de même le travail de mise au point. Par exemple ce '$/ffff0001' est émis par doslopes qui échoue un déplacement (-1, 1) et 'S/0' que GobWalkerController reprend la main avec des vitesses nulles dans les deux directions.

Wednesday, April 01, 2020

The Dreamland Map

I'm reaching the last pages of my plan-your-things notebook. It helped a lot completing both real-world and hobby projects. I've got more books available to take over, but I also need to make sure I won't miss contents of the 2019 book when I'll be hanging around with the 2020 book. That's why the 'todo maps' are on flying sheets rather than on proper pages.

Maybe there are things I should blog for remembering. Clearly there are things I should doxygen...

There are things I still need to blog in there. Notes I've taken about SNES hardware, for instance, and similar hardware features from the NDS which I haven't used yet.

And then, there are game analysis things, which are totally unrelated to tools & engine development, but which I'd like to bring into the 'design class'. Those, hopefully, will not be missing if I don't have them around in the new book.

You see, having the dsgametools code around in a e-boox is nice, but I need some additional place to "think out loud", and with my eyes not liking using screen more than 10 hours/day, it cannot only be this blog anymore. That's what the notebooks are for ;)


Tuesday, February 25, 2020

fakeMetaWindows

Bon, après un week-end assez "rock and roll", j'ai fini par pouvoir essayer un peu mon nouvel atout: un exécutable NDS alternatif pour la mise au point de l'interface graphique de LEDS. Parce que débugger SEDS c'est déjà pas rigolo mais il n'y a que "START + L + A" à taper pour charger un fichier. Dans LEDS, ça se fait avec les p'tits widgets d'exploration de répertoires. On clique par-ci, puis par-là, puis enfin l'émulateur charge le script principal, les spritesheets, le niveau. Et là tu peux faire A, réactiver tes breakpoints et commencer à débugger.

https://twitter.com/pypebros/status/1230601848022847494
Mais ce sera bientôt du passé. J'ai pu extraire en tous cas les dépendances de la "MapeditWindow", la "fenêtre" principale à travers laquelle on voit et modifie le niveau dans une structure qui lui prépare un niveau rien que pour le test qu'on pourra faire défiler, modifier et pour lequel on pourra aller regarder le contenu de la VRAM pour s'assurer qu'on a bien affiché ce qu'il fallait à chaque étape.

Et ce sera bien utile, parce que là, tout de suite, je me suis attaqué à "permettre de masquer/afficher les boutons qui définissent les propriétés des tiles sans corrompre le niveau, mais du coup, je casse le niveau dès le départ >_< Vous le voyez, ce gros pavé jaune dans la zone "radar"? et toutes ces petites flèches noires sur l'écran du bas (par-dessous le texte de debug blanc, c'est difficile, je vous le concède) ? Bin c't'un bug.

Tuesday, February 11, 2020

Au tour de meka-blador ...

Même si, j'avoue, mon analyse de "et qu'est-ce qu'on fait maintenant" m'avait conduit à définir MetaEdit dans l'éditeur de niveau comme la priorité suivante ... Mais la tentation a été trop grande: comment se comporterait un vrai personnage dans les tests automatiques de pentes que je viens de faire fonctionner avec un 'tic-tac-Bilou' complètement abstrait.

Je n'en suis pas au stade du Test.Read("blador.cmd"), mais j'ai au moins pu charger un vrai .spr et en extraire les animations (Merci, MedsAnim) puis constuire un nouveau cas de test basé sur un bout de texte extrait directement de blador.cmd.

Pour les bonnes nouvelles on s'arrête bientôt. Le meka-blador obtenu comme ça ne passe pas les tests. C'est qu'il est basé sur la vieille technique des testpoints qui sondent l'environnement autour de lui, et l'arrêtent avant qu'il n'approche trop du bord d'une plate-forme (là où le comportement de Bilou le laisserait avancer au-delà du bord). Mais blador ne saute pas.

Bref, mes collègues m'ont lancé dans la lecture de "Working Effectively with Legacy Code" où il est notamment question de "comment va-t-on s'y prendre pour que notre code écrit avant l'introduction des tests unitaires puisse subir des tests unitaires sans endommager sa fonctionalité". Je fais donc des p'tits exercices pratiques avec un iStateInspector que l'on peut définir au niveau de la classe GameObject et qui sera passé aux appels à GobState(::do_checks(), notamment) à la place de l'ancien flag "verbose_prints". Les vieux printf avec des coordonnées et des CON_GOTO peuvent donc quitter le code de GameObject.o: ils seront remplacé par des appels au StateInspector (s'il existe) qui peut être défini au niveau de MapTests.

Tuesday, January 28, 2020

Meka-Bilou au rapport ...

J.L.N s'est beaucoup intéressé à ce que je faisais, ce.tte.s dernière.s semaine.s sur mon ordinateur. Il y avait régulièrement une espèce de mini-niveau (en ASCII art) dans un coin de mon écran qui accompagne les rapports d'erreur du système de test des terrains pentus. Je suppose que ça attirait son attention.

Difficile d'expliquer le principe du unit-testing à un louloup de 7 ans, mais il y avait aussi mon carnet avec le même "niveau" et un bilou-mécanique prêt à le traverser. "Oh oui, c'est le tic-tac-Bilou de parrain! Tu mettras aussi celui avec un réacteur?"

Il ne croyait pas si bien dire. Après avoir reporté des paquets de coordonnées sur un schéma du 'niveau' et analysé dans ddd à quel étapes de la fonction "doslopes()" elles correspondaient, j'ai déjà pu mettre en évidence (et corriger) quelques couacs. Le fait par exemple que doslopes n'indiquaient "on est sur une pente" que si le dernier tile visité est pentu. Malheureusement, ça signifiait un glitch vertical au moment de passer sur le 'sol plat' à la fin d'une pente à plus grande vitesse parce que le code du GobController qui fait appel à doslopes pensait devoir "éviter un sursaut brusque"...

"Will you also put the rocket-meka-Bilou in your test ?" asked my 7-y-o seeing my debug notes for the on-going slopes unit test. He was closer to the reality than what the clockwork-Bilou sketch suggested. The virtual-meka-tester is now zooming at 8 pixels/frame and no longer detects it should start going down. But then the GobController in charge of 'walk-on-the-ground' detects there's no ground anymore and triggers a FAIL event. It should trigger a state change according to the state machine, but MekaBilou has none.

Now here's the catch: the GobController has not cancelled its move, and over every next frame, it will start flying off (so much for the little wheels I'd drawn) and only the 'killer' tiles I put in the sky can stop it. I'll need some more code to interupt tests when unexpected state transitions occur, apparently.

Mais le plus curieux m'attendait encore. Lancé à presque 8 pixels / frame voilà Meka-Bilou arrivé en haut de la pente, et par un malencontreux concours de circonstance (plus un p'tit bug), il ne détecte pas qu'il devrait redescendre. Le code du GobController, lui, constate bien qu'il n'y a plus moyen de se déplacer normalement sur le sol et génère un FAIL (qui doit normalement provoquer un changement d'état dans le comportement du personnage). Sauf que, désolé, les amis: meka-Bilou n'a pas de machine d'état, et le contrôleur n'a pas annulé le mouvement (il était possible: on ne rentrait pas dans un mur). Du coup, rien n'empêche le même mouvement d'avoir lieu au(x) cycle(s) suivant(s). Faisant fi de ses "roulettes", Meka-Bilou s'est mis à traverser le ciel à toute allure jusqu'à ce qu'il soit stoppé net par un 't'as rien à faire là' qui met fin au test.

Un peu de code en plus, et je peux à présent capturer les transitions 'on fail' dans mes cas de tests et tout arrêter quand ça se produit. Et ça me fait penser que, quand j'aurai réussi à importer le comportement des applemen et autre dumbladors dans mon environnement de tests, ça pourrait être intéressant de marquer certaines portions de tests plus sophistiqués comme "interdiction de tomber ici", "interdiction d'atterrir là" ...

Monday, January 20, 2020

test de pente en cours

Voilà, j'ai mis en route quelques modifications pour appliquer les idées du nouveau système de description du niveau avec comme point de départ un p'tit morceau de code qui crèe un 'niveau de référence' et place un personnage simple dessus qui devra avancer d'un bout à l'autre sans ce faire stopper.

Tout ça se passe dans l'environnement 'unit-testing' plutôt que sur la console elle-même et donc est testé contre les fuites de mémoire. Mais au moment d'essayer de comprendre pourquoi il y a une fuite, je me rends compte que scan-mem.pl (qui traduit les adresses stockées dans un fichier trace%d.log en nom de fichier/fonction/numéro de ligne) ne marche plus.

I had to do some more unit-testing on the new level description system. Good thing with that unit-testing environment (running on my dev PC rather than on the NDS or in an emulator) is that it features some memory leak detection. But unfortunately, as I tried to use my scan-mem.pl script -- the one that converts raw addresses stored in log files into filenames and line numbers -- I couldn't get anything relevant.

The reason for that is that Linux "now" features an address space layout randomization mechanism, that ensure .ELF files are no longer loaded at well-known memory locations, but instead takes advantage of their re*L*ocatable nature to make every instance of the program somewhat different from the others, and therefore make sith-hat hackers' life miserable by denying them simple access to part of the code/data they'd like to use in their exploit. Generally speaking, this is great, but right-here-right-now, this is bad news.

La faute au "nouveau" système de brouillage d'espace mémoire qui ne charge plus les fichiers .elf des programmes Linux à des adresses fixes (définies dans le programme) mais qui va utiliser la faculté des fichiers ELF à se reloger en mémoire pour que chaque exécution du programme utilise des adresses légèrement différentes. L'idée est de faire en sorte qu'un hacker qui parviendrait à provoquer un crash dans votre machine avec des données à lui (au hasard, une police .ttf véreuse ;) ne puisse pas pour autant appeler la fonction popen() ou system() avec des données à lui ... parce qu'il faudrait d'abord qu'il devine où elle se trouve dans ce processus-ci.

Ça ne fait pas mes affaires, mais c'est assez simple à régler: une 'simple' ligne supplémentaire dans le fichier log pour indiquer l'emplacement actuel d'une fonction précise et un appel à nm fichier_elf | grep nom_de_fonction dans le script de décodage, et je peux recalculer le décalage utilisé, le soustraire aux valeurs trouvées dans le fichier log et conquérir le monde (mouah hah hah ...)

Hopefully, this isn't that bad to fix. All I need to do is to extract the 'expected' address of some function within the decoding script, re-compute the offset and substract it to every value found in the logfile and tAke oVeR the wORld (mwah ha haah)... Erhm. The leak. Did I just said 'the world' ?  

Euh. Enfin. On va déjà essayer de conquérir le "leakage: 0%", ce sera pas si mal.

Où était le memory leak, alors?

Le bloc incriminé, c'est une palette d'actions spéciales qui est allouée dans le parseur de scripts. Je n'utilise encore rien de ce genre pour mes petits tests, mais ils sont alloués automatiquement quand on crée le parseur. Normalement, ils devraient ensuite être délégués à GameScript quand le parseur est détruit (et qu'on est prêt à jouer au niveau) .. sauf que dans ce cas-ci c'est le destructeur de GameScript qui détruit le ScriptParser, mais il le fait après avoir regardé aux palettes d'actions ... et donc cette délégation tombe trop tard. Facile à corriger.

Sunday, January 12, 2020

un p'tit pas de plus pour LEDS

 Bien. J'ai donc un éditeur de niveau capable de faire l'affichage des niveaux même quand j'utilise le "nouveau" format. Y compris pour les blocs spéciaux. J'ai encore un peu de travail à faire dessus (notamment faire en sorte que les boutons à droite de l'éditeur ne s'incrustent pas dans le niveau chaque fois qu'on les invoque), mais c'est plutôt bien parti.

Avec tout ça, et l'introduction de nouveaux types de pente, je me dis qu'il deviendra bien utile de pouvoir faire des cas de tests sur des micros-niveaux, avec un système capable de détecter qu'on arrive bien à passer les "obstacles" quelques soient les variations de conditions initiales (légèrement plus à l'ouest, vitesse qui n'est pas un multiple entier de pixels, etc.) sans pour autant entrer en contact avec les blocs supposés en dehors du trajet.

If I want to be effective with introducing more complexity in the sloped-ground engine code, I think I'll have to add some more unit-testing. I've learnt the hard way that sub-pixel initial position, interaction with step-motion and animation quirks can lead to broken slopes code, and that debugging that takes lots of time because it needs parts in-engine breakpoints and parts in-debugger breakpoints.

A micro-level with a few simple slope scenarios, easy control on the initial state that can be automated should help a lot. And help is welcome. Plus, it makes support for those slopes independent from Level editor updates, which is welcome as well.


Si ça peut sembler une perte de temps, vu que je n'ai encore aucun moyen d'ajouter des nouveaux types de pentes dans LEDS, ça ne serait peut-être pas si mal. En plus, dans un niveau comme celui de *deline, il est assez inconfortable de vouloir vérifier si la logique du code de gestion des pentes fonctionne bien comme prévu, parce qu'on est en permanence interrompu par ce que les autres "personnages" du jeu font.

Ça pourrait aussi être l'occasion d'introduire un truc qui me titille depuis un moment: une série alternatives de constructeurs pour les objets principaux du moteur de jeux (déclarateurs de blocs spéciaux, états du comportement des personnages, zones de collisions, etc) qui ne passent pas forcément par une analyse de bloc de texte ... et seraient donc un premier pas vers la possibilité de "compiler" du gobscript en code C++ (ou assembleur 68000 ?)

tempting to use that as an excuse to introduce an alternate set of constructors that could build objects without necessarily having to rely on text parsing. Like state.Using<GobWalkerController>("") rather than relying on "using walker;" processed by GobState::parse(). That would be handy for GBA or 16-bits ports of the engine, but it isn't easy to achieve with the current codebase, unfortunately. The core reason being that classes for the controllers are encap~insulated into a separate .o that was meant for 'dynamic linking' with the engine 'happily ignoring they even exist', except through a std::map of factories that can be invoked by controller names.

Wednesday, January 01, 2020

TileMap

I had a remark in my notebook, wrote a few months ago, where I felt it weird that some parts of the game engine would require a SpriteSet where they actually needed information about the level map, and that the SpriteSet class was actually the only object capturing the map pointer, as well as its dimensions.

I then realised there was several places in the code where you'd load a map from a file, and it was tricky to use only one of them because one is within SpriteSet and the other (in the level editor) has no use of such a SpriteSet. It was time to introduce a new class with informations about a loaded map. Refactoring things went pretty fine and I could even repair a few things thanks to the 'unit-testing' tools (and thanks to the 'watchpoint' feature of ddd).

Well, I realise that doesn't mean a lot. That's all I could craft since I'm on holiday, I'm afraid. Happy new year.

edit: now, with only one class doing .map - to - memory conversions, I can make a new unit-testing tool that operates on level maps. I stuck to the idea of having some 'generic' tool invoked in scripts to define test cases based on reference data, but I pushed it on step further than 'cmdck' I wrote in early 2019: 'mapdo' handles a stack of level maps in the way a RPN arithmetic evaluator handles a stack of numbers. And you can quite easily define new 'operators' that act on that stack. It will help for things like cropping, splitting, patching etc. and can also help for tests such as "load level1.map save test1.map load test1.map eq" to check the level hasn't changed after being saved-and-reloaded (e.g. on-the-fly newmeta conversion produces the same contents as PHYS chunk loading).
  • by just passing "show" as the constructor argument to CommandHandler, this handler will be invoked whenever we see "show" on the command line
  • CommandContext.maps is the stack of level maps,
  • CommandContext.next() provides one token from the command line, for both commands-to-handlers lookup or for command arguments.
  • it could be further simplified into a void run(cc) since we no longer need to communicate the amount of command line tokens we consumed.

I love how both the core loop and the handlers are elegant, although I'd have loved a more in-line syntax like case "show": or show=>sub { ... } as well, but they wouldn't have worked in C++, would they ?

Tuesday, September 11, 2018

Truly Testable Level Editor

There was one annoying thing with the scripts while adding 1-up, and  that was I had to add the new rules in every level. This is the kind of things that should be written only once, and as far as the script parser is concerned, it could be written once, in the "rules.gam" file. The problem is, this file would be ignored by the level editor, and thus is not used so far.

And unfortunately, there are some design flaws in the way LEDS' own parser is written, making any change in that part pretty tricky to do right. It would be nice to refactor that a bit, but such a refactory with no easy way to test things would be errors-prone. My next move must be towards testable LEDs logic.


And I realised my first idea for the tests, with modified readers and all, was over designed.

Instead, it would be interesting to have two simple programs that run checks on parsed levels (eg. what are the coordinates of game object #42 , or how to display special block#3) or that do simple changes and then write back the result. Test cases are then simple shell perl scripts combining calls to those tools and to standard file comparison tools.

What I still need to figure out is how I'll extract specific information (e.g. what gob another gob links to) out of the full data. And how to compare the extracted data.

Tuesday, February 06, 2018

gource and reDS

C'est un outil super: gource. Transformer les fichiers logs d'un gestionnaire de versions en une animation interactive où les développeurs deviennent des jardiniers taillant, soignant, élagant, greffant...

Et facile à utiliser, en plus! Bon évidemment, ici c'est assez moyennement intéressant puisque je suis tout seul sur le projet depuis le début ...

Mais au moins, ça met bien en valeur les efforts pour restructurer le code et permettre à d'autres (au cas où) de faire des projets à base du moteur de jeu GEDS plus facilement.
Au passage, j'ai franchi un cap avec le code d'AnimEDS. Les "modèles" sont maintenant activés. Je regrette un peu d'avoir quand même dû passer par l'émulateur et une exécution pas à pas pour corriger les bugs introduits lors du refactoring alors que j'avais des programmes de tests pour l'architecture native juste à côté... mais bon, les erreurs étaient dans le setup des objets, pas dans leur logique.
Maintenant, il reste à sortir la gestion des "callback" hors de la classe "Engine" (je les verrais bien en gestion autonome, avec un objet complètement interne qui assure la gestion et qui est caché derrière les méthodes "register" et "unregister" de la classe-maîtresse). edit: c'est fait.

Sunday, May 21, 2017

shell to cybook

I got the z-list issue fixed. The error was what I suspected, but what is more interesting is that I have been able to write a test case that reproduced the bug systematically, and thus that demonstrate that the problem is gone with the fix.

I had to change my approach for investigating that because I've been doing so much on-line activities these last days that my eyes started to "panic". So rather than staring at my laptop top understand the outcome of a test, I pushed it into a .html file that I could browse with my e-ink cybook.


python -m SimpleHTTPServer 8000 & # http.server if you're on python3

(echo "<html><body><pre>" ; 
  ./testme ; 
  echo "</pre></body></html>") > /tmp/html/out.html

(echo "<html><body><pre>" ; 
  grep -h -C14 prepare libgeds/source/* 
    | sed -e 's:&:&amp;:g;' 
    | sed -e "s:<:\&lt;:g;" 
    | sed -e 's:>:\&gt;:g;' ; 
  echo "</pre></body></html>") > /tmp/html/code.html

Bon, ça n'a pas été une semaine simple, mais j'ai réussi à pouvoir prouver que le bug d'affichage de Bilou est corrigé tout en reposant suffisamment mes yeux qui criaient "au secours" la semaine d'avant. J'ai notamment utilisé assez abondamment ma liseuse pour passer en revue les résultats des tests (puisque oui, j'ai choisi l'approche "test automatique plutôt que l'approche "debugging interactif raffiné", la faute aux yeux précédemment cités). Celà dit, je vais rester prudent et laisser les détails techniques uniquement en Anglais pour cette fois-ci. Dès que j'aurai compris pourquoi l'encre refuse de s'arrêter à la hauteur demandée, je pourrai faire une release améliorée de School Rush.

The test itself is actually fairly simple conceptually: I just drag Bilou around in the level, back and forth, emulating the camera and the game logic after each displacement. As the camera moves through the level, some game objects freeze and unfreeze, recycling the hardware sprites, and inkjets use the top-layer sprites so that ink drops look to come from within it.

On the first round, the bug did not happen, but I had programmed a "trap" to report what I thought to be the precondition to reproduce the bug (having the inkjet frozen while it had one hardware sprite at top priority). The test then showed me that this happened, but less often that I thought. Actually, it only happened with one inkjet near the end of the level.

Then, I extended the test so that I would make an increased number of scrolls through the level. There I got the bug appearing systematically on one of the levels. I had to filter out some of the events reported during the scroll (I reported every change in the zlist's size as well as any arrival/departure of hardware sprites): inkjets throwing ink corresponding for instance to 4 correlated events. Making sure that the camera coordinates are reported (instead of Bilou's coordinate) helped as well.

Monday, November 28, 2016

class *Model

It's a bit more complicated to make my level editor test-friendly than it was with the sprite editor... so allow me to recap how I proceeded with SEDS:

hmm ... je pensais que ce serait plus simple que ça d'adapter le code de LEDS pour qu'il permette le même genre de tests que celui de SEDS. En fait non. Sans doute parce que j'ai déjà essayé d'avoir une couche "modèle" pour LEDS mais qu'elle ne correspond pas assez bien à ce dont j'ai besoin.

Guidelines

  • the model captures all the information about internal state of the edited object.
  • the UI code makes no access to the components of the model (i.e. a palette, a spritesheet, ...) without going through one of the model's function
  • code within the model is free from any UI interaction
  • each UI component (aka *Window) has its corresponding model capturing the information it needs. When a component is used by multiple UIs, we'll use a common ancestor (e.g. ModelWithSheet) to capture the shared component.
  • editor-specific extensions to the library component (e.g. EditorSpriteSheet extends SpriteSheet) is declared at the *Model.h level.

Outcome
  • Every operation performed on edited objects can be reproduced out of native UI environment for testing
  • Dependent objects are created together as a *Model, making it simple to ensure they're working correctly with each other.
  • main code no longer needs to maintain and dispatch pointers to shared component all over the place, while components themselves still blissfully ignore where the peer components they're working with are managed.

Tuesday, October 18, 2016

sprck || fail.

Good news: I managed to reproduce in a controlled environment the corruption of a spriteset. Bad news: because I had no idea what was the possible cause of such corruption, I just went through a random set of deletions and then a random set of recycling of the released blocks. And repeating the process from a sane initial spriteset until the "checker" tool reports something abnormal

One interesting thing, though: what's abnormal is abnormal twice: not only I shouldn't have "cross clusters" in my sprite pages (two slots on two pages actually referring to the same tiles), but I possibly shouldn't have "0" at all (it is reserved on most spriterams) and I definitely shouldn't have some odd tile number since the smallest allocation unit so far is 4 tiles.

edit: Another curious thing, on the "animations" subset: one page makes reference to tiles that are not in the spriteset! possibly unused things that were inserted when the page was first created and then deleted before first saved into the spriteRAM. I guess I'll need to make sure I have some automated test that do something like that, too.

edit++: I think I got most issues fixed now. I'll have to give it a run on a real device and see whether I accidently broke something with all the "refactoring"  ...