doc: Improve texture documentation.
[chickadee.git] / chickadee / math.scm
1 ;;; Chickadee Game Toolkit
2 ;;; Copyright © 2016 David Thompson <davet@gnu.org>
3 ;;;
4 ;;; Chickadee is free software: you can redistribute it and/or modify
5 ;;; it under the terms of the GNU General Public License as published
6 ;;; by the Free Software Foundation, either version 3 of the License,
7 ;;; or (at your option) any later version.
8 ;;;
9 ;;; Chickadee is distributed in the hope that it will be useful, but
10 ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
11 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 ;;; 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
16 ;;; <http://www.gnu.org/licenses/>.
17
18 (define-module (chickadee math)
19 #:export (pi
20 pi/2
21 cotan
22 square
23 clamp
24 min
25 max
26 lerp)
27 #:replace (min max))
28
29 (define pi 3.14159265358979323846)
30 (define pi/2 (/ pi 2.0))
31
32 (define-inlinable (cotan z)
33 "Return the cotangent of Z."
34 (/ 1.0 (tan z)))
35
36 (define-inlinable (square x)
37 (* x x))
38
39 (define-inlinable (clamp min max x)
40 "Restrict X to the range defined by MIN and MAX. Assumes that MIN is
41 actually less than MAX."
42 (cond ((< x min) min)
43 ((> x max) max)
44 (else x)))
45
46 ;; Some macro trickery to inline calls to min/max with 2 arguments.
47 ;; We often call min/max on floating point values, so inlining such
48 ;; calls allows the compiler to unbox many of these operations,
49 ;; reducing allocation.
50 (define-syntax min
51 (syntax-rules ()
52 ((_ a b)
53 (if (< a b) a b))
54 ((_ a b ...)
55 (let ((m (min b ...)))
56 (if (< a m) a m)))))
57
58 (define-syntax max
59 (syntax-rules ()
60 ((_ a b) (if (> a b) a b))
61 ((_ a b ...)
62 (let ((m (max b ...)))
63 (if (> a m) a m)))))
64
65 (define-inlinable (lerp start end alpha)
66 (+ (* start (- 1.0 alpha))
67 (* end alpha)))