]> git.jsancho.org Git - gacela.git/blob - src/system.scm
4da0b1c91bfdac2c1dd0391e828b58e98db7acdf
[gacela.git] / src / system.scm
1 ;;; Gacela, a GNU Guile extension for fast games development
2 ;;; Copyright (C) 2013 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 system)
19   #:use-module (srfi srfi-1)
20   #:use-module (srfi srfi-9))
21
22
23 ;;; Component definitions
24
25 (define (make-symbol . args)
26   (string->symbol
27    (string-concatenate
28     (map (lambda (a) (if (symbol? a) (symbol->string a) a)) args))))
29
30 (define-macro (define-component name . args)
31   `(begin
32      (use-modules (srfi srfi-9) (srfi srfi-9 gnu))
33      (define-record-type ,name
34        (,(make-symbol "make-" name) ,@args)
35        ,(make-symbol name "?")
36        ,@(map (lambda (a) (list a (make-symbol name "-" a) (make-symbol "set-" name "-" a "!"))) args))
37      (set-record-type-printer! ,name
38        (lambda (record port)
39          (format port "#<[~a]" ',name)
40          ,@(map (lambda (a) `(format port " ~a: ~a" ',a (,(make-symbol name "-" a) record))) args)
41          (format port ">")))
42      ',name))
43
44 (define (get-component-type component)
45   (record-type-name (record-type-descriptor component)))
46
47 (export define-component
48         get-component-type)
49
50
51 ;;; Making systems
52
53 (define* (find-entities-by-components c t)
54   (cond ((null? t) '())
55         (else
56          (let* ((e (assoc-ref c (car t)))
57                 (e* (if e e '())))
58            (cond ((null? (cdr t)) e*)
59                  (else
60                   (lset-intersection eq? e* (find-entities-by-components c (cdr t)))))))))
61                   
62
63 (define (make-system component-types system-fun)
64   (lambda (entities components)
65     (let* ((e (find-entities-by-components components component-types))
66            (e* (map (lambda (x) (assoc x entities)) e))
67            (e** (map (lambda (x) (cons (car x) (filter (lambda (x) (memq (get-component-type x) component-types)) (cdr x)))) e*)))
68       e**)))
69
70
71 (export find-entities-by-components
72         make-system)