M4BASIC - sdl.m4b
Not logged in
REM Demo on how to embed an external library - https://www.libsdl.org/
REM Taken from http://sol.gfxile.net/gp/ch02.html
REM
REM PvE, August 2014 - GPL.
REM
REM Add the necessary include files and libraries as command line option to the compiler:
REM
REM gcc -include SDL/SDL.h -g -o sdl sdl.c -lm -lgc -lSDL
REM

DECLARE *screen TYPE SDL_Surface

REM Function to put a pixel on the canvas
SUB putpixel(int x, int y, int color)

    DECLARE *pr TYPE unsigned int
    DECLARE lineoffset TYPE int

    LET pr = (unsigned int*)screen->pixels
    LET lineoffset = y * (screen->pitch / 4)
    LET pr[lineoffset + x] = color

ENDSUB

SUB render()

    INTEGER tick

    REM Lock surface if needed
    IF SDL_MUSTLOCK(screen) THEN
        CALL SDL_LockSurface(screen)
    ENDIF

    REM Ask SDL for the time in milliseconds
    LET tick = SDL_GetTicks()

    REM Declare a couple of variables
    DECLARE i, j, yofs, ofs TYPE int

    REM Draw to screen
    LET yofs = 0
    FOR i = 0 TO 478
	LET ofs = yofs
	FOR j = 0 TO 638
	    INCR ofs
	    LET ((unsigned int*)screen->pixels)[ofs] = i * i + j * j + tick
	NEXT
	INCR yofs, screen->pitch / 4
    NEXT

    CALL putpixel(10, 10, 0xff0000)
    CALL putpixel(11, 10, 0xff0000)
    CALL putpixel(10, 11, 0xff0000)
    CALL putpixel(11, 11, 0xff0000)

    REM Unlock if needed
    IF SDL_MUSTLOCK(screen) THEN
        CALL SDL_UnlockSurface(screen)
    ENDIF

    REM Tell SDL to update the whole screen
    CALL SDL_UpdateRect(screen, 0, 0, 640, 480)

ENDSUB

REM Initialize SDL's subsystems - in this case, only video.
IF SDL_Init(SDL_INIT_VIDEO) < 0 THEN
    PRINT "Unable to init SDL: ", SDL_GetError() FORMAT "%s%s\n"
    END 1
ENDIF

REM Attempt to create a 640x480 window with 32bit pixels.
LET screen = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE)

REM If we fail, return error.
IF screen == NULL THEN
    PRINT "Unable to set 640x480 video: ", SDL_GetError() FORMAT "%s%s\n"
    END 1
ENDIF

REM Main loop: loop forever.
WHILE TRUE

    REM Render stuff
    CALL render()

    DECLARE event TYPE SDL_Event

    REM Poll for events, and handle the ones we care about.
    WHILE SDL_PollEvent(&event) 

	IF event.type == SDL_KEYUP THEN
	    REM If escape is pressed, return (and thus, quit)
	    IF event.key.keysym.sym == SDLK_ESCAPE THEN
                END
	    ELIF event.key.keysym.sym == SDL_QUIT THEN
		END
	    ENDIF
        ENDIF
    WEND
WEND

Return to M4BASIC