id
int64 0
45.1k
| file_name
stringlengths 4
68
| file_path
stringlengths 14
193
| content
stringlengths 32
9.62M
| size
int64 32
9.62M
| language
stringclasses 1
value | extension
stringclasses 6
values | total_lines
int64 1
136k
| avg_line_length
float64 3
903k
| max_line_length
int64 3
4.51M
| alphanum_fraction
float64 0
1
| repo_name
stringclasses 779
values | repo_stars
int64 0
882
| repo_forks
int64 0
108
| repo_open_issues
int64 0
90
| repo_license
stringclasses 8
values | repo_extraction_date
stringclasses 146
values | sha
stringlengths 64
64
| __index_level_0__
int64 0
45.1k
| exdup_ids_cmlisp_stkv2
sequencelengths 1
47
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
17,543 | point.lisp | rheaplex_rheart/draw-something/point.lisp | ;; point.lisp - A 2D point.
;; Copyright (C) 2006 Rhea Myers [email protected]
;;
;; This file is part of draw-something.
;;
;; draw-something is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3 of the License, or
;; (at your option) any later version.
;;
;; draw-something is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;(in-package "DRAW-SOMETHING")
(defclass point ()
((x :accessor x
:type float
:initform 0.0
:initarg :x
:documentation "The x co-ordinate of the point.")
(y :accessor y
:type float
:initform 0.0
:initarg :y
:documentation "The y co-ordinate of the point."))
(:documentation "A simple cartesian point on the picture plane (or page).
y goes up"))
(defmethod distance ((left point) (right point))
"The distance between two points."
(sqrt (+ (expt (- (x right) (x left)) 2)
(expt (- (y right) (y left)) 2))))
(defmethod distance-point-co-ordinates ((left point) x2 y2)
"The distance between two points."
(sqrt (+ (expt (- x2 (x left)) 2)
(expt (- y2 (y left)) 2))))
(defun random-co-ordinates (x-range y-range)
"Make random co-ordinates avoiding bell-curve point distribution."
;; Yay bignum!
(floor (random (+ x-range y-range))
x-range))
(defmethod random-point-in-bounds (x y width height)
"Make a point placed randomly within the given bounds."
(multiple-value-bind
(x-dist y-dist) (random-co-ordinates width height)
(make-instance 'point
:x (+ x x-dist)
:y (+ y y-dist))))
(defmethod translate-point ((p point) by-x by-y)
"Make a translated copy of the point."
(make-instance 'point
:x (+ (x p) by-x)
:y (+ (y p) by-y)))
(defmethod co-ordinates-at-angle-around-point-co-ordinates (a b r theta)
"Get the point on the circumference of the circle at theta."
(values (+ a (* r (cos theta)))
(+ b (* r (sin theta)))))
(defmethod co-ordinates-at-angle (obj theta)
"Get the point on the circumference of the arc/circle at theta.
Doesn't check limits of arc."
(co-ordinates-at-angle-around-point-co-ordinates (x obj) (y obj) (radius obj)
theta))
(defmethod angle-between-two-points-co-ordinates (x1 y1 x2 y2)
"Calculate the angle of the second point around the first."
(let ((dx (- x2 x1))
(dy (- y2 y1)))
(cond
((= dx 0.0)
(cond
((= dx 0.0) 0.0)
((> dy 0.0) (/ pi 2.0))
(t (* pi 2.0 3.0))))
((= dy 0.0)
(cond
((> dx 0.0) 0.0)
(t pi)))
(t
(cond
((< dx 0.0) (+ (atan (/ dy dx)) pi))
((< dy 0.0) (+ (atan (/ dy dx)) (* pi 2)))
(t (atan (/ dy dx))))))))
(defmethod angle-between-two-points ((p1 point) (p2 point))
"Calculate the angle of the second point around the first."
(angle-between-two-points-co-ordinates (x p1) (y p1) (x p2) (y p2)))
(defmethod highest-leftmost-of ((p1 point) (p2 point))
"Compare and return the highest leftmost point."
(if (or (> (y p1) (y p2))
(and (= (y p1) (y p2))
(< (x p1) (x p2))))
p1
p2))
(defmethod highest-leftmost-point (the-points)
"The highest point, or highest and leftmost point (if several are highest)."
(let ((highest (aref the-points 0)))
(dotimes (i (length the-points))
(let ((pt (aref the-points i)))
(setf highest (highest-leftmost-of pt highest))))
highest))
(defmethod point-line-side (p0 p2 p1)
"Find out which side of an infinite line through p1 and p2 that p0 lies on.
< 0 = left, > 0 = right, == 0 = exactly on."
(- (* (- (x p1) (x p0)) (- (y p2) (y p0)))
(* (- (x p2) (x p0)) (- (y p1) (y p0)))))
(defmethod furthest-point (p points &key ((:exclude exclude) '()))
"Return the point that is furthest from p"
(let ((candidate nil)
(candidate-distance -1.0))
(dovector (pp points)
(let ((ppd (distance p pp)))
(when (and (> ppd candidate-distance)
(not (member pp exclude)))
(setf candidate pp)
(setf candidate-distance ppd))))
candidate))
(defmethod closest-point (p points &key ((:exclude exclude) '()))
"Return the point that is closest to p."
(let ((candidate nil)
(candidate-distance 99999999.0))
(dolist (pp points)
(let ((ppd (distance p pp)))
(when (and (< ppd candidate-distance)
(not (member pp exclude)))
(setf candidate pp)
(setf candidate-distance ppd))))
candidate))
(defmethod points-closer-than (p points dist &key ((:exclude exclude) '()))
"Return any points closer to p than dist."
(let ((results '()))
(dolist (pp points)
(when (and (< (distance p pp) dist)
(not (member pp exclude)))
(push pp results)))
results))
(defmethod sort-points-by-distance ((p point) points)
"Return a copy of points sorted by distance from p."
(sort (copy-seq points)
(lambda (a b) (< (distance p a)
(distance p b)))))
(defmethod n-closest-points (p points num &key ((:exclude exclude) '()))
"Return num points closest to p (or all if less than num)."
(subseq (sort-points-by-distance p (set-difference points exclude))
0
(min num (length points))))
(defmethod all-points-leftp (p q the-points)
"Are all points to the left of or colinear with pq?"
(loop for pp across the-points
when (> (point-line-side pp p q) 0)
do (return nil)
finally (return t)))
(defmethod point-with-all-left (p points)
"Return the point q that all other points lie to the left of the line pq.
In the case of colinear points, returns the furthest point."
(let ((candidates (make-vector 10)))
(loop for candidate across points
when (all-points-leftp p candidate points)
do (vector-push-extend candidate candidates))
(furthest-point p candidates))) | 6,465 | Common Lisp | .lisp | 160 | 34.25625 | 79 | 0.614638 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 629f2ce6756eef9c9bd403b25244a4a08ad5f3f8a254af10feb92f44e98e0ce1 | 17,543 | [
-1
] |
17,544 | circle.lisp | rheaplex_rheart/draw-something/circle.lisp | ;; circle.lisp - A 2D circle.
;; Copyright (C) 2006 Rhea Myers [email protected]
;;
;; This file is part of draw-something.
;;
;; draw-something is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3 of the License, or
;; (at your option) any later version.
;;
;; draw-something is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;(in-package "DRAW-SOMETHING")
(defclass circle ()
((x :accessor x
:type float
:initform 0.0
:initarg :x
:documentation "The x co-ordinate of the circle centre.")
(y :accessor y
:type float
:initform 0.0
:initarg :y
:documentation "The y co-ordinate of the circle centre.")
(radius :accessor radius
:type float
:initform 0.0
:initarg :radius
:documentation "The radius of the circle."))
(:documentation "A simple circle."))
(defmethod distance ((p point) (c circle))
"The distance from a point to a polyline. Negative is inside circle."
(- (distance-point-co-ordinates p (x c) (y c))
(radius c)))
(defmethod highest-leftmost-point ((c circle))
"The highest point of the circle."
(make-instance 'point :x (x c) :y (+ (y c) (radius c)))) | 1,619 | Common Lisp | .lisp | 42 | 35.166667 | 73 | 0.69695 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 6d8d944eae6b8540cb1f9325f730ec571db71641460f5b146ea87567887caf5a | 17,544 | [
-1
] |
17,545 | run.lisp | rheaplex_rheart/draw-something/run.lisp | ;; run.lisp - Load the asdf system and make a drawing
;; Copyright (C) 2004 Rhea Myers [email protected]
;;
;; This file is part of draw-something.
;;
;; draw-something is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3 of the License, or
;; (at your option) any later version.
;;
;; draw-something is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;(load "draw-something.asd")
;;(asdf:operate 'asdf:load-op :draw-something)
(load "load")
(run)
(quit) | 914 | Common Lisp | .lisp | 22 | 40.272727 | 73 | 0.746352 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 9c514ba054c18e8c6f36435f884fef51d5a0744c5d7af8d5932d30f9db280853 | 17,545 | [
-1
] |
17,546 | postscript.lisp | rheaplex_rheart/draw-something/postscript.lisp | ;; postscript.lisp - Writing PostScript to streams.
;; Copyright (C) 2006 Rhea Myers [email protected]
;;
;; This file is part of draw-something.
;;
;; draw-something is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3 of the License, or
;; (at your option) any later version.
;;
;; draw-something is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;(in-package "DRAW-SOMETHING")
(defvar *ps-stream* t)
(defmethod write-eps-header (width height &key (to *ps-stream*))
"Write the standard raw PostScript header."
(format to "%!PS-Adobe-3.0 EPSF-3.0~%")
(format to "%%BoundingBox: 0 0 ~a ~a~%" width height)
(format to "/L {lineto} bind def~%/M {moveto} bind def~%"))
(defmethod write-eps-footer (&key (to *ps-stream*))
"Write the standard (but optional PostScript footer"
(format to "%%EOF~%"))
(defmethod write-rgb (r g b &key (to *ps-stream*))
"Set the PostScript RGB colour value."
(format to "~F ~F ~F setrgbcolor~%" r g b))
(defmethod write-colour ((col colour) &key (to *ps-stream*))
(multiple-value-bind (r g b) (hsb-to-rgb col)
(write-rgb r g b :to to)))
(defmethod write-close-path (&key (to *ps-stream*))
"Close the current PostScript path by drawing a line between its endpoints."
(format to "closepath~%"))
(defmethod write-stroke (&key (to *ps-stream*))
"Stroke the current PostScript path."
(format to "stroke~%"))
(defmethod write-fill (&key (to *ps-stream*))
"Fill the current PostScript path."
(format to "fill~%"))
(defmethod write-new-path (&key (to *ps-stream*))
"Start a new PostScript path."
(format to "newpath~%"))
(defmethod write-moveto (x y &key (to *ps-stream*))
"Move the PostScript pen to the given co-ordinates"
(format to "~,3F ~,3F M " x y))
(defmethod write-lineto (x y &key (to *ps-stream*))
"Draw a line with the PostScript pen to the given co-ordinates"
(format to "~,3F ~,3F L " x y))
(defmethod write-subpath (points &key (to *ps-stream*))
"Write a subpath of a PostScript path."
(write-moveto (x (aref points 0))
(y (aref points 0))
:to to)
(do ((i 1 (+ i 1)))
((= i (length points)))
(write-lineto (x (aref points i))
(y (aref points i))
:to to)))
(defmethod write-rectfill ((rect rectangle) &key (to *ps-stream*))
"Draw a rectangle with the given co-ordinates and dimensions."
(format to "~F ~F ~F ~F rectfill~%" (x rect) (y rect) (width rect)
(height rect)))
(defmethod write-rectstroke ((rect rectangle) &key (to *ps-stream*))
"Draw a rectangle with the given co-ordinates and dimensions."
(format to "~F ~F ~F ~F rectstroke~%" (x rect) (y rect) (width rect)
(height rect)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Drawing writing
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmethod write-form-skeleton ((f form) ps)
"Write the skeleton the drawing is made around."
(write-rgb 0.4 0.4 1.0 :to ps)
(write-new-path :to ps)
(write-subpath (points (skeleton f)) :to ps)
(write-stroke :to ps))
(defmethod write-form-fill ((f form) ps)
"Write the drawing outline."
(write-colour (fill-colour f) :to ps)
(write-new-path :to ps)
(write-subpath (points (outline f)) :to ps)
(write-fill :to ps))
(defmethod write-form-stroke ((f form) ps)
"Write the drawing outline."
(write-rgb 0.0 0.0 0.0 :to ps)
;;(write-rectstroke (bounds f) :to ps)
(write-new-path :to ps)
(write-subpath (points (outline f)) :to ps)
(write-stroke :to ps))
(defmethod write-form ((f form) ps)
"Write the form."
(write-form-fill f ps)
;;(write-figure-skeleton fig ps)
;;(write-form-stroke f ps)
)
(defmethod write-figure ((fig figure) ps)
"Write the figure for early multi-figure versions of draw-something."
;;(write-rgb 0.0 0.0 0.0 :to ps)
;;(write-rectstroke (bounds fig) :to ps)
;;(write-stroke :to ps)
(loop for fm across (forms fig)
do (write-form fm ps)))
(defmethod write-ground ((the-drawing drawing) ps)
"Colour the drawing ground."
(write-colour (ground the-drawing) :to ps)
(write-rectfill (bounds the-drawing) :to ps))
(defmethod write-frame ((the-drawing drawing) ps)
"Frame the drawing. Frame is bigger than PS bounds but should be OK."
(write-rectstroke (inset-rectangle (bounds the-drawing) -1)
:to ps))
(defmethod eps-write-drawing ((name string) (the-drawing drawing))
"Write the drawing"
(advisory-message (format nil "Writing drawing to file ~a .~%" name))
(ensure-directories-exist save-directory)
(with-open-file (ps name :direction :output
:if-exists :supersede)
(write-eps-header (width (bounds the-drawing))
(height (bounds the-drawing))
:to ps)
(write-ground the-drawing ps)
;;(write-frame the-drawing ps)
(loop for plane across (planes the-drawing)
do (loop for fig across (figures plane)
do (write-figure fig ps)))
(write-eps-footer :to ps)
(pathname ps)))
(defmethod eps-display-drawing (filepath)
"Show the drawing to the user in the GUI."
(let ((command
#+(or macos macosx darwin) "/usr/bin/open"
#-(or macos macosx darwin) "/usr/bin/gv"))
#+sbcl (sb-ext:run-program command (list filepath) :wait nil)
#+openmcl (ccl::os-command (format nil "~a ~a" command filepath)))
filepath)
(defmethod write-and-show-eps ((the-drawing drawing))
"Write and display the drawing as an eps file."
(advisory-message "Saving and viewing drawing as eps.~%")
(eps-display-drawing (eps-write-drawing (generate-filename)
the-drawing))) | 6,168 | Common Lisp | .lisp | 141 | 39.340426 | 80 | 0.649058 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 0a39bc4f3a56149ec6686755f0fc855df81b40543a2f8ca58d2eed37a898ce3a | 17,546 | [
-1
] |
17,547 | codelet.lisp | rheaplex_rheart/draw-something/codelet.lisp | ;; codelet.lisp - Codelets and the coderack.
;; Copyright (C) 2006 Rhea Myers [email protected]
;;
;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 2 of the License, or
;; (at your option) any later version.
;;
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program; if not, write to the Free Software
;; Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
;; Fluid Concepts & Creative Analogies notes:
;; - Platonet, slipnet, workspace, coderack.
;; p223 - How codekets are added.
;; p415 - Variations in perception.
(in-package "DRAW-SOMETHING")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defconstant maximum-urgency 100)
(defconstant minimum-urgency 1)
(defconstant maximum-number-of-codelets 100)
(defconstant number-of-ticks-per-pruning 10)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defclass codelet ()
((action :accessor action
:type symbol
:initarg :action
:documentation "The method to call.")
(arguments :accessor arguments
:type list
:initform '()
:initarg :arguments
:documentation "The arguments to pass to the method.")
(category :accessor category
:type symbol
:initform 'general
:initarg :category
:documentation "The category of the codelet.")
(urgency :accessor urgency
:type integer
:initform minimum-urgency
:initarg :urgency
:documentation "The urgency of the codelet.")
(created :accessor created
:type integer
:initarg :created
:documentation "The creation time of the codelet."))
(:documentation "A codelet."))
(defclass coderack ()
((codelets :accessor codelets
:type vector
:initform (make-vector maximum-number-of-codelets)
:documentation "The codelets.")
(time :accessor codelet-ticks
:type integer
:initform 0
:documentation "The number of ticks (run loop cycles) that have run.")
(should-continue :accessor should-continue
:initform t
:documentation "Whether the codelrt loop should continue."))
(:documentation "The coderack."))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmethod should-finish-running ((rack coderack))
(setf (should-continue rack) nil))
(defmethod advance-codelet-ticks ((rack coderack))
(incf (codelet-ticks rack)))
(defmethod should-prune-codelets ((rack coderack))
"Check whether it's time to prune again."
(mod (codelet-ticks rack) number-of-ticks-per-pruning))
(defmethod add-codelet-to-coderack ((c codelet) (rack coderack))
"Add the codelet to the list."
(advisory-message (format nil "Adding: ~a~%" (string-downcase (string (action c)))))
(vector-push-extend c (codelets rack)))
(defmethod add-codelet ((rack coderack) action urgency category &rest arguments)
"Make and add the codelet to the list."
(add-codelet-to-coderack (make-instance 'codelet
:action action
:arguments arguments
:category category
:urgency urgency
:created (codelet-ticks rack))
rack))
(defmethod remove-codelet ((rack coderack) i)
"Remove the codelet from the vector, filling the resulting hole."
(if (< i (1- (fill-pointer (codelets rack))))
(setf (aref (codelets rack) i)
(aref (codelets rack) (1- (fill-pointer (codelets rack))))))
(decf (fill-pointer (codelets rack))))
(defmethod remove-codelets-matching ((rack coderack) predicate)
"Remove all codelets that predicate returns t for."
(loop for i from 0 to (length rack)
when (apply predicate (aref rack i))
do (remove-codelet rack i)))
(defmethod codelet-should-run ((rack coderack) (c codelet))
"Probabilistically decide whether the codelet should run."
t) ;; todo
(defmethod run-codelet ((c codelet))
"Run the codelet."
(advisory-message (format nil "Running: ~a~%" (string-downcase (string (action c)))))
(apply #'funcall (action c) (arguments c)))
(defmethod run-one-codelet ((rack coderack))
"Run one codelet."
;; Make sure we run exactly one?
(dotimes (i (length (codelets rack)))
(let ((candidate (aref (codelets rack) i)))
(when (codelet-should-run rack candidate)
(run-codelet candidate)
(remove-codelet rack i)
(return)))))
(defmethod random-urgency ()
"A random urgency."
(random-range minimum-urgency maximum-urgency))
(defmethod codelet-age ((c codelet) (rack coderack))
"The age of the codelet."
(- (codelet-ticks rack) (created c)))
(defmethod should-remove-codelet ((c codelet))
"Should the codelet be removed? Weighted random choice."
(> (random-urgency)
(/ (urgency c)
(codelet-age c))))
(defmethod prune-codelets ((rack coderack))
"Randomly remove codelets that are too old and low priority."
(let ((to-remove (make-vector 10)))
(dotimes (i (length (codelets rack)))
(let ((c (aref (codelets rack) i)))
(when (should-remove-codelet c)
(format t "Removing: ~a~%" (string-downcase (string (action c))))
(vector-push-extend i to-remove))))
(dolist (remove to-remove)
(remove-codelet rack remove))))
(defmethod initialise-coderack ((rack coderack) the-drawing)
"Populate the coderack with the initial codelets."
;; Randomly add n. codelets
;; Ones that locate various sizes of wide/tall/equalish space
;; The codelets spawn figure-making codelets
;; Which spawn skeleton-making codelets
;; Which spawn drawing codelets
;; Which then call finish
;; this is just deterministic, go probabilistic for 0.5
(dotimes (i (random-range min-figures max-figures))
(add-figure-making-codelet rack the-drawing)))
(defmethod draw-loop-step ((rack coderack) the-drawing)
"One step of the loop"
(declare (ignore the-drawing))
;;(when (should-prune-codelets)
;; (prune-coderack coderack))
;;add new codelets from figures & from ongoing list to add
(run-one-codelet rack))
(defmethod coderack-draw-loop ((rack coderack) the-drawing)
"Run until complete."
(loop while (should-continue rack)
do (draw-loop-step rack the-drawing)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Specific codelets
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmethod figure-making-codelet ((rack coderack) the-drawing)
"Replace with space finder, form-adder, etc."
(add-figure-drawing-codelet rack the-drawing (make-figure the-drawing)))
(defmethod add-figure-making-codelet ((rack coderack) the-drawing)
"Add a codelet to make the figure."
(add-codelet rack 'figure-making-codelet 100 'drawing rack the-drawing))
(defmethod figure-drawing-codelet ((rack coderack) the-drawing fig)
"Draw the figure. Replace with various."
(draw-figure the-drawing fig)
(when (= (length (codelets rack)) 1)
(should-finish-running rack)))
(defmethod add-figure-drawing-codelet ((rack coderack) the-drawing fig)
"Add a codelet to draw the figure."
(add-codelet rack 'figure-drawing-codelet 100 'drawing rack
the-drawing fig))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Loop until drawing-finished
;; Coderack empty? post initial set of codelets
;; Steps modulo prune-steps? prune
;; Do one step, running a codelet
;; Temperature?
;; Dealing with snags?
;; Allow deletion of *drawn* "structures"?
;; Initial codelets:
;; Space finders, drawers, adorners
;; Find space
;; Find interesting figures to relate to
;; Add "system" to figure
;; Maybe start non-overlapping figure
;; Maybe start overlapping figure
;; Maybe start adornments on figure
;; Maybe start figure relating to figure
;; a grid or mirror or radial or other compositional arrangement
;; Maybe stop new figure generation, removing all possible figure generators
;; maybe start generating skeleton
;; Maybe add skeleton line according to notes on skeleton, or maybe change
;; Maybe mark skeleton as finished
;; Maybe start drawing
;; Maybe set ground colour
;; Maybe set figure colour
;; Maybe identify position for new figure based on existing figures
;; Maybe check to see if drawing is finished
;; &c
;; Codelets can post another codelet(s), remove codelets, add notes
;; create skeletons, draw outlines or fills, add other structures
;; The drawing can have skeletons, fills, outlines, negative space,
;; compositional guides, potential places for figures, and so on as objects
;; It is the workspace
;; -->
;; Grid of coarse cells, or grid of points to start expanding a hull at? | 8,965 | Common Lisp | .lisp | 209 | 39.708134 | 87 | 0.689172 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 244372ca548cafe8ad44ef5d6260c436a6f6593e6c836b6b09a554fe7076812a | 17,547 | [
-1
] |
17,548 | rectangle.lisp | rheaplex_rheart/draw-something/rectangle.lisp | ;; rectangle.lisp - A 2D rectangle.
;; Copyright (C) 2006 Rhea Myers [email protected]
;;
;; This file is part of draw-something.
;;
;; draw-something is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3 of the License, or
;; (at your option) any later version.
;;
;; draw-something is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;(in-package "DRAW-SOMETHING")
(defclass rectangle ()
((x :accessor x
:type float
:initform 0.0
:initarg :x
:documentation "The lower left x co-ordinate of the rectangle.")
(y :accessor y
:type float
:initform 0.0
:initarg :y
:documentation "The lower left y co-ordinate of the rectangle.")
(width :accessor width
:type float
:initform 0.0
:initarg :width
:documentation "The width of the rectangle.")
(height :accessor height
:type float
:initform 0.0
:initarg :height
:documentation "The height of the rectangle."))
(:documentation "A simple rectangle"))
(defmethod copy-rectangle ((r rectangle))
"Make a copy of the rectangle."
(make-instance 'rectangle
:x (x r) :y (y r) :width (width r) :height (height r)))
(defmethod random-point-in-rectangle ((bounds-rect rectangle))
"Make a point placed randomly within the given bounding rectangle."
(make-instance 'point
:x (+ (x bounds-rect) (random (width bounds-rect)))
:y (+ (y bounds-rect) (random (height bounds-rect)))))
(defmethod random-points-in-rectangle ((bounds-rect rectangle) count)
"Create the specified number of points placed randomly within the given rectangle."
(map-into (make-vector count)
(lambda ()(random-point-in-rectangle bounds-rect))))
(defmethod random-rectangle-in-rectangle ((bounds-rect rectangle))
"Make a random rectangle of at least size 1x1 in another rectangle."
(let* ((new-width (random (width bounds-rect)))
(new-height (random (height bounds-rect)))
(new-x (+ (x bounds-rect)
(random (- (width bounds-rect) new-width))))
(new-y (+ (y bounds-rect)
(random (- (height bounds-rect) new-height)))))
(make-instance 'rectangle
:x new-x
:y new-y
:width new-width
:height new-height)))
(defmethod random-rectangle-in-rectangle-size (in new-width new-height)
"Make a random rectangle of the given size in the given bounds."
(assert (<= new-width (width in)))
(assert (<= new-height (height in)))
(let ((new-x (+ (x in)
(random-number (- (width in) new-width))))
(new-y (+ (y in)
(random-number (- (height in) new-height)))))
(make-instance 'rectangle
:x new-x
:y new-y
:width new-width
:height new-height)))
(defmethod random-rectangle-in-rectangle ((bounds-rect rectangle))
"Make a random rectangle of at least size 1x1 in another rectangle."
(let* ((new-width (random (width bounds-rect)))
(new-height (random (height bounds-rect)))
(new-x (+ (x bounds-rect)
(random (- (width bounds-rect) new-width))))
(new-y (+ (y bounds-rect)
(random (- (height bounds-rect) new-height)))))
(make-instance 'rectangle
:x new-x
:y new-y
:width new-width
:height new-height)))
(defmethod inset-rectangle ((source rectangle) (offset real))
"Trim a rectangle by the given amount."
(make-instance 'rectangle
:x (+ (x source) offset)
:y (+ (y source) offset)
:width (- (width source) (* offset 2.0))
:height (- (height source) (* offset 2.0))))
(defmethod area ((rect rectangle))
"Get the rectangle's area."
(* (width rect) (height rect)))
(defmethod contains-point-co-ordinates ((rect rectangle) x y)
"Find whether the rectangle contains the point."
(if (and (> x (y rect))
(< x (+ (x rect) (width rect)))
(> y (y rect))
(< y (+ (y rect) (height rect))))
t
nil))
(defmethod contains ((rect rectangle) (p point))
"Find whether the rectangle contains the point."
(contains-point-co-ordinates rect (x p) (y p)))
(defmethod points-in-rectangle ((rect rectangle) (points vector))
"Get the vector of points within the rectangle"
(let ((contained (vector 1)))
(loop for p across points
when (contains rect p)
do (vector-push-extend contained p))
contained))
(defmethod intersects ((rect1 rectangle) (rect2 rectangle))
"Find whether the rectangles intersect."
(and (< (x rect1) (+ (x rect2) (width rect2)))
(< (y rect1) (+ (y rect2) (height rect2)))
(> (+ (x rect1) (width rect1)) (x rect2))
(> (+ (y rect1) (height rect1)) (y rect2))))
(defmethod include-point ((rect rectangle) (p point))
"Destructively expand the rectangle to include the point."
(let ((right (+ (x rect) (width rect)))
(top (+ (y rect) (height rect))))
(cond
((< (x p) (x rect))
(setf (width rect)
(+ (width rect) (- (x rect) (x p))))
(setf (x rect) (x p)))
((> (x p) right)
(setf (width rect)
(+ (width rect) (- (x p) right))))
((< (y p) (y rect))
(setf (height rect)
(+ (height rect) (- (y rect) (y p))))
(setf (y rect) (y p)))
((> (y p) top)
(setf (height rect)
(+ (height rect) (- (y p) top)))))))
(defmethod include-rectangle ((rect rectangle) (include rectangle))
"Expand the first rectangle to include the second."
(include-point rect (make-instance 'point :x (x include) :y (y include)))
(include-point rect (make-instance 'point :x (x include)
:y (+ (y include) (height include))))
(include-point rect (make-instance 'point :x (+ (x include) (width include))
:y (+ (y include) (height include))))
(include-point rect (make-instance 'point :x (+ (x include) (width include))
:y (y include))))
(defmethod rectangle-from-point ((p point))
"Make a zero-size rectangle for a point."
(make-instance 'rectangle :x (x p) :y (y p) :width 0.0 :height 0.0))
(defmethod random-point-on-rectangle ((r rectangle))
"Make a random point somewhere on the border of a rectangle."
(case (random 4)
(0 (random-point-on-line
(make-instance 'line
:from (make-instance 'point
:x (x r)
:y (y r))
:to (make-instance 'point
:x (x r)
:y (+ (y r)
(height r))))))
(1 (random-point-on-line
(make-instance 'line
:from (make-instance 'point
:x (x r)
:y (+ (y r)
(height r)))
:to (make-instance 'point
:x (+ (x r)
(width r))
:y (+ (y r)
(height r))))))
(2 (random-point-on-line
(make-instance 'line
:from (make-instance 'point
:x (+ (x r)
(width r))
:y (+ (y r)
(height r)))
:to (make-instance 'point
:x (+ (x r)
(width r))
:y (y r)))))
(3 (random-point-on-line
(make-instance 'line
:from (make-instance 'point
:x (+ (x r)
(width r))
:y (y r))
:to (make-instance 'point
:x (x r)
:y (y r)))))))
(defmethod random-points-on-rectangle ((r rectangle) count)
"Generate count points on a rectangle's outline. These will not be ordered."
(map-into (make-vector count) (lambda () (random-point-on-rectangle r))))
(defmethod random-points-at-rectangle-corners ((r rectangle) count)
"Return from 0 to 4 corner points of a rectangle, clamping out-of-range."
;; Inefficient but easy to code and easy to read ;-]
(choose-n-of count
(vector (make-instance 'point
:x (x r)
:y (y r))
(make-instance 'point
:x (x r)
:y (+ (y r) (height r)))
(make-instance 'point
:x (+ (x r) (width r))
:y (+ (y r) (height r)))
(make-instance 'point
:x (+ (x r) (width r))
:y (y r))))) | 8,184 | Common Lisp | .lisp | 219 | 32.063927 | 85 | 0.621928 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | cd13575eee5e494ee6763cc5f2a8481e8f6d39d4a645139dbba2ea869db85bab | 17,548 | [
-1
] |
17,549 | colour.lisp | rheaplex_rheart/draw-something/colour.lisp | ;; colour.lisp - Colour handling.
;; Copyright (C) 2006 Rhea Myers [email protected]
;;
;; This file is part of draw-something.
;;
;; draw-something is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3 of the License, or
;; (at your option) any later version.
;;
;; draw-something is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;(in-package "DRAW-SOMETHING")
(defclass colour ()
((hue :accessor hue
:initform 1.0
:initarg :hue
:documentation "The colour-wheel hue of the colour.")
(saturation :accessor saturation
:initform 1.0
:initarg :saturation
:documentation "The saturation of the colour.")
(brightness :accessor brightness
:initform 1.0
:initarg :brightness
:documentation "The brightness of the colour."))
(:documentation "A colour"))
(defmethod random-colour ()
"Make a random colour."
(make-instance 'colour :hue (random 1.0) :saturation (random 1.0)
:brightness (random 1.0)))
(defmethod hsb-to-rgb ((col colour))
"Convert the hue/saturation/brightness colour to RGB."
(if (= (saturation col) 0)
(values-list (list (brightness col) (brightness col) (brightness col)))
(let* ((p (* (brightness col)
(- 1.0
(saturation col))))
(q (* (brightness col)
(- 1.0
(* (saturation col) (hue col)))))
(tt (* (brightness col)
(- 1.0
(* (saturation col)
(- 1.0 (hue col)))))))
(case (floor (* (hue col) 5.0))
((0) (values-list (list (brightness col) tt p))) ;; Red
((1) (values-list (list q (brightness col) p))) ;; Yellow
((2) (values-list (list p (brightness col) tt))) ;; Green
((3) (values-list (list p q (brightness col)))) ;; Cyan
((4) (values-list (list tt p (brightness col)))) ;; Blue
((5) (values-list (list (brightness col) p q))))))) ;; Magenta
| 2,238 | Common Lisp | .lisp | 57 | 36.052632 | 77 | 0.67616 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | df6798e10fde5a6095b09cc89424edffd200e88d29137651b712c4af1796caa4 | 17,549 | [
-1
] |
17,550 | plane.lisp | rheaplex_rheart/draw-something/plane.lisp | ;; plane.lisp - A plane (layer, level, plane) in the drawing.
;; Copyright (C) 2006 Rhea Myers [email protected]
;;
;; This file is part of draw-something.
;;
;; draw-something is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3 of the License, or
;; (at your option) any later version.
;;
;; draw-something is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;(in-package "DRAW-SOMETHING")
(defconstant min-planes 1)
(defconstant max-planes 5)
(defconstant min-figures 3)
(defconstant max-figures 9)
(defclass plane ()
((figure-policy :accessor figure-policy
:initarg :figure-policy
:documentation "The function for generating figures.")
(figures :accessor figures
:initform (make-vector 10)
:documentation "The figures of the plane.")
(figure-count :accessor figure-count
:type integer
:initarg :figure-count
:documentation "The number of figures to make for the plane.")
(pen :accessor plane-pen
;;:type pen
:initarg :pen
:documentation "The pen properties for the plane."))
(:documentation "A plane of the drawing."))
(defconstant plane-pen-distance-minimum 0.1)
(defconstant plane-pen-distance-maximum 5.0)
(defconstant plane-pen-tolerance-minimum (/ plane-pen-distance-minimum 2.0))
(defconstant plane-pen-tolerance-maximum (/ plane-pen-distance-maximum 2.0))
(defmacro make-plane-pen (plane-index num-planes)
"Make a pen for the plane."
#|(let ((plane-factor (* (/ 1.0 (- num-planes 1))
plane-index)))
(make-instance 'pen
:distance (+ plane-pen-distance-minimum
(* plane-factor
(- plane-pen-distance-maximum
plane-pen-distance-minimum )))
:step 1.0
:tolerance (+ plane-pen-tolerance-minimum
(* plane-factor
(- plane-pen-tolerance-maximum
plane-pen-tolerance-minimum ))))))|#
nil)
(defconstant minimum-number-of-planes 1)
(defconstant maximum-number-of-planes (length figure-generation-method-list))
(defmethod number-of-planes ()
"Decide how many planes to have"
(random-range minimum-number-of-planes
maximum-number-of-planes))
(defmethod number-of-figures-for-plane (plane-index)
"Randomly determine how many figures a plane should have."
(random-range 2 10))
(defmethod make-planes ((d drawing) count)
"Make the planes, ready to have skeletons for figures generated."
(advisory-message "Making planes.~%")
(loop for point-method in (figure-generation-methods count)
for i from 0 below count
do (advisory-message (format nil "Making plane ~d.~%" (+ i 1)))
do (vector-push-extend
(make-instance 'plane
:figure-count (number-of-figures-for-plane i)
:figure-policy point-method
:pen (make-plane-pen i count))
(planes d))))
(defmethod make-plane-skeletons ((l plane) (d drawing))
"Generate the skeletons for the figures of the plane."
(advisory-message "Making plane skeleton(s).~%")
(setf (figures l)
(funcall (figure-policy l)
(composition-points d))))
(defmethod make-planes-skeletons ((d drawing))
"Generate the skeletons for the figures of each plane."
(advisory-message "Making planes skeletons.~%")
(loop for l across (planes d)
do (make-plane-skeletons l d)))
(defmethod draw-plane-figures ((l plane))
"Draw around the skeletons of the figures of the plane."
(advisory-message "Drawing plane figure(s).~%")
(loop for fig across (figures l)
do (draw-figure fig))) ;; (pen l)
(defmethod draw-planes-figures ((d drawing))
"Draw around the skeletons of the figures of each plane."
(advisory-message "Drawing planes figures.~%")
(loop for l across (planes d)
do (draw-plane-figures l)))
#|(defmethod make-figure-for-plane ((figure-bounds rectangle) (plane integer))
(let* ((form-width (/ (width figure-bounds) plane))
(form-height (/ (height figure-bounds) plane)))
(make-figure figure-bounds form-width form-height)))
(defmethod make-figures ((the-drawing drawing))
"Make the figures for the drawing."
(let ((figure-count (random-range-inclusive min-figures max-figures)))
(advisory-message (format nil "Making ~a figures.~%"
figure-count))
(loop for i from 1 to figure-count
do (advisory-message (format nil "Making figure ~a/~a.~%" i
figure-count))
do (add-figure the-drawing
(make-figure-for-plane (bounds the-drawing) i)))))|# | 4,766 | Common Lisp | .lisp | 113 | 38.761062 | 78 | 0.719491 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 40af71136857e6658b63028ac9dc1f731963ffddf7ad33983c428f5b9f06f72b | 17,550 | [
-1
] |
17,551 | web.lisp | rheaplex_rheart/draw-something/web.lisp | ;; web.lisp - Web generator version of draw-something.
;; Copyright (C) 2009 Rhea Myers [email protected]
;;
;; This file is part of draw-something.
;;
;; draw-something is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3 of the License, or
;; (at your option) any later version.
;;
;; draw-something is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;(in-package "DRAW-SOMETHING")
;;TODO - Write then swap all files?
;;TODO - Can this be AGPL and the rest of the package GPL unless this is used?
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Load code and libraries
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(load "load")
(require 'cl-ppcre)
(require 'gzip-stream)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Configuration
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Set the value of save-directory *before* loading this or draw-something
;; and they'll share it
(defvar save-directory ".")
(defparameter +index-file-path+ (format nil "~a/index.html" save-directory))
(defparameter +rss-file-path+ (format nil "~a/rss.xml" save-directory))
(defparameter +web-page-count+ 2)
(defparameter +rss-entry-count+ 10)
(defparameter +svg-extention+ ".svgz")
(defparameter +svg-extention-length+ (length +svg-extention+))
(defparameter +rss-header+ "<?xml version=\"1.0\" encoding=\"utf-8\"?>
<rss version=\"2.0\" xmlns:atom=\"http://www.w3.org/2005/Atom\">
<channel>
<title>draw-something</title>
<link>https://rhea.art/draw-something/</link>
<atom:link href=\"https://rhea.art/draw-something/rss.xml\" rel=\"self\" type=\"application/rss+xml\" />
<description>Images by draw-something.</description>
<language>en</language>
")
(defparameter +rss-footer+ " </channel>
</rss>
")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Utilities
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun ends-with (source target)
"Check whether the source string ends with the target string"
(= (search target source :from-end t)
(length source)))
(defun slurp-gzip-file (file-path)
"Slurp the contents of the file into a string"
(gzip-stream:with-open-gzip-file (stream file-path)
(with-output-to-string (str)
(loop for char = (read-char stream nil nil)
while char
do (write-char char str))
str)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Names
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun html-svg-filename (svg-filename)
"Change an .svg extention to an .html extention"
(format nil "~a.html" (pathname-name svg-filename)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; SVG Tag writing
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun get-svg-dimensions (svg-filename)
"Get the width and height of the svg file"
(let ((file-text (slurp-gzip-file svg-filename)))
(cl-ppcre:register-groups-bind
(width height)
("width=\"([0-9]+)[^\"]*\" height=\"([0-9]+)[^\"]*\"" file-text)
(values width height))))
(defun write-svg-tag (html-file svg-filename)
(with-open-file (svg-file svg-filename)
(multiple-value-bind (width height) (get-svg-dimensions svg-filename)
(format html-file "<p align=\"center\"><embed src=\"~a~a\" width=\"~a\" height=\"~a\" /></p>~%"
(pathname-name svg-filename) +svg-extention+ width height))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; HTML Generation
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun write-link (html-file text link)
"Write the html link, or just the label if the link is null"
(if link
(format html-file "<a href=\"~a\">~a</a>" link text)
(format html-file "~a" text)))
(defun write-links (html-file previous-html-file next-html-file)
"Write the next and previous links (or placeholders for first/last files)"
(format html-file "<p align=\"center\">")
(write-link html-file "next" next-html-file)
(format html-file " ")
(write-link html-file "index" "index.html")
(format html-file " ")
(write-link html-file "previous" previous-html-file)
(format html-file "</p>~%"))
(defun write-web-page (svg-filename previous-html-file next-html-file)
"Write a web page to wrap an svg file, complete with links to next/prev"
(with-open-file (html-file (format nil "~a/~a" save-directory
(html-svg-filename svg-filename))
:direction :output
:if-exists :supersede)
(format html-file "<html><head><title>~a</title>
<link rel=\"alternate\" type=\"application/rss+xml\" title=\"RSS\" href=\"https://rhea.art/draw-something/drawings/rss.xml\" />
<link rel=\"StyleSheet\" href=\"style.css\" type=\"text/css\" media=\"all\">
</head><body>~%"
(pathname-name svg-filename))
(write-svg-tag html-file svg-filename)
;; YOU MUST CHANGE THE SOURCE LINK IF YOU MODIFY THIS CODE
(format html-file "<p align=\"center\"><a href=\"http://creativecommons.org/licenses/by-sa/3.0/\">Image licence - CC-BY-SA</a> <a href=\"https://rhea.art/git/?p=rheart.git;a=tree;f=draw-something\">Code licence - GPL 3 or higher.</a></p>~%")
(write-links html-file previous-html-file next-html-file)
(format html-file "</body></html>~%")))
(defun write-web-pages (svg-list next-html limit)
"Recursively generate (at most) the given number of web pages for svg files"
(when (and svg-list
(> limit 0))
(let ((html-filename (or next-html
(html-svg-filename (car svg-list))))
(prev-html (if (cadr svg-list) (html-svg-filename (cadr svg-list)))))
(write-web-page (car svg-list) prev-html next-html)
(write-web-pages (cdr svg-list) html-filename (1- limit)))))
(defun link-index-page (html-file-path)
"Make a link to the most recent html file as the index for the directory"
(sb-posix:unlink +index-file-path+)
(sb-posix:symlink html-file-path +index-file-path+))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; RSS Generation
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun rfc-822-time (universal-time)
"Return a string representing the universal-time in rfc 822 time format"
(multiple-value-bind (seconds minutes hours day month year day-of-the-week
daylight-savings-time-flag time-zone)
(decode-universal-time universal-time 0)
(declare (ignore day-of-the-week daylight-savings-time-flag time-zone))
(format nil "~a ~a ~a ~2,'0d:~2,'0d:~2,'0d GMT"
day
(nth (1- month)
'("Jan" "Feb" "Mar" "Apr"
"May" "Jun" "Jul" "Aug"
"Sep" "Oct" "Nov" "Dec"))
year hours minutes seconds)))
(defun file-rss-timestamp (file-path)
"Get a file's creation time in a format usable in an rss entry"
(rfc-822-time (file-write-date file-path)))
(defun write-rss-entry (rss-file svg-file)
"Write an rss entry for the svg file"
(let ((html-filename (html-svg-filename svg-file))
(basename (pathname-name svg-file)))
(format rss-file " <item>
<title>draw-something image ~a</title>
<link>https://rhea.art/draw-something/drawings/~a</link>
<guid>https://rhea.art/draw-something/drawings/~a</guid>
<pubDate>~a</pubDate>
<description><![CDATA[<p><a href=\"https://rhea.art/draw-something/drawings/~a\">draw-something image ~a</a></p>]]></description>
</item>
"
;; We use the svg file time as the html file may have been remade
basename html-filename html-filename (file-rss-timestamp svg-file)
html-filename basename)))
(defun write-rss-file (svg-filenames)
"Write the rss file listing the most recent html files"
(with-open-file (rss-file +rss-file-path+
:direction :output
:if-exists :supersede)
(format rss-file +rss-header+)
(loop for i below +rss-entry-count+
for svg-filename in svg-filenames
do (write-rss-entry rss-file svg-filename))
(format rss-file +rss-footer+)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Main flow of execution
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun run-draw-something ()
"An sbcl-specific wrapper to make draw-something useful as a script"
(let ((filepath (run)))
#+sbcl (sb-ext:run-program "/bin/gzip"
(list "--suffix" "z"
(namestring filepath))
:wait t))
;; Yes it would be better if we cached the svg info somehow
(let ((svg-files (reverse (directory (format nil "~a/*~a" save-directory
+svg-extention+)))))
(when svg-files
(write-web-pages svg-files nil +web-page-count+)
(link-index-page (html-svg-filename (car svg-files)))
(write-rss-file svg-files)))
#+sbcl (quit))
| 9,474 | Common Lisp | .lisp | 194 | 45.21134 | 256 | 0.592108 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | c96e4f9f9f57e920e2c92c4ec3bf898314057b6d99d1c0cc1be0910ac89c19f2 | 17,551 | [
-1
] |
17,552 | svg.lisp | rheaplex_rheart/draw-something/svg.lisp | ;; svg.lisp - Writing SVG to streams.
;; Copyright (C) 2007 Rhea Myers [email protected]
;;
;; This file is part of draw-something.
;;
;; draw-something is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3 of the License, or
;; (at your option) any later version.
;;
;; draw-something is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;(in-package "DRAW-SOMETHING")
(defvar *svg-stream* t)
(defmethod svg-header (width height &key (to *svg-stream*))
"Write the start of the SVG file."
(format to "<?xml version=\"1.0\" standalone=\"no\"?>~%")
(format to "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"~%")
(format to " \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">~%")
(format to "<svg width=\"~dpx\" height=\"~dpx\" viewBox=\"0 0 ~d ~d\"~%"
width height width height)
(format to "xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">~%"))
(defmethod svg-footer (&key (to *svg-stream*))
"Write the end of the svg file."
(format to "</svg>~%"))
(defmethod svg-rgb ((col colour) )
(multiple-value-bind (r g b) (hsb-to-rgb col)
(format nil "#~X2~X2~X2" (round (* r 15))
(round (* b 15)) (round (* b 15)))))
(defmethod svg-path-tag-start (&key (to *svg-stream*))
"Write the start of the path tag."
(format to "<path"))
(defmethod svg-path-tag-end (&key (to *svg-stream*))
"Write the start of the path tag."
(format to " />~%"))
(defmethod svg-path-d-start (&key (to *svg-stream*))
"Write the start of the path d."
(format to " d=\""))
(defmethod svg-path-d-end (&key (to *svg-stream*))
"Write the start of the path d."
(format to "\""))
(defmethod svg-fill ((col colour) &key (to *svg-stream*))
"Write the fill property."
(format to " fill=\"~a\" " (svg-rgb col)))
(defmethod svg-stroke ((col colour) &key (to *svg-stream*))
"Write the stroke property."
(format to " stroke=\"~a\" " (svg-rgb col)))
(defmethod svg-close-path (&key (to *svg-stream*))
"Close the current PostScript path by drawing a line between its endpoints."
(format to " z"))
(defmethod svg-moveto (x y &key (to *svg-stream*))
"Move the PostScript pen to the given co-ordinates"
(format to " M ~,3F ~,3F" x y))
(defmethod svg-lineto (x y &key (to *svg-stream*))
"Draw a line with the PostScript pen to the given co-ordinates"
(format to " L ~,3F ~,3F" x y))
(defmethod svg-subpath (points &key (to *svg-stream*))
"Write a subpath of a PostScript path."
(svg-moveto (x (aref points 0))
(y (aref points 0))
:to to)
(do ((i 1 (+ i 1)))
((= i (length points)))
(svg-lineto (x (aref points i))
(y (aref points i))
:to to)))
(defmethod svg-rectfill ((rect rectangle) (col colour) &key (to *svg-stream*))
"Draw a rectangle with the given co-ordinates and dimensions."
(format to
"<rect x=\"~F\" y=\"~F\" width=\"~F\" height=\"~F\" fill=\"~a\" />~%"
(x rect) (y rect) (width rect) (height rect) (svg-rgb col)))
(defmethod svg-rectstroke ((rect rectangle) (col colour)
&key (to *svg-stream*))
"Draw a rectangle with the given co-ordinates and dimensions."
(format to
"<rect x=\"~F\" y=\"~F\" width=\"~F\" height=\"~F\" stroke=\"~a\" />~%"
(x rect) (y rect) (width rect) (height rect) (svg-rgb col)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Drawing writing
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmethod svg-form-skeleton ((f form) ps)
"Write the skeleton the drawing is made around."
(svg-path-tag-start :to ps)
(svg-stroke (make-instance 'colour
:hue 0.3
:saturation 0.6
:brightness 0.6)
:to ps)
(svg-path-d-start :to ps)
(svg-subpath (points (skeleton f)) :to ps)
(svg-path-d-end :to ps)
(svg-path-tag-end :to ps))
(defmethod svg-form-fill ((f form) ps)
"Write the drawing outline."
(svg-path-tag-start :to ps)
(svg-fill (fill-colour f)
:to ps)
(svg-path-d-start :to ps)
(svg-subpath (points (outline f)) :to ps)
(svg-path-d-end :to ps)
(svg-path-tag-end :to ps))
(defmethod svg-form-stroke ((f form) ps)
"Write the drawing outline."
(svg-path-tag-start :to ps)
(svg-stroke (make-instance 'colour
:hue 0.0
:saturation 0.0
:brightness 0.0)
:to ps)
(svg-path-d-start :to ps)
(svg-subpath (points (outline f)) :to ps)
(svg-path-d-end :to ps)
(svg-path-tag-end :to ps))
(defmethod svg-form ((f form) ps)
"Write the form."
(svg-form-fill f ps)
;;(svg-figure-skeleton fig ps)
;;(svg-form-stroke f ps)
)
(defmethod svg-figure ((fig figure) ps)
"Write the figure for early multi-figure versions of draw-something."
;;(svg-rgb 0.0 0.0 0.0 :to ps)
;;(svg-rectstroke (bounds fig) :to ps)
;;(svg-stroke :to ps)
(loop for fm across (forms fig)
do (svg-form fm ps)))
(defmethod svg-ground ((the-drawing drawing) ps)
"Colour the drawing ground."
(svg-rectfill (bounds the-drawing) (ground the-drawing)
:to ps))
(defmethod svg-frame ((the-drawing drawing) ps)
"Frame the drawing. Frame is bigger than PS bounds but should be OK."
(svg-rectstroke (inset-rectangle (bounds the-drawing) -1)
(make-instance 'colour :brightness 0.0)
:to ps))
(defmethod svg-write-drawing ((name string) (the-drawing drawing))
"Write the drawing"
(advisory-message (format nil "Writing drawing to file ~a .~%" name))
(ensure-directories-exist save-directory)
(with-open-file (ps name :direction :output
:if-exists :supersede)
(svg-header (width (bounds the-drawing))
(height (bounds the-drawing))
:to ps)
(svg-ground the-drawing ps)
;;(svg-frame the-drawing ps)
(loop for plane across (planes the-drawing)
do (loop for fig across (figures plane)
do (svg-figure fig ps)))
(svg-footer :to ps)
(pathname ps)))
(defmethod svg-display-drawing (filepath)
"Show the drawing to the user in the GUI."
(let ((command
#+(or macos macosx darwin) "/usr/bin/open"
#-(or macos macosx darwin) "/usr/bin/iceweasel"))
#+sbcl (sb-ext:run-program command (list filepath) :wait nil)
#+openmcl (ccl::os-command (format nil "~a ~a" command filepath)))
filepath)
(defmethod write-svg ((the-drawing drawing))
"Write the drawing as an svg file."
(advisory-message "Saving drawing as svg.~%")
(svg-write-drawing (generate-filename ".svg")
the-drawing))
(defmethod write-and-show-svg ((the-drawing drawing))
"Write and display the drawing as an svg file."
(advisory-message "Viewing drawing as svg.~%")
(svg-display-drawing (write-svg the-drawing)))
| 7,418 | Common Lisp | .lisp | 173 | 37.132948 | 80 | 0.609063 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | cc727a2fb40553029b3313cfe09bf676a2cf57b290293242e4fcc71c36783300 | 17,552 | [
-1
] |
17,553 | polyline.lisp | rheaplex_rheart/draw-something/polyline.lisp | ;; polyline.lisp - A classic computer graphics polyline.
;; Copyright (C) 2006 Rhea Myers [email protected]
;;
;; This file is part of draw-something.
;;
;; draw-something is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3 of the License, or
;; (at your option) any later version.
;;
;; draw-something is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;(in-package "DRAW-SOMETHING")
(defclass polyline ()
;; Optimised to use arrays not lists to avoid terrible (distance) consing
;; For speed set initial dimension to a size unlikely to need increasing
((points :accessor points
:initform (make-vector 1000)
:initarg :points
:documentation "The points of the polyline")
(bounds :accessor bounds
:type rectangle
:initarg :bounds
:documentation "The bounds of the polyline."))
(:documentation "A polyline or polygon. A series of joined line segments."))
(defmethod append-point ((poly polyline) (pt point))
"Append a point to the polyline."
(vector-push-extend pt (points poly))
(if (slot-boundp poly 'bounds)
(include-point (bounds poly) pt)
(setf (bounds poly) (rectangle-from-point pt))))
(defmethod point-count ((poly polyline))
"Get the number of points in the polyline"
(length (points poly)))
(defmethod first-point ((poly polyline))
"Get the first point of the polyline."
(aref (points poly) 0))
(defmethod last-point ((poly polyline))
"Get the last point of the polyline."
(aref (points poly)
(- (point-count poly) 1)))
(defmethod make-random-polyline-in-rectangle (rect count)
"Create a polyline with the given number of points in the given bounds."
(let ((poly (make-instance 'polyline)))
(dotimes (i count)
(append-point poly (random-point-in-rectangle rect)))
poly))
(defmethod make-polyline-from-points ((points vector))
"Create a polyline with the given points."
(let ((poly (make-instance 'polyline)))
(loop for p across points
do (append-point poly p))
poly))
(defmethod distance ((p point) (poly polyline))
"The distance from a point to a polyline."
(cond ((= (length (points poly)) 0)
nil) ;; Infinite distance? Zero?
((= (length (points poly)) 1)
(distance p (aref (points poly) 0)))
(t ;; More than 1 point
(let ((distance-to-poly nil)
(pts (points poly)))
(do ((i 1 (+ i 1)))
((= i (length pts)))
(let ((d (distance-point-line p
(aref pts (- i 1))
(aref pts i))))
(if (or (not distance-to-poly)
(< d distance-to-poly))
(setf distance-to-poly d))))
distance-to-poly))))
(defmethod highest-leftmost-point ((poly polyline))
"The highest point, or highest and leftmost point (if several are highest)."
(let* ((the-points (points poly))
(highest (aref the-points 0)))
(dotimes (i (length the-points))
(let ((pt (aref the-points i)))
(if (or (> (y pt) (y highest))
(and (= (y highest) (y pt))
(< (x highest) (x pt))))
(setf highest pt))))
highest))
(defmethod area ((poly polyline))
"Get the area of the POLYGON"
;; Cleanme!
(if (< (length (points poly)) 3)
0.0
(let ((pts (points poly))
(numpts (length (points poly)))
(area 0.0))
(dotimes (i (- numpts 1))
(let ((j (mod (+ i 1)
numpts)))
(setf area (+ area
(* (x (aref pts i))
(y (aref pts j)))))
(setf area (- area
(* (y (aref pts i))
(x (aref pts j)))))))
(setf area (/ area 2.0))
(abs area))))
(defmethod contains ((poly polyline) (p point))
"Find whether the POLYGON contains the point."
;; Count ray-poly-line intersections. Odd = inside, 0 or even = outside.
(if (> (length (points poly)) 2)
(let ((pts (points poly))
(numpts (length (points poly)))
(ray-line (make-instance 'line
:from p
:to (translate-point 10000.0 0.0)))
(crossings 0))
(dotimes (i (- numpts 1))
(let ((j (mod (+ i 1)
numpts)))
(when (line-intersect-line-points ray-line
(aref pts i)
(aref pts j))
(setf crossings(+ crossings 1)))))
(oddp crossings))))
(defmacro do-poly-lines ((sym poly) &body body)
"Apply fun to each line in the polyline, or not if there is only 1 point."
(with-gensyms (poly-points previous-point current-point i)
`(let ((,poly-points (points ,poly)))
(when (> (point-count ,poly-points) 1)
(let ((,previous-point (first-point ,poly-points))
(,current-point nil)
(,sym nil))
(dotimes (,i (point-count ,poly-points))
(setf ,current-point (aref ,poly-points (+ ,i 1)))
(setf ,sym (make-instance 'line
:from ,previous-point
:to ,current-point))
,@body
(setf ,previous-point ,current-point)))))))
(defmethod intersects ((l line) (poly polyline))
"Find whether the line intersects or is contained by the polyline."
;; Currently only intersects
(let ((result nil))
(do-poly-lines (l2 poly)
(when (intersects l l2)
(setf result t)
(return)))
result))
(defmethod intersects ((poly1 polyline) (poly2 polyline))
"Find whether the two POLYGONS intersect or contain each other."
;; Currently only intersects
(dolist (p (points poly2))
(when (contains poly1 p)
(return t))))
(defmethod intersects ((rect rectangle) (poly polyline))
"Find whether the polygon intersects or contains the rectangle."
;; Currently only intersects
(dolist (p (points poly))
(when (contains rect p)
(return t))))
(defmethod convex-hull (the-points)
"Get the convex hull of an array of points."
(let* ((first-point (highest-leftmost-point the-points))
(current-point first-point)
(next-point nil)
(hull (make-vector 10)))
(vector-push-extend first-point hull)
(loop until (and (not (eq next-point nil))
(eq next-point first-point))
do (setf next-point
(point-with-all-left current-point the-points))
(vector-push-extend next-point hull)
(setf current-point next-point))
(make-instance 'polyline :points hull)))
(defmethod adding-point-would-cause-self-intersection ((poly polyline)
(p point))
"Check if adding the point to the polyline would make it self-intersect."
(let ((l (make-instance 'line
:from (last-point poly)
:to p))
(result nil))
(do-poly-lines (ll poly)
(when (intersects l ll)
(setf result t)
(break)))
result))
| 7,798 | Common Lisp | .lisp | 186 | 32.376344 | 78 | 0.576771 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 28c241715be05dc501d2b77a7aa5945dbc5e3902f050d6ee490b673d6c98a5ee | 17,553 | [
-1
] |
17,554 | form.lisp | rheaplex_rheart/draw-something/form.lisp | ;; form.lisp - A form of a figure.
;; Copyright (C) 2006 Rhea Myers [email protected]
;;
;; This file is part of draw-something.
;;
;; draw-something is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3 of the License, or
;; (at your option) any later version.
;;
;; draw-something is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;(in-package "DRAW-SOMETHING")
(defconstant min-form-points 1)
(defconstant max-form-points 12)
(defconstant form-step-limit 5000)
(defconstant pen-width 1.0)
(defclass form ()
((skeleton :accessor skeleton
:type vector
:initarg :skeleton
:initform (make-vector 5)
:documentation "The guide shape for the outline.")
(outline :accessor outline
:type polyline
:initform (make-instance 'polyline)
:documentation "The outlines for the skeleton. Will be outline_s_.")
(bounds :accessor bounds
:type rectangle
:initform (make-instance 'rectangle)
:initarg :bounds
:documentation "The bounds of the form.")
(fill-colour :accessor fill-colour
:type colour
:initarg :colour
:initform (random-colour)
:documentation "The flat body colour of the form."))
(:documentation "A form drawn in the drawing."))
;; Skeleton will ultimately be generated from a list of objects, kept separately
;; Forms will be able to have no fill or no outline independently
(defmethod first-point ((the-form form))
"Get the first point in the outline of the form."
(first-point (outline the-form)))
(defmethod point-count ((the-form form))
"The number of points in the outline of the form."
(point-count (outline the-form)))
(defmethod most-recent-point ((the-form form))
"The most recent point added to the outline of the form."
(last-point (outline the-form)))
(defmethod make-form-start-point ((form-skeleton vector)
(params pen-parameters))
"Get the point to start drawing at."
(let ((start-point nil))
(dovector (skel form-skeleton)
(let* ((hp (highest-leftmost-point skel))
(candidate (make-instance 'point
:x (x hp)
:y (+ (y hp) (pen-distance params)))))
(when (or (not start-point)
(> (y candidate) (y start-point))
(and (= (y candidate) (y start-point))
(< (x candidate) (x start-point))))
(setf start-point candidate))))
start-point))
(defmethod make-form-turtle ((the-form form) (params pen-parameters))
"Make the turtle to draw around the form."
(make-instance 'turtle
:location (make-form-start-point (skeleton the-form) params)
:direction (- (/ pi 2.0))
))
(defmethod make-form-from-points ((points vector))
"Make a form, ready to be started."
(advisory-message (format nil "Making form.~%"))
(let* ((skel (make-polyline-from-points points))
(the-form (make-instance 'form
:skeleton (vector skel)
:bounds (bounds skel))))
;;(draw-form the-form) ;; Remove for codelets
the-form))
(defmethod path-ready-to-close ((the-form form) (the-pen pen-parameters))
(and (> (point-count the-form) 2) ;; Ignore very first point
(< (distance (most-recent-point the-form)
(first-point the-form))
(move-step the-pen))))
(defmethod path-timeout ((the-form form))
"Make sure that a failure of the form algorithm hasn't resulted in a loop."
(> (point-count the-form)
form-step-limit))
(defmethod should-finish-form ((the-form form) (the-pen pen-parameters))
"Decide whether the form should finish."
(or (path-ready-to-close the-form the-pen)
(path-timeout the-form)))
(defmethod draw-form ((the-form form))
"Find the next point forward along the drawn outline of the shape."
(let* ((form-bounds (bounds the-form))
(the-outline (outline the-form))
(the-pen (choose-one-of plane-pen-parameters))
(the-turtle (make-form-turtle the-form the-pen)))
(advisory-message "Drawing form.~%")
(append-point the-outline (location the-turtle))
(loop until (should-finish-form the-form the-pen)
do (progn
(adjust-next-pen (skeleton the-form) the-pen the-turtle)
(forward the-turtle (move-step the-pen))
(let ((new-location (location the-turtle)))
(append-point the-outline new-location)
(include-point form-bounds new-location))))
(append-point the-outline (first-point the-form))))
| 5,157 | Common Lisp | .lisp | 113 | 38.061947 | 80 | 0.643923 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | deb12219f297c72dd47571da7a9c9b0a9aadfe849244b893593d89d045417d79 | 17,554 | [
-1
] |
17,555 | geometry.lisp | rheaplex_rheart/draw-something/geometry.lisp | ;; geometry.lisp - Basic geometry stuff.
;; Copyright (C) 2006 Rhea Myers [email protected]
;;
;; This file is part of draw-something.
;;
;; draw-something is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3 of the License, or
;; (at your option) any later version.
;;
;; draw-something is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;(in-package "DRAW-SOMETHING")
(defconstant radian (* pi 2.0)
"One radian.")
(defconstant %radians-to-degrees (/ radian 360.0)
"The value to multiple radians by to get degrees.")
(defmethod radians-to-degrees (radians)
"Convert a value in radians to a huamn-readable value in degrees. :-)"
(/ radians %radians-to-degrees))
(defconstant radians-to-t-ratio (/ 1.0 (* pi 2.0)))
(defmethod radians-to-t (r)
"Convert the value in radians to a value from 0.0 to 1.0"
(* r radians-to-t-ratio)) | 1,297 | Common Lisp | .lisp | 29 | 43.103448 | 73 | 0.737926 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 1598db8c6b167485c61479ef5a28b5212811b388ae65a0d39ece7c3af7e0bb6c | 17,555 | [
-1
] |
17,556 | random.lisp | rheaplex_rheart/ben/random.lisp | ;; 1970s-compliant pseudo-random number generator.
;; See: https://en.wikipedia.org/wiki/Linear_congruential_generator
(defparameter +rand-a+ 1664525)
(defparameter +rand-c+ 1013904223)
(defparameter +rand-m+ (expt 2 32))
(defvar *rand-seed* 0)
(defun set-randseed (seed)
(setf *rand-seed* seed))
(defun rand ()
(setf *rand-seed*
(mod (* +rand-a+
(+ *rand-seed* +rand-c+))
+rand-m+)))
(defun randint (max)
"Return an integer from 0 to max, exclusive."
(ash (* (rand) max)
-32))
(defun random-range-int (min max)
"Return an integer from min to max, exclusive."
(let ((range (- max min)))
(if (= range 0)
min
(+ (randint range) min))))
(defun random-range (min max)
"Return a float from min to max, exclusive."
;;FIXME:!!!!
(if (= min max)
min
(let ((scale (/ (- max min) 1000)))
(+ (* (randint 1000) scale) min))))
(defun choose-one-of (&rest possibilities)
"Choose one of the given options."
(nth (randint (length possibilities)) possibilities))
| 1,059 | Common Lisp | .lisp | 33 | 27.666667 | 67 | 0.626104 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 9a799114afab5053aa805142d9d22f94fba3fa5a052d8679f1c00b073f905b88 | 17,556 | [
-1
] |
17,557 | on-purpose-line.lisp | rheaplex_rheart/ben/on-purpose-line.lisp |
;; on-purpose-line.lisp - An implementation of the line drawing algorithm from
;; Harold Cohen's essay "On Purpose".
;; Copyright (C) 2008, 2024 Rhea Myers [email protected]
;;
;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3 of the License, or
;; (at your option) any later version.
;;
;; draw-something is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; A simple implementation of the line drawing algorithm from Harold Cohen's
;; essay "On Perception".
;; The following are guesses:
;; - All the parameter ranges.
;; - The homing algorithm.
;; The following are historically inauthentic:
;; - The use of Lisp rather than C.
;; This is at best an approximation, but hopefully an interesting approximation.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Line Drawing.
(defvar pen-position)
(defvar pen-direction)
(defparameter pen-move-distance 2.0)
(defvar line-start)
(defvar line-end)
;; Cached calculations
(defvar line-distance)
(defvar line-direction)
(defun pen-direction-relative-to-line ()
(- pen-direction
line-direction))
;; Swings per phase. 0 or 2. 0 = no swings, > 0 = swings.
(defparameter swings 2)
(defvar swing-direction)
(defun set-swing-left-or-right ()
(if (= swings 0)
(setf swing-direction 'straight-ahead)
(setf swing-direction (choose-one-of 'left 'right))))
(defun reverse-swing ()
(case swing-direction
(straight-ahead (setf swing-direction 'straight-ahead))
(left (setf swing-direction 'right))
(right (setf swing-direction 'left))))
(defvar sub-phase-length)
(defvar sub-phase-length-so-far)
(defvar sub-phase-count 0)
(defun end-of-phase ()
(incf sub-phase-count)
(let ((is-end nil))
(when (>= sub-phase-count swings)
(setf sub-phase-count 0)
(setf is-end t))
is-end))
(defun end-of-sub-phase ()
(>= sub-phase-length-so-far sub-phase-length))
(defparameter min-sub-phase-length 50.0)
(defparameter max-sub-phase-length 256.0)
(defun set-length-of-sub-phase ()
(setf sub-phase-length-so-far 0)
(setf sub-phase-length (random-range (min min-sub-phase-length
line-distance)
(min max-sub-phase-length
line-distance))))
(defparameter min-angular-limit (/ pi 8))
(defparameter max-angular-limit (/ pi 4))
(defvar angular-limit)
(defun set-angular-limit ()
(setf angular-limit (random-range min-angular-limit max-angular-limit)))
(defun within-angular-limits ()
;; (format t "~a ~a ~a ~%" pen-direction line-direction (abs (- pen-direction line-direction)))
(< (abs (pen-direction-relative-to-line))
angular-limit))
(defparameter min-swing-rate 0.01)
(defparameter max-swing-rate 0.1)
(defparameter min-swing-rate-change least-positive-single-float)
(defparameter max-swing-rate-change 0.001)
(defvar swing-kind)
(defvar swing-rate)
(defvar swing-rate-change)
(defun set-swing-kind ()
"Set whether the swing will be constant, accelerate, or deccelerate."
(setf swing-kind
(choose-one-of 'constant 'accelerating 'decelerating)))
(defun random-swing-rate-change ()
"Set the amount the swing rate will increase or decrease by each step."
(case swing-kind
(constant 0)
(t (random-range min-swing-rate-change
max-swing-rate-change))))
(defun set-swing-straight-ahead ()
"When the swing state is straight ahead, swing rate and change rate are 0."
(setf swing-rate 0.0)
(setf swing-rate-change 0.0))
(defun set-swing-amount ()
"Set the swing and change rate for a left or right swing."
(setf swing-rate (random-range min-swing-rate max-swing-rate))
(setf swing-rate-change (random-swing-rate-change)))
(defun set-rate-of-swing ()
"Set values for the swing depending on whether we are within angular limit."
(set-swing-kind)
(if (eq swing-direction 'straight-ahead)
(set-swing-straight-ahead)
(set-swing-amount)))
(defun update-swing-rate ()
"Update the swing rate, constraining the result to 0..max-swing-rate."
(case swing-kind
;; Do nothing for constant
(accelerating
(setf swing-rate (+ swing-rate swing-rate-change))
(when (> swing-rate max-swing-rate)
(setf swing-rate max-swing-rate)))
(decelerating
(setf swing-rate (- swing-rate swing-rate-change))
(when (< swing-rate 0.0)
(setf swing-rate 0.0)))))
(defun calculate-new-direction-for-line ()
"Apply the swing to the pen."
(update-swing-rate)
(case swing-direction
(straight-ahead nil)
(left
(setf pen-direction (+ pen-direction swing-rate)))
(right
(setf pen-direction (- pen-direction swing-rate)))))
(defun position-difference ()
(point-distance line-start
pen-position))
(defun direction-difference ()
"The pen's relative direction to the line, -pi..+pi radians."
(assert (< (bearing-to-position (point-x pen-position) (point-y pen-position)
pen-direction (point-x line-end) (point-y line-end))
2.0))
(bearing-to-position (point-x pen-position) (point-y pen-position)
pen-direction (point-x line-end) (point-y line-end)))
(defun weight-curve (time)
"For time from 0..1 ."
(assert (<= 0.0 time 1.0))
time)
(defun weight-from-distance ()
"How close to the direction to the end point the pen should be now."
(weight-curve (- 1.0
(/ (abs (- line-distance
(position-difference)))
line-distance))))
(defun weighted-correction ()
(* (direction-difference)
(weight-from-distance)))
;; It would be a lot easier to store this separately from the pen direction
;; and add it in when calculating the next pen position but I don't think that
;; fits the description.
(defun correction-for-homing ()
;;(format t "~a ~a ~a ~%" pen-direction (weight-from-distance) (direction-difference))
(assert (< (direction-difference) 2.0))
(setf pen-direction (+ pen-direction (weighted-correction))))
(defun calculate-position-of-next-point ()
(setf pen-position
(offset-point-along-direction pen-position
pen-direction
pen-move-distance)))
(defun move-to-next-point ()
(set-cell-status (floor (point-x pen-position))
(floor (point-y pen-position))
'figure-outline)
(setf sub-phase-length-so-far
(+ sub-phase-length-so-far
pen-move-distance)))
(defparameter destination-distance-tolerance 1.0)
(defun reached-destination ()
(< (point-distance pen-position line-end)
destination-distance-tolerance))
(defun set-line-drawing-parameters (from to)
(setf line-start from)
(setf line-end to)
(setf line-distance (line-length line-start line-end))
(setf line-direction (angle-between-points line-start line-end))
(setf pen-position line-start)
(setf pen-direction line-direction))
(defun new-sub-phase ()
(set-length-of-sub-phase)
(if (= sub-phase-count 0)
(progn
(set-swing-left-or-right)
(set-rate-of-swing))
(reverse-swing))
;; (format t "Subphase: length ~a direction ~a swing ~a change ~a~%" sub-phase-length swing-direction swing-rate swing-rate-change)
(incf sub-phase-count))
(defun new-phase ()
"Start a new phase ."
(format t "NEW PHASE~%")
(setf sub-phase-count 0))
(defun new-phase-outside-angular-limits ()
(format t "Exceeded angular limit.~%")
(let ((direction swing-direction))
(new-phase)
(new-sub-phase)
(setf swing-direction direction)
(reverse-swing)))
(defun draw-line-step ()
(calculate-new-direction-for-line)
(correction-for-homing)
(calculate-position-of-next-point)
(move-to-next-point))
(defun draw-line (from to)
(apply-line-cells (point-x from) (point-y from) (point-x to) (point-y to)
(lambda (x y)
(set-cell-status x y 'unused-inside-figure)))
(set-line-drawing-parameters from to)
(loop
do (loop
initially (new-phase)
do (loop
initially (new-sub-phase)
when (not (within-angular-limits))
do (new-phase-outside-angular-limits)
do (draw-line-step)
until (or (end-of-sub-phase) (reached-destination)))
until (or (end-of-phase) (reached-destination)))
until (reached-destination)))
(defun test-draw-line ()
(initialise-cell-matrix)
(set-angular-limit) ;; Where should this go and how often?
;; Horizontal
(draw-line (make-point 10 100) (make-point 190 100))
(draw-line (make-point 190 100) (make-point 10 100))
;; Up diagonal
(draw-line (make-point 25 25) (make-point 175 175))
(draw-line (make-point 175 175) (make-point 25 25))
;; Down diagonal
(draw-line (make-point 25 175) (make-point 175 25))
(draw-line (make-point 175 25) (make-point 25 175))
;; Vertical
(draw-line (make-point 100 10) (make-point 100 190))
(draw-line (make-point 100 190) (make-point 100 10))
(write-cell-matrix-ppm-file))
(defun test-draw-lines ()
(dotimes (i 1000)
(test-draw-line)))
(defun test-draw-lines-lots ()
(dotimes (i 1000)
(format t "~a~%" i)
(test-draw-lines)))
| 9,938 | Common Lisp | .lisp | 248 | 34.729839 | 149 | 0.657982 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 3bfd38081cfa979dd4a13b298ec1f31f718f5ee9368359d85b60f6b32cb0bc91 | 17,557 | [
-1
] |
17,558 | figure.lisp | rheaplex_rheart/ben/figure.lisp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Figures
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defstruct figure
allocated-space
(actual-bounds nil)
(outline '())
(closed nil))
(defun set-cell-figure (x y fig)
"Set the cell's figure."
(assert (>= x 0))
(assert (< x *image-width*))
(assert (>= y 0))
(assert (< y *image-height*))
;; (assert (co-ordinates-in-rectangle-p x y (figure-allocated-space fig)))
(setf (cell-figure (get-cell x y)) fig)
(if (null (figure-actual-bounds fig))
(setf (figure-actual-bounds fig)
(make-rectangle :x x :y y :width 1 :height 1))
(rectangle-include-point (figure-actual-bounds fig) (make-point x y))))
(defun set-cell-figure-outline (x y fig)
"Set the cell to be part of the outline of the figure."
(assert (>= x 0))
(assert (< x *image-width*))
(assert (>= y 0))
(assert (< y *image-height*))
;; (assert (co-ordinates-in-rectangle-p x y (figure-allocated-space fig)))
(set-cell-figure x y fig)
(set-cell-status x y 'figure-outline))
(defun set-cell-figure-unused-space (x y fig)
"Set the cell to be part of the outline of the figure."
(assert (>= x 0))
(assert (< x *image-width*))
(assert (>= y 0))
(assert (< y *image-height*))
;; (assert (co-ordinates-in-rectangle-p x y (figure-allocated-space fig)))
(set-cell-figure x y fig)
(set-cell-status x y 'unused-inside-figure))
(defparameter *figures* '()
"The figures of the image.")
(defun figure-outline-cell-p (x y)
"Is the cell part of the outline of a figure?"
(assert (>= x 0))
(assert (< x *image-width*))
(assert (>= y 0))
(assert (< y *image-height*))
(not (cell-figure (get-cell x y))))
(defun figure-closed-p (fig)
"Has the figure been marked as closed?"
(figure-closed fig))
(defun cell-figure-closed-p (x y)
"Is the figure of the cell at x,y closed? No figure (or open) returns nil."
(assert (>= x 0))
(assert (< x *image-width*))
(assert (>= y 0))
(assert (< y *image-height*))
(let ((fig (cell-figure (get-cell x y))))
(and fig
(figure-closed-p fig))))
(defun cell-figure-p (x y)
"Is the point in a figure or on its outline (not optically)?"
(assert (>= x 0))
(assert (< x *image-width*))
(assert (>= y 0))
(assert (< y *image-height*))
;; (eq (cell-status (get-cell x y))
;; 'unused-inside-figure))
(cell-figure (get-cell x y)))
(defun apply-figure-fill (fig)
"Set the cells inside the figure outline to being figure space."
(assert (figure-closed-p fig))
(fill-polygon (figure-outline fig)
(figure-actual-bounds fig)
(lambda (x y)
(when (null (get-cell-status x y))
(set-cell-figure-unused-space x y fig)))))
| 2,820 | Common Lisp | .lisp | 76 | 33.118421 | 80 | 0.591142 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 5293673b2b9a192dd377fcdec9f6f583747193260a6f479323aeb1833545f7cf | 17,558 | [
-1
] |
17,559 | image-cell-matrix.lisp | rheaplex_rheart/ben/image-cell-matrix.lisp | (defparameter *image-width* 1024
"The width of the image cell matrix, in cells.")
(defparameter *image-height* 768
"The height of the image cell matrix, in cells.")
(defstruct cell
"An image matrix cell."
(status nil)
(figure nil))
(defparameter *statuses* '(nil rough figure-outline unused-inside-figure)
"The statuses each cell can have. nil is ground.")
(defparameter *image-cells* (make-array (list *image-width* *image-height*))
"The image cell matrix. Row major.")
(defun set-cell (x y value)
"Set cell x,y of the image cells matrix to value."
(assert (>= x 0))
(assert (< x *image-width*))
(assert (>= y 0))
(assert (< y *image-height*))
(setf (aref *image-cells*
x y)
value))
(defun get-cell (x y)
"Get the value of cell x,y in the image cells matrix. "
(assert (>= x 0))
(assert (<= x *image-width*))
(assert (>= y 0))
(assert (< y *image-height*))
(aref *image-cells*
x y))
(defun set-cell-status (x y status)
"Set the cell's status."
(assert (>= x 0))
(assert (< x *image-width*))
(assert (>= y 0))
(assert (< y *image-height*))
(setf (cell-status (get-cell x y)) status))
(defun get-cell-status (x y)
"Set the cell's status."
(assert (>= x 0))
(assert (< x *image-width*))
(assert (>= y 0))
(assert (< y *image-height*))
(cell-status (get-cell x y)))
(defun apply-line-cells (x0 y0 x1 y1 fun)
"Bresenham's algorithm. Always applies left to right."
;;FIXME: only connect cells horizontally or vertically.
(assert (>= x0 0))
(assert (< x0 *image-width*))
(assert (>= y0 0))
(assert (< y0 *image-height*))
(assert (>= x1 0))
(assert (< x1 *image-width*))
(assert (>= y1 0))
(assert (< y1 *image-height*))
(let ((steep (> (abs (- y1 y0)) (abs (- x1 x0)))))
(when steep
(rotatef x0 y0)
(rotatef x1 y1))
(when (> x0 x1)
(rotatef x0 x1)
(rotatef y0 y1))
(let* ((deltax (- x1 x0))
(deltay (abs (- y1 y0)))
(err (- (/ (+ deltax 1) 2)))
(ystep (if (< y0 y1) 1 -1))
(y y0))
(loop for x from x0 to x1 ;; Below?
do (progn
(if steep
(funcall fun y x)
(funcall fun x y))
(setf err (+ err deltay))
(when (>= err 0)
(setf y (+ y ystep))
(setf err (- err deltax))))))))
(defun apply-rect-cells (x y width height fun)
"Applies the function to each cell of each row of the area top-to-bottom."
(assert (>= x 0))
(assert (<= x *image-width*))
(assert (>= y 0))
(assert (<= y *image-height*))
(assert (>= (+ x width) 0))
(assert (<= (+ x width) *image-width*))
(assert (>= (+ y height) 0))
(assert (<= (+ y height) *image-height*))
(dotimes (j height)
(dotimes (i width)
(funcall fun
(+ x i)
(+ y j)))))
(defun clear-ground-p (x y width height)
"Is the rectangular space clear of figure or rough cells?"
(let ((clear t))
(block clear-block
(apply-rect-cells x y (1+ width) (1+ height)
(lambda (h v)
(when (not (eq (cell-status (get-cell h v)) nil))
(setf clear nil)
(return-from clear-block)))))
clear))
(defun initialise-cell-matrix ()
"Initialize the cell matrix."
(apply-rect-cells 0 0 *image-width* *image-height*
(lambda (x y) (set-cell x y (make-cell)))))
(defun roughen (&optional (count 10))
"Set some cells to be unusable for drawing."
(dotimes (i count)
(setf (cell-status (get-cell (random *image-width*)
(random *image-height*)) )
'rough)))
(defun write-cell-matrix-ppm-file (&optional (filename "./cells.ppm")
(comment ""))
"Write the cell matrix to a colour, binary ppm file."
;; Write the header in character stream mode
(with-open-file (stream filename
:direction :output
:if-exists :supersede)
(format stream "P6~%#~A~%~D ~D~%~d~%"
comment *image-width* *image-height* 255))
;; Append the rasters in byte stream mode
(with-open-file (stream filename
:direction :output
:if-exists :append
:element-type '(unsigned-byte 8))
(dotimes (j *image-height*)
(dotimes (i *image-width*)
(case (get-cell-status i (- *image-height* j 1))
(figure-outline (write-byte 0 stream)
(write-byte 0 stream)
(write-byte 0 stream))
(unused-inside-figure (write-byte 0 stream)
(write-byte 255 stream)
(write-byte 0 stream))
(rough (write-byte 255 stream)
(write-byte 0 stream)
(write-byte 0 stream))
(t (write-byte 255 stream)
(write-byte 255 stream)
(write-byte 255 stream)))))
(namestring stream)))
| 5,117 | Common Lisp | .lisp | 140 | 28.185714 | 76 | 0.541406 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 2f74ee3d175f42db6d005d7e32495e3f46952ede4d75c50e866d4466f8bdb9ae | 17,559 | [
-1
] |
17,560 | production-system.lisp | rheaplex_rheart/ben/production-system.lisp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Rule context
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defparameter *contexts* (make-hash-table))
(defparameter *context* nil
"The currently operating level of the system, e.g. curves, line.")
(defparameter possible-contexts '(nil artwork mapping planning lines sectors curves movement-control))
(defstruct context
name
(productions '()))
(defun get-context (context-name)
(or (gethash context-name *contexts*)
(setf (gethash context-name *contexts*)
(make-context :name context-name :productions '()))))
(defun add-production-to-context (context-name production)
(setf (context-productions (get-context context-name))
(append (context-productions (get-context context-name))
(list production))))
(defun set-context (context-name)
"Set the current context."
(assert (member context-name possible-contexts))
(setf *context* (gethash context-name *contexts*)))
(defun current-context-productions ()
(context-productions *context*))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Productions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defvar previous-production nil)
(defstruct production
description
left-hand-side
right-hand-side)
(defmacro defproduction (context-name description &body body)
"Define a production rule. Note description doesn't have to be unique."
(let* ((after-arrow (member '=> body))
(left-hand-side (ldiff body after-arrow))
(right-hand-side (rest after-arrow)))
`(add-production-to-context
,context-name
(make-production
:description ,description
:left-hand-side (lambda () (and ,@left-hand-side))
:right-hand-side (lambda () ,@right-hand-side)))))
(defun apply-production ()
"Try to find and apply a single production. Returns t if one ran."
(dolist (the-production (current-context-productions))
(when (funcall (production-left-hand-side the-production))
(when (not (eq (production-description the-production)
previous-production))
(format t "~a~%" (production-description the-production))
(setf previous-production (production-description the-production)))
(funcall (production-right-hand-side the-production))
(return t))))
| 2,423 | Common Lisp | .lisp | 53 | 41.433962 | 102 | 0.621392 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 5ee9331435459757d8829ca5a33554ad9a1c193324c02b5df81f3617cb18fada | 17,560 | [
-1
] |
17,561 | run.lisp | rheaplex_rheart/ben/run.lisp | (load "random")
(load "geometry")
(load "image-cell-matrix")
(load "figure")
(load "production-system")
;;(load "on-purpose-line")
(load "ben")
(defun main ()
(ben))
| 169 | Common Lisp | .lisp | 9 | 17.444444 | 26 | 0.672956 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 5485750ee0a62c49e881a1d54316e78604c1722bc5887ff340835f03763cd32f | 17,561 | [
-1
] |
17,562 | geometry.lisp | rheaplex_rheart/ben/geometry.lisp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Utility functions.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun mapl2 (list fun)
"Apply fun to successive pairs of values from list. Only takes one list."
(when (cadr list)
(funcall fun (car list) (cadr list))
(mapl2 (cddr list) fun)))
(defconstant 2pi (* pi 2))
(defconstant -pi (- pi))
(defconstant radian (* pi 2))
(defconstant radian/3/4 (/ (* pi 3) 2))
(defconstant radian/2 pi)
(defconstant radian/4 (/ pi 2))
(defun normalize-relative-angle (angle)
"Normalise a relative angle in radians to the range [-pi,+pi[."
(let ((trimmed-angle (mod angle 2pi)))
(if (>= trimmed-angle 0)
(if (< trimmed-angle pi)
trimmed-angle
(- trimmed-angle 2pi))
(if (>= trimmed-angle -pi)
trimmed-angle
(+ trimmed-angle 2pi)))))
(defun bearing-to-position (x y heading target-x target-y)
"Find the bearing from x,y,heading(radians, relative) to target-x,target-y."
(normalize-relative-angle (- (atan (- target-y y) (- target-x x))
heading)))
(defun make-point (x y)
(cons x y))
(defun point-x (item)
(car item))
(defun point-y (item)
(cdr item))
(defun point-distance (from to)
"The distance between two points."
(abs (sqrt (+ (expt (- (point-x to) (point-x from)) 2)
(expt (- (point-y to) (point-y from)) 2)))))
(defun offset-point-along-direction (p direction amount)
;; Direction is radians anticlockwise from the positive x axis
(make-point (+ (point-x p)
(* amount (cos direction)))
(+ (point-y p)
(* amount (sin direction)))))
(defun angle-between-points (from to)
"Calculate the angle of the second point around the first, 0..2pi from pos x."
(atan (- (point-y to) (point-y from))
(- (point-x to) (point-x from))))
(defun line-length (from to)
"The length of the line between the two points."
(abs (point-distance from to)))
(defstruct rectangle
x
y
width
height)
(defun rectangle-left (rect)
(rectangle-x rect))
(defun rectangle-top (rect)
(+ (rectangle-y rect) (rectangle-height rect)))
(defun rectangle-right (rect)
(+ (rectangle-x rect) (rectangle-width rect)))
(defun rectangle-bottom (rect)
(rectangle-y rect))
(defun co-ordinates-in-rectangle-p (x y r)
(and (>= x (rectangle-x r))
(>= y (rectangle-y r))
(< x (+ (rectangle-x r) (rectangle-width r)))
(< y (+ (rectangle-y r) (rectangle-height r)))))
(defun rectangle-include-point (rect p)
"Destructively expand the rectangle to include the point."
(let ((right (+ (rectangle-x rect) (rectangle-width rect)))
(top (+ (rectangle-y rect) (rectangle-height rect))))
(cond
((< (point-x p) (rectangle-x rect))
(setf (rectangle-width rect)
(+ (rectangle-width rect) (- (rectangle-x rect) (point-x p))))
(setf (rectangle-x rect) (point-x p)))
((> (point-x p) right)
(setf (rectangle-width rect)
(+ (rectangle-width rect) (- (point-x p) right)))))
(cond
((< (point-y p) (rectangle-y rect))
(setf (rectangle-height rect)
(+ (rectangle-height rect) (- (rectangle-y rect) (point-y p))))
(setf (rectangle-y rect) (point-y p)))
((> (point-y p) top)
(setf (rectangle-height rect)
(+ (rectangle-height rect) (- (point-y p) top))))))
rect)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Polygon Fill.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun fill-apply-span (x1 x2 y fun)
"Apply fun to the pixels between x1 and x2 on row y."
(loop for x from x1 below x2
do (funcall fun x y)))
(defun fill-between-node-pairs (nodes y fun)
"Walk the list of node start/end pairs on row y, calling fun between them."
(mapl2 nodes
(lambda (x1 x2)
(fill-apply-span x1 x2 y fun))))
(defun fill-line-intersects-row (p previous y)
"Does the line between p and previous pass through row y?"
(or (and (< (point-y p) y)
(>= (point-y previous) y))
(and (< (point-y previous) y)
(>= (point-y p) y))))
(defun fill-line-row-intersection-column (p previous y)
"The x position where line p->previous intersects row y (assuming it does)."
;; The flooring is needed to match the drawn outline, which is also floored.
(let ((px (floor (point-x p)))
(py (floor (point-y p)))
(prevx (floor (point-x previous)))
(prevy (floor (point-y previous))))
(floor (+ px
(* (/ (- y py)
(- prevy py))
(- prevx px))))))
(defun fill-build-node-list (points y)
"Build a list of positions where the path created by points intersects y."
(let ((nodes '())
(previous (car (last points))))
(dolist (p points)
(when (fill-line-intersects-row p previous y)
(push (fill-line-row-intersection-column p previous y)
nodes))
(setf previous p))
(sort nodes #'<)))
(defun fill-scanline (y points fun)
"Call fun for each x, y coord on row y inside the path described by points."
(let ((nodes (fill-build-node-list points y)))
(fill-between-node-pairs nodes y fun)))
(defun fill-polygon (points bounds fun)
"Call fun on each x, y coord inside path of points with cached bounds rect."
(loop for y from (rectangle-bottom bounds) below (rectangle-top bounds)
do (fill-scanline y points fun)))
| 5,553 | Common Lisp | .lisp | 137 | 35.240876 | 80 | 0.589534 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 8811c3192d53258696cb62e58a2c92af3a32526cbde7dcd917375f37d14968dc | 17,562 | [
-1
] |
17,563 | ben.lisp | rheaplex_rheart/ben/ben.lisp | ;; Ben.lisp - A toy reimplementation of Harold Cohen's AARON circa
;; "What Is An Image".
;; Copyright (C) 2008, 2024 Rhea Myers [email protected]
;;
;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3 of the License, or
;; (at your option) any later version.
;;
;; ben is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;; IN PROGRESS
;; The line drawing algorithm from "on-purpose-line.lisp" needs importing
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; The Current Development
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Eventually need a stack of current developments
;; and a list of past developments
(defvar current-figure)
(defvar current-line-spec)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Movement Control
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defvar pen-position nil)
(defvar pen-direction 2)
(defvar pen-speed 1.0)
(defvar pen-max-turn (/ radian 10))
(defvar pen-turn-damping 20)
(defvar pen-concentration-distance 10)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Curves
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Note that we don't try to match the line's finishing direction
;; This must be matched implicitly by reaching all the waypoints
(defvar next-waypoint)
(defvar waypoint-distance-tolerance 1)
(defun reaching-waypoint-impossible ()
"Will we not be able to reach the waypoint given the current parameters?"
;; How to factor in pen-concentration-distance if used?
;; How to factor in maximum amount of random change if used?
(let* ((steps-remaining (/ (point-distance pen-position next-waypoint)
pen-speed))
(direction-to-waypoint (angle-between-points pen-position
next-waypoint))
(direction-difference (- direction-to-waypoint pen-direction))
(min-turn-per-remaining-step (/ direction-difference steps-remaining)))
(< pen-max-turn min-turn-per-remaining-step)))
(defun veer-towards-waypoint ()
(let* ((direction-to-waypoint (angle-between-points pen-position
next-waypoint))
(direction-difference (- direction-to-waypoint pen-direction))
(direction-change (/ (min direction-difference pen-max-turn)
pen-turn-damping)))
(setf pen-direction (+ pen-direction direction-change))))
(defun close-enough-to-next-waypoint ()
(< (point-distance pen-position next-waypoint) waypoint-distance-tolerance))
(defproduction 'curves
"seeking to next waypoint"
(not (close-enough-to-next-waypoint))
=>
(veer-towards-waypoint)
(setf pen-position (offset-point-along-direction pen-position
pen-direction
pen-speed))
(set-cell-figure-outline (floor (point-x pen-position))
(floor (point-y pen-position))
current-figure)
(push pen-position (figure-outline current-figure)))
(defproduction 'curves
"close enough to to next waypoint"
(close-enough-to-next-waypoint)
=>
(set-context 'sectors))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Lines
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defstruct line-spec
from
from-angle
to
to-angle
curviness)
(defvar lines-for-current-development)
;; Used by Sectors, declared here to keep the compiler happy.
(defvar line-number-of-waypoints)
(defvar line-current-waypoint)
(defproduction 'lines
"finished drawing lines of current development"
(null lines-for-current-development)
=>
(set-context 'planning))
(defproduction 'lines
"drawing next line of current development"
(not (null lines-for-current-development))
=>
;; Lines should instantiate the line templates and call sectors for each
(setf current-line-spec (first lines-for-current-development))
(pop lines-for-current-development)
(set-context 'sectors)
(setf line-number-of-waypoints 1)
(setf line-current-waypoint 0)
(setf pen-position (line-spec-from current-line-spec))
(setf pen-direction (line-spec-from-angle current-line-spec)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Sectors
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun line-finished ()
;; Replace with a pen distance check
(= line-current-waypoint line-number-of-waypoints))
(defun set-waypoint ()
(incf line-current-waypoint)
(setf next-waypoint (line-spec-to current-line-spec)))
(defproduction 'sectors
"setting next waypoint"
(not (line-finished))
=>
(set-waypoint)
(set-context 'curves))
(defproduction 'sectors
"finished line"
(line-finished)
=>
(set-context 'lines))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Planning
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defvar planned-figure-space)
;; Just lines at the moment
;; Each development can consist of several lines...
(defun plan-line-figure ()
(setf current-figure (make-figure :allocated-space planned-figure-space))
(setf lines-for-current-development
;;FIXME: These should be line templates for lines to instantiate
(list (make-line-spec
:from (make-point (rectangle-left planned-figure-space)
(+ (rectangle-y planned-figure-space)
(/ (rectangle-height planned-figure-space)
2)))
:from-angle 1.6
:to (make-point (rectangle-right planned-figure-space)
(+ (rectangle-y planned-figure-space)
(/ (rectangle-height planned-figure-space)
2)))
:to-angle 1.6))))
(defun plan-loop-figure ()
(setf current-figure (make-figure :allocated-space planned-figure-space
:closed t))
(print planned-figure-space)
(setf lines-for-current-development
;;FIXME: These should be line templates for lines to instantiate
(list (make-line-spec
:from (make-point (rectangle-left planned-figure-space)
(+ (rectangle-y planned-figure-space)
(/ (rectangle-height planned-figure-space)
2)))
:from-angle 1.5
:to (make-point (rectangle-right planned-figure-space)
(+ (rectangle-y planned-figure-space)
(/ (rectangle-height planned-figure-space)
2)))
:to-angle 5)
(make-line-spec
:from (make-point (rectangle-right planned-figure-space)
(+ (rectangle-y planned-figure-space)
(/ (rectangle-height planned-figure-space)
2)))
:from-angle 5
:to (make-point (rectangle-left planned-figure-space)
(+ (rectangle-y planned-figure-space)
(/ (rectangle-height planned-figure-space)
2)))
:to-angle 1.5))))
(defproduction 'planning
"planning next development"
(not (null planned-figure-space))
=>
(if (> (random 1.0) 0.5)
(plan-loop-figure)
(progn (print "line")
(plan-line-figure)))
(print lines-for-current-development)
(setf planned-figure-space nil)
(set-context 'lines))
(defproduction 'planning
"finished planned development"
(null planned-figure-space)
=>
(when (figure-closed current-figure)
(apply-figure-fill current-figure))
(push current-figure *figures*)
(setf current-figure nil)
(set-context 'artwork))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Mapping
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defvar required-figure-space-width nil)
(defvar required-figure-space-height nil)
(defvar figure-allocation-failures 0)
(defvar figure-tries-this-time 0)
(defun call-mapping ()
(set-context 'mapping)
(setf planned-figure-space nil)
(setf figure-allocation-failures 0)
(setf figure-tries-this-time 0))
(defun allocation-failed-this-time ()
(> figure-tries-this-time 10))
(defun find-space-for-figure (width height &optional (tries 100))
"Very simple and dumb space-finding."
(let ((space nil))
(dotimes (i tries)
(let ((x (random (- *image-width* width)))
(y (random (- *image-height* height))))
(when (clear-ground-p x y width height)
(setf space (cons x y))
(return))))
space))
(defun try-to-find-space-for-figure ()
(let ((space (find-space-for-figure required-figure-space-width
required-figure-space-height)))
(cond
((not (null space))
(setf planned-figure-space
(make-rectangle :x (car space)
:y (cdr space)
:width required-figure-space-width
:height required-figure-space-height)))
(t
(incf figure-allocation-failures)
(setf planned-figure-space nil)))))
(defproduction 'mapping
"couldn't fulfill space requirement"
(allocation-failed-this-time)
=>
(incf figure-allocation-failures)
(setf figure-tries-this-time 0)
(set-context 'drawing))
(defproduction 'mapping
"fulfilled space requirement"
(not (null planned-figure-space))
=>
(setf required-figure-space-width nil)
(setf required-figure-space-height nil)
;; When planning can call mapping this will need changing
(set-context 'planning))
(defproduction 'mapping
"trying to fulfill space requirement"
(null planned-figure-space)
(not (allocation-failed-this-time))
=>
(try-to-find-space-for-figure))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Artwork
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; TODO: Decide on the number of small & large figures and general distribution
(defun enough-figures ()
(>= (length *figures*) 5))
(defun no-more-room ()
(> figure-allocation-failures 5))
(defun specify-required-figure-space ()
(setf required-figure-space-width (* 100 (random-range-int 1 5)))
(setf required-figure-space-height (* 100 (random-range-int 1 5))))
(defproduction 'artwork
"drawn enough figures"
(enough-figures)
=>
(set-context nil))
(defproduction 'artwork
"filled up the picture plane"
(no-more-room)
=>
(set-context nil))
(defproduction 'artwork
"specifying figure space to find"
(not (enough-figures))
(not (no-more-room))
=>
(specify-required-figure-space)
(call-mapping))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Tests
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun ben ()
(initialise-cell-matrix)
(roughen)
(setf *figures* '())
(set-context 'artwork)
(loop until (null *context*)
do (apply-production))
(write-cell-matrix-ppm-file))
| 12,204 | Common Lisp | .lisp | 294 | 34.078231 | 80 | 0.560759 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 65f7df80b2fd182a9b7c77f042d1e900a531afd2d7b19fc8532520a1af26e3cb | 17,563 | [
-1
] |
17,564 | test.lisp | rheaplex_rheart/ben/test.lisp | (load "random")
(load "geometry")
(load "image-cell-matrix")
(load "on-purpose-line")
(defun main ()
(test-draw-lines))
| 123 | Common Lisp | .lisp | 6 | 19 | 26 | 0.689655 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 01c145fa275835510a9845700f69778249ac1ea77227d112339220ba2c0a495b | 17,564 | [
-1
] |
17,565 | clopt.lisp | rheaplex_rheart/library/clopt.lisp | ;; clopt.lisp - Simple methods to get options from the command line.
;; Copyright 2007 Rhea Myers <[email protected]>
;;
;; This file is part of rheart.
;;
;; rheart is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3 of the License, or
;; (at your option) any later version.
;;
;; rheart is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;; Dummy until I sort command line options
(defmethod get-arg-value (long &key (short nil) (default nil)
(args *cli-args*))
default)
#|
(defparameter *cli-args* (ccl::command-line-arguments))
;; TODO: Consume parsed arguments
(defmethod get-arg (long &key (short nil) (args *cli-args*))
"Check the command line arguments for a unary switch."
(let ((result nil))
(dolist (arg args)
(when (or (equal long
arg)
(and short
(equal short
arg)))
(setf result t)
(return)))
result))
(defmethod get-arg-value (long &key (short nil) (default nil)
(args *cli-args*))
"Check the command line arguments for a switch with an accompanying value."
(let ((result nil)
(found nil))
(dolist (arg args)
;; If the last arg matched, return this one as the value
;;FIXME: Make sure it's not a - or --switch
(when (eq found
t)
(setf result arg)
(return))
;; When the arg matches, set a flag to return the next value
(when (or (equal long
arg)
(and short
(equal short
arg)))
(setf found t )))
;; Return the result or the value
(or result
default)))
(defmethod get-arg-values (long &key (short nil) (default '())
(args *cli-args*))
"Check the command line arguments for possibly many occurrences of a switch with an accompanying value."
(let ((result nil)
(found nil))
(dolist (arg args)
;; If the last arg matched, return this one as the value
;;FIXME: Make sure it's not a - or --switch
(when (eq found
t)
(setf result arg))
;; When the arg matches, set a flag to return the next value
(when (or (equal long
arg)
(and short
(equal short
arg)))
(setf found t )))
;; Return the result (in the order found on the command line) or the value
(or (reverse result)
default)))
|# | 2,687 | Common Lisp | .lisp | 80 | 29.475 | 106 | 0.672182 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 02c8f81d9d4aaf071cdacfa491d3d5e8cce54b51944e4d8f612d3cc7323be500 | 17,565 | [
-1
] |
17,566 | utilities.lisp | rheaplex_rheart/library/utilities.lisp | ;; utilities.lisp - Various utilities.
;; Copyright (C) 2004 Rhea Myers [email protected]
;;
;; This file is part of rheart.
;;
;; rheart is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3 of the License, or
;; (at your option) any later version.
;;
;; rheart is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
(defmacro while (test &rest body)
"Execute the body until test evaluates to false."
`(do ()
((not ,test))
,@body))
(defmacro until (test &rest body)
"Execute the body until test evaluates to true."
`(do ()
((eq t
,test))
,@body))
(defmethod debug-message (msg)
"Write the message to the error stream, not to standard output."
(format *debug-io*
"~A~%"
msg)
(finish-output *debug-io*)) | 1,207 | Common Lisp | .lisp | 34 | 32.823529 | 72 | 0.707088 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | de094bf125a1746afb60e3618c0961f44a7696a590b058214518f0aba355f1f0 | 17,566 | [
-1
] |
17,567 | run.lisp | rheaplex_rheart/cybernetic/run.lisp | ;; run.lisp : random image description generator
;;
;; Copyright (c) 2009 Rhea Myers, [email protected]
;;
;; This file is part of The Cybernetic Artwork Nobody Wrote ("Cybernetic").
;;
;; Cybernetic is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3 of the License, or
;; (at your option) any later version.
;;
;; Cybernetic is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
(load "./cybernetic.lisp")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; GO
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun run ()
(format t "~a~%" (generate-description))
(finish-output)
(quit))
;; Just call the main method when loaded
(run) | 1,160 | Common Lisp | .lisp | 28 | 39.964286 | 79 | 0.640071 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | aa90a1a48a181d2bbf482c3274e705d48c8fb25eb8908fb80b638404b121388c | 17,567 | [
-1
] |
17,568 | cybernetic.lisp | rheaplex_rheart/cybernetic/cybernetic.lisp | ;; cybernetic.lisp : random image description generator
;;
;; Copyright (c) 2004 Rhea Myers, [email protected]
;;
;; This file is part of The Cybernetic Artwork Nobody Wrote ("Cybernetic").
;;
;; Cybernetic is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3 of the License, or
;; (at your option) any later version.
;;
;; Cybernetic is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Constants
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defconstant the-random-state (make-random-state t))
;; Utilities
(defun maybe (fun &key (probability 0.5) (default nil))
"Call fun if random(0..1) is less than probability."
(if (< (random 1.0 the-random-state) probability)
(funcall fun)
default))
(defun choose-randomly (choices)
"Choose one of the parameters randomly."
(nth (random (list-length choices) the-random-state)
choices))
(defun choose-randomly-deep (choices)
"Choose one item from a list of lists."
(choose-randomly (choose-randomly choices)))
(defun concatenate-string (&rest strings)
"Concatenate a list of strings with an optional given prefix, separator and suffix."
(let ((all (car strings)))
(dolist (s (cdr strings))
(when (not (equal s ""))
(setf all (concatenate 'string all
(if (equal all "")
""
" ")
s))))
all))
(defun pluralise (object plurality)
"Make a word plural if necessary."
(if (equal plurality "A")
object
(concatenate 'string object "s")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Generators
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun amount ()
"Generate a quantity description."
(choose-randomly '("A" "A pair of" "Some" "Many")))
;; Appearance
(defparameter monochromes '("black" "grey" "white"))
(defparameter hues '("red" "orange" "yellow" "green" "blue" "purple"))
(defparameter colours '("magenta" "cyan" "brown" "pink" "turquoise" "mauve"))
(defparameter metals '("gold" "silver" "bronze" "platinum" "copper"
"rust-coloured"))
(defparameter fabrics '("khaki" "cotton-coloured" "denim blue"
"suede-coloured"))
(defparameter naturals '("sky blue" "leaf green" "sea green" "sunset red"))
(defparameter artificials '("neon blue" "sunset yellow" "shocking pink"
"non-repro blue" "blue-screen blue"))
(defparameter palettes (list monochromes hues colours metals fabrics naturals
artificials))
(defparameter tone '("pale" "" "rich" "bright" "" "dark"))
(defun colour ()
"Generate a colour description."
(concatenate-string (choose-randomly tone)
(choose-randomly-deep palettes)))
(defun texture ()
"Choose a texture."
(choose-randomly '("halftoned" "crosshatched" "scumbled" "glazed" "sketchy"
"smooth")))
(defun appearance ()
"Generate the appearance of a figure."
(concatenate-string (maybe #'texture :default "")
(colour)))
;; Shape
(defun shape-size ()
"Generate a size for the shape."
(choose-randomly '("" "" "tiny" "small" "large" "massive")))
(defparameter geometric '("circle" "triangle" "square" "pentagon" "hexagon"
"octagon"))
(defparameter form '("organic shape" "spiky shape" "irregular shape"))
(defparameter abstract-shapes (list geometric form))
(defparameter abstract-shape-treatment '("" "" "outlined"))
(defparameter building '("house" "skyscraper"))
(defparameter transport '("car" "aeroplane" "ship"))
(defparameter animal '("bird" "cat" "dog" "horse"))
(defparameter generic-shapes (list building transport animal))
(defparameter generic-shape-treatments '("" "" "" "silhouetted" "outlined"
"abstracted"))
(defun shape-form (plural)
"Generate a shape form description."
(cond
((> (random 1.0 the-random-state) 0.5)
(concatenate-string (choose-randomly abstract-shape-treatment)
(pluralise (choose-randomly-deep abstract-shapes) plural)))
(t
(concatenate-string (choose-randomly generic-shape-treatments)
(pluralise (choose-randomly-deep generic-shapes) plural)))))
(defun shape (plural)
"Generate a shape description."
(concatenate-string (shape-size)
(appearance)
(shape-form plural)))
;; Ground
(defun ground ()
"Generate a simple ground description."
(appearance))
;; Description
(defun generate-description ()
"Describe a single (set of) figure(s) on a single ground."
(let ((plural (amount)))
(concatenate-string plural (shape plural)
"on a" (ground) "ground."))) | 5,042 | Common Lisp | .lisp | 122 | 38.090164 | 86 | 0.6604 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 946a826cda9ae973332565040db82c5f5e176645a02cceed9b6ce44a4df37100 | 17,568 | [
-1
] |
17,569 | package.lisp | rheaplex_rheart/colour-cells/package.lisp | ;; package.lisp - The main package for colour-cell
;; Copyright (C) 2006 Rhea Myers [email protected]
;;
;; This file is part of colour-cells.
;;
;; colour-cells is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3 of the License, or
;; (at your option) any later version.
;;
;; colour-cells is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
(in-package "CL-USER")
(eval-when (:COMPILE-TOPLEVEL :LOAD-TOPLEVEL :EXECUTE)
(defpackage COLOUR-CELLS
(:documentation
"The colour-cells package.")
(:use common-lisp)
(:export run))) | 988 | Common Lisp | .lisp | 24 | 39.708333 | 72 | 0.750779 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 1bda3f40424084445e96e04c23d8d8231c6788f8a9feae2538655d443c2748e8 | 17,569 | [
-1
] |
17,570 | colouring-new.lisp | rheaplex_rheart/colour-cells/colouring-new.lisp | ;; colour-scheme.lisp - Colour scheme generation and application.
;; Copyright (C) 2006 Rhea Myers [email protected]
;;
;; This file is part of colour-cells.
;;
;; colour-cells is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3 of the License, or
;; (at your option) any later version.
;;
;; colour-cells is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;; Acronyms:
;; lmh = low, medium, high
;; sv = saturation, value
(in-package "COLOUR-CELLS")
(defconstant minimum-spec-probability 3)
(defconstant maximum-spec-probability 9)
(defconstant minimum-spec-count 2)
(defconstant maximum-spec-count 3)
(defconstant sv-spec-options '('ll 'lm 'lh 'ml 'mm 'mh 'hl 'hm 'hh))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; LMH - Low medium and high value ranges from 0.0..1.0
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defclass lmh-values ()
((lows :type vector
:initform (make-vector 7)
:initarg :lows
:accessor low-values)
(mediums :type vector
:initform (make-vector 7)
:initarg :mediums
:accessor medium-values)
(highs :type vector
:initform (make-vector 7)
:initarg :highs
:accessor high-values))
(:documentation
"A range of values divided into low, medium and high values."))
(defun make-random-low-values (count medium-start)
"Generate count random low values."
(map-into (make-vector count)
(lambda () (random-range 0.0 medium-start))))
(defun make-random-medium-values (count medium-start high-start)
"Generate count random medium values."
(map-into (make-vector count)
(lambda () (random-range medium-start high-start))))
(defun make-random-high-values (count high-start)
"Generate count random high values."
(map-into (make-vector count)
(lambda () (random-range high-start 1.0))))
(defmethod make-lmh (count medium-start high-start)
"Make an lmh."
(let* ((low-count (random-range 1 (- count 2)))
(medium-count (random-range 1 (- count low-count 1)))
(high-count (- count medium-count low-count)))
(make-instance 'lmh-values
:lows (make-random-low-values low-count
medium-start)
:mediums (make-random-medium-values medium-count
medium-start
high-start)
:highs (make-random-high-values high-count
high-start))))
(defmethod random-low-value ((lmh lmh-values))
"Randomly choose a value from the list of low values of the lmh."
(choose-one-of (low-values lmh)))
(defmethod random-medium-value ((lmh lmh-values))
"Randomly choose a value from the list of medium values of the lmh."
(choose-one-of (medium-values lmh)))
(defmethod random-high-value ((lmh lmh-values))
"Randomly choose a value from the list of medium values of the lmh."
(choose-one-of (high-values lmh)))
(defmethod random-lmh-value (lmh which)
"Return a random low ('l), medium ('m) or high ('h) value based on which."
(case which
('l (random-low-value lmh))
('m (random-medium-value lmh))
('h (random-high-value lmh))))
(defmethod print-lmh (lmh)
(format t "low: ")
(loop for l across (low-values lmh)
do (format t "~a " l))
(format t "~%medium: ")
(loop for m across (medium-values lmh)
do (format t "~a " m))
(format t "~%high: ")
(loop for h across (high-values lmh)
do (format t "~a " h))
(format t "~%"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Colour Scheme
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defclass colour-scheme ()
((hues :type hash-table
:initarg :hues
:initform (make-hash-table)
:accessor colour-scheme-hues)
(saturations :type lmh-values
:initarg :saturations
:initform (make-instance 'lmh-values)
:accessor colour-scheme-saturations)
(values :type lmh-values
:initarg :values
:initform (make-instance 'lmh-values)
:accessor colour-scheme-values))
(:documentation "The values describing a colour scheme."))
(defmethod print-colour-scheme (scheme)
(format t "Colour Scheme:~%")
(format t "hues:~%")
(maphash (lambda (key value)
(format t "~a ~a " key value))
(colour-scheme-hues scheme))
(format t "~%saturations:~%")
(print-lmh (colour-scheme-saturations scheme))
(format t "values:~%")
(print-lmh (colour-scheme-values scheme)))
(defmethod symbol-colour-scheme-hue (scheme hue-id)
"Get the hue value from the scheme for a given id, eg :stem, :stalk."
(gethash hue-id (colour-scheme-hues scheme)))
(defmethod random-colour-scheme-saturation (scheme spec)
"Choose a saturation from the range specified by spec."
(random-lmh-value (colour-scheme-saturations scheme)
spec))
(defmethod random-colour-scheme-value (scheme spec)
"Choose a value from the range specified by spec."
(random-lmh-value (colour-scheme-values scheme)
spec))
(defmethod sv-spec-components (spec)
"Return each half of the symbol specifying how to choose saturation & value."
(case spec
('ll (values 'l 'l))
('lm (values 'l 'm))
('lh (values 'l 'h))
('ml (values 'm 'l))
('mm (values 'm 'm))
('mh (values 'm 'h))
('hl (values 'h 'l))
('hm (values 'h 'm))
('hh (values 'h 'h))))
(defmethod make-colour-by-sv-spec (scheme hue-id sv-spec)
"Choose a colour for the hue id using the sv-spec eg 'lm, 'hh, 'ml."
(multiple-value-bind
(saturationspec valuespec) (sv-spec-components sv-spec)
(make-instance 'colour
:hue (symbol-colour-scheme-hue scheme hue-id)
:saturation (random-colour-scheme-saturation scheme
saturationspec)
:brightness (random-colour-scheme-value scheme
valuespec))))
;; Generate additive colour range
(defmethod make-hue-additive-series (hue-list)
(let ((series (make-hash-table))
(hue-value (random 1.0)))
(dolist (hue-symbol hue-list)
(setf hue-value (mod (+ hue-value (random 0.3))
1.0))
(setf (gethash hue-symbol series)
hue-value))
series))
(defmethod make-colour-scheme (hue-list saturations values medium high)
"Make a colour scheme for the saturation symbol list."
(make-instance 'colour-scheme
:hues (make-hue-additive-series hue-list)
:saturations (make-lmh saturations medium high)
:values (make-lmh values medium high)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Applying colour schemes
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defclass colour-scheme-applier ()
((scheme :type colour-scheme
:accessor applier-scheme
:initarg :scheme)
(count :type integer
:initform 1
:accessor applier-count
:documentation "How many objects this applier haas coloured.")
(check :type integer
:initform 5
:initarg :check
:accessor applier-when-to-check
:documentation "How often to check deviation.")
;; This one is more part of the scheme but is more convenient here
(sv-chooser :initarg :sv-chooser
:initform (lambda () 'll)
:accessor applier-sv-chooser
:documentation "The function to choose sv values.")
(sv-probabilites :type hash-table
:initform (make-hash-table)
:initarg :sv-probabilities
:accessor applier-probabilities
:documentation "The probabilities of the chooser sv specs")
(sv-occurrences :type hash-table
:initform (make-hash-table)
:accessor applier-occurences
:documentation "How often each sv spec has been chosen."))
(:documentation
"The data used in applying a colour scheme to an image."))
(defmethod set-applier-probabilities (applier spec-list)
"Set the probabilites from a list of num/specs, and set occurences to zero"
(let ((total-prob (float (prefs-range spec-list))))
(loop for prob in spec-list by #'cddr
for spec in (cdr spec-list) by #'cddr
do (setf (gethash (dequote spec)
(applier-probabilities applier))
(/ prob total-prob))
do (setf (gethash (dequote spec)
(applier-occurences applier)) 0))))
(defmethod set-applier-chooser (applier spec-list)
"Make and set the chooser function for sv specs from the list."
(setf (applier-sv-chooser applier)
(prefs-list-lambda spec-list)))
(defmethod set-applier-sv-spec (applier spec-list)
"Configure the applier from the sv spec eg '(1 'hh 4 'ml 3 'lm)"
(set-applier-chooser applier spec-list)
(set-applier-probabilities applier spec-list))
;; Change to being an :after initialize-instance method
(defmethod make-colour-scheme-applier (scheme spec-list)
"Make a colour scheme applier."
(let ((applier (make-instance 'colour-scheme-applier
:scheme scheme)))
(set-applier-chooser applier spec-list)
(set-applier-probabilities applier spec-list)
applier))
(defmethod spec-probability-difference (applier spec)
"Get the difference between the intended and actual occurence of a spec."
(let* ((generation-count (float (applier-count applier)))
(spec-count (gethash spec (applier-occurences applier)))
(target (float (gethash spec (applier-probabilities applier))))
(current (/ spec-count generation-count))
(difference (- target current)))
(format t " ~a ~a ~,3F ~,3F ~,3F~%"
spec spec-count target current difference)
difference))
(defmethod most-deviant-spec (applier)
"Find the spec that is being called the least compared to its probability."
(let ((highest 0.0)
(result nil))
(maphash #'(lambda (key val)
(declare (ignore val))
(let ((difference (spec-probability-difference applier key)))
(when (> difference highest)
(setf highest difference)
(setf result key))))
(applier-probabilities applier))
(format t "~a~%" result)
result))
(defmethod increase-spec-count (applier spec)
"Update the number of times a spec has been used."
(incf (gethash spec (applier-occurences applier))))
(defmethod increase-applier-count (applier)
"Increase the applier's count of objects it has been called for by 1."
(incf (applier-count applier)))
(defmethod update-applier-state (applier spec)
"Call when you've applied colour to an object & are ready for the next one."
(increase-spec-count applier spec)
(increase-applier-count applier))
(defmethod applier-should-correct (applier)
"Decide whether the applier should correct the spec probability error."
(eq (mod (applier-count applier)
(applier-when-to-check applier))
0))
(defmethod applier-spec-choice (applier hue-id)
"Choose the spec to be used."
(if (applier-should-correct applier)
(most-deviant-spec applier)
(funcall (applier-sv-chooser applier))))
(defmethod choose-colour-for (applier hue-id)
"Choose a colour from the scheme for the hue-id."
(let* ((spec (applier-spec-choice applier hue-id))
(choice (make-colour-by-sv-spec (applier-scheme applier)
hue-id spec)))
(update-applier-state applier spec)
choice))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; How to make and apply a colour scheme
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun chooser-spec ()
"Construct a list describing a random spec pref, eg (6 'll 3 'hm 2 'lh)."
(loop for spec in (choose-n-of (random-range-inclusive minimum-spec-count
maximum-spec-count)
sv-spec-options)
collect (random-range-inclusive minimum-spec-probability
maximum-spec-probability)
collect spec))
(defmethod colour-objects (drawing symbols)
(let* ((scheme (make-colour-scheme symbols 7 7 .3 .6))
(sv-spec-list (chooser-spec))
(applier (make-colour-scheme-applier scheme sv-spec-list)))
(print-colour-scheme scheme)
(format t "sv-spec: ~a~%" sv-spec-list)
(format t "Colouring forms.~%")
(setf (ground drawing)
(choose-colour-for applier
'background))
(loop for figure across (figures drawing)
do (loop for form across (forms figure)
do (setf (fill-colour form)
(choose-colour-for applier
(object-symbol form)))))))
| 12,450 | Common Lisp | .lisp | 305 | 37.07541 | 79 | 0.672566 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 083b9e1d1da9ee48855a08d7067d79f42f709fbc7adaad59eca228048abdbc2a | 17,570 | [
-1
] |
17,571 | utilities.lisp | rheaplex_rheart/colour-cells/utilities.lisp | ;; utilities.lisp - Various utilities.
;; Copyright (C) 2006 Rhea Myers [email protected]
;;
;; This file is part of colour-cells.
;;
;; colour-cells is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3 of the License, or
;; (at your option) any later version.
;;
;; colour-cells is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
(in-package "COLOUR-CELLS")
(defmethod debug-message (msg)
"Write the message to the error stream, not to standard output."
(format *debug-io*
"~A~%"
msg)
(finish-output *debug-io*))
(defmethod advisory-message (msg)
"Write the message to the error stream, not to standard output. No newline."
(format *debug-io*
msg)
(finish-output *debug-io*))
(defmethod dequote (item)
"Remove the quote from a symbol, returning the symbol."
(cadr item))
(defmethod random-number (a)
"The built in random doesn't like 0.0 ."
(if (= a 0)
a
(random a)))
(defmethod random-range (a b)
"Make a random number from a to below b."
(let ((range (- b a)))
(if (= range 0)
a
(+ (random range) a))))
(defmethod random-range-inclusive ((a integer) (b integer))
"Make a random number from a to below b."
(let ((range (+ (- b a) 1)))
(if (= range 0)
a
(+ (random range) a))))
(defmethod choose-one-of ((possibilities list))
"Choose one or none of the options."
(nth (random (length possibilities)) possibilities))
(defmethod choose-one-of ((possibilities vector))
"Choose one or none of the options."
(aref possibilities (random (length possibilities))))
(defmethod maybe-choose-one-of (possibilities)
"Choose one or none of the options."
(when (< (random 1.0) 0.5)
(choose-one-of possibilities)))
(defmethod maybe-choose-some-of (possibilities probability)
"Choose none or more possibilities when random 1.0 < probability for it."
(loop for item in possibilities
when (< (random 1.0) probability)
collect item))
(defun choose-n-of (n choice-list)
"Choose n different entries from choice-list."
(assert (<= n (length choice-list)))
(let ((choices choice-list)
(chosen '()))
(dotimes (i n)
(let ((choice (choose-one-of choices)))
(setf chosen (cons choice chosen))
(setf choices (remove choice choices))))
chosen))
(defun prefs-range (spec)
"Get the total probability range of a prefs spec."
(loop for prob in spec by #'cddr
sum prob))
(defun prefs-cond (spec)
"Make a cond to choose an option. eg (prefs 4 'a 4 'b 2 'c)"
`(let ((i (random ,(prefs-range spec))))
(cond
,@(loop for prob in spec by #'cddr
for val in (cdr spec) by #'cddr
sum prob into prob-so-far
collect `((< i ,prob-so-far) ,val)))))
(defmacro prefs (&rest spec)
"Make a prefs cond to choose an option. eg (prefs 4 'a 4 'b 2 'c)"
(prefs-cond spec))
(defmacro prefs-list (spec)
"Make a prefs cond to choose an option. eg (prefs-list '(4 'a 3 'b))"
(prefs-cond spec))
(defun prefs-lambda (&rest spec)
"Make a lambda to choose an option. eg (prefs-lambda 4 'a 4 'b 2 'c)"
(eval `(lambda () ,(prefs-cond spec))))
(defun prefs-list-lambda (spec)
"Make a lambda to choose an option. eg (prefs-list-lambda '(4 'a 3 'b))"
(eval `(lambda () ,(prefs-cond spec))))
(defmethod make-vector (initial-size)
"Make a stretchy vector."
(make-array initial-size
:adjustable t
:fill-pointer 0))
(defmacro while (test &rest body)
`(do ()
((not ,test))
,@body))
(defmacro until (test &rest body)
`(do ()
(,test)
,@body))
(defmacro dovector ((var vec) &rest body)
`(loop for ,var across ,vec
do (progn ,@body))) | 4,072 | Common Lisp | .lisp | 114 | 32.421053 | 78 | 0.680163 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 5252bff68e5a9ea6013b3822706cafe86233d9f000da7a54ed519063f8228035 | 17,571 | [
-1
] |
17,572 | load.lisp | rheaplex_rheart/colour-cells/load.lisp | ;; load.lisp - Load the asdf system.
;; Copyright (C) 2004 Rhea Myers [email protected]
;;
;; This file is part of colour-cells.
;;
;; colour-cells is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3 of the License, or
;; (at your option) any later version.
;;
;; colour-cells is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
(load "colour-cells.asd")
(asdf:operate 'asdf:load-op :colour-cells) | 853 | Common Lisp | .lisp | 19 | 43.736842 | 72 | 0.7506 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 724fe0e1287ba7b723c15ad08dba83124180a8fe02598e553427b8742ff97b52 | 17,572 | [
-1
] |
17,573 | point.lisp | rheaplex_rheart/colour-cells/point.lisp | ;; point.lisp - A 2D point.
;; Copyright (C) 2006 Rhea Myers [email protected]
;;
;; This file is part of colour-cells.
;;
;; colour-cells is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3 of the License, or
;; (at your option) any later version.
;;
;; colour-cells is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
(in-package "COLOUR-CELLS")
(defclass point ()
((x :accessor x
:type float
:initform 0.0
:initarg :x
:documentation "The x co-ordinate of the point.")
(y :accessor y
:type float
:initform 0.0
:initarg :y
:documentation "The y co-ordinate of the point."))
(:documentation "A simple cartesian point on the picture plane (or page).
y goes up"))
(defmethod distance ((left point) (right point))
"The distance between two points."
(sqrt (+ (expt (- (x right) (x left)) 2)
(expt (- (y right) (y left)) 2))))
(defmethod distance-point-co-ordinates ((left point) x2 y2)
"The distance between two points."
(sqrt (+ (expt (- x2 (x left)) 2)
(expt (- y2 (y left)) 2))))
(defmethod distance-to-closest-point ((p1 point) &rest points)
"Get the distance to the point closest to p1"
(let ((dist nil))
(dolist (p points)
(let ((new-dist (distance p1 p)))
(if (or (not dist) (< new-dist dist))
(setq dist new-dist))))
dist))
(defun random-co-ordinates (x-range y-range)
"Make random co-ordinates avoiding bell-curve point distribution."
;; Yay bignum!
(floor (random (+ x-range y-range))
x-range))
(defmethod random-point-in-bounds (x y width height)
"Make a point placed randomly within the given bounds."
(multiple-value-bind
(x-dist y-dist) (random-co-ordinates width height)
(make-instance 'point
:x (+ x x-dist)
:y (+ y y-dist))))
(defmethod translate-point ((p point) by-x by-y)
"Make a translated copy of the point."
(make-instance 'point
:x (+ (x p) by-x)
:y (+ (y p) by-y)))
(defmethod co-ordinates-at-angle-around-point-co-ordinates (a b r theta)
"Get the point on the circumference of the circle at theta."
(values (+ a (* r (cos theta)))
(+ b (* r (sin theta)))))
(defmethod co-ordinates-at-angle (obj theta)
"Get the point on the circumference of the arc/circle at theta.
Doesn't check limits of arc."
(co-ordinates-at-angle-around-point-co-ordinates (x obj) (y obj) (radius obj)
theta))
(defmethod angle-between-two-points-co-ordinates (x1 y1 x2 y2)
"Calculate the angle of the second point around the first."
(let ((dx (- x2 x1))
(dy (- y2 y1)))
(cond
((= dx 0.0)
(cond
((= dx 0.0) 0.0)
((> dy 0.0) (/ pi 2.0))
(t (* pi 2.0 3.0))))
((= dy 0.0)
(cond
((> dx 0.0) 0.0)
(t pi)))
(t
(cond
((< dx 0.0) (+ (atan (/ dy dx)) pi))
((< dy 0.0) (+ (atan (/ dy dx)) (* pi 2)))
(t (atan (/ dy dx))))))))
(defmethod angle-between-two-points ((p1 point) (p2 point))
"Calculate the angle of the second point around the first."
(angle-between-two-points-co-ordinates (x p1) (y p1) (x p2) (y p2)))
(defmethod highest-leftmost-of ((p1 point) (p2 point))
"Compare and return the highest leftmost point."
(if (or (> (y p1) (y p2))
(and (= (y p1) (y p2))
(< (x p1) (x p2))))
p1
p2)) | 3,732 | Common Lisp | .lisp | 102 | 32.647059 | 79 | 0.64175 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 722400ba5b11a85bf845f27e4fab2c657e03880376229c5ded79e94f8844f11b | 17,573 | [
-1
] |
17,574 | run.lisp | rheaplex_rheart/colour-cells/run.lisp | ;; run.lisp - Load the asdf system and make a drawing
;; Copyright (C) 2004 Rhea Myers [email protected]
;;
;; This file is part of colour-cells.
;;
;; colour-cells is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3 of the License, or
;; (at your option) any later version.
;;
;; colour-cells is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
(load "draw-something.asd")
(asdf:operate 'asdf:load-op :draw-something)
(draw-something:run)
(quit) | 905 | Common Lisp | .lisp | 21 | 41.809524 | 72 | 0.751982 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | b6cdabfd88d70208462e718faf9fc28605449bedb3fb670845a512ca9acbf645 | 17,574 | [
-1
] |
17,575 | postscript.lisp | rheaplex_rheart/colour-cells/postscript.lisp | ;; postscript.lisp - Writing PostScript to streams.
;; Copyright (C) 2006 Rhea Myers [email protected]
;;
;; This file is part of colour-cells.
;;
;; colour-cells is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3 of the License, or
;; (at your option) any later version.
;;
;; colour-cells is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
(in-package "COLOUR-CELLS")
(defvar *ps-stream* t)
(defmethod write-eps-header (width height &key (to *ps-stream*))
"Write the standard raw PostScript header."
(format to "%!PS-Adobe-3.0 EPSF-3.0~%")
(format to "%%BoundingBox: 0 0 ~D ~D~%" width height))
(defmethod write-eps-footer (&key (to *ps-stream*))
"Write the standard (but optional PostScript footer"
(format to "%%EOF~%"))
(defmethod write-rgb (r g b &key (to *ps-stream*))
"Set the PostScript RGB colour value."
(format to "~F ~F ~F setrgbcolor~%" r g b))
(defmethod write-colour ((col colour) &key (to *ps-stream*))
(multiple-value-bind (r g b) (hsb-to-rgb col)
(write-rgb r g b :to to)))
(defmethod write-rectfill ((rect rectangle) &key (to *ps-stream*))
"Draw a rectangle with the given co-ordinates and dimensions."
(format to "~F ~F ~F ~F rectfill~%" (x rect) (y rect) (width rect)
(height rect))) | 1,697 | Common Lisp | .lisp | 36 | 45.111111 | 72 | 0.711782 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | d6a6699896907fb4339b312c0eb0b34c6384c9fae6609721e66d298bbde48aba | 17,575 | [
-1
] |
17,576 | rectangle.lisp | rheaplex_rheart/colour-cells/rectangle.lisp | ;; rectangle.lisp - A 2D rectangle.
;; Copyright (C) 2006 Rhea Myers [email protected]
;;
;; This file is part of colour-cells.
;;
;; colour-cells is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3 of the License, or
;; (at your option) any later version.
;;
;; colour-cells is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
(in-package "COLOUR-CELLS")
(defclass rectangle ()
((x :accessor x
:type float
:initform 0.0
:initarg :x
:documentation "The lower left x co-ordinate of the rectangle.")
(y :accessor y
:type float
:initform 0.0
:initarg :y
:documentation "The lower left y co-ordinate of the rectangle.")
(width :accessor width
:type float
:initform 0.0
:initarg :width
:documentation "The width of the rectangle.")
(height :accessor height
:type float
:initform 0.0
:initarg :height
:documentation "The height of the rectangle."))
(:documentation "A simple rectangle"))
(defmethod copy-rectangle ((r rectangle))
"Make a copy of the rectangle."
(make-instance 'rectangle
:x (x r) :y (y r) :width (width r) :height (height r)))
(defmethod random-point-in-rectangle ((bounds-rect rectangle))
"Make a point placed randomly within the given bounding rectangle."
(make-instance 'point
:x (+ (x bounds-rect) (random (width bounds-rect)))
:y (+ (y bounds-rect) (random (height bounds-rect)))))
(defmethod random-points-in-rectangle ((bounds-rect rectangle) count)
"Create the specified number of points placed randomly within the given rectangle."
(let ((points (make-vector count)))
(map-into (random-point-in-rectangle bounds-rect) points)
points))
(defmethod random-rectangle-in-rectangle ((bounds-rect rectangle))
"Make a random rectangle of at least size 1x1 in another rectangle."
(let* ((new-width (random (width bounds-rect)))
(new-height (random (height bounds-rect)))
(new-x (+ (x bounds-rect)
(random (- (width bounds-rect) new-width))))
(new-y (+ (y bounds-rect)
(random (- (height bounds-rect) new-height)))))
(make-instance 'rectangle
:x new-x
:y new-y
:width new-width
:height new-height)))
(defmethod random-rectangle-in-rectangle-size (in new-width new-height)
"Make a random rectangle of the given size in the given bounds."
(assert (<= new-width (width in)))
(assert (<= new-height (height in)))
(let ((new-x (+ (x in)
(random-number (- (width in) new-width))))
(new-y (+ (y in)
(random-number (- (height in) new-height)))))
(make-instance 'rectangle
:x new-x
:y new-y
:width new-width
:height new-height)))
(defmethod random-rectangle-in-rectangle ((bounds-rect rectangle))
"Make a random rectangle of at least size 1x1 in another rectangle."
(let* ((new-width (random (width bounds-rect)))
(new-height (random (height bounds-rect)))
(new-x (+ (x bounds-rect)
(random (- (width bounds-rect) new-width))))
(new-y (+ (y bounds-rect)
(random (- (height bounds-rect) new-height)))))
(make-instance 'rectangle
:x new-x
:y new-y
:width new-width
:height new-height)))
(defmethod inset-rectangle ((source rectangle) (offset real))
"Trim a rectangle by the given amount."
(make-instance 'rectangle
:x (+ (x source) offset)
:y (+ (y source) offset)
:width (- (width source) (* offset 2.0))
:height (- (height source) (* offset 2.0))))
(defmethod area ((rect rectangle))
"Get the rectangle's area."
(* (width rect) (height rect)))
(defmethod contains-point-co-ordinates ((rect rectangle) x y)
"Find whether the rectangle contains the point."
(if (and (> x (y rect))
(< x (+ (x rect) (width rect)))
(> y (y rect))
(< y (+ (y rect) (height rect))))
t
nil))
(defmethod contains ((rect rectangle) (p point))
"Find whether the rectangle contains the point."
(contains-point-co-ordinates rect (x p) (y p)))
(defmethod intersects ((rect1 rectangle) (rect2 rectangle))
"Find whether the rectangles intersect."
(and (< (x rect1) (+ (x rect2) (width rect2)))
(< (y rect1) (+ (y rect2) (height rect2)))
(> (+ (x rect1) (width rect1)) (x rect2))
(> (+ (y rect1) (height rect1)) (y rect2))))
(defmethod include-point ((rect rectangle) (p point))
"Destructively expand the rectangle to include the point."
(let ((right (+ (x rect) (width rect)))
(top (+ (y rect) (height rect))))
(cond
((< (x p) (x rect))
(setf (width rect)
(+ (width rect) (- (x rect) (x p))))
(setf (x rect) (x p)))
((> (x p) right)
(setf (width rect)
(+ (width rect) (- (x p) right))))
((< (y p) (y rect))
(setf (height rect)
(+ (height rect) (- (y rect) (y p))))
(setf (y rect) (y p)))
((> (y p) top)
(setf (height rect)
(+ (height rect) (- (y p) top)))))))
(defmethod include-rectangle ((rect rectangle) (include rectangle))
"Expand the first rectangle to include the second."
(include-point rect (make-instance 'point :x (x include) :y (y include)))
(include-point rect (make-instance 'point :x (x include)
:y (+ (y include) (height include))))
(include-point rect (make-instance 'point :x (+ (x include) (width include))
:y (+ (y include) (height include))))
(include-point rect (make-instance 'point :x (+ (x include) (width include))
:y (y include))))
(defmethod rectangle-from-point ((p point))
"Make a zero-size rectangle for a point."
(make-instance 'rectangle :x (x p) :y (y p) :width 0.0 :height 0.0)) | 6,054 | Common Lisp | .lisp | 151 | 35.668874 | 85 | 0.649168 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 5c1678fb34a2b612fd0774212a00bde5d0b8d42317ffe847260054e7305c7f2e | 17,576 | [
-1
] |
17,577 | colour.lisp | rheaplex_rheart/colour-cells/colour.lisp | ;; colour.lisp - Colour handling.
;; Copyright (C) 2006 Rhea Myers [email protected]
;;
;; This file is part of colour-cells.
;;
;; colour-cells is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3 of the License, or
;; (at your option) any later version.
;;
;; colour-cells is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
(in-package "COLOUR-CELLS")
(defclass colour ()
((hue :accessor hue
:initform 1.0
:initarg :hue
:documentation "The colour-wheel hue of the colour.")
(saturation :accessor saturation
:initform 1.0
:initarg :saturation
:documentation "The saturation of the colour.")
(brightness :accessor brightness
:initform 1.0
:initarg :brightness
:documentation "The brightness of the colour."))
(:documentation "A colour"))
(defmethod random-colour ()
"Make a random colour."
(make-instance 'colour :hue (random 1.0) :saturation (random 1.0)
:brightness (random 1.0)))
(defmethod hsb-to-rgb ((col colour))
"Convert the hue/saturation/brightness colour to RGB."
(if (= (saturation col) 0)
(values-list (list (brightness col) (brightness col) (brightness col)))
(let* ((p (* (brightness col)
(- 1.0
(saturation col))))
(q (* (brightness col)
(- 1.0
(* (saturation col) (hue col)))))
(tt (* (brightness col)
(- 1.0
(* (saturation col)
(- 1.0 (hue col)))))))
(case (floor (* (hue col) 5.0))
((0) (values-list (list (brightness col) tt p))) ;; Red
((1) (values-list (list q (brightness col) p))) ;; Yellow
((2) (values-list (list p (brightness col) tt))) ;; Green
((3) (values-list (list p q (brightness col)))) ;; Cyan
((4) (values-list (list tt p (brightness col)))) ;; Blue
((5) (values-list (list (brightness col) p q))))))) ;; Magenta
| 2,228 | Common Lisp | .lisp | 57 | 35.877193 | 77 | 0.675588 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 0d65729bfdd84ae9653ff93a7ecce0bf49a9b8b9fee5fc39729c2831acb9386d | 17,577 | [
-1
] |
17,578 | colour-cells.lisp | rheaplex_rheart/colour-cells/colour-cells.lisp | ;; draw-something.lisp - The main lifecycle code for draw-something.
;; Copyright (C) 2006 Rhea Myers [email protected]
;;
;; This file is part of colour-cells.
;;
;; colour-cells is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3 of the License, or
;; (at your option) any later version.
;;
;; colour-cells is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;; Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
(in-package "COLOUR-CELLS")
(defconstant save-directory "./drawings/")
(defmethod generate-filename ()
"Make a unique filename for the drawing, based on the current date & time."
(multiple-value-bind (seconds minutes hours date month year)
(decode-universal-time (get-universal-time))
(format nil
"~a~a-~2,,,'0@A~2,,,'0@A~2,,,'0@A-~2,,,'0@A~2,,,'0@A~2,,,'0@A~a"
save-directory
"drawing" year month date hours minutes seconds ".eps")))
(defmethod run ()
"The main method that generates the drawing and writes it to file."
(advisory-message "Starting colour-cells.~%")
(setf *random-state* (make-random-state t))
;;(format t "Random state: ~a.~%" (write-to-string *random-state*))
(let ((filename (generate-filename))
(image-width 7)
(image-height 10)
(cell-size 10)
(file-path t))
(ensure-directories-exist save-directory)
(with-open-file (ps filename :direction :output
:if-exists :supersede)
(setf file-path (namestring ps))
(write-eps-header (* image-width cell-size)
(* image-height cell-size)
:to ps)
(generate-colours ps image-width image-height cell-size)
(write-eps-footer :to ps))
#+sbcl (sb-ext:run-program "/usr/bin/gv" (list file-path))))
(defconstant object-symbol-choices
'(leaf vein blade branch flower tendril background))
(defmethod object-symbol ()
(choose-one-of object-symbol-choices))
(defmethod generate-colours (ps along up cell-size)
(let* ((scheme (make-colour-scheme object-symbol-choices 7 7 .3 .6))
(sv-spec-list (chooser-spec))
(applier (make-colour-scheme-applier scheme sv-spec-list))
(cell (make-instance 'rectangle :x 0 :y 0
:width cell-size :height cell-size)))
(format t "sv-spec: ~a~%" sv-spec-list)
(print-colour-scheme scheme)
(format t "Colouring forms.~%")
(dotimes (cell-y up)
(setf (x cell) 0)
(setf (y cell) (* cell-y cell-size))
(dotimes (cell-x along)
(setf (x cell) (* cell-x cell-size))
(write-colour (choose-colour-for applier
(object-symbol))
:to ps)
(write-rectfill cell :to ps))))) | 2,999 | Common Lisp | .lisp | 70 | 39.342857 | 77 | 0.696471 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | ba5ab803ff8820d533400a479d6e521b85808a4da27cfa956b357da567345402 | 17,578 | [
-1
] |
17,579 | ae.lisp | rheaplex_rheart/ae/ae.lisp | ;; ae.lisp - A toy aesthetics description and evaluation system
;; Copyright (C) 2004 Rhea Myers [email protected]
;;
;; This file is part of ae.
;;
;; ae is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3 of the License, or
;; (at your option) any later version.
;;
;; ae is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; TODO:
;; When comparing properties to criteria, allow conceptual slippage.
;; How should this affect weights?
;; Representational imagery, representational colour, referential colour,
;; associative colour.
;; An emotional slipnet.
;; Slipnet-style "conceptual levels" (levels of abstractness)?
;; Scanners for relative/relational properties/links (bigger, inside,
;; adjacent, row of)
;; - Should these have prerequisites, or a predicate function? For example,
;; making sure that a bigger
;; object isn't ultimately inside an object it's smaller than requires
;; walking the Image. Making sure an
;; object is bigger requires evaluating one of a range of sizes (or
;; nothing) against another.
;; Possibly allow either, simple prereq/blocks *or* a fun depending on the
;; input. Wrap to always a fun or check in the calling routine (no, wrap a
;; lambda???)
;; Consequential relationships. So if something's bigger, the other must
;; be smaller.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;(use-package 'ptester);; "./third-party/ptester.lisp")
;; Global
(defconstant the-random-state (make-random-state t))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Classes
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defclass link ()
((to :accessor link-to
:initarg :to
:initform ""
:documentation "The concept the link leads to.")
(by :accessor link-by
:initarg :by
:initform ""
:documentation "The concept the concepts are linked by.")
(strength :accessor link-strength
:initarg :strength
:initform 0.0
:documentation "The strength (weight) of the link."))
(:documentation "A conceptual link between two concepts, a weighted
relationship to another concept. Do we need bidirectional and to-self
relationships as well? "))
(defmethod finish-create ((the-link link))
"Once every Link in every Concept is declared, we can iterate through and replace names with objects. This method does that for a single Link."
(setf (link-to the-link) (aref (concept-concepts 'concept)
(link-to the-link)))
(setf (link-by the-link) (aref (concept-concepts 'concept)
(link-by the-link))))
(defmethod print-object ((the-link link) the-stream)
"Describe the link."
(print-object (link-by the-link) the-stream))
(defmethod equals ((left link) (right link))
(and (equal (link-to left) (link-to right))
(equal (link-by left) (link-by right))
(= (link-strength left) (link-strength right))))
;; (deftest
;; (let ((a (make-instance 'link))
;; (b (make-instance 'link)))
;; (with-tests (:name "ontology - link")
;; (test t (equals a b) :fail-info "Instance equality"))))
(defclass concept ()
((name :accessor concept-name
:initarg :name
:initform ""
:documentation "The name of the concept. Must be unique.")
(general :accessor concept-general
:initarg :general
:initform '()
:documentation
"The more general concepts that the concept can generalise to. Finished by finish-create.")
(specific :accessor concept-specific
:initarg :specific
:initform '()
:documentation
"The more specific concepts that a concept can be specified to.")
(related :accessor concept-related
:initarg :related
:initform '()
:documentation
"Concepts related to this concept by link instances."))
(:documentation "A Concept in the slipnet/semantic net. The class keeps track of all Concepts in a program and all relationships between them. A Concept has a name, a more general concept, and relationships to other concepts. It also keeps track of concepts that are more specific than it is.
TODO:
We should have weights for generalisations
And we should have pre-requisites for applying or NOT applying a Concept to an object with other concepts already applied
And atoms/sub-conceipts for the conceipt"))
(defconstant *concept-concepts* (make-hash-table :test 'equal)
"A lookup table of all the concepts, keyed on their names.")
(defmethod concept-concepts ()
*concept-concepts*)
(defmethod initialize-instance :after ((instance concept) &rest initargs)
"Store the concept under its name in the class hash of concepts."
initargs ; Silence the compiler warning
(setf (gethash (concept-name instance) (concept-concepts)) instance))
(defmethod print-object ((the-concept concept) the-stream)
"Describe the concept by name."
(format the-stream "~A" (concept-name the-concept)))
(defmethod equals ((left concept) (right concept))
"Compare ourself to another object by name. So names must be unique..."
(eq (concept-name left)
(concept-name right)))
(defmethod find-concept (name)
"Find a concept object by name"
(gethash name (concept-concepts)))
(defmethod link-concepts ()
"Call exactly once after all Concepts have been defined to finish setting up the Concept graph."
;; Substitute the more general concept for its name
(maphash #'(lambda (key value)
key ; Silence unused variable warning
;; Note that concept-general is a string now, we replace this
(setf (concept-general value)
(find-concept (concept-general value))))
(concept-concepts))
;; Add each object to its general concept's list of specific concepts
(maphash #'(lambda (key value)
key ; Silence unused variable warning
(setf (concept-specific (concept-general value))
(cons value (concept-specific (concept-general value)))))
(concept-concepts))
;; Finish the relationships
(maphash #'(lambda (key value)
key ; Silence unused variable warning
(dolist (r (concept-related value))
(finish-create r)))
(concept-concepts)))
(defmethod print-all-concepts ()
"Print a list of all the concept names."
(format t "Concepts:~%")
(maphash #'(lambda (key value)
value ; Silence unused variable warning
(format t " ~A" key))
(concept-concepts)))
(defmethod random-leaf-concept (general)
"Randomly choose a leaf Concept below the named general concept. A leaf Concept is a concept with no more specific concepts, i.e. an empty specific list. This version is incredibly inefficient and should be improved to findall then choose..."
(let ((the-concept (find-concept general)))
(loop while (not (eq (concept-specific the-concept) '()))
do (let ((specific (concept-specific the-concept)))
(setf the-concept
(nth (random (length specific)
the-random-state)
specific))))
the-concept))
;; (deftest
;; (let ((a (make-instance 'concept))
;; (b (make-instance 'concept)))
;; (with-tests (:name "ontology - concept")
;; (test t (equals a b) :fail-info "Instance equality"))))
(defclass weight ()
((value :accessor weight-value
:initarg :value
:initform 0.5
:documentation "The conceptual weight or value of the object.")
(min :accessor weight-min
:allocation :class
:initform 0.0
:documentation "The minimum value for weights.")
(max :accessor weight-max
:allocation :class
:initform 1.0
:documentation "The maximum value for weights."))
(:documentation "Abstract base class for a property of some object or system with a weight/value."))
(defmethod initialize-instance :after ((instance weight) &rest initargs)
"Randomly generate a weight within the constraints set by our min and max.
The weight will be >= min, < max ."
initargs ; Silence the coimpiler warning
(let ((weight-range (- (weight-max instance)
(weight-min instance))))
(setf (weight-value instance) (+ (weight-min instance)
(random weight-range
the-random-state)))))
(defmethod equals ((left weight) (right weight))
"Compare our weight to the other Weight's weight for equality."
(format t "~A ~A ~%" (weight-value left) (weight-value right))
(eql (weight-value left) (weight-value right)))
(defmethod print-object ((object weight) the-stream)
"Describe the weight value."
(format the-stream "weight: ~A" (weight-value object)))
;;;; Random element, can't test equality?
;;(deftest
;; (let ((a (make-instance 'weight))
;; (b (make-instance 'weight)))
;; (with-tests (:name "ontology - weight")
;; (test t (equals a b) :fail-info "Instance equality")
;; ))
;;)
(defclass formal-property (weight)
((concept :accessor formal-property-concept
:initarg :concept
:documentation "The concept the property embodies.")
(min :accessor weight-min
:allocation :class
:initform 0.001
:documentation "The minimum value for weights.")
(max :accessor weight-max
:allocation :class
:initform 1.0
:documentation "The maximum value for weights."))
(:documentation
"A formal property of a figure of an image. The weight of this property will be positive, to represent its strength of presence."))
(defmethod initialize-instance :after ((instance formal-property)
&rest initargs)
"Store the concept under its name in the class hash of concepts."
initargs ; Silence the compiler warning
(setf (formal-property-concept instance)
(random-leaf-concept "formal quality"))
(setf (gethash (concept-name (formal-property-concept instance))
(concept-concepts)) instance))
(defmethod equals ((left formal-property) (right formal-property))
(and (equals (formal-property-concept left)
(formal-property-concept right))
;; Call equals on weight
(call-next-method left right)))
(defmethod print-object ((instance formal-property) the-stream)
"Describe the concept by name."
(format the-stream
"~A ~A"
(concept-name (formal-property-concept instance))
(weight-value instance)))
(defclass aesthetic-criterion (formal-property)
((domain :accessor aesthetic-criterion-domain
:initarg :domain
:documentation "The concept the criterion applies to.")
(min :accessor min-value
:initform -0.999
:initarg :min
:documentation "The minimum possible value for criteria")
(max :accessor max-value
:initform 0.999
:initarg :max
:documentation "The maximum possible value for criteria"))
(:documentation "A criterion for aesthetic evaluation of an image. The weight of this criterion can be positive or negative, to reflect varying strengths of like and dislike. Inheriting from FormalProperty may be slighly broken, but it's convenient."))
(defmethod initialize-instance :after ((instance aesthetic-criterion)
&rest initargs)
"Randomly choose the criterions' domain."
initargs ; Silence the unused variable warning
(setf (aesthetic-criterion-domain instance)
(random-leaf-concept "extra-aesthetic domain")))
(defmethod print-object ((instance aesthetic-criterion) the-stream)
"Print the criterion."
(format the-stream "Criterion: ~a " (aesthetic-criterion-domain instance))
;; Describe the formal property elements
(call-next-method))
(defclass figure ()
((properties :accessor figure-properties
:initform '()
:initarg :properties
:documentation "The properties of the figure."))
(:documentation "A figure described by its formal properties."))
(defmethod initialize-instance :after ((instance figure)
&rest initargs
&key (property-count 10))
"Randomly choose the given number of formal properties to describe the figure."
initargs ; Silence the unused variable warning
(dotimes (i property-count)
(push (make-instance 'formal-property)
(figure-properties instance))))
(defmethod print-object ((instance figure) the-stream)
"Describe the formal qualities of the figures of the image."
(format the-stream "Figure: ~%")
(dolist (prop (figure-properties instance))
(format the-stream " ~a~%" prop)))
(defclass image ()
((figures :accessor image-figures
:initform '()
:initarg :criteria
:documentation "The figures of the image."))
(:documentation "An image consisting of a number of figures."))
(defmethod initialize-instance :after ((instance image)
&rest initargs
&key (figure-count 10)
(property-count-min 4)
(property-count-max 10))
"Generate a composition with the given number of figures, described by a random number (between minProperties/maxProperties) of formal properties each."
initargs ; Silence the unused variable warning
(dotimes (i figure-count)
(let ((property-count (+ property-count-min
(random (- property-count-max
property-count-min)
the-random-state))))
(push (make-instance 'figure :property-count property-count)
(image-figures instance)))))
(defmethod print-object ((img image) the-stream)
"Describe the formal qualities of each of the figures in the image."
(format the-stream "Image: ~%")
(dolist (fig (image-figures img))
(format the-stream " ~A" fig)))
(defclass aesthetic ()
((criteria :accessor aesthetic-criteria
:initform '()
:initarg :criteria
:documentation "The criteria that the aesthetic looks for in a work"))
(:documentation "An aesthetic described as a series of formal likes (positively weighted criteria) and dislikes (negatively weighted criteria) determined by extra-aesthetic concerns. This is essentially an aesthetic of taste, and cannot handle combination, absence, irony, etc. Give me time... :-)"))
(defmethod initialize-instance :after ((instance aesthetic)
&rest initargs
&key (criteria-count 10))
"Generate the given number of aesthetic criteria with random properties."
initargs ; Silence the unused variable warning
(dotimes (i criteria-count)
(push (make-instance 'aesthetic-criterion)
(aesthetic-criteria instance))))
(defmethod print-object ((ae aesthetic) the-stream)
"Describe an aesthetic's criteria."
(format the-stream "Aesthetic: ~%")
(dolist (crit (aesthetic-criteria ae))
(format the-stream " ~a~%" crit)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Concept Registration
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(make-instance 'concept :name "concept" :general "concept")
(make-instance 'concept :name "formal quality" :general "concept")
(make-instance 'concept :name "shape" :general "formal quality")
(make-instance 'concept :name "line" :general "shape")
(make-instance 'concept :name "circle" :general "shape")
(make-instance 'concept :name "triangle" :general "shape")
(make-instance 'concept :name "square" :general "shape")
(make-instance 'concept :name "oval" :general "shape")
(make-instance 'concept :name "rectangle" :general "shape")
(make-instance 'concept :name "diamond" :general "shape")
(make-instance 'concept :name "lozenge" :general "shape")
(make-instance 'concept :name "star" :general "shape")
(make-instance 'concept :name "spiral" :general "shape")
(make-instance 'concept :name "colour" :general "formal quality")
(make-instance 'concept :name "hue" :general "colour")
(make-instance 'concept :name "red" :general "hue")
(make-instance 'concept :name "orange" :general "hue")
(make-instance 'concept :name "yellow" :general "hue")
(make-instance 'concept :name "green" :general "hue")
(make-instance 'concept :name "blue" :general "hue")
(make-instance 'concept :name "purple" :general "hue")
(make-instance 'concept :name "chroma" :general "colour")
(make-instance 'concept :name "bright" :general "chroma")
(make-instance 'concept :name "dark" :general "colour")
(make-instance 'concept :name "pale" :general "colour")
(make-instance 'concept :name "rich" :general "colour")
(make-instance 'concept :name "medium chroma" :general "colour")
(make-instance 'concept :name "size" :general "formal quality")
(make-instance 'concept :name "very small" :general "size")
(make-instance 'concept :name "small" :general "size")
(make-instance 'concept :name "medium sized" :general "size")
(make-instance 'concept :name "large" :general "size")
(make-instance 'concept :name "very large" :general "size")
(make-instance 'concept :name "texture" :general "formal quality")
(make-instance 'concept :name "rough" :general "texture")
(make-instance 'concept :name "smooth" :general "texture")
(make-instance 'concept :name "scribbled" :general "texture")
(make-instance 'concept :name "scumbled" :general "texture")
(make-instance 'concept :name "grainy" :general "texture")
(make-instance 'concept :name "extra-aesthetic domain" :general "concept")
(make-instance 'concept :name "environmental" :general "extra-aesthetic domain")
(make-instance 'concept :name "historical" :general "extra-aesthetic domain")
(make-instance 'concept :name "political" :general "extra-aesthetic domain")
(make-instance 'concept :name "cultural" :general "extra-aesthetic domain")
(make-instance 'concept :name "spiritual" :general "extra-aesthetic domain")
(make-instance 'concept :name "emotional" :general "extra-aesthetic domain")
(make-instance 'concept :name "perceptual" :general "extra-aesthetic domain")
(make-instance 'concept :name "cognitive" :general "extra-aesthetic domain")
(link-concepts)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Mutation
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmethod mutate-property-weight (property weight-drift)
"Mutate the property's weight by +/-<=weightAmount"
;; random -weightAmount -> +weightAmount
(let ((drift (- (* 2.0 (random 1.0) weight-drift) weight-drift)))
(setf (weight-value property)
(+ (weight-value property)
drift))))
(defmethod mutate-property-weights (properties probability weight-amount)
"For each property, mutate its weight by +/-<=weightAmount if random< probability"
(dolist (prop properties)
(when (< (random 1.0
the-random-state)
probability)
(mutate-property-weight prop weight-amount))))
(defmethod mutate-property-concept (property generalise)
"Mutate the property's concept.
TODO: allowing generalisation if generalise is true."
generalise ;; Silence unused variable warning
(let ((links (concept-related (formal-property-concept property))))
(when (not (eq links
'()))
(setf (formal-property-concept property)
(nth (random (length links)
the-random-state)
links)))))
(defmethod mutate-property-concepts (properties probability generalise)
"For each property, mutate its concept if random< probability"
(dolist (prop properties)
(when (< (random 1.0) probability)
(mutate-property-concept prop generalise))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Generation, Evaluation
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmethod evaluate (ae img)
"Match the image's figure's properties to the aesthetic's properties and get the resulting score."
(let (;(criteria '())
(score 0.0))
(dolist (fig (image-figures img))
(dolist (prop (figure-properties fig))
(dolist (crit (aesthetic-criteria ae))
(when (equal (formal-property-concept crit)
(formal-property-concept prop))
(let ((weight (* (weight-value crit)
(weight-value prop))))
(setf score weight)
(format t "Evaluation: ~a - ~a -> ~a~%"
(concept-name (aesthetic-criterion-domain crit))
(concept-name (formal-property-concept crit))
weight)
;; If criteria doesn't contain the concept, insert,
;;otherwise add the weight
;;criteria.append()
(setf score (+ score weight)))))))
score))
(defmethod critique ()
"Describe the results of evaluating a work against an aesthetic."
(let* ((ae (make-instance 'aesthetic :criteria-count (+ 3 (random 3))))
(pic (make-instance 'image :figure-count (+ 3 (random 3)))))
(format t "~a" ae)
(format t "~a" pic)
(format t "Score: ~a ~%" (evaluate ae pic))))
(defmethod group-show ()
"Generate a series of works and evaluate them against an aesthetic."
(let* ((ae (make-instance 'aesthetic :criteria-count (+ 4 (random 10))))
(highest-score -10000.0)
;; What about ties?
(highest-index 0))
(format t "~a~%" ae)
(dotimes (i (+ 2 (random 10)))
(format t "Image ~a ~%" (+ i 1))
(let ((pic (make-instance 'image
:figure-count (+ 1 (random 14))
:property-count-min 1
:property-count-max 9)))
(format t "~a" pic)
(let ((score (evaluate ae pic)))
(format t "Score: ~a~%~%" score)
(when (> score highest-score)
(setf highest-score score)
(setf highest-index i)))))
(format t "Highest score was Image ~a~%" (+ highest-index 1))))
(defmethod critical-convention ()
"Generate a series of aesthetics and evaluate them against a work (multiple reviews of a work)."
(let ((pic (make-instance 'image
:figure-count (+ 1 (random 15))
:property-count-min 3
:property-count-max 12))
(highest-score -10000.0)
;; What about ties?
(highest-index 0))
(format t "~a~%" pic)
(dotimes (i (+ 2 (random 10)))
(format t "Aesthetic ~a~%" (+ i 1))
(let ((ae (make-instance 'aesthetic
:criteria-count (+ 4 (random 10)))))
(format t "~a" ae)
(let ((score (evaluate ae pic)))
(format t "Score: ~a~%~%" score)
(when (> score highest-score)
(setf highest-score score)
(setf highest-index i)))))
(format t "Highest score was Aesthetic ~a~%" (+ highest-index 1))))
;; Generate a series of mutated works and evaluate them against an aesthetic (retrospective)
;; Etc.
;; Generate an aesthetic for an arists, generate a work or series of works for the aesthetic, evaluate them against
;; an aesthetic for a critic (aesthetics for critics), describe the results, allow the artists to point out what the
;; critic missed
| 22,975 | Common Lisp | .lisp | 485 | 43.183505 | 302 | 0.679317 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 3d3d86ccead8943fc8fcfbbf6c274085663e3c861f35ae953b2b791c58f08f03 | 17,579 | [
-1
] |
17,580 | run.lisp | rheaplex_rheart/ae/run.lisp | ;; run.lisp - A toy aesthetics description and evaluation system
;; Copyright (C) 2004 Rhea Myers [email protected]
;;
;; This file is part of ae.
;;
;; ae is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3 of the License, or
;; (at your option) any later version.
;;
;; ae is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;(load "../library/ptester.lisp")
(load "./ae.lisp")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Go
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;(run-tests)
;;(print-all-concepts)
(critique)
;;(group-show)
;;(critical-convention)
| 1,095 | Common Lisp | .lisp | 27 | 39.222222 | 79 | 0.629002 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | df7bb278ed5cee207432c2adae9c4989ba4222c072e073955ec87c7bd871a122 | 17,580 | [
-1
] |
17,581 | draw-something.asd | rheaplex_rheart/draw-something/draw-something.asd | ;; draw-something.asd - The main package for draw-something
;; Copyright (C) 2006 Rhea Myers [email protected]
;;
;; This file is part of draw-something.
;;
;; draw-something is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3 of the License, or
;; (at your option) any later version.
;;
;; draw-something is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
(require :asdf)
(in-package #:asdf)
(asdf:defsystem #:draw-something
:serial t
:components
((:file "package")
(:file "utilities")
(:file "geometry")
(:file "point")
(:file "line")
(:file "circle")
(:file "arc")
(:file "rectangle")
(:file "polyline")
;;(:file "cell-matrix")
(:file "colour")
(:file "colouring-new")
(:file "turtle")
(:file "form")
(:file "figure")
;;(:file "codelet")
(:file "drawing")
(:file "postscript")
(:file "draw-something")))
| 1,326 | Common Lisp | .asd | 41 | 29.731707 | 73 | 0.691108 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 9e1297477d0813a1c51b6b9835a31cbd0bd7f0a2a5427cc9d08e07e2745e7898 | 17,581 | [
-1
] |
17,582 | colour-cells.asd | rheaplex_rheart/colour-cells/colour-cells.asd | ;; draw-something.asd - The main package for draw-something
;; Copyright (C) 2006 Rhea Myers [email protected]
;;
;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 2 of the License, or
;; (at your option) any later version.
;;
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program; if not, write to the Free Software
;; Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
(require :asdf)
(in-package #:asdf)
(asdf:defsystem #:colour-cells
:serial t
:components
((:file "package")
(:file "utilities")
(:file "point")
(:file "rectangle")
(:file "colour")
(:file "colouring-new")
(:file "postscript")
(:file "colour-cells")))
| 1,122 | Common Lisp | .asd | 29 | 36.655172 | 77 | 0.722936 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 59e0afc5df5577d3eb1dd0c4d75bb7fc2fb12cb0006173f00778d298497b8aa0 | 17,582 | [
-1
] |
17,625 | Info.plist | rheaplex_rheart/draw-something-carbon/draw-something.app/Contents/Info.plist | <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>English</string>
<key>CFBundleExecutable</key>
<string>draw-something</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>0.1</string>
<key>NSMainNibFile</key>
<string>MainMenu</string>
</dict>
</plist>
| 600 | Common Lisp | .l | 20 | 28.3 | 111 | 0.737931 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 20ebaff0fc8fa3531ae11228b63f6e6a8473fc97368e84f154556895c13b9771 | 17,625 | [
-1
] |
17,626 | Makefile | rheaplex_rheart/draw-something-flash/Makefile | all: draw_something.swf
draw_something.swf: point.as polyline.as turtle.as drawing.as draw_something.as
mtasc -swf draw_something.swf -main -header 600:600:30 \
point.as \
polyline.as \
turtle.as \
drawing.as \
draw_something.as
| 241 | Common Lisp | .l | 8 | 27.625 | 79 | 0.75431 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 12bdc58653b6ee48b35f99fd0ed1108b3df44dfb036487add5f87e553b348436 | 17,626 | [
-1
] |
17,627 | polyline.as | rheaplex_rheart/draw-something-flash/polyline.as | /* polyline.as - A polyline.
Copyright (C) 2004-5 Rhea Myers [email protected]
This file is part of draw-something flash.
draw-something flash is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
draw-something flash is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class polyline
{
var points : Array;
function polyline ()
{
this.points = new Array ();
}
function add_point (p)
{
points.push (p);
}
function random_points_in_bounds (x : Number, y : Number,
width : Number, height : Number,
count : Number)
{
for (var i : Number = 0; i < count; i++)
{
var x_pos = Math.random () * width;
var y_pos = Math.random () * height;
var p : point = new point (x + x_pos, y + y_pos);
add_point (p);
}
}
// http://www.gamasutra.com/features/20000210/lander_l3.htm
function nearest_point_on_line (a : point, b : point, c : point)
{
// SEE IF a IS THE NEAREST POINT - ANGLE IS OBTUSE
var dot_ta = (c.x - a.x) * (b.x - a.x) +
(c.y - a.y) * (b.y - a.y);
if (dot_ta <= 0) // IT IS OFF THE AVERTEX
{
return new point (a.x , a.y);
}
var dot_tb : Number = (c.x - b.x) * (a.x - b.x) +
(c.y - b.y) * (a.y - b.y);
// SEE IF b IS THE NEAREST POINT - ANGLE IS OBTUSE
if (dot_tb <= 0)
{
return new point (b.x, b.y);
}
// FIND THE REAL NEAREST POINT ON THE LINE SEGMENT
// BASED ON RATIO
var nearest_x : Number = a.x + ((b.x - a.x) * dot_ta) /
(dot_ta + dot_tb);
var nearest_y : Number = a.y + ((b.y - a.y) * dot_ta) /
(dot_ta + dot_tb);
return new point (nearest_x, nearest_y);
}
function distance_from_line_to_point (a : point, b : point, c : point)
{
var nearest : point = nearest_point_on_line (a, b, c);
return nearest.distance_to_point (c);
}
function distance_to_point (p : point)
{
var distance_to_poly = Number.MAX_VALUE;
for (var i : Number = 1; i < points.length; i++)
{
var a: point = points[i - 1];
var b : point = points[i];
var d : Number =
distance_from_line_to_point (a, b, p);
if (d < distance_to_poly)
{
distance_to_poly = d;
}
}
return distance_to_poly;
}
function top_leftmost_point ()
{
var top_leftmost = points[0];
for (var i : Number = 1; i < points.length; i++)
{
if ((points[i].y <= top_leftmost.y) ||
((points[i].y == top_leftmost.y) &&
((points[i].x < top_leftmost.x))))
{
top_leftmost = points[i];
}
}
return new point (top_leftmost.x, top_leftmost.y);
}
} | 3,121 | Common Lisp | .l | 98 | 27.05102 | 80 | 0.606212 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 694d6ec9c302db7ce6e7de7d7482a267a12c3ab86008e9ea1616473218405d61 | 17,627 | [
-1
] |
17,628 | draw-something.html | rheaplex_rheart/draw-something-flash/draw-something.html | <html>
<head>
<title>draw-something</title>
</head>
<body bgcolor='#FFFFFF' onLoad='window.document.drawsomething.focus();'>
<div align="center" valign="center">
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0" width="770" height="580" id="myothermovie">
<param name="movie" value="draw_something.swf">
<param name="SeamlessTabbing" value="false">
<param name="swLiveConnect" value="true">
<param name="quality" value="high">
<embed src="draw_something.swf" width="770" height="580"
NAME='drawsomething'>
</embed>
</object>
</div>
</body>
</html>
| 710 | Common Lisp | .l | 18 | 35.388889 | 204 | 0.690751 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | ac9edf32453974f790959f13e82d903d65755ed4480ebacd68e0fbe641c993a2 | 17,628 | [
-1
] |
17,629 | turtle.as | rheaplex_rheart/draw-something-flash/turtle.as | /* turtle.as - A classic computer graphics 'turtle'.
Copyright (C) 2004-5 Rhea Myers [email protected]
This file is part of draw-something flash.
draw-something flash is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
draw-something flash is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class turtle
{
static var degrees_to_radians = (Math.PI * 2.0) / 360.0;
var forward_step : Number;
var turn_step : Number;
var position : point;
var direction : Number;
function turtle (position : point, forward_step : Number,
turn_step : Number)
{
this.direction = 90.0;
this.position = position;
this.forward_step = forward_step;
this.turn_step = turn_step;
}
function left ()
{
direction -= turn_step;
}
function right ()
{
direction += turn_step;
}
function forward ()
{
position = next_point_would_be ();
}
function next_point_would_be ()
{
var x : Number = position.x +
(forward_step * Math.sin (direction * degrees_to_radians));
var y : Number = position.y +
(forward_step * Math.cos (direction * degrees_to_radians));
return new point (x, y);
}
} | 1,714 | Common Lisp | .l | 50 | 29.64 | 80 | 0.691087 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 83f6eb034930322d6e9e88dae8b95ccea82318071e586a0b75d330b33c272e38 | 17,629 | [
-1
] |
17,630 | index.html | rheaplex_rheart/draw-something-flash/index.html | <html>
<head>
<title>draw-something</title>
<style>
h1 {font-family: helvetica, arial, sans-serif; color: #AAAABB;}
p {font-family: helvetica, arial, sans-serif; font-size: 11pt; color: #111122;}
</style>
</head>
<body bgcolor='#FFFFFF' onLoad='window.document.drawsomething.focus();'>
<h1>draw-something</h1>
<table border='0' width='780px'>
<tr>
<td width='320px'>
<p>draw-something is a program that generates original drawings. It does
so by generating a simple random polyline scribble then drawing
around that using a simple maze-running algorithm. This procedure was
chosen as the simplest behaviour that models the creative process of
drawing as either sketching or drafting. The program is written in
Lisp, although it has been translated to ActionScript for the Flash
version on this page.</p>
<p>These choices were inspired by Harold Cohen's drawing program AARON.
Its drawing behaviour and the choice of Lisp as implementation
language were inspired by some versions of AARON. Although he has
written essays describing AARON's algorithms Harold Cohen has not
made AARON's code public. My desire to see AARON's code, or the code
of an AARON-like system, motivated me to write draw-something and to
make it Free Software.</p>
<p>draw-something makes images in a different style from AARON and over
time it will be extended to have more, and different, features. A
current version does simple colour, and I am working on more complex
guide shapes. I exhibited a screen-based version of draw-something at
my show in Gallery o3one in Belgrade (alongside some prints from the
colour version) and at dorkbot London in 2005.</p>
<p>Press the 'a' key to toggle visibility of the skeleton that is being drawn around.</p>
<p><a href='./draw-something.html'
onclick='window.open("./draw-something.html","draw-something","width=600,height=600,location=0,status=0,scrollbars=0,resizable=0"); return false'>Launch draw-something in a new window.</a><br /> <br />
<a href='http://rheart.sourceforge.net'>Project homepage.</a><br /> <br />
<a href='./draw-something-flash.zip'>Download the source</a></p>
</td>
<td width="20px"> </td>
<td valign='top' align='right' width="340px">
<div style="border: 1px solid gray;">
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0" width="340" height="340" id="myothermovie">
<param name="movie" value="draw_something.swf">
<param name="SeamlessTabbing" value="false">
<param name="swLiveConnect" value="true">
<param name="quality" value="high">
<embed src="draw_something.swf" width="340" height="340"
NAME='drawsomething'>
</embed>
</object>
</div>
</td>
</tr>
</table>
</body>
</html>
| 2,819 | Common Lisp | .l | 57 | 47.122807 | 212 | 0.747285 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 3214608105dc63c6a752492d9296d5fbf1628f54122c353c4b33779c60c213ba | 17,630 | [
-1
] |
17,644 | ae.html | rheaplex_rheart/documentation/rheart/ae.html | <html lang="en">
<head>
<title>rheart documentation</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="rheart documentation">
<meta name="generator" content="makeinfo 4.6">
<!--
This is the documentation for rheart.
<p>Copyright © 2004 Rhea Myers.
<p>Copying and distribution of this file, with or without modification,
are permitted in any medium without royalty provided the copyright
notice and this notice are preserved-->
<meta http-equiv="Content-Style-Type" content="text/css">
<style type="text/css"><!--
pre.display { font-family:inherit }
pre.format { font-family:inherit }
pre.smalldisplay { font-family:inherit; font-size:smaller }
pre.smallformat { font-family:inherit; font-size:smaller }
pre.smallexample { font-size:smaller }
pre.smalllisp { font-size:smaller }
--></style>
</head>
<body>
<div class="node">
<p>
Node: <a name="ae">ae</a>,
Next: <a rel="next" accesskey="n" href="Draw-Something.html#Draw%20Something">Draw Something</a>,
Previous: <a rel="previous" accesskey="p" href="The-Cybernetic-Artwork-Nobody-Wrote.html#The%20Cybernetic%20Artwork%20Nobody%20Wrote">The Cybernetic Artwork Nobody Wrote</a>,
Up: <a rel="up" accesskey="u" href="index.html#Top">Top</a>
<hr><br>
</div>
<h2 class="chapter">ae</h2>
<p>ae is a toy aesthetic evaluator. It generates simple descriptions of aesthetics, basically just a list of valenced criteria. It also generates descriptions of artworks consisting of a number of figures, each described by a list of valenced properties. It then evaluates artwork against aesthetic and gives the artwork a numeric score, a measure of its value under that aesthetic.
<h3 class="section">Precedents</h3>
<p>I wrote ae before I'd read Gips and Stiny's "Algorithmic Aesthetics" (University of California Press, 1979 - <a href="http://www.algorithmicaesthetics.org/">http://www.algorithmicaesthetics.org/</a>), but I was certainly inspired by the idea of the possibility of an algorithmic aesthetics.
<p>The structure of ae's ontology, with specific concepts generalisable to more broader concepts, is inspired by Douglas Hofstadter and Melanie Mitchell's work on CopyCat, described in the book "Fluid Concepts and Creative Analogies".
<h3 class="section">Running ae</h3>
<p>To run ae, change to the directory rheart/ae and run the file run.lisp there.
<pre class="example"> $ cd ae
$ openmcl --load run.lisp
</pre>
</body></html>
| 2,498 | Common Lisp | .l | 42 | 57.404762 | 382 | 0.757464 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 4be491aa9b84eebf37ea4a2c00a4e88e8ec26e35007f23e4635460b248adaed4 | 17,644 | [
-1
] |
17,645 | The-Cybernetic-Artwork-Nobody-Wrote.html | rheaplex_rheart/documentation/rheart/The-Cybernetic-Artwork-Nobody-Wrote.html | <html lang="en">
<head>
<title>rheart documentation</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="rheart documentation">
<meta name="generator" content="makeinfo 4.6">
<!--
This is the documentation for rheart.
<p>Copyright © 2004 Rhea Myers.
<p>Copying and distribution of this file, with or without modification,
are permitted in any medium without royalty provided the copyright
notice and this notice are preserved-->
<meta http-equiv="Content-Style-Type" content="text/css">
<style type="text/css"><!--
pre.display { font-family:inherit }
pre.format { font-family:inherit }
pre.smalldisplay { font-family:inherit; font-size:smaller }
pre.smallformat { font-family:inherit; font-size:smaller }
pre.smallexample { font-size:smaller }
pre.smalllisp { font-size:smaller }
--></style>
</head>
<body>
<div class="node">
<p>
Node: <a name="The%20Cybernetic%20Artwork%20Nobody%20Wrote">The Cybernetic Artwork Nobody Wrote</a>,
Next: <a rel="next" accesskey="n" href="ae.html#ae">ae</a>,
Previous: <a rel="previous" accesskey="p" href="Introduction.html#Introduction">Introduction</a>,
Up: <a rel="up" accesskey="u" href="index.html#Top">Top</a>
<hr><br>
</div>
<h2 class="chapter">The Cybernetic Artwork Nobody Wrote</h2>
<p>"Cybernetic" generates random descriptions of possible abstract images. It is based on the poetry generation programs so beloved of basic computing texts, but generates descriptions of images rather than limericks. I think someone will probably have written such a program sometime in the 1960s, so the name refers to the conceptual artwork "The Cybernetic Artwork that Nobody Broke" by Harold Hurrell (1969).
<h3 class="section">Running Cybernetic...</h3>
<p>To run "Cybernetic", change to the directory rheart/cybernetic/ and run the file run.lisp there.
<pre class="example"> $ cd cybernetic
$ openmcl --load run.lisp
</pre>
<h3 class="section">Sample Session</h3>
<pre class="example"> $ cd cybernetic
$ openmcl --load run.lisp
A large smooth pale pink outlined organic shape on a halftoned rich
cotton-coloured ground.
A tiny bright sky blue abstracted bird on a pale sea green ground.
A pair of massive halftoned pale non-repro blue outlined octagons on a
crosshatched rich platinum ground.
Many massive pale suede-coloured birds on a scumbled white ground.
A small brown horse on a pale cotton-coloured ground.
Some sunset red spiky shapes on a halftoned denim blue ground.
A large green spiky shape on a black ground.
A pair of small bright black pentagons on a pale pink ground.
A pair of rich purple outlined ships on a scumbled cyan ground.
Many massive crosshatched bright shocking pink irregular shapes on a smooth
rich leaf green ground.
</pre>
</body></html>
| 2,899 | Common Lisp | .l | 56 | 48.696429 | 412 | 0.74797 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | da8ccfde5decded500e13d20982df4144f290971bee2d06683e058723bbb42c6 | 17,645 | [
-1
] |
17,646 | Draw-Something.html | rheaplex_rheart/documentation/rheart/Draw-Something.html | <html lang="en">
<head>
<title>rheart documentation</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="rheart documentation">
<meta name="generator" content="makeinfo 4.6">
<!--
This is the documentation for rheart.
<p>Copyright © 2004 Rhea Myers.
<p>Copying and distribution of this file, with or without modification,
are permitted in any medium without royalty provided the copyright
notice and this notice are preserved-->
<meta http-equiv="Content-Style-Type" content="text/css">
<style type="text/css"><!--
pre.display { font-family:inherit }
pre.format { font-family:inherit }
pre.smalldisplay { font-family:inherit; font-size:smaller }
pre.smallformat { font-family:inherit; font-size:smaller }
pre.smallexample { font-size:smaller }
pre.smalllisp { font-size:smaller }
--></style>
</head>
<body>
<div class="node">
<p>
Node: <a name="Draw%20Something">Draw Something</a>,
Next: <a rel="next" accesskey="n" href="Concept-Index.html#Concept%20Index">Concept Index</a>,
Previous: <a rel="previous" accesskey="p" href="ae.html#ae">ae</a>,
Up: <a rel="up" accesskey="u" href="index.html#Top">Top</a>
<hr><br>
</div>
<h2 class="chapter">Draw Something</h2>
<p>Draw Something generates simple line drawings. It does this by generating a set or random points, finding their convex hull (smallest enclosing shape), and drawing around that. These stages are a very simple analogue to observational or constructive drawing.
<h3 class="section">Precedents</h3>
<p>I was inspired to start on draw-something (and rheart as a whole) by Harold Cohen's program AARON. Ed Burton's ROSE and Kazushi Mukaiyuma's Shizuka, both also inspired by AARON, were influences as well.
<h3 class="section">Running Draw Something</h3>
<p>To run ae, change to the directory rheart/draw-something and run the file run.lisp there.<br>
<pre class="example"> $ cd draw-something
$ openmcl --load run.lisp
</pre>
<p>Draw Something will print messages describing its progress then write the files debug.ps and image.ps in its directory. image.ps is the finished drawing.
<p>You can open both files with a PostScript viewer such as GhostView, MacOSX Preview can also open PostScript files.
<h3 class="section">A Sample Session</h3>
<pre class="example"> cd draw-something
openmcl --load run.lisp
Drawing something.
Generating skeleton.
Finished generating skeleton.
Generating convex hull.
Finished generating convex hull.
Drawing around convex hull.
</pre>
<h3 class="section">Sample Image Output</h3>
<img src="draw-something.jpg" alt="draw-something.jpg">
</body></html>
| 2,718 | Common Lisp | .l | 55 | 46.727273 | 261 | 0.745372 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 2fa92e8848002c89f79dd9b5ba15fd268ead174af3b0cab3d9a81ce343938bec | 17,646 | [
-1
] |
17,647 | Introduction.html | rheaplex_rheart/documentation/rheart/Introduction.html | <html lang="en">
<head>
<title>rheart documentation</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="rheart documentation">
<meta name="generator" content="makeinfo 4.6">
<!--
This is the documentation for rheart.
<p>Copyright © 2004 Rhea Myers.
<p>Copying and distribution of this file, with or without modification,
are permitted in any medium without royalty provided the copyright
notice and this notice are preserved-->
<meta http-equiv="Content-Style-Type" content="text/css">
<style type="text/css"><!--
pre.display { font-family:inherit }
pre.format { font-family:inherit }
pre.smalldisplay { font-family:inherit; font-size:smaller }
pre.smallformat { font-family:inherit; font-size:smaller }
pre.smallexample { font-size:smaller }
pre.smalllisp { font-size:smaller }
--></style>
</head>
<body>
<div class="node">
<p>
Node: <a name="Introduction">Introduction</a>,
Next: <a rel="next" accesskey="n" href="The-Cybernetic-Artwork-Nobody-Wrote.html#The%20Cybernetic%20Artwork%20Nobody%20Wrote">The Cybernetic Artwork Nobody Wrote</a>,
Previous: <a rel="previous" accesskey="p" href="index.html#Top">Top</a>,
Up: <a rel="up" accesskey="u" href="index.html#Top">Top</a>
<hr><br>
</div>
<h2 class="chapter">Introduction</h2>
<p>rheart is a series of programs written in the course of developing a system to generate artistic images.
<h3 class="section">Implementation Notes</h3>
<p>The programs are written in the programming language Lisp, and should run on any ANSI Common Lisp system. OpenMCL and SBCL are particularly recommended.
<h3 class="section">Running The Programs</h3>
<p>To run one of the programs, change to its directory and run the file run.lisp in that directory.<br>
For example:
<pre class="example"> $ cd draw-something
$ openmcl --load run.lisp
</pre>
<p>In example code (such as above), the dollar sign ($) indicates the command-line prompt. It should not be typed.
</body></html>
| 2,027 | Common Lisp | .l | 43 | 45.162791 | 171 | 0.747086 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | fd929c432133e74aea1f14bcdc653d8d46598c4c9e7b48880d315496009fe2bd | 17,647 | [
-1
] |
17,648 | Concept-Index.html | rheaplex_rheart/documentation/rheart/Concept-Index.html | <html lang="en">
<head>
<title>rheart documentation</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="rheart documentation">
<meta name="generator" content="makeinfo 4.6">
<!--
This is the documentation for rheart.
<p>Copyright © 2004 Rhea Myers.
<p>Copying and distribution of this file, with or without modification,
are permitted in any medium without royalty provided the copyright
notice and this notice are preserved-->
<meta http-equiv="Content-Style-Type" content="text/css">
<style type="text/css"><!--
pre.display { font-family:inherit }
pre.format { font-family:inherit }
pre.smalldisplay { font-family:inherit; font-size:smaller }
pre.smallformat { font-family:inherit; font-size:smaller }
pre.smallexample { font-size:smaller }
pre.smalllisp { font-size:smaller }
--></style>
</head>
<body>
<div class="node">
<p>
Node: <a name="Concept%20Index">Concept Index</a>,
Previous: <a rel="previous" accesskey="p" href="Draw-Something.html#Draw%20Something">Draw Something</a>,
Up: <a rel="up" accesskey="u" href="index.html#Top">Top</a>
<hr><br>
</div>
<h2 class="unnumbered">Concept Index</h2>
<ul class="index-cp" compact>
<li>aesthetic: <a href="ae.html#ae">ae</a>
<li>aesthetic property: <a href="ae.html#ae">ae</a>
<li>aesthetic value: <a href="ae.html#ae">ae</a>
<li>aesthetics: <a href="ae.html#ae">ae</a>
<li>convex hull: <a href="Draw-Something.html#Draw%20Something">Draw Something</a>
<li>criteria: <a href="ae.html#ae">ae</a>
<li>drawing: <a href="Draw-Something.html#Draw%20Something">Draw Something</a>
<li>GhostScript: <a href="Draw-Something.html#Draw%20Something">Draw Something</a>
<li>Harold Hurrell: <a href="The-Cybernetic-Artwork-Nobody-Wrote.html#The%20Cybernetic%20Artwork%20Nobody%20Wrote">The Cybernetic Artwork Nobody Wrote</a>
<li>implementation: <a href="Introduction.html#Introduction">Introduction</a>
<li>Lisp: <a href="Introduction.html#Introduction">Introduction</a>
<li>OpenMCL: <a href="Introduction.html#Introduction">Introduction</a>
<li>poetry generators: <a href="The-Cybernetic-Artwork-Nobody-Wrote.html#The%20Cybernetic%20Artwork%20Nobody%20Wrote">The Cybernetic Artwork Nobody Wrote</a>
<li>PostScript: <a href="Draw-Something.html#Draw%20Something">Draw Something</a>
<li>rheart: <a href="Introduction.html#Introduction">Introduction</a>
<li>run.lisp: <a href="Introduction.html#Introduction">Introduction</a>, <a href="ae.html#ae">ae</a>, <a href="The-Cybernetic-Artwork-Nobody-Wrote.html#The%20Cybernetic%20Artwork%20Nobody%20Wrote">The Cybernetic Artwork Nobody Wrote</a>, <a href="Draw-Something.html#Draw%20Something">Draw Something</a>
<li>running ae: <a href="ae.html#ae">ae</a>
<li>running Cybernetic...: <a href="The-Cybernetic-Artwork-Nobody-Wrote.html#The%20Cybernetic%20Artwork%20Nobody%20Wrote">The Cybernetic Artwork Nobody Wrote</a>
<li>running draw something: <a href="Draw-Something.html#Draw%20Something">Draw Something</a>
<li>running the programs: <a href="Introduction.html#Introduction">Introduction</a>
<li>SBCL: <a href="Introduction.html#Introduction">Introduction</a>
<li>The Cybernetic Artwork that Nobody Broke: <a href="The-Cybernetic-Artwork-Nobody-Wrote.html#The%20Cybernetic%20Artwork%20Nobody%20Wrote">The Cybernetic Artwork Nobody Wrote</a>
</ul>
</body></html>
| 3,345 | Common Lisp | .l | 56 | 58.232143 | 303 | 0.759598 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 0ed3f12c26fd105ba90c8e4e4207dbe65c8fcd10b0d633179f96a41fb798daf8 | 17,648 | [
-1
] |
17,649 | index.html | rheaplex_rheart/documentation/rheart/index.html | <html lang="en">
<head>
<title>rheart documentation</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="rheart documentation">
<meta name="generator" content="makeinfo 4.6">
<!--
This is the documentation for rheart.
<p>Copyright © 2004 Rhea Myers.
<p>Copying and distribution of this file, with or without modification,
are permitted in any medium without royalty provided the copyright
notice and this notice are preserved-->
<meta http-equiv="Content-Style-Type" content="text/css">
<style type="text/css"><!--
pre.display { font-family:inherit }
pre.format { font-family:inherit }
pre.smalldisplay { font-family:inherit; font-size:smaller }
pre.smallformat { font-family:inherit; font-size:smaller }
pre.smallexample { font-size:smaller }
pre.smalllisp { font-size:smaller }
--></style>
</head>
<body>
<h1 class="settitle">rheart documentation</h1>
<div class="contents">
<h2>Table of Contents</h2>
<ul>
<li><a name="toc_Top" href="index.html#Top">rheart</a>
<li><a name="toc_Introduction" href="Introduction.html#Introduction">Introduction</a>
<ul>
<li><a href="Introduction.html#Introduction">Implementation Notes</a>
<li><a href="Introduction.html#Introduction">Running The Programs</a>
</li></ul>
<li><a name="toc_The%20Cybernetic%20Artwork%20Nobody%20Wrote" href="The-Cybernetic-Artwork-Nobody-Wrote.html#The%20Cybernetic%20Artwork%20Nobody%20Wrote">The Cybernetic Artwork Nobody Wrote</a>
<ul>
<li><a href="The-Cybernetic-Artwork-Nobody-Wrote.html#The%20Cybernetic%20Artwork%20Nobody%20Wrote">Running Cybernetic...</a>
<li><a href="The-Cybernetic-Artwork-Nobody-Wrote.html#The%20Cybernetic%20Artwork%20Nobody%20Wrote">Sample Session</a>
</li></ul>
<li><a name="toc_ae" href="ae.html#ae">ae</a>
<ul>
<li><a href="ae.html#ae">Precedents</a>
<li><a href="ae.html#ae">Running ae</a>
</li></ul>
<li><a name="toc_Draw%20Something" href="Draw-Something.html#Draw%20Something">Draw Something</a>
<ul>
<li><a href="Draw-Something.html#Draw%20Something">Precedents</a>
<li><a href="Draw-Something.html#Draw%20Something">Running Draw Something</a>
<li><a href="Draw-Something.html#Draw%20Something">A Sample Session</a>
<li><a href="Draw-Something.html#Draw%20Something">Sample Image Output</a>
</li></ul>
<li><a name="toc_Concept%20Index" href="Concept-Index.html#Concept%20Index">Concept Index</a>
</li></ul>
</div>
<div class="node">
<p>
Node: <a name="Top">Top</a>,
Next: <a rel="next" accesskey="n" href="Introduction.html#Introduction">Introduction</a>,
Up: <a rel="up" accesskey="u" href="../index.html#dir">(dir)</a>
<hr><br>
</div>
<h2 class="unnumbered">rheart</h2>
This is the documentation for rheart.
<p>Copyright © 2004 Rhea Myers.
<p>Copying and distribution of this file, with or without modification,
are permitted in any medium without royalty provided the copyright
notice and this notice are preserved
<ul class="menu">
<li><a accesskey="1" href="Introduction.html#Introduction">Introduction</a>: An introduction to rheart.
<li><a accesskey="2" href="The-Cybernetic-Artwork-Nobody-Wrote.html#The%20Cybernetic%20Artwork%20Nobody%20Wrote">The Cybernetic Artwork Nobody Wrote</a>: A program to generate descriptions of
abstract art images.
<li><a accesskey="3" href="ae.html#ae">ae</a>: A toy aesthetic evaluator.
<li><a accesskey="4" href="Draw-Something.html#Draw%20Something">Draw Something</a>: A simple drawing generator.
<li><a accesskey="5" href="Concept-Index.html#Concept%20Index">Concept Index</a>: Complete index.
</ul>
</body></html>
| 3,661 | Common Lisp | .l | 75 | 46.666667 | 193 | 0.732308 | rheaplex/rheart | 3 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 16235de6eae6de18d9c11abdf6fcc07a7760cfc7e07e376633037714ec92c1fc | 17,649 | [
-1
] |
17,664 | main.lisp | jadahl_hactar/src/main.lisp | (in-package :hactar)
(defvar *hactar-instance* nil)
(defvar *callbacks* nil)
(setf *callbacks*
'(google-command
katt))
(defun run ()
(when (not *hactar-instance*)
(setf *hactar-instance* (make-instance 'hactar))
(connect-all *hactar-instance*
(list
(make-instance
'jabber-connection
:username "hactar"
:password "paranoid"
:server "jabber.se"
:router-host "jabber.se"
:router-port 5222)))
(format t "Adding callbacks...~%")
(dolist (callback *callbacks*)
(add-callback *hactar-instance* callback (make-instance callback)))
(format t "Joining channels...~%")
(join-channel
(car (hactar-connections *hactar-instance*))
(make-jabber-channel "talks" "conference.jabber.se" "Hactar(beta)")))
(event:event-dispatch))
| 944 | Common Lisp | .lisp | 26 | 26.346154 | 75 | 0.568908 | jadahl/hactar | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 55c53950487cb2a1f1c1ee802203913fc2e317526727c701d6f8ad64a4afd176 | 17,664 | [
-1
] |
17,665 | hactar.lisp | jadahl_hactar/src/hactar.lisp | (in-package :hactar)
(defclass hactar ()
((connections :accessor hactar-connections
:initform nil
:documentation "Active connections.")
(callbacks :accessor hactar-callbacks
:initform (make-hash-table :test #'equal))))
;; FIXME remove default-connections, leave that to initating procedure
;;(default-connections :accessor hactar-default-connections
;; :initarg :default-connections
;; :initform nil)))
(defmethod new-connection ((h hactar) (c connection))
(setf (connection-event-handler c) 'hactar-handle-event)
(setf (connection-event-master c) h)
(pushnew c (hactar-connections h))
(connect c)
(format t "Adding:~a~%" 'hactar::read-and-act)
(event:add-event-callback (connection-stream c) (event:make-flags :ev-persist t) #'hactar::read-and-act c))
(defmethod connect-all ((h hactar) connections)
(dolist (c connections)
(new-connection h c)))
(defmethod disconnect-all ((h hactar))
(dolist (c (hactar-connections h))
(disconnect c)))
;;(defmethod handle-all-connections ((h hactar))
;; (dolist (c (hactar-connections h))
;; (read-and-act c)))
(defmethod continuous-handle-all-connections ((h hactar))
(event:event-dispatch))
(defmethod add-callback ((h hactar) name callback)
(setf (gethash name (hactar-callbacks h)) callback))
(defmethod join-channel ((h hactar) channel)
(dolist (c (hactar-connections h))
(join-channel c channel)))
;;(defmethod add-callback ((h hactar) (c callback))
;; (add-callback h (callback-id c) c))
(defmethod del-callback ((h hactar) name)
(remhash name (hactar-callbacks h)))
(defmethod filter-event ((h hactar) (c connection) (f filter) event)
(run-filter h c f event))
(defmethod command-event ((h hactar) (c connection) (cmd command) event)
(run-command h c cmd event))
(defmethod invoke-callback ((h hactar) (c connection) (e event) (f filter))
(format t "Running filter...")
(run-filter h c f e))
(defmethod invoke-callback ((h hactar) (c connection) (e event) (cmd command))
(format t "Running command...")
(if (run-command h c cmd e) (throw 'stop-callbacks nil)))
(defmethod hactar-handle-event ((h hactar) (c connection) (e event))
"Handle incoming event"
(format t "Handeling incoming event:\"~a\"~%" (event-message-body e))
(catch 'stop-callbacks
(maphash #'(lambda (cn cb)
(invoke-callback h c e cb)) (hactar-callbacks h))))
| 2,470 | Common Lisp | .lisp | 54 | 41.888889 | 109 | 0.684167 | jadahl/hactar | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 81f8c78947799ade6aef83e63998ff0f019049dac3d4825260a1dd0af915a420 | 17,665 | [
-1
] |
17,666 | packages.lisp | jadahl_hactar/src/packages.lisp | (in-package :cl-user)
(defpackage :hactar
(:use :cl :cl-user)
(:export
:hactar
:hactar-connections :hactar-default-connections
:connect-all
:handle-all-connections
:continuous-handle-all-connections
;; basic stuff
:room
:room-name
:room-contains-participant
:room-nick
:event
:event-respond-to :event-from-nick :event-respond-type :event-message-body
:message
:message-target
:message-body
;; basic protocol classes and accessors
:connection
:connection-state
:connection-default-rooms
:connect
:disconnect
:connected
:read-and-act
:send-message
:join-room
:add-room
:join-all-rooms
;; jabber specific
:jabber-room
:make-jabber-room
:jabber-event
:jabber-connection))
| 802 | Common Lisp | .lisp | 36 | 17.555556 | 78 | 0.681937 | jadahl/hactar | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | ac880d831508545a78684f50c110df8bb44352bccf3d3d4f42b9a1c175085f06 | 17,666 | [
-1
] |
17,667 | test-hactar.lisp | jadahl_hactar/src/test/test-hactar.lisp | (require 'asdf)
(asdf:operate 'asdf:load-op :hactar)
(in-package :hactar)
(defun test-irc ()
(let ((default-channels
(list
(make-irc-channel "#test" "Hactar_beta_"))))
(setf h (make-instance
'hactar
:default-connections (list
(make-instance
'irc-connection
:nick "Hactar_beta"
:server "kietsu.olf.sgsnet.se"
:port 5899
:default-channels default-channels))))
(connect-all c)))
(defun test-jabber ()
(setf h (make-instance
'hactar))
(connect-all h (list
(make-instance
'jabber-connection
:username "test"
:password "test"
:server "lap"
:router-host "lap"
:router-port 5222))))
(defun test-talks ()
(setf h (make-instance
'hactar))
(connect-all h (list
(make-instance
'jabber-connection
:username "hactar"
:password "paranoid"
:server "jabber.se"
:router-host "jabber.se"
:router-port 5222)))
(join-channel
(car (hactar-connections h))
(make-jabber-channel "talks" "conference.jabber.se" "Hactar(beta)")))
(defun test-talks ()
(setf h (make-instance
'hactar))
(connect-all h (list
(make-instance
'jabber-connection
:username "hactar"
:password "paranoid"
:server "jabber.se"
:router-host "jabber.se"
:router-port 5222)))
(join-channel
(car (hactar-connections h))
(make-jabber-channel "test" "conference.jabber.se" "Hactar(beta)")))
;(continuous-handle-all-connections h))
(defun join-jabber ()
(join-channel
(car (hactar-connections h))
(make-jabber-channel "test" "conference.lap" "Hactar_beta_")))
| 2,329 | Common Lisp | .lisp | 61 | 21.918033 | 77 | 0.457804 | jadahl/hactar | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | cd87abf327ea59c8cfa2f524ca519b4d2d0049587528b64c7393d548a4789905 | 17,667 | [
-1
] |
17,668 | http.lisp | jadahl_hactar/src/utils/http.lisp | (in-package :hactar)
(defun http-get-body (uri-string)
(multiple-value-bind (body status headers uri stream must close)
(drakma:http-request uri-string)
(progn
(close stream)
body)))
| 206 | Common Lisp | .lisp | 7 | 25.142857 | 66 | 0.69697 | jadahl/hactar | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 6214fe4f4201128cb637b784f4025ab9851559e9edbf3326e77cfdab69a1ef04 | 17,668 | [
-1
] |
17,669 | debug.lisp | jadahl_hactar/src/utils/debug.lisp | ; License: GNU GPLv2
; Description: Hactar 2
; Author: Jonas Ådahl <[email protected]>
; (c) Copyright 2005 Jonas Ådahl
(in-package :hactar)
(defvar debug-output t)
(defun my-debug (&rest args)
(when debug-output
(apply 'format t args)))
| 253 | Common Lisp | .lisp | 9 | 25.777778 | 44 | 0.731092 | jadahl/hactar | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | fc1bf9aae53cbddcd44e9feff34c5c36a5e53d2f05c55a29cfc2403c3249b533 | 17,669 | [
-1
] |
17,670 | utils.lisp | jadahl_hactar/src/utils/utils.lisp | (in-package :hactar)
; split string into words
(defun split-string (str)
(let ((words nil)
(w 0)
(s 0))
(loop
(setf w (position-if #'(lambda (chr) (char/= #\Space chr)) str :start s))
(when (not w) (return))
(setf s (position #\Space str :start w))
(pushnew (subseq str w s) words)
;;(setf words (append words (list (substring str w s))))
(when (or (not w) (not s)) (return)))
words))
(defvar *command-operators* (list "!" "+"))
(defun match-command (str command)
(format t "length:~a~%" (length str))
(when (and
(> (length str) 1)
(eq 0 (position (subseq str 0 1) *command-operators* :test #'string-equal)))
(let ((given-command (subseq str 1)))
(string-equal given-command command))))
| 789 | Common Lisp | .lisp | 22 | 30.227273 | 86 | 0.584535 | jadahl/hactar | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 37300f0bb20c8106346e1aff2b5a61021b9b20451ecd21fdcc23f07699e021bb | 17,670 | [
-1
] |
17,671 | jabber.lisp | jadahl_hactar/src/protocols/jabber.lisp | ; License: GNU GPLv2
; Description: Hactar 2
; Author: Jonas Ådahl <[email protected]>
; (c) Copyright 2005 Jonas Ådahl
(in-package :hactar)
(defclass jabber-channel (channel jabber:conference)
())
(defmethod channel-name ((r jabber-channel))
(format nil "~a@~a"
(jabber:conference-name r)
(jabber:conference-server r)))
(defmethod channel-contains-participant ((r jabber-channel) nick)
(if (gethash nick (jabber:conference-participants r)) t nil))
(defmethod channel-nick ((r jabber-channel))
(jabber:conference-nick r))
(defun make-jabber-channel (channel server nick)
"Instantiate a jabber channel"
(make-instance 'jabber-channel
:name channel
:server server
:nick nick))
(defclass jabber-event (event)
((jabber-message :accessor event-jabber-message
:initarg :jabber-message)))
(defmethod event-respond-type ((e jabber-event))
(let ((m (event-jabber-message e)))
(if (string-equal (jabber:stanza-type m) "groupchat")
'groupchat
'private)))
(defmethod event-respond-to ((e jabber-event))
(let ((m (event-jabber-message e)))
(if (eq (event-respond-type e) 'groupchat)
(jabber:jid-user (jabber:stanza-from m))
(jabber:stanza-from m))))
(defmethod event-from-nick ((e jabber-event))
(let ((m (event-jabber-message e)))
(jabber:jid-resource (stanza-from m))))
(defmethod event-message-body ((e jabber-event))
(let ((m (event-jabber-message e)))
(jabber:message-body m)))
(defclass jabber-connection (connection jabber:client jabber:muc)
())
(defmethod jabber:authenticated :after ((c jabber-connection))
(connected c))
(defmethod jabber:joined-conference :after ((c jabber-connection)
(co jabber:conference))
(format t "Joined ~a.~%" (format nil "~a@~a"
(jabber:conference-name co)
(jabber:conference-server co)))
(joined-channel c (format nil "~a@~a"
(jabber:conference-name co)
(jabber:conference-server co))))
(defmethod connect ((c jabber-connection))
"Connect to a Jabber server."
(format t "Connecting to jabber server...")
(jabber:connect c)
(setf (connection-state c) 'connected))
(defmethod disconnect ((c jabber-connection))
"Disconnect from a Jabber server."
(jabber:connection-close c))
(defmethod connection-stream ((c jabber-connection))
(jabber:connection-socket c))
(defmethod send-message ((c jabber-connection) (m message))
"Send event to target using jabber."
(let ((type (cond
((eq (message-type m) 'groupchat) "groupchat")
(t "chat"))))
(jabber:send-message c :to (message-target m) :body (message-body m) :type type)))
(defmethod read-and-act ((c jabber-connection) &key (block nil))
(format t "Reading and acting~%")
(jabber:read-and-act c :block block))
(defmethod join-channel ((c jabber-connection) (r jabber-channel))
(when (equal (connection-state c) 'activated)
(jabber:join-conference c r)))
(defmethod jabber:handle-stanza ((c jabber-connection) (m jabber:message))
(format t "Received message from ~a: ~a~%" (jabber:jid-resource (jabber:stanza-from m)) (jabber:message-body m))
;; when jid resource is empty the message comes directly from the conference room
;; should be changed to enable normal non-muc chats
(when (jabber:jid-resource (jabber:stanza-from m))
;; ignore history messages
(if (not (assoc '("x" . "jabber:x:delay") (jabber:stanza-children m) :test #'equal))
(let ((from-channel (get-channel c (jabber:jid-user (jabber:stanza-from m)))))
;; avoid handeling messages from self
(when (and from-channel
(not (string-equal (jabber:stanza-from m)
(concatenate 'string
(channel-name from-channel)
"/"
(channel-nick from-channel)))))
(call-event-master c (make-instance 'jabber-event
:jabber-message m
:connection c
;(remhash n (connection-pending-channels c)))
:channel from-channel)))))))
| 4,480 | Common Lisp | .lisp | 94 | 37.659574 | 114 | 0.610958 | jadahl/hactar | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 0e2f2edb248dd7b70f7d92db10820097619c4e04f5b06450596d2dc01c002f14 | 17,671 | [
-1
] |
17,672 | irc.lisp | jadahl_hactar/src/protocols/irc.lisp | ; License: GNU GPLv2
; Description: Hactar 2
; Author: Jonas Ådahl <[email protected]>
; (c) Copyright 2005 Jonas Ådahl
(in-package :hactar)
(defclass irc-channel (channel)
((name :accessor irc-channel-name
:initform nil
:initarg :name)
(nick :accessor irc-channel-nick
:initarg :nick
:initform nil)
(participants :accessor irc-channel-participants
:initform nil)))
(defmethod channel-name ((c irc-channel))
(irc-channel-name c))
(defmethod channel-contains-participant ((c irc-channel) nick)
(if (gethash nick (irc-channel-participants c)) t nil))
(defmethod channel-nick ((c irc-channel))
(irc-channel-nick c))
(defun make-irc-channel (channel nick)
"Instantiate a IRC channel"
(make-instance 'irc-channel
:name channel
:nick nick))
(defclass irc-event (event)
((irc-message :accessor irc-event-message
:initform nil
:initarg :irc-message)))
(defmethod event-respond-to ((e irc-event))
(let ((m (irc-event-message e)))
(irc:source m)))
(defmethod event-from-nick ((e irc-event))
(let ((m (irc-event-message e)))
(irc:user m)))
(defmethod event-respond-type ((e irc-event))
'groupchat) ;;; verify
(defmethod event-message-body ((e irc-event))
(let ((m (irc-event-message e)))
(irc:command m)))
(defclass irc-connection (connection)
((nick :accessor irc-nick
:initarg :nick
:initform nil)
(socket :accessor irc-socket
:initform nil)
(server :accessor irc-server
:initarg :server
:initform nil)
(port :accessor irc-port
:initarg :port
:initform 6667)))
(defmethod add-hooks ((c irc-connection))
(format t "HOOKING UP IRC-HANDLE-PRIVMSG")
(irc:add-hook (irc-socket c) 'irc::irc-privmsg-message (lambda (m) (irc-handle-privmsg c m))))
(defmethod connect ((c irc-connection))
"Connect to an IRC server."
;;(my-debug "Connecting to ~a:~a~%" host port)
(setf (irc-socket c) (irc:connect :nickname (irc-nick c) :server (irc-server c) :port (irc-port c)))
(add-hooks c))
(defmethod disconnect ((c irc-connection))
(irc:quit *hactar-quit-message*))
(defmethod connection-stream ((c irc-connection))
(irc::network-stream (irc-socket c)))
(defmethod send-message ((c irc-connection) (m message))
"Send message to a target using irc"
(format t "Sending irc message to ~a: ~a~%" (message-target m) (message-body m))
(irc:privmsg (irc-socket c) (message-target m) (message-body m)))
(defmethod read-and-act ((c irc-connection) &key (block nil))
(when (or block
#+clisp (ext:read-byte-lookahead (irc::network-stream (irc-socket c)))
#-clisp (listen (irc::network-stream (irc-socket c)))
)
(format t "read?~a~%" (ext:read-byte-lookahead (irc::network-stream (irc-socket c))))
(irc:read-message (irc-socket c))))
(defmethod join-channel ((c irc-connection) (ch irc-channel))
(irc:join (irc-socket c) (channel-name ch)))
(defmethod irc-handle-privmsg ((c irc-connection) (m irc:irc-message))
(call-event-master c (make-instance 'irc-event :irc-message m)))
;; add ctcp version
(in-package :irc)
(setf *ctcp-version* (format nil "Hactar 0.2.0 using ~a" *ctcp-version*))
(in-package :hactar)
| 3,322 | Common Lisp | .lisp | 83 | 34.855422 | 102 | 0.665005 | jadahl/hactar | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 6fb0a61bec8cc7433120ec5f3514acbd8fab7df56666082761489d58b50ce42c | 17,672 | [
-1
] |
17,673 | base.lisp | jadahl_hactar/src/protocols/base.lisp | ; License: GNU GPLv2
; Description: Hactar 2
; Author: Jonas Ådahl <[email protected]>
; (c) Copyright 2005 Jonas Ådahl
(in-package :hactar)
;; Room class
;; put stuff like data private to channel here some way like hashtable
(defclass channel ()
((database :accessor channel-database
:initform nil)))
(defmethod channel-name ((r channel))
"Returns the name of the channel"
"woot")
(defmethod channel-contains-participant ((r channel) nick)
"Returns t if nick exists in the channel")
(defmethod channel-nick ((r channel))
"Returns the nick Hactar uses in this channel")
;;;
; event - messages from chat channel or person
(defclass event ()
((connection :accessor event-connection
:initform nil
:initarg :connection)
(channel :accessor event-channel
:initform nil
:initarg :channel)))
(defmethod event-respond-to ((e event))
"Return the target of which the respond should be sent to")
(defmethod event-from-nick ((e event))
"Return the nick of the identity that the message comes from")
(defmethod event-respond-type ((c event))
"Return what type the respond message should be: 'private or 'groupchat")
(defmethod event-message-body ((e event))
"Return the message part of the event")
(defclass dummy-event ()
((body :accessor dummy-event-body
:initarg :body)))
(defmethod event-message-body ((e dummy-event))
(dummy-event-body e))
(defclass message ()
((target :accessor message-target
:initarg :target)
(body :accessor message-body
:initarg :body)
(type :accessor message-type
:initarg :type
:initform 'chat)))
(defmethod response-message ((e event) body)
"Generate a respond message from an event with a given body."
(make-instance 'message
:target (event-respond-to e)
:type (event-respond-type e)
:body body))
;;;
; hactar-connection - basic operations for a server connection
;
; Usage:
; (defclass irc-connection (hactar-connection) ...)
;
; Features:
; hook - function hooks, features to the bot
; database - data stored on hard drive, should be loaded on startup
; runtime - runtime data for this connection
;
; Methods:
; (hactar-connect connection :host "hostname" :port portnum)
; (hactar-disconnect connection)
; (hactar-read connection)
; (hactar-send connection hactar-id data)
;;;
(defclass connection ()
((state :accessor connection-state
:initarg :state
:initform 'unconnected)
(event-handler :accessor connection-event-handler
:initform nil)
(event-master :accessor connection-event-master
:initform nil)
;; integer telling how many seconds the client should wait to connect
;; after a ping packet is transmitted
(reconnect-timeout :accessor connection-reconnect-timeout
:initarg :reconnect-timeout
:initform 0)
;; channels who are being connected to
(pending-channels :accessor connection-pending-channels
:initform (make-hash-table :test #'equal))
;; established channels
(channels :accessor connection-channels
:initform (make-hash-table :test #'equal))
;; list of filter and function callbacks
(callbacks :accessor connection-callbacks
:initarg :hooks
:initform nil)
;; reference to what database to use
(database :accessor connection-database
:initarg :database
:initform nil)
;; (socket :accessor connection-socket
;; :initform nil)
(runtime :accessor connection-runtime
:initarg :runtime
:initform nil)))
;;;
; Methods of hactar-connection
(defmethod connect :before ((c connection))
(setf (connection-state c) 'connecting)
(my-debug "Protocol: connecting..."))
(defmethod disconnect :before ((c connection))
(setf (connection-state c) 'disconnected)
(my-debug "Protocol: disconnecting~%"))
(defmethod connected ((c connection))
(format t "Connected... joining all channels.~%")
; FIXME notify session handler
(setf (connection-state c) 'activated)
(maphash #'(lambda (cn ch) (join-channel c ch))
(connection-pending-channels c)))
;;(join-all-channels c))
(defmethod connection-stream ((c connection))
"Return stream object"
(error "There is no stream object in an abstract connection"))
(defmethod read-and-act ((c connection) &key (block nil))
"Read and act.")
(defmethod send-message ((c connection) (m message)))
(defmethod delete-channel ((c connection) n)
(remhash n (connection-pending-channels c)))
(defmethod get-channel-f ((c connection) channel-name f)
(format t "calling ~a with ~a~%" f c)
(let ((channels (funcall f c)))
(gethash channel-name channels)))
(defmethod get-pending-channel ((c connection) channel-name)
(get-channel-f c channel-name 'connection-pending-channels))
(defmethod get-channel ((c connection) channel-name)
(get-channel-f c channel-name 'connection-channels))
(defmethod join-channel :before ((c connection) (r channel))
"Join a channel"
(let ((n (channel-name r)))
(setf (gethash n (connection-pending-channels c)) r)))
(defmethod joined-channel ((c connection) channel-name)
(let ((ch (gethash channel-name (connection-pending-channels c))))
(remhash channel-name (connection-pending-channels c))
(setf (gethash channel-name (connection-channels c)) ch)
))
;; when to initiate channel wise?
;;(when ch (initiate-all-callbacks c ch))))
(defmethod initiate-all-callbacks ((c connection) (r channel))
(maphash #'(lambda (ck cb) (initiate-callback (cdr cb) r))
(connection-callbacks c)))
(defmethod add-channel ((c connection) (r channel))
(pushnew r (connection-channels c)))
(defmethod join-all-channels ((c connection) channels)
(dolist (r channels)
(join-channel c r)))
(defmethod call-event-master ((c connection) (e event))
(let ((handler (connection-event-handler c))
(master (connection-event-master c)))
(if (and handler master)
(funcall (connection-event-handler c) (connection-event-master c) c e)
(format t "WARNING: Connection has no master, all events will be discarded."))))
| 6,304 | Common Lisp | .lisp | 158 | 34.892405 | 86 | 0.690772 | jadahl/hactar | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | e660561b2b6ecc1f3828528791869f6b6cdc1cdc6c65c570848f551eba9b19be | 17,673 | [
-1
] |
17,674 | command.lisp | jadahl_hactar/src/func/command.lisp | (in-package :hactar)
(defclass command (callback)
((prefixes :accessor command-prefixes
:initform '("!" "+")
:initarg :prefixes
:documentation "Command prefixes, !weather where ! is the prefix")
(ignore-whitespace :accessor command-ignore-whitespace
:initform t
:initarg :ignore-whitespace)))
(defmethod run-command (h c (cmd command) x)
"Function: do something with every event")
;; helper functions
;; Name: command-prefix-of
;; Returns: prefix length or nil if no match
(defun command-prefix-of (prefix command body)
(let ((prefix-length (+ (length prefix) (length command))))
(when (>= (length body) prefix-length)
(string-equal (concatenate 'string prefix command)
body :end2 prefix-length))))
(defun is-of-command (prefixes command body)
(let ((prefix (car prefixes)))
(when prefix
(if (command-prefix-of prefix command body)
t
(is-of-command (cdr prefixes) command body)))))
(defmacro cond-command-args (command event &rest clauses)
(cons
'cond
(let ((body `(event-message-body ,event)))
(mapcar
(lambda (clause)
(let* ((cmd-expr (car clause))
(cmd-string (first cmd-expr))
(args-name (second cmd-expr))
(code (cdr clause)))
`((is-of-command (command-prefixes ,command) ,cmd-string ,body)
(let ((,args-name (cdr (ppcre:split " " ,body))))
,@code))))
clauses))))
(defmacro cond-command (command event &rest clauses)
`(cond-command-args ,command ,event
,@(mapcar (lambda (clause)
`((,(car clause)
tmp)
(declare (ignore tmp))
,@(cdr clause)))
clauses)))
| 1,856 | Common Lisp | .lisp | 47 | 30.021277 | 79 | 0.578333 | jadahl/hactar | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | caa05596ec321c5206cd5788a26e0ea0d72db78aad93039faf491431328d5ec2 | 17,674 | [
-1
] |
17,675 | filterskel.lisp | jadahl_hactar/src/func/filterskel.lisp | (in-package :hactar)
(defclass filterskel (filter) ())
(defmethod initiate-callback ((h hactar) (c connection) (f filterskel))
(setf (connection-database c) (acons 'filterskel 0 (connection-database c))))
(defmethod run-filter ((h hactar) (c connection) (f filterskel) (e event))
(format t "Length of message:~a~%" (length (event-message-body e))))
| 357 | Common Lisp | .lisp | 6 | 57.166667 | 79 | 0.720461 | jadahl/hactar | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | e2a33482a802c49824957cbdfa318e3cf01e5ba23f477e7348a9a51be74d05b4 | 17,675 | [
-1
] |
17,676 | foo-command.lisp | jadahl_hactar/src/func/foo-command.lisp | (in-package :hactar)
(defclass foo-command (command)
())
(defmethod run-command ((h hactar) (c connection) (cmd command) (e event))
(if (equal (event-message-body e) "!foo")
(progn
(send-message c (response-message e "bar"))
t)
nil))
| 261 | Common Lisp | .lisp | 9 | 25 | 74 | 0.64257 | jadahl/hactar | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | de6f2fb9f2b000af87db9aacb5ad4771020395db0fe7799592d457a623942d36 | 17,676 | [
-1
] |
17,677 | callback.lisp | jadahl_hactar/src/func/callback.lisp | (in-package :hactar)
(defclass callback ()
((id :accessor callback-id
:initarg :id
:initform nil)
(acl :accessor callback-acl
:initarg :acl
:initform '((allow . all)))))
(defmethod initiate-callback (h c (cb callback))
"Called once for every channel")
| 302 | Common Lisp | .lisp | 10 | 24.3 | 48 | 0.628472 | jadahl/hactar | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 7541f8f52aebb15870afa99c4f54dded3258549cbdd20ba9c9b84dfa8048ff73 | 17,677 | [
-1
] |
17,678 | filter.lisp | jadahl_hactar/src/func/filter.lisp | (in-package :hactar)
(defclass filter (callback)
())
(defmethod run-filter (h c (f filter) x)
"Do something with every event")
| 133 | Common Lisp | .lisp | 5 | 24.4 | 40 | 0.714286 | jadahl/hactar | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 549fb7ce67a4cb46ff0e14016f359801ae51c365a2cc74e4a61a2cd164a37f0e | 17,678 | [
-1
] |
17,679 | katter.lisp | jadahl_hactar/src/plugins/katter.lisp | (defvar *katt*
'("Katt åt bakpulver, pös i magen."
"Katt åt ballong, var blåst."
"Katt åt basketboll, fick uppkast."
"Katt åt batteri, gjorde volt."
"Katt åt ben, gick bort."
"Katt åt bestick, började gaffla"
"Katt åt bi, sur."
"Katt åt bil, blev ivägkörd."
"Katt åt bil, blev Jaguar."
"Katt åt bildäck, spann loss."
"Katt åt biskop, stift i magen."
"Katt åt blondin, våp i magen."
"Katt åt Bob Marley, Jam(n)ing."
"Katt åt boll, fick uppkast."
"Katt åt boll, rund om magen."
"Katt ät bomb, smällde av."
"Katt åt bord, dukade under."
"Katt åt båt, dog förut."
"Katt åt cement, hård i magen."
"Katt åt deg, smet."
"Katt åt cigarett, blev rökt."
"Katt åt cigarett, blev överaskad."
"Katt åt cyanid, blev gift."
"Katt åt drag, blev förkyld."
"Katt åt dörrvakt, blev portad."
"Katt åt eka, fick ro."
"Katt åt elkabel, följde strömmen."
"Katt åt elskåp, blev proppmätt."
"Katt åt engelsk hund, dog."
"Katt åt filmrulle, blev negativ."
"Katt åt fisk, gös i magen."
"Katt åt fiskare, fick spö."
"Katt åt fjärdedel, bråk i magen."
"Katt åt fluga, flög iväg."
"Katt åt flykting, utvisades."
"Katt åt frys, svalt."
"Katt åt färgburk, dog på fläcken."
"Katt åt fönster, såg bra ut."
"Katt åt gammal historia, skämt i magen."
"Katt åt gasol, gaser i magen."
"Katt åt gitarr, blev stämd."
"Katt åt golfare, fick utslag."
"Katt åt glas, blev splittrad."
"Katt åt glasögon, såg bra ut."
"Katt åt glödlampa, lös i magen."
"Katt åt glödlampa, blev tänd."
"Katt åt granat, blev på smällen."
"Katt åt gris, blev grymt mätt."
"Katt åt grus, blev stenad."
"Katt åt haj, hade inge´ val."
"Katt åt hammare, blev slagfärdig."
"Katt åt helvete, alla glada."
"Katt åt helvete, fick halsbränna."
"Katt åt helvete, började svära."
"Katt åt helvete, klös i magen."
"Katt åt honung, fick biverknigar."
"Katt åt hummer, blev dummer."
"Katt åt hjul, blev däckad."
"Katt åt honung, hade bismak."
"Katt åt hästskit, fattade galoppen."
"Katt åt höger, röstade borgerligt."
"Katt åt svärmor, släkt i magen."
"Katt åt hink, spann."
"Katt åt hip-hoppare, rapade."
"Katt åt hund, fick skäll."
"Katt åt illsint katt, klös i magen."
"Katt åt insekt, fick fjärilar i magen."
"Katt åt is, frös i magen."
"Katt åt JAS, blev Gripen."
"Katt åt John Pohlman, släppte väder."
"Katt åt kaktus, stack iväg."
"Katt åt karta, var utmärkt."
"Katt åt kasse, sket påse!"
"Katt åt kattsand, skit också."
"Katt åt klocka, gick rätt."
"Katt åt klocka, spårar ur."
"Katt åt klämma, knip i magen."
"Katt åt kniv, tappade hakan."
"Katt åt kork, blev dum!"
"Katt åt kortlek, fick spader."
"Katt åt kruka, blev feg."
"Katt åt kruka, växte."
"Katt åt kvällsmus, var ute efteråtta."
"Katt åt kyl, skåp i magen."
"Katt åt kälke, fick medgång."
"Katt åt lampa, lös i magen."
"Katt åt linjal, blev mätt."
"Katt åt lur, blev lurad, som katten."
"Katt åt massor av sten, rös i magen."
"Katt åt trasig miniräknare, fick talfel."
"Katt åt moped, fick kicken."
"Katt åt mus, fick datorkrångel."
"Katt åt målare, fick färg."
"Katt åt måttstock, blev mätt."
"Katt åt näsduk, nös i magen."
"Katt åt olja, fick smörj."
"Katt åt paj, kom i form."
"Katt åt papper, sket massa."
"Katt åt peruk, fick håravfall."
"Katt åt pipan, gick upp i rök."
"Katt åt pipeline, fick gas i magen."
"Katt åt PlayStation, fick spel."
"Katt åt programmerare, kunde inte C."
"Katt åt påse, fick påssjuka."
"Katt åt påse, sket på´se."
"Katt åt resväska, blev packad."
"Katt åt räka, börja kräka."
"Katt åt seismograf, fick utslag."
"Katt åt sill, blev inlagd."
"Katt åt sko, fick sparken."
"Katt åt skogen, försvunnen."
"Katt åt printer, skrevs ut dagen efter."
"Katt åt sladd, tog ledningen."
"Katt åt släpvagn, blev dragen."
"Katt åt skidor, hamnade på glid."
"Katt åt sko, kunde gå på Catwalk."
"Katt åt 200 kg skinka, blev baktung."
"Katt åt smed, fick städmani."
"Katt åt snickare, blev brädad."
"Katt åt snikare, börja planka."
"Katt åt snyggingar på flygplats, reste ragg."
"Katt åt socker, blev söt."
"Katt åt spöke, fick dålig ande-dräkt."
"Katt åt stenåldersgrav, dös i magen."
"Katt åt stins, spårade ur."
"Katt åt stins, en skenmanöver."
"Katt åt stins, blev enkenspårig."
"Katt åt stins, fick platt form."
"Katt åt stol, satt fint."
"Katt åt stol, satt i halsen."
"Katt åt stege, blev hög."
"Katt åt suddgummi, försvann."
"Katt åt Susanne Lanefelt, fick kniip i magen."
"Katt åt Svan, skidåkare i magen."
"Katt åt säck, sket på se."
"Katt åt t-sprit, fick blindtarmen."
"Katt åt telefon, tog en lur."
"Katt åt telefon i krukmakeri, lurendrejad."
"Katt åt tomten, fick klapp."
"Katt åt tre flickor och tre pojkar, sex i magen."
"Katt åt windows, hängde sig."
"Katt åt trummor, kände sig slagen."
"Katt åt träd, dog på stubben."
"Katt åt träd, fick stock."
"Katt åt trädgård, fick rabatt."
"Katt åt tåg, blev tuff."
"Katt åt Viagra, fick ståpäls."
"Katt åt vulkan, fick utbrott."
"Katt åt vänster, prasslade."
"Katt åt östermalmsbo, knös i magen."))
| 5,741 | Common Lisp | .lisp | 151 | 31.192053 | 54 | 0.647015 | jadahl/hactar | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 4e2c09dff4885e8595175e0cd50fcbac23909b24f4fae384cd7d4d402446c2bd | 17,679 | [
-1
] |
17,680 | google.lisp | jadahl_hactar/src/plugins/google.lisp | (in-package :hactar)
(defclass google-command (command)
())
(defmethod run-command ((h hactar) (c connection) (cmd google-command) (ev event))
(cond-command-args (identity cmd) (identity ev)
(("google" args)
(format t "eh:~a~%" args)))
(cond-command-args
cmd ev
(("google" args)
(let ((result (google-search args)))
(when result
(send-message c (response-message ev result)))))))
(defun render-query (args)
(reduce (lambda (x y) (concatenate 'string x "+" y)) args))
(defun google-search (args)
(let ((query (render-query args)))
(multiple-value-bind (body code headers uri stream must-close)
(drakma:http-request
(format nil "http://www.google.com/search?q=~a&btnI=" query)
:redirect nil)
(declare (ignore body))
(declare (ignore uri))
(declare (ignore must-close))
(declare (ignore body))
(let ((loc (cdr (assoc :location headers))))
(if loc
loc
"No result.")))))
| 1,036 | Common Lisp | .lisp | 29 | 28.862069 | 82 | 0.599202 | jadahl/hactar | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 7108965ccc9029466ec2c525cbcb8e3aff26386e312872011025dd9f75d4a0d8 | 17,680 | [
-1
] |
17,681 | katt.lisp | jadahl_hactar/src/plugins/katt.lisp | ; License: GNU GPLv2
; Author: Jonas Ådahl
; (c) Copyright 2007 Jonas Ådahl
;
; Based on katt.lisp from Hactar version 1
(in-package :hactar)
(defclass katt (command)
())
(defmethod run-command ((h hactar) (c connection) (cmd katt) (e event))
(if (string-equal (event-message-body e) "!katt")
(progn
(send-message c (response-message
e
(elt *katt* (random (length *katt*)))))
t)
nil))
| 463 | Common Lisp | .lisp | 16 | 23.0625 | 71 | 0.603175 | jadahl/hactar | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | a57dc01f4e46e252da1935149aab11653ea8a4c4489839dd47b6853aabfa4efe | 17,681 | [
-1
] |
17,682 | hactar.asd | jadahl_hactar/src/hactar.asd | (defpackage hactar-system
(:use :common-lisp :asdf))
(in-package hactar-system)
(defsystem hactar
:version "0.2.0"
:licence "GPLv2"
:depends-on (:jabber-client
:jabber-muc
:cl-event
:cl-ppcre
:drakma)
;:cl-irc)
:components
((:file "packages")
(:module utils
:depends-on ("packages")
:components
((:file "debug")
(:file "utils")))
(:module protocols
:depends-on ("packages" utils)
:components
((:file "base")
(:file "jabber" :depends-on ("base"))))
;(:file "irc" :depends-on ("base"))))
(:module func
:depends-on ("packages" utils)
:components
((:file "callback")
(:file "filter" :depends-on ("callback"))
(:file "command" :depends-on ("callback"))))
(:file "hactar" :depends-on (protocols func))
(:module plugins
:depends-on ("hactar" utils)
:components
((:file "google")
(:file "katter")
(:file "katt" :depends-on ("katter"))))
(:file "main" :depends-on ("hactar" plugins))))
| 1,428 | Common Lisp | .asd | 39 | 21.487179 | 66 | 0.421774 | jadahl/hactar | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | dd8b812da79e224bad270060fee01f1b8cbc789a3ea3a562cb41f784a368c701 | 17,682 | [
-1
] |
17,716 | db.lisp | ryanbarry_btcl/db.lisp | (in-package :btcl-db)
(defclass db-block ()
((hash :col-type (string 64) :initarg :hash)
(network :col-type bigint :initarg :network)
(version :col-type bigint :initarg :version)
(hash-prev-block :col-type (string 64) :initarg :hash-prev-block)
(hash-merkle-root :col-type (string 64) :initarg :hash-merkle-root)
(timestamp :col-type timestamp-with-time-zone :initarg :timestamp)
(bits :col-type bigint :initarg :bits)
(nonce :col-type bigint :initarg :nonce)
(height :col-type bigint :initarg :height))
(:metaclass pomo:dao-class)
(:keys hash)
(:table-name block))
(pomo:deftable (db-block "block")
(pomo:!dao-def))
(defclass db-transaction ()
((hash :col-type (string 64) :initarg :hash)
(network :col-type bigint :initarg :network)
(version :col-type bigint :initarg :version)
(lock-time :col-type bigint :initarg :lock-time))
(:metaclass pomo:dao-class)
(:keys hash)
(:table-name transaction))
(pomo:deftable (db-transaction "transaction")
(pomo:!dao-def))
(defclass db-tx-in ()
((hash-prev-tx :col-type (string 64) :initarg :hash-prev-tx)
(index-prev-tx :col-type integer :initarg :index-prev-tx)
(script-sig :col-type bytea :initarg :script-sig)
(sequence :col-type bigint :initarg :sequence)
(transaction :col-type (string 64) :initarg :transaction)
(tx-index :col-type integer :initarg :tx-index))
(:metaclass pomo:dao-class)
(:keys transaction tx-index)
(:table-name tx-in))
(pomo:deftable (db-tx-in "tx-in")
(pomo:!dao-def)
(pomo:!foreign 'transaction 'transaction :primary-key))
(defclass db-tx-out ()
((value :col-type bigint :initarg :value)
(script-pubkey :col-type bytea :initarg :script-pubkey)
(transaction :col-type (string 64) :initarg :transaction)
(tx-index :col-type integer :initarg :tx-index))
(:metaclass pomo:dao-class)
(:keys transaction tx-index)
(:table-name tx-out))
(pomo:deftable (db-tx-out "tx-out")
(pomo:!dao-def)
(pomo:!foreign 'transaction 'transaction :primary-key))
(defclass db-block-transaction ()
((block-hash :col-type (string 64) :initarg :block-hash)
(tx-hash :col-type (string 64) :initarg :tx-hash)
(block-tx-index :col-type integer :initarg :block-tx-index))
(:metaclass pomo:dao-class)
(:keys block-hash block-tx-index)
(:table-name block-transaction))
(pomo:deftable (db-block-transaction "block-transaction")
(pomo:!dao-def)
(pomo:!foreign 'block 'block-hash :primary-key)
(pomo:!foreign 'transaction 'tx-hash :primary-key))
(defun start (&key (db "btcl") (user "btcl") (password "btcl") (host "localhost") (port 5432))
(unless (and pomo:*database* (pomo:connected-p pomo:*database*))
(pomo:connect-toplevel db user password host :port port))
;; TODO: auto-create schema if not already exists
;; (dolist (t '(blk transaction tx-in tx-out block-transaction)))
)
(defun end ()
(pomo:disconnect-toplevel))
(defgeneric save (obj))
(defmethod save ((obj bty:tx))
(let ((tx-hash (btcl-digest:strhash obj)))
;; (format t "hash: ~s (~d)~%" tx-hash (length tx-hash))
(with-slots (bty::version bty::tx-in bty::tx-out bty::lock-time) obj
(pomo:with-transaction ()
(list (pomo:save-dao (make-instance 'db-transaction
:hash tx-hash
:network btcl-constants:+TESTNET3-MAGIC+
:version bty::version
:lock-time bty::lock-time))
(loop for txin in bty::tx-in
for i from 0
collect (with-slots (bty::previous-output bty::script-sig bty::seq) txin
(pomo:save-dao (make-instance 'db-tx-in
:hash-prev-tx (ironclad:byte-array-to-hex-string
(slot-value bty::previous-output 'bty::hash))
:index-prev-tx (slot-value bty::previous-output 'bty::index)
:script-sig bty::script-sig
:sequence bty::seq
:transaction tx-hash
:tx-index i))))
(loop for txout in bty::tx-out
for i from 0
collect (with-slots (bty::value bty::script-pk) txout
(pomo:save-dao (make-instance 'db-tx-out
:value bty::value
:script-pubkey bty::script-pk
:transaction tx-hash
:tx-index i)))))))))
(defun init-db ()
(pomo:create-package-tables 'btcl-db))
| 4,962 | Common Lisp | .lisp | 101 | 37.039604 | 116 | 0.570574 | ryanbarry/btcl | 3 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | f7196380df53e4dde76b1dd91070d19a79a25bf78a8e9b57dd55c812a3d82a5f | 17,716 | [
-1
] |
17,717 | package.lisp | ryanbarry_btcl/package.lisp | ;;;
;;; BTCL: Bitcoin network node implementation in Common Lisp
;;; Copyright (C) 2015 Ryan Barry <[email protected]>
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU Affero General Public License as
;;; published by the Free Software Foundation, either version 3 of the
;;; License, or (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU Affero General Public License for more details.
;;;
;;; You should have received a copy of the GNU Affero General Public License
;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;
(in-package :cl-user)
(defpackage #:com.gigamonkeys.macro-utilities
(:nicknames :macut)
(:use :common-lisp)
(:export
:with-gensyms
:with-gensymed-defuns
:once-only
:spliceable
:ppme))
(defpackage #:com.gigamonkeys.portable-pathnames
(:use :common-lisp)
(:export
:list-directory
:file-exists-p
:directory-pathname-p
:file-pathname-p
:pathname-as-directory
:pathname-as-file
:walk-directory
:directory-p
:file-p))
(defpackage #:com.gigamonkeys.binary-data
(:nicknames :bindata)
(:use :common-lisp :com.gigamonkeys.macro-utilities)
(:export :define-binary-class
:define-tagged-binary-class
:define-binary-type
:read-value
:write-value
:*in-progress-objects*
:parent-of-type
:current-binary-object
:+null+))
(defpackage #:btcl
(:import-from #:com.gigamonkeys.portable-pathnames #:pathname-as-directory)
(:use #:cl)
(:export #:parse-bootstrap-file
#:parse-blockfile
#:print-block
#:get-unix-time))
(defpackage #:btcl-web
(:use :cl :cl-ppcre :cl-async :cl-who :parenscript)
(:import-from :babel #:octets-to-string)
(:export #:start-server
#:publish!
#:notify-tx
#:notify-blk))
(defpackage #:btcl-constants
(:nicknames #:btconst)
(:use #:cl)
(:export #:+P2P-MSG-HEADER-LEN+
#:+TESTNET3-MAGIC+
#:+TESTNET3-GENESIS-BLOCK+
#:+MAINNET-MAGIC+
#:+MAINNET-GENESIS-BLOCK+))
(defpackage #:btcl-types
(:nicknames #:bty)
(:use #:cl)
(:export #:raw-bytes
#:u8
#:u16be
#:u32be
#:u64be
#:u16le
#:u32le
#:u64le
#:s32le
#:s64le
#:varint
#:iso-8859-1-string
#:varstr
#:net-addr
#:version-net-addr
#:addr-list
#:inv-vector
#:inv-vector-list
#:outpoint
#:tx-in
#:tx-in-list
#:tx-out
#:tx-out-list
#:tx
#:tx-list
#:blk
#:build-ip-addr))
(defpackage #:btcl-digest
(:use #:cl)
(:export #:dsha256-checksum
#:dsha256
#:hash
#:strhash))
(defpackage #:btcl-db
(:use #:cl #:postmodern #:btcl-types)
(:export #:start
#:end
#:init-db
#:save))
(defpackage #:btcl-wire
(:nicknames #:btw)
(:use #:cl #:btcl #:btcl-digest #:btcl-util #:btcl-types #:btcl-db)
(:export #:peer-connection
#:start-peer
#:msg-version
#:msg-verack
#:msg-inv
#:msg-getdata
#:msg-tx
#:msg-block
#:msg-addr))
(defpackage #:btcl-core
(:nicknames #:bto)
(:export #:blok-header
#:blok))
(defpackage #:btcl-rules
(:nicknames #:btr)
(:use #:cl #:btcl #:btcl-core)
(:export #:check-block-header))
| 3,806 | Common Lisp | .lisp | 135 | 21.466667 | 77 | 0.587093 | ryanbarry/btcl | 3 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 2208e2b74446043a332a2265f89aceb3196e8092a561e1c673f6a1d804824632 | 17,717 | [
-1
] |
17,718 | rules.lisp | ryanbarry_btcl/rules.lisp | (in-package :btcl-rules)
(defun check-block-header (blk-header)
(if (and (check-proof-of-work (hash blk-header) (bits block-header))
(check-block-timestamp (timestamp blk-header)))
t
nil))
(defun check-proof-of-work (hash bits)
;; bits->target calculation from https://en.bitcoin.it/wiki/Difficulty#How_is_difficulty_stored_in_blocks.3F
(if (<= hash (* bits (expt 2 (* 8 (- #x1b 3)))))
t
nil))
(defun check-block-timestamp (timestamp)
(if (<= timestamp (+ (get-unix-time) (* 2 60 60)))
t
nil))
| 552 | Common Lisp | .lisp | 15 | 31.933333 | 110 | 0.638577 | ryanbarry/btcl | 3 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 37b35e2364a81ec8a15ee50a06d4d2290d623404b4355189b775461a2adec3a0 | 17,718 | [
-1
] |
17,719 | macro-utilities.lisp | ryanbarry_btcl/macro-utilities.lisp | (in-package :com.gigamonkeys.macro-utilities)
;;; Copyright (c) 2005-2010, Peter Seibel. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions are
;;; met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials provided
;;; with the distribution.
;;; * Neither the name of Gigamonkeys Consulting nor the names of its
;;; contributors may be used to endorse or promote products derived
;;; from this software without specific prior written permission.
;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
;;; LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
;;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
;;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
;;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(defmacro with-gensyms ((&rest names) &body body)
`(let ,(loop for n in names collect `(,n (make-symbol ,(string n))))
,@body))
(defmacro once-only ((&rest names) &body body)
(let ((gensyms (loop for n in names collect (gensym (string n)))))
`(let (,@(loop for g in gensyms collect `(,g (gensym))))
`(let (,,@(loop for g in gensyms for n in names collect ``(,,g ,,n)))
,(let (,@(loop for n in names for g in gensyms collect `(,n ,g)))
,@body)))))
(defun spliceable (value)
(if value (list value)))
(defmacro ppme (form &environment env)
(progn
(write (macroexpand-1 form env)
:length nil
:level nil
:circle nil
:pretty t
:gensym nil
:right-margin 83
:case :downcase)
nil))
| 2,429 | Common Lisp | .lisp | 47 | 47.87234 | 75 | 0.713504 | ryanbarry/btcl | 3 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | ffe0f711fd20c7636e1861569b3ef5a5a14cd09da0b8f0dcad3cb1cf996fce5e | 17,719 | [
-1
] |
17,720 | peer.lisp | ryanbarry_btcl/peer.lisp | (in-package :btcl-wire)
;;; TODO: all commented out (format)s need to be wrapped in a shim that allows
;;; them to be easily enabled/disabled
(defparameter *debug* t)
(defun event-cb (ev)
(handler-case
(error ev)
(as:tcp-timeout ()
(as:close-socket (as:tcp-socket ev)))
(as:tcp-error ()
(format t "tcp-error received, closing socket...")
(as:delay (lambda () (as:close-socket (as:tcp-socket ev)))))
(as:tcp-eof ()
(format t "tcp-eof received (peer likely disconnected) closing socket...")
(as:delay (lambda () (as:close-socket (as:tcp-socket ev)))))
(error ()
(when *debug*
(format t "error-ev: ~a (~a)~%" (type-of ev) ev)))))
(define-condition invalid-msg () (reason))
(defun accumulate-input (remote input-bytevec)
(push input-bytevec (slot-value remote 'read-buffers)))
(defun sum-list-sequence-lengths (buffers)
(reduce #'+ (map 'list #'length buffers) :initial-value 0))
(defun make-octet-input-stream (octet-vectors)
(apply #'make-concatenated-stream
(loop
for ov in octet-vectors
when (and (not (eql nil ov)) (> (length ov) 1))
collect (ironclad:make-octet-input-stream ov))))
(defun octet-input-stream-to-vector (stream)
(let ((s (ironclad:make-octet-output-stream)))
(handler-case (loop for b = (read-byte stream nil 'eof)
until (eql b 'eof)
do (write-byte b s)))
(ironclad:get-output-stream-octets s)))
;; in: list of byte vectors
;; out: (message or nil) and (list of byte vectors for remaining input)
(defun try-read-message (buffers)
"given a list of octet vectors as a read buffer, try to read a message"
;; (format t "~&trying to read a message (buffer has ~d bytes)"
;; (sum-list-sequence-lengths buffers))
(if (>= (sum-list-sequence-lengths buffers)
btcl-constants:+P2P-MSG-HEADER-LEN+)
(let* ((instream (make-octet-input-stream buffers))
(header (bindata:read-value 'p2p-msg-header instream)))
(if (>= (sum-list-sequence-lengths buffers) (+ (slot-value header 'len)
btcl-constants:+P2P-MSG-HEADER-LEN+))
(let* ((instream (make-octet-input-stream buffers))
(msg (bindata:read-value 'p2p-msg instream))
(leftovers (list (octet-input-stream-to-vector instream)))
;; (leftovers-len (sum-list-sequence-lengths leftovers))
)
;; (format t "~&got a msg, ~d bytes left in buffer after reading" leftovers-len)
;; (if (> leftovers-len 0)
;; (format t ", contents:~%~a" leftovers))
(values msg leftovers))
(progn
;; (format t "~%buffers only contain partial message (header-specified len: ~d, buffer len: ~d)"
;; (slot-value header 'len) (sum-list-sequence-lengths buffers))
;; (if (> (slot-value header 'len) 33554432) ; constant from bitcoind's serialize.h
;; (progn
;; (format t "this message is greater than MAX_SIZE!~%~a" buffers)
;; (-1)))
(values nil buffers))))
(progn
;; (format t "~%didn't get enough bytes for a header~%~%")
(values nil buffers))))
(defun make-read-cb (remote)
(lambda (socket bytevec)
(declare (ignore socket))
(accumulate-input remote bytevec)
(with-slots (read-buffers) remote
(loop with got-a-msg = t
do (multiple-value-bind (msg buf-list)
(try-read-message (reverse read-buffers))
(if msg
(handle-message remote msg)
(setf got-a-msg nil))
(setf read-buffers (reverse buf-list)))
while (and got-a-msg
(>= (sum-list-sequence-lengths read-buffers)
btcl-constants:+P2P-MSG-HEADER-LEN+))))))
(defun handle-message (remote message)
(with-slots (command checksum) (slot-value message 'header)
(multiple-value-bind (computed-cksm length msg-hash) (checksum-payload message)
(declare (ignore length))
(if (/= computed-cksm checksum)
(progn
(format t "~&checksum received: ~X~%checksum computed: ~X~%" checksum computed-cksm)
(signal 'invalid-msg :bad-checksum))
;(format t "checksum checks out!")
)
(with-slots (handshaken) remote
(cond ((string= command "verack")
(format t "~&got a verack!")
(setf handshaken (boole boole-ior handshaken #b10))
(format t "~&handshaken: ~d~%" handshaken))
((string= command "version")
(with-slots (version user-agent start-height) message
(format t "~&receive version message: ~s: version ~d, blocks=~d" user-agent version start-height))
(setf handshaken (boole boole-ior handshaken #b01))
(send-msg remote (prep-msg (make-instance 'msg-verack)))
(format t "~&handshaken: ~d~%" handshaken))
((string= command "inv")
(format t "~&got an inv notification!")
(with-slots (magic command len checksum cnt inv-vectors) (slot-value message 'header)
(with-slots (cnt inv-vectors) message
;(format t "~&magic: ~X~%command: ~s~%len: ~d~%checksum: ~X" magic command len checksum)
(let ((interesting-inventory (loop for inv in inv-vectors
for objtype = (slot-value inv 'bty::obj-type)
for hsh = (slot-value inv 'bty::hash)
;; do (format t "~&~tcount: ~d~%~tobj_type: ~d~%~thash: ~X~%"
;; cnt objtype hsh)
when (or (= objtype 1) (= objtype 2))
collect inv)))
(send-msg remote (prep-msg (make-instance 'msg-getdata
:cnt (length interesting-inventory)
:inv-vectors interesting-inventory)))))))
((string= command "tx")
(format t "~&got a tx! ")
;; (with-slots (bty::version bty::lock-time) (slot-value message 'tx)
;; (format t "version: ~a~%nLockTime: ~a~%" bty::version bty::lock-time))
(format t "saving...")
(let* ((res (btcl-db:save (slot-value message 'tx)))
; from http://rosettacode.org/wiki/Flatten_a_list#Common_Lisp
(flat-res (do* ((result (list res))
(node result))
((null node) (delete nil result))
(cond ((consp (car node))
(when (cdar node) (push (cdar node) (cdr node)))
(setf (car node) (caar node)))
(t (setf node (cdr node)))))))
(if (every #'identity flat-res)
(format t "success!")
(format t "failed!")))
(btcl-web:notify-tx (slot-value message 'tx) msg-hash))
((string= command "block")
(format t "~&got a block!~%")
(btcl-web:notify-blk (slot-value message 'blk)))
(t (format t "~&received message of unknown type: ~s~%" command)))))))
(defun start-peer (remote)
(btcl-db:start)
(as:with-event-loop (:catch-app-errors nil)
(as:signal-handler as:+sigint+
(lambda (sig)
(declare (ignore sig))
(format t "~&got sigint, stopping peer...~%")
(as:exit-event-loop)))
(let ((tcpsock (as:tcp-connect (slot-value remote 'host)
(slot-value remote 'port)
(make-read-cb remote)
:event-cb #'event-cb)))
(setf (slot-value remote 'tcp-socket) tcpsock)
(setf (slot-value remote 'write-stream) (make-instance 'as:async-output-stream :socket tcpsock)))
(send-msg remote (prep-msg (make-instance 'msg-version
:version 70002
:services 1
:timestamp (get-unix-time)
:addr-recv (make-instance 'version-net-addr
:services 1
:ip-addr (build-ip-addr (slot-value remote 'host))
:port (slot-value remote 'port))
:addr-from (make-instance 'version-net-addr
:services 1
:ip-addr (build-ip-addr "0.0.0.0")
:port 0)
:nonce (random (expt 2 64))
:user-agent "/btcl:0.0.2/"
:start-height 0
:relay 1)))
(btcl-web:start-server)))
| 9,619 | Common Lisp | .lisp | 171 | 38.245614 | 115 | 0.4929 | ryanbarry/btcl | 3 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | f3a73514e1703f9e162777752551150d397b464075323c64a86b6fa6e60978dc | 17,720 | [
-1
] |
17,721 | wire.lisp | ryanbarry_btcl/wire.lisp | (in-package :btcl-wire)
;;; connection structure & functions for networking that use it
(defclass peer-connection ()
((host :initarg :host)
(port :initarg :port)
(net :initarg net :initform 'testnet3)
(handshaken :initform #b00) ; low bit means version rec'd, 2nd is verack rec'd
(tcp-socket)
(write-stream)
(read-buffers :initform '())))
;;; msg header and message definition plus macro to create all the types
(bindata:define-binary-class p2p-msg-header ()
((magic u32le)
(command (iso-8859-1-string :length 12))
(len u32le)
(checksum u32le)))
(bindata:define-tagged-binary-class p2p-msg ()
((header p2p-msg-header))
(:dispatch (find-msg-class (slot-value header 'command))))
(defun find-msg-class (name)
(multiple-value-bind (sym status)
(find-symbol (concatenate 'string "MSG-" (string-upcase name)) :btcl-wire)
(declare (ignore status))
sym))
(defgeneric checksum-payload (msg))
(defgeneric prep-msg (msg))
(defgeneric send-msg (remote msg))
(defmacro define-p2p-msg (name slots)
(macut:with-gensyms (objectvar streamvar slotvar bytesvar slottypevar remvar retcksmvar retlenvar)
`(progn
(bindata:define-binary-class ,name (p2p-msg) ,slots)
(defmethod checksum-payload ((,objectvar ,name))
(let ((,streamvar (ironclad:make-octet-output-stream)))
(dolist (,slotvar ',slots)
(let ((,slottypevar (cadr ,slotvar)))
(bindata:write-value (if (typep ,slottypevar 'list) (car ,slottypevar) ,slottypevar) ,streamvar (slot-value ,objectvar (car ,slotvar)))))
(let ((,bytesvar (ironclad:get-output-stream-octets ,streamvar)))
(multiple-value-bind (checksum hash) (dsha256-checksum ,bytesvar)
(values checksum
(length ,bytesvar)
hash)))))
(defmethod prep-msg ((,objectvar ,name))
(multiple-value-bind (,retcksmvar ,retlenvar) (checksum-payload ,objectvar)
(setf (slot-value ,objectvar 'header)
(make-instance 'p2p-msg-header
:command (subseq (string-downcase (symbol-name ',name)) 4)
:checksum ,retcksmvar
:len ,retlenvar))
,objectvar))
(defmethod send-msg (,remvar (,objectvar ,name))
(setf (slot-value (slot-value ,objectvar 'header) 'magic)
(symbol-value (find-symbol
(concatenate 'string
"+"
(symbol-name (slot-value ,remvar
'net))
"-MAGIC+")
:btcl-constants)))
(bindata:write-value ',name (slot-value ,remvar 'write-stream) ,objectvar)))))
;;; now come the message types in the p2p protocol
(define-p2p-msg msg-version
((version u32le)
(services u64le)
(timestamp u64le)
(addr-recv version-net-addr)
(addr-from version-net-addr)
(nonce u64le)
(user-agent varstr)
(start-height u32le)
(relay u8)))
(define-p2p-msg msg-verack ())
(define-p2p-msg msg-inv
((cnt varint)
(inv-vectors (inv-vector-list :count cnt))))
(define-p2p-msg msg-getdata
((cnt varint)
(inv-vectors (inv-vector-list :count cnt))))
(define-p2p-msg msg-tx
((tx tx)))
(define-p2p-msg msg-block
((blk blk)))
(define-p2p-msg msg-addr
((cnt varint)
(addresses (addr-list :count cnt))))
| 3,607 | Common Lisp | .lisp | 84 | 32.857143 | 151 | 0.591505 | ryanbarry/btcl | 3 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 920f1e790b57b73fdef3e7550f8b19583d061915b640b2893d9d7a950b1412e5 | 17,721 | [
-1
] |
17,722 | datatypes.lisp | ryanbarry_btcl/datatypes.lisp | (in-package :btcl-types)
;; binary blobs
(bindata:define-binary-type raw-bytes (size)
(:reader (in)
(let ((buf (make-array size :element-type '(unsigned-byte 8))))
(read-sequence buf in)
buf))
(:writer (out buf)
(write-sequence buf out)))
;; various integer formats
(bindata:define-binary-type unsigned-integer-be (bytes)
(:reader (in)
(loop with value = 0
for low-bit downfrom (* 8 (1- bytes)) to 0 by 8 do
(setf (ldb (byte 8 low-bit) value) (read-byte in))
finally (return value)))
(:writer (out value)
(loop for low-bit downfrom (* 8 (1- bytes)) to 0 by 8
do (write-byte (ldb (byte 8 low-bit) value) out))))
(defun read-unsigned-le (in bytes)
(loop with value = 0
for low-bit upto (* 8 (1- bytes)) from 0 by 8 do
(setf (ldb (byte 8 low-bit) value) (read-byte in))
finally (return value)))
(defun write-unsigned-le (out value bytes)
(loop for low-bit upto (* 8 (1- bytes)) from 0 by 8
do (write-byte (ldb (byte 8 low-bit) value) out)))
(bindata:define-binary-type unsigned-integer-le (bytes)
(:reader (in) (read-unsigned-le in bytes))
(:writer (out value) (write-unsigned-le out value bytes)))
(bindata:define-binary-type signed-integer-le (bytes)
(:reader (in)
(let ((rawnum (read-unsigned-le in bytes))
(bytes-max (expt 2 bytes)))
(if (>= rawnum (/ bytes-max 2))
(- bytes-max rawnum)
rawnum)))
(:writer (out value)
(if (>= value 0)
(write-unsigned-le out value bytes)
(error "Writing negative values isn't implemented yet lulz"))))
;; just one byte, can't technically be little- or big-endian, w/e
(bindata:define-binary-type u8 () (unsigned-integer-le :bytes 1))
;; big-endian types used
(bindata:define-binary-type u16be () (unsigned-integer-be :bytes 2))
(bindata:define-binary-type u32be () (unsigned-integer-be :bytes 4))
(bindata:define-binary-type u64be () (unsigned-integer-be :bytes 8))
;; little-endian
(bindata:define-binary-type u16le () (unsigned-integer-le :bytes 2))
(bindata:define-binary-type u32le () (unsigned-integer-le :bytes 4))
(bindata:define-binary-type u64le () (unsigned-integer-le :bytes 8))
(bindata:define-binary-type s32le () (signed-integer-le :bytes 4))
(bindata:define-binary-type s64le () (signed-integer-le :bytes 8))
;; CompactSize in BitcoinQT
(bindata:define-binary-type varint ()
(:reader (in)
(let ((lowbyte (read-byte in)))
(cond ((< lowbyte #xfd) lowbyte)
((= lowbyte #xfd) (read-unsigned-le in 2))
((= lowbyte #xfe) (read-unsigned-le in 4))
((= lowbyte #xff) (read-unsigned-le in 8)))))
(:writer (out value)
(cond ((< value #xfd) (write-unsigned-le out value 1))
((<= value #xffff) (progn (write-byte #xfd out)
(write-unsigned-le out value 2)))
((<= value #xffffffff) (progn (write-byte #xfe out)
(write-unsigned-le out value 4)))
(t (progn (write-byte #xff out)
(write-unsigned-le out value 8))))))
;; string of defined length, in characters, where char type is defined separately
(bindata:define-binary-type generic-string (length character-type)
(:reader (in)
(let ((string (make-string length))
(end 0))
(loop for i from 0 below length
for char = (bindata:read-value character-type in)
do (setf (char string i) char)
unless (char= char #\null) do (incf end) end
finally (return (subseq string 0 end)))))
(:writer (out string)
(dotimes (i (length string))
(bindata:write-value character-type out (char string i)))
(if (> length (length string))
(dotimes (i (- length (length string)))
(write-byte 0 out)))))
;; character type meant to be used with generic-string
(bindata:define-binary-type iso-8859-1-char ()
(:reader (in)
(let ((code (read-byte in)))
(or (code-char code)
(error "Character code ~d not supported" code))))
(:writer (out char)
(let ((code (char-code char)))
(if (<= 0 code #xff)
(write-byte code out)
(error "Illegal character for iso-8859-1 encoding: character: ~c with code: ~d" char code)))))
;; concrete string type
(bindata:define-binary-type iso-8859-1-string (length)
(generic-string :length length :character-type 'iso-8859-1-char))
;; iso-8859-1 string whose length is defined with a varint
(bindata:define-binary-type varstr ()
(:reader (in)
(let ((len (bindata:read-value 'varint in)))
(bindata:read-value 'iso-8859-1-string in :length len)))
(:writer (out value)
(let ((len (length value)))
(bindata:write-value 'varint out len)
(bindata:write-value 'iso-8859-1-string out value :length len))))
;; structure used to describe node addresses
(bindata:define-binary-class net-addr ()
((timestamp u32le)
(services u64le)
(ip-addr (raw-bytes :size 16))
(port u16be)))
;; special form of net-addr used in the "version" message
(bindata:define-binary-class version-net-addr ()
((services u64le)
(ip-addr (raw-bytes :size 16))
(port u16be)))
;; list of net-addr
(bindata:define-binary-type addr-list (count)
(:reader (in)
(loop repeat count
collect (bindata:read-value 'net-addr in)))
(:writer (out net-addrs)
(dolist (net-addr net-addrs)
(bindata:write-value 'net-addr out net-addr))))
;; identifier for "inventory" (blocks, transactions, etc)
(bindata:define-binary-class inv-vector ()
((obj-type u32le)
(hash (raw-bytes :size 32))))
;; list of inv-vector
(bindata:define-binary-type inv-vector-list (count)
(:reader (in)
(loop repeat count
collect (bindata:read-value 'inv-vector in)))
(:writer (out inv-vectors)
(dolist (inv-vec inv-vectors)
(bindata:write-value 'inv-vector out inv-vec))))
;; pointer to prior transaction's output
(bindata:define-binary-class outpoint ()
((hash (raw-bytes :size 32))
(index u32le)))
;; transaction input
(bindata:define-binary-class tx-in ()
((previous-output outpoint)
(script-len varint)
(script-sig (raw-bytes :size script-len))
(seq u32le)))
;; list of transaction inputs
(bindata:define-binary-type tx-in-list (count)
(:reader (in)
(loop repeat count
collect (bindata:read-value 'tx-in in)))
(:writer (out tx-in-list)
(dolist (tx-in tx-in-list)
(bindata:write-value 'tx-in out tx-in))))
;; transaction output
(bindata:define-binary-class tx-out ()
((value u64le)
(script-len varint)
(script-pk (raw-bytes :size script-len))))
;; list of transaction outputs
(bindata:define-binary-type tx-out-list (count)
(:reader (in)
(loop repeat count
collect (bindata:read-value 'tx-out in)))
(:writer (out tx-out-list)
(dolist (tx-out tx-out-list)
(bindata:write-value 'tx-out out tx-out))))
(bindata:define-binary-class tx ()
((version u32le)
(tx-in-count varint)
(tx-in (tx-in-list :count tx-in-count))
(tx-out-count varint)
(tx-out (tx-out-list :count tx-out-count))
(lock-time u32le)))
;; list of transactions
(bindata:define-binary-type tx-list (count)
(:reader (in)
(loop repeat count
collect (bindata:read-value 'tx in)))
(:writer (out tx-list)
(dolist (txn tx-list)
(bindata:write-value 'tx out txn))))
;; block (named in order to not conflict with CL's block)
(bindata:define-binary-class blk ()
((version u32le)
(hash-prev-block (raw-bytes :size 32))
(hash-merkle-root (raw-bytes :size 32))
(timestamp u32le)
(bits u32le)
(nonce u32le)
(tx-count varint)
(tx-list (tx-list :count tx-count))))
;;; helpers
(defgeneric build-ip-addr (addr)
(:documentation "make a 16-byte address in network byte order"))
;; make it from a dotted-quad format string, e.g. "192.168.1.25"
(defmethod build-ip-addr ((addr string))
(let ((ip-addr (make-array 16 :element-type '(unsigned-byte 8) :initial-element 0)))
(setf (elt ip-addr 10) 255) ;;;; 0xFFFF to represent IPv4
(setf (elt ip-addr 11) 255) ;;;; address within IPv6 address
(loop for char across addr
with pos = 12
with byte = 0
when (char= char #\.)
do (progn
(setf (elt ip-addr pos) byte)
(incf pos)
(setf byte 0))
else do (setf byte (+ (- (char-int char) 48) (* 10 byte)))
finally (setf (elt ip-addr pos) byte))
ip-addr))
;; make it from a dotted-quad-like list, e.g. '(192 168 1 25)
(defmethod build-ip-addr ((addr list))
(let ((ip-addr (make-array 16 :element-type '(unsigned-byte 8) :initial-element 0)))
(setf (elt ip-addr 10) 255)
(setf (elt ip-addr 11) 255)
(loop for byte in addr
for i from 12 upto 16
do (setf (elt ip-addr i) byte))
ip-addr))
| 9,329 | Common Lisp | .lisp | 223 | 34.452915 | 111 | 0.611613 | ryanbarry/btcl | 3 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 8338da4da5279875e9d76c4673c62cc4e68a7962b0479a97aa5b4482864b9610 | 17,722 | [
-1
] |
17,723 | digest.lisp | ryanbarry_btcl/digest.lisp | (in-package :btcl-digest)
(defun dsha256-checksum (data)
(let ((hash (dsha256 data))
(checksum 0))
(setf (ldb (byte 8 0) checksum) (elt hash 0))
(setf (ldb (byte 8 8) checksum) (elt hash 1))
(setf (ldb (byte 8 16) checksum) (elt hash 2))
(setf (ldb (byte 8 24) checksum) (elt hash 3))
(values checksum
hash)))
(defun dsha256 (data)
(let ((digester (ironclad:make-digest :sha256)))
(ironclad:update-digest digester data)
(let ((1st-round (ironclad:produce-digest digester)))
(reinitialize-instance digester)
(ironclad:update-digest digester 1st-round)
(ironclad:produce-digest digester))))
(defgeneric hash (obj))
(defmethod hash ((obj bty:tx))
(let ((octstream (ironclad:make-octet-output-stream)))
(bindata:write-value 'bty:tx octstream obj)
(btcl-digest:dsha256 (ironclad:get-output-stream-octets octstream))))
(defmethod hash ((obj bty:blk))
(let ((octstream (ironclad:make-octet-output-stream)))
(bindata:write-value 'bty:blk octstream obj)
(btcl-digest:dsha256 (ironclad:get-output-stream-octets octstream))))
(defun strhash (obj)
(ironclad:byte-array-to-hex-string (hash obj)))
| 1,182 | Common Lisp | .lisp | 28 | 37.714286 | 73 | 0.690767 | ryanbarry/btcl | 3 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | c4aaa47a723b316456db011ac83ae694a0142e8514ef7bfe9093c47619991d0b | 17,723 | [
-1
] |
17,724 | time.lisp | ryanbarry_btcl/time.lisp | ;;; credit goes to Common Lisp Tips
;;; http://lisptips.com/post/11649360174/the-common-lisp-and-unix-epochs
(in-package :btcl)
(defvar +unix-epoch-difference+ (encode-universal-time 0 0 0 1 1 1970 0))
(defun universal-to-unix-time (universal-time)
(- universal-time +unix-epoch-difference+))
(defun unix-to-universal-time (unix-time)
(+ unix-time +unix-epoch-difference+))
(defun get-unix-time ()
(universal-to-unix-time (get-universal-time)))
| 455 | Common Lisp | .lisp | 10 | 43.5 | 73 | 0.743764 | ryanbarry/btcl | 3 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 1efef656fd4caa38b579e74768811b1e5f69f37eb3a7c1d9cedb611ccb409fd8 | 17,724 | [
-1
] |
17,725 | binary-data.lisp | ryanbarry_btcl/binary-data.lisp | (in-package :com.gigamonkeys.binary-data)
;;; Copyright (c) 2005-2010, Peter Seibel. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions are
;;; met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials provided
;;; with the distribution.
;;; * Neither the name of Gigamonkeys Consulting nor the names of its
;;; contributors may be used to endorse or promote products derived
;;; from this software without specific prior written permission.
;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
;;; LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
;;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
;;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
;;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(defvar *in-progress-objects* nil)
(defconstant +null+ (code-char 0))
(defgeneric read-value (type stream &key)
(:documentation "Read a value of the given type from the stream."))
(defgeneric write-value (type stream value &key)
(:documentation "Write a value as the given type to the stream."))
(defgeneric read-object (object stream)
(:method-combination progn :most-specific-last)
(:documentation "Fill in the slots of object from stream."))
(defgeneric write-object (object stream)
(:method-combination progn :most-specific-last)
(:documentation "Write out the slots of object to the stream."))
(defmethod read-value ((type symbol) stream &key)
(let ((object (make-instance type)))
(read-object object stream)
object))
(defmethod write-value ((type symbol) stream value &key)
(assert (typep value type))
(write-object value stream))
;;; Binary types
(defmacro define-binary-type (name (&rest args) &body spec)
(with-gensyms (type stream value)
`(progn
(defmethod read-value ((,type (eql ',name)) ,stream &key ,@args)
(declare (ignorable ,@args))
,(type-reader-body spec stream))
(defmethod write-value ((,type (eql ',name)) ,stream ,value &key ,@args)
(declare (ignorable ,@args))
,(type-writer-body spec stream value)))))
(defun type-reader-body (spec stream)
(ecase (length spec)
(1 (destructuring-bind (type &rest args) (mklist (first spec))
`(read-value ',type ,stream ,@args)))
(2 (destructuring-bind ((in) &body body) (cdr (assoc :reader spec))
`(let ((,in ,stream)) ,@body)))))
(defun type-writer-body (spec stream value)
(ecase (length spec)
(1 (destructuring-bind (type &rest args) (mklist (first spec))
`(write-value ',type ,stream ,value ,@args)))
(2 (destructuring-bind ((out v) &body body) (cdr (assoc :writer spec))
`(let ((,out ,stream) (,v ,value)) ,@body)))))
;;; Binary classes
(defmacro define-generic-binary-class (name (&rest superclasses) slots read-method)
(with-gensyms (objectvar streamvar)
`(progn
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf (get ',name 'slots) ',(mapcar #'first slots))
(setf (get ',name 'superclasses) ',superclasses))
(defclass ,name ,superclasses
,(mapcar #'slot->defclass-slot slots))
,read-method
(defmethod write-object progn ((,objectvar ,name) ,streamvar)
(declare (ignorable ,streamvar))
(with-slots ,(new-class-all-slots slots superclasses) ,objectvar
,@(mapcar #'(lambda (x) (slot->write-value x streamvar)) slots))))))
(defmacro define-binary-class (name (&rest superclasses) slots)
(with-gensyms (objectvar streamvar)
`(define-generic-binary-class ,name ,superclasses ,slots
(defmethod read-object progn ((,objectvar ,name) ,streamvar)
(declare (ignorable ,streamvar))
(with-slots ,(new-class-all-slots slots superclasses) ,objectvar
,@(mapcar #'(lambda (x) (slot->read-value x streamvar)) slots))))))
(defmacro define-tagged-binary-class (name (&rest superclasses) slots &rest options)
(with-gensyms (typevar objectvar streamvar)
`(define-generic-binary-class ,name ,superclasses ,slots
(defmethod read-value ((,typevar (eql ',name)) ,streamvar &key)
(let* ,(mapcar #'(lambda (x) (slot->binding x streamvar)) slots)
(let ((,objectvar
(make-instance
,@(or (cdr (assoc :dispatch options))
(error "Must supply :disptach form."))
,@(mapcan #'slot->keyword-arg slots))))
(read-object ,objectvar ,streamvar)
,objectvar))))))
(defun as-keyword (sym) (intern (string sym) :keyword))
(defun normalize-slot-spec (spec)
(list (first spec) (mklist (second spec))))
(defun mklist (x) (if (listp x) x (list x)))
(defun slot->defclass-slot (spec)
(let ((name (first spec)))
`(,name :initarg ,(as-keyword name) :accessor ,name)))
(defun slot->read-value (spec stream)
(destructuring-bind (name (type &rest args)) (normalize-slot-spec spec)
`(setf ,name (read-value ',type ,stream ,@args))))
(defun slot->write-value (spec stream)
(destructuring-bind (name (type &rest args)) (normalize-slot-spec spec)
`(write-value ',type ,stream ,name ,@args)))
(defun slot->binding (spec stream)
(destructuring-bind (name (type &rest args)) (normalize-slot-spec spec)
`(,name (read-value ',type ,stream ,@args))))
(defun slot->keyword-arg (spec)
(let ((name (first spec)))
`(,(as-keyword name) ,name)))
;;; Keeping track of inherited slots
(defun direct-slots (name)
(copy-list (get name 'slots)))
(defun inherited-slots (name)
(loop for super in (get name 'superclasses)
nconc (direct-slots super)
nconc (inherited-slots super)))
(defun all-slots (name)
(nconc (direct-slots name) (inherited-slots name)))
(defun new-class-all-slots (slots superclasses)
"Like all slots but works while compiling a new class before slots
and superclasses have been saved."
(nconc (mapcan #'all-slots superclasses) (mapcar #'first slots)))
;;; In progress Object stack
(defun current-binary-object ()
(first *in-progress-objects*))
(defun parent-of-type (type)
(find-if #'(lambda (x) (typep x type)) *in-progress-objects*))
(defmethod read-object :around (object stream)
(declare (ignore stream))
(let ((*in-progress-objects* (cons object *in-progress-objects*)))
(call-next-method)))
(defmethod write-object :around (object stream)
(declare (ignore stream))
(let ((*in-progress-objects* (cons object *in-progress-objects*)))
(call-next-method)))
| 7,321 | Common Lisp | .lisp | 144 | 46.215278 | 84 | 0.696697 | ryanbarry/btcl | 3 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 6b429d70ebdb717780bd8060a43587a9637a40809e1eb8658b2d92f0aa915a67 | 17,725 | [
-1
] |
17,726 | web.lisp | ryanbarry_btcl/web.lisp | ;;; from http://pastebin.com/yW6Xbuv1
(in-package :btcl-web)
(defparameter *channel* nil)
(defun start-server ()
(format t "Starting Web UI server.~%")
(as:tcp-server "0.0.0.0" 3000
(lambda (socket data)
(let ((req (parse (octets-to-string data))))
(format t "~s~%~%" req)
(cond ((string= "/sub" req)
(subscribe! socket))
((string= "/pub" req)
(publish! "Got a message!")
(write/close socket (cat "HTTP/1.1 200 OK" crlf
"Content-Type: text/plain; charset=UTF-8" crlf
"Cache-Control: no-cache, no-store, must-revalidate" crlf
"Content-Length: 10" crlf crlf
"Published!" crlf crlf)))
((string= "/watch" req)
(write/close socket test-page))
(t
(write/close socket (cat "HTTP/1.1 200 OK" crlf
"Content-Type: text/plain; charset=UTF-9" crlf
"Content-Length: 2" crlf crlf
"Ok" crlf crlf))))))
:event-cb (lambda (err)
(format t "listener event: ~a" err))))
(defparameter day-names '("Mon" "Tue" "Wed" "Thu" "Fri" "Sat" "Sun"))
(defparameter month-names '("Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"))
(defun http-date ()
(multiple-value-bind (second minute hour date month year day-of-week dst-p tz)
(get-decoded-time)
(format nil "~a, ~a ~a ~a ~a:~a:~a GMT~@d"
(nth day-of-week day-names) date
(nth month month-names) year hour minute second (- tz))))
(defun subscribe! (sock)
(write/keep-alive
sock (cat "HTTP/1.1 200 OK" crlf
"Date: " (http-date) crlf
"Content-Type: text/event-stream; charset=utf-8" crlf
"Transfer-Encoding: chunked" crlf
"Connection: keep-alive" crlf
"Expires: Thu, 01 Jan 1970 00:00:01 GMT" crlf
"Cache-Control: no-cache, no-store, must-revalidate" crlf crlf))
(push sock *channel*)
(write/keep-alive sock (cat ": comment" crlf crlf)))
(defun publish! (msg)
; (format t "~&sending msg: ~s~%" msg)
(loop for sock in *channel*
do (handler-case
(if (as:socket-closed sock)
(setf *channel* (remove sock *channel*))
(write/keep-alive sock (format nil "data: ~a~c~c~c~c" msg #\Return #\Linefeed #\Return #\Linefeed)))
(error (e)
(declare (ignore e))
(format t "Removing inactive socket...")
(setf *channel* (remove sock *channel*))))))
(defun notify-tx (tx msg-hash)
(let ((uidata '()))
(with-slots (bty::tx-in-count bty::tx-out-count bty::tx-out) tx
(let ((tx-total-value (/ (loop for txo in bty::tx-out
sum (slot-value txo 'bty::value)) 100000000)))
(setf uidata (acons "type" "tx" uidata))
(setf uidata (acons "hash" (format nil "~a" (ironclad:byte-array-to-hex-string (reverse msg-hash))) uidata))
(setf uidata (acons "tx-in-count" bty::tx-in-count uidata))
(setf uidata (acons "tx-out-count" bty::tx-out-count uidata))
(setf uidata (acons "total-sent" (format nil "~8,1,,$" tx-total-value) uidata)))
(publish! (cl-json:encode-json-alist-to-string uidata)))))
(defun notify-blk (blk)
(let ((uidata '()))
(with-slots (bty::tx-count bty::timestamp bty::bits) blk
(setf uidata (acons "type" "block" uidata))
(setf uidata (acons "numtx" bty::tx-count uidata))
(setf uidata (acons "timestamp" bty::timestamp uidata))
(setf uidata (acons "diff" (/ #xFFFF0000000000000000000000000000000000000000000000000000
(* (ldb (byte 24 0) bty::bits) (expt 2 (* 8 (- (ldb (byte 8 24) bty::bits) 3))))) uidata)))
(publish! (cl-json:encode-json-alist-to-string uidata))))
(defun write/keep-alive (sock data)
(unless (as:socket-closed sock)
(as:write-socket-data sock (cat (format nil "~X" (length data)) crlf data crlf))))
(defun write/close (sock data)
(unless (as:socket-closed sock)
(as:write-socket-data
sock data
:write-cb (lambda (sock)
(setf (as:socket-data sock) nil)
(as:close-socket sock)))))
(defmethod parse ((req string))
(let ((lines (split "\\r?\\n" req)))
(second (split " " (first lines)))))
;;;;;;;;;; General purpose utilities
(defun cat (&rest seqs)
(apply #'concatenate 'string seqs))
(defconstant crlf (list #\return #\linefeed))
(defparameter test-page
(let ((content (with-html-output-to-string (str nil :prologue t)
(:html
(:head (:title "Live Network Activity"))
(:body
(:div :id "row" :style "margin-right: -15px; margin-left: -15px; clear:both;"
(:div :id "row" :style "margin-right: -15px; margin-left: -15px;"
(:div :id "txn-container" :style "float: left; width: 33%; padding-left: 15px; padding-right: 15px; position:relative;"
(:h3 :style "width: 100%; display: inline; padding-left: 15px;" "Transactions"))
(:div :id "block-container" :style "width:66%; padding-left: 15px; padding-right: 15px; position:relative;"
(:h3 :style "width: 100%; display: inline; padding-left: 15px;" "Blocks"))))
(:div)
(:div :id "row" :style "margin-right: -15px; margin-left: -15px; clear: both; min-height: 600px; width:95%;"
(:div :id "txn-container" :style "float: left; width: 33%; padding-left: 15px; padding-right: 15px; position:relative;"
(:table :id "txn-list" :style "width: 100%; border: 1px solid black;"
(:thead :style "color: white; background-color: #333;"
(:tr
(:th "Latest TX") (:th "In : Out") (:th "Sent (BTC)")))
(:tbody)))
(:div :id "block-container" :style "width:66%; padding-left: 15px; padding-right: 15px; position:relative;"
(:table :id "blk-list" :style "width: 100%; border: 1px solid black;"
(:thead :style "color: white; background-color: #333;"
(:tr
(:th "Time") (:th "Txns") (:th "Difficulty")))
(:tbody))))
(:div)
(:div :id "console")
(:script :src "//code.jquery.com/jquery-1.11.2.min.js")
(:script
:type "text/javascript"
(str (ps (defvar src (new (-event-source "/sub")))
(defun p (msg)
(let ((elem (chain document (get-element-by-id "console"))))
(setf (@ elem inner-h-t-m-l)
(+ (@ elem inner-h-t-m-l) "<p>" msg "</p>"))))
(defun addtx (txdata)
(let ((row (+ "<tr><td> ..." (chain (@ txdata hash) (substring 56))
"</td><td style=\"text-align:center;\">" (@ txdata "tx-in-count")
" : " (@ txdata "tx-out-count")
"</td><td style=\"text-align:right;\">" (@ txdata "total-sent") "</td></tr>")))
(chain ($ row) (prepend-to "#txn-list"))))
(defun addblock (blkdata)
(let ((row (+ "<tr><td>" (new (-date (* 1000 (@ blkdata timestamp))))
"</td><td>" (@ blkdata numtx)
"</td><td>" (@ blkdata diff) "</td></tr>")))
(chain ($ row) (prepend-to "#blk-list"))))
(setf (@ src onerror)
(lambda (e)
(p "error:")
(p (chain -j-s-o-n (stringify e))))
(@ src onopen)
(lambda (e) (p "Connected..."))
(@ src onmessage)
(lambda (e)
(let ((data (chain -j-s-o-n (parse (@ e data)))))
(if (= (@ data type) "tx")
(addtx data)
(addblock data)))))))))))))
(cat "HTTP/1.1 200 OK" crlf
"Content-Type: text/html; charset=UTF-8" crlf
"Cache-Control: no-cache, no-store, must-revalidate" crlf
"Content-Length: " (write-to-string (length content)) crlf crlf
content crlf crlf)))
| 9,659 | Common Lisp | .lisp | 157 | 40.515924 | 152 | 0.452062 | ryanbarry/btcl | 3 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | e2768b1a1d36f7faa1555c4a00b08ba4b991343782fc90bdbadce760e8a445cf | 17,726 | [
-1
] |
17,727 | constants.lisp | ryanbarry_btcl/constants.lisp | (in-package :btcl-constants)
(defconstant +P2P-MSG-HEADER-LEN+ 24)
(defconstant +TESTNET3-MAGIC+ #x0709110b) ; network byte order
(defconstant +MAINNET-MAGIC+ #xfeb4bef9) ; network byte order
(defparameter +MAINNET-GENESIS-BLOCK+
#(#x01 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00
#x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00
#x00 #x00 #x00 #x00 #x3B #xA3 #xED #xFD #x7A #x7B #x12 #xB2 #x7A #xC7 #x2C #x3E
#x67 #x76 #x8F #x61 #x7F #xC8 #x1B #xC3 #x88 #x8A #x51 #x32 #x3A #x9F #xB8 #xAA
#x4B #x1E #x5E #x4A #x29 #xAB #x5F #x49 #xFF #xFF #x00 #x1D #x1D #xAC #x2B #x7C
#x01 #x01 #x00 #x00 #x00 #x01 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00
#x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00
#x00 #x00 #x00 #x00 #x00 #x00 #xFF #xFF #xFF #xFF #x4D #x04 #xFF #xFF #x00 #x1D
#x01 #x04 #x45 #x54 #x68 #x65 #x20 #x54 #x69 #x6D #x65 #x73 #x20 #x30 #x33 #x2F
#x4A #x61 #x6E #x2F #x32 #x30 #x30 #x39 #x20 #x43 #x68 #x61 #x6E #x63 #x65 #x6C
#x6C #x6F #x72 #x20 #x6F #x6E #x20 #x62 #x72 #x69 #x6E #x6B #x20 #x6F #x66 #x20
#x73 #x65 #x63 #x6F #x6E #x64 #x20 #x62 #x61 #x69 #x6C #x6F #x75 #x74 #x20 #x66
#x6F #x72 #x20 #x62 #x61 #x6E #x6B #x73 #xFF #xFF #xFF #xFF #x01 #x00 #xF2 #x05
#x2A #x01 #x00 #x00 #x00 #x43 #x41 #x04 #x67 #x8A #xFD #xB0 #xFE #x55 #x48 #x27
#x19 #x67 #xF1 #xA6 #x71 #x30 #xB7 #x10 #x5C #xD6 #xA8 #x28 #xE0 #x39 #x09 #xA6
#x79 #x62 #xE0 #xEA #x1F #x61 #xDE #xB6 #x49 #xF6 #xBC #x3F #x4C #xEF #x38 #xC4
#xF3 #x55 #x04 #xE5 #x1E #xC1 #x12 #xDE #x5C #x38 #x4D #xF7 #xBA #x0B #x8D #x57
#x8A #x4C #x70 #x2B #x6B #xF1 #x1D #x5F #xAC #x00 #x00 #x00 #x00))
| 1,753 | Common Lisp | .lisp | 23 | 71.913043 | 84 | 0.599188 | ryanbarry/btcl | 3 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 3bbdb22dc8a004b721f4157fe21311cd8127dba7ef3bd9998ef466e34feb2dd6 | 17,727 | [
-1
] |
17,728 | portable-pathnames.lisp | ryanbarry_btcl/portable-pathnames.lisp | (in-package :com.gigamonkeys.portable-pathnames)
;;; a portable pathname library
;;;
;;; helps smooth over some differences between common lisp implementations
;;;
;;;
;;; Copyright (c) 2005-2010, Peter Seibel. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions are
;;; met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials provided
;;; with the distribution.
;;; * Neither the name of Gigamonkeys Consulting nor the names of its
;;; contributors may be used to endorse or promote products derived
;;; from this software without specific prior written permission.
;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
;;; LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
;;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
;;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
;;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;;
(defun component-present-p (value)
(and value (not (eql value :unspecific))))
;; is the given pathname a directory?
;; returns the pathname if true, nil if false
(defun directory-pathname-p (p)
(and
(not (component-present-p (pathname-name p)))
(not (component-present-p (pathname-type p)))
p))
;; converts given pathname to directory form
(defun pathname-as-directory (name)
(let ((pathname (pathname name)))
(when (wild-pathname-p pathname)
(error "Can't reliably convert wild pathnames."))
(if (not (directory-pathname-p name))
(make-pathname
:directory (append (or (pathname-directory pathname) (list :relative))
(list (file-namestring pathname)))
:name nil
:type nil
:defaults pathname)
pathname)))
;; converts given pathname to file form
(defun pathname-as-file (name)
(let ((pathname (pathname name)))
(when (wild-pathname-p pathname)
(error "Can't reliably convert wild pathnames."))
(if (directory-pathname-p name)
(let* ((directory (pathname-directory pathname))
(name-and-type (pathname (first (last directory)))))
(make-pathname
:directory (butlast directory)
:name (pathname-name name-and-type)
:type (pathname-type name-and-type)
:defaults pathname))
pathname)))
(defun directory-wildcard (dirname)
(make-pathname
:name :wild
:type #-clisp :wild #+clisp nil ;clisp needs this to show files w/o extension
:defaults (pathname-as-directory dirname)))
;; clisp helper to product directory wildcard with nil pathname-type
;; required since clisp won't match extensionless files when wildcard has non-nil type
#+clisp
(defun clisp-subdirectories-wildcard (wildcard)
(make-pathname
:directory (append (pathname-directory wildcard) (list :wild))
:name nil
:type nil
:defaults wildcard))
;; lists all files and subdirectories in given directory pathname
;; subdirectories are listed in directory form for easy differentiation from files
(defun list-directory (dirname)
(when (wild-pathname-p dirname)
(error "Can only list concrete directory names."))
(let ((wildcard (directory-wildcard dirname)))
#+ (or sbcl cmu lispworks)
(directory wildcard)
#+openmcl
(directory wildcard :directories t)
#+allegro
(directory wildcard :directories-are-files nil)
#+clisp
(nconc
(directory wildcard)
(directory (clisp-subdirectories-wildcard wildcard)))
#-(or sbcl cmu lispworks openmcl allegro clisp)
(error "list-subdirectory not implemented")))
;; simple test for whether file or directory represented by pathname exists
;; returns the pathname if true, nil if false
;; always returns pathnames representing directories in directory form
(defun file-exists-p (pathname)
#+ (or sbcl lispworks openmcl)
(probe-file pathname)
#+ (or allegro cmu)
(or (probe-file (pathname-as-directory pathname))
(probe-file pathname))
#+clisp
(or (ignore-errors
(probe-file (pathname-as-file pathname)))
(ignore-errors
(let ((directory-form (pathname-as-directory pathname)))
(when (ext:probe-directory directory-form)
directory-form))))
#- (or sbcl lispworks openmcl allegro cmu clisp)
(error "file-exists-p not implemented"))
;; recursively calls given function on pathnames of all files under given directory
;; two keyword args:
;; :directories - when true, will call function on pathnames of directories also
;; :test - specifies fun invoked prior to main fun, skips main fun if ret false
(defun walk-directory (dirname fn &key directories (test (constantly t)))
(labels
((walk (name)
(cond
((directory-pathname-p name)
(when (and directories (funcall test name))
(funcall fn name))
(dolist (x (list-directory name)) (walk x)))
((funcall test name) (funcall fn name)))))
(walk (pathname-as-directory dirname))))
| 5,616 | Common Lisp | .lisp | 131 | 39.78626 | 86 | 0.742313 | ryanbarry/btcl | 3 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | ba8f5b648de7a7e06a6e0b1ef9a5b97f455f75165b30e94fa3959134f37437cb | 17,728 | [
-1
] |
17,729 | block.lisp | ryanbarry_btcl/block.lisp | (in-package :btcl-core)
(defclass blok-header ()
((version :accessor version)
(hash-prev-block :accessor hash-prev-block)
(hash-merkle-root :accessor hash-merkle-root)
(timestamp :accessor timestamp)
(bits :accessor bits)
(nonce :accessor nonce)
(hash :accessor hash)))
(defclass blok ()
((header :accessor header)
(tx-list :accessor tx-list)))
| 372 | Common Lisp | .lisp | 12 | 27.75 | 48 | 0.712291 | ryanbarry/btcl | 3 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 591e72b78be200a6c6a240d2196093d43fd8705cb72f28da8f43e9fc1b911a07 | 17,729 | [
-1
] |
17,730 | btcl.asd | ryanbarry_btcl/btcl.asd | (asdf:defsystem #:btcl
:serial t
:depends-on (#:cl-async
#:ironclad
#:babel
#:cl-who
#:cl-ppcre
#:parenscript
#:cl-json
#:postmodern)
:components ((:file "package")
(:file "macro-utilities")
(:file "portable-pathnames")
(:file "binary-data")
(:file "time")
(:file "web")
(:file "constants")
(:file "datatypes")
(:file "digest")
(:file "db")
(:file "wire")
(:file "peer")
(:file "block")
(:file "rules")))
| 711 | Common Lisp | .asd | 24 | 15.875 | 43 | 0.37409 | ryanbarry/btcl | 3 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | c657f3dbb1f4df599c9e9777a46ed7277fec5fa85287594d60f17b8d52704108 | 17,730 | [
-1
] |
17,762 | finite-state-machine-test.lisp | keithj_deoxybyte-utilities/test/finite-state-machine-test.lisp | ;;;
;;; Copyright (c) 2008-2012 Keith James. All rights reserved.
;;;
;;; This file is part of deoxybyte-utilities.
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation, either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;
(in-package :uk.co.deoxybyte-utilities-test)
(defsmfun char-triples/1 (str &key (start 0))
((i start)
(len (length str))
(triples ())
(triple ()))
((c0 ((< i len) c1
(setf triple (list (char str i)))
(incf i))
(t nil
(reverse triples)))
(c1 ((< i len) c2
(push (char str i) triple)
(incf i))
(t nil
(reverse triples)))
(c2 ((< i len) c0
(push (char str i) triple)
(push (reverse triple) triples)
(incf i))
(t nil
(reverse triples)))))
(addtest (deoxybyte-utilities-tests) defsmfun/1
(ensure (equalp '((#\a #\a #\a) (#\b #\b #\b) (#\c #\c #\c))
(char-triples/1 "aaabbbccc")))
(ensure (equalp '((#\a #\a #\b) (#\b #\b #\c))
(char-triples/1 "aaabbbccc" :start 1)))
(ensure (equalp '((#\c #\c #\c))
(char-triples/1 "aaabbbccc" :start 6)))
(ensure-null (char-triples/1 "aaabbbccc" :start 7)))
(defun char-triples/2 (str)
(let ((i 0)
(len (length str))
(triples ())
(triple ()))
(defsm ((c0 ((< i len) c1
(setf triple (list (char str i)))
(incf i))
(t nil
(reverse triples)))
(c1 ((< i len) c2
(push (char str i) triple)
(incf i))
(t nil
(reverse triples)))
(c2 ((< i len) c0
(push (char str i) triple)
(push (reverse triple) triples)
(incf i))
(t nil
(reverse triples)))))))
(addtest (deoxybyte-utilities-tests) defsm/1
(ensure (equalp '((#\a #\a #\a) (#\b #\b #\b) (#\c #\c #\c))
(char-triples/2 "aaabbbccc"))))
| 2,642 | Common Lisp | .lisp | 72 | 28.027778 | 73 | 0.526911 | keithj/deoxybyte-utilities | 3 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 44c081b6e815aca93dda52a6034090d8eac0aba093fe2709834bf25a9f4d89be | 17,762 | [
-1
] |
17,763 | package.lisp | keithj_deoxybyte-utilities/test/package.lisp | ;;;
;;; Copyright (c) 2007-2012 Keith James. All rights reserved.
;;;
;;; This file is part of deoxybyte-utilities.
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation, either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;
(defpackage :uk.co.deoxybyte-utilities-test
(:use #:common-lisp #:deoxybyte-utilities #:lift)
(:documentation "Deoxybyte utilities tests.")
(:export #:deoxybyte-utilities-tests))
| 968 | Common Lisp | .lisp | 22 | 42.681818 | 73 | 0.741799 | keithj/deoxybyte-utilities | 3 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 9270878b3e83124ae2fb8bf2af80af77cacee6175c273f4dac5923c670d8714d | 17,763 | [
-1
] |
17,764 | string-utilities-test.lisp | keithj_deoxybyte-utilities/test/string-utilities-test.lisp | ;;;
;;; Copyright (c) 2008-2012 Keith James. All rights reserved.
;;;
;;; This file is part of deoxybyte-utilities.
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation, either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;
(in-package :uk.co.deoxybyte-utilities-test)
(addtest (deoxybyte-utilities-tests) control-char-p/1
(ensure (loop
for i from 0 to 31
always (control-char-p (code-char i))))
(ensure (control-char-p (code-char 127))))
(addtest (deoxybyte-utilities-tests) control-char-p/2
(ensure (loop
for c across "abcdefghijklmnopqrstuvwxyz"
never (control-char-p c))))
(addtest (deoxybyte-utilities-tests) whitespace-char-p/1
(ensure (loop
for c in '(#\Space #\Tab #\Return
#\Linefeed #\FormFeed)
always (whitespace-char-p c))))
(addtest (deoxybyte-utilities-tests) whitespace-char-p/2
(ensure (loop
for c across "abcdefghijklmnopqrstuvwxyz"
never (whitespace-char-p c))))
(addtest (deoxybyte-utilities-tests) whitespace-string-p/1
(ensure (whitespace-string-p
(make-array 5 :element-type 'base-char
:initial-contents '(#\Space #\Tab #\Return
#\Linefeed #\FormFeed)))))
(addtest (deoxybyte-utilities-tests) whitespace-string-p/2
(ensure (not (whitespace-string-p
(make-array 6 :element-type 'base-char
:initial-contents
'(#\Space #\Tab #\Return
#\Linefeed #\FormFeed #\a))))))
(addtest (deoxybyte-utilities-tests) content-string-p/1
(ensure (content-string-p
(make-array 6 :element-type 'base-char
:initial-contents '(#\Space #\Tab #\Return
#\Linefeed #\FormFeed #\a)))))
(addtest (deoxybyte-utilities-tests) content-string-p/2
(ensure (not (content-string-p
(make-array 5 :element-type 'base-char
:initial-contents
'(#\Space #\Tab #\Return
#\Linefeed #\FormFeed))))))
(addtest (deoxybyte-utilities-tests) empty-string-p/1
(ensure (empty-string-p
(make-array 5 :element-type 'base-char
:initial-contents '(#\Space #\Tab #\Return
#\Linefeed #\FormFeed)))))
(addtest (deoxybyte-utilities-tests) empty-string-p/2
(ensure (empty-string-p "")))
(addtest (deoxybyte-utilities-tests) empty-string-p/3
(ensure (not (empty-string-p
(make-array 6 :element-type 'base-char
:initial-contents
'(#\Space #\Tab #\Return
#\Linefeed #\FormFeed #\a))))))
(addtest (deoxybyte-utilities-tests) contains-char-p/1
(ensure (contains-char-p "abc" #\a))
(ensure (contains-char-p "abc" #\b))
(ensure (contains-char-p "abc" #\c))
(ensure (not (contains-char-p "abc" #\d))))
(addtest (deoxybyte-utilities-tests) has-char-at-p/1
(ensure (has-char-at-p "abc" #\a 0))
(ensure (has-char-at-p "abc" #\b 1))
(ensure (has-char-at-p "abc" #\c 2))
(ensure (not (has-char-at-p "abc" #\a 1)))
(ensure (not (has-char-at-p "abc" #\c 0))))
(addtest (deoxybyte-utilities-tests) starts-with-char-p/1
(ensure (starts-with-char-p "abc" #\a))
(ensure (not (starts-with-char-p "abc" #\b))))
(addtest (deoxybyte-utilities-tests) every-char-p/1
(let ((fn #'(lambda (c) (char= #\a c))))
(ensure (every-char-p "aaa" fn 0 1 2))
(ensure (every-char-p "aab" fn 0 1))
(ensure (every-char-p "baa" fn 1 2))))
(addtest (deoxybyte-utilities-tests) concat-strings/1
(ensure (string=
"aaabbbccc"
(concat-strings (make-array 4 :initial-contents
'("aaa" "bbb" "ccc" ""))))))
| 4,494 | Common Lisp | .lisp | 96 | 37.302083 | 73 | 0.593015 | keithj/deoxybyte-utilities | 3 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 9120a878f3480ea21576dd69c9345e529fc58c3f7bcb93f9f0d55c9034a8302d | 17,764 | [
-1
] |
17,765 | set-utilities-test.lisp | keithj_deoxybyte-utilities/test/set-utilities-test.lisp | ;;;
;;; Copyright (c) 2010-2012 Keith James. All rights reserved.
;;;
;;; This file is part of deoxybyte-utilities.
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation, either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;
(in-package :uk.co.deoxybyte-utilities-test)
(defun make-random-list (max-length elt-fn &rest elt-args)
(loop
repeat (random max-length)
collect (apply elt-fn elt-args)))
(defun make-list-of-lists (max-length)
(make-random-list max-length (lambda ()
(list (random 1000)))))
(defun test-numlist (fn1 fn2)
(loop
repeat 100
always (let ((x (make-random-list 10000 #'random 1000))
(y (make-random-list 10000 #'random 1000)))
(equal (funcall fn1 x y) (funcall fn2 x y)))))
(defun test-list-of-lists (fn1 fn2)
(loop
repeat 100
always (let ((x (make-random-list 1000 #'make-list-of-lists 100))
(y (make-random-list 1000 #'make-list-of-lists 100)))
(equal (funcall fn1 x y :key #'car)
(funcall fn2 x y :key #'car)))))
(addtest (deoxybyte-utilities-tests) linear-union/1
(test-numlist #'union #'linear-union))
(addtest (deoxybyte-utilities-tests) linear-union/2
(test-list-of-lists #'union #'linear-union))
(addtest (deoxybyte-utilities-tests) linear-intersection/1
(test-numlist #'intersection #'linear-intersection))
(addtest (deoxybyte-utilities-tests) linear-intersection/2
(test-list-of-lists #'intersection #'linear-intersection))
(addtest (deoxybyte-utilities-tests) linear-set-difference/1
(test-numlist #'set-difference #'linear-set-difference))
(addtest (deoxybyte-utilities-tests) linear-set-difference/2
(test-list-of-lists #'set-difference #'linear-set-difference))
(addtest (deoxybyte-utilities-tests) linear-set-exclusive-or/1
(test-numlist #'set-exclusive-or #'linear-set-exclusive-or))
(addtest (deoxybyte-utilities-tests) linear-set-exclusive-or/2
(test-list-of-lists #'set-exclusive-or #'linear-set-exclusive-or))
(addtest (deoxybyte-utilities-tests) linear-subsetp/1
(test-numlist #'subsetp #'linear-subsetp))
(addtest (deoxybyte-utilities-tests) linear-subsetp/2
(test-list-of-lists #'subsetp #'linear-subsetp))
(addtest (deoxybyte-utilities-tests) linear-set-equal/1
(test-numlist (lambda (x y &rest args)
(declare (ignore args))
(equal x y)) #'linear-set-equal))
(addtest (deoxybyte-utilities-tests) linear-set-equal/2
(test-list-of-lists (lambda (x y &rest args)
(declare (ignore args))
(equal x y)) #'linear-set-equal))
(addtest (deoxybyte-utilities-tests) linear-set-equal/3
(ensure (not (linear-set-equal '(1 2 3) '(2 3)))))
| 3,329 | Common Lisp | .lisp | 69 | 42.84058 | 73 | 0.690255 | keithj/deoxybyte-utilities | 3 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 0a1930a138ceb2215b038d41431cdec4c9a0eb86f234e212a9433504ab0d5be6 | 17,765 | [
-1
] |
17,766 | queue-test.lisp | keithj_deoxybyte-utilities/test/queue-test.lisp | ;;;
;;; Copyright (c) 2009-2012 Keith James. All rights reserved.
;;;
;;; This file is part of deoxybyte-utilities.
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation, either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;
(in-package :uk.co.deoxybyte-utilities-test)
(addtest (deoxybyte-utilities-tests) queue/1
(ensure (queue-p (make-queue))))
(addtest (deoxybyte-utilities-tests) queue-enqueue/1
(let ((queue (make-queue))
(items (iota 10)))
(ensure-same queue (queue-enqueue (first items) queue))
(dolist (item (rest items))
(queue-enqueue item queue))
(ensure (equal items (queue-head queue)))
(ensure (equal (car (last items)) (queue-last queue)))))
(addtest (deoxybyte-utilities-tests) queue-dequeue/1
(let ((queue (make-queue))
(items (iota 10)))
(dolist (item items)
(queue-enqueue item queue))
(dolist (item items)
(multiple-value-bind (x presentp)
(queue-dequeue queue)
(ensure (= item x))
(ensure presentp)))
(ensure (queue-empty-p queue))
(multiple-value-bind (x presentp)
(queue-dequeue queue)
(ensure-null x)
(ensure (not presentp)))))
(addtest (deoxybyte-utilities-tests) queue-dequeue-if/1
(let ((queue (make-queue))
(items (iota 10)))
(dolist (item items)
(queue-enqueue item queue))
(multiple-value-bind (q x)
(queue-dequeue-if #'oddp queue)
(ensure (equal '(0 2 4 6 8) (queue-head q)))
(ensure-same queue q)
(ensure (equal '(1 3 5 7 9) x)))))
(addtest (deoxybyte-utilities-tests) queue-dequeue-if/2
(let ((queue (make-queue))
(items (iota 10)))
(dolist (item items)
(queue-enqueue (list item) queue))
(multiple-value-bind (q x)
(queue-dequeue-if #'oddp queue :key #'first)
(ensure (equalp '((0) (2) (4) (6) (8)) (queue-head q)))
(ensure-same queue q)
(ensure (equalp '((1) (3) (5) (7) (9)) x)))))
(addtest (deoxybyte-utilities-tests) queue-clear/1
(let ((queue (make-queue))
(items (iota 10)))
(dolist (item items)
(queue-enqueue item queue))
(multiple-value-bind (q x)
(queue-clear queue)
(ensure (queue-empty-p q))
(ensure-same queue q)
(ensure (equal items x)))))
| 2,823 | Common Lisp | .lisp | 74 | 33.405405 | 73 | 0.651095 | keithj/deoxybyte-utilities | 3 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | bd83a538bbed15dba092ae7f01a9ca176a9a230cfd1fc8eaaafdc400963f96b8 | 17,766 | [
-1
] |
17,767 | numeric-utilities-test.lisp | keithj_deoxybyte-utilities/test/numeric-utilities-test.lisp | ;;;
;;; Copyright (c) 2008-2012 Keith James. All rights reserved.
;;;
;;; This file is part of deoxybyte-utilities.
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation, either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;
(in-package :uk.co.deoxybyte-utilities-test)
(addtest (deoxybyte-utilities-tests) iota/1
(ensure (equal '(0 0 0 0 0) (iota 5 0 0)))
(ensure (equal '(0 1 2 3 4) (iota 5)))
(ensure (equal '(10 11 12 13 14) (iota 5 10)))
(ensure (equal '(0 2 4 6 8) (iota 5 0 2)))
(ensure (equal '(0 -1 -2 -3 -4) (iota 5 0 -1)))
(ensure (equal '(0 -2 -4 -6 -8) (iota 5 0 -2)))
(ensure (equal '(1 1 1 1 1) (iota 5 1 0))))
(addtest (deoxybyte-utilities-tests) number-generator/1
(let ((gen (number-generator)))
(ensure (equal '(0 1 2 3 4) (loop
repeat 5
collect (next gen)))))
(let ((gen (number-generator 10)))
(ensure (equal '(10 11 12 13 14) (loop
repeat 5
collect (next gen)))))
(let ((gen (number-generator 0 2)))
(ensure (equal '(0 2 4 6 8) (loop
repeat 5
collect (next gen))))))
(addtest (deoxybyte-utilities-tests) numeric-selector/1
;; 5 bins, defaulting to integer range
(with-numeric-selector (select-bin 5 :out-of-bounds :ignore)
(let ((bins (make-array 5 :initial-element 0)))
(loop
for i from 0 below 10 ; 10 rounds
do (loop
for j from -3 upto 7 ; 5 in each bin, 3 outside low & high
do (let ((b (select-bin j)))
(when b
(incf (aref bins b))))))
(ensure (equalp #(10 10 10 10 10) bins)))))
(addtest (deoxybyte-utilities-tests) numeric-selector/2
(with-numeric-selector (select-bin 5 :out-of-bounds :include)
(let ((bins (make-array 5 :initial-element 0)))
(loop
for i from 0 below 10 ; 10 rounds
do (loop
for j from -3 to 7 ; 5 in each bin, 3 outside low & high
do (let ((b (select-bin j)))
(when b
(incf (aref bins b))))))
(ensure (equalp #(40 10 10 10 40) bins))))
(ensure-condition invalid-argument-error
(with-numeric-selector (select-bin 5 :out-of-bounds :error)
(select-bin -1)))
(ensure-condition invalid-argument-error
(with-numeric-selector (select-bin 5 :out-of-bounds :error)
(select-bin 5))))
(addtest (deoxybyte-utilities-tests) categorical-binner/1
(let ((fn (define-categorical-binner x
(and (oddp x) (plusp x))
(and (oddp x) (minusp x))
(and (evenp x) (plusp x))
(and (evenp x) (minusp x))))
(bins nil)
(out nil))
(dolist (i '(-5 -4 -3 -2 -1 0 1 2 3 4 5))
(multiple-value-setq (bins out)
(funcall fn i)))
(ensure (equalp #(3 3 2 2) bins))
(ensure (= 1 out))))
| 3,552 | Common Lisp | .lisp | 82 | 34.97561 | 73 | 0.575635 | keithj/deoxybyte-utilities | 3 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 3e60970da4d7e5b19a034f06a956711b03ea4b32b0d8fc6e797b1ab6c7aafe42 | 17,767 | [
-1
] |
17,768 | vector-utilities-test.lisp | keithj_deoxybyte-utilities/test/vector-utilities-test.lisp | ;;;
;;; Copyright (c) 2008-2012 Keith James. All rights reserved.
;;;
;;; This file is part of deoxybyte-utilities.
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation, either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;
(in-package :uk.co.deoxybyte-utilities-test)
(let ((vec1 (make-array 10 :initial-contents '(a b c d e a g h i j)))
(vec2 "abcdeaghij"))
(addtest (deoxybyte-utilities-tests) vector-positions/1
(ensure (equal '(0 5) (vector-positions 'a vec1))))
(addtest (deoxybyte-utilities-tests) vector-positions/2
(ensure (equal '(5) (vector-positions 'a vec1 :start 1))))
(addtest (deoxybyte-utilities-tests) vector-positions/3
(ensure (equal '(0) (vector-positions 'a vec1 :end 2))))
(addtest (deoxybyte-utilities-tests) vector-positions/4
(ensure-null (vector-positions 'a vec1 :start 1 :end 4)))
(addtest (deoxybyte-utilities-tests) vector-positions/5
(ensure (equal '(0 5) (vector-positions #\a vec2 :test #'char=)))))
(let ((vec1 (make-array 10 :initial-contents '(a b c d e a g h i j)))
(vec2 "abcdeaghij"))
(addtest (deoxybyte-utilities-tests) vector-split-indices/1
(multiple-value-bind (starts ends)
(vector-split-indices 'a vec1)
(ensure (equal '(0 1 6) starts))
(ensure (equal '(0 5 10) ends))))
(addtest (deoxybyte-utilities-tests) vector-split-indices/2
(multiple-value-bind (starts ends)
(vector-split-indices 'a vec1 :start 1)
(ensure (equal '(1 6) starts))
(ensure (equal '(5 10) ends))))
(addtest (deoxybyte-utilities-tests) vector-split-indices/3
(multiple-value-bind (starts ends)
(vector-split-indices 'a vec1 :end 2)
(ensure (equal '(0 1) starts))
(ensure (equal '(0 2) ends))))
(addtest (deoxybyte-utilities-tests) vector-split-indices/4
(multiple-value-bind (starts ends)
(vector-split-indices 'a vec1 :start 1 :end 4)
(ensure-null starts)
(ensure-null ends)))
(addtest (deoxybyte-utilities-tests) vector-split-indices/5
(multiple-value-bind (starts ends)
(vector-split-indices #\a vec2 :test #'char=)
(ensure (equal '(0 1 6) starts))
(ensure (equal '(0 5 10) ends)))))
(let ((vec1 (make-array 10 :initial-contents '(a b c d e a g h i j)))
(vec2 "abcdeaghij"))
(addtest (deoxybyte-utilities-tests) vector-split/1
(ensure (equalp '(#() #(b c d e) #(g h i j))
(vector-split 'a vec1))))
(addtest (deoxybyte-utilities-tests) vector-split/2
(ensure (equalp '(#(b c d e) #(g h i j))
(vector-split 'a vec1 :remove-empty-subseqs t))))
(addtest (deoxybyte-utilities-tests) vector-split/3
(ensure (equalp '(#(b c d e) #(g h i j))
(vector-split 'a vec1 :start 1))))
(addtest (deoxybyte-utilities-tests) vector-split/4
(ensure (equalp '(#() #(b))
(vector-split 'a vec1 :end 2))))
(addtest (deoxybyte-utilities-tests) vector-split/5
(ensure (equalp '(#(b c d))
(vector-split 'a vec1 :start 1 :end 4))))
(addtest (deoxybyte-utilities-tests) vector-split/6
(ensure (equal '("" "bcde" "ghij")
(vector-split #\a vec2 :test #'char=)))))
(addtest (deoxybyte-utilities-tests) vector-errors/1
(let ((vec1 (make-array 10 :initial-contents '(a b c d e a g h i j))))
(dolist (fn (list #'vector-positions #'vector-split
#'vector-split-indices))
(ensure-error
(funcall fn 'a vec1 :start -1))
(ensure-error
(funcall fn 'a vec1 :end -1))
(ensure-condition invalid-argument-error
(funcall fn 'a vec1 :end 99))
(ensure-condition invalid-argument-error
(funcall fn 'a vec1 :start 1 :end 0)))))
| 4,322 | Common Lisp | .lisp | 90 | 41.833333 | 73 | 0.643247 | keithj/deoxybyte-utilities | 3 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 02833ecb70e44af7e2b962132b301709627827f6a6825bb2c6702d01868d3422 | 17,768 | [
-1
] |
17,769 | cons-utilities-test.lisp | keithj_deoxybyte-utilities/test/cons-utilities-test.lisp | ;;;
;;; Copyright (c) 2008-2012 Keith James. All rights reserved.
;;;
;;; This file is part of deoxybyte-utilities.
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation, either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;
(in-package :uk.co.deoxybyte-utilities-test)
(addtest (deoxybyte-utilities-tests) assocdr/1
(let ((keys '(a b c))
(vals '(1 2 3)))
(mapc #'(lambda (key val)
(ensure (= val (assocdr key (pairlis keys vals)))))
keys vals)))
(addtest (deoxybyte-utilities-tests) assocdr/2
(let ((keys '("a" "b" "c"))
(vals '(1 2 3)))
(mapc #'(lambda (key val)
(ensure (= val (assocdr key (pairlis keys vals)
:test #'string=))))
keys vals)))
(addtest (deoxybyte-utilities-tests) rassocar/1
(let ((keys '(a b c))
(vals '(1 2 3)))
(mapc #'(lambda (key val)
(ensure (eql key (rassocar val (pairlis keys vals)))))
keys vals)))
(addtest (deoxybyte-utilities-tests) rassocar/2
(let ((keys '(a b c))
(vals '("1" "2" "3")))
(mapc #'(lambda (key val)
(ensure (eql key (rassocar val (pairlis keys vals)
:test #'string=))))
keys vals)))
(addtest (deoxybyte-utilities-tests) rplassoc/1
(let ((keys '(a b c))
(vals '(1 2 3)))
(let ((alist (pairlis keys vals)))
(rplassoc 'a alist 99)
(ensure (= 99 (assocdr 'a alist))))))
(addtest (deoxybyte-utilities-tests) rplassoc/2
(let ((keys '("a" "b" "c"))
(vals '(1 2 3)))
(let ((alist (pairlis keys vals)))
(rplassoc "a" alist 99
:test #'string=)
(ensure (= 99 (assocdr "a" alist
:test #'string=))))))
(addtest (deoxybyte-utilities-tests) assocpush/1
(let ((keys '(a b))
(vals '((1 2) (3 4))))
(let ((alist (pairlis keys vals)))
(assocpush 'a alist 99)
(ensure (equal '(99 1 2) (assocdr 'a alist))))))
(addtest (deoxybyte-utilities-tests) assocpush/2
(let ((keys '("a" "b"))
(vals '((1 2) (3 4))))
(let ((alist (pairlis keys vals)))
(assocpush "a" alist 99
:test #'string=)
(ensure (equal '(99 1 2) (assocdr "a" alist
:test #'string=))))))
(addtest (deoxybyte-utilities-tests) assocpop/1
(let ((keys '(a b))
(vals '((1 2) (3 4))))
(let ((alist (pairlis keys vals)))
(ensure (= 1 (assocpop 'a alist)))
(ensure (equal '(2) (assocdr 'a alist))))))
(addtest (deoxybyte-utilities-tests) assocpop/2
(let ((keys '("a" "b"))
(vals '((1 2) (3 4))))
(let ((alist (pairlis keys vals)))
(ensure (= 1 (assocpop "a" alist
:test #'string=)))
(ensure (equal '(2) (assocdr "a" alist
:test #'string=))))))
(addtest (deoxybyte-utilities-tests) splice/1
(let ((x (list 1 2 3))
(y 99)) ; atom
(ensure (equal '(99 1 2 3) (splice x y 0)))
(ensure (equal '(1 99 2 3) (splice x y 1)))
(ensure (equal '(1 2 99 3) (splice x y 2)))
(ensure (equal '(1 2 3 99) (splice x y 3)))))
(addtest (deoxybyte-utilities-tests) splice/2
(let ((x (list 1 2 3))
(y (list 99 77))) ; list
(ensure (equal '(99 77 1 2 3) (splice x y 0)))
(ensure (equal '(1 99 77 2 3) (splice x y 1)))
(ensure (equal '(1 2 99 77 3) (splice x y 2)))
(ensure (equal '(1 2 3 99 77) (splice x y 3)))))
(addtest (deoxybyte-utilities-tests) intersperse/1
(ensure (equal '(a x b x c) (intersperse '(a b c) 'x)))
(ensure (equal '(a x b) (intersperse '(a b) 'x)))
(ensure (equal '(a) (intersperse '(a) 'x)))
(ensure (equal '() (intersperse '() 'x))))
(addtest (deoxybyte-utilities-tests) collect-key-values/1
(let ((arg-list '(:a 1 :b 2 :c 3)))
(multiple-value-bind (args vals)
(collect-key-values '(:a :b) arg-list)
(ensure (equal '(:a :b) args))
(ensure (equal '( 1 2) vals)))))
(addtest (deoxybyte-utilities-tests) key-value/1
(let ((arg-list '(:a 1 :b 2 :c 3)))
(ensure (= 1 (key-value :a arg-list)))
(ensure (= 2 (key-value :b arg-list)))
(ensure (= 3 (key-value :c arg-list)))))
(addtest (deoxybyte-utilities-tests) remove-key-values/1
(let ((arg-list '(:a 1 :b 2 :c 3)))
(multiple-value-bind (retained removed)
(remove-key-values '(:a :c) arg-list)
(ensure (equal '(:b 2) retained))
(ensure (= 1 (assocdr :a removed)))
(ensure (= 3 (assocdr :c removed))))))
(addtest (deoxybyte-utilities-tests) modify-key-value/1
(let ((arg-list '(:a 1 :b 2 :c 3))
(fn (lambda (x &optional (y 0))
(+ 10 x y))))
(ensure (equal '(:a 11 :b 2 :c 3)
(modify-key-value :a arg-list fn)))
(ensure (equal '(:a 1 :b 12 :c 3)
(modify-key-value :b arg-list fn)))
(ensure (equal '(:a 1 :b 2 :c 13)
(modify-key-value :c arg-list fn)))
(ensure (equal '(:a 1 :b 2 :c 113)
(modify-key-value :c arg-list fn 100)))))
| 5,626 | Common Lisp | .lisp | 136 | 34.345588 | 73 | 0.558662 | keithj/deoxybyte-utilities | 3 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | ce548d6fb248aefb4a4f4d6b7bd89d18de56528b19228d193e362a81838f2056 | 17,769 | [
-1
] |
17,770 | octet-vector-utilities-test.lisp | keithj_deoxybyte-utilities/test/octet-vector-utilities-test.lisp | ;;;
;;; Copyright (c) 2008-2012 Keith James. All rights reserved.
;;;
;;; This file is part of deoxybyte-utilities.
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation, either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;
(in-package :uk.co.deoxybyte-utilities-test)
(addtest (deoxybyte-utilities-tests) octets-to-string/1
(let ((octets (make-array 2 :element-type 'octet :initial-contents '(65 65))))
(ensure (subtypep (type-of (octets-to-string octets)) 'simple-base-string))
(ensure (equal "AA" (octets-to-string octets)))
(ensure-error
(octets-to-string octets -1))
(ensure-condition invalid-argument-error
(octets-to-string octets 99))
(ensure-condition invalid-argument-error
(octets-to-string octets 1 0))
(ensure-error
(octets-to-string octets 0 99))))
| 1,373 | Common Lisp | .lisp | 31 | 41.612903 | 80 | 0.722388 | keithj/deoxybyte-utilities | 3 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 375e498882ad6ef8f3d1ce63b3602a4e93632ea1eaea446f784f7af7ea758269 | 17,770 | [
-1
] |
17,771 | clos-utilities-test.lisp | keithj_deoxybyte-utilities/test/clos-utilities-test.lisp | ;;;
;;; Copyright (c) 2008-2012 Keith James. All rights reserved.
;;;
;;; This file is part of deoxybyte-utilities.
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation, either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;
(in-package :uk.co.deoxybyte-utilities-test)
(addtest (deoxybyte-utilities-tests) has-superclass-p/1
(ensure (has-superclass-p (find-class 'x2) (find-class 'x1)))
(ensure (has-superclass-p (find-class 'x3) (find-class 'x1)))
(ensure (not (has-superclass-p (find-class 'y1) (find-class 'x1)))))
(addtest (deoxybyte-utilities-tests) all-superclasses/1
(ensure (equal (list (find-class 'x1))
(all-superclasses (find-class 'x1))))
(ensure (equal (mapcar #'find-class '(x1 x2))
(all-superclasses (find-class 'x2))))
(ensure (equal (mapcar #'find-class '(y1 x1 x2 x3))
(all-superclasses (find-class 'x3)))))
(addtest (deoxybyte-utilities-tests) all-specialized-methods/1
(ensure (subsetp (mapcar #'find-slot-reader-method
'(x1) (list #'slotx1-of))
(all-specialized-methods (find-class 'x1))))
(ensure (subsetp (mapcar #'find-slot-reader-method
'(x1 x2) (list #'slotx1-of #'slotx2-of))
(all-specialized-methods (find-class 'x2))))
(ensure (subsetp (mapcar #'find-slot-reader-method
'(x1 x2 x3 y1) (list #'slotx1-of #'slotx2-of
#'slotx3-of #'sloty1-of))
(all-specialized-methods (find-class 'x3)))))
(addtest (deoxybyte-utilities-tests) all-specialized-generic-functions/1
(let ((mgf #+:sbcl #'sb-mop:method-generic-function
#+:ccl #'ccl:method-generic-function))
(ensure (subsetp (mapcar mgf (all-specialized-methods (find-class 'x1)))
(all-specialized-generic-functions (find-class 'x1))))
(ensure (subsetp (mapcar mgf (all-specialized-methods (find-class 'x2)))
(all-specialized-generic-functions (find-class 'x2))))
(ensure (subsetp (mapcar mgf (all-specialized-methods (find-class 'x3)))
(all-specialized-generic-functions (find-class 'x3))))))
(addtest (deoxybyte-utilities-tests) all-external-generic-functions/1
(let ((external ()))
(do-external-symbols (sym (find-package :common-lisp) external)
(when (fboundp sym)
(push (symbol-function sym) external)))
(ensure (loop
for gf in (all-external-generic-functions
(find-package :common-lisp))
always (eql 'standard-generic-function (type-of gf))))
(ensure (subsetp (all-external-generic-functions
(find-package :common-lisp)) external))))
| 3,334 | Common Lisp | .lisp | 61 | 46.04918 | 77 | 0.636364 | keithj/deoxybyte-utilities | 3 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 632925b779d22e4992bd589e46254772cd1ee9dd17b97b1c926f9f0b72f2982a | 17,771 | [
-1
] |
17,772 | deoxybyte-utilities-test.lisp | keithj_deoxybyte-utilities/test/deoxybyte-utilities-test.lisp | ;;;
;;; Copyright (c) 2007-2012 Keith James. All rights reserved.
;;;
;;; This file is part of deoxybyte-utilities.
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation, either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;
(in-package :uk.co.deoxybyte-utilities-test)
(deftestsuite deoxybyte-utilities-tests ()
())
(defclass x1 ()
((slotx1 :initarg :slotx1
:reader slotx1-of)))
(defclass y1 ()
((sloty1 :initarg :sloty1
:reader sloty1-of)))
(defclass x2 (x1)
((slotx2 :initarg :slotx2
:reader slotx2-of)))
(defclass x3 (x2 y1)
((slotx3 :initarg :slotx3
:reader slotx3-of)))
(defun find-slot-reader-method (class-name generic-function)
(find-method generic-function '() (list (find-class class-name))))
(defun seq-iterator (seq)
(let ((n (length seq))
(i 0))
(defgenerator
(more (< i n))
(next (prog1
(elt seq i)
(incf i))))))
(addtest (deoxybyte-utilities-tests) funcall-if-fn/1
(ensure (equal "ABCDEF" (funcall-if-fn nil "ABCDEF")))
(ensure (equal "abcdef" (funcall-if-fn #'string-downcase "ABCDEF"))))
(addtest (deoxybyte-utilities-tests) defgenerator/1
(let ((gen (seq-iterator (iota 10))))
(ensure (equal (iota 10) (loop
while (has-more-p gen)
collect (next gen))))
(ensure (not (has-more-p gen)))))
(addtest (deoxybyte-utilities-tests) collect/1
(let ((gen (seq-iterator (iota 10))))
(ensure (equal (iota 1) (collect gen)))
(ensure (equal (iota 5 1) (collect gen 5)))))
(addtest (deoxybyte-utilities-tests) discard/1
(let ((gen (seq-iterator (iota 10))))
(ensure (= 5 (discard gen 5)))
(ensure (= 5 (discard gen 10)))))
(addtest (deoxybyte-utilities-tests) discarding-if/1
(let ((gen (discarding-if #'evenp (seq-iterator (iota 1)))))
(ensure (equal '() (loop
while (has-more-p gen)
collect (next gen)))))
(let ((gen (discarding-if #'oddp (seq-iterator (iota 1)))))
(ensure (equal '(0) (loop
while (has-more-p gen)
collect (next gen))))))
(addtest (deoxybyte-utilities-tests) discarding-if/2
(let ((gen (discarding-if #'null (seq-iterator (iota 10)))))
(ensure (equal (iota 10) (loop
while (has-more-p gen)
collect (next gen)))))
(let ((gen (discarding-if #'oddp (seq-iterator (iota 10)))))
(ensure (equal '(0 2 4 6 8) (loop
while (has-more-p gen)
collect (next gen)))))
(let ((gen (discarding-if #'evenp (seq-iterator (iota 10)))))
(ensure (equal '(1 3 5 7 9) (loop
while (has-more-p gen)
collect (next gen))))))
| 3,441 | Common Lisp | .lisp | 82 | 34.085366 | 73 | 0.592526 | keithj/deoxybyte-utilities | 3 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | a60ec20042bc809cd1e221db4763b0c3629ce8cb2ebc2b6249825cf988211168 | 17,772 | [
-1
] |
17,773 | finite-state-machine.lisp | keithj_deoxybyte-utilities/src/finite-state-machine.lisp | ;;;
;;; Copyright (c) 2008-2012 Keith James. All rights reserved.
;;;
;;; This file is part of deoxybyte-utilities.
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation, either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;
(in-package :uk.co.deoxybyte-utilities)
(defmacro defsmfun (name args bindings (&rest states))
"Returns a function that encapsulates a finite state machine over STATES.
Arguments:
- name (symbol): The name of the function.
- args (lambda list): The function lambda list.
- bindings (list): A list of parallel bindings (as for LET).
Rest:
- states (list): A list of forms describing the state
transitions. Each state form consists of a symbol that denotes a
current state and a series of conditional forms that act indicate
potential states that may be reached from the current state. The
tests are evaluated in turn as in a COND form.
(current-state (test1 next-state1 &rest actions)
(test2 next-state2 &rest actions)
(t nil))
When a test returns T, the machine moves to the next state once the
current state's action forms are evaluated. A next state of NIL
indicates termination, at which point the function returns the
result of evaluating the last action form.
For example, the following definition returns a function that
partitions a DNA sequence into base triples (codons).
;;; (defsmfun codon-iterator (seq &key (start 0))
;;; ((i start)
;;; (len (length-of seq))
;;; (codons ())
;;; (codon ()))
;;; ((base0 ((< i len) base1
;;; (setf codon (list (element-of seq i)))
;;; (incf i))
;;; (t nil
;;; (reverse codons)))
;;; (base1 ((< i len) base2
;;; (push (element-of seq i) codon)
;;; (incf i))
;;; (t nil
;;; (reverse codons)))
;;; (base2 ((< i len) base0
;;; (push (element-of seq i) codon)
;;; (push (reverse codon) codons)
;;; (incf i))
;;; (t nil
;;; (reverse codons)))))
Returns:
- A function."
`(defun ,name ,args
(let (,@bindings)
(block nil
(tagbody
,@(apply #'append
(mapcar
(lambda (state)
(destructuring-bind (name &rest acceptors)
state
(cons name
(if (zerop (length acceptors))
'((return))
(make-conditional acceptors)))))
states)))))))
(defmacro defsm ((&rest states))
"Defines a finite state machine over STATES.
Arguments:
- states (list): A list of forms describing the state transitions. See
{defun defsmfun} .
For example:
;;; (let* ((seq (make-dna \"atggtgcct\"))
;;; (i 0)
;;; (len (length-of seq))
;;; (codons ())
;;; (codon ()))
;;; (defsm ((base0 ((< i len) base1
;;; (setf codon (list (element-of seq i)))
;;; (incf i))
;;; (t nil
;;; (reverse codons)))
;;; (base1 ((< i len) base2
;;; (push (element-of seq i) codon)
;;; (incf i))
;;; (t nil
;;; (reverse codons)))
;;; (base2 ((< i len) base0
;;; (push (element-of seq i) codon)
;;; (push (reverse codon) codons)
;;; (incf i))
;;; (t nil
;;; (reverse codons)))))"
`(block nil
(tagbody
,@(apply #'append
(mapcar
(lambda (state)
(destructuring-bind (name &rest acceptors)
state
(cons name
(if (zerop (length acceptors))
'((return))
(make-conditional acceptors)))))
states)))))
(defun make-conditional (acceptors)
`((cond
,@(mapcar
(lambda (acceptor)
(destructuring-bind (test state &rest forms)
acceptor
`(,test ,@(cond (state
`(,@forms
(go ,state)))
(forms
`((let ((x (progn
,@forms)))
(return x))))
(t ; this may be redundant if the user
; supplies their own catch-all clause
'((return)))))))
acceptors)
(t
(return)))))
| 5,402 | Common Lisp | .lisp | 135 | 31.148148 | 75 | 0.502572 | keithj/deoxybyte-utilities | 3 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 7c6a20db113e099af37fd43989e66d52a332ca97e43408771e296d1b2866f7bc | 17,773 | [
-1
] |
17,774 | clos-utilities.lisp | keithj_deoxybyte-utilities/src/clos-utilities.lisp | ;;;
;;; Copyright (c) 2008-2012 Keith James. All rights reserved.
;;;
;;; This file is part of deoxybyte-utilities.
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation, either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;
(in-package :uk.co.deoxybyte-utilities)
;;; Introspection utility functions
(defun all-classes (package-name &optional (superclass
(find-class 'standard-object)))
"Returns a list of all classes defined in package PACKAGE-NAME,
optionally restricted to those classes that have SUPERCLASS."
(let ((package (find-package package-name))
(classes ()))
(do-symbols (s package classes)
(let ((c (find-class s nil)))
(when (and c
(eql package (symbol-package (class-name c)))
(has-superclass-p c superclass))
(push c classes))))))
(defun all-external-classes (package-name
&optional (superclass (find-class t)))
"Returns a list of all exported classes defined in package
PACKAGE-NAME, optionally restricted to those classes that have
SUPERCLASS."
(let ((package (find-package package-name))
(classes ()))
(do-external-symbols (s package classes)
(let ((c (find-class s nil)))
(when (and c
(eql package (symbol-package (class-name c)))
(has-superclass-p c superclass))
(push c classes))))))
(defun all-external-generic-functions (package-name)
"Returns a list of all the external generic functions in package
PACKAGE-NAME."
(let ((generic-fns ()))
(do-external-symbols (s (find-package package-name) generic-fns)
(when (fboundp s)
(let ((fn (symbol-function s)))
(when (eql 'standard-generic-function (type-of fn))
(push fn generic-fns)))))))
| 2,394 | Common Lisp | .lisp | 54 | 38.185185 | 75 | 0.662955 | keithj/deoxybyte-utilities | 3 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | a64c9e8f544691010915089293068c313ab2eeec9545554090d3248b5dcfbaa6 | 17,774 | [
-1
] |
17,775 | package.lisp | keithj_deoxybyte-utilities/src/package.lisp | ;;;
;;; Copyright (c) 2007-2012 Keith James. All rights reserved.
;;;
;;; This file is part of deoxybyte-utilities.
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation, either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;
(in-package :cl-user)
(defpackage :uk.co.deoxybyte-utilities
(:use #:common-lisp)
(:nicknames
#:deoxybyte-utilities
#:dxu)
(:export
;; Conditions
#:check-arguments
#:simple-text-condition
#:formatted-condition
#:invalid-argument-error
#:missing-argument-error
#:invalid-operation-error
#:deprecation-warning
#:message-of
;; Deoxybyte-utilities
#:with-gensyms
#:funcall-if-fn
#:copy-vector
#:defgenerator
#:current
#:next
#:has-more-p
#:consume
#:collect
#:discard
#:discarding-if
;; Type utilities
#:octet
#:nibble
#:uint8
#:int8
#:uint16
#:int16
#:uint32
#:int32
#:array-index
#:vector-index
#:simple-octet-vector
;; CLOS utilities
#:has-superclass-p
#:direct-superclasses
#:direct-subclasses
#:all-superclasses
#:all-classes
#:all-external-classes
#:all-specialized-methods
#:all-specialized-generic-functions
#:all-external-generic-functions
#:all-slots
#:slot-documentation
;; Cons utilities
#:assocdr
#:rassocar
#:rplassoc
#:assocpush
#:assocpop
#:dotted-pair-p
#:proper-list-p
#:splice
#:nsplice
#:intersperse
#:flatten
#:exactly-n
#:exactly-one
#:collect-key-values
#:key-value
#:remove-key-values
#:modify-key-value
;; Vector utilities
#:vector-positions
#:vector-split-indices
#:vector-split
#:binary-search
;; Set utilities
#:linear-union
#:linear-intersection
#:linear-set-difference
#:linear-set-exclusive-or
#:linear-subsetp
#:linear-set-equal
;; String utilities
#:control-char-p
#:whitespace-char-p
#:whitespace-string-p
#:content-string-p
#:empty-string-p
#:contains-char-p
#:has-char-at-p
#:starts-with-char-p
#:ends-with-char-p
#:every-char-p
#:starts-with-string-p
#:ends-with-string-p
#:concat-strings
#:txt
#:str
#:string-positions
#:string-split-indices
#:string-split
;; Octet vector utilities
#:octets-to-string
#:string-to-octets
;; Numeric utilities
#:iota
#:number-generator
#:with-numeric-selector
#:define-categorical-binner
;; Finite state machine
#:defsmfun
#:defsm
;; Queue
#:queue
#:queue-p
#:queue-head
#:queue-first
#:queue-last
#:make-queue
#:queue-enqueue
#:queue-dequeue
#:queue-dequeue-if
#:queue-clear
#:queue-first
#:queue-last
#:queue-nth
#:queue-empty-p
#:queue-delete
#:queue-append)
(:documentation "The deoxybyte-utilities system provides general
purpose utilities. These are for the most part simple, standalone
functions and macros. Once a particular function or macro has been
written more than once or twice in other systems, it normally gets
moved here.
Given the fluid nature of the contents of this system, its package's
exported symbols are intended primarily for use by other deoxybyte
packages."))
| 3,730 | Common Lisp | .lisp | 155 | 20.522581 | 73 | 0.697557 | keithj/deoxybyte-utilities | 3 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | f945e0d1ff3714f6bbd335a1b64cff1000b3eafe4ac00bcdf50e95cea0125340 | 17,775 | [
-1
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.