Thursday, 29 November 2012

[ASM] How to use the windows API in NASM

Hellooow everybody! ;-)

Today I will give you a short guide on how to use windows API in ASM programming! (at least in programs compiled with NASM because this is the one I'm using and as I'm quite noob about the different versions of asm, I prefer not risk to tell wrong things) This is because I wanted to learn some asm stuff and make little programs on windows, and quickly realized that windows was too protected to use pure asm and that we need to use the windows C++ API, including console I/O.

What is the windows API?
It's a library of C++ functions. You have to use it if you want to make any program on windows. So that means you will have to call these functions in your asm code.
It's called kernel32.dll for 32bits systems, and normally it's in the path :-)
Here is the official documentation:
Here is the documentation for console stuff:

How to call a windows API function in asm?
1) Don't forget the header!
You have to declare any function you want to use in your code by specifying them as external functions. Basically at this point all you have to do is to put a line like this in the begining of your file:
  extern    Function1Name, Function2Name, FunctionNName
example (console I/O):
  extern    ExitProcess, GetStdHandle, WriteConsoleA, ReadConsoleInputA

/!\ If you want to use any windows constant in the function calls, you also have to declare those.
For example for the GetStdHandle, these can come in handy :
  STD_OUTPUT_HANDLE    equ -11
  STD_INPUT_HANDLE     equ -10
But of course you can directly pass the constant value as an argument (if you wanna do it in the hardcore way :p) 

2) Function calls in asm
Function calls in asm aren't really more complicated than in any other language. You just have to pass the arguments the function needs and call the function's name.
In asm your pass the arguments by pushing them on top of the stack:
  push    arg

/!\ Always remember that as the stack goes decreasing, (unlike a stack of papers) you have to pass the arguments in the reverse order:
  push    arg3
  push    arg2
  push    arg1

Once all the arguments are sent to the stack, you can call the function:
  call    function

Example: WriteConsole call
  push    NULL
  push    buffer_out
  push    msg.len
  push    msg
  push    dword[handleOut]
  call    WriteConsoleA

How to compile and link a program that uses win API functions? (using nasm and golink)
This is the easy part! Just open a console and eventually cd in the right directory.
To compile, type something like:
>> nasm -f win32 yourProgram.asm -o yourProgram.obj
and to link the library using golink:
>> GoLink.exe /console /entry starting_point_of_your_asm_program yourProgram.obj kernell32.dll

Or, you can do a makefile:
  yourProgram: yourProgram.obj
  GoLink.exe /console /entry starting_point_of_your_asm_program yourProgram.obj kernell32.dll
  yourProgram.obj: yourProgram.asm 
  nasm -f win32 yourProgram.asm -o yourProgram.obj

NB: 
If you don't already know GoLink, it's a linker, which means it's able to link your file with the libraries you want. (in this case the kernel32.dll file)
You can download it here: (direct download of last version)
Manual:

NB2:
In order to use these commands, the source folders for nasm and GoLink.exe have to be in the path. So when you install them don't forget to add these at the end of the path variable. (right click on computer => advanced system parameters => environment variables... => find "path" in the system variables table, hit "modify" and add your new paths at the end, separated by a ';')

Working example: system("pause")
  STD_OUTPUT_HANDLE   equ -11
  STD_INPUT_HANDLE    equ -10
  NULL                equ 0
  global start
  extern ExitProcess, GetStdHandle, WriteConsoleA, ReadConsoleInputA

  section .data    ;message we want to display on console
  msg                 db "Press a key to continue...", 13, 10, 0
  msg.len             equ $ - msg
  consoleInHandle     dd 1

  section .bss     ;buffers declaration
  buffer_out          resd 2
  buffer_in           resb 32

  section .text
    start:       ;starting point of our program
        push    STD_OUTPUT_HANDLE
        call    GetStdHandle   ;call to get a handle to the
        push    NULL           ;specified mode (input, output...)
        push    buffer_out
        push    msg.len
        push    msg
        push    eax            ;contains the GetStdHandle result
        call    WriteConsoleA  ;call to print our msg in console

    read:
        push    STD_INPUT_HANDLE
        call    GetStdHandle        ;new call to get input handle
        push    NULL
        push    1
        push    buffer_in
        push    eax
        call    ReadConsoleInputA   ;call to detect user input
                                    ;this function will wait til
    exit:                           ;it detects enough keypresses
        push    NULL                ;(in this case, 1)
        call    ExitProcess

Manual pages for the functions used in this code:
- ExitProcess
- GetStdHandle
- WriteConsole (A stands for ANSI version)
- ReadConsoleInput (A stands for ANSI version)


I hope this helped some of you! See ya around and have fun coding ;-)


Additional source for this article:
This thread I posted on stackoverflow.com when I was having a hard time understanding all this: ;-p

Monday, 16 July 2012

BA de BJPSTA

Note : An english version of this article is coming! Stay tuned! ;-)

     Mais que cache ce titre obscur ? Rien de moins que la présentation tant attendue du petit jeu que je suis en train de développer pour smartphone. La première version sera la version android  (hé oui), que je vais essayer de terminer pour septembre.

Pour reprendre la présentation du twitter 'officiel' (@BJellyPixel), Bikini - Jelly : Pixel Smash Them all ! est un petit jeu de plateforme bien sympa en devenir, avec un nom absurdement long, néanmoins indubitablement cool ! Le jeu est pensé pour être dynamique et fun, en plus d'une mignonitude ambiante très présente :p

via @BJellyPixel :
BJPSTA est la fusion révolutionnaire de tout ce qu'il y a de plus cool : filles en bikinis, mobs trop chous, pixels à gogo, et MASSACRE :-O   |   Le principe est simple : (1) On contrôle une "fille" en petit bikini   |   (2) Le but d'un niveau est d'écrabouiller sans pitié tous les mignons petits monstres en gelée ! :-D   |   Et enfin, (3) Pour corser le jeu, il faut être habile pour triompher car nos amies les Jellies ont plus d'un tour dans leur sac !   |   Le tout dans un environnement tout en pixel art, pour le plaisir des yeux... ;-)
Heliosa, première héroine !
     Mais enfin, un peu plus de détails. L'idée de base m'est venue en cours d'éco, alors que je songeais aux ingrédients les plus cool que l'on puisse mettre dans un jeu video... Et je me suis dit : Pourquoi ne pas faire un jeu composé de tout ce qu'il y a de plus cool, un jeu auquel j'adorerai jouer ? (J'ai toujours du mal à trouver des jeux sur smartphone qui me plaisent, n'étant pas addepte des Angry Bird, Fruit Ninja, et autre Doodle Jump, pour ne citer que les meilleurs moins mauvais ;p) Je me suis donc mise en route pour développer le jeu le plus cool du monde o/

Note : Je ne dis pas qu'il n'y a aucun bon jeu sur smartphone, c'est vrai que c'est une question de goût. Mais à part sur émulateur, je n'en ai jamais trouvé qui me fasse dire : Wouah, ce jeu est génial ! Et si je ne trouve pas mon bonheur sur le market, j'imagine que ça doit être le cas d'autres personnes... En tout cas je suis ouverte à toute suggestion :-)

Les briques élémentaires de Bikini - Jelly : Pixel Smash Them All ! sont tout simplement transparentes dans le nom du jeu :
 - des bikinis pour le coté sexy,
 - des 'jellies', aka des monstres en gelée pour euh... parce que c'est cool quand y'a de la gelée partout ! ^^'
 - des gros pixels pour un environnement mignon et un rien old school,
 - et enfin, de la violence, puisqu'il faut toutes les écraser avec une arme de guerre ! De la violence sans conséquences cependant, puisque ce ne sont que des monstres en gelées, et comme chacun sait, les monstres en gelée... ne meurent pas... ;-p

Voilà voilà, j'éspère que le jeu et son univers vous plairont ! ;-) Je donnerai plus d'info par la suite via la section Bikini-Jelly PSTA de ce blog, ou le site en devenir pixel-smash-them-all.com, et surtout sur le fil twitter @BJellyPixel. En attendant je suis en plein dev, alors n'hésitez pas à me faire parvenir vos remarques ou suggestions ! A très bientôt !

Wednesday, 11 July 2012

Cours Heliosa, cours !

Coucou tout le monde !

     Vous avez bien sûr tous entendu parler de mon petit projet de jeu smartphone ! (j'en parlais dans un précédent article : lien, et je donnerai plus d'infos quand j'aurais le temps. J'en profite pour créer un libellé "Bikini - Jelly : PSTA" qui regroupera tous les futurs articles sur le sujet)
Pour ceux qui n'étaient pas attentifs, il va s'agir d'un petit jeu de plateforme bien fun répondant au nom mélodieux de Bikini - Jelly : Pixel Smash'em'all ! Retrouvez toutes les infos sur le fil twitter @BJellyPixel , j'ai la flemme de tout remettre ici ;p

Hier, j'ai réalisé l'animation de course de ma première héroïne, Heliosa ! :3
- Version grande qui fait mal aux yeux -
Donc comme Twitter ne permet pas de publier de GIF animés (j'ai même essayé de changer l'extension en .png et tout mais ça a pas fonctionné), je la met ici :



- Version taille réelle -











Vous la trouvez pas trop mimi ?! <3

Blague à part, l'animation est réalisée sur six sprites donc c'est légèrement saccadé, et encore bien perfectible... Pour la taille, j'ai choisi des dimensions beaucoup plus modestes que l'ancien pixart de la version pc inachevée : 60x50px environ. (ici avec du blanc autour on en est à 65x55)

Voilou ! N'hésitez pas à laisser vos commentaires, je suis à l'écoute ! :p