]> git.jsancho.org Git - gacela.git/blob - src/video.scm
a9db7be0b7e03dce39f93e0c0bb611acbd9331a9
[gacela.git] / src / video.scm
1 ;;; Gacela, a GNU Guile extension for fast games development
2 ;;; Copyright (C) 2009 by Javier Sancho Fernandez <jsf at jsancho dot org>
3 ;;;
4 ;;; This program is free software: you can redistribute it and/or modify
5 ;;; it under the terms of the GNU General Public License as published by
6 ;;; the Free Software Foundation, either version 3 of the License, or
7 ;;; (at your option) any later version.
8 ;;;
9 ;;; This program is distributed in the hope that it will be useful,
10 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
11 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 ;;; GNU General Public License for more details.
13 ;;;
14 ;;; You should have received a copy of the GNU General Public License
15 ;;; along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
17
18 (define-module (gacela video)
19   #:use-module (gacela sdl)
20   #:use-module (gacela gl)
21   #:use-module (gacela ftgl)
22   #:use-module (gacela math)
23   #:use-module (gacela utils)
24   #:use-module (ice-9 optargs)
25   #:use-module (ice-9 receive)
26   #:export (init-video
27             get-screen-height
28             get-screen-width
29             get-screen-bpp
30             set-screen-bpp!
31             resize-screen
32             quit-video
33             clear-screen
34             flip-screen
35             set-screen-title!
36             get-screen-title
37             set-2d-mode
38             set-3d-mode
39             3d-mode?
40             get-frames-per-second
41             set-frames-per-second!
42             get-fullscreen
43             set-fullscreen!
44             init-frame-time
45             get-frame-time
46             delay-frame
47             get-current-color
48             set-current-color
49             with-color
50             progn-textures
51             draw
52             load-texture
53             load-texture-without-cache
54             get-texture-properties
55             draw-texture
56             draw-line
57             draw-quad
58             draw-rectangle
59             draw-square
60             draw-cube
61             translate
62             rotate
63             to-origin
64             add-light
65             set-camera
66             camera-look
67             load-font
68             load-font-without-texture
69             render-text)
70   #:re-export (glPushMatrix
71                glPopMatrix)
72   #:export-syntax (glmatrix-block))
73
74
75
76 ;;; Screen
77
78 (define screen #f)
79 (define flags 0)
80
81 (define* (init-video width height bpp #:key (mode '2d) (title "") (fps 20) (fullscreen 'off))
82   (SDL_Init SDL_INIT_VIDEO)
83   (let ((info (SDL_GetVideoInfo)))
84     (SDL_GL_SetAttribute SDL_GL_DOUBLEBUFFER 1)
85     (set! flags (+ SDL_OPENGL SDL_GL_DOUBLEBUFFER SDL_HWPALETTE SDL_RESIZABLE
86                    (if (= (assoc-ref info 'hw_available) 0) SDL_SWSURFACE SDL_HWSURFACE)
87                    (if (= (assoc-ref info 'blit_hw) 0) 0 SDL_HWACCEL)
88                    (if (eq? fullscreen 'on) SDL_FULLSCREEN 0)))
89     (set! screen (SDL_SetVideoMode width height bpp flags))
90     (set-screen-title! title)
91     (set-frames-per-second! fps)
92     (set-fullscreen! fullscreen #f)
93     (init-gl)
94     (if (eq? mode '3d) (set-3d-mode) (set-2d-mode))))
95
96 (define (get-screen-height)
97   (surface-h screen))
98
99 (define (get-screen-width)
100   (surface-w screen))
101
102 (define (get-screen-bpp)
103   (* (surface-format-BytesPerPixel screen) 8))
104
105 (define (set-screen-bpp! bpp)
106   (cond (screen
107          (set! screen (SDL_SetVideoMode (get-screen-width) (get-screen-height) (get-screen-bpp) flags)))))
108
109 (define (resize-screen width height)
110   (cond (screen
111          (set! screen (SDL_SetVideoMode width height (get-screen-bpp) flags))
112          (resize-screen-GL width height))))
113
114 (define (quit-video)
115   (cond (screen
116          (SDL_FreeSurface screen)
117          (set! screen #f)
118          (SDL_Quit))))
119
120 (define (clear-screen)
121   (glClear (+ GL_COLOR_BUFFER_BIT GL_DEPTH_BUFFER_BIT)))
122
123 (define (flip-screen)
124   (SDL_GL_SwapBuffers))
125
126
127 (define screen-title "")
128
129 (define (set-screen-title! title)
130   (set! screen-title title)
131   (SDL_WM_SetCaption title ""))
132
133 (define (get-screen-title)
134   screen-title)
135
136
137 (define mode '2d)
138
139 (define (set-2d-mode)
140   (set! mode '2d)
141   (glDisable GL_DEPTH_TEST)
142   (resize-screen-GL (get-screen-width) (get-screen-height)))
143
144 (define (set-3d-mode)
145   (set! mode '3d)
146   (glClearDepth 1)
147   (glEnable GL_DEPTH_TEST)
148   (glDepthFunc GL_LEQUAL)
149   (resize-screen-GL (get-screen-width) (get-screen-height)))
150
151 (define (3d-mode?)
152   (eq? mode '3d))
153
154
155 (define fullscreen 'off)
156
157 (define* (set-fullscreen! fs #:optional (toggle #t))
158   (cond ((or (and (eq? fullscreen 'on) (eq? fs 'off))
159              (and (eq? fullscreen 'off) (eq? fs 'on)))
160          (set! fullscreen fs)
161          (cond (toggle
162                 (SDL_WM_ToggleFullScreen screen))))))
163
164 (define (get-fullscreen)
165   fullscreen)
166
167
168 (define (init-gl)
169   (glShadeModel GL_SMOOTH)
170   (glClearColor 0 0 0 0)
171   (glEnable GL_BLEND)
172   (glBlendFunc GL_SRC_ALPHA GL_ONE_MINUS_SRC_ALPHA)
173   (glHint GL_PERSPECTIVE_CORRECTION_HINT GL_NICEST))
174
175 (define (resize-screen-GL width height)
176   (glViewport 0 0 width height)
177   (glMatrixMode GL_PROJECTION)
178   (glLoadIdentity)
179   (cond ((3d-mode?)
180          (let ((ratio (if (= height 0) width (/ width height))))
181            (gluPerspective 45 ratio 0.1 100)))
182         (else
183          (let* ((w (/ width 2)) (h (/ height 2)))
184            (glOrtho (- w) w (- h) h 0 1))))
185   (glMatrixMode GL_MODELVIEW)
186   (glLoadIdentity))
187
188
189 ;;; Frames per second
190
191 (define time 0)
192 (define frames-per-second 20)
193 (define time-per-frame 50)   ;in ms
194
195 (define (get-frames-per-second)
196   frames-per-second)
197
198 (define (set-frames-per-second! fps)
199   (set! frames-per-second fps)
200   (set! time-per-frame (/ 1000.0 fps)))
201
202 (define (init-frame-time)
203   (set! time (SDL_GetTicks)))
204
205 (define (get-frame-time)
206   time)
207
208 (define (delay-frame)
209   (let ((frame-time (- (SDL_GetTicks) time)))
210     (cond ((< frame-time time-per-frame)
211            (SDL_Delay (- time-per-frame frame-time))))))
212
213
214 ;;; Drawing
215
216 (define current-color '(1 1 1 1))
217
218 (define (get-current-color)
219   current-color)
220
221 (define* (set-current-color red green blue #:optional (alpha 1))
222   (set! current-color (list red green blue alpha))
223   (glColor4f red green blue alpha))
224
225 (define-macro (with-color color . code)
226   (cond (color
227          `(let ((original-color (get-current-color))
228                 (result #f))
229             (apply set-current-color ,color)
230             (set! result (begin ,@code))
231             (apply set-current-color original-color)
232             result))
233         (else `(begin ,@code))))
234
235 (define-macro (progn-textures . code)
236   `(let ((result #f))
237      (glEnable GL_TEXTURE_2D)
238      (set! result (begin ,@code))
239      (glDisable GL_TEXTURE_2D)
240      result))
241
242 (define (draw . vertexes)
243   (begin-draw (length vertexes))
244   (draw-vertexes vertexes)
245   (glEnd))
246
247 (define (begin-draw number-of-points)
248   (cond ((= number-of-points 2) (glBegin GL_LINES))
249         ((= number-of-points 3) (glBegin GL_TRIANGLES))
250         ((= number-of-points 4) (glBegin GL_QUADS))))
251
252 (define (draw-vertexes vertexes)
253   (cond ((not (null? vertexes))
254          (draw-vertex (car vertexes))
255          (draw-vertexes (cdr vertexes)))))
256
257 (define* (draw-vertex vertex #:key texture-coord)
258   (cond ((list? (car vertex))
259          (with-color (car vertex)
260                      (apply simple-draw-vertex (cadr vertex))))
261         (else
262          (cond (texture-coord (apply glTexCoord2f texture-coord)))
263          (apply simple-draw-vertex vertex))))
264
265 (define* (simple-draw-vertex x y #:optional (z 0))
266   (cond ((3d-mode?) (glVertex3f x y z))
267         (else (glVertex2f x y))))
268
269 (define (load-image filename)
270   (let ((image (IMG_Load filename)))
271     (cond (image
272            (SDL_DisplayFormatAlpha image)))))
273   
274 (define (load-image-for-texture filename)
275   (let ((image (load-image filename)))
276     (cond (image
277            (let* ((width (surface-w image)) (height (surface-h image))
278                   (power-2 (nearest-power-of-two (min width height)))
279                   (resized-image #f))
280              (cond ((and (= width power-2) (= height power-2)) (values image width height))
281                    (else (set! resized-image (resize-surface image power-2 power-2))
282                          (if resized-image (values resized-image width height))))))
283           (else
284            (values #f 0 0)))))
285
286 (define (resize-surface surface width height)
287   (let ((old-width (surface-w surface)) (old-height (surface-h surface)))
288     (cond ((and (= width old-width) (= height old-height)) surface)
289           (else (let ((zoomx (/ (+ width 0.5) old-width)) (zoomy (/ (+ height 0.5) old-height)))
290                (zoomSurface surface zoomx zoomy 0))))))
291
292 (define* (load-texture-without-cache filename #:key (min-filter GL_LINEAR) (mag-filter GL_LINEAR))
293   (progn-textures
294    (receive
295     (image real-w real-h) (load-image-for-texture filename)
296     (cond (image
297            (let ((width (surface-w image)) (height (surface-h image))
298                  (byteorder (if (= SDL_BYTEORDER SDL_LIL_ENDIAN)
299                                 (if (= (surface-format-BytesPerPixel image) 3) GL_BGR GL_BGRA)
300                                 (if (= (surface-format-BytesPerPixel image) 3) GL_RGB GL_RGBA)))
301                  (texture (car (glGenTextures 1))))
302
303              (glBindTexture GL_TEXTURE_2D texture)
304              (glTexImage2D GL_TEXTURE_2D 0 4 width height 0 byteorder GL_UNSIGNED_BYTE (surface-pixels image))
305              (glTexParameteri GL_TEXTURE_2D GL_TEXTURE_MIN_FILTER min-filter)
306              (glTexParameteri GL_TEXTURE_2D GL_TEXTURE_MAG_FILTER mag-filter)
307              (set-texture-size! texture real-w real-h)
308              texture))))))
309
310 (define load-texture (use-cache-with load-texture-without-cache))
311
312 (define (get-texture-properties texture)
313   `((width . ,(texture-w texture)) (height . ,(texture-h texture))))
314
315 (define* (draw-texture texture #:key (zoom 1) (sprite '((0 0) (1 1))))
316   (cond (texture
317          (let ((width (texture-w texture))
318                (height (texture-h texture)))
319            (draw-rectangle (* zoom width (- (caadr sprite) (caar sprite)))
320                            (* zoom height (- (cadadr sprite) (cadar sprite)))
321                            #:texture texture
322                            #:texture-coord sprite)))))
323
324 (define* (draw-line length #:optional color)
325   (let ((l (/ length 2)))
326     (cond (color
327            (with-color color (draw (list 0 l) (list 0 (- l)))))
328           (else
329            (draw (list 0 l) (list 0 (- l)))))))
330
331 (define* (draw-quad v1 v2 v3 v4 #:key texture color (texture-coord '((0 0) (1 1))))
332   (cond (texture
333          (progn-textures
334           (glBindTexture GL_TEXTURE_2D texture)
335           (begin-draw 4)
336           (draw-vertex v1 #:texture-coord (car texture-coord))
337           (draw-vertex v2 #:texture-coord (list (caadr texture-coord) (cadar texture-coord)))
338           (draw-vertex v3 #:texture-coord (cadr texture-coord))
339           (draw-vertex v4 #:texture-coord (list (caar texture-coord) (cadadr texture-coord)))
340           (glEnd)))
341         (color
342          (with-color color (draw v1 v2 v3 v4)))
343         (else
344          (draw v1 v2 v3 v4))))
345
346 (define* (draw-rectangle width height #:key texture color texture-coord)
347   (let ((w (/ width 2)) (h (/ height 2)))
348     (draw-quad (list (- w) h 0)
349                (list w h 0)
350                (list w (- h) 0)
351                (list (- w) (- h) 0)
352                #:texture texture
353                #:texture-coord texture-coord
354                #:color color)))
355
356 (define* (draw-square size #:key texture color)
357   (draw-rectangle size size #:texture texture #:color color))
358
359 (define* (draw-cube #:key (size 1)
360                    texture texture-1 texture-2 texture-3 texture-4 texture-5 texture-6
361                    color color-1 color-2 color-3 color-4 color-5 color-6)
362   (let ((-size (- size)))
363     (progn-textures
364      (glNormal3f 0 0 1)
365      (draw-quad (list -size size size) (list size size size) (list size -size size) (list -size -size size) #:texture (or texture-1 texture) #:color (or color-1 color))
366      (glNormal3f 0 0 -1)
367      (draw-quad (list -size -size -size) (list size -size -size) (list size size -size) (list -size size -size) #:texture (or texture-2 texture) #:color (or color-2 color))
368      (glNormal3f 0 1 0)
369      (draw-quad (list size size size) (list -size size size) (list -size size -size) (list size size -size) #:texture (or texture-3 texture) #:color (or color-3 color))
370      (glNormal3f 0 -1 0)
371      (draw-quad (list -size -size size) (list size -size size) (list size -size -size) (list -size -size -size) #:texture (or texture-4 texture) #:color (or color-4 color))
372      (glNormal3f 1 0 0)
373      (draw-quad (list size -size -size) (list size -size size) (list size size size) (list size size -size) #:texture (or texture-5 texture) #:color (or color-5 color))
374      (glNormal3f -1 0 0)
375      (draw-quad (list -size -size size) (list -size -size -size) (list -size size -size) (list -size size size) #:texture (or texture-6 texture) #:color (or color-6 color)))))
376
377 (define* (gtranslate x y #:optional (z 0))
378   (glTranslatef x y z))
379
380 (define (grotate . rot)
381   (cond ((3d-mode?)
382          (apply 3d-rotate rot))
383         (else
384          (2d-rotate (car (last-pair rot))))))
385
386 (define (3d-rotate xrot yrot zrot)
387   (glRotatef xrot 1 0 0)
388   (glRotatef yrot 0 1 0)
389   (glRotatef zrot 0 0 1))
390
391 (define (2d-rotate rot)
392   (glRotatef rot 0 0 1))
393
394 (define (to-origin)
395   (glLoadIdentity)
396   (cond ((3d-mode?) (camera-look))))
397
398 (define-macro (glmatrix-block . code)
399   `(let ((result #f))
400      (glPushMatrix)
401      (set! result (begin ,@code))
402      (glPopMatrix)
403      result))
404
405
406 ;;; Lights
407
408 ;; (define* (add-light #:key light position ambient (id GL_LIGHT1) (turn-on t))
409 ;;   (init-lighting)
410 ;;   (and light (glLightfv id GL_DIFFUSE (car light) (cadr light) (caddr light) (cadddr light)))
411 ;;   (and light position (glLightfv GL_POSITION (car position) (cadr position) (caddr position) (cadddr position)))
412 ;;   (and ambient (glLightfv id GL_AMBIENT (car ambient) (cadr ambient) (caddr ambient) (cadddr ambient)))
413 ;;   (and turn-on (glEnable id))
414 ;;   id)
415
416
417 ;;; Camera
418
419 (define camera-eye '(0 0 0))
420 (define camera-center '(0 0 -100))
421 (define camera-up '(0 1 0))
422
423 (define* (set-camera #:key eye center up)
424   (cond (eye (set! camera-eye eye)))
425   (cond (center (set! camera-center center)))
426   (cond (up (set! camera-up up))))
427
428 (define (camera-look)
429   (apply gluLookAt (append camera-eye camera-center camera-up)))
430
431
432 ;;; Text and fonts
433
434 (define* (load-font-without-cache font-file #:key (size 40) (encoding ft_encoding_unicode))
435   (let ((font (ftglCreateTextureFont font-file size)))
436     (ftglSetFontFaceSize font size 72)
437     (ftglSetFontCharMap font encoding)
438     font))
439
440 (define load-font (use-cache-with load-font-without-cache))
441
442 (define* (render-text text font #:key (size #f))
443   (cond (size
444          (cond ((not (= (ftglGetFontFaceSize font) size))
445                 (ftglSetFontFaceSize font size 72))))
446         ((not (= (ftglGetFontFaceSize font) (font-size font)))
447          (ftglSetFontFaceSize font (font-size font) 72)))
448   (ftglRenderFont font text FTGL_RENDER_ALL))
449
450
451 ;;; Meshes
452
453 (define mesh-type
454   (make-record-type "mesh" 
455                     '(draw translate turn rotate inner-properties inner-property properties properties-set! property property-set!)
456                     (lambda (record port)
457                       (format port "#<mesh: ~a" (mesh-inner-property record 'type))
458                       (for-each (lambda (x) (format port " ~a" x))
459                                 (mesh-properties record))
460                       (display ">" port))))
461
462 (define mesh? (record-predicate mesh-type))
463
464 (define* (make-mesh type proc)
465   (apply
466    (record-constructor mesh-type)
467    (let ((px 0) (py 0) (pz 0)
468          (ax 0) (ay 0) (az 0)
469          (rx 0) (ry 0) (rz 0)
470          (properties '()))
471      (let ((inner-properties
472             (lambda ()
473               `((type . ,type) (x . ,px) (y . ,py) (z . ,pz) (ax . ,ax) (ay . ,ay) (az . ,az) (rx . ,rx) (ry . ,ry) (rz . ,rz)))))
474        (list
475         (lambda ()
476           "draw"
477           (glmatrix-block
478            (grotate ax ay az)
479            (gtranslate px py pz)
480            (grotate rx ry rz)
481            (proc properties)))
482         (lambda (x y z)
483           "translate"
484           (set! px (+ px x))
485           (set! py (+ py y))
486           (set! pz (+ pz z)))
487         (lambda (x y z)
488           "turn"
489           (set! ax (+ ax x))
490           (set! ay (+ ay y))
491           (set! az (+ az z)))
492         (lambda (x y z)
493           "rotate"
494           (set! rx (+ rx x))
495           (set! ry (+ ry y))
496           (set! rz (+ rz z)))
497         (lambda ()
498           "inner-properties"
499           (inner-properties))
500         (lambda (prop-name)
501           "inner-property"
502           (assoc-ref (inner-properties) prop-name))
503         (lambda ()
504           "properties"
505           properties)
506         (lambda (new-properties)
507           "properties-set!"
508           (set! properties new-properties))
509         (lambda (prop-name)
510           "property"
511           (assoc-ref properties prop-name))
512         (lambda (prop-name value)
513           "property-set!"
514           (set! properties (assoc-set! properties prop-name value))))))))
515
516 (define (mesh-draw mesh)
517   (((record-accessor mesh-type 'draw) mesh)))
518
519 (define (mesh-inner-properties mesh)
520   (((record-accessor mesh-type 'inner-properties) mesh)))
521
522 (define (mesh-inner-property mesh prop-name)
523   (((record-accessor mesh-type 'inner-property) mesh) prop-name))
524
525 (define (mesh-properties mesh)
526   (((record-accessor mesh-type 'properties) mesh)))
527
528 (define (mesh-properties-set! mesh new-properties)
529   (((record-accessor mesh-type 'properties-set!) mesh) new-properties))
530
531 (define (mesh-property mesh prop-name)
532   (((record-accessor mesh-type 'property) mesh) prop-name))
533
534 (define (mesh-property-set! mesh prop-name value)
535   (((record-accessor mesh-type 'property-set!) mesh) prop-name value))
536
537 (define* (translate mesh x y #:optional (z 0))
538   (((record-accessor mesh-type 'translate) mesh) x y z)
539   mesh)
540
541 (define (turn mesh . params)
542   (apply ((record-accessor mesh-type 'turn) mesh)
543          (if (>= (length params) 3)
544              params
545              (list 0 0 (car params))))
546   mesh)
547
548 (define (rotate mesh . params)
549   (apply ((record-accessor mesh-type 'rotate) mesh)
550          (if (>= (length params) 3)
551              params
552              (list 0 0 (car params))))
553   mesh)
554
555
556 ;;; Advanced meshes
557
558 (define (mesh-join . meshes)
559   (make-mesh
560    'joined-meshes
561    (lambda (props)
562      (for-each (lambda (m) (glmatrix-block (mesh-draw m))) meshes))))
563
564
565 ;;; Primitives
566
567 (define-macro (primitive header . body)
568   (let* ((type (car header))
569          (args (cdr header))
570          (list-args (names-arguments args)))
571     `(lambda* ,args
572        (let ((m (make-mesh
573                  ',type
574                  (lambda (props)
575                    (apply (lambda* ,(cons #:key list-args) ,@body)
576                           (list
577                            ,@(let get-params ((l list-args))
578                                (cond ((null? l) '())
579                                      (else
580                                       (cons (symbol->keyword (car l))
581                                             (cons `(assoc-ref props ',(car l))
582                                                   (get-params (cdr l)))))))))))))
583          (mesh-properties-set! m (list ,@(map (lambda (a) `(cons ',a ,a)) list-args)))
584          m))))
585
586 (define-macro (define-primitive header . body)
587   `(define ,(car header) (primitive ,header ,@body)))
588
589
590 ;;; Primitives definition
591
592 (define-primitive (square size #:key texture color)
593   (draw-square size #:texture texture #:color color))
594
595 (define-primitive (rectangle width height #:key texture color texture-coord)
596   (draw-rectangle width height #:texture texture #:color color #:texture-coord texture-coord))
597
598 (define-primitive (picture filename #:key (min-filter GL_LINEAR) (mag-filter GL_LINEAR) (zoom 1) (sprite '((0 0) (1 1))))
599   (draw-texture (load-texture filename #:min-filter min-filter #:mag-filter mag-filter) #:zoom zoom #:sprite sprite))
600
601
602 (module-map (lambda (sym var)
603               (if (not (eq? sym '%module-public-interface))
604                   (module-export! (current-module) (list sym))))
605             (current-module))