]> git.jsancho.org Git - gacela.git/blob - src/video.scm
c01341243a3d94a1e00772d2ea2b584634ea9932
[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 (figl gl)
22   #:use-module (figl glu)
23   #:use-module (gacela ftgl)
24   #:use-module (gacela math)
25   #:use-module (gacela utils)
26   #:use-module (ice-9 optargs)
27   #:use-module (ice-9 receive)
28   #:export (init-video
29             get-screen-height
30             get-screen-width
31             get-screen-bpp
32             set-screen-bpp!
33             resize-screen
34             quit-video
35             clear-screen
36             flip-screen
37             set-screen-title!
38             get-screen-title
39             set-2d-mode
40             set-3d-mode
41             3d-mode?
42             get-frames-per-second
43             set-frames-per-second!
44             get-fullscreen
45             set-fullscreen!
46             init-frame-time
47             get-frame-time
48             delay-frame
49             get-current-color
50             set-current-color
51             with-color
52             begin-textures
53             draw
54             load-texture
55             load-texture-without-cache
56             get-texture-properties
57             draw-texture
58             draw-line
59             draw-quad
60             draw-rectangle
61             draw-square
62             draw-cube
63             translate
64             rotate
65             to-origin
66             add-light
67             set-camera
68             camera-look
69             load-font
70             load-font-without-texture
71             render-text)
72   #:re-export (with-gl-push-matrix))
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   (gl-clear (clear-buffer-mask color-buffer depth-buffer)))
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   (gl-disable (enable-cap depth-test))
142   (resize-screen-GL (get-screen-width) (get-screen-height)))
143
144 (define (set-3d-mode)
145   (set! mode '3d)
146   (set-gl-clear-depth 1)
147   (gl-enable (enable-cap depth-test))
148   (set-gl-depth-function (depth-function 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   (set-gl-shade-model (shading-model smooth))
170   (set-gl-clear-color 0 0 0 0)
171   (gl-enable (enable-cap blend))
172   (set-gl-blend-function (blending-factor-dest src-alpha) (blending-factor-dest one-minus-src-alpha))
173   (set-gl-hint (hint-target perspective-correction-hint) (hint-mode nicest)))
174
175 (define (resize-screen-GL width height)
176   (gl-viewport 0 0 width height)
177   (set-gl-matrix-mode (matrix-mode projection))
178   (gl-load-identity)
179   (cond ((3d-mode?)
180          (let ((ratio (if (= height 0) width (/ width height))))
181            (glu-perspective 45 ratio 0.1 100)))
182         (else
183          (let* ((w (/ width 2)) (h (/ height 2)))
184            (gl-ortho (- w) w (- h) h 0 1))))
185   (set-gl-matrix-mode (matrix-mode modelview))
186   (gl-load-identity))
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   (gl-color 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 (begin-textures . code)
236   `(let ((result #f))
237      (gl-enable (oes-framebuffer-object texture-2d))
238      (set! result (begin ,@code))
239      (gl-disable (oes-framebuffer-object texture-2d))
240      result))
241
242 (define (draw . vertexes)
243   (gl-begin
244    (let ((number-of-points (length vertexes)))
245      (cond ((= number-of-points 2) (begin-mode lines))
246            ((= number-of-points 3) (begin-mode triangles))
247            ((= number-of-points 4) (begin-mode quads))
248            ((> number-of-points 4) (begin-mode polygon))))
249    (draw-vertexes vertexes)))
250
251 (define (draw-vertexes vertexes)
252   (cond ((not (null? vertexes))
253          (apply draw-vertex (if (list? (caar vertexes)) (car vertexes) (list (car vertexes))))
254          (draw-vertexes (cdr vertexes)))))
255
256 (define* (draw-vertex vertex #:key texture-coord)
257   (cond (texture-coord (apply glTexCoord2f texture-coord)))
258   (apply gl-vertex vertex))
259
260 (define (load-image filename)
261   (let ((image (IMG_Load filename)))
262     (cond (image
263            (SDL_DisplayFormatAlpha image)))))
264   
265 (define (load-image-for-texture filename)
266   (let ((image (load-image filename)))
267     (cond (image
268            (let* ((width (surface-w image)) (height (surface-h image))
269                   (power-2 (nearest-power-of-two (min width height)))
270                   (resized-image #f))
271              (cond ((and (= width power-2) (= height power-2)) (values image width height))
272                    (else (set! resized-image (resize-surface image power-2 power-2))
273                          (if resized-image (values resized-image width height))))))
274           (else
275            (values #f 0 0)))))
276
277 (define (resize-surface surface width height)
278   (let ((old-width (surface-w surface)) (old-height (surface-h surface)))
279     (cond ((and (= width old-width) (= height old-height)) surface)
280           (else (let ((zoomx (/ (+ width 0.5) old-width)) (zoomy (/ (+ height 0.5) old-height)))
281                (zoomSurface surface zoomx zoomy 0))))))
282
283 (define* (load-texture-without-cache filename #:key (min-filter (texture-min-filter linear)) (mag-filter (texture-mag-filter linear)))
284   (begin-textures
285    (receive
286     (image real-w real-h) (load-image-for-texture filename)
287     (cond (image
288            (let ((width (surface-w image)) (height (surface-h image))
289                  (byteorder (if (= SDL_BYTEORDER SDL_LIL_ENDIAN)
290                                 (if (= (surface-format-BytesPerPixel image) 3) (ext-bgra bgr-ext) (ext-bgra bgra-ext))
291                                 (if (= (surface-format-BytesPerPixel image) 3) (pixel-format rgb) (pixel-format rgba))))
292                  (texture (car (glGenTextures 1))))
293
294              (glBindTexture (oes-framebuffer-object texture-2d) texture)
295              (glTexImage2D (oes-framebuffer-object texture-2d) 0 4 width height 0 byteorder (data-type unsigned-byte) (surface-pixels image))
296              (glTexParameteri (oes-framebuffer-object texture-2d) (texture-parameter-name texture-min-filter) min-filter)
297              (glTexParameteri (oes-framebuffer-object texture-2d) (texture-parameter-name texture-mag-filter) mag-filter)
298              (set-texture-size! texture real-w real-h)
299              texture))))))
300
301 (define load-texture (use-cache-with load-texture-without-cache))
302
303 (define (get-texture-properties texture)
304   `((width . ,(texture-w texture)) (height . ,(texture-h texture))))
305
306 (define* (draw-texture texture #:key (zoom 1) (sprite '((0 0) (1 1))))
307   (cond (texture
308          (let ((width (texture-w texture))
309                (height (texture-h texture)))
310            (draw-rectangle (* zoom width (- (caadr sprite) (caar sprite)))
311                            (* zoom height (- (cadadr sprite) (cadar sprite)))
312                            #:texture texture
313                            #:texture-coord sprite)))))
314
315 (define* (draw-line length)
316   (let ((l (/ length 2)))
317     (draw (list 0 l) (list 0 (- l)))))
318
319 (define (draw-circle radius)
320   (gl-begin
321    (begin-mode polygon)
322    (do ((i 0 (1+ i)))
323        ((>= i 360))
324      (let ((a (degrees-to-radians i)))
325        (draw-vertex (list (* radius (cos a)) (* radius (sin a))))))))
326
327 (define* (draw-quad v1 v2 v3 v4 #:key texture (texture-coord '((0 0) (1 1))))
328   (cond (texture
329          (begin-textures
330           (glBindTexture (oes-framebuffer-object texture-2d) texture)
331           (draw (list v1 #:texture-coord (car texture-coord))
332                 (list v2 #:texture-coord (list (caadr texture-coord) (cadar texture-coord)))
333                 (list v3 #:texture-coord (cadr texture-coord))
334                 (list v4 #:texture-coord (list (caar texture-coord) (cadadr texture-coord))))))
335         (else
336          (draw v1 v2 v3 v4))))
337
338 (define* (draw-rectangle width height #:key texture texture-coord)
339   (let ((w (/ width 2)) (h (/ height 2)))
340     (draw-quad (list (- w) h 0)
341                (list w h 0)
342                (list w (- h) 0)
343                (list (- w) (- h) 0)
344                #:texture texture
345                #:texture-coord texture-coord)))
346
347 (define* (draw-square size #:key texture)
348   (draw-rectangle size size #:texture texture))
349
350 (define* (draw-cube #:key (size 1)
351                    texture texture-1 texture-2 texture-3 texture-4 texture-5 texture-6
352                    color-1 color-2 color-3 color-4 color-5 color-6)
353   (let ((-size (- size)))
354     (begin-textures
355      (gl-normal 0 0 1)
356      (with-color color-1 (draw-quad (list -size size size) (list size size size) (list size -size size) (list -size -size size) #:texture (or texture-1 texture)))
357      (gl-normal 0 0 -1)
358      (with-color color-2 (draw-quad (list -size -size -size) (list size -size -size) (list size size -size) (list -size size -size) #:texture (or texture-2 texture)))
359      (gl-normal 0 1 0)
360      (with-color color-3 (draw-quad (list size size size) (list -size size size) (list -size size -size) (list size size -size) #:texture (or texture-3 texture)))
361      (gl-normal 0 -1 0)
362      (with-color color-4 (draw-quad (list -size -size size) (list size -size size) (list size -size -size) (list -size -size -size) #:texture (or texture-4 texture)))
363      (gl-normal 1 0 0)
364      (with-color color-5 (draw-quad (list size -size -size) (list size -size size) (list size size size) (list size size -size) #:texture (or texture-5 texture)))
365      (gl-normal -1 0 0)
366      (with-color color-6 (draw-quad (list -size -size size) (list -size -size -size) (list -size size -size) (list -size size size) #:texture (or texture-6 texture))))))
367
368 (define* (gtranslate x y #:optional (z 0))
369   (gl-translate x y z))
370
371 (define (grotate . rot)
372   (cond ((3d-mode?)
373          (apply 3d-rotate rot))
374         (else
375          (2d-rotate (car (last-pair rot))))))
376
377 (define (3d-rotate xrot yrot zrot)
378   (gl-rotate xrot 1 0 0)
379   (gl-rotate yrot 0 1 0)
380   (gl-rotate zrot 0 0 1))
381
382 (define (2d-rotate rot)
383   (gl-rotate rot 0 0 1))
384
385 (define (to-origin)
386   (gl-load-identity)
387   (cond ((3d-mode?) (camera-look))))
388
389
390 ;;; Lights
391
392 ;; (define* (add-light #:key light position ambient (id GL_LIGHT1) (turn-on t))
393 ;;   (init-lighting)
394 ;;   (and light (glLightfv id GL_DIFFUSE (car light) (cadr light) (caddr light) (cadddr light)))
395 ;;   (and light position (glLightfv GL_POSITION (car position) (cadr position) (caddr position) (cadddr position)))
396 ;;   (and ambient (glLightfv id GL_AMBIENT (car ambient) (cadr ambient) (caddr ambient) (cadddr ambient)))
397 ;;   (and turn-on (gl-enable id))
398 ;;   id)
399
400
401 ;;; Camera
402
403 (define camera-eye '(0 0 0))
404 (define camera-center '(0 0 -100))
405 (define camera-up '(0 1 0))
406
407 (define* (set-camera #:key eye center up)
408   (cond (eye (set! camera-eye eye)))
409   (cond (center (set! camera-center center)))
410   (cond (up (set! camera-up up))))
411
412 (define (camera-look)
413   (apply glu-look-at (append camera-eye camera-center camera-up)))
414
415
416 ;;; Text and fonts
417
418 (define* (load-font-without-cache font-file #:key (size 40) (encoding ft_encoding_unicode))
419   (let ((font (ftglCreateTextureFont font-file size)))
420     (ftglSetFontFaceSize font size 72)
421     (ftglSetFontCharMap font encoding)
422     font))
423
424 (define load-font (use-cache-with load-font-without-cache))
425
426 (define* (render-text text font #:key (size #f))
427   (cond (size
428          (cond ((not (= (ftglGetFontFaceSize font) size))
429                 (ftglSetFontFaceSize font size 72))))
430         ((not (= (ftglGetFontFaceSize font) (font-size font)))
431          (ftglSetFontFaceSize font (font-size font) 72)))
432   (ftglRenderFont font text FTGL_RENDER_ALL))
433
434
435 ;;; Meshes
436
437 (define mesh-type
438   (make-record-type "mesh" 
439                     '(draw translate turn rotate color inner-properties inner-property properties properties-set! property property-set!)
440                     (lambda (record port)
441                       (format port "#<mesh: ~a" (mesh-inner-property record 'type))
442                       (for-each (lambda (x) (format port " ~a" x))
443                                 (mesh-properties record))
444                       (display ">" port))))
445
446 (define mesh? (record-predicate mesh-type))
447
448 (define* (make-mesh type proc)
449   (apply
450    (record-constructor mesh-type)
451    (let ((px 0) (py 0) (pz 0)
452          (ax 0) (ay 0) (az 0)
453          (rx 0) (ry 0) (rz 0)
454          (color #f)
455          (properties '()))
456      (let ((inner-properties
457             (lambda ()
458               `((type . ,type) (color . ,color)
459                 (x . ,px) (y . ,py) (z . ,pz)
460                 (ax . ,ax) (ay . ,ay) (az . ,az)
461                 (rx . ,rx) (ry . ,ry) (rz . ,rz)))))
462        (list
463         (lambda ()
464           "draw"
465           (with-gl-push-matrix
466            (grotate ax ay az)
467            (gtranslate px py pz)
468            (grotate rx ry rz)
469            (with-color color (proc properties))))
470         (lambda (x y z)
471           "translate"
472           (set! px (+ px x))
473           (set! py (+ py y))
474           (set! pz (+ pz z)))
475         (lambda (x y z)
476           "turn"
477           (set! ax (+ ax x))
478           (set! ay (+ ay y))
479           (set! az (+ az z)))
480         (lambda (x y z)
481           "rotate"
482           (set! rx (+ rx x))
483           (set! ry (+ ry y))
484           (set! rz (+ rz z)))
485         (lambda (c)
486           "color"
487           (set! color c))
488         (lambda ()
489           "inner-properties"
490           (inner-properties))
491         (lambda (prop-name)
492           "inner-property"
493           (assoc-ref (inner-properties) prop-name))
494         (lambda ()
495           "properties"
496           properties)
497         (lambda (new-properties)
498           "properties-set!"
499           (set! properties new-properties))
500         (lambda (prop-name)
501           "property"
502           (assoc-ref properties prop-name))
503         (lambda (prop-name value)
504           "property-set!"
505           (set! properties (assoc-set! properties prop-name value))))))))
506
507 (define (mesh-draw mesh)
508   (((record-accessor mesh-type 'draw) mesh)))
509
510 (define (mesh-inner-properties mesh)
511   (((record-accessor mesh-type 'inner-properties) mesh)))
512
513 (define (mesh-inner-property mesh prop-name)
514   (((record-accessor mesh-type 'inner-property) mesh) prop-name))
515
516 (define (mesh-properties mesh)
517   (((record-accessor mesh-type 'properties) mesh)))
518
519 (define (mesh-properties-set! mesh new-properties)
520   (((record-accessor mesh-type 'properties-set!) mesh) new-properties))
521
522 (define (mesh-property mesh prop-name)
523   (((record-accessor mesh-type 'property) mesh) prop-name))
524
525 (define (mesh-property-set! mesh prop-name value)
526   (((record-accessor mesh-type 'property-set!) mesh) prop-name value))
527
528 (define* (translate mesh x y #:optional (z 0))
529   (((record-accessor mesh-type 'translate) mesh) x y z)
530   mesh)
531
532 (define (turn mesh . params)
533   (apply ((record-accessor mesh-type 'turn) mesh)
534          (if (>= (length params) 3)
535              params
536              (list 0 0 (car params))))
537   mesh)
538
539 (define (rotate mesh . params)
540   (apply ((record-accessor mesh-type 'rotate) mesh)
541          (if (>= (length params) 3)
542              params
543              (list 0 0 (car params))))
544   mesh)
545
546 (define (color mesh c)
547   (((record-accessor mesh-type 'color) mesh) c)
548   mesh)
549
550
551 ;;; Advanced meshes
552
553 (define (mesh-join . meshes)
554   (make-mesh
555    'joined-meshes
556    (lambda (props)
557      (for-each (lambda (m) (with-gl-push-matrix (mesh-draw m))) meshes))))
558
559
560 ;;; Primitives
561
562 (define-macro (primitive header . body)
563   (let* ((type (car header))
564          (args (cdr header))
565          (list-args (names-arguments args)))
566     `(lambda* ,args
567        (let ((m (make-mesh
568                  ',type
569                  (lambda (props)
570                    (apply (lambda* ,(cons #:key list-args) ,@body)
571                           (list
572                            ,@(let get-params ((l list-args))
573                                (cond ((null? l) '())
574                                      (else
575                                       (cons (symbol->keyword (car l))
576                                             (cons `(assoc-ref props ',(car l))
577                                                   (get-params (cdr l)))))))))))))
578          (mesh-properties-set! m (list ,@(map (lambda (a) `(cons ',a ,a)) list-args)))
579          m))))
580
581 (define-macro (define-primitive header . body)
582   `(define ,(car header) (primitive ,header ,@body)))
583
584
585 ;;; Primitives definition
586
587 (define-primitive (square size #:key texture)
588   (draw-square size #:texture texture))
589
590 (define-primitive (rectangle width height #:key texture texture-coord)
591   (draw-rectangle width height #:texture texture #:texture-coord texture-coord))
592
593 (define-primitive (circle radius)
594   (draw-circle radius))
595
596 (define-primitive (picture filename #:key (min-filter (texture-min-filter linear)) (mag-filter (texture-mag-filter linear)) (zoom 1) (sprite '((0 0) (1 1))))
597   (draw-texture (load-texture filename #:min-filter min-filter #:mag-filter mag-filter) #:zoom zoom #:sprite sprite))
598
599
600 (module-map (lambda (sym var)
601               (if (not (eq? sym '%module-public-interface))
602                   (module-export! (current-module) (list sym))))
603             (current-module))