forked from fjolliton/cl-vectors
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpaths.lisp
1611 lines (1458 loc) · 67.3 KB
/
paths.lisp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;;; cl-vectors -- Rasterizer and paths manipulation library
;;;; Copyright (C) 2007-2013 Frédéric Jolliton <[email protected]>
;;;; This code is licensed under the MIT license.
;;;; This file provides facilities to create and manipulate vectorial paths.
#+nil(error "This file assume that #+NIL is never defined.")
(in-package #:net.tuxee.paths)
(defvar *bezier-distance-tolerance* 0.5
"The default distance tolerance used when rendering Bezier
curves.")
(defvar *bezier-angle-tolerance* 0.05
"The default angle tolerance (in radian) used when rendering
Bezier curves")
(defvar *arc-length-tolerance* 1.0
"The maximum length of segment describing an arc.")
(defvar *miter-limit* 4.0
"Miter limit before reverting to bevel joint. Must be >=1.0.")
;;;--[ Math utilities ]------------------------------------------------------
;;; http://mathworld.wolfram.com/Line-LineIntersection.html
(defun line-intersection (x1 y1 x2 y2
x3 y3 x4 y4)
"Compute the intersection between 2 lines (x1,y1)-(x2,y2)
and (x3,y3)-(x4,y4). Return the coordinates of the intersection
points as 2 values. If the 2 lines are colinears, return NIL."
(flet ((det (a b c d)
(- (* a d)
(* b c))))
(let* ((dx1 (- x2 x1))
(dy1 (- y2 y1))
(dx2 (- x4 x3))
(dy2 (- y4 y3))
(d (det dx2 dy2 dx1 dy1)))
(unless (zerop d)
(let ((a (det x1 y1 x2 y2))
(b (det x3 y3 x4 y4)))
(values (/ (det a dx1 b dx2) d)
(/ (det a dy1 b dy2) d)))))))
(defun line-intersection/delta (x1 y1 dx1 dy1
x2 y2 dx2 dy2)
"Compute the intersection between the line by (x1,y1) and
direction (dx1,dy1) and the line by (x2,y2) and
direction (dx2,dy2). Return the coordinates of the intersection
points as 2 values. If the 2 lines are colinears, return NIL."
(flet ((det (a b c d)
(- (* a d)
(* b c))))
(let ((d (det dx2 dy2 dx1 dy1)))
(unless (zerop d)
(let ((a (det x1 y1 (+ x1 dx1) (+ y1 dy1)))
(b (det x2 y2 (+ x2 dx2) (+ y2 dy2))))
(values (/ (det a dx1 b dx2) d)
(/ (det a dy1 b dy2) d)))))))
(defun normalize (x y &optional (length 1.0))
"Normalize the vector (X,Y) such that its length is LENGTH (or
1.0 if unspecified.) Return the component of the resulting vector
as 2 values. Return NIL if the input vector had a null length."
(if (zerop length)
(values 0.0 0.0)
(let ((norm (/ (sqrt (+ (* x x) (* y y))) length)))
(unless (zerop norm)
(values (/ x norm) (/ y norm))))))
(defun line-normal (x1 y1 x2 y2)
"Normalize the vector (X2-X1,Y2-Y1). See NORMALIZE."
(normalize (- x2 x1) (- y2 y1)))
;;;--[ Points ]--------------------------------------------------------------
;;; Points are supposed to be immutable
(declaim (inline make-point point-x point-y))
(defun make-point (x y) (cons x y))
(defun point-x (point) (car point))
(defun point-y (point) (cdr point))
;;; Utility functions for points
(defun p+ (p1 p2)
(make-point (+ (point-x p1) (point-x p2))
(+ (point-y p1) (point-y p2))))
(defun p- (p1 p2)
(make-point (- (point-x p1) (point-x p2))
(- (point-y p1) (point-y p2))))
(defun p* (point scale &optional (scale-y scale))
(make-point (* (point-x point) scale)
(* (point-y point) scale-y)))
(defun point-rotate (point angle)
"Rotate POINT by ANGLE radian around the origin."
(let ((x (point-x point))
(y (point-y point)))
(make-point (- (* x (cos angle)) (* y (sin angle)))
(+ (* y (cos angle)) (* x (sin angle))))))
(defun point-angle (point)
"Compute the angle of POINT relatively to the X axis."
(atan (point-y point) (point-x point)))
(defun point-norm (point)
"Compute the distance of POINT from origin."
(sqrt (+ (expt (point-x point) 2)
(expt (point-y point) 2))))
;; (point-norm (p- p2 p1))
(defun point-distance (p1 p2)
"Compute the distance between P1 and P2."
(sqrt (+ (expt (- (point-x p2) (point-x p1)) 2)
(expt (- (point-y p2) (point-y p1)) 2))))
;; (p* (p+ p1 p2) 0.5)
(defun point-middle (p1 p2)
"Compute the point between P1 and P2."
(make-point (/ (+ (point-x p1) (point-x p2)) 2.0)
(/ (+ (point-y p1) (point-y p2)) 2.0)))
;;;--[ Paths ]---------------------------------------------------------------
(defstruct path
(type :open-polyline :type (member :open-polyline :closed-polyline :polygon))
(orientation :unknown :type (member :unknown :cw :ccw))
(knots (make-array 0 :adjustable t :fill-pointer 0))
(interpolations (make-array 0 :adjustable t :fill-pointer 0)))
(defun create-path (type)
"Create a new path of the given type. The type must be one of
the following keyword:
:open-polyline -- An open polyline path,
:closed-polyline -- A closed polyline path,
:polygon -- Like :closed-polyline, but implicitly filled."
(assert (member type '(:open-polyline :closed-polyline :polygon)))
(make-path :type type))
(defun path-clear (path)
"Clear the path such that it is empty."
(setf (path-orientation path) :unknown
(fill-pointer (path-knots path)) 0
(fill-pointer (path-interpolations path)) 0))
(defun path-reset (path knot)
"Reset the path such that it is a single knot."
(path-clear path)
(vector-push-extend knot (path-knots path))
(vector-push-extend (make-straight-line) (path-interpolations path)))
(defun path-extend (path interpolation knot)
"Extend the path to KNOT, with INTERPOLATION."
(vector-push-extend interpolation (path-interpolations path))
(vector-push-extend knot (path-knots path))
;; Extending the path can change how the orientation is
;; auto-detected.
(setf (path-orientation path) :unknown))
(defun path-concatenate (path interpolation other-path)
"Append OTHER-PATH to PATH, joined by INTERPOLATION."
(let ((interpolations (path-interpolations other-path))
(knots (path-knots other-path)))
(loop for i below (length knots)
do (path-extend path
(interpolation-clone (if (and (zerop i) interpolation)
interpolation
(aref interpolations i)))
(aref knots i)))))
(defun path-replace (path other-path)
"Replace PATH with contents of OTHER-PATH."
(path-clear path)
(path-concatenate path nil other-path))
(defun path-size (path)
"Return the number of knots on the path."
(length (path-knots path)))
(defun path-last-knot (path)
"Return the last knot of the path. Return NIL if the path is
empty."
(let ((knots (path-knots path)))
(when (plusp (length knots))
(aref knots (1- (length knots))))))
(defun path-guess-orientation (path)
"Guess the orientation of the path.
This is implemented loosely because we don't take care about
interpolations. We only consider a polygon described by the
knots. However, it should work..
Update path orientation flag, and returns either :CW or :CCW."
(let ((knots (path-knots path)))
(let ((loose-area (loop for last-knot-index = (1- (length knots)) then knot-index
for knot-index below (length knots)
sum (- (* (point-x (aref knots last-knot-index))
(point-y (aref knots knot-index)))
(* (point-x (aref knots knot-index))
(point-y (aref knots last-knot-index)))))))
(setf (path-orientation path) (if (plusp loose-area) :ccw :cw)))))
(defun path-orient (path orientation &optional other-paths)
"Orient the path in the given orientation.
If OTHER-PATHS is specified, then the paths are reversed
inconditionnaly if PATH is also reversed."
(assert (member orientation '(:cw :ccw)) (orientation) "Expected either :CW or :CCW")
(when (eq (path-orientation path) :unknown)
(path-guess-orientation path))
(unless (eq (path-orientation path) orientation)
(path-reverse path)
(map nil #'path-reverse other-paths))
(values))
;;; Iterators
(defgeneric path-iterator-reset (iterator)
(:documentation "Reset the iterator before the first knot."))
(defgeneric path-iterator-next (iterator)
(:documentation "Move the iterator to the next knot, and return
3 values: INTERPOLATION, KNOT and END-P. INTERPOLATION is the
interpolation between the previous knot and the current one. For
the first iteration, INTERPOLATION is usually the implicit
straight line between the last knot and the first knot. KNOT and
INTERPOLATION are null if the path is empty. END-P is true if the
knot is the last on the path or if the path is empty."))
(defun path-from-iterator (iterator type)
"Construct a new path from the given iterator."
(let ((path (create-path type)))
(loop
(multiple-value-bind (iterator knot end-p) (path-iterator-next iterator)
(path-extend path iterator knot)
(when end-p
(return path))))))
;;; Classic iterator
(defstruct path-iterator-state
path index)
(defun path-iterator (path)
(make-path-iterator-state :path path :index nil))
(defmethod path-iterator-reset ((iterator path-iterator-state))
(setf (path-iterator-state-index iterator) nil))
(defmethod path-iterator-next ((iterator path-iterator-state))
(let* ((index (path-iterator-state-index iterator))
(path (path-iterator-state-path iterator))
(knots (path-knots path))
(interpolations (path-interpolations path)))
(cond
((zerop (length knots))
(values nil nil t))
(t
;; Update index to the next place
(setf index
(setf (path-iterator-state-index iterator)
(if (null index) 0 (mod (1+ index) (length knots)))))
(values (aref interpolations index)
(aref knots index)
(= index (1- (length knots))))))))
;;; Segmented iterator
;;;
;;; This iterator iterate over segmented interpolation, if the
;;; interpolation is matched by the predicate. This is useful for
;;; algorithms that doesn't handle certain type of interpolations.
;;; The predicate could test the type, but also certain type of
;;; interpolation (such as arc of circle vs arc of ellipse, or degree
;;; of the Bezier curves.)
;;; Note: I use PI prefix instead of PATH-ITERATOR to shorten names.
(defstruct pi-segmented-state
path index predicate end-p queue)
(defun path-iterator-segmented (path &optional (predicate (constantly t)))
(make-pi-segmented-state :path path :index nil
:predicate predicate
:end-p nil :queue nil))
(defmethod path-iterator-reset ((iterator pi-segmented-state))
(setf (pi-segmented-state-index iterator) nil
(pi-segmented-state-queue iterator) nil))
(defmethod path-iterator-next ((iterator pi-segmented-state))
(flet ((update-queue (interpolation k1 k2 last-p)
(let (new-queue)
(interpolation-segment interpolation k1 k2 (lambda (p) (push p new-queue)))
(push k2 new-queue)
(setf (pi-segmented-state-end-p iterator) last-p
(pi-segmented-state-queue iterator) (nreverse new-queue))))
(dequeue ()
(let* ((knot (pop (pi-segmented-state-queue iterator)))
(end-p (and (pi-segmented-state-end-p iterator)
(null (pi-segmented-state-queue iterator)))))
(values (make-straight-line) knot (when end-p t)))))
(cond
((pi-segmented-state-queue iterator)
;; Queue is not empty, process it first.
(dequeue))
(t
;; Either refill the queue, or return the next straight line
;; from the sub iterator.
(let* ((index (pi-segmented-state-index iterator))
(path (pi-segmented-state-path iterator))
(knots (path-knots path))
(interpolations (path-interpolations path)))
(cond
((zerop (length knots))
;; Empty path.
(values nil nil t))
(t
;; Update index to the next place
(setf index
(setf (pi-segmented-state-index iterator)
(if (null index) 0 (mod (1+ index) (length knots)))))
(let ((interpolation (aref interpolations index))
(knot (aref knots index))
(end-p (= index (1- (length knots)))))
;; Check if we have to segment the next interpolation
(if (funcall (pi-segmented-state-predicate iterator)
interpolation)
(let ((previous-index (mod (1- index) (length knots))))
(update-queue interpolation
(aref knots previous-index)
knot end-p)
(dequeue))
(values interpolation knot end-p))))))))))
;;; Iterate distinct
;;; This iterator filter out identical knots. That is, the knots with
;;; the same positions, with any interpolation. (All interpolations
;;; currently implemented are empty when knot around them are not
;;; distinct.)
;;; When cyclic-p is true, the first knot of the iterator is the first
;;; knot distinct from the first knot of the reference iterator.
;;; When cyclic-p is false, the first knot of the iterator if the
;;; first knot of the reference iterator, and if the path ends with a
;;; knot which is not distinct from the first, it is kept.
(defclass filter-distinct-state ()
((iterator :initarg :iterator)
(cyclic-p :initarg :cyclic-p)
(fixed :initarg :fixed)
(next :initarg :next)
(next-is-end-p)))
(defun filter-distinct (iterator &optional (preserve-cyclic-end-p nil))
(make-instance 'filter-distinct-state
:iterator iterator
:cyclic-p (not preserve-cyclic-end-p)
:fixed nil
:next nil))
(defmethod path-iterator-reset ((iterator filter-distinct-state))
(with-slots ((sub iterator) next next-is-end-p) iterator
(path-iterator-reset sub)
(setf next nil
next-is-end-p nil)))
(defmethod path-iterator-next ((iterator filter-distinct-state))
(with-slots ((sub iterator) cyclic-p fixed next next-is-end-p) iterator
(when fixed
;; constant result cached
(return-from path-iterator-next (values-list fixed)))
(labels ((get-next ()
"Get the next knot information as a list (not as
multiple values)."
(multiple-value-list (path-iterator-next sub)))
(distinct-p (a b)
"Test if A and B have distinct knots."
(not (zerop (point-distance (second a) (second b)))))
(move-to-next (previous loop-p)
"Move iterator to find a knot distinct from the
PREVIOUS. Also indicate if the resulting knot is
the first of the sub iterator, and if end of path
was encountered. This is needed to compute the
effective END-P flag for the resulting iterator."
(loop
with first-p = (third previous)
with end-encountered-p = (third previous)
for current = (get-next)
until (or (distinct-p previous current)
(and (not loop-p) first-p))
do (setf first-p (third current))
when (third current)
do (setf end-encountered-p t)
finally (return (values current first-p end-encountered-p)))))
(let (result)
(unless next
;; First time we iterate.
(setf next-is-end-p nil)
(let ((first (get-next)))
(cond
((or (not (second first))
(third first))
;; It was an empty path or a single knot path. Cache it
;; and returns it for each further iterations.
(setf fixed first
result first))
(cyclic-p
(multiple-value-bind (first-in-cycle first-p end-p) (move-to-next first nil)
(declare (ignore first-p))
(cond
(end-p
(setf (third first) t
fixed first
result first))
(t
(setf next first-in-cycle)))))
(t
(setf next first)))))
(unless result
;; We copy NEXT because we need to modify RESULT, and since
;; NEXT is kept for the next iteration, we take care of not
;; modifying it.
(setf result (copy-seq next)
(third result) next-is-end-p)
(multiple-value-bind (current first-p end-encountered-p) (move-to-next next cyclic-p)
(setf next current)
;; Set end marker
(cond
(cyclic-p
(setf next-is-end-p first-p)
(when (and end-encountered-p (not first-p))
(setf (third result) t)))
(t
(setf (third result) end-encountered-p)))))
(values-list result)))))
;;; Misc
(defun path-clone (path)
(let ((new-interpolations (copy-seq (path-interpolations path))))
(loop for i below (length new-interpolations)
do (setf (aref new-interpolations i)
(interpolation-clone (aref new-interpolations i))))
(let ((new-path (create-path (path-type path))))
(setf (path-knots new-path) (copy-seq (path-knots path))
(path-interpolations new-path) new-interpolations
(path-orientation new-path) (path-orientation path))
new-path)))
(defun path-reverse (path)
;; reverse the order of knots
(setf (path-knots path) (nreverse (path-knots path)))
;; reverse the order of interpolations 1..n (not the first one,
;; which is the implicit straight line.)
(loop with interpolations = (path-interpolations path)
with length = (length interpolations)
for i from 1 upto (floor (1- length) 2)
do (rotatef (aref interpolations i)
(aref interpolations (- length i))))
;; reverse each interpolation
(loop for interpolation across (path-interpolations path)
do (interpolation-reverse interpolation))
(unless (eq (path-orientation path) :unknown)
(setf (path-orientation path) (ecase (path-orientation path)
(:cw :ccw)
(:ccw :cw))))
path)
(defun path-reversed (path)
(let ((new-path (path-clone path)))
(path-reverse new-path)
new-path))
(defmacro do-path ((path interpolation knot) &body body)
(let ((path-sym (gensym))
(knots (gensym))
(interpolations (gensym))
(index (gensym)))
`(symbol-macrolet ((,interpolation (aref ,interpolations ,index))
(,knot (aref ,knots ,index)))
(loop
with ,path-sym = ,path
with ,knots = (path-knots ,path-sym)
with ,interpolations = (path-interpolations ,path-sym)
for ,index below (length ,knots)
do (progn ,@body)))))
(defun path-translate (path vector)
"Translate the whole path accordingly to VECTOR."
(if (listp path)
(dolist (path-item path)
(path-translate path-item vector))
(unless (and (zerop (point-x vector))
(zerop (point-y vector)))
(do-path (path interpolation knot)
(setf knot (p+ knot vector))
(interpolation-translate interpolation vector))))
path)
(defun path-rotate (path angle &optional center)
"Rotate the whole path by ANGLE radian around CENTER (which is
the origin if unspecified.)"
(if (listp path)
(dolist (path-item path)
(path-rotate path-item angle center))
(unless (zerop angle)
(when center
(path-translate path (p* center -1.0)))
(do-path (path interpolation knot)
(setf knot (point-rotate knot angle))
(interpolation-rotate interpolation angle))
(when center
(path-translate path center))))
path)
(defun path-scale (path scale-x scale-y &optional center)
"Scale the whole path by (SCALE-X,SCALE-Y) from CENTER (which
is the origin if unspecified.) Warning: not all interpolations
support non uniform scaling (when scale-x /= scale-y)."
;;; FIXME: What to do about path-orientation?
(if (listp path)
(dolist (path-item path)
(path-scale path-item scale-x scale-y center))
(progn
(when center
(path-translate path (p* center -1.0)))
(do-path (path interpolation knot)
(setf knot (p* knot scale-x scale-y))
(interpolation-scale interpolation scale-x scale-y))
(when center
(path-translate path center))
(when (minusp (* scale-x scale-y))
(path-reverse path))))
path)
(defun path-end-info (path side)
(when (>= (path-size path) 2)
(if (not side)
(values (aref (path-knots path) 0)
(interpolation-normal (aref (path-interpolations path) 1)
(aref (path-knots path) 0)
(aref (path-knots path) 1)
nil))
(let ((ks (length (path-knots path)))
(is (length (path-interpolations path))))
(values (aref (path-knots path) (1- ks))
(interpolation-normal (aref (path-interpolations path) (1- is))
(aref (path-knots path) (- is 2))
(aref (path-knots path) (- is 1))
t))))))
(defun path-transform-as-marker (path path-reference side &key (offset 0.0) (scale 1.0) (angle 0.0))
"Translate, rotate and scale PATH representing a marker such
that it is adapted to the PATH-REFERENCE. If SIDE is false, it is
placed at the start of the path, otherwise it is placed at the
end of the path."
(multiple-value-bind (knot normal) (path-end-info path-reference side)
(when knot
(path-rotate path (+ (/ pi -2) angle (point-angle normal)))
(path-scale path scale scale)
(path-translate path (p+ knot (p* normal offset)))
path)))
;;;--[ Interpolations ]------------------------------------------------------
(defgeneric interpolation-segment (interpolation k1 k2 function)
(:documentation "Segment the path between K1 and K2 described
by the INTERPOLATION. Call FUNCTION for each generated point on
the interpolation path."))
(defgeneric interpolation-normal (interpolation k1 k2 side)
(:documentation "Compute the normal, going \"outside\" at
either K1 (if SIDE is false) or K2 (if SIDE is true). Return NIL
if the normal cannot be computed. Return a point otherwise."))
(defgeneric interpolation-clone (interpolation)
(:documentation "Duplicate INTERPOLATION."))
(defgeneric interpolation-reverse (interpolation)
(:documentation "Reverse the path described by INTERPOLATION
in-place."))
(defgeneric interpolation-reversed (interpolation)
(:method (interpolation)
(let ((cloned-interpolation (interpolation-clone interpolation)))
(interpolation-reversed cloned-interpolation)
cloned-interpolation))
(:documentation "Duplicate and reverse the INTERPOLATION."))
(defgeneric interpolation-translate (interpolation vector))
(defgeneric interpolation-rotate (interpolation angle))
(defgeneric interpolation-scale (interpolation scale-x scale-y))
;;; Straight lines
(defun make-straight-line ()
:straight-line)
(defun straight-line-p (value)
(eq value :straight-line))
(defmethod interpolation-segment ((interpolation (eql :straight-line)) k1 k2 function)
(declare (ignore interpolation k1 k2 function)))
(defmethod interpolation-normal ((interpolation (eql :straight-line)) k1 k2 side)
(let* ((x1 (point-x k1))
(y1 (point-y k1))
(x2 (point-x k2))
(y2 (point-y k2))
(dx (- x2 x1))
(dy (- y2 y1))
(dist (sqrt (+ (expt dx 2) (expt dy 2)))))
(when (plusp dist)
(if side
(make-point (/ dx dist)
(/ dy dist))
(make-point (- (/ dx dist))
(- (/ dy dist)))))))
(defmethod interpolation-clone ((interpolation (eql :straight-line)))
(make-straight-line))
(defmethod interpolation-reverse ((interpolation (eql :straight-line)))
(declare (ignore interpolation)))
(defmethod interpolation-translate ((interpolation (eql :straight-line)) vector)
(declare (ignore interpolation vector)))
(defmethod interpolation-rotate ((interpolation (eql :straight-line)) angle)
(declare (ignore interpolation angle)))
(defmethod interpolation-scale ((interpolation (eql :straight-line)) scale-x scale-y)
(declare (ignore interpolation scale-x scale-y)))
;;; Arc (SVG style)
(defclass arc ()
((rx :initarg rx)
(ry :initarg ry)
(x-axis-rotation :initarg x-axis-rotation)
(large-arc-flag :initarg large-arc-flag) ; t = choose the longest arc, nil = choose the smallest arc
(sweep-flag :initarg sweep-flag))) ; t = arc on the right, nil = arc on the left
(defun make-arc (rx ry &key (x-axis-rotation 0.0) (large-arc-flag nil) (sweep-flag nil))
(make-instance 'arc
'rx rx
'ry ry
'x-axis-rotation x-axis-rotation
'large-arc-flag large-arc-flag
'sweep-flag sweep-flag))
(defun svg-arc-parameters/reverse (center rx ry rotation start-angle delta-angle)
"Conversion from center to endpoint parameterization of SVG arc.
Returns values P1, P2, LARGE-ARC-FLAG-P, SWEEP-FLAG-P."
(let ((p1 (point-rotate (make-point rx 0) start-angle))
(p2 (point-rotate (make-point rx 0) (+ start-angle delta-angle))))
(flet ((transform (p)
(p+
(point-rotate
(p* p 1.0 (/ rx ry))
rotation)
center)))
(values (transform p1) (transform p2)
(> (abs delta-angle) pi)
(plusp delta-angle)))))
(defun svg-arc-parameters (p1 p2 rx ry rotation large-arc-flag-p sweep-flag-p)
"Conversion from endpoint to center parameterization of SVG arc.
Returns values RC, RX, RY, START-ANGLE and DELTA-ANGLE, where RC is
the center of the ellipse, RX and RY are the normalized
radii (needed if scaling was necessary)."
(when (and (/= rx 0)
(/= ry 0))
;; [SVG] "If rX or rY have negative signs, these are dropped; the
;; absolute value is used instead."
(setf rx (abs rx)
ry (abs ry))
;; normalize boolean value to nil/t
(setf large-arc-flag-p (when large-arc-flag-p t)
sweep-flag-p (when sweep-flag-p t))
;; rp1 and rp2 are p1 and p2 into the coordinate system such
;; that rotation is cancelled and ellipse ratio is 1 (a circle.)
(let* ((rp1 (p* (point-rotate p1 (- rotation)) 1.0 (/ rx ry)))
(rp2 (p* (point-rotate p2 (- rotation)) 1.0 (/ rx ry)))
(rm (point-middle rp1 rp2))
(drp1 (p- rm rp1))
(dist (point-norm drp1)))
(when (plusp dist)
(let ((diff-sq (- (expt rx 2) (expt dist 2)))
rc)
(cond
((not (plusp diff-sq))
;; a/ scale the arc if it is too small to touch the points
(setf ry (* dist (/ ry rx))
rx dist
rc rm))
(t
;; b/ otherwise compute the center of the circle
(let ((d (/ (sqrt diff-sq) dist)))
(unless (eq large-arc-flag-p sweep-flag-p)
(setf d (- d)))
(setf rc (make-point (+ (point-x rm) (* (point-y drp1) d))
(- (point-y rm) (* (point-x drp1) d)))))))
(let* ((start-angle (point-angle (p- rp1 rc)))
(end-angle (point-angle (p- rp2 rc)))
(delta-angle (- end-angle start-angle)))
(when (minusp delta-angle)
(incf delta-angle (* 2 pi)))
(unless sweep-flag-p
(decf delta-angle (* 2 pi)))
(values (point-rotate (p* rc 1.0 (/ ry rx)) rotation) rx ry start-angle delta-angle)))))))
(defmethod interpolation-segment ((interpolation arc) k1 k2 function)
(let ((rotation (slot-value interpolation 'x-axis-rotation)))
(multiple-value-bind (rc rx ry start-angle delta-angle)
(svg-arc-parameters k1 k2
(slot-value interpolation 'rx)
(slot-value interpolation 'ry)
rotation
(slot-value interpolation 'large-arc-flag)
(slot-value interpolation 'sweep-flag))
(when rc
(loop with n = (max 3 (* (max rx ry) (abs delta-angle)))
for i from 1 below n
for angle = (+ start-angle (/ (* delta-angle i) n))
for p = (p+ (point-rotate
(p*
(make-point (* rx (cos angle))
(* rx (sin angle)))
1.0 (/ ry rx))
rotation)
rc)
do (funcall function p))))))
(defmethod interpolation-normal ((interpolation arc) k1 k2 side)
(let ((rotation (slot-value interpolation 'x-axis-rotation)))
(multiple-value-bind (rc rx ry start-angle delta-angle)
(svg-arc-parameters k1 k2
(slot-value interpolation 'rx)
(slot-value interpolation 'ry)
rotation
(slot-value interpolation 'large-arc-flag)
(slot-value interpolation 'sweep-flag))
(flet ((adjust (normal)
(let* ((p (point-rotate (p* normal 1.0 (/ ry rx)) rotation))
(d (point-norm p)))
(when (plusp delta-angle)
(setf d (- d)))
(make-point (/ (point-x p) d) (/ (point-y p) d)))))
(when rc
(let ((end-angle (+ start-angle delta-angle)))
(adjust (if side
(make-point (sin end-angle)
(- (cos end-angle)))
(make-point (- (sin start-angle))
(cos start-angle))))))))))
(defmethod interpolation-clone ((interpolation arc))
(make-arc (slot-value interpolation 'rx)
(slot-value interpolation 'ry)
:x-axis-rotation (slot-value interpolation 'x-axis-rotation)
:large-arc-flag (slot-value interpolation 'large-arc-flag)
:sweep-flag (slot-value interpolation 'sweep-flag)))
(defmethod interpolation-reverse ((interpolation arc))
(setf (slot-value interpolation 'sweep-flag)
(not (slot-value interpolation 'sweep-flag))))
(defmethod interpolation-translate ((interpolation arc) vector)
(declare (ignore interpolation vector)))
(defmethod interpolation-rotate ((interpolation arc) angle)
(incf (slot-value interpolation 'x-axis-rotation) angle))
(defmethod interpolation-scale ((interpolation arc) scale-x scale-y)
;; FIXME: Return :segment-me if scaling is not possible?
(assert (and (not (zerop scale-x))
(= scale-x scale-y)))
(with-slots (rx ry) interpolation
(setf rx (* rx scale-x)
ry (* ry scale-y))))
;;; Catmull-Rom
(defclass catmull-rom ()
((head
:initarg head)
(control-points
:initform (make-array 0)
:initarg control-points)
(queue
:initarg queue)))
(defun make-catmull-rom (head control-points queue)
(make-instance 'catmull-rom
'head head
'control-points (coerce control-points 'vector)
'queue queue))
(defmethod interpolation-segment ((interpolation catmull-rom) k1 k2 function)
(let* ((control-points (slot-value interpolation 'control-points))
(points (make-array (+ (length control-points) 4))))
(replace points control-points :start1 2)
(setf (aref points 0) (slot-value interpolation 'head)
(aref points 1) k1
(aref points (- (length points) 2)) k2
(aref points (- (length points) 1)) (slot-value interpolation 'queue))
(labels ((eval-catmull-rom (a b c d p)
;; http://www.mvps.org/directx/articles/catmull/
(* 0.5
(+ (* 2 b)
(* (+ (- a) c) p)
(* (+ (* 2 a) (* -5 b) (* 4 c) (- d)) (expt p 2))
(* (+ (- a) (* 3 b) (* -3 c) d) (expt p 3))))))
(loop for s below (- (length points) 3)
for a = (aref points (+ s 0)) then b
for b = (aref points (+ s 1)) then c
for c = (aref points (+ s 2)) then d
for d = (aref points (+ s 3))
do (funcall function b)
(loop with n = 32
for i from 1 below n
for p = (/ (coerce i 'float) n)
for x = (eval-catmull-rom (point-x a)
(point-x b)
(point-x c)
(point-x d)
p)
for y = (eval-catmull-rom (point-y a)
(point-y b)
(point-y c)
(point-y d)
p)
do (funcall function (make-point x y)))
(funcall function c)))))
(defmethod interpolation-normal ((interpolation catmull-rom) k1 k2 side)
(with-slots (head control-points queue) interpolation
(let (a b)
(if (zerop (length control-points))
(if side
(setf a k1
b queue)
(setf a k2
b head))
(if side
(setf a (aref control-points (1- (length control-points)))
b queue)
(setf a (aref control-points 0)
b head)))
(let* ((x1 (point-x a))
(y1 (point-y a))
(x2 (point-x b))
(y2 (point-y b))
(dx (- x2 x1))
(dy (- y2 y1))
(dist (sqrt (+ (expt dx 2) (expt dy 2)))))
(when (plusp dist)
(make-point (/ dx dist)
(/ dy dist)))))))
(defmethod interpolation-clone ((interpolation catmull-rom))
(make-catmull-rom (slot-value interpolation 'head)
(copy-seq (slot-value interpolation 'control-points))
(slot-value interpolation 'queue)))
(defmethod interpolation-reverse ((interpolation catmull-rom))
(rotatef (slot-value interpolation 'head)
(slot-value interpolation 'queue))
(nreverse (slot-value interpolation 'control-points)))
(defmethod interpolation-translate ((interpolation catmull-rom) vector)
(with-slots (head control-points queue) interpolation
(setf head (p+ head vector)
queue (p+ queue vector))
(loop for i below (length control-points)
do (setf (aref control-points i) (p+ (aref control-points i) vector)))))
(defmethod interpolation-rotate ((interpolation catmull-rom) angle)
(with-slots (head control-points queue) interpolation
(setf head (point-rotate head angle)
queue (point-rotate queue angle))
(loop for i below (length control-points)
do (setf (aref control-points i) (point-rotate (aref control-points i) angle)))))
(defmethod interpolation-scale ((interpolation catmull-rom) scale-x scale-y)
(with-slots (head control-points queue) interpolation
(setf head (p* head scale-x scale-y)
queue (p* queue scale-x scale-y))
(loop for i below (length control-points)
do (setf (aref control-points i) (p* (aref control-points i)
scale-x scale-y)))))
;;; Bezier curves
;;; [http://www.fho-emden.de/~hoffmann/bezier18122002.pdf]
(defclass bezier ()
((control-points
:initform (make-array 0)
:initarg control-points)))
(defun make-bezier-curve (control-points)
(make-instance 'bezier
'control-points (make-array (length control-points)
:initial-contents control-points)))
(defun split-bezier (points &optional (position 0.5))
"Split the Bezier curve described by POINTS at POSITION into
two Bezier curves of the same degree. Returns the curves as 2
values."
(let* ((size (length points))
(stack (make-array size))
(current points))
(setf (aref stack 0) points)
(loop for j from 1 below size
for next-size from (1- size) downto 1
do (let ((next (make-array next-size)))
(loop for i below next-size
for a = (aref current i)
for b = (aref current (1+ i))
do (setf (aref next i)
(make-point (+ (* (- 1.0 position) (point-x a))
(* position (point-x b)))
(+ (* (- 1.0 position) (point-y a))
(* position (point-y b))))))
(setf (aref stack j) next
current next)))
(let ((left (make-array (length points)))
(right (make-array (length points))))
(loop for i from 0 below size
for j from (1- size) downto 0
do (setf (aref left i) (aref (aref stack i) 0)
(aref right i) (aref (aref stack j) i)))
(values left right))))
(defun evaluate-bezier (points position)
"Evaluate the point at POSITION on the Bezier curve described
by POINTS."
(let* ((size (length points))
(temp (make-array (1- size))))
(loop for current = points then temp
for i from (length temp) downto 1
do (loop for j below i
for a = (aref current j)
for b = (aref current (1+ j))
do (setf (aref temp j)
(make-point (+ (* (- 1.0 position) (point-x a))
(* position (point-x b)))
(+ (* (- 1.0 position) (point-y a))
(* position (point-y b)))))))
(let ((p (aref temp 0)))
(values (point-x p) (point-y p)))))
(defun discrete-bezier-curve (points function
&key
(include-ends t)
(min-subdivide nil)
(max-subdivide 10)
(distance-tolerance *bezier-distance-tolerance*)
(angle-tolerance *bezier-angle-tolerance*))
"Subdivize Bezier curve up to certain criterions."
;; FIXME: Handle cusps correctly!
(unless min-subdivide
(setf min-subdivide (floor (log (1+ (length points)) 2))))
(labels ((norm (a b)
(sqrt (+ (expt a 2) (expt b 2))))
(refine-bezier (points depth)
(let* ((a (aref points 0))
(b (aref points (1- (length points))))
(middle-straight (point-middle a b)))
(multiple-value-bind (bx by) (evaluate-bezier points 0.5)
(when (or (< depth min-subdivide)
(and (<= depth max-subdivide)
(or (> (norm (- bx (point-x middle-straight))
(- by (point-y middle-straight)))
distance-tolerance)
(> (abs (- (atan (- by (point-y a)) (- bx (point-x a)))
(atan (- (point-y b) by) (- (point-x b) bx))))
angle-tolerance))))
(multiple-value-bind (a b) (split-bezier points 0.5)
(refine-bezier a (1+ depth))
(funcall function bx by)
(refine-bezier b (1+ depth))))))))
(when include-ends
(let ((p (aref points 0)))
(funcall function (point-x p) (point-y p))))