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
listlengths 1
47
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2,906
|
init-game-events-common.lisp
|
gwathlobal_CotD/src/game-events/init-game-events-common.lisp
|
(in-package :cotd)
(defparameter *game-events-military-list* (list +mob-type-soldier+ +mob-type-soldier+ +mob-type-gunner+ +mob-type-sergeant+ +mob-type-scout+ +mob-type-chaplain+))
(defun dump-when-dead ()
(let* ((final-str (if (null (killed-by *player*))
"Killed by unknown forces."
(format nil "Killed by ~A." (killed-by *player*))))
(score (calculate-player-score 0))
)
(values final-str score)
))
(declaim (ftype (function (world &key (:final-str string)
(:score fixnum)
(:if-player-won boolean)
(:player-msg string)
(:game-over-type game-over-enum)
(:mission-result list))
null)
trigger-game-over))
(defun trigger-game-over (world &key final-str score if-player-won player-msg game-over-type mission-result)
(let* ((tmp-world world)
(tmp-final-str final-str)
(tmp-score score)
(tmp-if-player-won if-player-won)
(tmp-player-msg player-msg)
(tmp-game-over-type game-over-type)
(highscores-place)
(player-died (player-check-dead))
(tmp-mission-result (copy-list mission-result)))
(declare (type string tmp-final-str player-msg) (type boolean tmp-if-player-won) (type fixnum tmp-score) (type game-over-enum game-over-type))
(when player-died
(multiple-value-setq (tmp-final-str tmp-score) (dump-when-dead)))
(setf highscores-place (add-highscore-record *highscores*
:name-str *player-name*
:score tmp-score
:mob-type-str *player-title*
:turns (player-game-time (level tmp-world))
:result-str tmp-final-str
:sector-name-str (name (world-sector (level tmp-world)))))
(if (null (level/scenario-ended (level tmp-world)))
(progn
(save-highscores-to-disk)
(dump-character-on-game-over (name *player*) tmp-score (player-game-time (level tmp-world)) (name (world-sector (level tmp-world)))
tmp-final-str (return-scenario-stats nil))
;; increase world flesh points
(when (or (eq tmp-game-over-type :game-over-demons-won)
(eq tmp-game-over-type :game-over-satanists-won))
(when (null (getf tmp-mission-result :flesh-points))
(loop with sum = 0
for item-id in (item-id-list (level tmp-world))
for item = (get-item-by-id item-id)
when (item-ability-p item +item-abil-corpse+) do
(incf sum (item-ability-p item +item-abil-corpse+))
finally (setf (getf tmp-mission-result :flesh-points) (truncate sum 40)))))
(setf (getf tmp-mission-result :mission-result) tmp-game-over-type)
(setf (level/mission-result (level tmp-world)) tmp-mission-result)
(add-message (format nil "~%"))
(add-message tmp-player-msg)
(add-message (format nil "~%Press any key...~%"))
(setf (level/scenario-ended (level tmp-world)) t))
(progn
;; immediately reload highscores from disk to eliminate a duplicated entry created above
(load-highscores-from-disk)))
(setf *current-window* (make-instance 'cell-window))
(update-visible-area (level *world*) (x *player*) (y *player*) (z *player*))
(make-output *current-window*)
(sdl:with-events ()
(:quit-event () (funcall (quit-func *current-window*)) t)
(:key-down-event ()
(setf *current-window* (make-instance 'final-stats-window :game-over-type tmp-game-over-type :highscores-place highscores-place
:player-won tmp-if-player-won :player-died player-died))
(make-output *current-window*)
(run-window *current-window*))
(:video-expose-event () (make-output *current-window*)))
)
nil)
(defun get-demon-raid-overall-points (world)
(loop for feature-id in (demonic-portals (level world))
for feature = (get-feature-by-id feature-id)
when (= (feature-type feature) +feature-demonic-portal+)
sum (if (param1 feature)
(param1 feature)
0)))
(defun get-demon-steal-check-relic-captured (world)
(loop for feature-id in (feature-id-list (level world))
for feature = (get-feature-by-id feature-id)
when (= (feature-type feature) +feature-demonic-portal+)
do
(when (param1 feature)
(return-from get-demon-steal-check-relic-captured t))
)
nil)
(defun get-demon-conquest-turns-left (world)
(multiple-value-bind (sigils-num max-turns) (values-list (win-condition/win-formula (get-win-condition-by-id :win-cond-demonic-conquest)))
(declare (ignore max-turns))
(loop for sigil-id in (stable-sort (demonic-sigils (level world)) #'(lambda (a b)
(if (> (param1 (get-effect-by-id (mob-effect-p (get-mob-by-id a) +mob-effect-demonic-sigil+)))
(param1 (get-effect-by-id (mob-effect-p (get-mob-by-id b) +mob-effect-demonic-sigil+))))
t
nil)))
repeat sigils-num
for sigil = (get-mob-by-id sigil-id)
for effect = (get-effect-by-id (mob-effect-p sigil +mob-effect-demonic-sigil+))
minimize (param1 effect))))
(defun get-military-conquest-check-alive-sigils (level)
(if (> (length (demonic-sigils level)) 0)
t
nil))
(defun get-angel-steal-angel-with-relic (world)
(let ((relic-item (if (level/relic-id (level world))
(get-item-by-id (level/relic-id (level world)))
nil)))
(when (and relic-item
(inv-id relic-item)
(mob-ability-p (get-mob-by-id (inv-id relic-item)) +mob-type-angel+))
(return-from get-angel-steal-angel-with-relic (get-mob-by-id (inv-id relic-item)))))
nil)
(defun get-angel-sabotage-check-alive-machines (level)
(if (> (length (demonic-machines level)) 0)
t
nil))
;;===========================
;; WIN EVENTS
;;===========================
(set-game-event (make-instance 'game-event :id +game-event-win-for-thief+
:descr-func #'(lambda ()
"To win, gather at least $1500 worth of items and leave the district by moving to its border. To lose, die or get possessed.")
:disabled nil
:on-check #'(lambda (world)
(if (and (= (loyal-faction *player*) +faction-type-criminals+)
(>= (get-overall-value (inv *player*)) *thief-win-value*)
(or (<= (x *player*) 1) (>= (x *player*) (- (array-dimension (terrain (level world)) 0) 2))
(<= (y *player*) 1) (>= (y *player*) (- (array-dimension (terrain (level world)) 1) 2))))
t
nil))
:on-trigger #'(lambda (world)
(trigger-game-over world
:final-str (format nil "Escaped with $~A." (calculate-total-value *player*))
:score (calculate-player-score 0)
:if-player-won t
:player-msg (format nil "Congratulations! You have won the game!~%")
:game-over-type :game-over-thief-won)
)))
(set-game-event (make-instance 'game-event :id +game-event-win-for-eater+
:descr-func #'(lambda ()
"To win, destroy all angels and demons in the district. To lose, die.")
:disabled nil
:on-check #'(lambda (world)
(if (or (and (= (loyal-faction *player*) +faction-type-eater+)
(zerop (total-demons (level world)))
(zerop (total-angels (level world))))
(and (/= (loyal-faction *player*) +faction-type-eater+)
(> (nth +faction-type-military+ (total-faction-list (level world))) 0)
(zerop (total-demons (level world)))
(zerop (total-angels (level world)))))
t
nil))
:on-trigger #'(lambda (world)
(let ((if-player-won (if (or (= (loyal-faction *player*) +faction-type-angels+)
(= (loyal-faction *player*) +faction-type-church+))
t
nil)))
(trigger-game-over world
:final-str "Enemies of Primordials eliminated."
:score (calculate-player-score 1430)
:if-player-won if-player-won
:player-msg (if if-player-won
(format nil "Congratulations! Your have won!~%")
(format nil "Curses! Your faction has lost!~%"))
:game-over-type :game-over-eater-won))
)))
(set-game-event (make-instance 'game-event :id +game-event-win-for-eater-consume+
:descr-func #'(lambda ()
(let* ((win-condition (get-win-condition-by-id :win-cond-eater-cosnume))
(corpses (funcall (win-condition/win-func win-condition) *world* win-condition)))
(format nil "To win, eat at least ~A corpses using your 'Cannibalize' ability. To lose, die." corpses)))
:disabled nil
:on-check #'(lambda (world)
(let* ((win-condition (get-win-condition-by-id :win-cond-eater-cosnume))
(corpses (funcall (win-condition/win-func win-condition) world win-condition)))
(if (and (= (loyal-faction *player*) +faction-type-eater+)
(>= (eater-corpses-consumed *player*) corpses))
t
nil)))
:on-trigger #'(lambda (world)
(let ((if-player-won (if (or (= (loyal-faction *player*) +faction-type-angels+)
(= (loyal-faction *player*) +faction-type-church+))
t
nil)))
(trigger-game-over world
:final-str "Primordials have satiated their hunger."
:score (calculate-player-score 1430)
:if-player-won if-player-won
:player-msg (if if-player-won
(format nil "Congratulations! Your have won!~%")
(format nil "Curses! Your faction has lost!~%"))
:game-over-type :game-over-eater-won))
)))
(set-game-event (make-instance 'game-event :id +game-event-win-for-ghost+
:descr-func #'(lambda ()
"To win, find the Book of Rituals in the library and read it while standing on a sacrificial circle in the satanists' lair. To lose, die.")
:disabled nil
:on-check #'(lambda (world)
(declare (ignore world))
(if (mob-effect-p *player* +mob-effect-rest-in-peace+)
t
nil))
:on-trigger #'(lambda (world)
(trigger-game-over world
:final-str "Put itself to rest."
:score (calculate-player-score 1450)
:if-player-won t
:player-msg (format nil "Congratulations! You have won the game!~%")
:game-over-type :game-over-ghost-won)
)))
;;===========================
;; LOSE EVENTS
;;===========================
(set-game-event (make-instance 'game-event :id +game-event-lose-game-died+ :disabled nil
:on-check #'(lambda (world)
(declare (ignore world))
(player-check-dead))
:on-trigger #'(lambda (world)
(trigger-game-over world
:final-str "Player died."
:score 0
:if-player-won nil
:player-msg (format nil "You are dead.~%")
:game-over-type :game-over-player-dead)
)))
(set-game-event (make-instance 'game-event :id +game-event-player-died+ :disabled nil
:on-check #'(lambda (world)
(declare (ignore world))
(if (and (player-check-dead)
(null (dead-message-displayed *player*)))
t
nil))
:on-trigger #'(lambda (world)
(declare (ignore world))
(add-message (create-string "~%"))
(add-message (create-string "You are dead.~%"))
(add-message (create-string "Wait while the scenario is resolved...~%~%"))
(setf (dead-message-displayed *player*) t))))
(set-game-event (make-instance 'game-event :id +game-event-lose-game-possessed+ :disabled nil
:on-check #'(lambda (world)
(declare (ignore world))
(if (and (mob-ability-p *player* +mob-abil-human+)
(master-mob-id *player*))
t
nil))
:on-trigger #'(lambda (world)
(trigger-game-over world
:final-str (format nil "Possessed by ~A." (get-qualified-name (get-mob-by-id (master-mob-id *player*))))
:score (calculate-player-score 0)
:if-player-won nil
:player-msg (format nil "You are possessed.~%")
:game-over-type :game-over-player-possessed)
)))
;;===========================
;; ENCHANTMENT EVENTS
;;===========================
(set-game-event (make-instance 'game-event :id +game-event-unnatural-darkness+ :disabled nil
:on-check #'(lambda (world)
(declare (ignore world))
t)
:on-trigger #'(lambda (world)
(when (zerop (random 10))
(setf (game-events (level world)) (remove +game-event-unnatural-darkness+ (game-events (level world))))
(add-message (format nil "Unnatural darkness is no longer.~%"))))))
(set-game-event (make-instance 'game-event :id +game-event-constant-reanimation+ :disabled nil
:on-check #'(lambda (world)
(declare (ignore world))
t)
:on-trigger #'(lambda (world)
(let ((corpse-items (loop for item-id in (item-id-list (level world))
for item = (get-item-by-id item-id)
when (and (item-ability-p item +item-abil-corpse+)
(not (get-mob-* (level world) (x item) (y item) (z item))))
collect item)))
(loop with failure-result = t
while (and (eq failure-result t)
corpse-items)
do
(setf failure-result nil)
(when (zerop (random 3))
(setf failure-result t))
(let ((item (nth (random (length corpse-items))
corpse-items)))
(when (not (get-mob-* (level world) (x item) (y item) (z item)))
(print-visible-message (x item) (y item) (z item) (level *world*) (format nil "An evil spirit has entered ~A. "
(prepend-article +article-the+ (visible-name item)))
:color sdl:*white*
:tags (list (when (if-cur-mob-seen-through-shared-vision *player*)
:singlemind)))
(invoke-reanimate-body item)
(setf corpse-items (remove item corpse-items))
))))
)))
(set-game-event (make-instance 'game-event :id +game-event-malseraphs-power-infusion+ :disabled nil
:on-check #'(lambda (world)
(declare (ignore world))
(if (< (random 100) 25)
t
nil))
:on-trigger #'(lambda (world)
(loop with demon-list = ()
repeat (random 20)
for mob-id = (nth (random (length (mob-id-list (level world)))) (mob-id-list (level world)))
for mob = (get-mob-by-id mob-id)
when (and (mob-ability-p mob +mob-abil-demon+)
(not (mob-ability-p mob +mob-abil-animal+))
(not (mob-ability-p mob +mob-abil-primordial+))
(< (cur-fp mob) (max-fp mob)))
do
(pushnew mob demon-list)
finally
(loop for mob in demon-list do
(print-visible-message (x mob) (y mob) (z mob) (level *world*)
(if (zerop (random 2))
(format nil "Malseraph giggles and grants its blessing. ")
(format nil "Malseraph cackles and grants its blessing. "))
:color sdl:*magenta*
:tags (list (when (and (find (id mob) (shared-visible-mobs *player*))
(not (find (id mob) (proper-visible-mobs *player*))))
:singlemind)))
(let ((pwr (1+ (random 3))))
(when (> (+ (cur-fp mob) pwr) (max-fp mob))
(setf pwr (- (max-fp mob) (cur-fp mob))))
(incf (cur-fp mob) pwr)
(print-visible-message (x mob) (y mob) (z mob) (level *world*)
(format nil "~A gains ~A unholy power.~%" (capitalize-name (prepend-article +article-the+ (visible-name mob))) pwr)
:color sdl:*white*
:tags (list (when (and (find (id mob) (shared-visible-mobs *player*))
(not (find (id mob) (proper-visible-mobs *player*))))
:singlemind)))))))))
;;===========================
;; OTHER EVENTS
;;===========================
(set-game-event (make-instance 'game-event :id +game-event-rain-falls+ :disabled nil
:on-check #'(lambda (world)
(declare (ignore world))
t)
:on-trigger #'(lambda (world)
(loop repeat 10
for x of-type fixnum = (random (array-dimension (terrain (level world)) 0))
for y of-type fixnum = (random (array-dimension (terrain (level world)) 1))
do
(loop for z from (1- (array-dimension (terrain (level world)) 2)) downto 0
when (or (get-terrain-type-trait (get-terrain-* (level world) x y z) +terrain-trait-blocks-move-floor+)
(and (> z 0)
(get-terrain-type-trait (get-terrain-* (level world) x y (1- z)) +terrain-trait-water+))
(and (> z 0)
(get-terrain-type-trait (get-terrain-* (level world) x y (1- z)) +terrain-trait-blocks-move+))
(get-mob-* (level world) x y z))
do
(log:info "GAME-EVENT: Rain falls at (~A ~A ~A)" x y z)
(place-animation x y z +anim-type-rain-dot+)
(when (get-mob-* (level world) x y z)
(set-mob-effect (get-mob-* (level world) x y z) :effect-type-id +mob-effect-wet+ :actor-id (id (get-mob-* (level world) x y z)) :cd 2))
(when (get-features-* (level world) x y z)
(loop for feature-id in (get-features-* (level world) x y z)
for feature = (get-feature-by-id feature-id)
when (or (= (feature-type feature) +feature-blood-old+)
(= (feature-type feature) +feature-blood-fresh+))
do
(remove-feature-from-level-list (level world) feature)
(remove-feature-from-world feature)
when (= (feature-type feature) +feature-blood-stain+)
do
(remove-feature-from-level-list (level world) feature)
(remove-feature-from-world feature)
(add-feature-to-level-list (level *world*) (make-instance 'feature :feature-type +feature-blood-fresh+ :x x :y y :z z))
when (= (feature-type feature) +feature-fire+)
do
(decf (counter feature) 2)
(when (<= (counter feature) 0)
(remove-feature-from-level-list (level world) feature)
(remove-feature-from-world feature))))
(loop-finish))
)
)))
(set-game-event (make-instance 'game-event :id +game-event-snow-falls+ :disabled nil
:on-check #'(lambda (world)
(declare (ignore world))
t)
:on-trigger #'(lambda (world)
(loop repeat (sqrt (* (array-dimension (terrain (level world)) 0) (array-dimension (terrain (level world)) 1)))
for x = (random (array-dimension (terrain (level world)) 0))
for y = (random (array-dimension (terrain (level world)) 1))
when (= (get-terrain-* (level world) x y 2) +terrain-floor-snow-prints+)
do
(log:info "GAME-EVENT: Snow falls at (~A ~A)" x y)
(set-terrain-* (level world) x y 2 +terrain-floor-snow+))
)))
(set-game-event (make-instance 'game-event :id +game-event-hellday+ :disabled nil
:on-check #'(lambda (world)
(declare (ignore world))
t)
:on-trigger #'(lambda (world)
(declare (ignore world))
nil)))
(set-game-event (make-instance 'game-event :id +game-event-adjust-outdoor-light+ :disabled nil
:on-check #'(lambda (world)
(declare (ignore world))
t)
:on-trigger #'(lambda (world)
(cond
((find +game-event-unnatural-darkness+ (game-events (level world)))
(progn
(setf (outdoor-light (level world))
0)))
((find +game-event-hellday+ (game-events (level world)))
(progn
(setf (outdoor-light (level world))
(round (- 50 (* 50 (sin (+ 8 (* (/ pi (* 1 60 10)) (world-game-time world))))))))))
(t
(progn
(setf (outdoor-light (level world))
(round (- 50 (* 50 (sin (+ 8 (* (/ pi (* 12 60 10)) (world-game-time world))))))))))
))))
(set-game-event (make-instance 'game-event :id +game-event-acid-falls+ :disabled nil
:on-check #'(lambda (world)
(declare (ignore world))
t)
:on-trigger #'(lambda (world)
(loop repeat 3
for x of-type fixnum = (random (array-dimension (terrain (level world)) 0))
for y of-type fixnum = (random (array-dimension (terrain (level world)) 1))
do
(loop for z from (1- (array-dimension (terrain (level world)) 2)) downto 0
when (or (get-terrain-type-trait (get-terrain-* (level world) x y z) +terrain-trait-blocks-move-floor+)
(and (> z 0)
(get-terrain-type-trait (get-terrain-* (level world) x y (1- z)) +terrain-trait-water+))
(and (> z 0)
(get-terrain-type-trait (get-terrain-* (level world) x y (1- z)) +terrain-trait-blocks-move+))
(get-mob-* (level world) x y z))
do
(log:info "GAME-EVENT: Acid falls at (~A ~A ~A)" x y z)
(place-animation x y z +anim-type-acid-dot+)
(check-surroundings x y t #'(lambda (dx dy)
(when (and (>= dx 0)
(>= dy 0)
(< dx (array-dimension (terrain (level *world*)) 0))
(< dy (array-dimension (terrain (level *world*)) 1))
(and (not (get-terrain-type-trait (get-terrain-* (level *world*) dx dy z) +terrain-trait-blocks-move+))
(not (get-terrain-type-trait (get-terrain-* (level *world*) dx dy z) +terrain-trait-blocks-projectiles+))))
(add-feature-to-level-list (level *world*) (make-instance 'feature :feature-type +feature-smoke-weak-acid-gas+ :x dx :y dy :z z
:counter 1)))))
(loop-finish))
)
)))
;;===========================
;; ARRIVAL EVENTS
;;===========================
(set-game-event (make-instance 'game-event :id +game-event-delayed-arrival-military+ :disabled nil
:on-check #'(lambda (world)
(if (and (= (player-game-time (level world)) (turns-for-delayed-military (level world))) (turn-finished world))
t
nil))
:on-trigger #'(lambda (world)
(log:info "GAME-EVENT: The military has arrived!")
;; find a suitable arrival point to accomodate 4 groups of military
(let ((military-list (list (list (list +mob-type-chaplain+ 1 nil)
(list +mob-type-sergeant+ 1 nil)
(list +mob-type-scout+ 1 nil)
(list +mob-type-soldier+ 3 nil)
(list +mob-type-gunner+ 1 nil))
(list (list +mob-type-chaplain+ 1 nil)
(list +mob-type-sergeant+ 1 nil)
(list +mob-type-scout+ 1 nil)
(list +mob-type-soldier+ 3 nil)
(list +mob-type-gunner+ 1 nil))
(list (list +mob-type-chaplain+ 1 nil)
(list +mob-type-sergeant+ 1 nil)
(list +mob-type-scout+ 1 nil)
(list +mob-type-soldier+ 3 nil)
(list +mob-type-gunner+ 1 nil))
(list (list +mob-type-chaplain+ 1 nil)
(list +mob-type-sergeant+ 1 nil)
(list +mob-type-scout+ 1 nil)
(list +mob-type-soldier+ 3 nil)
(list +mob-type-gunner+ 1 nil)))))
(when (= (player-lvl-mod-placement-id (mission (level world))) +lm-placement-military-chaplain+)
(setf military-list (remove (first military-list) military-list))
(push (list (list +mob-type-chaplain+ 1 t)
(list +mob-type-sergeant+ 1 nil)
(list +mob-type-scout+ 1 nil)
(list +mob-type-soldier+ 3 nil)
(list +mob-type-gunner+ 1 nil))
military-list))
(when (= (player-lvl-mod-placement-id (mission (level world))) +lm-placement-military-scout+)
(push (list (list +mob-type-scout+ 1 t))
military-list))
(loop for squad-list in military-list do
(destructuring-bind (mob-type-id mob-num is-player) (first squad-list)
(declare (ignore mob-num))
(let ((leader (if is-player
(progn
(setf (player-outside-level *player*) nil)
*player*)
(make-instance 'mob :mob-type mob-type-id))))
(loop with arrival-point-list = (copy-list (delayed-military-arrival-points (level world)))
while (> (length arrival-point-list) 0)
for random-arrival-point = (nth (random (length arrival-point-list)) arrival-point-list)
for x = (first random-arrival-point)
for y = (second random-arrival-point)
for z = (third random-arrival-point)
do
(setf arrival-point-list (remove random-arrival-point arrival-point-list))
(find-unoccupied-place-around (level world) leader x y z)
(loop-finish))
(setf squad-list (remove (first squad-list) squad-list))
(when squad-list
(populate-level-with-mobs (level world) squad-list
#'(lambda (level mob)
(find-unoccupied-place-around level mob (x leader) (y leader) (z leader)))))))
)
(loop for mob-id in (mob-id-list (level world))
for horse = (get-mob-by-id mob-id)
for rider = (if (mounted-by-mob-id horse)
(get-mob-by-id (mounted-by-mob-id horse))
nil)
when rider
do
(setf (x horse) (x rider) (y horse) (y rider) (z horse) (z rider)))
)
)
))
(set-game-event (make-instance 'game-event :id +game-event-delayed-arrival-angels+ :disabled nil
:on-check #'(lambda (world)
(if (and (turn-finished world)
(or (= (player-game-time (level world)) (turns-for-delayed-angels (level world)))
(= (player-game-time (level world)) (1- (turns-for-delayed-angels (level world))))
(= (player-game-time (level world)) (1+ (turns-for-delayed-angels (level world))))))
t
nil))
:on-trigger #'(lambda (world)
;; before arrivals
;; find suitable arrival points and place portals
(when (= (player-game-time (level world)) (1- (turns-for-delayed-angels (level world))))
(log:info "GAME-EVENT: The angels are about to arrive!")
(let ((portals ()))
(setf portals (place-custom-portals (level world) +feature-divine-portal+ :max-portals 10 :map-margin 10 :distance 6 :test-mob-free t :test-repel-demons nil))
(setf (delayed-angels-arrival-points (level world)) portals)))
;; at arrival
;; place chrome angels & trinity mimics to portals
(when (= (player-game-time (level world)) (turns-for-delayed-angels (level world)))
(log:info "GAME-EVENT: The angels are arriving!")
(let ((angels-list (list (list +mob-type-angel+ *min-angels-number* nil))))
(if (= (player-lvl-mod-placement-id (mission (level world))) +lm-placement-angel-trinity+)
(push (list +mob-type-star-singer+ 1 t) angels-list)
(push (list +mob-type-star-singer+ 1 nil)
angels-list))
(when (= (player-lvl-mod-placement-id (mission (level world))) +lm-placement-angel-chrome+)
(push (list +mob-type-angel+ 1 t)
angels-list))
(place-angels-on-level-immediate (level world)
:start-point-list (delayed-angels-arrival-points (level world))
:create-player nil
:angel-list angels-list)))
;; after arrival
;; remove portals
(when (= (player-game-time (level world)) (1+ (turns-for-delayed-angels (level world))))
(log:info "GAME-EVENT: Divine portals removed!")
(loop for lvl-feature-id in (feature-id-list (level world))
for lvl-feature = (get-feature-by-id lvl-feature-id)
when (= (feature-type lvl-feature) +feature-divine-portal+) do
(remove-feature-from-level-list (level world) lvl-feature)
(remove-feature-from-world lvl-feature)))
)))
(set-game-event (make-instance 'game-event :id +game-event-delayed-arrival-demons+ :disabled nil
:on-check #'(lambda (world)
(if (and (turn-finished world)
(or (= (player-game-time (level world)) (turns-for-delayed-demons (level world)))
(= (player-game-time (level world)) (1- (turns-for-delayed-demons (level world))))
(= (player-game-time (level world)) (1+ (turns-for-delayed-demons (level world))))))
t
nil))
:on-trigger #'(lambda (world)
;; before arrivals
;; find suitable arrival points and place portals
(when (= (player-game-time (level world)) (1- (turns-for-delayed-demons (level world))))
(log:info "GAME-EVENT: The demons are about to arrive!")
(let ((portals ()))
(setf portals (place-custom-portals (level world) +feature-demonic-portal+ :max-portals 10 :map-margin 10 :distance 6 :test-mob-free t :test-repel-demons t))
(setf (delayed-demons-arrival-points (level world)) portals)))
;; at arrival
;; place demons
(when (= (player-game-time (level world)) (turns-for-delayed-demons (level world)))
(log:info "GAME-EVENT: The demons are arriving!")
(multiple-value-bind (year month day hour min sec) (get-current-date-time (world-game-time world))
(declare (ignore year month day min sec))
(let ((demon-list (if (and (>= hour 7) (< hour 19))
(list (list +mob-type-archdemon+ 2 nil)
(list +mob-type-demon+ 15 nil)
(list +mob-type-imp+ (+ (random (- *max-imps-number* *min-imps-number*)) *min-imps-number*) nil))
(list (list +mob-type-archdemon+ 1 nil)
(list +mob-type-shadow-devil+ 1 nil)
(list +mob-type-demon+ 7 nil)
(list +mob-type-shadow-demon+ 8 nil)
(list +mob-type-imp+ (truncate (+ (random (- *max-imps-number* *min-imps-number*)) *min-imps-number*) 2) nil)
(list +mob-type-shadow-imp+ (truncate (+ (random (- *max-imps-number* *min-imps-number*)) *min-imps-number*) 2) nil)))))
(if (= (player-lvl-mod-placement-id (mission (level world))) +lm-placement-demon-malseraph+)
(push (list +mob-type-malseraph-puppet+ 1 t) demon-list)
(push (list +mob-type-malseraph-puppet+ 1 nil) demon-list))
(when (= (player-lvl-mod-placement-id (mission (level world))) +lm-placement-demon-crimson+)
(push (list +mob-type-imp+ 1 t) demon-list))
(when (= (player-lvl-mod-placement-id (mission (level world))) +lm-placement-demon-shadow+)
(push (list +mob-type-shadow-imp+ 1 t) demon-list))
(place-mobs-on-level-immediate (level world)
:start-point-list (delayed-demons-arrival-points (level world))
:create-player nil
:mob-list demon-list
:no-center t))))
;; after arrival
;; remove portals
(when (= (player-game-time (level world)) (1+ (turns-for-delayed-demons (level world))))
(log:info "GAME-EVENT: Demonic portals removed!")
(loop for lvl-feature-id in (feature-id-list (level world))
for lvl-feature = (get-feature-by-id lvl-feature-id)
when (= (feature-type lvl-feature) +feature-demonic-portal+) do
(remove-feature-from-level-list (level world) lvl-feature)
(remove-feature-from-world lvl-feature))))
))
| 61,705
|
Common Lisp
|
.lisp
| 623
| 40.611557
| 238
| 0.30001
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
96602638b6bc4f4f675358fa0e9718757857bd2c2ea630f0c38489386be7e258
| 2,906
|
[
-1
] |
2,907
|
init-game-events-demonic-raid.lisp
|
gwathlobal_CotD/src/game-events/init-game-events-demonic-raid.lisp
|
(in-package :cotd)
;;===========================
;; WIN EVENTS
;;===========================
(set-game-event (make-instance 'game-event :id +game-event-demon-raid-win-for-angels+
:descr-func #'(lambda ()
(let ((win-figure (win-condition/win-formula (get-win-condition-by-id :win-cond-demonic-raid))))
(format nil "To win, destroy all demons in the district. To lose, have all angels killed or let the demons collect ~A pts of flesh (corpses)." win-figure)))
:disabled nil
:on-check #'(lambda (world)
(if (or (and (= (loyal-faction *player*) +faction-type-angels+)
(> (total-angels (level world)) 0)
(zerop (total-demons (level world))))
(and (/= (loyal-faction *player*) +faction-type-angels+)
(zerop (nth +faction-type-satanists+ (total-faction-list (level world))))
(> (total-angels (level world)) 0)
(zerop (total-demons (level world)))))
t
nil))
:on-trigger #'(lambda (world)
(let ((if-player-won (if (or (= (loyal-faction *player*) +faction-type-angels+)
(= (loyal-faction *player*) +faction-type-church+))
t
nil)))
(trigger-game-over world
:final-str "Demonic raid broken."
:score (calculate-player-score (+ 1400 (if (not (mimic-id-list *player*))
0
(loop for mimic-id in (mimic-id-list *player*)
for mimic = (get-mob-by-id mimic-id)
with cur-score = 0
when (not (eq mimic *player*))
do
(incf cur-score (cur-score mimic))
finally (return cur-score)))))
:if-player-won if-player-won
:player-msg (if if-player-won
(format nil "Congratulations! Your faction has won!~%")
(format nil "Curses! Your faction has lost!~%"))
:game-over-type :game-over-angels-won))
)))
(set-game-event (make-instance 'game-event :id +game-event-demon-raid-win-for-demons+
:descr-func #'(lambda ()
(let ((win-figure (win-condition/win-formula (get-win-condition-by-id :win-cond-demonic-raid))))
(format nil "To win, collect ~A pts of flesh by throwing corpses into the demonic portals (use your ability for that). To lose, have all demons killed." win-figure)))
:disabled nil
:on-check #'(lambda (world)
(if (and (> (total-demons (level world)) 0)
(>= (get-demon-raid-overall-points world) (win-condition/win-formula (get-win-condition-by-id :win-cond-demonic-raid))))
t
nil))
:on-trigger #'(lambda (world)
(let ((if-player-won (if (or (= (loyal-faction *player*) +faction-type-demons+)
(= (loyal-faction *player*) +faction-type-satanists+))
t
nil)))
(trigger-game-over world
:final-str "Flesh successfully gathered."
:score (calculate-player-score 1450)
:if-player-won if-player-won
:player-msg (if if-player-won
(format nil "Congratulations! Your faction has won!~%")
(format nil "Curses! Your faction has lost!~%"))
:game-over-type :game-over-demons-won
:mission-result (list :flesh-points (truncate (get-demon-raid-overall-points world) 40))))
)))
(set-game-event (make-instance 'game-event :id +game-event-demon-raid-win-for-military+
:descr-func #'(lambda ()
(let ((win-figure (win-condition/win-formula (get-win-condition-by-id :win-cond-demonic-raid))))
(format nil "To win, destroy all demons in the district. To lose, have all military killed or let the demons collect the ~A pts of flesh they want." win-figure))
)
:disabled nil
:on-check #'(lambda (world)
(if (and (> (total-humans (level world)) 0)
(zerop (total-demons (level world))))
t
nil))
:on-trigger #'(lambda (world)
(let ((if-player-won (if (= (loyal-faction *player*) +faction-type-military+)
t
nil)))
(trigger-game-over world
:final-str "Demonic raid broken."
:score (calculate-player-score (+ 1450 (* 7 (total-humans (level world)))))
:if-player-won if-player-won
:player-msg (if if-player-won
(format nil "Congratulations! Your faction has won!~%")
(format nil "Curses! Your faction has lost!~%"))
:game-over-type :game-over-military-won))
)))
(set-game-event (make-instance 'game-event :id +game-event-demon-raid-win-for-church+
:descr-func #'(lambda ()
(let ((win-figure (win-condition/win-formula (get-win-condition-by-id :win-cond-demonic-raid))))
(format nil "To win, destroy all demons in the district. To lose, get all priests and angels killed or let the demons collect ~A pts of flesh they want." win-figure)))
:disabled nil
:on-check #'(lambda (world)
(if (and (= (loyal-faction *player*) +faction-type-church+)
(> (nth +faction-type-church+ (total-faction-list (level world))) 0)
(zerop (total-demons (level world))))
t
nil))
:on-trigger #'(lambda (world)
(let ((if-player-won (if (or (= (loyal-faction *player*) +faction-type-angels+)
(= (loyal-faction *player*) +faction-type-church+))
t
nil)))
(trigger-game-over world
:final-str "Demonic raid broken."
:score (calculate-player-score (+ 1400 (if (not (mimic-id-list *player*))
0
(loop for mimic-id in (mimic-id-list *player*)
for mimic = (get-mob-by-id mimic-id)
with cur-score = 0
when (not (eq mimic *player*))
do
(incf cur-score (cur-score mimic))
finally (return cur-score)))))
:if-player-won if-player-won
:player-msg (if if-player-won
(format nil "Congratulations! Your faction has won!~%")
(format nil "Curses! Your faction has lost!~%"))
:game-over-type :game-over-church-won))
)))
(set-game-event (make-instance 'game-event :id +game-event-demon-raid-win-for-satanists+
:descr-func #'(lambda ()
(let ((win-figure (win-condition/win-formula (get-win-condition-by-id :win-cond-demonic-raid))))
(format nil "To win, collect ~A pts of flesh by throwing corpses into the demonic portals. To lose, get all satanists and demons killed." win-figure))
)
:disabled nil
:on-check #'(lambda (world)
(if (and (= (loyal-faction *player*) +faction-type-satanists+)
(> (nth +faction-type-satanists+ (total-faction-list (level world))) 0)
(>= (get-demon-raid-overall-points world) (win-condition/win-formula (get-win-condition-by-id :win-cond-demonic-raid))))
t
nil))
:on-trigger #'(lambda (world)
(let ((if-player-won (if (or (= (loyal-faction *player*) +faction-type-demons+)
(= (loyal-faction *player*) +faction-type-satanists+))
t
nil)))
(trigger-game-over world
:final-str "Flesh successfully gathered."
:score (calculate-player-score 1450)
:if-player-won if-player-won
:player-msg (if if-player-won
(format nil "Congratulations! Your faction has won!~%")
(format nil "Curses! Your faction has lost!~%"))
:game-over-type :game-over-satanists-won
:mission-result (list :flesh-points (get-demon-raid-overall-points world))))
)))
| 16,703
|
Common Lisp
|
.lisp
| 150
| 40.626667
| 228
| 0.264338
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
3c84f3f76f4e79d1baa9e4be89222cb31571ec1bafee263e73a9f4483204958a
| 2,907
|
[
-1
] |
2,908
|
init-game-events-campaign.lisp
|
gwathlobal_CotD/src/game-events/init-game-events-campaign.lisp
|
(in-package :cotd)
;;===========================
;; WIN EVENTS
;;===========================
(set-game-event (make-instance 'game-event :id +game-event-campaign-satanists-move+
:descr-func #'(lambda ()
(format nil "Each day, move satanists to a location nearby."))
:disabled nil
:on-check #'(lambda (world)
(declare (ignore world))
t)
:on-trigger #'(lambda (world)
(let ((world-sector)
(cur-lair)
(lair-list-init ())
(lair-list-final ()))
(loop for x from 0 below (array-dimension (cells (world-map world)) 0) do
(loop for y from 0 below (array-dimension (cells (world-map world)) 1) do
(setf world-sector (aref (cells (world-map world)) x y))
(setf cur-lair (find +lm-feat-lair+ (feats world-sector) :key #'(lambda (a) (first a))))
(when cur-lair
(push (list cur-lair x y) lair-list-init))))
(loop with select-sector = nil
for (lair x y) in lair-list-init
for avail-sectors = ()
do
(check-surroundings x y nil #'(lambda (dx dy)
(when (and (>= dx 0) (>= dy 0) (< dx (array-dimension (cells (world-map world)) 0)) (< dy (array-dimension (cells (world-map world)) 1))
(setf world-sector (aref (cells (world-map world)) dx dy))
(not (eq (wtype world-sector) :world-sector-normal-sea))
(not (find +lm-feat-lair+ (feats world-sector) :key #'(lambda (a) (first a))))
(not (find-if #'(lambda (a)
(if (and (= (second a) dx)
(= (third a) dx))
t
nil))
lair-list-final)))
(push (list dx dy) avail-sectors))))
(when avail-sectors
(setf select-sector (nth (random (length avail-sectors)) avail-sectors))
(push (list lair (first select-sector) (second select-sector)) lair-list-final)))
(loop for (lair x y) in lair-list-init do
(setf world-sector (aref (cells (world-map world)) x y))
(setf (feats world-sector) (remove +lm-feat-lair+ (feats world-sector) :key #'(lambda (a) (first a)))))
(loop for (lair x y) in lair-list-final do
(setf world-sector (aref (cells (world-map world)) x y))
(push lair (feats world-sector))))
)))
(set-game-event (make-instance 'game-event :id +game-event-campaign-flesh-gathered+
:descr-func #'(lambda ()
(format nil "Each day, gather the flesh from missions."))
:disabled nil
:on-check #'(lambda (world)
(if (and (getf (world/post-mission-results world) :flesh-points)
(> (getf (world/post-mission-results world) :flesh-points) 0))
t
nil))
:on-trigger #'(lambda (world)
(let ((flesh-points (getf (world/post-mission-results world) :flesh-points)))
(add-message (format nil "Demons managed to gather ") sdl:*white* `(,(world/event-message-box world)))
(add-message (format nil "~A flesh ~A" flesh-points (if (= flesh-points 1) "point" "points")) sdl:*yellow* `(,(world/event-message-box *world*)))
(add-message (format nil " recently.~%") sdl:*white* `(,(world/event-message-box *world*)))
(incf (world/flesh-points *world*) flesh-points)
))))
(set-game-event (make-instance 'game-event :id +game-event-campaign-move-military+
:descr-func #'(lambda ()
(format nil "Each day, move military towards enemy."))
:disabled nil
:on-check #'(lambda (world)
(if (> (calc-all-military-on-world-map (world-map world)) 0)
t
nil))
:on-trigger #'(lambda (world)
(multiple-value-bind (military-num military-sectors) (calc-all-military-on-world-map (world-map world))
(declare (ignore military-num))
(loop for military-sector in military-sectors do
(let ((world-sector nil)
(nearest-sector nil)
(message-box-list `(,(world/event-message-box *world*))))
;; find nearest corrupted or abandoned sector
(loop for x from 0 below (array-dimension (cells (world-map world)) 0) do
(loop for y from 0 below (array-dimension (cells (world-map world)) 1) do
(setf world-sector (aref (cells (world-map world)) x y))
(when (or (world-sector-abandoned-p world-sector)
(world-sector-corrupted-p world-sector))
(unless nearest-sector
(setf nearest-sector world-sector))
(when (< (get-distance (x military-sector) (y military-sector) (x world-sector) (y world-sector))
(get-distance (x military-sector) (y military-sector) (x nearest-sector) (y nearest-sector)))
(setf nearest-sector world-sector)))))
;; move the military towards that sector
(when nearest-sector
(loop with correct-dirs = ()
with x = (x military-sector)
with y = (y military-sector)
for dir from 1 to 9
for (dx dy) = (multiple-value-list (x-y-dir dir))
when (and (>= (+ dx x) 0) (>= (+ dy y) 0) (< (+ dx x) (array-dimension (cells (world-map world)) 0)) (< (+ dy y) (array-dimension (cells (world-map world)) 1))
(< (get-distance (+ dx x) (+ dy y) (x nearest-sector) (y nearest-sector))
(get-distance x y (x nearest-sector) (y nearest-sector)))
(world-sector-normal-p (aref (cells (world-map world)) (+ dx x) (+ dy y)))
(eq (controlled-by (aref (cells (world-map world)) (+ dx x) (+ dy y))) +lm-controlled-by-none+))
do
(push dir correct-dirs)
finally (when correct-dirs
(multiple-value-bind (dx dy) (x-y-dir (nth (random (length correct-dirs)) correct-dirs))
(setf (controlled-by military-sector) +lm-controlled-by-none+)
(setf (controlled-by (aref (cells (world-map world)) (+ dx x) (+ dy y))) +lm-controlled-by-military+)
(add-message (format nil "The ") sdl:*white* message-box-list)
(add-message (format nil "military") sdl:*yellow* message-box-list)
(add-message (format nil " moved from ") sdl:*white* message-box-list)
(add-message (format nil "~(~A~)" (name military-sector)) sdl:*yellow* message-box-list)
(add-message (format nil " to ") sdl:*white* message-box-list)
(add-message (format nil "~(~A~)" (name (aref (cells (world-map world)) (+ dx x) (+ dy y)))) sdl:*yellow* message-box-list)
(add-message (format nil ".~%") sdl:*white* message-box-list))))))
)))
))
(set-game-event (make-instance 'game-event :id +game-event-campaign-move-demons+
:descr-func #'(lambda ()
(format nil "Each day, move demons around corrupted districts."))
:disabled nil
:on-check #'(lambda (world)
(if (> (calc-all-demons-on-world-map (world-map world)) 0)
t
nil))
:on-trigger #'(lambda (world)
(multiple-value-bind (demons-num demon-sectors) (calc-all-demons-on-world-map (world-map world))
(declare (ignore demons-num))
(loop for demon-sector in demon-sectors do
(let ((avail-sectors ())
(world-sector nil)
(message-box-list `(,(world/event-message-box *world*))))
(check-surroundings (x demon-sector) (y demon-sector) nil
#'(lambda (dx dy)
(when (and (>= dx 0) (>= dy 0) (< dx (array-dimension (cells (world-map world)) 0)) (< dy (array-dimension (cells (world-map world)) 1))
(setf world-sector (aref (cells (world-map world)) dx dy))
(world-sector-corrupted-p world-sector)
(eq (controlled-by world-sector) +lm-controlled-by-none+))
(push world-sector avail-sectors))))
(when avail-sectors
(setf world-sector (nth (random (length avail-sectors)) avail-sectors))
(setf (controlled-by demon-sector) +lm-controlled-by-none+)
(setf (controlled-by world-sector) +lm-controlled-by-demons+)
(add-message (format nil "The ") sdl:*white* message-box-list)
(add-message (format nil "demons") sdl:*yellow* message-box-list)
(add-message (format nil " moved from ") sdl:*white* message-box-list)
(add-message (format nil "~(~A~)" (name demon-sector)) sdl:*yellow* message-box-list)
(add-message (format nil " to ") sdl:*white* message-box-list)
(add-message (format nil "~(~A~)" (name world-sector)) sdl:*yellow* message-box-list)
(add-message (format nil ".~%") sdl:*white* message-box-list))
))))
))
(set-game-event (make-instance 'game-event :id +game-event-campaign-trigger-commands+
:descr-func #'(lambda ()
(format nil "Each day, trigger commands for all factions."))
:disabled nil
:on-check #'(lambda (world)
(declare (ignore world))
t)
:on-trigger #'(lambda (world)
(loop for faction-type in (list +faction-type-demons+ +faction-type-angels+ +faction-type-military+ +faction-type-satanists+ +faction-type-church+) do
;; assume all commands are already present
(let* ((world-command (gethash faction-type (world/commands world)))
(command (get-campaign-command-by-id (getf world-command :command)))
(cd (getf world-command :cd)))
(when (= cd (campaign-command/cd command))
(if (funcall (campaign-command/on-check-func command) world command)
(when (campaign-command/on-trigger-start-func command)
(funcall (campaign-command/on-trigger-start-func command) world command))
(setf (gethash faction-type (world/commands *world*)) nil)))
(decf (getf world-command :cd))
(when (= (getf world-command :cd) 0)
(when (and (funcall (campaign-command/on-check-func command) world command)
(campaign-command/on-trigger-end-func command))
(funcall (campaign-command/on-trigger-end-func command) world command))
(setf (gethash faction-type (world/commands *world*)) nil)))
)
)
))
(set-game-event (make-instance 'game-event :id +game-event-campaign-move-relic-to-church+
:descr-func #'(lambda ()
(format nil "Each day, try to move a relic from inhabited district to a district with a church."))
:disabled nil
:on-check #'(lambda (world)
(declare (ignore world))
t)
:on-trigger #'(lambda (world)
(let ((free-church-sectors (loop with church-sector-list = ()
for dx from 0 below (array-dimension (cells (world-map world)) 0) do
(loop for dy from 0 below (array-dimension (cells (world-map world)) 1) do
(when (and (world-sector-normal-p (aref (cells (world-map world)) dx dy))
(find +lm-feat-church+ (feats (aref (cells (world-map world)) dx dy)) :key #'(lambda (a) (first a)))
(not (find +lm-item-holy-relic+ (items (aref (cells (world-map world)) dx dy)))))
(push (aref (cells (world-map world)) dx dy) church-sector-list)))
finally (return church-sector-list)))
(normal-relic-sectors (loop with relic-sector-list = ()
for dx from 0 below (array-dimension (cells (world-map world)) 0) do
(loop for dy from 0 below (array-dimension (cells (world-map world)) 1) do
(when (and (world-sector-normal-p (aref (cells (world-map world)) dx dy))
(not (find +lm-feat-church+ (feats (aref (cells (world-map world)) dx dy)) :key #'(lambda (a) (first a))))
(find +lm-item-holy-relic+ (items (aref (cells (world-map world)) dx dy))))
(push (aref (cells (world-map world)) dx dy) relic-sector-list)))
finally (return relic-sector-list)))
(message-box-list `(,(world/event-message-box *world*))))
(loop for church-sector in free-church-sectors
for relic-sector in normal-relic-sectors
do
(setf (items relic-sector) (remove +lm-item-holy-relic+ (items relic-sector)))
(push +lm-item-holy-relic+ (items church-sector))
(add-message (format nil "The ") sdl:*white* message-box-list)
(add-message (format nil "relic") sdl:*yellow* message-box-list)
(add-message (format nil " was moved back into the church in ") sdl:*white* message-box-list)
(add-message (format nil "~(~A~)" (name church-sector)) sdl:*yellow* message-box-list)
(add-message (format nil ".~%") sdl:*white* message-box-list))
)
)
))
(set-game-event (make-instance 'game-event :id +game-event-campaign-malseraphs-focus+
:descr-func #'(lambda ()
(format nil "Each day, check if Malseraph wants to turn its attention to the city."))
:disabled nil
:on-check #'(lambda (world)
(if (and (not (find-campaign-effects-by-id world :campaign-effect-demon-malseraph-blessing))
(not (find-campaign-effects-by-id world :campaign-effect-demon-malseraph-bored))
(or (and (first (find-specific-world-sectors world #'(lambda (world-sector x y)
(declare (ignore x y))
(and (find +lm-item-holy-relic+ (items world-sector))
(world-sector-corrupted-p world-sector)))))
(< (random 100) 15))
(< (random 100) 5)))
t
nil))
:on-trigger #'(lambda (world)
(let* ((effects-list (list :campaign-effect-demon-malseraph-blessing))
(chosen-effect (nth (random (length effects-list)) effects-list)))
(add-campaign-effect world :id chosen-effect :cd (+ 3 (random 4)) :param nil)))
))
| 27,720
|
Common Lisp
|
.lisp
| 237
| 47.632911
| 238
| 0.298366
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
78eea0ded1f0fedc874130eda054d910a7b4dc35d6df449a79498f7a5eb102c8
| 2,908
|
[
-1
] |
2,909
|
init-game-events-demonic-steal.lisp
|
gwathlobal_CotD/src/game-events/init-game-events-demonic-steal.lisp
|
(in-package :cotd)
;;===========================
;; WIN EVENTS
;;===========================
(set-game-event (make-instance 'game-event :id +game-event-demon-steal-win-for-angels+
:descr-func #'(lambda ()
"To win, destroy all demons in the district. To lose, have all angels killed or let the demons capture the relic.")
:disabled nil
:on-check #'(lambda (world)
(if (or (and (= (loyal-faction *player*) +faction-type-angels+)
(> (total-angels (level world)) 0)
(zerop (total-demons (level world))))
(and (/= (loyal-faction *player*) +faction-type-angels+)
(zerop (nth +faction-type-satanists+ (total-faction-list (level world))))
(> (total-angels (level world)) 0)
(zerop (total-demons (level world)))))
t
nil))
:on-trigger #'(lambda (world)
(let ((if-player-won (if (or (= (loyal-faction *player*) +faction-type-angels+)
(= (loyal-faction *player*) +faction-type-church+))
t
nil)))
(trigger-game-over world
:final-str "Demonic theivery attempt prevented."
:score (calculate-player-score (+ 1400 (if (not (mimic-id-list *player*))
0
(loop for mimic-id in (mimic-id-list *player*)
for mimic = (get-mob-by-id mimic-id)
with cur-score = 0
when (not (eq mimic *player*))
do
(incf cur-score (cur-score mimic))
finally (return cur-score)))))
:if-player-won if-player-won
:player-msg (if if-player-won
(format nil "Congratulations! Your faction has won!~%")
(format nil "Curses! Your faction has lost!~%"))
:game-over-type :game-over-angels-won))
)))
(set-game-event (make-instance 'game-event :id +game-event-demon-steal-win-for-demons+
:descr-func #'(lambda ()
"To win, capture the relic in the church and throw it into a demonic portal (use your ability for that). To lose, have all demons killed.")
:disabled nil
:on-check #'(lambda (world)
(if (and (> (total-demons (level world)) 0)
(get-demon-steal-check-relic-captured world))
t
nil))
:on-trigger #'(lambda (world)
(let ((if-player-won (if (or (= (loyal-faction *player*) +faction-type-demons+)
(= (loyal-faction *player*) +faction-type-satanists+))
t
nil)))
(trigger-game-over world
:final-str "Relic captured by demons."
:score (calculate-player-score 1300)
:if-player-won if-player-won
:player-msg (if if-player-won
(format nil "Congratulations! Your faction has won!~%")
(format nil "Curses! Your faction has lost!~%"))
:game-over-type :game-over-demons-won))
)))
(set-game-event (make-instance 'game-event :id +game-event-demon-steal-win-for-military+
:descr-func #'(lambda ()
"To win, destroy all demons in the district. To lose, have all military killed or let the demons capture the relic.")
:disabled nil
:on-check #'(lambda (world)
(if (and (> (total-humans (level world)) 0)
(zerop (total-demons (level world))))
t
nil))
:on-trigger #'(lambda (world)
(let ((if-player-won (if (= (loyal-faction *player*) +faction-type-military+)
t
nil)))
(trigger-game-over world
:final-str "Demonic theivery attempt prevented."
:score (calculate-player-score (+ 1450 (* 7 (total-humans (level world)))))
:if-player-won if-player-won
:player-msg (if if-player-won
(format nil "Congratulations! Your faction has won!~%")
(format nil "Curses! Your faction has lost!~%"))
:game-over-type :game-over-military-won))
)))
(set-game-event (make-instance 'game-event :id +game-event-demon-steal-win-for-church+
:descr-func #'(lambda ()
"To win, destroy all demons in the district. To lose, get all priests and angels killed or let the demons capture the relic.")
:disabled nil
:on-check #'(lambda (world)
(if (and (= (loyal-faction *player*) +faction-type-church+)
(> (nth +faction-type-church+ (total-faction-list (level world))) 0)
(zerop (total-demons (level world))))
t
nil))
:on-trigger #'(lambda (world)
(let ((if-player-won (if (or (= (loyal-faction *player*) +faction-type-angels+)
(= (loyal-faction *player*) +faction-type-church+))
t
nil)))
(trigger-game-over world
:final-str "Demonic theivery attempt prevented."
:score (calculate-player-score (+ 1400 (if (not (mimic-id-list *player*))
0
(loop for mimic-id in (mimic-id-list *player*)
for mimic = (get-mob-by-id mimic-id)
with cur-score = 0
when (not (eq mimic *player*))
do
(incf cur-score (cur-score mimic))
finally (return cur-score)))))
:if-player-won if-player-won
:player-msg (if if-player-won
(format nil "Congratulations! Your faction has won!~%")
(format nil "Curses! Your faction has lost!~%"))
:game-over-type :game-over-church-won))
)))
(set-game-event (make-instance 'game-event :id +game-event-demon-steal-win-for-satanists+
:descr-func #'(lambda ()
"To win, capture the relic in the church and throw it into a demonic portal (use your ability for that). To lose, get all satanists and demons killed.")
:disabled nil
:on-check #'(lambda (world)
(if (and (= (loyal-faction *player*) +faction-type-satanists+)
(> (nth +faction-type-satanists+ (total-faction-list (level world))) 0)
(get-demon-steal-check-relic-captured world))
t
nil))
:on-trigger #'(lambda (world)
(let ((if-player-won (if (or (= (loyal-faction *player*) +faction-type-demons+)
(= (loyal-faction *player*) +faction-type-satanists+))
t
nil)))
(trigger-game-over world
:final-str "Relic sucessfully captured."
:score (calculate-player-score 1450)
:if-player-won if-player-won
:player-msg (if if-player-won
(format nil "Congratulations! Your faction has won!~%")
(format nil "Curses! Your faction has lost!~%"))
:game-over-type :game-over-satanists-won))
)))
| 15,212
|
Common Lisp
|
.lisp
| 141
| 36.843972
| 211
| 0.246996
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
7ea14cf0be85ddefc077aa59f6fa8f9d5f14635ca157806c2754f16e3215ed45
| 2,909
|
[
-1
] |
2,910
|
init-game-events-angelic-steal.lisp
|
gwathlobal_CotD/src/game-events/init-game-events-angelic-steal.lisp
|
(in-package :cotd)
;;===========================
;; WIN EVENTS
;;===========================
(set-game-event (make-instance 'game-event :id +game-event-angelic-steal-win-for-angels+
:descr-func #'(lambda ()
"To win, capture the relic in the corrupted shrine and get to the edge of the map with it. To lose, have all angels killed.")
:disabled nil
:on-check #'(lambda (world)
(if (and (get-angel-steal-angel-with-relic world)
(or (<= (x (get-angel-steal-angel-with-relic world)) 1)
(>= (x (get-angel-steal-angel-with-relic world)) (- (array-dimension (terrain (level world)) 0) 2))
(<= (y (get-angel-steal-angel-with-relic world)) 1)
(>= (y (get-angel-steal-angel-with-relic world)) (- (array-dimension (terrain (level world)) 1) 2))))
t
nil))
:on-trigger #'(lambda (world)
(let ((if-player-won (if (or (= (loyal-faction *player*) +faction-type-angels+)
(= (loyal-faction *player*) +faction-type-church+))
t
nil)))
(trigger-game-over world
:final-str "Relic sucessfully returned."
:score (calculate-player-score (+ 1400 (if (not (mimic-id-list *player*))
0
(loop for mimic-id in (mimic-id-list *player*)
for mimic = (get-mob-by-id mimic-id)
with cur-score = 0
when (not (eq mimic *player*))
do
(incf cur-score (cur-score mimic))
finally (return cur-score)))))
:if-player-won if-player-won
:player-msg (if if-player-won
(format nil "Congratulations! Your faction has won!~%")
(format nil "Curses! Your faction has lost!~%"))
:game-over-type :game-over-angels-won))
)))
(set-game-event (make-instance 'game-event :id +game-event-angelic-steal-win-for-demons+
:descr-func #'(lambda ()
"To win, destroy all angels & military in the district. To lose, have all demons killed or let the angels take the relic and escape with it.")
:disabled nil
:on-check #'(lambda (world)
(if (or (and (= (loyal-faction *player*) +faction-type-demons+)
(> (total-demons (level world)) 0)
(zerop (total-angels (level world))))
(and (/= (loyal-faction *player*) +faction-type-demons+)
(> (total-demons (level world)) 0)
(zerop (nth +faction-type-military+ (total-faction-list (level world))))
(zerop (nth +faction-type-church+ (total-faction-list (level world))))
(zerop (total-angels (level world)))))
t
nil))
:on-trigger #'(lambda (world)
(let ((if-player-won (if (or (= (loyal-faction *player*) +faction-type-demons+)
(= (loyal-faction *player*) +faction-type-satanists+))
t
nil)))
(trigger-game-over world
:final-str "Angelic retrieval attempt prevented."
:score (calculate-player-score 1350)
:if-player-won if-player-won
:player-msg (if if-player-won
(format nil "Congratulations! Your faction has won!~%")
(format nil "Curses! Your faction has lost!~%"))
:game-over-type :game-over-demons-won))
)))
(set-game-event (make-instance 'game-event :id +game-event-angelic-steal-win-for-military+
:descr-func #'(lambda ()
(format nil "To win, destroy all demons in the district. To lose, have all military killed."))
:disabled nil
:on-check #'(lambda (world)
(if (and (> (total-humans (level world)) 0)
(zerop (total-demons (level world))))
t
nil))
:on-trigger #'(lambda (world)
(let ((if-player-won (if (= (loyal-faction *player*) +faction-type-military+)
t
nil)))
(trigger-game-over world
:final-str "Enemies eliminated."
:score (calculate-player-score (+ 1500 (* 7 (total-humans (level world)))))
:if-player-won if-player-won
:player-msg (if if-player-won
(format nil "Congratulations! Your faction has won!~%")
(format nil "Curses! Your faction has lost!~%"))
:game-over-type :game-over-military-won))
)))
(set-game-event (make-instance 'game-event :id +game-event-angelic-steal-win-for-satanists+
:descr-func #'(lambda ()
"To win, destroy all angels & military in the district. To lose, have all demons & satanists killed or let the angels take the relic and escape with it.")
:disabled nil
:on-check #'(lambda (world)
(if (and (= (loyal-faction *player*) +faction-type-satanists+)
(> (nth +faction-type-satanists+ (total-faction-list (level world))) 0)
(zerop (total-angels (level world))))
t
nil)
)
:on-trigger #'(lambda (world)
(let ((if-player-won (if (or (= (loyal-faction *player*) +faction-type-demons+)
(= (loyal-faction *player*) +faction-type-satanists+))
t
nil)))
(trigger-game-over world
:final-str "Angelic retrieval attempt prevented."
:score (calculate-player-score 1350)
:if-player-won if-player-won
:player-msg (if if-player-won
(format nil "Congratulations! Your faction has won!~%")
(format nil "Curses! Your faction has lost!~%"))
:game-over-type :game-over-satanists-won))
)))
| 12,121
|
Common Lisp
|
.lisp
| 114
| 38.27193
| 213
| 0.25829
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
fa9bd8a0d674865782712ccbab6acb60c38eaf50da4342aa018a63fcb6805d8a
| 2,910
|
[
-1
] |
2,911
|
init-game-events-demonic-conquest.lisp
|
gwathlobal_CotD/src/game-events/init-game-events-demonic-conquest.lisp
|
(in-package :cotd)
;;===========================
;; WIN EVENTS
;;===========================
(set-game-event (make-instance 'game-event :id +game-event-demon-conquest-win-for-angels+
:descr-func #'(lambda ()
(multiple-value-bind (sigils-num max-turns) (values-list (win-condition/win-formula (get-win-condition-by-id :win-cond-demonic-conquest)))
(format nil "To win, destroy all demons in the district. To lose, have all angels killed or let the demons create ~A demonic sigils and let them charge for ~A turns." sigils-num max-turns)))
:disabled nil
:on-check #'(lambda (world)
(if (or (and (= (loyal-faction *player*) +faction-type-angels+)
(> (total-angels (level world)) 0)
(zerop (total-demons (level world))))
(and (/= (loyal-faction *player*) +faction-type-angels+)
(zerop (nth +faction-type-satanists+ (total-faction-list (level world))))
(> (total-angels (level world)) 0)
(zerop (total-demons (level world)))))
t
nil))
:on-trigger #'(lambda (world)
(let ((if-player-won (if (or (= (loyal-faction *player*) +faction-type-angels+)
(= (loyal-faction *player*) +faction-type-church+))
t
nil)))
(trigger-game-over world
:final-str "Demonic conquest prevented."
:score (calculate-player-score (+ 1400 (if (not (mimic-id-list *player*))
0
(loop for mimic-id in (mimic-id-list *player*)
for mimic = (get-mob-by-id mimic-id)
with cur-score = 0
when (not (eq mimic *player*))
do
(incf cur-score (cur-score mimic))
finally (return cur-score)))))
:if-player-won if-player-won
:player-msg (if if-player-won
(format nil "Congratulations! Your faction has won!~%")
(format nil "Curses! Your faction has lost!~%"))
:game-over-type :game-over-angels-won))
)))
(set-game-event (make-instance 'game-event :id +game-event-demon-conquest-win-for-demons+
:descr-func #'(lambda ()
(multiple-value-bind (sigils-num max-turns) (values-list (win-condition/win-formula (get-win-condition-by-id :win-cond-demonic-conquest)))
(format nil "To win, create at least ~A demonic sigils (using your ability) and let them charge for ~A turns. To lose, have all demons killed." sigils-num max-turns)))
:disabled nil
:on-check #'(lambda (world)
(multiple-value-bind (sigils-num max-turns) (values-list (win-condition/win-formula (get-win-condition-by-id :win-cond-demonic-conquest)))
(if (and (> (total-demons (level world)) 0)
(get-demon-conquest-turns-left world)
(>= (length (demonic-sigils (level world))) sigils-num)
(>= (get-demon-conquest-turns-left world) max-turns))
t
nil)))
:on-trigger #'(lambda (world)
(let ((if-player-won (if (or (= (loyal-faction *player*) +faction-type-demons+)
(= (loyal-faction *player*) +faction-type-satanists+))
t
nil)))
(trigger-game-over world
:final-str "District successfully conquered by demons."
:score (calculate-player-score 1500)
:if-player-won if-player-won
:player-msg (if if-player-won
(format nil "Congratulations! Your faction has won!~%")
(format nil "Curses! Your faction has lost!~%"))
:game-over-type :game-over-demons-won))
)))
(set-game-event (make-instance 'game-event :id +game-event-demon-conquest-win-for-military+
:descr-func #'(lambda ()
(multiple-value-bind (sigils-num max-turns) (values-list (win-condition/win-formula (get-win-condition-by-id :win-cond-demonic-conquest)))
(format nil "To win, destroy all demons in the district. To lose, have all military killed or let the demons create ~A demonic sigils and let them charge for ~A turns." sigils-num max-turns)))
:disabled nil
:on-check #'(lambda (world)
(if (and (> (total-humans (level world)) 0)
(zerop (total-demons (level world))))
t
nil))
:on-trigger #'(lambda (world)
(let ((if-player-won (if (= (loyal-faction *player*) +faction-type-military+)
t
nil)))
(trigger-game-over world
:final-str "Demonic conquest prevented."
:score (calculate-player-score (+ 1450 (* 7 (total-humans (level world)))))
:if-player-won if-player-won
:player-msg (if if-player-won
(format nil "Congratulations! Your faction has won!~%")
(format nil "Curses! Your faction has lost!~%"))
:game-over-type :game-over-military-won))
)))
(set-game-event (make-instance 'game-event :id +game-event-demon-conquest-win-for-church+
:descr-func #'(lambda ()
(multiple-value-bind (sigils-num max-turns) (values-list (win-condition/win-formula (get-win-condition-by-id :win-cond-demonic-conquest)))
(format nil "To win, destroy all demons in the district. To lose, get all priests and angels killed or let the demons create ~A demonic sigils and let them charge for ~A turns." sigils-num max-turns)))
:disabled nil
:on-check #'(lambda (world)
(if (and (= (loyal-faction *player*) +faction-type-church+)
(> (nth +faction-type-church+ (total-faction-list (level world))) 0)
(zerop (total-demons (level world))))
t
nil))
:on-trigger #'(lambda (world)
(let ((if-player-won (if (or (= (loyal-faction *player*) +faction-type-angels+)
(= (loyal-faction *player*) +faction-type-church+))
t
nil)))
(trigger-game-over world
:final-str "Demonic conquest prevented."
:score (calculate-player-score (+ 1400 (if (not (mimic-id-list *player*))
0
(loop for mimic-id in (mimic-id-list *player*)
for mimic = (get-mob-by-id mimic-id)
with cur-score = 0
when (not (eq mimic *player*))
do
(incf cur-score (cur-score mimic))
finally (return cur-score)))))
:if-player-won if-player-won
:player-msg (if if-player-won
(format nil "Congratulations! Your faction has won!~%")
(format nil "Curses! Your faction has lost!~%"))
:game-over-type :game-over-church-won))
)))
(set-game-event (make-instance 'game-event :id +game-event-demon-conquest-win-for-satanists+
:descr-func #'(lambda ()
(multiple-value-bind (sigils-num max-turns) (values-list (win-condition/win-formula (get-win-condition-by-id :win-cond-demonic-conquest)))
(format nil "To win, create at least ~A demonic sigils (using your ability) and let them charge for ~A turns. To lose, get all satanists and demons killed." sigils-num max-turns)))
:disabled nil
:on-check #'(lambda (world)
(multiple-value-bind (sigils-num max-turns) (values-list (win-condition/win-formula (get-win-condition-by-id :win-cond-demonic-conquest)))
(if (and (= (loyal-faction *player*) +faction-type-satanists+)
(> (nth +faction-type-satanists+ (total-faction-list (level world))) 0)
(get-demon-conquest-turns-left world)
(>= (length (demonic-sigils (level world))) sigils-num)
(>= (get-demon-conquest-turns-left world) max-turns))
t
nil)))
:on-trigger #'(lambda (world)
(let ((if-player-won (if (or (= (loyal-faction *player*) +faction-type-demons+)
(= (loyal-faction *player*) +faction-type-satanists+))
t
nil)))
(trigger-game-over world
:final-str "District successfully conquered by demons."
:score (calculate-player-score 1500)
:if-player-won if-player-won
:player-msg (if if-player-won
(format nil "Congratulations! Your faction has won!~%")
(format nil "Curses! Your faction has lost!~%"))
:game-over-type :game-over-satanists-won))
)))
| 17,404
|
Common Lisp
|
.lisp
| 152
| 43.861842
| 262
| 0.280587
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
98b29b31f0b14bf6b492d5f7fcfe392a29230fe2d3a1937cc654820fbaa858ea
| 2,911
|
[
-1
] |
2,912
|
window-campaign-over.lisp
|
gwathlobal_CotD/src/windows/window-campaign-over.lisp
|
(in-package :cotd)
(defclass campaign-over-window (window)
((campaign-over-type :initarg :campaign-over-type :accessor campaign-over-window/campaign-over-type :type campaign-over-enum)
(player-won :initform nil :initarg :player-won :accessor campaign-over-window/player-won)))
(defmethod make-output ((win campaign-over-window))
;; fill the screen black
(sdl:with-rectangle (a-rect (sdl:rectangle :x 0 :y 0 :w *window-width* :h *window-height*))
(sdl:fill-surface sdl:*black* :template a-rect))
(with-slots (player-won campaign-over-type) win
;; set up all strings
(let ((header-str (create-string))
(long-text)
(max-lines)
(color)
(prompt-str))
(if player-won
(progn
(format header-str "VICTORY! ")
(setf color sdl:*green*))
(progn
(format header-str "DEFEAT! ")
(setf color sdl:*red*)))
(case campaign-over-type
(:campaign-over-demons-conquer (progn
(format header-str "THE PANDEMONIUM HIERARCHY WON")
(setf long-text (format nil "The Firstborn have conquered the entire city and reshaped it into their own bastion on Earth. The human armies are crushed and the Thirdborn do not dare to attack any more. For now, the hostilities are over as no one is left to oppose the forces of Hell but for how long..."))))
(:campaign-over-demons-gather (progn
(format header-str "THE PANDEMONIUM HIERARCHY WON")
(setf long-text (format nil "The Firstborn have gathered enough flesh for their nefarious purposes and have withdrawn into their own hellish dimension. The humankind can now reclaim the City back and try to forget the horrors that transpired there. But the portals to the world of humans are not completely shut and may open one day again..."))))
(:campaign-over-angels-won (progn
(format header-str "THE CELESTIAL COMMUNION WON")
(setf long-text (format nil "The Thirdborn were able to destroy the hellish machines of the Pandemonium Hierarchy and close the Prison Dimension. Those forces of Hell left on Earth were eventually slain by the humans. The Communion once again stands vigil to keep the malformed Firstborn inside the confines designated by the One."))))
(:campaign-over-military-won (progn
(format header-str "THE MILITARY WON")
(setf long-text (format nil "The humans managed to fend off the hellish invaders and hunt down the traitors who aided them into our world. The scars of the Otherworldly War run deep and the humankind is shaken by the cosmic truth that was revealed to it..."))))
)
(setf prompt-str (format nil "[Esc] Main menu"))
;; display header
(sdl:draw-string-solid-* header-str (truncate *window-width* 2) 10 :justify :center :color color)
;; display ending text
(sdl:with-rectangle (a-rect (sdl:rectangle :x 30 :y 30 :w (- *window-width* 60) :h (* 1 (sdl:get-font-height))))
(setf max-lines (write-text long-text a-rect :count-only t)))
(sdl:with-rectangle (a-rect (sdl:rectangle :x 30 :y 30 :w (- *window-width* 60) :h (* max-lines (sdl:get-font-height))))
(write-text long-text a-rect))
;; display prompt
(sdl:draw-string-solid-* prompt-str
10 (- *window-height* 13 (sdl:char-height sdl:*default-font*)))
)
)
(sdl:update-display))
(defmethod run-window ((win campaign-over-window))
(sdl:with-events ()
(:quit-event () (funcall (quit-func win)) t)
(:key-down-event (:key key :mod mod :unicode unicode)
(declare (ignore mod unicode))
(cond
;; escape - return to main menu
((sdl:key= key :sdl-key-escape)
(when (game-manager/game-slot-id *game-manager*)
(let* ((final-save-name (format nil "~A~A" *save-final-base-dirname* (game-manager/game-slot-id *game-manager*)))
(dir-pathname (merge-pathnames (make-pathname :directory `(:relative ,final-save-name)) (find-save-game-path :save-game-campaign)))
(descr-pathname (merge-pathnames (make-pathname :name *save-descr-filename*) dir-pathname))
(dir-to-delete (make-pathname :host (pathname-host descr-pathname)
:device (pathname-device descr-pathname)
:directory (pathname-directory descr-pathname)))
(result))
(setf result (delete-dir-from-disk dir-to-delete))
(when (not result)
(setf *current-window* (make-instance 'display-msg-window
:msg-line "An error has occured while the system tried to remove the game!"))
(make-output *current-window*)
(run-window *current-window*))))
(game-state-post-scenario->menu)
(go-to-start-game)
)
)
)
(:video-expose-event () (make-output *current-window*))))
| 5,606
|
Common Lisp
|
.lisp
| 78
| 53.833333
| 379
| 0.576622
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
c1844d714930da72128e0166ddb5ee0156c4b793972626e3614950daea37307e
| 2,912
|
[
-1
] |
2,913
|
window-display-msg.lisp
|
gwathlobal_CotD/src/windows/window-display-msg.lisp
|
(in-package :cotd)
(defclass display-msg-window (window)
((msg-line :initarg :msg-line :accessor display-msg-window/msg-line :type string)
(x :initform nil :initarg :x :accessor display-msg-window/x)
(y :initform nil :initarg :y :accessor display-msg-window/y)
(w :initform nil :initarg :w :accessor display-msg-window/w)
(h-txt :initform nil :accessor display-msg-window/h-txt)
(prompt-line :initform "[Space] Ok" :initarg :prompt-line :accessor display-msg-window/prompt-line :type string)
(cur-str :initform 0 :accessor display-msg-window/cur-str)
(margin :initform 4 :accessor display-msg-window/margin :type fixnum)
))
(defmethod initialize-instance :after ((win display-msg-window) &key)
(with-slots (msg-line prompt-line x y w h-txt cur-str margin) win
(let ((max-str)
(max-w 330))
(unless w
(setf w max-w))
(sdl:with-rectangle (rect (sdl:rectangle :x 0 :y 0 :w (- w margin margin) :h 30))
(setf max-str (write-text msg-line rect :count-only t))
;(when (< max-str (+ cur-str (truncate (sdl:height rect) (sdl:char-height sdl:*default-font*))))
; (setf cur-str (- max-str (truncate (sdl:height rect) (sdl:char-height sdl:*default-font*)))))
(when (< cur-str 0)
(setf cur-str 0))
(when (= max-str 1)
(setf w (loop with max = max-w
for str in (list msg-line prompt-line)
for try-max = (+ 10 (* (sdl:char-width sdl:*default-font*) (length str)))
when (> try-max max) do
(setf max try-max)
finally (return-from nil max))))
(setf h-txt (* (sdl:char-height sdl:*default-font*) max-str))
(unless x
(setf x (- (truncate *window-width* 2) (truncate w 2) margin)))
(unless y
(setf y (- (truncate *window-height* 2) (truncate h-txt 2) margin)))
))))
(defmethod make-output ((win display-msg-window))
(with-slots (msg-line prompt-line x y w margin h-txt) win
(let* ((h-prompt (sdl:char-height sdl:*default-font*))
(x-txt-rect x)
(y-txt-rect y)
(w-txt-rect w)
(h-txt-rect (+ h-txt margin margin))
(x-txt-text (+ x-txt-rect margin))
(y-txt-text (+ y-txt-rect margin))
(w-txt-text (- w-txt-rect margin margin))
(h-txt-text (- h-txt-rect margin margin))
(y-prompt-rect (+ y-txt-rect h-txt-rect -1))
(h-prompt-rect (+ h-prompt margin margin))
(y-prompt-text (+ y-prompt-rect margin))
(h-prompt-text (- h-prompt-rect margin margin))
)
;; draw rectangle for text
(sdl:with-rectangle (rect (sdl:rectangle :x x-txt-rect :y y-txt-rect :w w-txt-rect :h h-txt-rect))
(sdl:fill-surface sdl:*black* :template rect)
(sdl:draw-rectangle rect :color sdl:*white*))
;; draw text
(sdl:with-rectangle (rect (sdl:rectangle :x x-txt-text :y y-txt-text :w w-txt-text :h h-txt-text))
(write-text msg-line rect :start-line (display-msg-window/cur-str win)))
;; draw rectangle for prompt
(sdl:with-rectangle (rect (sdl:rectangle :x x-txt-rect :y y-prompt-rect :w w-txt-rect :h h-prompt-rect))
(sdl:fill-surface sdl:*black* :template rect)
(sdl:draw-rectangle rect :color sdl:*white*))
;; draw prompt
(sdl:with-rectangle (rect (sdl:rectangle :x x-txt-text :y y-prompt-text :w w-txt-text :h h-prompt-text))
(write-text prompt-line rect :start-line 0))
))
(sdl:update-display))
(defmethod run-window ((win display-msg-window))
(sdl:with-events ()
(:quit-event () (funcall (quit-func win)) t)
(:key-down-event (:key key :mod mod :unicode unicode)
(declare (ignore mod unicode))
(cond
;; escape - quit with nil
((sdl:key= key :sdl-key-escape) (progn
(setf *current-window* (return-to win))
(make-output *current-window*)
(return-from run-window nil)))
;; space, enter - quit with t
((or (sdl:key= key :sdl-key-space) (sdl:key= key :sdl-key-return) (sdl:key= key :sdl-key-kp-enter)) (progn
(setf *current-window* (return-to win))
(make-output *current-window*)
(return-from run-window t))))
(make-output *current-window*)
)
(:video-expose-event () (make-output *current-window*))))
| 5,152
|
Common Lisp
|
.lisp
| 87
| 42.022989
| 164
| 0.525101
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
ec2e62bdadbec4eb5f0f6d932133e04bab93cfccd9359dd9b00eab4659990163
| 2,913
|
[
-1
] |
2,914
|
window-input-str.lisp
|
gwathlobal_CotD/src/windows/window-input-str.lisp
|
(in-package :cotd)
(defclass input-str-window (window)
((input :initform (make-array '(0) :element-type 'character :adjustable t :fill-pointer t) :accessor input)
(max-w :initform 0 :accessor max-w)
(init-input :initform nil :initarg :init-input :accessor init-input)
(header-str :initarg :header-str :accessor header-str)
(main-str :initarg :main-str :accessor main-str)
(prompt-str :initarg :prompt-str :accessor prompt-str)
(all-func :initform nil :initarg :all-func :accessor all-func) ;; a function that takes no args and returns a string with a predefined value that means "all" in the context
(input-check-func :initform #'(lambda (char cur-str) (declare (ignore char cur-str)) t) :initarg :input-check-func :accessor input-check-func)
(final-check-func :initform nil :initarg :final-check-func :accessor final-check-func) ;; a funcation that takes the full input string and checks if its value is valid in the context before the window can return it
(no-escape :initform nil :initarg :no-escape :accessor no-escape))
)
(defmethod initialize-instance :after ((win input-str-window) &key)
(when (init-input win)
;(vector-push-extend (init-input win) (input win))
(setf (input win) (make-array (list (length (init-input win))) :element-type 'character :adjustable t :fill-pointer t :initial-contents (init-input win)))))
(defmethod make-output ((win input-str-window))
(let* ((w (if (> (+ 10 (* (max (length (header-str win)) (length (format nil "~A: ~A" (main-str win) (input win))) (length (prompt-str win))) (sdl:char-width sdl:*default-font*)))
(max-w win))
(+ 10 (* (max (length (header-str win)) (length (format nil "~A: ~A" (main-str win) (input win))) (length (prompt-str win))) (sdl:char-width sdl:*default-font*)))
(max-w win)))
(h (+ 11 (* (sdl:char-height sdl:*default-font*) 3)))
(x (- (truncate *window-width* 2) (truncate w 2)))
(y (- (truncate *window-height* 2) (truncate h 2))))
(setf (max-w win) w)
;; drawing a large rectangle in white
(sdl:with-rectangle (a-rect (sdl:rectangle :x x :y y :w w :h h))
(sdl:fill-surface sdl:*white* :template a-rect))
;; drawing a smaller rectanagle in black to make a 1 pixel width border
(sdl:with-rectangle (a-rect (sdl:rectangle :x (1+ x) :y (1+ y) :w (- w 2) :h (- h 2)))
(sdl:fill-surface sdl:*black* :template a-rect))
;; drawing a line to separate the header and main string
(sdl:with-rectangle (a-rect (sdl:rectangle :x x :y (+ y 3 (* (sdl:char-height sdl:*default-font*) 1)) :w w :h 1))
(sdl:fill-surface sdl:*white* :template a-rect))
;; drawing a line to separate the prompt and main string
(sdl:with-rectangle (a-rect (sdl:rectangle :x x :y (+ y 6 (* (sdl:char-height sdl:*default-font*) 2)) :w w :h 1))
(sdl:fill-surface sdl:*white* :template a-rect))
(sdl:draw-string-solid-* (header-str win) (+ x 5) (+ y 1) :color sdl:*white*)
(sdl:draw-string-solid-* (format nil "~A: ~A" (main-str win) (input win)) (+ x 5) (+ y 4 (* (sdl:char-height sdl:*default-font*) 1)) :color sdl:*white*)
(sdl:draw-string-solid-* (prompt-str win) (+ x 5) (+ y 8 (* (sdl:char-height sdl:*default-font*) 2)) :color sdl:*white*)
(sdl:update-display)))
(defmethod run-window ((win input-str-window))
(sdl:with-events ()
(:quit-event () (funcall (quit-func win)) t)
(:key-down-event (:key key :mod mod :unicode unicode)
;; normalize mod
(loop while (>= mod sdl-key-mod-num) do
(decf mod sdl-key-mod-num))
(cond
((and (not (no-escape win)) (sdl:key= key :sdl-key-escape))
(setf *current-window* (return-to win)) (make-output *current-window*) (return-from run-window nil))
((sdl:key= key :sdl-key-backspace) (when (> (fill-pointer (input win)) 0) (decf (fill-pointer (input win)))))
;; a - select all
((and (all-func win) (sdl:key= key :sdl-key-a) (= mod 0)) (setf (fill-pointer (input win)) 0) (format (input win) "~A" (funcall (all-func win))))
;; enter - confirm
((or (sdl:key= key :sdl-key-return) (sdl:key= key :sdl-key-kp-enter))
(when (and (not (zerop (length (input win))))
(or (null (final-check-func win))
(and (final-check-func win)
(funcall (final-check-func win) (input win)))))
(setf *current-window* (return-to win))
(make-output *current-window*)
(return-from run-window (input win))))
(t (when (funcall (input-check-func win) (code-char unicode) (input win))
(setf (input win) (get-text-input (input win) key mod unicode)))
))
(make-output *current-window*))
(:video-expose-event () (make-output *current-window*)))
)
| 5,176
|
Common Lisp
|
.lisp
| 70
| 61.542857
| 217
| 0.586037
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
adad00220ed3eb8ea8f24120bab5b3cff84750e4cb53bd919760a55eed0b422e
| 2,914
|
[
-1
] |
2,915
|
window-select-faction.lisp
|
gwathlobal_CotD/src/windows/window-select-faction.lisp
|
(in-package :cotd)
(defclass select-faction-window (window)
((menu-items :initarg :menu-items :accessor select-faction-window/menu-items)
(menu-descrs :initarg :menu-descrs :accessor select-faction-window/menu-descrs)
(cur-sel :initform 0 :accessor select-faction-window/cur-sel)
(max-menu-length :initform (truncate (- (/ *window-height* 2) 60) (sdl:char-height sdl:*default-font*)) :initarg :max-menu-length :accessor select-faction-window/max-menu-length)
(window-title :initform "QUICK SCENARIO" :initarg :window-title :accessor select-faction-window/window-title)
(window-subtitle :initform "Choose your faction & character:" :initarg :window-subtitle :accessor select-faction-window/window-subtitle)
))
(defmethod make-output ((win select-faction-window))
(with-slots (window-title window-subtitle cur-sel menu-descrs menu-items max-menu-length) win
(sdl:with-rectangle (a-rect (sdl:rectangle :x 0 :y 0 :w *window-width* :h *window-height*))
(sdl:fill-surface sdl:*black* :template a-rect))
(sdl:draw-string-solid-* window-title (truncate *window-width* 2) 0 :justify :center :color sdl:*white*)
(sdl:draw-string-solid-* window-subtitle
10 (+ 10 (sdl:char-height sdl:*default-font*)))
;; drawing selection list
(let ((color-list nil))
;;(format t "max-menu-length = ~A, cur-str ~A~%" (max-menu-length win) (cur-sel win))
(dotimes (i (length menu-items))
;; choose the description
;;(setf lst (append lst (list (aref (line-array win) i))))
(if (= i cur-sel)
(setf color-list (append color-list (list sdl:*yellow*)))
(setf color-list (append color-list (list sdl:*white*)))))
(draw-selection-list menu-items cur-sel max-menu-length 20 (+ 30 (sdl:char-height sdl:*default-font*)) :color-list color-list :use-letters t))
;; drawing selection description
(let ((descr (nth cur-sel menu-descrs)))
(sdl:with-rectangle (rect (sdl:rectangle :x 20 :y (+ (truncate *window-height* 2) 0)
:w (- *window-width* 40)
:h (- (truncate *window-height* 2) 20 0 (sdl:char-height sdl:*default-font*))))
(write-text descr rect :start-line 0)))
(sdl:draw-string-solid-* (format nil "[Enter] Select [Up/Down] Move selection [Shift+Up/Down] Scroll page [Esc] Exit")
10 (- *window-height* 10 (sdl:char-height sdl:*default-font*)))
(sdl:update-display)))
(defmethod run-window ((win select-faction-window))
(with-slots (quit-func return-to cur-sel menu-items max-menu-length) win
(sdl:with-events ()
(:quit-event () (funcall quit-func) t)
(:key-down-event (:key key :mod mod :unicode unicode)
(setf cur-sel (run-selection-list key mod unicode cur-sel :start-page (truncate cur-sel (length menu-items)) :max-str-per-page max-menu-length))
(setf cur-sel (adjust-selection-list cur-sel (length menu-items)))
(cond
;; escape - quit
((sdl:key= key :sdl-key-escape)
(setf *current-window* return-to)
(return-from run-window nil))
;; enter - select
((or (sdl:key= key :sdl-key-return) (sdl:key= key :sdl-key-kp-enter))
(return-from run-window cur-sel)
))
(make-output *current-window*))
(:video-expose-event () (make-output *current-window*)))))
(defun quick-scenario-menu-items ()
(let ((menu-items nil)
(menu-funcs nil)
(menu-descrs nil)
(join-heaven-item (list "Join the Celestial Communion (as a Chrome angel)"
#'(lambda (n)
(declare (ignore n))
(multiple-value-bind (mission world-sector) (find-random-scenario-options +specific-faction-type-angel-chrome+)
(when (and mission world-sector)
(values world-sector mission)))
)
(get-txt-from-file "data/descriptions/communion_chrome.txt")))
(join-trinity-item (list "Join the Celestial Communion (as a Trinity mimic)"
#'(lambda (n)
(declare (ignore n))
(multiple-value-bind (mission world-sector) (find-random-scenario-options +specific-faction-type-angel-trinity+)
(when (and mission world-sector)
(values world-sector mission)))
)
(get-txt-from-file "data/descriptions/communion_trinity.txt")))
(join-legion-item (list "Join the Pandemonium Hierarchy (as a Crimson imp)"
#'(lambda (n)
(declare (ignore n))
(multiple-value-bind (mission world-sector) (find-random-scenario-options +specific-faction-type-demon-crimson+)
(when (and mission world-sector)
(values world-sector mission)))
)
(get-txt-from-file "data/descriptions/pandemonium_crimsonimp.txt")))
(join-shadow-item (list "Join the Pandemonium Hierarchy (as a Shadow imp)"
#'(lambda (n)
(declare (ignore n))
;; start in the evening
(let ((lvl-mod-list (append (list (get-level-modifier-by-id +lm-tod-evening+))
(remove :level-mod-tod (get-all-lvl-mods-list) :key #'(lambda (a)
(lm-type a))))))
(multiple-value-bind (mission world-sector) (find-random-scenario-options +specific-faction-type-demon-shadow+ :avail-lvl-mods-list lvl-mod-list)
(when (and mission world-sector)
(values world-sector mission))))
)
(get-txt-from-file "data/descriptions/pandemonium_shadowimp.txt")))
(join-puppet-item (list "Join the Pandemonium Hierarchy (as Malseraph's puppet)"
#'(lambda (n)
(declare (ignore n))
(multiple-value-bind (mission world-sector) (find-random-scenario-options +specific-faction-type-demon-malseraph+)
(when (and mission world-sector)
(values world-sector mission)))
)
(get-txt-from-file "data/descriptions/pandemonium_puppet.txt")))
(join-chaplain-item (list "Join the Military (as a Chaplain)"
#'(lambda (n)
(declare (ignore n))
(multiple-value-bind (mission world-sector) (find-random-scenario-options +specific-faction-type-military-chaplain+)
(when (and mission world-sector)
(values world-sector mission)))
)
(get-txt-from-file "data/descriptions/military_chaplain.txt")))
(join-scout-item (list "Join the Military (as a Scout)"
#'(lambda (n)
(declare (ignore n))
(multiple-value-bind (mission world-sector) (find-random-scenario-options +specific-faction-type-military-scout+)
(when (and mission world-sector)
(values world-sector mission)))
)
(get-txt-from-file "data/descriptions/military_scout.txt")))
(join-thief-item (list "Join as the Thief"
#'(lambda (n)
(declare (ignore n))
;; start in the evening
(let ((lvl-mod-list (append (list (get-level-modifier-by-id +lm-tod-evening+))
(remove :level-mod-tod (get-all-lvl-mods-list) :key #'(lambda (a)
(lm-type a))))))
(multiple-value-bind (mission world-sector) (find-random-scenario-options +specific-faction-type-thief+ :avail-lvl-mods-list lvl-mod-list)
(when (and mission world-sector)
(values world-sector mission))))
)
(get-txt-from-file "data/descriptions/criminals.txt")))
(join-satanist-item (list "Join the Satanists"
#'(lambda (n)
(declare (ignore n))
(multiple-value-bind (mission world-sector) (find-random-scenario-options +specific-faction-type-satanist+)
(when (and mission world-sector)
(values world-sector mission)))
)
(get-txt-from-file "data/descriptions/satanists.txt")))
(join-church-item (list "Join the Church"
#'(lambda (n)
(declare (ignore n))
(multiple-value-bind (mission world-sector) (find-random-scenario-options +specific-faction-type-priest+)
(when (and mission world-sector)
(values world-sector mission)))
)
(get-txt-from-file "data/descriptions/church.txt")))
(join-eater-item (list "Join as the Eater of the dead"
#'(lambda (n)
(declare (ignore n))
;; do not start in the snow
(let ((lvl-mod-list (remove +lm-weather-snow+ (get-all-lvl-mods-list) :key #'(lambda (a)
(lm-type a)))))
(multiple-value-bind (mission world-sector) (find-random-scenario-options +specific-faction-type-eater+ :avail-lvl-mods-list lvl-mod-list)
(when (and mission world-sector)
(values world-sector mission))))
)
(get-txt-from-file "data/descriptions/primordials_eater.txt")))
(join-skin-item (list "Join as the Skinchanger"
#'(lambda (n)
(declare (ignore n))
;; do not start in the snow
(let ((lvl-mod-list (remove +lm-weather-snow+ (get-all-lvl-mods-list) :key #'(lambda (a)
(lm-type a)))))
(multiple-value-bind (mission world-sector) (find-random-scenario-options +specific-faction-type-skinchanger+ :avail-lvl-mods-list lvl-mod-list)
(when (and mission world-sector)
(values world-sector mission))))
)
(get-txt-from-file "data/descriptions/primordials_skinchanger.txt")))
(join-ghost-item (list "Join as the Lost soul"
#'(lambda (n)
(declare (ignore n))
(multiple-value-bind (mission world-sector) (find-random-scenario-options +specific-faction-type-ghost+)
(when (and mission world-sector)
(values world-sector mission)))
)
(get-txt-from-file "data/descriptions/lostsoul.txt")))
)
(setf menu-items (list (first join-heaven-item) (first join-trinity-item) (first join-legion-item) (first join-shadow-item) (first join-puppet-item)
(first join-chaplain-item) (first join-scout-item) (first join-thief-item) (first join-satanist-item) (first join-church-item)
(first join-eater-item) (first join-skin-item) (first join-ghost-item)))
(setf menu-funcs (list (second join-heaven-item) (second join-trinity-item) (second join-legion-item) (second join-shadow-item) (second join-puppet-item)
(second join-chaplain-item) (second join-scout-item) (second join-thief-item) (second join-satanist-item) (second join-church-item)
(second join-eater-item) (second join-skin-item) (second join-ghost-item)))
(setf menu-descrs (list (third join-heaven-item) (third join-trinity-item) (third join-legion-item) (third join-shadow-item) (third join-puppet-item)
(third join-chaplain-item) (third join-scout-item) (third join-thief-item) (third join-satanist-item) (third join-church-item)
(third join-eater-item) (third join-skin-item) (third join-ghost-item)))
(values menu-items menu-funcs menu-descrs)))
(defun new-campaign-menu-items ()
(let ((menu-items nil)
(menu-funcs nil)
(menu-descrs nil)
(join-heaven-item (list "Join the Celestial Communion (as a Chrome angel)"
#'(lambda (n)
(declare (ignore n))
+specific-faction-type-angel-chrome+
)
(get-txt-from-file "data/descriptions/communion_chrome.txt")))
(join-trinity-item (list "Join the Celestial Communion (as a Trinity mimic)"
#'(lambda (n)
(declare (ignore n))
+specific-faction-type-angel-trinity+
)
(get-txt-from-file "data/descriptions/communion_trinity.txt")))
(join-legion-item (list "Join the Pandemonium Hierarchy (as a Crimson imp)"
#'(lambda (n)
(declare (ignore n))
+specific-faction-type-demon-crimson+
)
(get-txt-from-file "data/descriptions/pandemonium_crimsonimp.txt")))
(join-shadow-item (list "Join the Pandemonium Hierarchy (as a Shadow imp)"
#'(lambda (n)
(declare (ignore n))
+specific-faction-type-demon-shadow+
)
(get-txt-from-file "data/descriptions/pandemonium_shadowimp.txt")))
(join-puppet-item (list "Join the Pandemonium Hierarchy (as Malseraph's puppet)"
#'(lambda (n)
(declare (ignore n))
+specific-faction-type-demon-malseraph+
)
(get-txt-from-file "data/descriptions/pandemonium_puppet.txt")))
(join-chaplain-item (list "Join the Military (as a Chaplain)"
#'(lambda (n)
(declare (ignore n))
+specific-faction-type-military-chaplain+
)
(get-txt-from-file "data/descriptions/military_chaplain.txt")))
(join-scout-item (list "Join the Military (as a Scout)"
#'(lambda (n)
(declare (ignore n))
+specific-faction-type-military-scout+
)
(get-txt-from-file "data/descriptions/military_scout.txt")))
)
(setf menu-items (list (first join-heaven-item) (first join-trinity-item) (first join-legion-item) (first join-shadow-item) (first join-puppet-item)
(first join-chaplain-item) (first join-scout-item)))
(setf menu-funcs (list (second join-heaven-item) (second join-trinity-item) (second join-legion-item) (second join-shadow-item) (second join-puppet-item)
(second join-chaplain-item) (second join-scout-item)))
(setf menu-descrs (list (third join-heaven-item) (third join-trinity-item) (third join-legion-item) (third join-shadow-item) (third join-puppet-item)
(third join-chaplain-item) (third join-scout-item)))
(values menu-items menu-funcs menu-descrs)))
| 18,202
|
Common Lisp
|
.lisp
| 240
| 47.304167
| 183
| 0.477993
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
561cc88b66039c7f18a0d26d33f0805d661d11db7369268e136ab408279257ae
| 2,915
|
[
-1
] |
2,916
|
window-journal.lisp
|
gwathlobal_CotD/src/windows/window-journal.lisp
|
(in-package :cotd)
(defclass journal-window (window)
())
(defmethod make-output ((win journal-window))
(fill-background-tiles)
(sdl:draw-string-solid-* "JOURNAL" (truncate *window-width* 2) 0 :justify :center)
(let* ((x 10)
(y (+ 0 (* 2 (sdl:char-height sdl:*default-font*))))
(w (- *window-width* 20))
(h (- *window-height* 20 (sdl:char-height sdl:*default-font*) y))
(txt-struct (make-colored-txt)))
(sdl:with-rectangle (a-rect (sdl:rectangle :x x :y y :w w :h h))
(sdl:fill-surface sdl:*black* :template a-rect)
(when (find (loyal-faction *player*) (win-condition-list (get-mission-type-by-id (mission-type-id (mission (level *world*))))) :key #'(lambda (a)
(first a)))
(add-colored-str txt-struct (format nil "~A~%~%~%" (funcall (descr-func (get-game-event-by-id (second (find (loyal-faction *player*) (win-condition-list (get-mission-type-by-id (mission-type-id (mission (level *world*)))))
:key #'(lambda (a)
(first a)))))))))
)
(add-colored-str txt-struct (format nil "Faction relations~%"))
(loop for faction-type across *faction-types*
when (and faction-type
(not (= (id faction-type) (faction *player*))))
do
(add-colored-str txt-struct (format nil " ~20A : ~A~%" (name faction-type) (if (get-faction-relation (id faction-type) (faction *player*))
"ALLY"
"ENEMY"))))
(write-colored-text (colored-txt-list txt-struct) a-rect))
)
(sdl:draw-string-solid-* (format nil "[Esc] Exit")
10 (- *window-height* 13 (sdl:char-height sdl:*default-font*)))
(sdl:update-display))
(defmethod run-window ((win journal-window))
(sdl:with-events ()
(:quit-event () (funcall (quit-func win)) t)
(:key-down-event (:key key :mod mod :unicode unicode)
(declare (ignore mod unicode))
(cond
((sdl:key= key :sdl-key-escape)
(setf *current-window* (return-to win)) (make-output *current-window*) (return-from run-window nil))
)
(make-output *current-window*))
(:video-expose-event () (make-output *current-window*)))
)
| 2,867
|
Common Lisp
|
.lisp
| 44
| 42.25
| 230
| 0.466619
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
24a26b975e4513e346fcd3dac0c26d5dc756f8796b59ebbdffe4383ea758cac5
| 2,916
|
[
-1
] |
2,917
|
window-level.lisp
|
gwathlobal_CotD/src/windows/window-level.lisp
|
(in-package :cotd)
(defclass cell-window (window)
((shoot-mode :initform :single :accessor shoot-mode)
(idle-calcing :initform :done :accessor idle-calcing) ; :done - background pathfinding calculation finished
; :in-progress - background pathfinding calculation in progress
; :npc-turn - it is not players turn
(max-glyphs :initform 11 :accessor max-glyphs)
))
(defun show-char-effects (mob x y h)
(loop for effect-id being the hash-value in (effects mob)
for effect = (get-effect-by-id effect-id)
with y1 = y
do
(when (and (> (hash-table-count (effects mob)) (truncate h (sdl:get-font-height)))
(> (+ y1 (* 2 (sdl:get-font-height))) (+ y h)))
(sdl:draw-string-solid-* "(...)" x y1 :color sdl:*white*)
(loop-finish))
(sdl:draw-string-solid-* (format nil "~A~A" (name effect) (if (eq (cd effect) t)
""
(format nil " (~A)" (cd effect))))
x y1 :color (funcall (color-func (get-effect-type-by-id (effect-type effect)))
effect
mob))
(incf y1 (sdl:get-font-height))))
(defun show-part-of-level (win win-x win-y x y z)
(with-slots (max-glyphs) win
;; draw a rectangle
(sdl:with-rectangle (rect (sdl:rectangle :x win-x :y win-y :w (* *glyph-w* (+ 1 max-glyphs)) :h (* *glyph-h* (+ 1 max-glyphs))))
(sdl:fill-surface sdl:*black* :template rect)
(sdl:draw-rectangle rect :color sdl:*white*))
;; draw relative level
(let ((str (format nil "~@D" (- z (z *player*))))
(sx (+ 10 win-x))
(sy (- win-y 5)))
(sdl:with-rectangle (rect (sdl:rectangle :x sx :y sy :w (* (sdl:char-width sdl:*default-font*) (length str)) :h (sdl:char-height sdl:*default-font*)))
(sdl:fill-surface sdl:*black* :template rect))
(sdl:draw-string-solid-* str
sx sy :color sdl:*white*))
;; draw map
(update-map-area (+ win-x (truncate *glyph-w* 2)) (+ win-y (truncate *glyph-h* 2)) :rel-x x :rel-y y :rel-z z :max-x-view max-glyphs :max-y-view max-glyphs)
(highlight-map-tile (+ win-x (truncate *glyph-w* 2) (* *glyph-w* (truncate max-glyphs 2))) (+ win-y (truncate *glyph-h* 2) (* *glyph-h* (truncate max-glyphs 2))))
))
(defun show-char-properties (x y idle-calcing)
(let* ((str (create-string))
(str-lines))
(sdl:with-rectangle (a-rect (sdl:rectangle :x x :y y :w (- *window-width* x 10) :h (* *glyph-h* *max-y-view*)))
(sdl:fill-surface sdl:*black* :template a-rect)
;; name
(format str "~A - ~A~%~%" (name *player*) (capitalize-name (name (get-mob-type-by-id (mob-type *player*)))))
;; player stats
(format str "HP: ~A/~A~%"
(cur-hp *player*) (max-hp *player*))
(unless (zerop (max-fp *player*))
(format str "Power: ~A/~A~%" (cur-fp *player*) (max-fp *player*)))
(when (/= (cur-oxygen *player*) *max-oxygen-level*)
(format str "Oxygen: ~A/~A~%" (cur-oxygen *player*) *max-oxygen-level*))
;; god
(when (worshiped-god *player*)
(format str "~A: ~A~%" (name (get-god-by-id (get-worshiped-god-type (worshiped-god *player*)))) (return-piety-str (get-worshiped-god-type (worshiped-god *player*))
(get-worshiped-god-piety (worshiped-god *player*)))))
;; followers
(when (or (mob-ability-p *player* +mob-abil-military-follow-me+)
(mob-ability-p *player* +mob-abil-prayer-bless+))
(format str "Followers: ~A~%" (count-follower-list *player*)))
;; weapon description
(format str "~%~A~%" (get-weapon-descr-line *player*))
;; win condition for demonic attack
(when (or (and (or (= (loyal-faction *player*) +faction-type-demons+)
(= (loyal-faction *player*) +faction-type-angels+)
(= (loyal-faction *player*) +faction-type-military+)
(= (loyal-faction *player*) +faction-type-church+)
(= (loyal-faction *player*) +faction-type-satanists+))
(eq (mission-type-id (mission (level *world*))) :mission-type-demonic-attack))
(eq (mission-type-id (mission (level *world*))) :mission-type-test))
(let ((win-condition (get-win-condition-by-id :win-cond-demonic-attack)))
(format str "~%Civilians left: ~A~%" (funcall (win-condition/win-func win-condition) *world* win-condition)))
)
;; win condition for demonic raid
(when (or (and (or (= (loyal-faction *player*) +faction-type-demons+)
(= (loyal-faction *player*) +faction-type-angels+)
(= (loyal-faction *player*) +faction-type-military+)
(= (loyal-faction *player*) +faction-type-church+)
(= (loyal-faction *player*) +faction-type-satanists+))
(eq (mission-type-id (mission (level *world*))) :mission-type-demonic-raid))
(eq (mission-type-id (mission (level *world*))) :mission-type-test))
(let ((win-formula (win-condition/win-formula (get-win-condition-by-id :win-cond-demonic-raid))))
(format str "~%Flesh left: ~A pts~%" (if (> (- win-formula (get-demon-raid-overall-points *world*)) 0)
(- win-formula (get-demon-raid-overall-points *world*))
0)))
)
;; win condition for thief
(when (and (= (mob-type *player*) +mob-type-thief+)
(not (mob-ability-p *player* +mob-abil-ghost-possess+)))
(let ((win-formula (win-condition/win-formula (get-win-condition-by-id :win-cond-thief))))
(format str "~%Value left: ~A$~%" (if (> (- win-formula (get-overall-value (inv *player*))) 0)
(- win-formula (get-overall-value (inv *player*)))
0))))
;; win condition for demonic conquest
(when (or (and (or (= (loyal-faction *player*) +faction-type-demons+)
(= (loyal-faction *player*) +faction-type-angels+)
(= (loyal-faction *player*) +faction-type-military+)
(= (loyal-faction *player*) +faction-type-church+)
(= (loyal-faction *player*) +faction-type-satanists+))
(eq (mission-type-id (mission (level *world*))) :mission-type-demonic-conquest))
(eq (mission-type-id (mission (level *world*))) :mission-type-test))
(multiple-value-bind (max-sigils max-turns) (values-list (win-condition/win-formula (get-win-condition-by-id :win-cond-demonic-conquest)))
(format str "~%Demonic sigils: ~A/~A (~A)~%" (length (demonic-sigils (level *world*))) max-sigils
(if (>= (length (demonic-sigils (level *world*))) max-sigils)
(format nil "~D turn~:P left" (- max-turns (get-demon-conquest-turns-left *world*)))
"none"))))
;; win condition for celestial purge
(when (or (and (or (= (loyal-faction *player*) +faction-type-demons+)
(= (loyal-faction *player*) +faction-type-angels+)
(= (loyal-faction *player*) +faction-type-military+)
(= (loyal-faction *player*) +faction-type-church+)
(= (loyal-faction *player*) +faction-type-satanists+))
(eq (mission-type-id (mission (level *world*))) :mission-type-celestial-purge))
(eq (mission-type-id (mission (level *world*))) :mission-type-test))
(format str "~%Demonic sigils left: ~A~%" (length (demonic-sigils (level *world*)))))
;; win condition for military conquest
(when (or (and (or (= (loyal-faction *player*) +faction-type-demons+)
(= (loyal-faction *player*) +faction-type-angels+)
(= (loyal-faction *player*) +faction-type-military+)
(= (loyal-faction *player*) +faction-type-satanists+))
(eq (mission-type-id (mission (level *world*))) :mission-type-military-conquest))
(eq (mission-type-id (mission (level *world*))) :mission-type-test))
(let ((max-sigils (win-condition/win-formula (get-win-condition-by-id :win-cond-military-conquest))))
(format str "~%Demonic sigils: ~A/~A~%" (length (demonic-sigils (level *world*))) max-sigils)))
;; win condition for satanist elimination
(when (or (and (or (= (loyal-faction *player*) +faction-type-demons+)
(= (loyal-faction *player*) +faction-type-angels+)
(= (loyal-faction *player*) +faction-type-military+)
(= (loyal-faction *player*) +faction-type-church+)
(= (loyal-faction *player*) +faction-type-satanists+))
(eq (mission-type-id (mission (level *world*))) :mission-type-eliminate-satanists))
(eq (mission-type-id (mission (level *world*))) :mission-type-test))
(format str "~%Satanists left: ~A~%" (nth +faction-type-satanists+ (total-faction-list (level *world*))))
)
;; win condition for celestial sabotage
(when (or (and (or (= (loyal-faction *player*) +faction-type-demons+)
(= (loyal-faction *player*) +faction-type-angels+))
(eq (mission-type-id (mission (level *world*))) :mission-type-celestial-sabotage))
(eq (mission-type-id (mission (level *world*))) :mission-type-test))
(let ((max-machines (win-condition/win-formula (get-win-condition-by-id :win-cond-celestial-sabotage))))
(format str "~%Demonic machines: ~A/~A~%" (length (demonic-machines (level *world*))) max-machines)))
;; win condition for military sabotage
(when (or (and (or (= (loyal-faction *player*) +faction-type-military+)
(= (loyal-faction *player*) +faction-type-angels+))
(eq (mission-type-id (mission (level *world*))) :mission-type-military-sabotage))
(eq (mission-type-id (mission (level *world*))) :mission-type-test))
(format str "~%Raw storages left: ~A~%" (length (bomb-plant-locations (level *world*)))))
;; win condition for eater during satanist elimination
(when (or (and (= (loyal-faction *player*) +faction-type-eater+)
(eq (mission-type-id (mission (level *world*))) :mission-type-eliminate-satanists))
(eq (mission-type-id (mission (level *world*))) :mission-type-test))
(let* ((win-condition (get-win-condition-by-id :win-cond-eater-cosnume))
(corpses (funcall (win-condition/win-func win-condition) *world* win-condition)))
(format str "~%Corpses eaten: ~A/~A~%" (eater-corpses-consumed *player*) corpses)))
;; delayed arrival
(loop with do-once = nil
for (game-event-id turns-left init-str) in `((,+game-event-delayed-arrival-demons+ ,(- (turns-for-delayed-demons (level *world*)) (player-game-time (level *world*))) "Demons arrive")
(,+game-event-delayed-arrival-angels+ ,(- (turns-for-delayed-angels (level *world*)) (player-game-time (level *world*))) "Angels arrive")
(,+game-event-delayed-arrival-military+ ,(- (turns-for-delayed-military (level *world*)) (player-game-time (level *world*))) "Military arrive"))
when (and (find game-event-id (game-events (level *world*)))
(>= turns-left 0))
do
(unless do-once
(setf do-once t)
(format str "~%"))
(format str "~A: ~A~%"
init-str
(if (zerop turns-left)
"now!"
(format nil "in ~A turn~:P" turns-left))))
(setf str (format nil "~A~%Humans ~A~%Blessed ~A~%Angels ~A~%Demons ~A~%Undead ~A~%~A~A~A~A~%~%Visibility: ~A~A"
str
(total-humans (level *world*))
(total-blessed (level *world*))
(total-angels (level *world*))
(total-demons (level *world*))
(total-undead (level *world*))
(sense-good-evil-str)
(if (mimic-id-list *player*)
(loop for mimic-id in (mimic-id-list *player*)
for mimic = (get-mob-by-id mimic-id)
with i = 0
with str = (create-string)
when (and (not (eq *player* mimic))
(not (is-merged mimic))
(not (check-dead mimic)))
do
(when (> i 0)
(format str "~%"))
(format str "~A (HP: ~A, Pwr: ~A~A)" (capitalize-name (name (get-mob-type-by-id (mob-type mimic)))) (cur-hp mimic) (cur-fp mimic)
(if (find (id mimic) (merged-id-list *player*))
", merged"
""))
(incf i)
finally (return (format nil "~%~A" str)))
"")
(if (or (mob-ability-p *player* +mob-abil-momentum+)
(mob-ability-p *player* +mob-abil-facing+)) (format nil "~%Moving: ~A~A"
(x-y-into-str (momentum-dir *player*))
(if (not (zerop (momentum-spd *player*)))
(format nil " (Spd: ~A)" (momentum-spd *player*))
""))
"")
(if (riding-mob-id *player*) (format nil "~%Riding: ~A~% HP: ~A/~A~A"
(name (get-mob-by-id (riding-mob-id *player*)))
(cur-hp (get-mob-by-id (riding-mob-id *player*))) (max-hp (get-mob-by-id (riding-mob-id *player*)))
(if (or (mob-ability-p (get-mob-by-id (riding-mob-id *player*)) +mob-abil-momentum+)
(mob-ability-p (get-mob-by-id (riding-mob-id *player*)) +mob-abil-facing+))
(format nil "~% Direction: ~A~A"
(x-y-into-str (momentum-dir (get-mob-by-id (riding-mob-id *player*))))
(if (not (zerop (momentum-spd (get-mob-by-id (riding-mob-id *player*)))))
(format nil " (Spd: ~A)" (momentum-spd (get-mob-by-id (riding-mob-id *player*))))
""))
"")
)
"")
(format nil "~A~A" (get-mob-visibility *player*) (if (> (brightness *player*) *mob-visibility-threshold*)
" (lit)"
""))
(if *cotd-release* "" (format nil " (B: ~A)" (brightness *player*)))
))
(setf str-lines (write-text str a-rect :color sdl:*white*)))
(show-char-effects *player* x (+ y (* (sdl:get-font-height) (1+ str-lines))) (- (+ (- *window-height* *msg-box-window-height* 20) (* -3 (sdl:char-height sdl:*default-font*)))
(+ y (* (sdl:get-font-height) (1+ str-lines)))))
(show-time-label idle-calcing x (+ (- *window-height* *msg-box-window-height* 20) (* -3 (sdl:char-height sdl:*default-font*))))
))
(defun show-message-box (x y w &optional (h *msg-box-window-height*) (message-box (level/small-message-box (level *world*))))
(sdl:with-rectangle (a-rect (sdl:rectangle :x x :y y :w w :h h))
(sdl:fill-surface sdl:*black* :template a-rect))
(sdl:with-rectangle (a-rect (sdl:rectangle :x x :y y :w w :h h))
(let ((max-lines (write-colored-text (colored-txt-list (message-box-strings message-box)) a-rect :count-only t)))
(when (> (message-list-length) 0)
(write-colored-text (colored-txt-list (message-box-strings message-box)) a-rect :start-line (if (< (truncate h (sdl:char-height sdl:*default-font*)) max-lines)
(- max-lines (truncate h (sdl:char-height sdl:*default-font*)))
0))))))
(defun sense-good-evil-str ()
(let ((str (create-string)) (first t))
(when (sense-evil-id *player*)
(when first (format str "~%") (setf first nil))
(format str "Sense evil: ~A~%" (general-direction-str (x *player*) (y *player*) (x (get-mob-by-id (sense-evil-id *player*))) (y (get-mob-by-id (sense-evil-id *player*))))))
(when (sense-good-id *player*)
(when first (format str "~%") (setf first nil))
(format str "Sense good: ~A~%" (general-direction-str (x *player*) (y *player*) (x (get-mob-by-id (sense-good-id *player*))) (y (get-mob-by-id (sense-good-id *player*))))))
(when (sense-unnatural-pos *player*)
(when first (format str "~%") (setf first nil))
(format str "Sense unnatural: ~A~%" (general-direction-str (x *player*) (y *player*) (first (sense-unnatural-pos *player*)) (second (sense-unnatural-pos *player*)))))
(when (sense-relic-pos *player*)
(when first (format str "~%") (setf first nil))
(format str "Sense relic: ~A~%" (general-direction-str (x *player*) (y *player*) (first (sense-relic-pos *player*)) (second (sense-relic-pos *player*)))))
(when (sense-portal-pos *player*)
(when first (format str "~%") (setf first nil))
(format str "Sense portal: ~A~%" (general-direction-str (x *player*) (y *player*) (first (sense-portal-pos *player*)) (second (sense-portal-pos *player*)))))
(when (sense-sigil-pos *player*)
(when first (format str "~%") (setf first nil))
(format str "Sense sigil: ~A~A~%" (general-direction-str (x *player*) (y *player*) (first (sense-sigil-pos *player*)) (second (sense-sigil-pos *player*)))
(if (and (mob-ability-p *player* +mob-abil-create-demon-sigil+)
(>= (get-distance (x *player*) (y *player*) (first (sense-sigil-pos *player*)) (second (sense-sigil-pos *player*))) *demonic-conquest-win-sigils-dist*))
" (available)"
"")))
(when (sense-machine-pos *player*)
(when first (format str "~%") (setf first nil))
(format str "Sense engine: ~A~%" (general-direction-str (x *player*) (y *player*) (first (sense-machine-pos *player*)) (second (sense-machine-pos *player*)))))
(when (sense-stockpile-pos *player*)
(when first (format str "~%") (setf first nil))
(format str "Sense storage: ~A~%" (general-direction-str (x *player*) (y *player*) (first (sense-stockpile-pos *player*)) (second (sense-stockpile-pos *player*)))))
str))
(defun general-direction-str (sx sy tx ty)
(let ((a (round (* (atan (- sy ty) (- sx tx)) (/ 180 pi))))
(result))
(cond
((and (> a 22.5) (<= a 67.5)) (setf result "NW"))
((and (> a 67.5) (<= a 112.5)) (setf result "N"))
((and (> a 112.5) (<= a 157.5)) (setf result "NE"))
((and (< a -22.5) (>= a -67.5)) (setf result "SW"))
((and (< a -67.5) (>= a -112.5)) (setf result "S"))
((and (< a -112.5) (>= a -157.5)) (setf result "SE"))
((or (> a 157.5) (< a -157.5)) (setf result "E"))
((or (> a -22.5) (<= a 22.5)) (setf result "W")))
result))
(defun draw-visible-mob-func (x y target-mob origin-mob color)
(let ((vmob target-mob)
(mob origin-mob))
(draw-glyph x y (get-current-mob-glyph-idx vmob :x (x vmob) :y (y vmob) :z (z vmob))
:front-color (get-current-mob-glyph-color vmob)
:back-color (get-current-mob-back-color vmob))
(sdl:draw-string-solid-* (format nil "~A~A~A~A"
(if (find (id vmob) (proper-visible-mobs mob))
""
"(M) ")
(capitalize-name (visible-name vmob))
(if (riding-mob-id vmob)
(format nil ", riding ~A" (prepend-article +article-a+ (visible-name (get-mob-by-id (riding-mob-id vmob)))))
"")
(if (/= (- (z vmob) (z mob)) 0)
(format nil " (~@d)" (- (z vmob) (z mob)))
""))
(+ x *glyph-w* 10) y :color color)))
(defun show-visible-mobs (x y w h &key (mob *player*) (visible-mobs (stable-sort (copy-list (visible-mobs mob))
#'(lambda (a b)
(if (< (get-distance-3d (x mob) (y mob) (z mob) (x a) (y a) (z a))
(get-distance-3d (x mob) (y mob) (z mob) (x b) (y b) (z b)))
t
nil))
:key #'get-mob-by-id)))
(sdl:with-rectangle (a-rect (sdl:rectangle :x x :y y :w w :h h))
(sdl:fill-surface sdl:*black* :template a-rect))
(loop with y1 = y
for mob-id in visible-mobs
for vmob = (get-mob-by-id mob-id)
do
(when (and (> (length visible-mobs) (truncate h *glyph-h*))
(> (+ y1 (* 1 *glyph-h*)) (+ y h)))
(sdl:draw-string-solid-* "(...)" x y1 :color sdl:*white*)
(loop-finish))
(draw-visible-mob-func x y1 vmob mob sdl:*white*)
(incf y1 *glyph-h*)))
(defun show-level-weather (x y &key (level (level *world*)))
(sdl:draw-string-solid-* (format nil "Wind: ~A, ~A"
(cond
((eq (wind-dir level) 1) "SW")
((eq (wind-dir level) 2) "S")
((eq (wind-dir level) 3) "SE")
((eq (wind-dir level) 4) "W")
((eq (wind-dir level) 6) "E")
((eq (wind-dir level) 7) "NW")
((eq (wind-dir level) 8) "N")
((eq (wind-dir level) 9) "NE")
(t "None"))
(return-weather-type-str (level *world*)))
x y :color sdl:*white*))
(defun show-abilities-on-cooldown (x y)
(loop with str = (create-string)
with need-comma = nil
for ability-type-id in (stable-sort (loop for ability-type-id in (get-mob-all-abilities *player*)
when (not (abil-applic-cd-p ability-type-id *player*))
collect ability-type-id)
#'(lambda (a b)
(if (> (abil-cur-cd-p *player* a)
(abil-cur-cd-p *player* b))
t
nil)))
do
(when (> (+ (* (length str) (sdl:char-width sdl:*default-font*)) (* (+ (length (name (get-ability-type-by-id ability-type-id))) 7) (sdl:char-width sdl:*default-font*)))
(+ 20 (* *glyph-w* *max-x-view*)))
(format str " ...")
(loop-finish))
(format str "~A~A [~A]"
(if need-comma ", " "")
(name (get-ability-type-by-id ability-type-id))
(abil-cur-cd-p *player* ability-type-id)
)
(setf need-comma t)
finally (sdl:draw-string-solid-* str x y :color sdl:*red*))
)
(defun show-delayed-arrival ()
(let* ((turns-before-arrival (cond
((= (loyal-faction *player*) +faction-type-demons+) (turns-for-delayed-demons (level *world*)))
((= (loyal-faction *player*) +faction-type-angels+) (turns-for-delayed-angels (level *world*)))
((= (loyal-faction *player*) +faction-type-military+) (turns-for-delayed-military (level *world*)))
(t 220)))
(str (format nil "Turns before arrival: ~A/~A" (player-game-time (level *world*)) turns-before-arrival))
(w (* (sdl:char-width sdl:*default-font*) (length str)))
(h (sdl:char-height sdl:*default-font*))
(x (+ *start-map-x* (- (truncate (* *max-x-view* *glyph-w*) 2) (truncate w 2))))
(y (- (truncate (* *max-y-view* *glyph-h*) 2) (truncate h 2))))
(sdl:with-rectangle (a-rect (sdl:rectangle :x x :y y :w w :h h))
(sdl:fill-surface sdl:*black* :template a-rect)
(sdl:draw-string-solid-* str x y :color sdl:*white*))
))
(defun update-screen (win)
;; filling the background with black rectangle
(fill-background-tiles)
(with-slots (max-glyphs) win
(update-map-area *start-map-x* 0 :post-func #'(lambda (x y x1 y1)
(loop for sound in (heard-sounds *player*)
when (and (= (sound-x sound) x)
(= (sound-y sound) y)
(= (sound-z sound) (z *player*)))
do
(draw-glyph x1
y1
31
:front-color sdl:*white*
:back-color sdl:*black*))
))
(show-abilities-on-cooldown 10 (- *window-height* *msg-box-window-height* 20 (* (sdl:char-height sdl:*default-font*) 2)))
(show-char-properties (+ *start-map-x* 20 (* *glyph-w* *max-x-view*)) 10 (idle-calcing win))
(show-message-box 10 (- *window-height* *msg-box-window-height* 20) (- *window-width* 260 10))
(show-visible-mobs (- *window-width* 260) (- *window-height* *msg-box-window-height* 20) 260 *msg-box-window-height*)
(show-level-weather (+ *start-map-x* 20 (* *glyph-w* *max-x-view*)) (+ (- *window-height* *msg-box-window-height* 20) (* -2 (sdl:char-height sdl:*default-font*))))
;; display up to two parts of the level
;; sort the list of visible z levels
;; if there is an enemy in range -
(loop with result = (remove-duplicates (loop for mob-id in (visible-mobs *player*)
for mob = (get-mob-by-id mob-id)
when (and (<= (abs (- (x *player*) (x mob))) 5)
(<= (abs (- (y *player*) (y mob))) 5)
(/= (z *player*) (z mob))
(find (z mob) (visible-z-list *player*)))
collect (z mob)))
for off-z from 1 below (array-dimension (terrain (level *world*)) 2) do
(when (find (- (z *player*) off-z) (visible-z-list *player*))
(pushnew (- (z *player*) off-z) result))
(when (find (+ (z *player*) off-z) (visible-z-list *player*))
(pushnew (+ (z *player*) off-z) result))
finally (setf (visible-z-list *player*) (reverse result)))
(loop with accepted-z-levels = ()
with offset = (truncate max-glyphs 2)
for z in (visible-z-list *player*) do
(let ((non-air-found nil))
(block outer
(loop for x from (- (x *player*) offset) to (+ (x *player*) offset) do
(loop for y from (- (y *player*) offset) to (+ (y *player*) offset) do
(when (and (>= x 0) (>= y 0) (< x (array-dimension (terrain (level *world*)) 0)) (< y (array-dimension (terrain (level *world*)) 1))
(or (and (not (eq (get-terrain-* (level *world*) x y z) +terrain-border-air+))
(not (eq (get-terrain-* (level *world*) x y z) +terrain-floor-air+)))
(get-mob-* (level *world*) x y z)))
(setf non-air-found t)
(return-from outer nil)))))
(when non-air-found
(push z accepted-z-levels)))
(when (>= (length accepted-z-levels) 2)
(loop-finish))
finally
(when accepted-z-levels
(show-part-of-level win 5 10 (x *player*) (y *player*) (first accepted-z-levels)))
(when (> (length accepted-z-levels) 1)
(show-part-of-level win 5 (+ 10 10 (* *glyph-h* (+ 1 max-glyphs))) (x *player*) (y *player*) (second accepted-z-levels))))
(when (player-outside-level *player*)
(show-delayed-arrival)))
(sdl:update-display)
)
(defmethod make-output ((win cell-window))
(update-screen win)
)
(defmethod run-window ((win cell-window))
(tagbody
(sdl:with-events ()
(:quit-event () (funcall (quit-func *current-window*)) t)
(:key-down-event (:key key :mod mod :unicode unicode)
;(format t "~%")
;(format t "KEY = ~A~%" key)
;(format t "MOD BEFORE NORMALIZE = ~A~%" mod)
;; normalize mod
(loop while (>= mod sdl-key-mod-num) do
(decf mod sdl-key-mod-num))
;(format t "MOD AFTER NORMALIZE = ~A~%" mod)
;(format t "UNICODE = ~A~%" unicode)
;;------------------
;; moving - arrows
(when (or (sdl:key= key :sdl-key-pageup) (sdl:key= key :sdl-key-kp9))
(if (mob-ability-p *player* +mob-abil-immobile+)
(add-message (format nil "You are immobile and can not move.~%"))
(progn
(clear-message-list (level/small-message-box (level *world*)))
(if (can-move-if-possessed *player*)
(setf (can-move-if-possessed *player*) nil)
(move-mob *player* 9)
)))
)
(when (or (sdl:key= key :sdl-key-up) (sdl:key= key :sdl-key-kp8))
(if (mob-ability-p *player* +mob-abil-immobile+)
(add-message (format nil "You are immobile and can not move.~%"))
(progn
(clear-message-list (level/small-message-box (level *world*)))
(if (can-move-if-possessed *player*)
(setf (can-move-if-possessed *player*) nil)
(move-mob *player* 8)
)))
)
(when (or (sdl:key= key :sdl-key-home) (sdl:key= key :sdl-key-kp7))
(if (mob-ability-p *player* +mob-abil-immobile+)
(add-message (format nil "You are immobile and can not move.~%"))
(progn
(clear-message-list (level/small-message-box (level *world*)))
(if (can-move-if-possessed *player*)
(setf (can-move-if-possessed *player*) nil)
(move-mob *player* 7)
)))
)
(when (or (sdl:key= key :sdl-key-right) (sdl:key= key :sdl-key-kp6))
(if (mob-ability-p *player* +mob-abil-immobile+)
(add-message (format nil "You are immobile and can not move.~%"))
(progn
(clear-message-list (level/small-message-box (level *world*)))
(if (can-move-if-possessed *player*)
(setf (can-move-if-possessed *player*) nil)
(move-mob *player* 6)
)))
)
(when (or (sdl:key= key :sdl-key-kp5)
(and (sdl:key= key :sdl-key-period)
(= mod 0)))
(clear-message-list (level/small-message-box (level *world*)))
(if (can-move-if-possessed *player*)
(setf (can-move-if-possessed *player*) nil)
(move-mob *player* 5)
)
)
(when (or (sdl:key= key :sdl-key-left) (sdl:key= key :sdl-key-kp4))
(if (mob-ability-p *player* +mob-abil-immobile+)
(add-message (format nil "You are immobile and can not move.~%"))
(progn
(clear-message-list (level/small-message-box (level *world*)))
(if (can-move-if-possessed *player*)
(setf (can-move-if-possessed *player*) nil)
(move-mob *player* 4)
)))
)
(when (or (sdl:key= key :sdl-key-pagedown) (sdl:key= key :sdl-key-kp3))
(if (mob-ability-p *player* +mob-abil-immobile+)
(add-message (format nil "You are immobile and can not move.~%"))
(progn
(clear-message-list (level/small-message-box (level *world*)))
(if (can-move-if-possessed *player*)
(setf (can-move-if-possessed *player*) nil)
(move-mob *player* 3)
)))
)
(when (or (sdl:key= key :sdl-key-down) (sdl:key= key :sdl-key-kp2))
(if (mob-ability-p *player* +mob-abil-immobile+)
(add-message (format nil "You are immobile and can not move.~%"))
(progn
(clear-message-list (level/small-message-box (level *world*)))
(if (can-move-if-possessed *player*)
(setf (can-move-if-possessed *player*) nil)
(move-mob *player* 2)
)))
)
(when (or (sdl:key= key :sdl-key-end) (sdl:key= key :sdl-key-kp1))
(if (mob-ability-p *player* +mob-abil-immobile+)
(add-message (format nil "You are immobile and can not move.~%"))
(progn
(clear-message-list (level/small-message-box (level *world*)))
(if (can-move-if-possessed *player*)
(setf (can-move-if-possessed *player*) nil)
(move-mob *player* 1)
)))
)
;;------------------
;; move down - Shift + . (i.e., >)
(when (and (or (and (sdl:key= key :sdl-key-period) (/= (logand mod sdl-cffi::sdl-key-mod-shift) 0))
(eq unicode +cotd-unicode-greater-than-sign+))
(> (z *player*) 0)
(not (get-terrain-type-trait (get-terrain-* (level *world*) (x *player*) (y *player*) (z *player*)) +terrain-trait-blocks-move-floor+))
(not (get-terrain-type-trait (get-terrain-* (level *world*) (x *player*) (y *player*) (1- (z *player*))) +terrain-trait-blocks-move+))
(or (mob-effect-p *player* +mob-effect-climbing-mode+)
(get-terrain-type-trait (get-terrain-* (level *world*) (x *player*) (y *player*) (z *player*)) +terrain-trait-water+)
(mob-effect-p *player* +mob-effect-flying+)
(mob-ability-p *player* +mob-abil-flying+))
)
(if (mob-ability-p *player* +mob-abil-immobile+)
(add-message (format nil "You are immobile and can not move.~%"))
(progn
(clear-message-list (level/small-message-box (level *world*)))
(if (can-move-if-possessed *player*)
(setf (can-move-if-possessed *player*) nil)
(move-mob *player* 5 :dir-z -1)
)))
)
;;------------------
;; move up - Shift + , (i.e., <)
(when (and (or (and (sdl:key= key :sdl-key-comma) (/= (logand mod sdl-cffi::sdl-key-mod-shift) 0))
(eq unicode +cotd-unicode-less-than-sign+))
(or (and (mob-effect-p *player* +mob-effect-climbing-mode+)
(funcall #'(lambda ()
(let ((result nil))
(check-surroundings (x *player*) (y *player*) nil
#'(lambda (dx dy)
(when (and (get-terrain-type-trait (get-terrain-* (level *world*) dx dy (z *player*)) +terrain-trait-blocks-move+)
(not (get-terrain-type-trait (get-terrain-* (level *world*) dx dy (z *player*)) +terrain-trait-not-climable+)))
(setf result t))))
result))))
(and (get-terrain-type-trait (get-terrain-* (level *world*) (x *player*) (y *player*) (1+ (z *player*))) +terrain-trait-water+)
(get-terrain-type-trait (get-terrain-* (level *world*) (x *player*) (y *player*) (z *player*)) +terrain-trait-water+))
(mob-effect-p *player* +mob-effect-flying+)
(mob-ability-p *player* +mob-abil-flying+))
(not (mob-effect-p *player* +mob-effect-gravity-pull+))
(< (z *player*) (1- (array-dimension (terrain (level *world*)) 2))))
(if (mob-ability-p *player* +mob-abil-immobile+)
(add-message (format nil "You are immobile and can not move.~%"))
(progn
(clear-message-list (level/small-message-box (level *world*)))
(if (can-move-if-possessed *player*)
(setf (can-move-if-possessed *player*) nil)
(move-mob *player* 5 :dir-z 1)
)))
)
;;------------------
;; character mode - Shift + 2
(when (or (and (sdl:key= key :sdl-key-2) (/= (logand mod sdl-cffi::sdl-key-mod-shift) 0))
(eq unicode +cotd-unicode-at-sign+))
(setf *current-window* (make-instance 'character-window :return-to *current-window*)))
;;------------------
;; help screen - ?
(when (or (sdl:key= key :sdl-key-question)
(eq unicode +cotd-unicode-question-mark+)
(and (sdl:key= key :sdl-key-slash) (/= (logand mod sdl-cffi::sdl-key-mod-shift) 0))
(and (sdl:key= key :sdl-key-7) (/= (logand mod sdl-cffi::sdl-key-mod-shift) 0)))
(setf *current-window* (make-instance 'help-window :return-to *current-window*)))
;;------------------
;; select item to use - u
(when (or (and (sdl:key= key :sdl-key-u))
(eq unicode +cotd-unicode-latin-u-small+))
(when (can-move-if-possessed *player*)
(setf (can-move-if-possessed *player*) nil)
(go exit-loop))
(let ((item-name-list nil)
(item-descr-list nil)
(item-prompt-list nil)
(item-color-list nil)
(mob-items nil))
;; filter item list to leave only usable ones
(setf mob-items (loop for item-id in (inv *player*)
for item = (get-item-by-id item-id)
when (and (on-check-applic item)
(on-use item)
(funcall (on-check-applic item) *player* item))
collect item))
(if mob-items
(progn
;; populate item name list
(setf item-name-list
(loop for item in mob-items
collect (capitalize-name (prepend-article +article-a+ (visible-name item)))))
;; populate item descripiton list
(setf item-descr-list
(loop for item in mob-items
collect (descr item)))
;; populate item color list
(setf item-color-list
(loop for item in mob-items
collect sdl:*white*))
;; populate item prompt list
(setf item-prompt-list
(loop for item in mob-items
collect #'(lambda (cur-sel)
(declare (ignore cur-sel))
"[Enter] Use [Escape] Cancel")))
;; display the window with the list
(setf *current-window* (make-instance 'select-obj-window
:return-to *current-window*
:w (- *window-width* 300)
:header-line "Choose item:"
:color-list item-color-list
:select-color-func #'(lambda (cur-sel)
(declare (ignore cur-sel))
sdl:*yellow*)
:enter-func #'(lambda (cur-sel)
(let ((item (get-inv-item-by-pos (inv *player*) cur-sel)))
(window-use-item item win)))
:line-list item-name-list
:descr-list item-descr-list
:prompt-list item-prompt-list)))
(progn
;; no items - display a message
(add-message (format nil "You have no items to use.~%"))
))
))
;;------------------
;; select abilities - a
(when (or (and (sdl:key= key :sdl-key-a))
(eq unicode +cotd-unicode-latin-a-small+))
(when (can-move-if-possessed *player*)
(setf (can-move-if-possessed *player*) nil)
(go exit-loop))
(let ((abil-name-list nil)
(abil-descr-list nil)
(abil-prompt-list nil)
(abil-color-list nil)
(mob-abilities nil))
;; filter ability list to leave only non passive and applicable
(setf mob-abilities (loop for ability-type-id in (get-mob-all-abilities *player*)
when (and (not (abil-passive-p ability-type-id))
(abil-applicable-p (get-ability-type-by-id ability-type-id) *player* *player*))
collect ability-type-id))
(if mob-abilities
(progn
;; populate the ability name list
(setf abil-name-list
(loop
for ability-type-id in mob-abilities
collect (name (get-ability-type-by-id ability-type-id))))
;; populate the ability description list
(setf abil-descr-list
(loop
for ability-type-id in mob-abilities
collect (cond
((not (abil-applic-cost-p ability-type-id *player*)) (format nil "Cost: ~A pwr. Insufficient power!" (cost (get-ability-type-by-id ability-type-id))))
((not (abil-applic-cd-p ability-type-id *player*)) (format nil "CD: ~A turn~:P. On cooldown!" (abil-cur-cd-p *player* ability-type-id)))
(t (format nil "~A~ATime: ~A turn~:P."
(if (zerop (cost (get-ability-type-by-id ability-type-id)))
""
(format nil "Cost: ~A pwr. " (cost (get-ability-type-by-id ability-type-id))))
(if (abil-applic-cd-p ability-type-id *player*)
""
(format nil "CD: ~A turn~:P. " (abil-cur-cd-p *player* ability-type-id)))
(/ (spd (get-ability-type-by-id ability-type-id)) +normal-ap+))))))
;; populate the ability description list
(setf abil-color-list
(loop
for ability-type-id in mob-abilities
collect (if (or (not (abil-applic-cost-p ability-type-id *player*))
(not (abil-applic-cd-p ability-type-id *player*)))
sdl:*red*
sdl:*white*)
))
;; populate the ability prompt list
(setf abil-prompt-list
(loop
for ability-type-id in mob-abilities
collect #'(lambda (cur-sel)
(if (can-invoke-ability *player* *player* (nth cur-sel mob-abilities))
"[Enter] Invoke [Escape] Cancel"
"[Escape] Cancel"))))
;; display the window with the list
(setf *current-window* (make-instance 'select-obj-window
:return-to *current-window*
:header-line "Choose ability:"
:descr-list abil-descr-list
:color-list abil-color-list
:select-color-func #'(lambda (n)
(if (or (not (abil-applic-cost-p (nth n mob-abilities) *player*))
(not (abil-applic-cd-p (nth n mob-abilities) *player*)))
(sdl:color :r 255 :g 69 :b 0)
sdl:*yellow*))
:enter-func #'(lambda (cur-sel)
(when (can-invoke-ability *player* *player* (nth cur-sel mob-abilities))
(cond
((map-select-func (get-ability-type-by-id (nth cur-sel mob-abilities)))
(progn
(setf *current-window* (make-instance 'map-select-window
:return-to *current-window*
:start-map-select (abil-start-map-select-func-p (nth cur-sel mob-abilities))
:cmd-str (list "[Enter] Invoke "
"")
:exec-func #'(lambda ()
(if (funcall (map-select-func (get-ability-type-by-id (nth cur-sel mob-abilities)))
(nth cur-sel mob-abilities))
(progn
(setf *current-window* win)
(make-output *current-window*)
t)
(progn
nil)))
))
(make-output *current-window*)))
((obj-select-func (get-ability-type-by-id (nth cur-sel mob-abilities)))
(progn
(funcall (obj-select-func (get-ability-type-by-id (nth cur-sel mob-abilities)))
(nth cur-sel mob-abilities))
(setf *current-window* win)
(make-output *current-window*)))
(t
(progn
(clear-message-list (level/small-message-box (level *world*)))
(mob-invoke-ability *player* *player* (nth cur-sel mob-abilities))
(setf *current-window* win)
(set-idle-calcing win))))
)
)
:line-list abil-name-list
:prompt-list abil-prompt-list)))
(progn
;; no abilites - display a message
(add-message (format nil "You have no abilities to invoke.~%"))
))
))
;;------------------
;; look mode - l
(when (or (and (sdl:key= key :sdl-key-l) (= mod 0))
(eq unicode +cotd-unicode-latin-l-small+))
(setf *current-window* (make-instance 'map-select-window
:return-to *current-window*
:cmd-str (list "[<] Look up [>] Look down "
"")
:exec-func #'(lambda ()
nil)))
(make-output *current-window*))
;;------------------
;; shoot mode - f
(when (or (and (sdl:key= key :sdl-key-f) (= mod 0))
(eq unicode +cotd-unicode-latin-f-small+))
(when (can-move-if-possessed *player*)
(setf (can-move-if-possessed *player*) nil)
(go exit-loop))
(if (is-weapon-ranged *player*)
(progn
(if (mob-can-shoot *player*)
(progn
(setf *current-window* (make-instance 'map-select-window
:return-to *current-window*
:cmd-str (list "[Enter] Fire [<] Look up [>] Look down "
"")
:start-map-select #'player-start-map-select-nearest-hostile
:check-lof t
:exec-func #'(lambda ()
(if (get-mob-* (level *world*) (view-x *player*) (view-y *player*) (view-z *player*))
(progn
(clear-message-list (level/small-message-box (level *world*)))
(mob-shoot-target *player* (get-mob-* (level *world*) (view-x *player*) (view-y *player*) (view-z *player*)))
(setf (view-x *player*) (x *player*) (view-y *player*) (y *player*))
(setf *current-window* (return-to *current-window*))
t)
(progn
nil))
)))
(make-output *current-window*))
(progn
(add-message (format nil "Can't switch into firing mode: need to reload.~%")))))
(progn
(add-message (format nil "Can't switch into firing mode: no ranged weapons.~%")))))
;;------------------
;; reload - r
(when (or (and (sdl:key= key :sdl-key-r) (= mod 0))
(eq unicode +cotd-unicode-latin-r-small+))
(clear-message-list (level/small-message-box (level *world*)))
(when (can-move-if-possessed *player*)
(setf (can-move-if-possessed *player*) nil)
(go exit-loop))
(if (is-weapon-ranged *player*)
(progn
(if (< (get-ranged-weapon-charges *player*) (get-ranged-weapon-max-charges *player*))
(progn
(mob-reload-ranged-weapon *player*))
(progn
(add-message (format nil "Can't reload: magazine already full.~%")))))
(progn
(add-message (format nil "Can't reload: this is not a ranged weapon.~%")))))
;;------------------
;; view inventory - i
(when (or (and (sdl:key= key :sdl-key-i) (= mod 0))
(eq unicode +cotd-unicode-latin-i-small+))
(setf *current-window* (make-instance 'inventory-window :return-to *current-window*)))
;;------------------
;; pick item - p, g or ,
(when (or (and (sdl:key= key :sdl-key-p) (= mod 0))
(and (sdl:key= key :sdl-key-g) (= mod 0))
(and (sdl:key= key :sdl-key-comma) (= mod 0)))
(when (can-move-if-possessed *player*)
(setf (can-move-if-possessed *player*) nil)
(go exit-loop))
;; count the number of items and containers at the grid-cell
(let ((item-line-list nil)
(item-prompt-list)
(item-list (get-items-* (level *world*) (x *player*) (y *player*) (z *player*))))
;;
(setf item-line-list (loop for item-id in item-list
for item = (get-item-by-id item-id)
collect (format nil "~A"
(capitalize-name (prepend-article +article-a+ (visible-name item)))
)))
;; populate the ability prompt list
(setf item-prompt-list (loop for item-id in item-list
collect #'(lambda (cur-sel)
(declare (ignore cur-sel))
"[Enter] Pick up [Escape] Cancel")))
;; a single item - just pick it up
(when (= (length item-list) 1)
(log:info (format nil "PLAYER-ITEM-PICK: On item on the tile, pick it right away~%"))
(clear-message-list (level/small-message-box (level *world*)))
(mob-pick-item *player* (get-inv-item-by-pos item-list 0)))
;; a several items - show selection window
(when (> (length item-list) 1)
(setf *current-window* (make-instance 'select-obj-window
:return-to *current-window*
:header-line "Choose an item to pick up:"
:enter-func #'(lambda (cur-sel)
(clear-message-list (level/small-message-box (level *world*)))
(mob-pick-item *player* (get-inv-item-by-pos item-list cur-sel))
(setf *current-window* win)
(set-idle-calcing win)
;(show-time-label (idle-calcing win) (+ 20 (* *glyph-w* *max-x-view*)) (+ 10 237) t)
)
:line-list item-line-list
:prompt-list item-prompt-list)))
))
;;------------------
;; view messages - m
(when (or (and (sdl:key= key :sdl-key-m) (= mod 0))
(eq unicode +cotd-unicode-latin-m-small+))
(setf *current-window* (make-instance 'message-window
:return-to *current-window*
:message-box (level/full-message-box (level *world*))
:header-str "MESSAGES"))
(make-output *current-window*))
;;------------------
;; view journal - j
(when (or (and (sdl:key= key :sdl-key-j) (= mod 0))
(eq unicode +cotd-unicode-latin-j-small+))
(setf *current-window* (make-instance 'journal-window
:return-to *current-window*))
(make-output *current-window*))
;;------------------
;; scenario main menu - Esc
(when (sdl:key= key :sdl-key-escape)
(show-escape-menu)
)
(set-idle-calcing win)
(make-output *current-window*)
(go exit-loop)
)
(:idle () (update-swank)
(set-idle-calcing win)
(show-time-label (idle-calcing win) (+ *start-map-x* 20 (* *glyph-w* *max-x-view*)) (+ (- *window-height* *msg-box-window-height* 20) (* -3 (sdl:char-height sdl:*default-font*))) t)
)
(:video-expose-event () (make-output *current-window*)))
exit-loop)
nil)
(defun show-time-label (idle-calcing x y &optional (update nil))
(sdl:draw-string-solid-* (format nil "~A [T: ~A]" (show-date-time-short (world-game-time *world*)) (player-game-time (level *world*)))
x y :color (cond ((eql idle-calcing :done) sdl:*white*)
((eql idle-calcing :in-progress) sdl:*yellow*)
((eql idle-calcing :npc-turn) sdl:*red*)))
(when update
(sdl:update-display)))
(defun set-idle-calcing (win)
(if (made-turn *player*)
(setf (idle-calcing win) :npc-turn)
(setf (idle-calcing win) :done)))
| 69,215
|
Common Lisp
|
.lisp
| 924
| 42.190476
| 229
| 0.390923
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
016ff7c0d5ca25cc770fdef421c50e50ccc808f7fe631834cd00884b75ca0b80
| 2,917
|
[
-1
] |
2,918
|
window-character.lisp
|
gwathlobal_CotD/src/windows/window-character.lisp
|
(in-package :cotd)
(defconstant +character-win-weapon&armor+ 0)
(defconstant +character-win-abilities+ 1)
(defconstant +character-win-effects+ 2)
(defclass character-window (window)
((cur-tab :initform 0 :accessor cur-tab)
(cur-sel :initform 0 :accessor cur-sel)))
(defun get-mob-stats-line (mob)
(let ((str))
(setf str (format nil "~%"))
(unless (zerop (calculate-total-kills mob))
(setf str (format nil "~ATotal kills: ~A~%" str (calculate-total-kills mob))))
(unless (zerop (stat-blesses mob))
(setf str (format nil "~ATotal blessings: ~A~%" str (stat-blesses mob))))
(unless (zerop (stat-calls mob))
(setf str (format nil "~ATotal summons: ~A~%" str (stat-calls mob))))
(unless (zerop (stat-answers mob))
(setf str (format nil "~ATotal answers: ~A~%" str (stat-answers mob))))
str))
(defun char-win-draw-weapon&armor (win)
(declare (ignore win))
(let* ((x 10)
(y (+ 30 (* (sdl:char-height sdl:*default-font*) 1)))
(w (- *window-width* 20))
(h (- *window-height* 20 (sdl:char-height sdl:*default-font*) y)))
(sdl:with-rectangle (a-rect (sdl:rectangle :x x :y y :w w :h h))
(sdl:fill-surface sdl:*black* :template a-rect)
(write-text (format nil "~A - ~A~%~%HP: ~A/~A~%~A~A~A~%~A~%~%~A~%Dodge chance: ~A~%~A~A"
(name *player*) (capitalize-name (name (get-mob-type-by-id (mob-type *player*))))
(cur-hp *player*) (max-hp *player*)
(if (zerop (max-fp *player*)) "" (format nil "Power: ~A/~A~%" (cur-fp *player*) (max-fp *player*)))
(if (or (mob-ability-p *player* +mob-abil-military-follow-me+)
(mob-ability-p *player* +mob-abil-prayer-bless+))
(format nil "Followers: ~A~%" (count-follower-list *player*)) "")
(if (worshiped-god *player*)
(format nil "~A: ~A~%" (name (get-god-by-id (get-worshiped-god-type (worshiped-god *player*)))) (return-piety-str (get-worshiped-god-type (worshiped-god *player*))
(get-worshiped-god-piety (worshiped-god *player*))))
"")
(get-weapon-descr-long *player*)
(get-armor-descr *player*)
(cur-dodge *player*)
(cond
((> (cur-light *player*) 0) (format nil "Light radius: ~A~%" (cur-light *player*)))
((< (cur-light *player*) 0) (format nil "Darkness radius: ~A~%" (abs (cur-light *player*))))
(t ""))
(get-mob-stats-line *player*))
a-rect :color sdl:*white*)
)
(sdl:draw-string-solid-* (format nil "[Right] Change tab [Esc] Exit")
10 (- *window-height* 10 (sdl:char-height sdl:*default-font*)))
))
(defun char-win-draw-abilities (win)
(sdl:with-rectangle (a-rect (sdl:rectangle :x 10 :y 10 :w 20 :h 20))
(sdl:fill-surface sdl:*black* :template a-rect))
(let* ((x 10)
(y (+ 30 (* (sdl:char-height sdl:*default-font*) 1)))
(w (- (truncate *window-width* 2) 20))
(h (- *window-height* 20 (sdl:char-height sdl:*default-font*) y)))
(sdl:with-rectangle (a-rect (sdl:rectangle :x x :y y :w w :h h))
(sdl:fill-surface sdl:*black* :template a-rect))
(let ((cur-str) (color-list nil) (str-list) (abilities-list (get-mob-all-abilities *player*)))
(setf cur-str (cur-sel win))
;(setf abilities-list (stable-sort abilities-list #'(lambda (a b)
; (if (and (not (mob-is-ability-mutation *player* b))
; (mob-is-ability-mutation *player* a))
; t
; nil))))
(setf abilities-list (stable-sort abilities-list #'(lambda (a b)
(if (or (and (not (mob-is-ability-mutation *player* a))
(not (mob-is-ability-mutation *player* b))
(abil-passive-p a)
(not (abil-passive-p b)))
(and (mob-is-ability-mutation *player* a)
(mob-is-ability-mutation *player* b)
(abil-passive-p a)
(not (abil-passive-p b)))
(and (not (mob-is-ability-mutation *player* a))
(mob-is-ability-mutation *player* b)))
t
nil))))
(setf str-list (loop for ability-type-id in abilities-list
collect (name (get-ability-type-by-id ability-type-id))))
(setf color-list (loop for i from 0 below (length (get-mob-all-abilities *player*))
collect (if (= i cur-str)
sdl:*yellow*
(cond
((mob-is-ability-mutation *player* (nth i abilities-list)) sdl:*magenta*)
((mob-is-ability-mission *player* (nth i abilities-list)) (sdl:color :r 153 :g 0 :b 76))
(t sdl:*white*)))))
(draw-selection-list str-list cur-str (truncate h (sdl:get-font-height)) x y :color-list color-list))
)
(let* ((x (+ (truncate *window-width* 2) 10))
(y (+ 30 (* (sdl:char-height sdl:*default-font*) 1)))
(w (- (truncate *window-width* 2) 20))
(h (- *window-height* 20 (sdl:char-height sdl:*default-font*) y))
(abilities-list (stable-sort (get-mob-all-abilities *player*) #'(lambda (a b)
(if (or (and (not (mob-is-ability-mutation *player* a))
(not (mob-is-ability-mutation *player* b))
(abil-passive-p a)
(not (abil-passive-p b)))
(and (mob-is-ability-mutation *player* a)
(mob-is-ability-mutation *player* b)
(abil-passive-p a)
(not (abil-passive-p b)))
(and (not (mob-is-ability-mutation *player* a))
(mob-is-ability-mutation *player* b)))
t
nil))))
(ability (get-ability-type-by-id (nth (cur-sel win) abilities-list))))
(sdl:with-rectangle (a-rect (sdl:rectangle :x x :y y :w w :h h))
(write-text (format nil "~A~%~%~A~A"
(descr ability)
(if (mob-is-ability-mutation *player* (id ability))
"Mutation. "
"")
(if (passive ability)
"Passive."
(format nil "~A~ATime cost: ~A turn~:P"
(if (zerop (cost ability)) "" (format nil "Cost: ~A pwr " (cost ability)))
(if (zerop (cd ability)) "" (format nil "Cooldown: ~A turn~:P " (cd ability)))
(/ (spd ability) +normal-ap+))))
a-rect :color sdl:*white*)
)
)
(sdl:draw-string-solid-* (format nil "[Left/Right] Change tab [Up/Down] Change selection [Esc] Exit")
10 (- *window-height* 10 (sdl:char-height sdl:*default-font*))))
(defun char-win-draw-effects (win)
(declare (ignore win))
(let* ((x 10)
(y (+ 30 (* (sdl:char-height sdl:*default-font*) 1)))
(w (- (truncate *window-width* 2) 20))
(h (- *window-height* 20 (sdl:char-height sdl:*default-font*) y)))
(sdl:with-rectangle (a-rect (sdl:rectangle :x x :y y :w w :h h))
(sdl:fill-surface sdl:*black* :template a-rect))
(show-char-effects *player* x y h)
)
(sdl:draw-string-solid-* (format nil "[Left] Change tab [Esc] Exit")
10 (- *window-height* 10 (sdl:char-height sdl:*default-font*))))
(defmethod make-output ((win character-window))
(fill-background-tiles)
(sdl:draw-string-solid-* "CHARACTER" (truncate *window-width* 2) 0 :justify :center)
(let ((color-1 sdl:*white*) (color-2 sdl:*white*) (color-3 sdl:*white*))
(cond
((= (cur-tab win) +character-win-weapon&armor+)
(setf color-1 sdl:*yellow*)
(char-win-draw-weapon&armor win))
((= (cur-tab win) +character-win-abilities+)
(setf color-2 sdl:*yellow*)
(char-win-draw-abilities win))
((= (cur-tab win) +character-win-effects+)
(setf color-3 sdl:*yellow*)
(char-win-draw-effects win)))
(sdl:draw-string-solid-* (format nil "Stats") 10 (+ 10 (* (sdl:char-height sdl:*default-font*) 1)) :justify :left :color color-1)
(sdl:draw-string-solid-* (format nil "Abilities") (truncate *window-width* 2) (+ 10 (* (sdl:char-height sdl:*default-font*) 1)) :justify :center :color color-2)
(sdl:draw-string-solid-* (format nil "Effects") (- *window-width* 10) (+ 10 (* (sdl:char-height sdl:*default-font*) 1)) :justify :right :color color-3))
(sdl:update-display))
(defmethod run-window ((win character-window))
(sdl:with-events ()
(:quit-event () (funcall (quit-func win)) t)
(:key-down-event (:key key :mod mod :unicode unicode)
(when (= (cur-tab win) +character-win-abilities+)
(setf (cur-sel win) (run-selection-list key mod unicode (cur-sel win)))
(setf (cur-sel win) (adjust-selection-list (cur-sel win) (length (get-mob-all-abilities *player*)))))
(cond
((sdl:key= key :sdl-key-left)
(decf (cur-tab win))
(when (< (cur-tab win) +character-win-weapon&armor+)
(setf (cur-tab win) +character-win-weapon&armor+)))
((sdl:key= key :sdl-key-right)
(incf (cur-tab win))
(when (> (cur-tab win) +character-win-effects+)
(setf (cur-tab win) +character-win-effects+)))
((sdl:key= key :sdl-key-escape)
(setf *current-window* (return-to win)) (make-output *current-window*) (return-from run-window nil))
)
(make-output *current-window*))
(:video-expose-event () (make-output *current-window*)))
)
| 12,358
|
Common Lisp
|
.lisp
| 178
| 44.410112
| 193
| 0.436743
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
a40c3e36957105a92aa57e1bab98934328ed45d50e416d13a6273a4765d23841
| 2,918
|
[
-1
] |
2,919
|
window-main-menu.lisp
|
gwathlobal_CotD/src/windows/window-main-menu.lisp
|
(in-package :cotd)
(defclass main-menu-window (window)
((cur-sel :initform 0 :accessor main-menu-window/cur-sel :type fixnum)
(menu-items :initform () :accessor main-meni-window/menu-items :type list)
(menu-strs :initform () :accessor main-menu-window/menu-strs :type list)
(menu-funcs :initform () :accessor main-menu-window/menu-funcs :type list)
))
(defmethod initialize-instance :after ((win main-menu-window) &key)
(populate-main-menu win))
(defmethod make-output ((win main-menu-window))
(with-slots (cur-sel menu-items menu-strs) win
(sdl:with-rectangle (a-rect (sdl:rectangle :x 0 :y 0 :w *window-width* :h *window-height*))
(sdl:fill-surface sdl:*black* :template a-rect))
(sdl:draw-string-solid-* "City of the Damned" (truncate *window-width* 2) 10 :justify :center :color sdl:*white*)
(sdl:draw-string-solid-* "Whoever wins... We lose" (- *window-width* 20) (+ 10 30 (sdl:char-height sdl:*default-font*)) :justify :right :color sdl:*white*)
;; drawing selection list
(loop with color-list = ()
for i from 0 below (length menu-strs) do
(if (= i cur-sel)
(push sdl:*yellow* color-list)
(push sdl:*white* color-list))
finally (setf color-list (reverse color-list))
(draw-selection-list menu-strs cur-sel (length menu-strs) 20 (+ 10 30 20 (sdl:char-height sdl:*default-font*) (sdl:char-height sdl:*default-font*)) :color-list color-list :use-letters t))
(sdl:draw-string-solid-* (format nil "[Enter] Select [Up/Down] Move selection [Shift+Up/Down] Scroll page [Esc] Exit game")
10 (- *window-height* 10 (sdl:char-height sdl:*default-font*)))
(sdl:update-display)))
(defmethod run-window ((win main-menu-window))
(with-slots (cur-sel menu-funcs menu-strs) win
(sdl:with-events ()
(:quit-event () (funcall (quit-func win)) t)
(:key-down-event (:key key :mod mod :unicode unicode)
(setf cur-sel (run-selection-list key mod unicode cur-sel :start-page (truncate cur-sel (length menu-strs)) :max-str-per-page (length menu-strs)))
(setf cur-sel (adjust-selection-list cur-sel (length menu-strs)))
(cond
;; escape - quit
((sdl:key= key :sdl-key-escape)
(game-state-menu->quit)
(go-to-quit-game))
;; enter - select
((or (sdl:key= key :sdl-key-return) (sdl:key= key :sdl-key-kp-enter))
(when (and menu-funcs (nth cur-sel menu-funcs))
(let ((menu-result (funcall (nth cur-sel menu-funcs))))
(when (eq menu-result :menu-stop-loop)
(return-from run-window nil))))
))
(make-output *current-window*))
(:video-expose-event () (make-output *current-window*)))))
(defun populate-main-menu (win)
(with-slots (menu-items menu-strs menu-funcs) win
(setf menu-items ()
menu-strs ()
menu-funcs ())
(let ((new-campaign-item (list "New campaign"
#'(lambda ()
(setf *world* (make-instance 'world))
(setf (world-game-time *world*) (set-current-date-time 1915 3 12 0 0 0))
(setf (world-map *world*) (generate-normal-world-map *world*))
(push +game-event-campaign-demon-win+ (game-events *world*))
(push +game-event-campaign-military-win+ (game-events *world*))
(push +game-event-campaign-angel-win+ (game-events *world*))
(push +game-event-campaign-flesh-gathered+ (game-events *world*))
(push +game-event-campaign-satanists-move+ (game-events *world*))
(push +game-event-campaign-move-military+ (game-events *world*))
(push +game-event-campaign-move-demons+ (game-events *world*))
(push +game-event-campaign-move-relic-to-church+ (game-events *world*))
(push +game-event-campaign-trigger-commands+ (game-events *world*))
(push +game-event-campaign-malseraphs-focus+ (game-events *world*))
(add-campaign-effect *world* :id :campaign-effect-satanist-sacrifice :cd 5)
(multiple-value-bind (campaign-items campaign-funcs campaign-descrs) (new-campaign-menu-items)
(setf *current-window* (make-instance 'select-faction-window :window-title "SELECT FACTION FOR CAMPAIGN" :menu-items campaign-items :menu-descrs campaign-descrs))
(make-output *current-window*)
(let ((select-n (run-window *current-window*)))
(if select-n
(progn
(enter-player-name)
(setf (world/player-specific-faction *world*) (funcall (nth select-n campaign-funcs) select-n))
(setf *player-title* (get-specific-faction-name (world/player-specific-faction *world*)))
(game-state-menu->campaign-init)
:menu-stop-loop)
nil)))
)))
(load-campaign-item (list "Load campaign"
#'(lambda ()
(setf *current-window* (make-instance 'load-game-window :save-game-type :save-game-campaign))
(make-output *current-window*)
(case (run-window *current-window*)
(:save-campaign (progn
(game-state-menu->campaign-map)
:menu-stop-loop))
(:save-scenario (progn
(game-state-menu->campaign-scenario)
:menu-stop-loop))
(t (progn
(populate-main-menu win)
nil))))))
(quick-scenario-item (list "Quick scenario"
#'(lambda ()
(multiple-value-bind (quick-scenario-items quick-scenario-funcs quick-scenario-descrs) (quick-scenario-menu-items)
(setf *current-window* (make-instance 'select-faction-window :menu-items quick-scenario-items :menu-descrs quick-scenario-descrs))
(make-output *current-window*)
(let ((select-n (run-window *current-window*)))
(when select-n
(multiple-value-bind (world-sector mission) (funcall (nth select-n quick-scenario-funcs) select-n)
(when (and mission world-sector)
(enter-player-name)
(setf *player-title* (get-specific-faction-name (player-specific-faction mission)))
(prepare-game-scenario mission world-sector)
(game-state-menu->custom-scenario)
:menu-stop-loop
))))
))
))
(custom-scenario-item (list "Custom scenario"
#'(lambda ()
(setf *current-window* (make-instance 'custom-scenario-window))
(make-output *current-window*)
(multiple-value-bind (world-sector mission) (run-window *current-window*)
(when (and world-sector mission)
(enter-player-name)
(setf *player-title* (get-specific-faction-name (player-specific-faction mission)))
(prepare-game-scenario mission world-sector)
(game-state-menu->custom-scenario)
:menu-stop-loop
))
)))
(load-scenario-item (list "Load scenario"
#'(lambda ()
(setf *current-window* (make-instance 'load-game-window :save-game-type :save-game-scenario))
(make-output *current-window*)
(case (run-window *current-window*)
(:save-scenario (progn
(game-state-menu->custom-scenario)
:menu-stop-loop))
(t (progn
(populate-main-menu win)
nil)))
)))
(settings-item (list "Settings"
#'(lambda ()
(setf *current-window* (make-instance 'settings-window))
(make-output *current-window*)
(run-window *current-window*)
nil)))
(highscores-item (list "High scores"
#'(lambda ()
(truncate-highscores *highscores*)
(setf *current-window* (make-instance 'highscores-window))
(make-output *current-window*)
(run-window *current-window*)
nil)))
(help-item (list "Help"
#'(lambda ()
(setf *current-window* (make-instance 'help-window))
(make-output *current-window*)
(run-window *current-window*)
nil)))
(exit-item (list "Exit"
#'(lambda ()
(game-state-menu->quit)
(go-to-quit-game)
)))
(all-see-item (list "City with all-seeing"
#'(lambda ()
(multiple-value-bind (mission world-sector) (find-random-scenario-options +specific-faction-type-player+)
(when (and mission world-sector)
(prepare-game-scenario mission world-sector)
(game-state-menu->custom-scenario)
:menu-stop-loop
))
)))
(test-level-item (list "Test level"
#'(lambda ()
(let ((test-world-map (make-instance 'world-map))
(mission (make-instance 'mission :mission-type-id :mission-type-test
:x 0 :y 0
:level-modifier-list (list +lm-tod-night+)))
(world-sector (make-instance 'world-sector :wtype :world-sector-test :x 0 :y 0)))
(setf *world* (make-instance 'world))
(setf (world-game-time *world*) (set-current-date-time 1915 3 12 0 0 0))
(generate-empty-world-map test-world-map)
(setf (world-map *world*) test-world-map)
(setf (aref (cells test-world-map) 0 0) world-sector)
(setf (mission (aref (cells test-world-map) 0 0)) mission)
(setf (player-lvl-mod-placement-id mission) +lm-placement-test+)
(setf (player-specific-faction mission) nil)
(prepare-game-scenario mission world-sector)
(game-state-menu->custom-scenario)
:menu-stop-loop
)
)))
(play-prev-scenario (list "Replay the previous scenario"
#'(lambda ()
(multiple-value-bind (mission world-sector) (find-random-scenario-options (second *previous-scenario*) :avail-mission-type-list (list (get-mission-type-by-id (first *previous-scenario*))))
(if (and mission world-sector)
(progn
(enter-player-name)
(prepare-game-scenario mission world-sector)
(game-state-menu->custom-scenario)
:menu-stop-loop)
nil))
)))
(test-campaign-item (list "Test campaign"
#'(lambda ()
(let ((mission nil)
(world-sector nil))
(flet ((test-map-func ()
(setf (world-map *world*) (generate-test-world-map *world*))
(setf (mission (aref (cells (world-map *world*)) 1 2)) (generate-mission-on-world-map *world* 1 2 :mission-type-military-conquest :off-map nil))
(world-map *world*)))
(setf *world* (make-instance 'world))
(setf (world-game-time *world*) (set-current-date-time 1915 3 12 0 0 0))
(test-map-func)
(game-state-menu->campaign-map)
(setf *current-window* (make-instance 'campaign-window
:test-map-func #'test-map-func))
(make-output *current-window*)
(multiple-value-setq (mission world-sector) (run-window *current-window*))
(when (and mission world-sector)
(setf (player-lvl-mod-placement-id mission) +lm-placement-player+)
(setf (player-specific-faction mission) nil)
(setf *current-window* (return-to *current-window*))
(game-state-campaign-map->menu)
(prepare-game-scenario mission world-sector)
(game-state-menu->custom-scenario)
:menu-stop-loop
)))))))
(if *cotd-release*
(progn
(setf menu-items (append (if *previous-scenario*
(list play-prev-scenario)
nil)
(list new-campaign-item)
(if (find-all-save-game-paths :save-game-campaign)
(list load-campaign-item)
nil)
(list quick-scenario-item custom-scenario-item)
(if (find-all-save-game-paths :save-game-scenario)
(list load-scenario-item)
nil)
(list settings-item highscores-item help-item exit-item)))
)
(progn
(setf menu-items (append (if *previous-scenario*
(list play-prev-scenario)
nil)
(list new-campaign-item)
(if (find-all-save-game-paths :save-game-campaign)
(list load-campaign-item)
nil)
(list quick-scenario-item custom-scenario-item)
(if (find-all-save-game-paths :save-game-scenario)
(list load-scenario-item)
nil)
(list all-see-item test-level-item test-campaign-item settings-item highscores-item help-item exit-item)))
))
)
(loop for (menu-str menu-func) in menu-items
do
(push menu-str menu-strs)
(push menu-func menu-funcs)
finally (setf menu-strs (reverse menu-strs))
(setf menu-funcs (reverse menu-funcs)))))
| 19,522
|
Common Lisp
|
.lisp
| 262
| 38.561069
| 229
| 0.401868
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
c9ebd1bcc43fb38c5d503b57afc60c2e84063b5bc6cfc511aa8162dda14beaad
| 2,919
|
[
-1
] |
2,920
|
window-inventory.lisp
|
gwathlobal_CotD/src/windows/window-inventory.lisp
|
(in-package :cotd)
(defclass inventory-window (window)
((cur-tab :initform 0 :accessor cur-tab)
(cur-inv :initform 0 :accessor cur-inv)))
(defconstant +inv-tab-inv+ 0)
(defconstant +inv-tab-descr+ 1)
(defconstant +inv-tab-char+ 2)
(defmethod make-output ((win inventory-window))
(fill-background-tiles)
;; a pane for inventory
(sdl:with-rectangle (a-rect (sdl:rectangle :x 10 :y 10 :w 305 :h 435))
(sdl:fill-surface sdl:*black* :template a-rect))
;; a pane for item description
(sdl:with-rectangle (a-rect (sdl:rectangle :x 325 :y 10 :w 305 :h (- *window-height* 20)))
(sdl:fill-surface sdl:*black* :template a-rect))
;; a pane for player chars
(sdl:with-rectangle (a-rect (sdl:rectangle :x 325 :y 245 :w 305 :h 200))
(sdl:fill-surface sdl:*black* :template a-rect))
;; a pane for displaying commands
(sdl:with-rectangle (a-rect (sdl:rectangle :x 10 :y (- *window-height* (* 2 (sdl:char-height sdl:*default-font*))) :w 620 :h 13))
(sdl:fill-surface sdl:*black* :template a-rect)
(sdl:draw-string-solid-* (format nil "~A~A~A[Esc] Exit"
(if (> (length (inv *player*)) 0)
"[d] Drop all "
"")
(if (and (> (length (inv *player*)) 0)
(> (qty (get-inv-item-by-pos (inv *player*) (cur-inv win))) 1))
"[Ctrl+d] Drop "
"")
(if (and (> (length (inv *player*)) 0)
(on-check-applic (get-inv-item-by-pos (inv *player*) (cur-inv win)))
(on-use (get-inv-item-by-pos (inv *player*) (cur-inv win)))
(funcall (on-check-applic (get-inv-item-by-pos (inv *player*) (cur-inv win))) *player* (get-inv-item-by-pos (inv *player*) (cur-inv win))))
"[u] Use "
""))
10 (sdl:y a-rect) :color sdl:*white*))
;; drawing the inventory list
(let ((cur-str) (lst (make-list 0)) (color-list (make-list 0)))
;(when (= +inv-tab-inv+ (cur-tab win)) (setf selected t))
(setf cur-str (cur-inv win))
(loop for i from 0 below (length (inv *player*))
for item = (get-inv-item-by-pos (inv *player*) i)
do
(push (capitalize-name (prepend-article +article-a+ (visible-name item))) lst)
(push (if (= i cur-str)
sdl:*yellow*
sdl:*white*)
color-list))
(setf lst (reverse lst) color-list (reverse color-list))
(draw-selection-list lst cur-str (truncate 425 15) 20 20 :color-list color-list))
;; drawing selected item description
(when (> (length (inv *player*)) 0)
(let ((item (get-inv-item-by-pos (inv *player*) (cur-inv win)))
(lines-count 0))
(setf lines-count (write-text (get-item-descr item) (sdl:rectangle :x 330 :y 15 :w (- *window-width* 330 20) :h (- *window-height* 50))))
(when (flavor-quote item)
(cond
((equal (options-font *options*) 'font-8x13) (sdl:initialise-default-font sdl:*font-8x13o*))
(t (sdl:initialise-default-font sdl:*font-6x13o*)))
(write-text (flavor-quote item) (sdl:rectangle :x 330 :y (+ 15 (* lines-count (sdl:char-height sdl:*default-font*))) :w (- *window-width* 330 20) :h (- *window-height* 50)))
(cond
((equal (options-font *options*) 'font-8x13) (sdl:initialise-default-font sdl:*font-8x13*))
(t (sdl:initialise-default-font sdl:*font-6x13*))))
))
(sdl:update-display))
(defmethod run-window ((win inventory-window))
(sdl:with-events ()
(:quit-event () (funcall (quit-func win)) t)
(:key-down-event (:key key :mod mod :unicode unicode)
;; normalize mod
(loop while (>= mod sdl-key-mod-num) do
(decf mod sdl-key-mod-num))
;; adjusting the inventory selection
(cond
((= (cur-tab win) +inv-tab-inv+) (progn (setf (cur-inv win) (run-selection-list key mod unicode (cur-inv win)))
(setf (cur-inv win) (adjust-selection-list (cur-inv win) (length (inv *player*)))))))
(cond
((sdl:key= key :sdl-key-escape)
(setf *current-window* (return-to win)) (make-output *current-window*) (return-from run-window nil))
;; d - drop all items
((and (sdl:key= key :sdl-key-d) (= mod 0))
(clear-message-list (level/small-message-box (level *world*)))
(mob-drop-item *player* (get-inv-item-by-pos (inv *player*) (cur-inv win)))
(setf *current-window* (return-to win))
(make-output *current-window*)
(return-from run-window nil))
;; Ctrl + d - drop a number of items
((and (sdl:key= key :sdl-key-d) (/= (logand mod sdl-cffi::sdl-key-mod-ctrl) 0))
(progn
(setf *current-window* (make-instance 'input-str-window
:init-input "1"
:header-str (format nil "Dropping ~A" (prepend-article +article-a+ (visible-name (get-inv-item-by-pos (inv *player*) (cur-inv win)))))
:main-str "Enter the quantity to drop"
:prompt-str "[Enter] Drop [Escape] Cancel [a] All"
:all-func #'(lambda () (format nil "~A" (qty (get-inv-item-by-pos (inv *player*) (cur-inv win)))))
:input-check-func #'(lambda (char cur-str)
(declare (ignore cur-str))
(let ((i (parse-integer (string char) :junk-allowed t)))
(if (and (not (null i))
(<= 1 i (qty (get-inv-item-by-pos (inv *player*) (cur-inv win)))))
t
nil)))
:final-check-func #'(lambda (full-input-str)
(let ((i (parse-integer full-input-str :junk-allowed t)))
(if (and (not (null i))
(<= 1 i (qty (get-inv-item-by-pos (inv *player*) (cur-inv win)))))
t
nil)))
))
(make-output *current-window*)
(let ((qty (run-window *current-window*)))
(when qty
(clear-message-list (level/small-message-box (level *world*)))
(mob-drop-item *player* (get-inv-item-by-pos (inv *player*) (cur-inv win)) :qty (parse-integer qty :junk-allowed nil))
(setf *current-window* (return-to win))
(make-output *current-window*)
(return-from run-window nil)))
))
;; u - use an item
((sdl:key= key :sdl-key-u)
(let ((item (get-inv-item-by-pos (inv *player*) (cur-inv win)))
(result))
(setf result (window-use-item item (return-to win)))
(when result
(return-from run-window nil)))))
(make-output *current-window*)
)
(:video-expose-event () (make-output *current-window*)))
)
| 8,953
|
Common Lisp
|
.lisp
| 129
| 41.883721
| 198
| 0.421557
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
6d1751261c594c83c3cebe7831d11159430ddc3e8a4ac8ffb079ea121dd5a653
| 2,920
|
[
-1
] |
2,921
|
window-highscores.lisp
|
gwathlobal_CotD/src/windows/window-highscores.lisp
|
(in-package :cotd)
(defclass highscores-window (window)
((highscores-place :initform nil :initarg :highscores-place :accessor highscores-place)))
(defmethod make-output ((win highscores-window))
;; fill the screen black
(sdl:with-rectangle (a-rect (sdl:rectangle :x 0 :y 0 :w *window-width* :h *window-height*))
(sdl:fill-surface sdl:*black* :template a-rect))
(sdl:draw-string-solid-* "HIGH SCORES" (truncate *window-width* 2) 10 :justify :center :color sdl:*white*)
(loop for record in (highscores-table/records *highscores*)
for n from 0 to 9
with str = nil
with color = sdl:*white*
with additional-record = (if (> (length (highscores-table/records *highscores*)) 10)
(nth 10 (highscores-table/records *highscores*))
nil)
do
(setf str (format nil " ~3<~A.~> ~A~%~%" (1+ n) (write-highscore-record-to-str record)))
(if (and (highscores-place win)
(= (highscores-place win) n))
(setf color sdl:*yellow*)
(setf color sdl:*white*))
(sdl:with-rectangle (rect (sdl:rectangle :x 0 :y (+ 30 (* n (sdl:char-height sdl:*default-font*) 3)) :w *window-width* :h (* (sdl:char-height sdl:*default-font*) 2)))
(write-text str rect :color color))
finally
(when additional-record
(sdl:draw-string-solid-* " ---" 0 (+ 30 (* 10 (sdl:char-height sdl:*default-font*) 3)) :color sdl:*white*)
(setf str (format nil " ~3<11.~> ~A~%" (write-highscore-record-to-str additional-record)))
(if (and (highscores-place win)
(= (highscores-place win) 10))
(setf color sdl:*yellow*)
(setf color sdl:*white*))
(sdl:with-rectangle (rect (sdl:rectangle :x 0 :y (+ 30 (sdl:char-height sdl:*default-font*) (* 10 (sdl:char-height sdl:*default-font*) 3)) :w *window-width* :h (* (sdl:char-height sdl:*default-font*) 2)))
(write-text str rect :color color)))
)
(sdl:draw-string-solid-* (format nil "[Esc] Quit")
10 (- *window-height* 13 (sdl:char-height sdl:*default-font*)))
(sdl:update-display))
(defmethod run-window ((win highscores-window))
(sdl:with-events ()
(:quit-event () (funcall (quit-func win)) t)
(:key-down-event (:key key :mod mod :unicode unicode)
(declare (ignore mod unicode))
(cond
((sdl:key= key :sdl-key-escape)
(setf *current-window* (return-to win)) (make-output *current-window*) (return-from run-window nil))
)
(make-output *current-window*)
)
(:video-expose-event () (make-output *current-window*)))
)
| 2,890
|
Common Lisp
|
.lisp
| 50
| 44.88
| 217
| 0.562166
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
0fc9d6c0f9a459bc9735e526133e16460b5b11e0838a9f08c8c0a404467d2e80
| 2,921
|
[
-1
] |
2,922
|
window-loading.lisp
|
gwathlobal_CotD/src/windows/window-loading.lisp
|
(in-package :cotd)
(defclass loading-window (window)
((update-func :initarg :update-func :accessor update-func)
(cur-str :initform "Generating map" :initarg :cur-str :accessor cur-str)
(hint-text :initform (nth (random (length *scenario-hints*)) *scenario-hints*) :initarg :hint-text :accessor loading-window/hint-text)))
(defmethod make-output ((win loading-window))
;; fill the screen black
(sdl:with-rectangle (a-rect (sdl:rectangle :x 0 :y 0 :w *window-width* :h *window-height*))
(sdl:fill-surface sdl:*black* :template a-rect))
;; invoke the function to update the window
(funcall (update-func win) win)
(when (loading-window/hint-text win)
(let* ((max-lines 0)
(x-margin 30)
(x x-margin)
(w (- *window-width* (* x-margin 2)))
(y-margin 30))
(sdl:with-rectangle (a-rect (sdl:rectangle :x 0 :y 0 :w w :h (* 1 (sdl:get-font-height))))
(setf max-lines (write-text (loading-window/hint-text win) a-rect :count-only t)))
(sdl:with-rectangle (a-rect (sdl:rectangle :x x :y (- *window-height* y-margin (* max-lines (sdl:get-font-height))) :w w :h (* max-lines (sdl:get-font-height))))
(write-text (loading-window/hint-text win) a-rect))))
(sdl:update-display))
(defmethod run-window ((win loading-window))
(sdl:with-events ()
(:quit-event () (funcall (quit-func win)) t)
(:video-expose-event () (make-output *current-window*)))
)
| 1,483
|
Common Lisp
|
.lisp
| 27
| 48.222222
| 168
| 0.641221
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
74930e036ea8edc2abed1c86f62432d73da1ce54746125dc614808ba9c8778f6
| 2,922
|
[
-1
] |
2,923
|
window-classes.lisp
|
gwathlobal_CotD/src/windows/window-classes.lisp
|
(in-package :cotd)
(defconstant +cotd-unicode-question-mark+ 63)
(defconstant +cotd-unicode-at-sign+ 64)
(defconstant +cotd-unicode-latin-q-captial+ 81)
(defconstant +cotd-unicode-latin-a-small+ 97)
(defconstant +cotd-unicode-latin-b-small+ 98)
(defconstant +cotd-unicode-latin-c-small+ 99)
(defconstant +cotd-unicode-latin-d-small+ 100)
(defconstant +cotd-unicode-latin-e-small+ 101)
(defconstant +cotd-unicode-latin-f-small+ 102)
(defconstant +cotd-unicode-latin-i-small+ 105)
(defconstant +cotd-unicode-latin-j-small+ 106)
(defconstant +cotd-unicode-latin-l-small+ 108)
(defconstant +cotd-unicode-latin-m-small+ 109)
(defconstant +cotd-unicode-latin-n-small+ 110)
(defconstant +cotd-unicode-latin-r-small+ 114)
(defconstant +cotd-unicode-latin-s-small+ 115)
(defconstant +cotd-unicode-latin-u-small+ 117)
(defconstant +cotd-unicode-greater-than-sign+ 62)
(defconstant +cotd-unicode-less-than-sign+ 60)
(defparameter *glyph-w* 15)
(defparameter *glyph-h* 15)
(defvar *quit-func* 0)
(defvar *start-func* 0)
(defparameter *current-window* nil)
(defparameter *rects-to-update* ())
(defvar *msg-box-window-height*)
(defenum:defenum menu-command-enum (:menu-stop-loop
:menu-continue
:menu-load-scenario
))
(defclass window ()
((return-to :initarg :return-to :initform *current-window* :accessor return-to)
(quit-func :initform *quit-func* :accessor quit-func)))
(defgeneric make-output (win))
(defgeneric get-input (win key mod unicode))
(defgeneric run-window (win))
(defun go-to-quit-game ()
(funcall *quit-func*))
(defun go-to-start-game ()
(funcall *start-func*))
(defmacro continuable (&body body)
"Helper macro that we can use to allow us to continue from an error. Remember to hit C in slime or pick the restart so errors don't kill the app."
`(restart-case (progn ,@body) (continue () :report "Continue")))
#+swank
(defun update-swank ()
"Called from within the main loop, this keep the lisp repl working while the game runs"
(continuable (let ((connection (or swank::*emacs-connection* (swank::default-connection))))
(when connection
(swank::handle-requests connection t)))))
#-swank
(defun update-swank ()
nil)
| 2,358
|
Common Lisp
|
.lisp
| 53
| 38.962264
| 149
| 0.690487
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
ee637440272f1bdd3432fe316e8b4e524165d8af2ba2fa74156430f536d321e8
| 2,923
|
[
-1
] |
2,924
|
window-load-game.lisp
|
gwathlobal_CotD/src/windows/window-load-game.lisp
|
(in-package :cotd)
(defclass load-game-window (window)
((save-game-type :initarg :save-game-type :type save-game-type-enum)
(title-string :type string)
(display-str-list :initform () :type list)
(game-pathname-list :initform () :type list)
(descr-pathname-list :initform () :type list)
(game-slot-list :initform () :type list)
(cur-sel :initform 0 :type fixnum)))
(defmethod initialize-instance :after ((win load-game-window) &key)
(with-slots (save-game-type title-string display-str-list game-pathname-list descr-pathname-list game-slot-list) win
(loop with filename-descr = (make-pathname :name *save-descr-filename*)
with filename-game = (make-pathname :name *save-game-filename*)
with serialized-save-descr = nil
with save-descr-list = ()
for pathname in (find-all-save-game-paths save-game-type)
for descr-pathname = (merge-pathnames filename-descr pathname)
for game-pathname = (merge-pathnames filename-game pathname)
do
(setf serialized-save-descr (load-descr-from-disk descr-pathname))
(when serialized-save-descr
(push (list serialized-save-descr game-pathname descr-pathname) save-descr-list))
finally
(setf save-descr-list (stable-sort save-descr-list #'<
:key #'(lambda (a)
(serialized-save-descr/save-date (first a)))))
(loop for (save-descr game-pathname descr-pathname) in save-descr-list do
(with-slots (id player-name sector-name mission-name world-date-str save-date) save-descr
(multiple-value-bind (second minute hour date month year day-of-week dst-p tz) (decode-universal-time save-date)
(declare (ignore day-of-week dst-p tz))
(push (format nil "~40@<~A~> ~40@<~A~>~30@<~A~>~%~A [~A]" player-name
(if sector-name
sector-name
"")
(if mission-name
mission-name
"")
(show-date-time-short (set-current-date-time year (1- month) (1- date) hour minute second))
world-date-str)
display-str-list))
(push id game-slot-list))
(push game-pathname game-pathname-list)
(push descr-pathname descr-pathname-list)))
(case save-game-type
(:save-game-campaign (setf title-string "LOAD CAMPAIGN"))
(:save-game-scenario (setf title-string "LOAD SCENARIO")))))
(defmethod make-output ((win load-game-window))
(with-slots (title-string display-str-list cur-sel) win
;; fill the screen black
(sdl:with-rectangle (a-rect (sdl:rectangle :x 0 :y 0 :w *window-width* :h *window-height*))
(sdl:fill-surface sdl:*black* :template a-rect))
(sdl:draw-string-solid-* title-string (truncate *window-width* 2) 10 :justify :center :color sdl:*white*)
(let ((color-list nil))
(dotimes (i (length display-str-list))
(if (= i cur-sel)
(setf color-list (append color-list (list sdl:*yellow*)))
(setf color-list (append color-list (list sdl:*white*)))))
(draw-multiline-selection-list display-str-list cur-sel 20 (+ 10 10 (sdl:char-height sdl:*default-font*)) (- *window-width* 10) (- *window-height* (+ 10 (sdl:char-height sdl:*default-font*)) (sdl:char-height sdl:*default-font*) 20)
color-list)
;;(draw-selection-list (menu-items win) cur-sel (length (menu-items win)) 20 (+ 10 30 20 (sdl:char-height sdl:*default-font*) (sdl:char-height sdl:*default-font*)) :color-list color-list :use-letters t)
)
(sdl:draw-string-solid-* (format nil "~A[Up/Down] Move selection [Shift+Up/Down] Scroll page [Esc] Quit"
(if display-str-list
"[Enter] Load game [d] Delete game "
""))
10 (- *window-height* 13 (sdl:char-height sdl:*default-font*)))
(sdl:update-display)))
(defmethod run-window ((win load-game-window))
(with-slots (display-str-list game-pathname-list descr-pathname-list cur-sel game-slot-list) win
(sdl:with-events ()
(:quit-event () (funcall (quit-func win)) t)
(:key-down-event (:key key :mod mod :unicode unicode)
(when display-str-list
(setf cur-sel (run-selection-list key mod unicode cur-sel :start-page (truncate cur-sel (length display-str-list)) :max-str-per-page (length display-str-list) :use-letters nil))
(setf cur-sel (adjust-selection-list cur-sel (length display-str-list))))
(cond
;; esc - exit the window
((sdl:key= key :sdl-key-escape)
(setf *current-window* (return-to win))
(make-output *current-window*)
(return-from run-window nil))
;; d - remove the selected game
((or (and (sdl:key= key :sdl-key-d))
(eq unicode +cotd-unicode-latin-d-small+))
(when (and game-pathname-list (nth cur-sel game-pathname-list)
descr-pathname-list (nth cur-sel descr-pathname-list))
(setf *current-window* (make-instance 'select-obj-window
:return-to *current-window*
:header-line "Are you sure you want to delete this game?"
:enter-func #'(lambda (current-sel)
(case current-sel
(0 (progn
(let* ((descr-pathname (nth cur-sel descr-pathname-list))
(dir-to-delete (make-pathname :host (pathname-host descr-pathname)
:device (pathname-device descr-pathname)
:directory (pathname-directory descr-pathname)))
(result))
(setf result (delete-dir-from-disk dir-to-delete))
(when (not result)
(setf *current-window* (make-instance 'display-msg-window
:msg-line "An error has occured while the system tried to remove the game!"))
(make-output *current-window*)
(run-window *current-window*))
(setf game-pathname-list (remove (nth cur-sel game-pathname-list) game-pathname-list))
(setf descr-pathname-list (remove (nth cur-sel descr-pathname-list) descr-pathname-list))
(setf display-str-list (remove (nth cur-sel display-str-list) display-str-list))
(when (>= cur-sel (length display-str-list))
(setf cur-sel (1- (length display-str-list)))))
(setf *current-window* (return-to *current-window*))))
(t (progn
(setf *current-window* (return-to *current-window*)))))
)
:line-list (list "Yes" "No")
:prompt-list (list #'(lambda (cur-sel)
(declare (ignore cur-sel))
"[Enter] Select [Esc] Exit")
#'(lambda (cur-sel)
(declare (ignore cur-sel))
"[Enter] Select [Esc] Exit"))))
(make-output *current-window*)
(run-window *current-window*)
)
)
;; enter - load selected game
((or (sdl:key= key :sdl-key-return) (sdl:key= key :sdl-key-kp-enter))
(when (and game-pathname-list (nth cur-sel game-pathname-list))
(let ((saved-game nil)
(serialized-save-descr (load-descr-from-disk (nth cur-sel descr-pathname-list))))
(if (and serialized-save-descr
(not (eq (getf (serialized-save-descr/params serialized-save-descr) :version) *save-version*)))
(progn
(setf *current-window* (make-instance 'display-msg-window
:msg-line (format nil "Failed to load the game!~%The save file is incompatible with the current version of the game and it is recommended to remove it." )
:w (- *window-width* 400)))
(make-output *current-window*)
(run-window *current-window*))
(progn
(setf saved-game (load-game-from-disk (nth cur-sel game-pathname-list)))
(if saved-game
(progn
(setf *current-window* (make-instance 'display-msg-window
:msg-line (format nil "Save game loaded successfully!" )
:w (- *window-width* 400)))
(make-output *current-window*)
(run-window *current-window*)
(setf (game-manager/game-slot-id *game-manager*) (nth cur-sel game-slot-list))
(return-from run-window (serialized-game/save-type saved-game)))
(progn
(setf *current-window* (make-instance 'display-msg-window
:msg-line (format nil "Failed to load the game!~%The save file is corrupted and it is recommended to remove it." )
:w (- *window-width* 400)))
(make-output *current-window*)
(run-window *current-window*))
)))
))
)
)
(make-output *current-window*)
)
(:video-expose-event () (make-output *current-window*)))
))
| 13,125
|
Common Lisp
|
.lisp
| 161
| 44.049689
| 237
| 0.406514
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
77425097792cc96cab650046a11a944d770c6958fbce8819a11f1c236bd1bb95
| 2,924
|
[
-1
] |
2,925
|
window-map-select.lisp
|
gwathlobal_CotD/src/windows/window-map-select.lisp
|
(in-package :cotd)
(defconstant +map-select-win-map+ 0)
(defconstant +map-select-win-mobs+ 1)
(defclass map-select-window (cell-window)
((max-x :initform 0 :accessor max-x)
(max-y :initform 0 :accessor max-y)
(exec-func :initarg :exec-func :accessor exec-func)
(check-lof :initform nil :initarg :check-lof :accessor check-lof)
(cmd-str :initarg :cmd-str :accessor cmd-str)
(cur-sel :initform 0 :accessor cur-sel)
(start-map-select :initform nil :initarg :start-map-select :accessor start-map-select)
(sel-list :initform (stable-sort (copy-list (visible-mobs *player*))
#'(lambda (a b)
(if (< (get-distance-3d (x *player*) (y *player*) (z *player*) (x a) (y a) (z a))
(get-distance-3d (x *player*) (y *player*) (z *player*) (x b) (y b) (z b)))
t
nil))
:key #'get-mob-by-id)
:initarg :sel-list :accessor sel-list)
(cur-tab :initform +map-select-win-map+ :accessor cur-tab))) ;; map-select-win-... constants
(defmethod initialize-instance :after ((win map-select-window) &key)
(when (start-map-select win)
(funcall (start-map-select win))))
(defun map-select-update (win)
(update-map-area *start-map-x* 0 :rel-x (view-x *player*) :rel-y (view-y *player*) :rel-z (view-z *player*)
:post-func #'(lambda (x y x1 y1)
(loop for sound in (heard-sounds *player*)
when (and (= (sound-x sound) x)
(= (sound-y sound) y)
(= (sound-z sound) (view-z *player*)))
do
(draw-glyph x1
y1
31
:front-color sdl:*white*
:back-color sdl:*black*))))
;; drawing the highlighting rectangle around the viewed grid-cell
(let ((lof-blocked t))
(let ((x1 0) (y1 0) (color) (tx (view-x *player*)) (ty (view-y *player*)) (tz (view-z *player*)))
(declare (type fixnum x1 y1))
(multiple-value-bind (sx sy max-x max-y) (calculate-start-coord (view-x *player*) (view-y *player*) (memo (level *world*)) *max-x-view* *max-y-view*)
(setf (max-x win) max-x (max-y win) max-y)
;; calculate the coordinates where to draw the rectangle
(setf x1 (+ (* (- (view-x *player*) sx) *glyph-w*) *start-map-x*))
(setf y1 (+ (* (- (view-y *player*) sy) *glyph-h*) ))
;;(format t "VIEW X,Y = (~A, ~A); sx, sy = (~A, ~A); x1 , y1 = (~A, ~A)~%" (view-x *player*) (view-y *player*) sx sy x1 y1)
(when (check-lof win)
(line-of-sight (x *player*) (y *player*) (z *player*) (view-x *player*) (view-y *player*) (view-z *player*)
#'(lambda (dx dy dz prev-cell)
(declare (type fixnum dx dy))
(let ((exit-result t))
(block nil
(setf tx dx ty dy tz dz)
(unless (check-LOS-propagate dx dy dz prev-cell :check-projectile t)
(setf exit-result 'exit)
(return))
)
exit-result))))
(when (and (= tx (view-x *player*)) (= ty (view-y *player*)) (= tz (view-z *player*)))
(setf lof-blocked nil))
;; adjust color depending on the target
(if (and (not lof-blocked)
(get-mob-* (level *world*) (view-x *player*) (view-y *player*) (view-z *player*))
(get-single-memo-visibility (get-memo-* (level *world*) (view-x *player*) (view-y *player*) (view-z *player*)))
(check-mob-visible (get-mob-* (level *world*) (view-x *player*) (view-y *player*) (view-z *player*)) :observer *player*))
(setf color sdl:*red*)
(setf color sdl:*yellow*))
;; draw the rectangle
(sdl:with-rectangle (l-rect (sdl:rectangle :x x1 :y y1 :w 1 :h *glyph-h*))
(sdl:fill-surface color :template l-rect))
(sdl:with-rectangle (r-rect (sdl:rectangle :x (+ x1 (1- *glyph-w*)) :y y1 :w 1 :h *glyph-h*))
(sdl:fill-surface color :template r-rect))
(sdl:with-rectangle (t-rect (sdl:rectangle :x x1 :y y1 :w *glyph-w* :h 1))
(sdl:fill-surface color :template t-rect))
(sdl:with-rectangle (b-rect (sdl:rectangle :x x1 :y (+ y1 (1- *glyph-h*)) :w *glyph-w* :h 1))
(sdl:fill-surface color :template b-rect))))
;; drawing a list of objects in the grid-cell instead of a message box
(sdl:with-rectangle (obj-list-rect (sdl:rectangle :x 10 :y (- *window-height* *msg-box-window-height* 10) :w (- *window-width* 260 10) :h *msg-box-window-height*))
(sdl:fill-surface sdl:*black* :template obj-list-rect))
(let ((str (create-string))
(feature-list)
(mob (get-mob-* (level *world*) (view-x *player*) (view-y *player*) (view-z *player*))))
(when (get-single-memo-visibility (get-memo-* (level *world*) (view-x *player*) (view-y *player*) (view-z *player*)))
;;(format t "HERE~%")
(when lof-blocked
(format str "Line of fire blocked!~%"))
(format str "~A (~A, ~A, ~A)~A~A~A~A" (capitalize-name (get-terrain-name (get-terrain-* (level *world*) (view-x *player*) (view-y *player*) (view-z *player*)))) (view-x *player*) (view-y *player*) (view-z *player*)
(if *cotd-release* "" (format nil " Light: ~A-~A"
(get-single-memo-light (get-memo-* (level *world*) (view-x *player*) (view-y *player*) (view-z *player*)))
(get-outdoor-light-* (level *world*) (view-x *player*) (view-y *player*) (view-z *player*))))
(if *cotd-release* "" (format nil " ~A" (aref (aref (connect-map (level *world*)) 1) (view-x *player*) (view-y *player*) (view-z *player*))))
(if *cotd-release* "" (format nil " ~A" (aref (aref (connect-map (level *world*)) 3) (view-x *player*) (view-y *player*) (view-z *player*))))
(if *cotd-release* "" (format nil " ~A" (level-cells-connected-p (level *world*) (x *player*) (y *player*) (z *player*) (view-x *player*) (view-y *player*) (view-z *player*)
(if (riding-mob-id *player*)
(map-size (get-mob-by-id (riding-mob-id *player*)))
(map-size *player*))
(get-mob-move-mode *player*) :can-open-doors (can-open-doors *player*))))
)
(setf feature-list (get-features-* (level *world*) (view-x *player*) (view-y *player*) (view-z *player*)))
(dolist (feature feature-list)
(format str ", ~A~A"
(capitalize-name (name (get-feature-by-id feature)))
(if *cotd-release* "" (format nil " (~A)" (counter (get-feature-by-id feature))))))
(when (and mob
(check-mob-visible mob :observer *player*))
(format str "~%~A~A~A"
(capitalize-name (visible-name mob))
(if (riding-mob-id mob)
(format nil ", riding ~A" (prepend-article +article-a+ (visible-name (get-mob-by-id (riding-mob-id mob)))))
"")
(if (and (check-lof win) (not lof-blocked))
(format nil " (hit: ~D%)" (if (< (get-distance (x *player*) (y *player*) (view-x *player*) (view-y *player*)) 2)
100
(truncate (- (r-acc *player*) (* (get-distance (x *player*) (y *player*) (view-x *player*) (view-y *player*)) *acc-loss-per-tile*)))))
"")))
(loop for item-id in (get-items-* (level *world*) (view-x *player*) (view-y *player*) (view-z *player*))
for item = (get-item-by-id item-id)
do
(format str "~%~A"
(capitalize-name (prepend-article +article-a+ (visible-name item)))
))
)
(sdl:with-rectangle (rect (sdl:rectangle :x 10 :y (- *window-height* *msg-box-window-height* 20) :w (- *window-width* 260 10) :h (- *msg-box-window-height* (* 2 (sdl:get-font-height)))))
(write-text str rect)))
;; drawing the propmt line
(let ((x 10) (y (- *window-height* 5 (sdl:char-height sdl:*default-font*))) (w (- *window-width* 260 10)) (h (sdl:get-font-height)))
(sdl:with-rectangle (a-rect (sdl:rectangle :x x :y y :w w :h h))
(sdl:fill-surface sdl:*black* :template a-rect)
(cond
((= (cur-tab win) +map-select-win-mobs+) (sdl:draw-string-solid-* (format nil "[Up/Down] Move selection [Shift+Up/Down] Scroll page [Ctrl+l] Map select [Esc] Quit") x y :color sdl:*white*))
((and (= (cur-tab win) +map-select-win-map+) (sel-list win)) (sdl:draw-string-solid-* (format nil "~A[Ctrl+l] Mob select [Esc] Quit" (nth +map-select-win-map+ (cmd-str win))) x y :color sdl:*white*))
(t (sdl:draw-string-solid-* (format nil "~A[Esc] Quit" (first (cmd-str win))) x y :color sdl:*white*)))
))))
(defmethod make-output ((win map-select-window))
(fill-background-tiles)
(show-char-properties (+ *start-map-x* 20 (* *glyph-w* *max-x-view*)) 10 (idle-calcing win))
;(show-small-message-box *glyph-w* (- *window-height* *msg-box-window-height* 10) (+ 250 (+ 10 (* *glyph-w* *max-x-view*))))
(show-level-weather (+ *start-map-x* 20 (* *glyph-w* *max-x-view*)) (+ (- *window-height* *msg-box-window-height* 20) (* -2 (sdl:char-height sdl:*default-font*))))
(cond
((and (= (cur-tab win) +map-select-win-mobs+) (sel-list win))
(progn
(let ((color-list)
)
(dotimes (i (length (sel-list win)))
(if (= i (cur-sel win))
(setf color-list (append color-list (list sdl:*yellow*)))
(setf color-list (append color-list (list sdl:*white*)))))
(draw-selection-list (sel-list win) (cur-sel win) 6 (- *window-width* 260) (- *window-height* *msg-box-window-height* 20)
:color-list color-list
:char-height (if (> *glyph-h* (+ (sdl:char-height sdl:*default-font*) *sel-y-offset*))
*glyph-h*
(+ (sdl:char-height sdl:*default-font*) *sel-y-offset*))
:str-func #'(lambda (x y color str use-letters)
;; the list of strings to display is basically a list of visible mob IDs, so 'str' param is a mob ID here
;; use-letters here can be
;; nil
;; (list i str-per-page)
(if use-letters
(progn
(sdl:draw-string-solid-* (if (< (first use-letters) (second use-letters))
(format nil "[~A] " (nth (first use-letters) *char-list*))
(format nil " "))
x y :color color)
(draw-visible-mob-func (+ x (* 5 (sdl:char-width sdl:*default-font*))) y (get-mob-by-id str) *player* color))
(progn
(draw-visible-mob-func x y (get-mob-by-id str) *player* color))))
:use-letters t))))
(t (show-visible-mobs (- *window-width* 260) (- *window-height* *msg-box-window-height* 20) 260 *msg-box-window-height* :mob *player* :visible-mobs (sel-list win))))
(map-select-update win)
(sdl:update-display))
(defmethod run-window ((win map-select-window))
(sdl:with-events ()
(:quit-event () (funcall (quit-func win)) t)
(:key-down-event (:key key :mod mod :unicode unicode)
(cond
((= (cur-tab win) +map-select-win-mobs+)
(progn
(when (and (sdl:key= key :sdl-key-l) (/= (logand mod sdl-cffi::sdl-key-mod-ctrl) 0))
(setf (cur-tab win) +map-select-win-map+))
(setf (cur-sel win) (run-selection-list key mod unicode (cur-sel win) :start-page (truncate (cur-sel win) 6) :max-str-per-page 6))
(setf (cur-sel win) (adjust-selection-list (cur-sel win) (length (sel-list win))))
(when (sel-list win)
(setf (view-x *player*) (x (get-mob-by-id (nth (cur-sel win) (sel-list win))))
(view-y *player*) (y (get-mob-by-id (nth (cur-sel win) (sel-list win))))
(view-z *player*) (z (get-mob-by-id (nth (cur-sel win) (sel-list win))))))
))
(t (progn
(when (and (sdl:key= key :sdl-key-l) (/= (logand mod sdl-cffi::sdl-key-mod-ctrl) 0) (sel-list win))
(setf (cur-tab win) +map-select-win-mobs+)
(when (sel-list win)
(setf (view-x *player*) (x (get-mob-by-id (nth (cur-sel win) (sel-list win))))
(view-y *player*) (y (get-mob-by-id (nth (cur-sel win) (sel-list win))))
(view-z *player*) (z (get-mob-by-id (nth (cur-sel win) (sel-list win)))))))
;; move the target rectangle
(when (or (sdl:key= key :sdl-key-pageup) (sdl:key= key :sdl-key-kp9))
(when (and (< (view-x *player*) (- (array-dimension (terrain (level *world*)) 0) 1)) (> (view-y *player*) 0))
(incf (view-x *player*)) (decf (view-y *player*))))
(when (or (sdl:key= key :sdl-key-up) (sdl:key= key :sdl-key-kp8))
(when (> (view-y *player*) 0)
(decf (view-y *player*))))
(when (or (sdl:key= key :sdl-key-home) (sdl:key= key :sdl-key-kp7))
(when (and (> (view-x *player*) 0) (> (view-y *player*) 0))
(decf (view-x *player*)) (decf (view-y *player*))))
(when (or (sdl:key= key :sdl-key-right) (sdl:key= key :sdl-key-kp6))
(when (< (view-x *player*) (- (array-dimension (terrain (level *world*)) 0) 1))
(incf (view-x *player*))))
(when (or (sdl:key= key :sdl-key-left) (sdl:key= key :sdl-key-kp4))
(when (> (view-x *player*) 0)
(decf (view-x *player*))))
(when (or (sdl:key= key :sdl-key-pagedown) (sdl:key= key :sdl-key-kp3))
(when (and (< (view-x *player*) (- (array-dimension (terrain (level *world*)) 0) 1)) (< (view-y *player*) (- (array-dimension (terrain (level *world*)) 1) 1)))
(incf (view-x *player*)) (incf (view-y *player*))))
(when (or (sdl:key= key :sdl-key-down) (sdl:key= key :sdl-key-kp2))
(when (< (view-y *player*) (- (array-dimension (terrain (level *world*)) 1) 1))
(incf (view-y *player*))))
(when (or (sdl:key= key :sdl-key-end) (sdl:key= key :sdl-key-kp1))
(when (and (> (view-x *player*) 0) (< (view-y *player*) (- (array-dimension (terrain (level *world*)) 1) 1)))
(decf (view-x *player*)) (incf (view-y *player*))))
(when (and (sdl:key= key :sdl-key-period) (/= (logand mod sdl-cffi::sdl-key-mod-shift) 0))
(when (and (> (view-z *player*) 0))
(decf (view-z *player*))))
(when (and (sdl:key= key :sdl-key-comma) (/= (logand mod sdl-cffi::sdl-key-mod-shift) 0))
(when (and (< (view-z *player*) (- (array-dimension (terrain (level *world*)) 2) 1)))
(incf (view-z *player*))))
))
)
(cond
((sdl:key= key :sdl-key-escape) (setf (view-x *player*) (x *player*) (view-y *player*) (y *player*) (view-z *player*) (z *player*))
(setf *current-window* (return-to win))
(make-output *current-window*)
(return-from run-window nil))
((or (sdl:key= key :sdl-key-return) (sdl:key= key :sdl-key-kp-enter)) (when (funcall (exec-func win))
(make-output *current-window*)
(return-from run-window t)))
)
(make-output *current-window*))
(:video-expose-event () (make-output *current-window*)))
)
| 19,219
|
Common Lisp
|
.lisp
| 238
| 53.079832
| 225
| 0.440561
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
203da2bcfa0593ad6edfd521f42dad9ad9e9957b42e37603f0817228b788325e
| 2,925
|
[
-1
] |
2,926
|
window-campaign.lisp
|
gwathlobal_CotD/src/windows/window-campaign.lisp
|
(in-package :cotd)
(defenum:defenum campaign-window-tab-type (:campaign-window-map-mode
:campaign-window-mission-mode
:campaign-window-status-mode
:campaign-window-effects-mode
:campaign-window-command-mode
:campaign-window-help-mode))
(defclass campaign-window (window)
((cur-sector :initform (cons 0 0) :initarg :cur-sector :accessor campaign-window/cur-sector :type cons)
(cur-mode :initform :campaign-window-map-mode :initarg :cur-mode :accessor campaign-window/cur-mode :type campaign-window-tab-type)
(prev-mode :initform :campaign-window-mission-mode :initarg :prev-mode :accessor campaign-window/prev-mode :type campaign-window-tab-type)
(cur-sel :initform 0 :accessor campaign-window/cur-sel :type fixnum)
(avail-missions :initform () :accessor campaign-window/avail-missions :type list)
(test-map-func :initform nil :initarg :test-map-func :accessor campaign-window/test-map-func)
(reveal-lair :initform t :initarg :reveal-lair :accessor campaign-window/reveal-lair :type boolean)))
(defmethod initialize-instance :after ((win campaign-window) &key)
(with-slots (cur-mode) win
(campaign-win-calculate-avail-missions win)
(when (eq cur-mode :campaign-window-command-mode)
(campaign-win-display-command win))
(when (eq cur-mode :campaign-window-status-mode)
(campaign-win-display-sitrep win))
(when (eq cur-mode :campaign-window-effects-mode)
(campaign-win-display-effects win))
(when (eq cur-mode :campaign-window-help-mode)
(campaign-win-display-help win))
(when (eq cur-mode :campaign-window-mission-mode)
(campaign-win-move-select-to-mission win)))
)
(defmethod campaign-win-display-sitrep ((win campaign-window))
(when (not (eq (campaign-window/cur-mode win) :campaign-window-status-mode))
(setf (campaign-window/prev-mode win) (campaign-window/cur-mode win))
(setf (campaign-window/cur-mode win) :campaign-window-status-mode))
(let ((sitrep-msg-box (make-message-box)))
(setf (colored-txt-list (message-box-strings sitrep-msg-box)) (append (colored-txt-list (message-box-strings (world/mission-message-box *world*)))
(colored-txt-list (message-box-strings (world/event-message-box *world*)))
(colored-txt-list (message-box-strings (world/effect-message-box *world*)))))
(setf *current-window* (make-instance 'message-window
:return-to win
:message-box sitrep-msg-box
:header-str "SITUATION REPORT"))
(make-output *current-window*)
(run-window *current-window*)
)
(setf (campaign-window/cur-mode win) (campaign-window/prev-mode win)))
(defmethod campaign-win-display-effects ((win campaign-window))
(let* ((effects-message-box (make-message-box))
(message-box-list `(,effects-message-box)))
(loop for campaign-effect in (world/campaign-effects *world*)
when (campaign-effect/displayed campaign-effect)
do
(add-message (format nil "~A" (campaign-effect/name campaign-effect)) sdl:*yellow* message-box-list)
(if (campaign-effect/cd campaign-effect)
(add-message (format nil " [~A turn~:P left]~%" (campaign-effect/cd campaign-effect)) sdl:*white* message-box-list)
(add-message (format nil "~%") sdl:*white* message-box-list))
(add-message (format nil "~A~%~%" (campaign-effect/descr campaign-effect)) sdl:*white* message-box-list))
(when (not (eq (campaign-window/cur-mode win) :campaign-window-effects-mode))
(setf (campaign-window/prev-mode win) (campaign-window/cur-mode win))
(setf (campaign-window/cur-mode win) :campaign-window-effects-mode))
(setf *current-window* (make-instance 'message-window
:return-to win
:message-box effects-message-box
:header-str "CURRENT EFFECTS"))
(make-output *current-window*)
(run-window *current-window*)
(setf (campaign-window/cur-mode win) (campaign-window/prev-mode win))))
(defmethod campaign-win-display-help ((win campaign-window))
(when (not (eq (campaign-window/cur-mode win) :campaign-window-help-mode))
(setf (campaign-window/prev-mode win) (campaign-window/cur-mode win))
(setf (campaign-window/cur-mode win) :campaign-window-help-mode))
(let* ((help-msg-box (make-message-box))
(msg-box-list `(,help-msg-box))
(text-list (list (list +faction-type-angels+ +game-event-campaign-angel-win+)
(list +faction-type-demons+ +game-event-campaign-demon-win+)
(list +faction-type-military+ +game-event-campaign-military-win+)))
(keys-txt (get-txt-from-file "help/campaign_keybindings.txt")))
(when (find (get-general-faction-from-specific (world/player-specific-faction *world*)) text-list :key #'(lambda (a) (first a)))
(let ((objective-text (funcall (descr-func (get-game-event-by-id (second (find (get-general-faction-from-specific (world/player-specific-faction *world*)) text-list :key #'(lambda (a) (first a)))))))))
(add-message objective-text sdl:*white* msg-box-list)))
(when keys-txt
(add-message (format nil "~%~%~%") sdl:*white* msg-box-list)
(add-message keys-txt sdl:*white* msg-box-list))
(setf *current-window* (make-instance 'message-window
:return-to win
:message-box help-msg-box
:header-str "HELP"))
(make-output *current-window*)
(run-window *current-window*)
)
(setf (campaign-window/cur-mode win) (campaign-window/prev-mode win)))
(defun campaign-win-display-command (win &key (can-esc nil))
(when (not (eq (campaign-window/cur-mode win) :campaign-window-command-mode))
(setf (campaign-window/prev-mode win) (campaign-window/cur-mode win))
(setf (campaign-window/cur-mode win) :campaign-window-command-mode))
(let ((player-faction (get-general-faction-from-specific (world/player-specific-faction *world*))))
(when (not (gethash player-faction (world/commands *world*)))
(let ((command-list (loop for command being the hash-values in *campaign-commands*
when (and (eq (campaign-command/faction-type command) player-faction)
(not (campaign-command/disabled command))
(funcall (campaign-command/on-check-func command) *world* command))
collect command))
(menu-items ())
(prompt-list ())
(enter-func nil)
(header-str nil)
(descr-list ()))
(setf header-str "Select a command")
(setf menu-items (loop for command in command-list
collect (format nil "~A ~A"
(funcall (campaign-command/name-func command) *world*)
(if (campaign-command/on-trigger-end-func command)
(format nil "(effect in ~A turn~:P)" (campaign-command/cd command))
(format nil "(immediate effect, cooldown ~A turn~:P)" (campaign-command/cd command))))))
(setf prompt-list (loop repeat (length menu-items)
collect #'(lambda (cur-sel)
(declare (ignore cur-sel))
(format nil "[Enter] Select~A" (if can-esc " [Esc] Cancel" ""))
)))
(setf enter-func #'(lambda (cur-sel)
(setf (gethash player-faction (world/commands *world*))
(list :command (campaign-command/id (nth cur-sel command-list)) :cd (campaign-command/cd (nth cur-sel command-list))))
(setf *current-window* (return-to *current-window*))
))
(setf descr-list (loop for command in command-list
collect (funcall (campaign-command/descr-func command) *world*)))
(setf *current-window* (make-instance 'select-obj-window
:return-to *current-window*
:header-line header-str
:line-list menu-items
:prompt-list prompt-list
:descr-list descr-list
:enter-func enter-func
:can-esc can-esc
))
(make-output *current-window*)
(run-window *current-window*))))
(setf (campaign-window/cur-mode win) (campaign-window/prev-mode win)))
(defmethod campaign-win-display-init-hint ((win campaign-window))
(let* ((msg-str nil)
(text-list (list (list +faction-type-angels+ +game-event-campaign-angel-win+)
(list +faction-type-demons+ +game-event-campaign-demon-win+)
(list +faction-type-military+ +game-event-campaign-military-win+))))
(setf msg-str (format nil "Welcome to the campaign of the City of the Damned!"))
(when (find (get-general-faction-from-specific (world/player-specific-faction *world*)) text-list :key #'(lambda (a) (first a)))
(let ((objective-text (funcall (descr-func (get-game-event-by-id (second (find (get-general-faction-from-specific (world/player-specific-faction *world*)) text-list :key #'(lambda (a) (first a)))))))))
(setf msg-str (format nil "~A~%~%" msg-str))
(setf msg-str (format nil "~A~A" msg-str objective-text))))
(setf msg-str (format nil "~A~%~%To display help, press '?'." msg-str))
(setf *current-window* (make-instance 'display-msg-window
:msg-line msg-str
:w 400))
(make-output *current-window*)
(run-window *current-window*))
)
(defmethod campaign-win-display-mission-details ((win campaign-window))
(with-accessors ((cur-sector campaign-window/cur-sector)
(reveal-lair campaign-window/reveal-lair))
win
(let* ((world-sector (aref (cells (world-map *world*)) (car cur-sector) (cdr cur-sector)))
(mission-type (get-mission-type-by-id (mission-type-id (mission world-sector))))
(msg-str nil))
(setf msg-str (format nil "~A~%~%" (name (mission world-sector))))
(setf msg-str (format nil "~A~A~%" msg-str (description world-sector :reveal-lair reveal-lair)))
(when (find (get-general-faction-from-specific (world/player-specific-faction *world*)) (win-condition-list mission-type) :key #'(lambda (a) (first a)))
(let ((objective-text (funcall (descr-func (get-game-event-by-id (second (find (get-general-faction-from-specific (world/player-specific-faction *world*)) (win-condition-list mission-type) :key #'(lambda (a) (first a)))))))))
(setf msg-str (format nil "~A~A~%~%" msg-str objective-text))))
(setf *current-window* (make-instance 'display-msg-window
:msg-line msg-str
:w (truncate (* *window-width* 2/3))
:prompt-line "[Enter] Start mission [Esc] Cancel"))
(make-output *current-window*)
(run-window *current-window*)))
)
(defmethod campaign-win-calculate-avail-missions ((win campaign-window))
(with-slots (avail-missions) win
(setf avail-missions (world/present-missions *world*))))
(defmethod campaign-win-move-select-to-mission ((win campaign-window))
(with-slots (cur-sector cur-sel avail-missions) win
(when avail-missions
(setf cur-sector (cons (x (nth cur-sel avail-missions))
(y (nth cur-sel avail-missions)))))))
(defun calc-is-mission-available (mission general-player-faction)
(let* ((faction-obj (find general-player-faction (faction-list mission) :key #'(lambda (a) (first a))))
(faction-present (if faction-obj
(not (eq (second faction-obj) :mission-faction-absent))
nil)))
faction-present))
(defmethod make-output ((win campaign-window))
(with-slots (cur-mode cur-sector cur-sel avail-missions reveal-lair) win
(sdl:with-rectangle (a-rect (sdl:rectangle :x 0 :y 0 :w *window-width* :h *window-height*))
(sdl:fill-surface sdl:*black* :template a-rect))
(let* ((x1 20) (y1 20) (map-w (* *glyph-w* 5 *max-x-world-map*)) (map-h (* *glyph-h* 5 *max-y-world-map*))
(x2 (+ x1 map-w 20)) (y2 (+ y1 20))
(select-mission-sector-str "Select mission in a sector:")
(select-avail-mission-str "Select available mission:")
(date-str (format nil "~A" (show-date-time-YMD (world-game-time *world*))))
(init-campaign-str "Generate a campaign map, press [r] to create a new one")
(prompt-str nil)
(header-str nil))
(with-slots (game-state) *game-manager*
(case game-state
(:game-state-campaign-init (progn
(setf header-str "NEW CAMPAIGN")
(setf prompt-str (format nil "[Enter] Accept map [r] Randomize map [Arrows/Numpad] Move selection"))
;; draw subheader
(sdl:draw-string-solid-* init-campaign-str (- (truncate *window-width* 2) (truncate (* (length init-campaign-str) (sdl:char-width sdl:*default-font*)) 2)) y1 :justify :left :color sdl:*white*)))
(:game-state-campaign-map (progn
(let* ((player-faction (get-general-faction-from-specific (world/player-specific-faction *world*)))
(demon-win-cond (get-win-condition-by-id :win-cond-demon-campaign))
(military-win-cond (get-win-condition-by-id :win-cond-military-campaign))
(angels-win-cond (get-win-condition-by-id :win-cond-angels-campaign))
(max-flesh-points (win-condition/win-formula demon-win-cond))
(normal-sectors-left (funcall (win-condition/win-func demon-win-cond) *world* demon-win-cond))
(machines-left (funcall (win-condition/win-func angels-win-cond) *world* angels-win-cond))
(demon-str nil)
(max-lines 0)
(command-str "Press [c] to select a new command"))
(setf header-str "CAMPAIGN MAP")
(setf prompt-str (format nil "~A[Tab] Change mode ~A[s] Situation report [e] Effects [n] Next day"
(if (and (mission (aref (cells (world-map *world*)) (car cur-sector) (cdr cur-sector)))
(calc-is-mission-available (mission (aref (cells (world-map *world*)) (car cur-sector) (cdr cur-sector)))
(get-general-faction-from-specific (world/player-specific-faction *world*))))
"[Enter] Start mission "
"")
(if (not (gethash player-faction (world/commands *world*)))
"[c] Select a command "
"")
))
(when (gethash player-faction (world/commands *world*))
(let* ((world-command (gethash player-faction (world/commands *world*)))
(command (get-campaign-command-by-id (getf world-command :command)))
(cd (getf world-command :cd)))
(setf command-str (format nil "~A ~A"
(funcall (campaign-command/name-func command) *world*)
(if (campaign-command/on-trigger-end-func command)
(format nil "[complete in ~A day~:P]" cd)
(format nil "[~A day~:P for next]" cd))))))
(multiple-value-bind (corrupted-sectors-left satanist-lairs-left) (funcall (win-condition/win-func military-win-cond) *world* military-win-cond)
(setf demon-str (format nil "Flesh gathered: ~A of ~A, inhabited districts left: ~A, sectors corrupted: ~A, satanists' lairs left: ~A, dimensional engines left: ~A~%~%Command: ~A"
(world/flesh-points *world*) max-flesh-points normal-sectors-left corrupted-sectors-left satanist-lairs-left machines-left command-str)))
(sdl:with-rectangle (a-rect (sdl:rectangle :x (+ x1 0) :y (+ y1 map-h 50) :w (- *window-width* x1 20) :h (* 1 (sdl:get-font-height))))
(setf max-lines (write-text demon-str a-rect :count-only t)))
(sdl:with-rectangle (a-rect (sdl:rectangle :x (+ x1 0) :y (+ y1 map-h 50) :w (- *window-width* x1 20) :h (* max-lines (sdl:get-font-height))))
(write-text demon-str a-rect))
)
;; draw subheader
(if (eq cur-mode :campaign-window-map-mode)
(sdl:draw-string-solid-* select-mission-sector-str (+ x1 (truncate map-w 2)) y1 :justify :center :color sdl:*white*)
(sdl:draw-string-solid-* select-avail-mission-str (+ x2 (truncate (- *window-width* x2 20) 2)) y1 :justify :center :color sdl:*white*)))))
)
;; draw map
(draw-world-map (world-map *world*) x1 y2 :reveal-lairs reveal-lair)
(highlight-world-map-tile (+ x1 (* (car cur-sector) (* *glyph-w* 5))) (+ y2 (* (cdr cur-sector) (* *glyph-h* 5))))
;; draw date
(sdl:draw-string-solid-* date-str (+ x1 (truncate map-w 2)) (+ y1 map-h 30) :justify :center :color sdl:*white*)
;; display missions
(case cur-mode
(:campaign-window-map-mode (progn
(sdl:with-rectangle (rect (sdl:rectangle :x x2 :y y2 :w (- *window-width* x2 20) :h map-h))
(write-text (description (aref (cells (world-map *world*)) (car cur-sector) (cdr cur-sector)) :reveal-lair reveal-lair)
rect))))
(:campaign-window-mission-mode (progn
(let ((color-list nil)
(mission-names-list ())
(str-per-page 10))
(loop with general-player-faction = (get-general-faction-from-specific (world/player-specific-faction *world*))
for i from 0 below (length avail-missions)
for mission = (nth i avail-missions)
for faction-present = (calc-is-mission-available mission general-player-faction)
do
(push (name mission) mission-names-list)
(cond
((and (= i cur-sel) faction-present) (push sdl:*yellow* color-list))
((and (= i cur-sel) (not faction-present)) (push (sdl:color :r 150 :g 150 :b 0) color-list))
((and (/= i cur-sel) faction-present) (push sdl:*white* color-list))
((and (/= i cur-sel) (not faction-present)) (push (sdl:color :r 150 :g 150 :b 150) color-list)))
finally
(setf mission-names-list (reverse mission-names-list))
(setf color-list (reverse color-list)))
(draw-selection-list mission-names-list cur-sel str-per-page x2 y2 :color-list color-list)
(sdl:with-rectangle (rect (sdl:rectangle :x x2
:y (+ y2 10 (* (sdl:char-height sdl:*default-font*) str-per-page))
:w (- *window-width* x2 20)
:h (- *window-height* 40 (+ 10 10 (* (sdl:char-height sdl:*default-font*) str-per-page)))))
(write-text (description (aref (cells (world-map *world*)) (car cur-sector) (cdr cur-sector)) :reveal-lair reveal-lair)
rect))))))
;; draw header
(sdl:draw-string-solid-* header-str (truncate *window-width* 2) 0 :justify :center :color sdl:*white*)
;; draw prompt
(sdl:draw-string-solid-* prompt-str 10 (- *window-height* 10 (sdl:char-height sdl:*default-font*))))
(sdl:update-display)))
(defmethod run-window ((win campaign-window))
(sdl:with-events ()
(:quit-event () (funcall (quit-func win)) t)
(:key-down-event (:key key :mod mod :unicode unicode)
;; normalize mod
(loop while (>= mod sdl-key-mod-num) do
(decf mod sdl-key-mod-num))
(with-slots (test-map-func cur-mode cur-sector cur-sel avail-missions return-to reveal-lair) win
;;------------------
;; moving - arrows
(case cur-mode
(:campaign-window-map-mode (progn (let ((new-coords cur-sector))
(when (or (sdl:key= key :sdl-key-pageup) (sdl:key= key :sdl-key-kp9))
(setf new-coords (cons (1+ (car cur-sector))
(1- (cdr cur-sector))))
)
(when (or (sdl:key= key :sdl-key-up) (sdl:key= key :sdl-key-kp8))
(setf new-coords (cons (car cur-sector)
(1- (cdr cur-sector))))
)
(when (or (sdl:key= key :sdl-key-home) (sdl:key= key :sdl-key-kp7))
(setf new-coords (cons (1- (car cur-sector))
(1- (cdr cur-sector))))
)
(when (or (sdl:key= key :sdl-key-right) (sdl:key= key :sdl-key-kp6))
(setf new-coords (cons (1+ (car cur-sector))
(cdr cur-sector)))
)
(when (or (sdl:key= key :sdl-key-left) (sdl:key= key :sdl-key-kp4))
(setf new-coords (cons (1- (car cur-sector))
(cdr cur-sector)))
)
(when (or (sdl:key= key :sdl-key-pagedown) (sdl:key= key :sdl-key-kp3))
(setf new-coords (cons (1+ (car cur-sector))
(1+ (cdr cur-sector))))
)
(when (or (sdl:key= key :sdl-key-down) (sdl:key= key :sdl-key-kp2))
(setf new-coords (cons (car cur-sector)
(1+ (cdr cur-sector))))
)
(when (or (sdl:key= key :sdl-key-end) (sdl:key= key :sdl-key-kp1))
(setf new-coords (cons (1- (car cur-sector))
(1+ (cdr cur-sector))))
)
(when (and (>= (car new-coords) 0) (>= (cdr new-coords) 0)
(< (car new-coords) *max-x-world-map*) (< (cdr new-coords) *max-y-world-map*))
(setf cur-sector new-coords))
)))
(:campaign-window-mission-mode (progn (setf cur-sel (run-selection-list key mod unicode cur-sel))
(setf cur-sel (adjust-selection-list cur-sel (length avail-missions)))
(campaign-win-move-select-to-mission win))))
(cond
;; escape - quit
((sdl:key= key :sdl-key-escape)
(with-slots (game-state) *game-manager*
(case game-state
(:game-state-campaign-map (show-escape-menu))))
)
;; r - random map
((sdl:key= key :sdl-key-r)
(with-slots (game-state) *game-manager*
(case game-state
(:game-state-campaign-init (progn
(multiple-value-bind (year month day hour min sec) (get-current-date-time (world-game-time *world*))
(declare (ignore month))
(setf (world-game-time *world*) (set-current-date-time year (random 12) day hour min sec)))
(setf (world-map *world*) (generate-normal-world-map *world*))
(setf cur-mode :campaign-window-map-mode))))
)
)
;; Shift + D - debug menu, for debug purposes only
((and (sdl:key= key :sdl-key-d) (/= (logand mod sdl-cffi::sdl-key-mod-shift) 0)
(null *cotd-release*))
(let ((menu-items ())
(prompt-list ())
(enter-func nil)
(header-str nil))
(setf header-str "Debug Menu")
(setf menu-items (list "Add 500 flesh points"
(if reveal-lair
"Hide satanists' lairs"
"Show satanists' lairs")
"Close"))
(setf prompt-list (list #'(lambda (cur-sel)
(declare (ignore cur-sel))
"[Enter] Select [Esc] Exit")
#'(lambda (cur-sel)
(declare (ignore cur-sel))
"[Enter] Select [Esc] Exit")
#'(lambda (cur-sel)
(declare (ignore cur-sel))
"[Enter] Select [Esc] Exit")))
(setf enter-func #'(lambda (cur-sel)
(case cur-sel
(0 (progn
(incf (world/flesh-points *world*) 500)
(setf *current-window* (return-to *current-window*))))
(1 (progn
(setf reveal-lair (not reveal-lair))
(setf *current-window* (return-to *current-window*))))
(t (progn
(setf *current-window* (return-to *current-window*)))))
))
(setf *current-window* (make-instance 'select-obj-window
:return-to *current-window*
:header-line header-str
:line-list menu-items
:prompt-list prompt-list
:enter-func enter-func
))
(make-output *current-window*)
(run-window *current-window*))
)
;; tab - change mode
((sdl:key= key :sdl-key-tab)
(if (eq cur-mode :campaign-window-mission-mode)
(setf cur-mode :campaign-window-map-mode)
(when avail-missions
(setf cur-mode :campaign-window-mission-mode)
(campaign-win-move-select-to-mission win))))
;; enter - select
((or (sdl:key= key :sdl-key-return) (sdl:key= key :sdl-key-kp-enter))
(with-slots (game-state) *game-manager*
(case game-state
(:game-state-campaign-init (progn
(generate-missions-on-world-map *world*)
(campaign-win-calculate-avail-missions win)
(setf cur-mode :campaign-window-mission-mode)
(campaign-win-move-select-to-mission win)
(game-state-campaign-init->campaign-map)
(make-output *current-window*)
(campaign-win-display-init-hint win)
))
(:game-state-campaign-map (when (and (mission (aref (cells (world-map *world*)) (car cur-sector) (cdr cur-sector)))
(calc-is-mission-available (mission (aref (cells (world-map *world*)) (car cur-sector) (cdr cur-sector)))
(get-general-faction-from-specific (world/player-specific-faction *world*))))
(when (campaign-win-display-mission-details win)
(campaign-win-display-command win :can-esc nil)
(return-from run-window (values (mission (aref (cells (world-map *world*)) (car cur-sector) (cdr cur-sector)))
(world-sector (mission (aref (cells (world-map *world*)) (car cur-sector) (cdr cur-sector))))))))))
)))
;;------------------
;; select a command - c
(when (or (and (sdl:key= key :sdl-key-c) (= mod 0))
(eq unicode +cotd-unicode-latin-c-small+))
(case (game-manager/game-state *game-manager*)
(:game-state-campaign-map (campaign-win-display-command win :can-esc t))))
;;------------------
;; view situation report - s
(when (or (and (sdl:key= key :sdl-key-s) (= mod 0))
(eq unicode +cotd-unicode-latin-s-small+))
(case (game-manager/game-state *game-manager*)
(:game-state-campaign-map (campaign-win-display-sitrep win))))
;;------------------
;; view situation report - e
(when (or (and (sdl:key= key :sdl-key-e) (= mod 0))
(eq unicode +cotd-unicode-latin-e-small+))
(case (game-manager/game-state *game-manager*)
(:game-state-campaign-map (campaign-win-display-effects win))))
;;------------------
;; help screen - ?
(when (or (sdl:key= key :sdl-key-question)
(eq unicode +cotd-unicode-question-mark+)
(and (sdl:key= key :sdl-key-slash) (/= (logand mod sdl-cffi::sdl-key-mod-shift) 0))
(and (sdl:key= key :sdl-key-7) (/= (logand mod sdl-cffi::sdl-key-mod-shift) 0)))
(case (game-manager/game-state *game-manager*)
(:game-state-campaign-map (campaign-win-display-help win))))
;;------------------
;; next day - n
(when (or (and (sdl:key= key :sdl-key-n) (= mod 0))
(eq unicode +cotd-unicode-latin-n-small+))
(with-slots (game-state) *game-manager*
(case game-state
(:game-state-campaign-map (progn
(campaign-win-display-command win)
(game-state-campaign-map->post-scenario)
(return-from run-window nil))))))
(make-output *current-window*)))
(:idle () #+swank
(update-swank)
)
(:video-expose-event () (make-output *current-window*))))
| 38,336
|
Common Lisp
|
.lisp
| 473
| 47.448203
| 233
| 0.434888
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
39651b496839190f0790d0e950a105cc1bf08703c06c57dcfb7b6a75450928c6
| 2,926
|
[
-1
] |
2,927
|
window-messages.lisp
|
gwathlobal_CotD/src/windows/window-messages.lisp
|
(in-package :cotd)
(defclass message-window (window)
((cur-str :accessor cur-str)
(message-box :initarg :message-box :accessor message-window/message-box)
(header-str :initarg :header-str :accessor message-window/header-str)
))
(defmethod initialize-instance :after ((win message-window) &key)
(with-slots (cur-str message-box) win
(setf cur-str (message-list-length message-box))))
(defmethod make-output ((win message-window))
(with-slots (cur-str message-box header-str) win
(sdl:with-rectangle (a-rect (sdl:rectangle :x 0 :y 0 :w *window-width* :h *window-height*))
(sdl:fill-surface sdl:*black* :template a-rect))
(sdl:draw-string-solid-* header-str (truncate *window-width* 2) 0 :justify :center)
(sdl:with-rectangle (rect (sdl:rectangle :x 10 :y (+ 10 (sdl:char-height sdl:*default-font*)) :w (- *window-width* 10) :h (- *window-height* (+ 10 (sdl:char-height sdl:*default-font*)) (sdl:char-height sdl:*default-font*) 20)))
(let ((max-str (write-colored-text (colored-txt-list (message-box-strings message-box)) rect :count-only t)))
(when (< max-str (+ cur-str (truncate (sdl:height rect) (sdl:char-height sdl:*default-font*))))
(setf cur-str (- max-str (truncate (sdl:height rect) (sdl:char-height sdl:*default-font*)))))
(when (< cur-str 0)
(setf cur-str 0))
(write-colored-text (colored-txt-list (message-box-strings message-box)) rect :start-line cur-str)
)
)
(sdl:draw-string-solid-* (format nil "[Shift+Up/Down] Scroll page [Up/Down] Scroll text [Esc] Exit")
10 (- *window-height* 10 (sdl:char-height sdl:*default-font*)))
(sdl:update-display)))
(defmethod run-window ((win message-window))
(with-slots (cur-str) win
(sdl:with-events ()
(:quit-event () (funcall (quit-func win)) t)
(:key-down-event (:key key :mod mod :unicode unicode)
(declare (ignore unicode))
;; normalize mod
(loop while (>= mod sdl-key-mod-num) do
(decf mod sdl-key-mod-num))
(cond
((and (sdl:key= key :sdl-key-up) (= mod 0))
(decf cur-str))
((and (sdl:key= key :sdl-key-down) (= mod 0))
(incf cur-str))
((and (or (sdl:key= key :sdl-key-up) (sdl:key= key :sdl-key-kp8)) (/= (logand mod sdl-cffi::sdl-key-mod-shift) 0))
(decf cur-str 30))
((and (or (sdl:key= key :sdl-key-down) (sdl:key= key :sdl-key-kp2)) (/= (logand mod sdl-cffi::sdl-key-mod-shift) 0))
(incf cur-str 30))
;; escape - quit
((sdl:key= key :sdl-key-escape)
(setf *current-window* (return-to win))
(make-output *current-window*)
(return-from run-window nil))
)
(make-output *current-window*))
(:video-expose-event () (make-output *current-window*)))
))
| 3,337
|
Common Lisp
|
.lisp
| 53
| 46.283019
| 232
| 0.542902
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
0d5b2a4a1141b33af762afa67a450898c65086ab4d3bcc2ab13325a7663dac8b
| 2,927
|
[
-1
] |
2,928
|
window-select-obj.lisp
|
gwathlobal_CotD/src/windows/window-select-obj.lisp
|
(in-package :cotd)
(defclass select-obj-window (window)
((cur-sel :initform 0 :accessor cur-sel)
(header-line :initform nil :initarg :header-line :accessor header-line)
(line-list :initarg :line-list :accessor line-list :type list)
(descr-list :initform nil :initarg :descr-list :accessor descr-list)
(color-list :initform nil :initarg :color-list :accessor color-list)
(prompt-list :initarg :prompt-list :accessor prompt-list :type list) ;; each value is (<func if this prompt should apply with 1 arg - cur-sel> <prompt string proper>)
(enter-func :initarg :enter-func :accessor enter-func) ;; 1 arg - cur-sel
(select-color-func :initform nil :initarg :select-color-func :accessor select-color-func) ;; 1 arg - cur-sel
(can-esc :initform t :initarg :can-esc :accessor can-esc)
(x :initform nil :initarg :x :accessor select-obj-window/x)
(y :initform nil :initarg :y :accessor select-obj-window/y)
(w :initform nil :initarg :w :accessor select-obj-window/w)
(h-list :initform nil :accessor select-obj-window/h-list)
(h-descr :initform nil :accessor select-obj-window/h-descr)
(margin :initform 4 :accessor select-obj-window/margin :type fixnum)
))
(defmethod initialize-instance :after ((win select-obj-window) &key)
(with-slots (x y w h-list h-descr margin cur-sel header-line line-list descr-list prompt-list can-esc) win
(let ((default-w 330))
;; find the maximum width among all strings
(unless w
(setf w (loop with max = default-w
for str in (append (if (header-line win)
(list (header-line win))
nil)
(line-list win)
(loop for prompt-func in prompt-list
collect (return-prompt-str prompt-func cur-sel :can-esc can-esc)))
for try-max = (+ 10 (* (sdl:char-width sdl:*default-font*) (+ 10 (length str))))
when (> try-max max) do
(setf max try-max)
finally (return-from nil max))))
;; find the maximum height of the description text depending on the found width
(if descr-list
(sdl:with-rectangle (rect (sdl:rectangle :x 0 :y 0 :w (- w margin margin) :h 30))
(setf h-descr (loop with max = 0
for descr in descr-list
for try-max = (* (sdl:char-height sdl:*default-font*) (write-text descr rect :count-only t))
when (> try-max max) do
(setf max try-max)
finally (return-from nil max))))
(setf h-descr 0))
;; find the height of the list
(unless h-list
(setf h-list (* (sdl:char-height sdl:*default-font*) (length line-list))))
;; set x if necessary
(unless x
(setf x (- (truncate *window-width* 2) (truncate w 2) margin)))
;; set y if necessary
(unless y
(setf y (- (truncate *window-height* 2) (truncate (+ h-descr h-list) 2) margin))))))
(defun return-prompt-str (prompt-func cur-sel &key (can-esc t))
(if prompt-func
(funcall prompt-func cur-sel)
(if can-esc
"[Esc] Escape"
"")))
(defmethod make-output ((win select-obj-window))
(with-slots (x y w h-list h-descr margin cur-sel header-line line-list descr-list prompt-list can-esc select-color-func color-list) win
(let* ((h-header (sdl:char-height sdl:*default-font*))
(h-prompt (sdl:char-height sdl:*default-font*))
(cur-y y)
(x-rect x)
(w-rect w)
(x-txt (+ x-rect margin))
(w-txt (- w-rect margin margin))
(y-header-rect)
(h-header-rect)
(y-header-txt)
(h-header-txt)
(y-list-rect)
(h-list-rect)
(y-list-txt)
(y-descr-rect)
(h-descr-rect)
(y-descr-txt)
(h-descr-txt)
(y-prompt-rect)
(h-prompt-rect)
(y-prompt-txt)
(h-prompt-txt)
)
(when header-line
;; setting up coordiantes
(setf y-header-rect cur-y
h-header-rect (+ h-header margin margin)
y-header-txt (+ y-header-rect margin)
h-header-txt (- h-header-rect margin margin)
cur-y (+ cur-y h-header-rect -1))
;; draw rectangle for header
(sdl:with-rectangle (rect (sdl:rectangle :x x-rect :y y-header-rect :w w-rect :h h-header-rect))
(sdl:fill-surface sdl:*black* :template rect)
(sdl:draw-rectangle rect :color sdl:*white*))
;; draw text for header
(sdl:with-rectangle (rect (sdl:rectangle :x x-txt :y y-header-txt :w w-txt :h h-header-txt))
(write-text header-line rect)))
(when line-list
;; setting up coordiantes
(setf y-list-rect cur-y
h-list-rect (+ h-list margin margin)
y-list-txt (+ y-list-rect margin)
cur-y (+ cur-y h-list-rect -1))
;; draw rectangle for list
(sdl:with-rectangle (rect (sdl:rectangle :x x-rect :y y-list-rect :w w-rect :h h-list-rect))
(sdl:fill-surface sdl:*black* :template rect)
(sdl:draw-rectangle rect :color sdl:*white*))
;; draw list
(loop with final-color-list = ()
for i from 0 below (length line-list) do
(if (= i cur-sel)
(if select-color-func
(push (funcall select-color-func cur-sel) final-color-list)
(push sdl:*yellow* final-color-list))
(if color-list
(push (nth i color-list) final-color-list)
(push sdl:*white* final-color-list)))
finally
(setf final-color-list (reverse final-color-list))
(draw-selection-list line-list cur-sel (length line-list) x-txt y-list-txt :color-list final-color-list :use-letters t)))
(when descr-list
;; setting up coordiantes
(setf y-descr-rect cur-y
h-descr-rect (+ h-descr margin margin)
y-descr-txt (+ y-descr-rect margin)
h-descr-txt (- h-descr-rect margin margin)
cur-y (+ cur-y h-descr-rect -1))
;; draw rectangle for description
(sdl:with-rectangle (rect (sdl:rectangle :x x-rect :y y-descr-rect :w w-rect :h h-descr-rect))
(sdl:fill-surface sdl:*black* :template rect)
(sdl:draw-rectangle rect :color sdl:*white*))
;; draw description text
(sdl:with-rectangle (rect (sdl:rectangle :x x-txt :y y-descr-txt :w w-txt :h h-descr-txt))
(write-text (nth cur-sel descr-list) rect :color sdl:*white*)))
(when prompt-list
;; setting up coordiantes
(setf y-prompt-rect cur-y
h-prompt-rect (+ h-prompt margin margin)
y-prompt-txt (+ y-prompt-rect margin)
h-prompt-txt (- h-prompt-rect margin margin)
cur-y (+ cur-y h-prompt-rect -1))
;; draw rectangle for prompt
(sdl:with-rectangle (rect (sdl:rectangle :x x-rect :y y-prompt-rect :w w-rect :h h-prompt-rect))
(sdl:fill-surface sdl:*black* :template rect)
(sdl:draw-rectangle rect :color sdl:*white*))
;; draw text for prompt
(sdl:with-rectangle (rect (sdl:rectangle :x x-txt :y y-prompt-txt :w w-txt :h h-prompt-txt))
(write-text (return-prompt-str (nth cur-sel prompt-list) cur-sel :can-esc can-esc) rect)))
))
(sdl:update-display))
(defmethod run-window ((win select-obj-window))
(tagbody
(sdl:with-events ()
(:quit-event () (funcall (quit-func win)) t)
(:key-down-event (:key key :mod mod :unicode unicode)
(setf (cur-sel win) (run-selection-list key mod unicode (cur-sel win) :start-page (truncate (cur-sel win) (length (line-list win))) :max-str-per-page (length (line-list win))))
(setf (cur-sel win) (adjust-selection-list (cur-sel win) (length (line-list win))))
(cond
;; escape - quit
((and (sdl:key= key :sdl-key-escape) (can-esc win))
(setf *current-window* (return-to win)) (go exit-func))
;; enter - select
((or (sdl:key= key :sdl-key-return) (sdl:key= key :sdl-key-kp-enter))
(funcall (enter-func win) (cur-sel win))
(go exit-func)))
(make-output *current-window*)
)
(:video-expose-event () (make-output *current-window*)))
exit-func (make-output *current-window*)))
| 8,963
|
Common Lisp
|
.lisp
| 170
| 39.647059
| 180
| 0.560156
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
5bb50ab96aeb5753e962e6251a19eb738b293e52dedb7105fc1f063a16d0b6e4
| 2,928
|
[
-1
] |
2,929
|
window-game-over.lisp
|
gwathlobal_CotD/src/windows/window-game-over.lisp
|
(in-package :cotd)
(defclass final-stats-window (window)
((game-over-type :initarg :game-over-type :accessor game-over-type :type game-over-enum)
(highscores-place :initform nil :initarg :highscores-place :accessor highscores-place)
(player-died :initform nil :initarg :player-died :accessor player-died)
(player-won :initform nil :initarg :player-won :accessor player-won)))
(defmethod make-output ((win final-stats-window))
;; fill the screen black
(sdl:with-rectangle (a-rect (sdl:rectangle :x 0 :y 0 :w *window-width* :h *window-height*))
(sdl:fill-surface sdl:*black* :template a-rect))
;; displaying the type of game over
(let ((str (create-string)) (color))
(if (player-won win)
(progn
(format str "VICTORY! ")
(setf color sdl:*green*))
(progn
(format str "DEFEAT! ")
(setf color sdl:*red*)))
(when (player-died win)
(format str "YOU DIED, AND "))
(case (game-over-type win)
(:game-over-player-dead (setf str (format nil "YOU ARE DEAD")))
(:game-over-demons-won (format str "THE PANDEMONIUM HIERARCHY WON"))
(:game-over-angels-won (format str "THE CELESTIAL COMMUNION WON"))
(:game-over-military-won (format str "THE MILITARY WON"))
(:game-over-church-won (format str "THE CHURCH WON"))
(:game-over-satanists-won (format str "THE SATANISTS WON"))
(:game-over-player-possessed (setf str (format nil "YOU ARE POSSESSED")))
(:game-over-thief-won (setf str (format nil "YOU HAVE COLLECTED ENOUGH VALUABLES AND MANAGED TO ESCAPE THE CITY")))
(:game-over-eater-won (setf str (format nil "YOU HAVE KILLED ALL OUTSIDERS")))
(:game-over-ghost-won (setf str (format nil "YOU HAVE PUT YOURSELF TO REST"))))
(sdl:draw-string-solid-* str (truncate *window-width* 2) 10 :justify :center :color color)
)
;; display scenario stats
(let* ((str (return-scenario-stats))
(max-lines)
(prompt-str))
(sdl:with-rectangle (a-rect (sdl:rectangle :x 0 :y 30 :w *window-width* :h (* 1 (sdl:get-font-height))))
(setf max-lines (write-text str a-rect :count-only t)))
(sdl:with-rectangle (a-rect (sdl:rectangle :x 0 :y 30 :w *window-width* :h (* max-lines (sdl:get-font-height))))
(write-text str a-rect))
(show-message-box 6 (+ 40 (* max-lines (sdl:get-font-height))) *window-width* (- *window-height* 40 10 (sdl:char-height sdl:*default-font*) (* (1+ max-lines) (sdl:get-font-height))) (level/full-message-box (level *world*)))
(case (game-manager/game-state *game-manager*)
(:game-state-campaign-scenario (setf prompt-str (format nil "[m] Return to Campaign Map [Esc] High Scores")))
(:game-state-custom-scenario (setf prompt-str (format nil "[m] Main menu [Esc] High Scores"))))
(sdl:draw-string-solid-* prompt-str
10 (- *window-height* 13 (sdl:char-height sdl:*default-font*))))
(sdl:update-display))
(defmethod run-window ((win final-stats-window))
(sdl:with-events ()
(:quit-event () (funcall (quit-func win)) t)
(:key-down-event (:key key :mod mod :unicode unicode)
(declare (ignore mod unicode))
(flet ((exit-func ()
(case (game-manager/game-state *game-manager*)
(:game-state-campaign-scenario (progn
(game-state-campaign-scenario->post-scenario)
(go-to-start-game)))
(:game-state-custom-scenario (progn
(when (game-manager/game-slot-id *game-manager*)
(let* ((final-save-name (format nil "~A~A" *save-final-base-dirname* (game-manager/game-slot-id *game-manager*)))
(dir-pathname (merge-pathnames (make-pathname :directory `(:relative ,final-save-name)) (find-save-game-path :save-game-scenario)))
(descr-pathname (merge-pathnames (make-pathname :name *save-descr-filename*) dir-pathname))
(dir-to-delete (make-pathname :host (pathname-host descr-pathname)
:device (pathname-device descr-pathname)
:directory (pathname-directory descr-pathname)))
(result))
(setf result (delete-dir-from-disk dir-to-delete))
(when (not result)
(setf *current-window* (make-instance 'display-msg-window
:msg-line "An error has occured while the system tried to remove the game!"))
(make-output *current-window*)
(run-window *current-window*))))
(game-state-custom-scenario->menu)
(go-to-start-game))))))
(cond
;; escape - high scores
((sdl:key= key :sdl-key-escape)
(setf *current-window* (make-instance 'highscores-window :highscores-place (highscores-place win)))
(make-output *current-window*)
(run-window *current-window*)
(truncate-highscores *highscores*)
(save-highscores-to-disk)
(exit-func))
;; m - return to main menu/campaign map
((sdl:key= key :sdl-key-m)
(truncate-highscores *highscores*)
(save-highscores-to-disk)
(exit-func)))))
(:video-expose-event () (make-output *current-window*))))
| 6,703
|
Common Lisp
|
.lisp
| 91
| 48.197802
| 228
| 0.489556
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
0a1232c6a4aa0066ea73e813ebcdef32bdafe84802ce53ffdc0a4f4b519bbc12
| 2,929
|
[
-1
] |
2,930
|
window-custom-scenario.lisp
|
gwathlobal_CotD/src/windows/window-custom-scenario.lisp
|
(in-package :cotd)
(defenum:defenum custom-scenario-window-tab-type (:custom-scenario-tab-missions
:custom-scenario-tab-sectors
:custom-scenario-tab-months
:custom-scenario-tab-feats
:custom-scenario-tab-factions
:custom-scenario-tab-specific-factions))
(defclass custom-scenario-window (window)
((cur-step :initform :custom-scenario-tab-missions :accessor custom-scenario-window/cur-step :type custom-scenario-window-tab-type)
(cur-sel :initform 0 :accessor custom-scenario-window/cur-sel :type fixnum)
(menu-items :initform () :accessor custom-scenario-window/menu-items :type list)
(scenario :initform (make-instance 'scenario-gen-class) :accessor custom-scenario-window/scenario :type scenario-gen-class)
(months-list :initform (list "January" "February" "March" "April" "May" "June" "July" "August" "September" "October" "November" "December") :accessor custom-scenario-window/months-list :type list)
(cur-mission-type :initform 0 :accessor custom-scenario-window/cur-mission-type :type fixnum)
(cur-sector :initform 0 :accessor custom-scenario-window/cur-sector :type fixnum)
(cur-month :initform 0 :accessor custom-scenario-window/cur-month :type fixnum)
(cur-feat :initform 0 :accessor custom-scenario-window/cur-feat :type fixnum)
(cur-faction :initform 0 :accessor custom-scenario-window/cur-faction :type fixnum)
(cur-specific-faction :initform 0 :accessor custom-scenario-window/cur-specific-faction :type fixnum)
))
(defmethod initialize-instance :after ((win custom-scenario-window) &key)
(with-slots (scenario cur-mission-type cur-month menu-items cur-sel cur-step) win
(with-slots (world avail-mission-type-list) scenario
;; set up supporting world
(scenario-create-world scenario)
(setf *world* world)
(setf cur-month (random 12))
(scenario-set-world-date scenario 1915 cur-month (random 30) 0 0 0)
;; find all available missions
(scenario-set-avail-mission-types scenario)
(setf cur-mission-type (random (length avail-mission-type-list)))
(adjust-mission-after-change win)
(setf menu-items (populate-custom-scenario-win-menu win cur-step))
(setf cur-sel cur-mission-type)
)))
(defun adjust-mission-after-change (win)
(with-slots (scenario cur-mission-type) win
(with-slots (avail-mission-type-list) scenario
;; create the mission
(scenario-create-mission scenario (id (nth cur-mission-type avail-mission-type-list)))
(readjust-sectors-after-mission-change win))))
(defun readjust-sectors-after-mission-change (win)
(with-slots (scenario cur-sector) win
(with-slots (avail-world-sector-type-list) scenario
;; a precaution for the first start before any sectors are added
(let ((cur-world-sector-type (if avail-world-sector-type-list
(nth cur-sector avail-world-sector-type-list)
nil)))
;; find all available sectors for the selected mission
(scenario-set-avail-world-sector-types scenario)
;; make the selection be the same if there is a world-sector in the new selection
(if (and cur-world-sector-type
(position cur-world-sector-type avail-world-sector-type-list))
(progn
(setf cur-sector (position cur-world-sector-type avail-world-sector-type-list)))
(progn
(setf cur-sector (random (length avail-world-sector-type-list)))))
(adjust-world-sector-after-change win)))))
(defun adjust-months-before-feats (win)
(with-slots (scenario cur-month) win
(with-slots (world) scenario
(multiple-value-bind (year month day hour min sec) (get-current-date-time (world-game-time world))
(declare (ignore month))
(scenario-set-world-date scenario year cur-month day hour min sec))
(adjust-world-sector-after-change win))))
(defun adjust-world-sector-after-change (win)
(with-slots (scenario cur-sector) win
(with-slots (avail-world-sector-type-list) scenario
;; create the world sector
(scenario-create-sector scenario (wtype (nth cur-sector avail-world-sector-type-list)))
(readjust-feats-after-sector-change win))))
(defun readjust-feats-after-sector-change (win)
(with-slots (scenario cur-feat) win
(with-slots (world world-sector avail-controlled-list avail-feats-list avail-items-list avail-tod-list avail-weather-list) scenario
(scenario-set-avail-lvl-mods scenario)
;; set a random controlled-by lvl-mod
(scenario-add/remove-lvl-mod scenario (nth (random (length avail-controlled-list)) avail-controlled-list) :add-general t)
;; add random feats lvl-mods
(loop for lvl-mod in avail-feats-list
when (zerop (random 4)) do
(scenario-add/remove-lvl-mod scenario lvl-mod :add-general t))
;; add random items lvl-mods
(loop for lvl-mod in avail-items-list
when (zerop (random 4)) do
(scenario-add/remove-lvl-mod scenario lvl-mod :add-general t))
(generate-feats-for-world-sector world-sector (world-map world))
;; set a random time-of-day lvl-mod
(scenario-add/remove-lvl-mod scenario (nth (random (length avail-tod-list)) avail-tod-list) :add-general t)
;; add random weather lvl-mods
(loop for lvl-mod in avail-weather-list
when (or (not (random-available-for-mission lvl-mod))
(funcall (random-available-for-mission lvl-mod)))
do
(scenario-add/remove-lvl-mod scenario lvl-mod :add-general t))
(setf cur-feat 0)
(scenario-adjust-lvl-mods-after-sector-regeneration scenario)
(scenario-sort-select-lvl-mods scenario)
(readjust-factions-after-feats-change win))))
(defun readjust-factions-after-feats-change (win)
(with-slots (scenario cur-faction) win
(with-slots (cur-faction-list) scenario
;; set up a all general factions
(scenario-adjust-factions scenario)
(setf cur-faction 0)
(readjust-specific-factions-after-faction-change win))))
(defun readjust-specific-factions-after-faction-change (win)
(with-slots (scenario cur-specific-faction) win
(with-slots (specific-faction-list) scenario
;; find all specific factions
(let ((cur-faction-id (if specific-faction-list
(nth cur-specific-faction specific-faction-list)
nil)))
(scenario-adjust-specific-factions scenario)
(if (and cur-faction-id
(position cur-faction-id specific-faction-list))
(progn
(setf cur-specific-faction (position cur-faction-id specific-faction-list)))
(progn
(setf cur-specific-faction (random (length specific-faction-list)))))
))))
(defun populate-custom-scenario-win-menu (win step)
(with-slots (scenario months-list) win
(with-slots (mission avail-mission-type-list avail-world-sector-type-list overall-lvl-mods-list select-lvl-mods-list cur-faction-list specific-faction-list) scenario
(case step
(:custom-scenario-tab-missions (return-from populate-custom-scenario-win-menu
(loop for mission-type in avail-mission-type-list
collect (name mission-type))))
(:custom-scenario-tab-sectors (return-from populate-custom-scenario-win-menu
(loop for world-sector-type in avail-world-sector-type-list
collect (name world-sector-type))))
(:custom-scenario-tab-months (return-from populate-custom-scenario-win-menu
(copy-list months-list)))
(:custom-scenario-tab-feats (return-from populate-custom-scenario-win-menu
(loop for lvl-mod in overall-lvl-mods-list
collect (format nil "~A ~A"
(if (find lvl-mod select-lvl-mods-list)
"[+]"
" ")
(name lvl-mod)))))
(:custom-scenario-tab-factions (return-from populate-custom-scenario-win-menu
(loop for (faction-id faction-present) in cur-faction-list
collect (format nil "~A ~A"
(case faction-present
(:mission-faction-present "[+]")
(:mission-faction-delayed "[d]")
(t " "))
(name (get-faction-type-by-id faction-id))))))
(:custom-scenario-tab-specific-factions (return-from populate-custom-scenario-win-menu
(loop for specific-faction-type in specific-faction-list
when (find specific-faction-type (scenario-faction-list (get-mission-type-by-id (mission-type-id mission)))
:key #'(lambda (a) (first a)))
collect (name (get-level-modifier-by-id (second (find specific-faction-type
(scenario-faction-list (get-mission-type-by-id (mission-type-id mission)))
:key #'(lambda (a) (first a)))))))
)))
)))
(defun get-included-faction-str (win-faction-list)
(loop with str = (create-string)
with first-no-comma = t
for (faction-id faction-present) in win-faction-list
when (not (eq faction-present :mission-faction-absent)) do
(format str "~A~A ~A"
(if (not first-no-comma)
", "
"")
(case faction-present
(:mission-faction-present "[+]")
(:mission-faction-delayed "[d]"))
(name (get-faction-type-by-id faction-id)))
(setf first-no-comma nil)
finally (return-from nil str)))
(defun get-included-lvl-mods (select-lvl-mods-list)
(loop with str = (create-string)
with first-no-comma = t
for lvl-mod in select-lvl-mods-list
do
(format str "~A~A"
(if (not first-no-comma)
", "
"")
(name lvl-mod))
(setf first-no-comma nil)
finally (return-from nil str)))
(defmethod make-output ((win custom-scenario-window))
(with-slots (cur-step cur-sel menu-items scenario cur-sector cur-faction cur-specific-faction) win
(with-slots (world world-sector mission avail-world-sector-type-list overall-lvl-mods-list always-lvl-mods-list select-lvl-mods-list avail-faction-list cur-faction-list specific-faction-list) scenario
(sdl:with-rectangle (a-rect (sdl:rectangle :x 0 :y 0 :w *window-width* :h *window-height*))
(sdl:fill-surface sdl:*black* :template a-rect))
(sdl:draw-string-solid-* "CUSTOM SCENARIO" (truncate *window-width* 2) 0 :justify :center)
(let ((text-str-num)
(x-title (+ 10 10 (* *glyph-w* 5)))
(y-title (+ 10 (sdl:char-height sdl:*default-font*))))
;; draw the sector image
(let ((*random-state* (make-random-state (world-map/random-state (world-map world)))))
(draw-world-map-cell world-sector 10 (+ 10 y-title)))
;; draw the current scenario info
(sdl:with-rectangle (rect (sdl:rectangle :x x-title :y (+ 10 (sdl:char-height sdl:*default-font*)) :w (- *window-width* x-title 10) :h (- (truncate *window-height* 2) 20)))
(setf text-str-num (write-text (format nil "Date&Time: ~A~%Mission: ~A~%Sector: ~A~%Feats: ~A~%Factions: ~A~%Player faction: ~A"
(show-date-time-YMD (world-game-time world))
(name (get-mission-type-by-id (mission-type-id mission)))
(name (get-world-sector-type-by-id (wtype world-sector)))
(get-included-lvl-mods select-lvl-mods-list)
(get-included-faction-str cur-faction-list)
(name (get-level-modifier-by-id (second (find (nth cur-specific-faction specific-faction-list)
(scenario-faction-list (get-mission-type-by-id (mission-type-id mission)))
:key #'(lambda (a) (first a))))))
)
rect)))
;; draw the steps of scenario customization
(let ((color-1 sdl:*white*) (color-2 sdl:*white*) (color-3 sdl:*white*) (color-4 sdl:*white*) (color-5 sdl:*white*) (color-6 sdl:*white*))
(case cur-step
(:custom-scenario-tab-missions (setf color-1 sdl:*yellow*))
(:custom-scenario-tab-sectors (setf color-2 sdl:*yellow*))
(:custom-scenario-tab-months (setf color-3 sdl:*yellow*))
(:custom-scenario-tab-feats (setf color-4 sdl:*yellow*))
(:custom-scenario-tab-factions (setf color-5 sdl:*yellow*))
(:custom-scenario-tab-specific-factions (setf color-6 sdl:*yellow*)))
(sdl:draw-string-solid-* (format nil "1. Mission") 10 (+ 10 (* (sdl:char-height sdl:*default-font*) (+ 2 text-str-num))) :justify :left :color color-1)
(sdl:draw-string-solid-* (format nil "2. Sector") (* 4 (truncate *window-width* 20)) (+ 10 (* (sdl:char-height sdl:*default-font*) (+ 2 text-str-num))) :justify :left :color color-2)
(sdl:draw-string-solid-* (format nil "3. Month") (* 8 (truncate *window-width* 20)) (+ 10 (* (sdl:char-height sdl:*default-font*) (+ 2 text-str-num))) :justify :center :color color-3)
(sdl:draw-string-solid-* (format nil "4. Feats") (* 11 (truncate *window-width* 20)) (+ 10 (* (sdl:char-height sdl:*default-font*) (+ 2 text-str-num))) :justify :center :color color-4)
(sdl:draw-string-solid-* (format nil "5. Factions") (* 14 (truncate *window-width* 20)) (+ 10 (* (sdl:char-height sdl:*default-font*) (+ 2 text-str-num))) :justify :center :color color-5)
(sdl:draw-string-solid-* (format nil "6. Player faction") (- *window-width* 10) (+ 10 (* (sdl:char-height sdl:*default-font*) (+ 2 text-str-num))) :justify :right :color color-6))
;; draw the selection for each step
(let ((color-list nil))
(dotimes (i (length menu-items))
(case cur-step
(:custom-scenario-tab-feats (progn
(cond
((and (= i cur-sel) (find (nth i overall-lvl-mods-list) always-lvl-mods-list)) (setf color-list (append color-list (list (sdl:color :r 150 :g 150 :b 0)))))
((and (= i cur-sel) (not (find (nth i overall-lvl-mods-list) always-lvl-mods-list))) (setf color-list (append color-list (list sdl:*yellow*))))
((and (/= i cur-sel) (find (nth i overall-lvl-mods-list) always-lvl-mods-list)) (setf color-list (append color-list (list (sdl:color :r 150 :g 150 :b 150)))))
((and (/= i cur-sel) (not (find (nth i overall-lvl-mods-list) always-lvl-mods-list))) (setf color-list (append color-list (list sdl:*white*)))))))
(:custom-scenario-tab-factions (progn
(let* ((current-faction (first (nth i cur-faction-list)))
(ref-faction-obj (find current-faction
avail-faction-list :key #'(lambda (a)
(first a))))
(more-than-one (if (> (length (second ref-faction-obj)) 1)
t
nil)))
(cond
((and (= i cur-sel) (not more-than-one)) (setf color-list (append color-list (list (sdl:color :r 150 :g 150 :b 0)))))
((and (= i cur-sel) more-than-one) (setf color-list (append color-list (list sdl:*yellow*))))
((and (/= i cur-sel) (not more-than-one)) (setf color-list (append color-list (list (sdl:color :r 150 :g 150 :b 150)))))
((and (/= i cur-sel) more-than-one) (setf color-list (append color-list (list sdl:*white*))))))))
(t (if (= i cur-sel)
(setf color-list (append color-list (list sdl:*yellow*)))
(setf color-list (append color-list (list sdl:*white*)))))))
(draw-selection-list menu-items cur-sel (length menu-items) 20 (+ 10 (* (sdl:char-height sdl:*default-font*) (+ 4 text-str-num))) :color-list color-list))
)
(sdl:with-rectangle (rect (sdl:rectangle :x 10 :y (- *window-height* 10 (* 2 (sdl:char-height sdl:*default-font*))) :w (- *window-width* 20) :h (* 2 (sdl:char-height sdl:*default-font*))))
(let ((str (create-string)))
(case cur-step
(:custom-scenario-tab-missions (format str "[Enter/Right] Select [Up/Down] Move selection [Esc] Exit"))
(:custom-scenario-tab-specific-factions (format str "[Enter] Start game [Up/Down] Move selection [Left] Previous step [Esc] Exit"))
(:custom-scenario-tab-factions (progn
(let* ((current-faction (first (nth cur-faction cur-faction-list)))
(faction-present (second (nth cur-faction cur-faction-list)))
(ref-faction-obj (find current-faction
avail-faction-list :key #'(lambda (a)
(first a))))
(ref-faction-present-pos (position faction-present (second ref-faction-obj)))
(next-faction-present (if (>= (1+ ref-faction-present-pos) (length (second ref-faction-obj)))
(first (second ref-faction-obj))
(nth (1+ ref-faction-present-pos) (second ref-faction-obj)))))
(cond
((<= (length (second ref-faction-obj)) 1) nil)
((eq next-faction-present :mission-faction-present) (format str "[Space] Include as present faction "))
((eq next-faction-present :mission-faction-delayed) (format str "[Space] Include as delayed faction "))
((eq next-faction-present :mission-faction-absent) (format str "[Space] Exclude the faction "))))
(format str "[Right] Next step [Up/Down] Move selection [Left] Previous step [Esc] Exit")
))
(:custom-scenario-tab-feats (progn
(when (not (find (nth cur-sel overall-lvl-mods-list) always-lvl-mods-list))
(if (find (nth cur-sel overall-lvl-mods-list) select-lvl-mods-list)
(format str "[Space] Remove feat ")
(format str "[Space] Add feat ")))
(format str "[Right] Next step [Up/Down] Move selection [Left] Previous step [Esc] Exit")
))
(t (format str "[Enter/Right] Select [Up/Down] Move selection [Left] Previous step [Esc] Exit"))
)
(write-text str rect)))
(sdl:update-display))))
(defmethod run-window ((win custom-scenario-window))
(sdl:with-events ()
(:quit-event () (funcall (quit-func win)) t)
(:key-down-event (:key key :mod mod :unicode unicode)
(with-slots (cur-step cur-sel menu-items scenario months-list cur-mission-type cur-sector cur-month cur-feat cur-faction cur-specific-faction) win
(with-slots (world world-sector mission
avail-mission-type-list avail-world-sector-type-list
overall-lvl-mods-list always-lvl-mods-list select-feats-list select-items-list select-weather-list select-misc-list
avail-faction-list cur-faction-list specific-faction-list)
scenario
(cond
((sdl:key= key :sdl-key-left)
(progn
(when (defenum:previous-enum-tag 'custom-scenario-window-tab-type cur-step)
(setf cur-step (defenum:previous-enum-tag 'custom-scenario-window-tab-type cur-step)))
(setf menu-items (populate-custom-scenario-win-menu win cur-step))))
((sdl:key= key :sdl-key-right)
(progn
(when (defenum:next-enum-tag 'custom-scenario-window-tab-type cur-step)
(setf cur-step (defenum:next-enum-tag 'custom-scenario-window-tab-type cur-step)))
(setf menu-items (populate-custom-scenario-win-menu win cur-step))))
;; escape - quit
((sdl:key= key :sdl-key-escape)
(setf *current-window* (return-to win))
(return-from run-window (values nil nil)))
;; Space - add/remove feat inside feats tab
((and (sdl:key= key :sdl-key-space)
(eq cur-step :custom-scenario-tab-feats))
(progn
(let ((lvl-mod (nth cur-sel overall-lvl-mods-list)))
(when (not (find lvl-mod always-lvl-mods-list))
(case (lm-type lvl-mod)
;; make a radio button for the controlled-by lvl mods
(:level-mod-controlled-by (scenario-add/remove-lvl-mod scenario lvl-mod))
;; make checkboxes for the feats lvl mods
(:level-mod-sector-feat (if (find lvl-mod select-feats-list)
(progn
(scenario-add/remove-lvl-mod scenario lvl-mod :add-general nil))
(progn
(scenario-add/remove-lvl-mod scenario lvl-mod :add-general t))))
;; make checkboxes for the items lvl mods
(:level-mod-sector-item (if (find lvl-mod select-items-list)
(progn
(scenario-add/remove-lvl-mod scenario lvl-mod :add-general nil))
(progn
(scenario-add/remove-lvl-mod scenario lvl-mod :add-general t))))
;; make a radio button for the time of day lvl mods
(:level-mod-tod (scenario-add/remove-lvl-mod scenario lvl-mod))
;; make checkboxes for the weather lvl mods
(:level-mod-weather (if (find lvl-mod select-weather-list)
(progn
(scenario-add/remove-lvl-mod scenario lvl-mod :add-general nil))
(progn
(scenario-add/remove-lvl-mod scenario lvl-mod :add-general t))))
;; make checkboxes for misc lvl mods
(:level-mod-misc (if (find lvl-mod select-misc-list)
(progn
(scenario-add/remove-lvl-mod scenario lvl-mod :add-general nil))
(progn
(scenario-add/remove-lvl-mod scenario lvl-mod :add-general t)))))
(generate-feats-for-world-sector world-sector (world-map world))
(scenario-adjust-lvl-mods-after-sector-regeneration scenario)
(scenario-sort-select-lvl-mods scenario)
(readjust-factions-after-feats-change win)
(setf menu-items (populate-custom-scenario-win-menu win cur-step))))))
;; Space - add/remove faction inside factions tab
((and (sdl:key= key :sdl-key-space)
(eq cur-step :custom-scenario-tab-factions))
(progn
(let* ((current-faction (first (nth cur-faction cur-faction-list)))
(faction-present (second (nth cur-faction cur-faction-list)))
(ref-faction-obj (find current-faction
avail-faction-list :key #'(lambda (a)
(first a))))
(ref-faction-present-pos (position faction-present (second ref-faction-obj)))
(next-faction-present (if (>= (1+ ref-faction-present-pos) (length (second ref-faction-obj)))
(first (second ref-faction-obj))
(nth (1+ ref-faction-present-pos) (second ref-faction-obj)))))
(setf (nth cur-faction cur-faction-list) (list current-faction next-faction-present))
(readjust-specific-factions-after-faction-change win)
(setf menu-items (populate-custom-scenario-win-menu win cur-step)))))
;; enter - select
((or (sdl:key= key :sdl-key-return) (sdl:key= key :sdl-key-kp-enter))
(if (not (eq cur-step :custom-scenario-tab-specific-factions))
(progn
(setf cur-step (defenum:next-enum-tag 'custom-scenario-window-tab-type cur-step))
(setf menu-items (populate-custom-scenario-win-menu win cur-step)))
(progn
(scenario-set-player-specific-faction scenario (nth cur-specific-faction specific-faction-list))
(return-from run-window (values world-sector mission)))))
)
(case cur-step
(:custom-scenario-tab-missions (progn (let ((prev-cur-sel cur-mission-type))
(setf cur-mission-type (run-selection-list key mod unicode cur-mission-type))
(setf cur-mission-type (adjust-selection-list cur-mission-type (length avail-mission-type-list)))
(setf cur-sel cur-mission-type)
(when (/= prev-cur-sel cur-sel)
(adjust-mission-after-change win)))))
(:custom-scenario-tab-sectors (progn (let ((prev-cur-sel cur-sector))
(setf cur-sector (run-selection-list key mod unicode cur-sector))
(setf cur-sector (adjust-selection-list cur-sector (length avail-world-sector-type-list)))
(setf cur-sel cur-sector)
(when (/= prev-cur-sel cur-sel)
(adjust-world-sector-after-change win)))))
(:custom-scenario-tab-months (progn (let ((prev-cur-sel cur-month))
(setf cur-month (run-selection-list key mod unicode cur-month))
(setf cur-month (adjust-selection-list cur-month (length months-list)))
(setf cur-sel cur-month)
(when (/= prev-cur-sel cur-sel)
(adjust-months-before-feats win)))))
(:custom-scenario-tab-feats (progn (setf cur-feat (run-selection-list key mod unicode cur-feat))
(setf cur-feat (adjust-selection-list cur-feat (length overall-lvl-mods-list)))
(setf cur-sel cur-feat)
))
(:custom-scenario-tab-factions (progn (setf cur-faction (run-selection-list key mod unicode cur-faction))
(setf cur-faction (adjust-selection-list cur-faction (length cur-faction-list)))
(setf cur-sel cur-faction)
))
(:custom-scenario-tab-specific-factions (progn (setf cur-specific-faction (run-selection-list key mod unicode cur-specific-faction))
(setf cur-specific-faction (adjust-selection-list cur-specific-faction
(length specific-faction-list)))
(setf cur-sel cur-specific-faction))))
(make-output *current-window*))))
(:video-expose-event () (make-output *current-window*))))
| 33,759
|
Common Lisp
|
.lisp
| 408
| 51.887255
| 204
| 0.487917
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
ceb82b73e10b77af6c983277d5a30f33eaa3af30d5a92730d396cea288f7b0ef
| 2,930
|
[
-1
] |
2,931
|
window-settings.lisp
|
gwathlobal_CotD/src/windows/window-settings.lisp
|
(in-package :cotd)
(defclass settings-window (window)
((cur-str :initform 0 :accessor cur-str)
(cur-sel :initform 0 :accessor cur-sel)
(options-list :initform (list (list " Font size"
;; currently displayed value
#'(lambda (options)
(options-font options))
;; function to change the value
#'(lambda ()
(let ((avail-values (list 'font-6x13 'font-8x13))
(n 0))
;; find current value
(setf n (loop for i from 0 below (length avail-values)
for item in avail-values
do
(when (eq item (options-font *options*))
(return i))
))
;; move to next value
(incf n)
(when (>= n (length avail-values))
(setf n 0))
(setf (options-font *options*) (nth n avail-values)))
))
(list " Player name"
;; currently displayed value
#'(lambda (options)
(options-player-name options))
;; function to change the value
#'(lambda ()
(setf *current-window* (make-instance 'input-str-window
:init-input (options-player-name *options*)
:header-str "Choose name"
:main-str "Enter you name"
:prompt-str "[Enter] Confirm [Esc] Cancel"
:all-func nil
:no-escape nil
:input-check-func #'(lambda (char cur-str)
(if (and (not (null char))
(or (find (string-downcase (string char)) *char-list* :test #'string=)
(char= char #\Space)
(char= char #\-))
(< (length cur-str) *max-player-name-length*))
t
nil))
:final-check-func #'(lambda (full-input-str)
(if (not (null full-input-str))
t
nil))
))
(make-output *current-window*)
(let ((return-value (run-window *current-window*)))
(unless (eq return-value nil)
(setf (options-player-name *options*) return-value)))
))
(list "Hide messages available through Singlemind"
;; currently displayed value
#'(lambda (options)
(if (options-ignore-singlemind-messages options)
"Yes"
"No")
)
;; function to change the value
#'(lambda ()
(if (options-ignore-singlemind-messages *options*)
(setf (options-ignore-singlemind-messages *options*) nil)
(setf (options-ignore-singlemind-messages *options*) t))
)))
:initarg :options-list
:accessor options-list)))
(defmethod make-output ((win settings-window))
;; fill the screen black
(sdl:with-rectangle (a-rect (sdl:rectangle :x 0 :y 0 :w *window-width* :h *window-height*))
(sdl:fill-surface sdl:*black* :template a-rect))
(sdl:draw-string-solid-* "SETTINGS" (truncate *window-width* 2) 10 :justify :center :color sdl:*white*)
(let ((cur-str (cur-sel win))
(color-list nil)
(options-list (loop for item in (options-list win)
collect (format nil "~A : ~A" (first item) (funcall (second item) *options*)))))
(dotimes (i (length (options-list win)))
(if (= i cur-str)
(setf color-list (append color-list (list sdl:*yellow*)))
(setf color-list (append color-list (list sdl:*white*)))))
(draw-selection-list options-list cur-str (length options-list) 20 (+ 10 20) :color-list color-list :use-letters t))
(sdl:draw-string-solid-* (format nil "[Enter] Change [Esc] Quit")
10 (- *window-height* 13 (sdl:char-height sdl:*default-font*)))
(sdl:update-display))
(defmethod run-window ((win settings-window))
(sdl:with-events ()
(:quit-event () (funcall (quit-func win)) t)
(:key-down-event (:key key :mod mod :unicode unicode)
;; normalize mod
(loop while (>= mod sdl-key-mod-num) do
(decf mod sdl-key-mod-num))
(setf (cur-sel win) (run-selection-list key mod unicode (cur-sel win) :start-page (truncate (cur-sel win) (length (options-list win))) :max-str-per-page (length (options-list win))))
(setf (cur-sel win) (adjust-selection-list (cur-sel win) (length (options-list win))))
(cond
((sdl:key= key :sdl-key-escape)
(setf *current-window* (return-to win)) (make-output *current-window*) (return-from run-window nil))
((or (sdl:key= key :sdl-key-return) (sdl:key= key :sdl-key-kp-enter))
(funcall (third (nth (cur-sel win) (options-list win))))
(with-open-file (file (merge-pathnames "options.cfg" *current-dir*) :direction :output :if-exists :supersede)
(format file "~A" (create-options-file-string *options*)))
))
(make-output *current-window*)
)
(:video-expose-event () (make-output *current-window*)))
)
| 8,533
|
Common Lisp
|
.lisp
| 109
| 35.706422
| 203
| 0.33297
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
63508f94b1d148394165e14155e0db51fedc02c162254a6332a180b152f4ed17
| 2,931
|
[
-1
] |
2,932
|
window-methods.lisp
|
gwathlobal_CotD/src/windows/window-methods.lisp
|
(in-package :cotd)
(defvar *glyph-temp*)
(defvar *glyph-front*)
(defvar *window-width*)
(defvar *window-height*)
(defparameter *temp-rect* nil)
(defparameter *msg-box-window-height* (* 13 5))
(defun draw-glyph (x y n &key (surface sdl:*default-surface*) front-color back-color)
"Drawing a glyph from 'font.bmp' at a certain point of the surface."
(declare (type fixnum x y n) (type sdl:color front-color back-color))
;; select a rectangle with the glyph to be drawn
(sdl:set-cell-* (* n *glyph-w*) 0 *glyph-w* *glyph-h* :surface *glyph-front* :index 0)
;; fill the temporary surface with the desired color of the glyph
;; draw the glyph to the temporary surface
;; as the transparent color of the src surface is the actual color of the glyph (white), we get the glyph of the desired color on the black background
(sdl:fill-surface front-color :surface *glyph-temp*)
(sdl:draw-surface-at-* *glyph-front* 0 0 :surface *glyph-temp*)
;; fill the rectangle on the dst surface with the desired color of the background
;; draw the glyph from the temporary surface to the dst surface
;; as the transparent color of the temporary surface is black, we get the glyph of the desired color on the desired background
;; for speed I use this temporary rectangle as this function is invoked about 4000 times or more a frame and otherwise (e.g. using with-rectangle) map rendering slows to a crawl
(setf (sdl:x *temp-rect*) x)
(setf (sdl:y *temp-rect*) y)
(setf (sdl:width *temp-rect*) *glyph-w*)
(setf (sdl:height *temp-rect*) *glyph-h*)
(sdl:fill-surface back-color :surface surface :template *temp-rect*)
(sdl:draw-surface-at-* *glyph-temp* x y :surface surface))
(defun calculate-start-coord (rel-x rel-y array max-x-view max-y-view)
"Calculate the top-left corner of the visible area. Used to draw the map and to choose objects on it."
(let* ((array-max-x (first (array-dimensions array))) (array-max-y (second (array-dimensions array)))
(max-x (min array-max-x max-x-view)) (max-y (min array-max-y max-y-view))
(sx 0) (sy 0))
(declare (type fixnum sx sy max-x max-y))
(setf sx (if (< (- rel-x (truncate max-x 2)) 1) 0 (- rel-x (truncate max-x 2))))
(setf sy (if (< (- rel-y (truncate max-y 2)) 1) 0 (- rel-y (truncate max-y 2))))
(when (> (+ sx max-x) array-max-x) (setf sx (- array-max-x max-x)))
(when (> (+ sy max-y) array-max-y) (setf sy (- array-max-y max-y)))
;;(format t "rel = (~A, ~A), s = (~A, ~A)~%" rel-x rel-y sx sy)
(values sx sy max-x max-y)))
(defun update-map-area (start-x start-y &key (rel-x (x *player*)) (rel-y (y *player*)) (rel-z (z *player*)) (array (memo (level *world*))) (max-x-view *max-x-view*) (max-y-view *max-y-view*)
(post-func #'(lambda (x y x1 y1) (declare (ignore x y x1 y1)) nil)))
(declare (optimize (speed 3)))
;; draw the level
(let* ((x1 0) (y1 0) (glyph-w *glyph-w*) (glyph-h *glyph-h*) (single-memo))
(declare (type fixnum x1 y1 rel-x rel-y glyph-w glyph-h))
(multiple-value-bind (sx sy max-x max-y) (calculate-start-coord rel-x rel-y array max-x-view max-y-view)
(declare (type fixnum sx sy max-x max-y))
(dotimes (x max-x)
(declare (type fixnum x))
(dotimes (y max-y)
(declare (type fixnum y))
;; calculate the coordinates where to draw the glyph
(setf x1 (+ (* x glyph-w) start-x))
(setf y1 (+ (* y glyph-h) start-y))
;; select the object, the glyph of which shall be drawn
(setf single-memo (aref array (+ sx x) (+ sy y) rel-z))
;;(when (and (eql (get-single-memo-visible single-memo) nil)
;; (not (eql (glyph object) (map-object-template-glyph (get-map-object-template +glyph-blank+)))))
;; (setf (glyph-color object) (sdl:color :r 140 :b 140 :g 140))
;; (setf (back-color object) (sdl:color :r 30 :b 30 :g 30)))
;; draw the glyph
(draw-glyph x1 y1 (get-single-memo-glyph-idx single-memo)
:front-color (get-single-memo-glyph-color single-memo)
:back-color (get-single-memo-back-color single-memo))
(funcall post-func (+ sx x) (+ sy y) x1 y1)
(when (get-single-memo-player single-memo)
(highlight-map-tile x1 y1)))))))
(defun highlight-left-top-corner (x1 y1 &key (color sdl:*yellow*))
(sdl:draw-pixel-* (+ x1 1) y1 :color color)
(sdl:draw-pixel-* (+ x1 2) y1 :color color)
(sdl:draw-pixel-* x1 (+ y1 1) :color color)
(sdl:draw-pixel-* x1 (+ y1 2) :color color))
(defun highlight-left-bottom-corner (x1 y1 &key (color sdl:*yellow*))
(sdl:draw-pixel-* (+ x1 1) y1 :color color)
(sdl:draw-pixel-* (+ x1 2) y1 :color color)
(sdl:draw-pixel-* x1 (- y1 1) :color color)
(sdl:draw-pixel-* x1 (- y1 2) :color color))
(defun highlight-right-top-corner (x1 y1 &key (color sdl:*yellow*))
(sdl:draw-pixel-* (- x1 1) y1 :color color)
(sdl:draw-pixel-* (- x1 2) y1 :color color)
(sdl:draw-pixel-* x1 (+ y1 1) :color color)
(sdl:draw-pixel-* x1 (+ y1 2) :color color))
(defun highlight-right-bottom-corner (x1 y1 &key (color sdl:*yellow*))
(sdl:draw-pixel-* (- x1 1) y1 :color color)
(sdl:draw-pixel-* (- x1 2) y1 :color color)
(sdl:draw-pixel-* x1 (- y1 1) :color color)
(sdl:draw-pixel-* x1 (- y1 2) :color color))
(defun highlight-map-tile (x1 y1)
(let ((color (sdl:color :r 85 :g 107 :b 47)))
;; draw the rectangle
(highlight-left-top-corner x1 y1 :color color)
(highlight-left-bottom-corner x1 (+ y1 (1- *glyph-h*)) :color color)
(highlight-right-top-corner (+ x1 (1- *glyph-w*)) y1 :color color)
(highlight-right-bottom-corner (+ x1 (1- *glyph-w*)) (+ y1 (1- *glyph-h*)) :color color)
))
(defun highlight-world-map-tile (x1 y1)
(let ((color sdl:*yellow*))
;; draw the rectangle
(highlight-left-top-corner x1 y1 :color color)
(highlight-left-bottom-corner x1 (+ y1 (* *glyph-h* 5) -1) :color color)
(highlight-right-top-corner (+ x1 (* *glyph-w* 5) -1) y1 :color color)
(highlight-right-bottom-corner (+ x1 (* *glyph-w* 5) -1) (+ y1 (* *glyph-h* 5) -1) :color color)
))
(defun check-tile-on-map (map-x map-y map-z sx sy max-x-view max-y-view view-z)
(if (and (>= map-x sx) (>= map-y sy)
(< map-x (+ sx max-x-view))
(< map-y (+ sy max-y-view))
(= view-z map-z))
t
nil))
(defun display-animation-on-map (map-x map-y map-z glyph-idx glyph-color back-color)
(let ((scr-x 0) (scr-y 0))
(declare (type fixnum scr-x scr-y))
(when (/= (view-z *player*) map-z)
(return-from display-animation-on-map nil))
(multiple-value-bind (sx sy) (calculate-start-coord (x *player*) (y *player*) (memo (level *world*)) *max-x-view* *max-y-view*)
;; calculate the coordinates where to draw the animation
(setf scr-x (+ (* (- map-x sx) *glyph-w*) *start-map-x*))
(setf scr-y (+ (* (- map-y sy) *glyph-h*)))
;(format t "MAP-X ~A MAP-Y ~A; SX ~A SY ~A; SCR-X ~A SCR-Y ~A~%" map-x map-y sx sy scr-x scr-y)
;; drawing glyph
(draw-glyph scr-x scr-y glyph-idx
:front-color glyph-color
:back-color back-color)
)
))
(defun display-cell-on-map (map-x map-y map-z &key (array (memo (level *world*))))
(let ((scr-x 0) (scr-y 0) (single-memo))
(declare (type fixnum scr-x scr-y))
(when (/= (view-z *player*) map-z)
(return-from display-cell-on-map nil))
(multiple-value-bind (sx sy) (calculate-start-coord (x *player*) (y *player*) (memo (level *world*)) *max-x-view* *max-y-view*)
;; calculate the coordinates where to draw the animation
(setf scr-x (+ (* (- map-x sx) *glyph-w*) *start-map-x*))
(setf scr-y (+ (* (- map-y sy) *glyph-h*)))
(setf single-memo (aref array map-x map-y map-z))
;; drawing glyph
(draw-glyph scr-x scr-y (get-single-memo-glyph-idx single-memo)
:front-color (get-single-memo-glyph-color single-memo)
:back-color (get-single-memo-back-color single-memo))
)
))
(defun fill-background-tiles ()
"Fill the background"
(sdl:with-rectangle (a-rect (sdl:rectangle :x 0 :y 0 :w *window-width* :h *window-height*))
(sdl:fill-surface sdl:*black* :template a-rect)))
(defun create-string (&optional str)
(let ((new-str (make-array (list 0) :element-type 'character :adjustable t :fill-pointer t)))
(when str
(format new-str str))
new-str))
(defun get-input-player ()
(run-window *current-window*)
)
(defun get-text-input (str key mod unicode)
(declare (ignore key mod))
(when (> unicode 0)
(vector-push-extend (code-char unicode) str))
str)
(defvar *sel-y-offset* 0)
(defvar *sel-x-offset* 4)
(defun draw-selection-list (str-list cur-str str-per-page x y &key (color-list ())
(char-height (+ (sdl:char-height sdl:*default-font*) *sel-y-offset*))
(str-func #'(lambda (x y color str use-letters)
;; use-letters here can be
;; nil
;; (list i str-per-page)
(sdl:draw-string-solid-* (if use-letters
(if (< (first use-letters) (second use-letters))
(format nil "[~A] ~A" (nth (first use-letters) *char-list*) str)
(format nil " ~A" str))
str)
x y :color color)))
(use-letters nil))
(declare (type list color-list str-list))
(unless str-list
(return-from draw-selection-list nil))
(when (and use-letters (> str-per-page (length *char-list*)))
(setf str-per-page (length *char-list*)))
(let* ((color) (str)
(list-start (* (truncate cur-str str-per-page) str-per-page))
(list-end (if (> (+ list-start str-per-page) (length str-list)) (length str-list) (+ list-start str-per-page))))
;; from the start of the current page (determined previously) to the end of the page (or end of list whichever is less)
(dotimes (i (- list-end list-start))
(setf str (nth (+ i list-start) str-list))
;; highlight the current selected item
(if (eql color-list nil)
(setf color sdl:*white*)
(setf color (nth (+ i list-start) color-list)))
(funcall str-func (+ x (sdl:char-width sdl:*default-font*) *sel-x-offset*) (+ y (* i char-height)) color str (if use-letters
(list i str-per-page)
nil))
)
;; draw a scroll bar when necessary
(when (> (length str-list) str-per-page)
(sdl:draw-string-solid-* "*" x (+ y (* char-height (truncate (* (/ cur-str (length str-list)) str-per-page)))) :color sdl:*white*))))
(defun draw-multiline-selection-list (item-list cur-item x y w h &optional (color-list ()))
(unless item-list
(return-from draw-multiline-selection-list nil))
(sdl:with-rectangle (rect (sdl:rectangle :x x :y y :w (- w 12) :h h))
(let ((screen-list ()) (start-item) (is-more-than-one-screen nil))
;; assign numbers of screens to the items pertaining to them
(let ((screen-i 0) (item-h) (is-first t))
(dotimes (i (length item-list))
(setf item-h (* 13 (write-text (nth i item-list) rect :count-only t)))
(if (or (> (sdl:height rect) item-h) (and is-first (<= (sdl:height rect) item-h)))
(progn
(setf screen-list (append screen-list (list screen-i)))
(setf is-first nil)
(if (> (sdl:height rect) item-h)
(progn
(incf (sdl:y rect) item-h)
(decf (sdl:height rect) item-h))
(progn
(incf screen-i)
(setf is-more-than-one-screen t))))
(progn
(incf screen-i)
(setf is-more-than-one-screen t)
(setf screen-list (append screen-list (list screen-i)))
(setf (sdl:y rect) y)
(setf (sdl:height rect) h)
(incf (sdl:y rect) item-h)
(decf (sdl:height rect) item-h)
(setf is-first t)))
))
;; find the screen by current item
(dotimes (i (length item-list))
(when (= (nth i screen-list) (nth cur-item screen-list))
(setf start-item i)
(return)))
;; draw the screen found
(let ((str) (item-h) (color))
(setf (sdl:y rect) y)
(setf (sdl:height rect) h)
;; yes, ugly hack but I was being lazy and did not want to investigate how to create a 'while' statement
;; iterate through all items until we get to the starting one
(dotimes (i (- (length item-list) start-item))
(if (= (nth (+ i start-item) screen-list) (nth cur-item screen-list))
(progn
(setf str (nth (+ i start-item) item-list))
;; highlight the current selected item
(if (eql color-list nil)
(setf color sdl:*white*)
(setf color (nth (+ i start-item) color-list)))
(setf item-h (* 13 (write-text str rect :color color :count-only nil)))
(when (> (sdl:height rect) item-h)
(incf (sdl:y rect) item-h)
(decf (sdl:height rect) item-h)))
(progn
(return)))))
;; draw scroll bar when necessary
(when is-more-than-one-screen
(sdl:draw-string-solid-* "*" (- (+ x w) 12) (+ y (truncate (* h (/ cur-item (length item-list))))) :color sdl:*white*)))))
;; I might do something wrong here but I am not sure how I can access this enum otherwise
(defconstant SDL-KEY-MOD-NUM (cffi:foreign-enum-value sdl-cffi::'Sdl-Mod :SDL-KEY-MOD-NUM))
(defun run-selection-list (key mod unicode cur-str &key (start-page 0) (max-str-per-page -1) (use-letters t))
(declare (ignore unicode))
;; normalize mod
(loop while (>= mod sdl-key-mod-num) do
(decf mod sdl-key-mod-num))
(cond
((and (or (sdl:key= key :sdl-key-up) (sdl:key= key :sdl-key-kp8)) (= mod 0)) (decf cur-str))
((and (or (sdl:key= key :sdl-key-down) (sdl:key= key :sdl-key-kp2)) (= mod 0)) (incf cur-str))
((and (or (sdl:key= key :sdl-key-up) (sdl:key= key :sdl-key-kp8)) (/= (logand mod sdl-cffi::sdl-key-mod-shift) 0))
(if (= max-str-per-page -1)
(decf cur-str 10)
(decf cur-str max-str-per-page)))
((and (or (sdl:key= key :sdl-key-down) (sdl:key= key :sdl-key-kp2)) (/= (logand mod sdl-cffi::sdl-key-mod-shift) 0))
(if (= max-str-per-page -1)
(incf cur-str 10)
(incf cur-str max-str-per-page)))
((and use-letters (sdl:key= key :sdl-key-a) (= mod 0) (< 0 max-str-per-page)) (setf cur-str (+ (* start-page max-str-per-page) 0)))
((and use-letters (sdl:key= key :sdl-key-b) (= mod 0) (< 1 max-str-per-page)) (setf cur-str (+ (* start-page max-str-per-page) 1)))
((and use-letters (sdl:key= key :sdl-key-c) (= mod 0) (< 2 max-str-per-page)) (setf cur-str (+ (* start-page max-str-per-page) 2)))
((and use-letters (sdl:key= key :sdl-key-d) (= mod 0) (< 3 max-str-per-page)) (setf cur-str (+ (* start-page max-str-per-page) 3)))
((and use-letters (sdl:key= key :sdl-key-e) (= mod 0) (< 4 max-str-per-page)) (setf cur-str (+ (* start-page max-str-per-page) 4)))
((and use-letters (sdl:key= key :sdl-key-f) (= mod 0) (< 5 max-str-per-page)) (setf cur-str (+ (* start-page max-str-per-page) 5)))
((and use-letters (sdl:key= key :sdl-key-g) (= mod 0) (< 6 max-str-per-page)) (setf cur-str (+ (* start-page max-str-per-page) 6)))
((and use-letters (sdl:key= key :sdl-key-h) (= mod 0) (< 7 max-str-per-page)) (setf cur-str (+ (* start-page max-str-per-page) 7)))
((and use-letters (sdl:key= key :sdl-key-i) (= mod 0) (< 8 max-str-per-page)) (setf cur-str (+ (* start-page max-str-per-page) 8)))
((and use-letters (sdl:key= key :sdl-key-j) (= mod 0) (< 9 max-str-per-page)) (setf cur-str (+ (* start-page max-str-per-page) 9)))
((and use-letters (sdl:key= key :sdl-key-k) (= mod 0) (< 10 max-str-per-page)) (setf cur-str (+ (* start-page max-str-per-page) 10)))
((and use-letters (sdl:key= key :sdl-key-l) (= mod 0) (< 11 max-str-per-page)) (setf cur-str (+ (* start-page max-str-per-page) 11)))
((and use-letters (sdl:key= key :sdl-key-m) (= mod 0) (< 12 max-str-per-page)) (setf cur-str (+ (* start-page max-str-per-page) 12)))
((and use-letters (sdl:key= key :sdl-key-n) (= mod 0) (< 13 max-str-per-page)) (setf cur-str (+ (* start-page max-str-per-page) 13)))
((and use-letters (sdl:key= key :sdl-key-o) (= mod 0) (< 14 max-str-per-page)) (setf cur-str (+ (* start-page max-str-per-page) 14)))
((and use-letters (sdl:key= key :sdl-key-p) (= mod 0) (< 15 max-str-per-page)) (setf cur-str (+ (* start-page max-str-per-page) 15)))
((and use-letters (sdl:key= key :sdl-key-q) (= mod 0) (< 16 max-str-per-page)) (setf cur-str (+ (* start-page max-str-per-page) 16)))
((and use-letters (sdl:key= key :sdl-key-r) (= mod 0) (< 17 max-str-per-page)) (setf cur-str (+ (* start-page max-str-per-page) 17)))
((and use-letters (sdl:key= key :sdl-key-s) (= mod 0) (< 18 max-str-per-page)) (setf cur-str (+ (* start-page max-str-per-page) 18)))
((and use-letters (sdl:key= key :sdl-key-t) (= mod 0) (< 19 max-str-per-page)) (setf cur-str (+ (* start-page max-str-per-page) 19)))
((and use-letters (sdl:key= key :sdl-key-u) (= mod 0) (< 20 max-str-per-page)) (setf cur-str (+ (* start-page max-str-per-page) 20)))
((and use-letters (sdl:key= key :sdl-key-v) (= mod 0) (< 21 max-str-per-page)) (setf cur-str (+ (* start-page max-str-per-page) 21)))
((and use-letters (sdl:key= key :sdl-key-w) (= mod 0) (< 22 max-str-per-page)) (setf cur-str (+ (* start-page max-str-per-page) 22)))
((and use-letters (sdl:key= key :sdl-key-x) (= mod 0) (< 23 max-str-per-page)) (setf cur-str (+ (* start-page max-str-per-page) 23)))
((and use-letters (sdl:key= key :sdl-key-y) (= mod 0) (< 24 max-str-per-page)) (setf cur-str (+ (* start-page max-str-per-page) 24)))
((and use-letters (sdl:key= key :sdl-key-z) (= mod 0) (< 25 max-str-per-page)) (setf cur-str (+ (* start-page max-str-per-page) 25))))
cur-str)
(defun adjust-selection-list (cur-str max-str)
(when (< cur-str 0) (setf cur-str 0))
(when (>= cur-str max-str) (setf cur-str (- max-str 1)))
cur-str)
(defun read-word (txt start-pos)
(let ((txt-length (length txt)) (was-letter nil) (cur-pos) (word-length) (eol nil))
(loop named outer finally (setf cur-pos read-pos word-length (- read-pos start-pos))
for read-pos from start-pos to (1- txt-length) do
(cond
((eql (char-code (aref txt read-pos)) (char-code #\Space)) (when (eql was-letter t) (setf cur-pos (incf read-pos) word-length (- read-pos start-pos)) (return-from outer nil)))
((eql (char-code (aref txt read-pos)) 13)
(setf eol t cur-pos read-pos word-length (- read-pos start-pos))
(when (< read-pos (1- txt-length))
(incf cur-pos))
(return-from outer nil))
((eql (char-code (aref txt read-pos)) 10) (setf eol t cur-pos (1+ read-pos) word-length (- read-pos start-pos)) (return-from outer nil))
(t (setf was-letter t))))
(values cur-pos word-length eol)))
(defun write-text (txt rect &key (surface sdl:*default-surface*) (justify :left) (color sdl:*white*) (font sdl:*default-font*) (count-only nil) (start-line 0))
(let ((txt-length (length txt)) (read-pos 0) (x (sdl:x rect)) (y (sdl:y rect)) (eol) (word-length) (row-length-in-pixels 0) (prev-pos) (cur-pos) (read-pos2) (cur-line 0)
(final-txt (create-string)))
(loop until (or (>= read-pos txt-length) (>= y (+ (sdl:y rect) (sdl:height rect)))) do
(setf prev-pos read-pos)
(setf cur-pos prev-pos)
(multiple-value-setq (read-pos word-length eol) (read-word txt read-pos))
(setf row-length-in-pixels (* word-length (sdl:char-width font)))
(incf cur-pos word-length)
(loop until (or (>= read-pos txt-length) (>= x (+ (sdl:x rect) (sdl:width rect)))) do
(when (eql eol t) (loop-finish))
(multiple-value-setq (read-pos2 word-length eol) (read-word txt read-pos))
(if (< (+ row-length-in-pixels (* word-length (sdl:char-width font))) (sdl:width rect))
(progn (incf row-length-in-pixels (* word-length (sdl:char-width font))) (setf read-pos read-pos2))
(progn (loop-finish)))
(incf cur-pos word-length))
(cond
((eql justify ':left) (setf x (sdl:x rect)))
((eql justify ':center) (setf x (truncate (+ (sdl:x rect) (sdl:width rect)) 2)))
((eql justify ':right) (setf x (+ (sdl:x rect) (sdl:width rect)))))
(when (and (eql count-only t) (>= cur-line start-line))
(format final-txt "~A~A~%" (subseq txt prev-pos cur-pos) (new-line)))
(when (and (eql count-only nil) (>= cur-line start-line))
(sdl:draw-string-solid-* (subseq txt prev-pos cur-pos) x y :justify justify :surface surface :font font :color color)
(incf y (sdl:char-height font)))
(incf cur-line))
(values cur-line final-txt)))
(defun write-colored-text (txt-struct rect &key (surface sdl:*default-surface*) (font sdl:*default-font*) (count-only nil) (start-line 0))
;;(format t "write-colored-text~%")
(let ((x (sdl:x rect)) (y (sdl:y rect)) (eol) (word-length) (prev-pos) (cur-pos) (read-pos2) (cur-line 0)
(final-txt (create-string)))
(loop for (txt color) in txt-struct
for txt-length = (length txt)
for read-pos = 0
do
;;(format t "TXT = ~A~%~%" txt)
(loop until (or (>= read-pos txt-length) (>= y (+ (sdl:y rect) (sdl:height rect)))) do
(setf prev-pos read-pos)
(setf cur-pos prev-pos)
(loop until (or (>= read-pos txt-length) (>= x (+ (sdl:x rect) (sdl:width rect)))) do
(when (eql eol t) (loop-finish))
(multiple-value-setq (read-pos2 word-length eol) (read-word txt read-pos))
(if (< (+ x (* word-length (sdl:char-width font))) (+ (sdl:x rect) (sdl:width rect)))
(progn
(setf read-pos read-pos2)
;;(format t "read-pos = ~A, cur-pos = ~A, cur-pos + world-length = ~A " read-pos cur-pos (+ cur-pos word-length))
;;(format t "txt = ~A~%" (subseq txt cur-pos (+ cur-pos word-length)))
(when (>= cur-line start-line)
(format final-txt "~A" (subseq txt cur-pos (+ cur-pos word-length)))
(when (null count-only)
(sdl:draw-string-solid-* (subseq txt cur-pos (+ cur-pos word-length)) x y :justify :left :surface surface :font font :color color)))
(incf x (* word-length (sdl:char-width font)))
(incf cur-pos word-length))
(progn (setf eol t) (loop-finish)))
)
;;(format t "X = ~A, Y = ~A, EOL = ~A, read-pos = ~A, txt-length = ~A~%" x y eol read-pos txt-length)
(when eol
(setf x (sdl:x rect))
(setf eol nil)
(when (>= cur-line start-line)
(format final-txt "~A~%" (new-line))
(when (null count-only)
(incf y (sdl:char-height font))))
(incf cur-line))
)
)
;;(format t "final-txt = ~A~%" final-txt)
(values cur-line final-txt)))
(defun show-escape-menu ()
(let ((menu-items ())
(prompt-list ())
(enter-func nil)
(header-str nil))
(case (game-manager/game-state *game-manager*)
(:game-state-campaign-scenario (progn
(setf header-str "Scenario Menu")
(setf menu-items (list "Save game & quit" "Abandon mission" "Close"))
(setf prompt-list (list #'(lambda (cur-sel)
(declare (ignore cur-sel))
"[Enter] Select [Esc] Exit")
#'(lambda (cur-sel)
(declare (ignore cur-sel))
"[Enter] Select [Esc] Exit")
#'(lambda (cur-sel)
(declare (ignore cur-sel))
"[Enter] Select [Esc] Exit")))
(setf enter-func #'(lambda (cur-sel)
(case cur-sel
(0 (progn
(save-game-to-disk :save-game-campaign :save-scenario)
(game-state-campaign-scenario->menu)
(go-to-start-game)
))
(1 (progn
(game-state-campaign-scenario->post-scenario)
(go-to-start-game)
))
(t (progn
(setf *current-window* (return-to *current-window*)))))
))))
(:game-state-custom-scenario (progn
(setf header-str "Scenario Menu")
(setf menu-items (list "Save game & quit" "Quit without saving" "Close"))
(setf prompt-list (list #'(lambda (cur-sel)
(declare (ignore cur-sel))
"[Enter] Select [Esc] Exit")
#'(lambda (cur-sel)
(declare (ignore cur-sel))
"[Enter] Select [Esc] Exit")
#'(lambda (cur-sel)
(declare (ignore cur-sel))
"[Enter] Select [Esc] Exit")))
(setf enter-func #'(lambda (cur-sel)
(case cur-sel
(0 (progn
(save-game-to-disk :save-game-scenario :save-scenario)
(game-state-custom-scenario->menu)
(go-to-start-game)
))
(1 (progn
(game-state-custom-scenario->menu)
(go-to-start-game)
))
(t (progn
(setf *current-window* (return-to *current-window*)))))
))))
(:game-state-campaign-map (progn
(setf header-str "Campaign Menu")
(setf menu-items (list "Save campaign & quit" "Quit without saving" "Close"))
(setf prompt-list (list #'(lambda (cur-sel)
(declare (ignore cur-sel))
"[Enter] Select [Esc] Exit")
#'(lambda (cur-sel)
(declare (ignore cur-sel))
"[Enter] Select [Esc] Exit")
#'(lambda (cur-sel)
(declare (ignore cur-sel))
"[Enter] Select [Esc] Exit")))
(setf enter-func #'(lambda (cur-sel)
(case cur-sel
(0 (progn
(save-game-to-disk :save-game-campaign :save-campaign)
(game-state-campaign-map->menu)
(go-to-start-game)
))
(1 (progn
(game-state-campaign-map->menu)
(go-to-start-game)
))
(t (progn
(setf *current-window* (return-to *current-window*)))))
)))))
(setf *current-window* (make-instance 'select-obj-window
:return-to *current-window*
:header-line header-str
:line-list menu-items
:prompt-list prompt-list
:enter-func enter-func
))
(make-output *current-window*)
(run-window *current-window*)))
(defun pause-for-poll ()
(sdl:with-events (:poll)
(:quit-event () (funcall (quit-func *current-window*)) t)
(:key-down-event (:key key :mod mod :unicode unicode)
(declare (ignore mod unicode))
(cond
;; escape - quit
((sdl:key= key :sdl-key-escape)
(show-escape-menu))
)
)
(:video-expose-event () (make-output *current-window*))
(:idle () (return-from pause-for-poll))))
(defun draw-world-map-cell (world-sector scr-x scr-y &key (reveal-lair nil))
(let* ((max-disp-w 5)
(max-disp-h 5)
(river-feat (find +lm-feat-river+ (feats world-sector) :key #'(lambda (a) (first a))))
(sea-feat (find +lm-feat-sea+ (feats world-sector) :key #'(lambda (a) (first a))))
(barricade-feat (find +lm-feat-barricade+ (feats world-sector) :key #'(lambda (a) (first a))))
(satanists-feat (find +lm-feat-lair+ (feats world-sector) :key #'(lambda (a) (first a))))
(church-feat (find +lm-feat-church+ (feats world-sector) :key #'(lambda (a) (first a))))
(library-feat (find +lm-feat-library+ (feats world-sector) :key #'(lambda (a) (first a))))
(machine-feat (find +lm-feat-hell-engine+ (feats world-sector) :key #'(lambda (a) (first a))))
(flesh-feat (find +lm-feat-hell-flesh-storage+ (feats world-sector) :key #'(lambda (a) (first a))))
(displayed-cells (make-array (list max-disp-w max-disp-h) :initial-element (list 0 sdl:*black* sdl:*black*)))
(water-color nil)
(gray-color (sdl:color :r 40 :g 40 :b 40))
(purple-color (sdl:color :r 40 :g 0 :b 40))
(brown-color (sdl:color :r 40 :g 20 :b 0))
(green-color (sdl:color :r 0 :g 40 :b 0)))
(when *world*
(multiple-value-bind (year month day hour min sec) (get-current-date-time (world-game-time *world*))
(declare (ignore year day hour min sec))
(if (or (= month 11) (= month 0) (= month 1))
(setf water-color (sdl:color :r 0 :g 150 :b 255))
(setf water-color sdl:*blue*))))
(case (wtype world-sector)
;; display sea sector
((:world-sector-normal-sea)
(progn
(setf displayed-cells (make-array (list max-disp-w max-disp-h) :initial-element (list +glyph-id-wall+ sdl:*blue* sdl:*black*)))))
;; display island sector
((:world-sector-normal-island :world-sector-abandoned-island :world-sector-corrupted-island)
(progn
(setf displayed-cells (make-array (list max-disp-w max-disp-h) :initial-element (list +glyph-id-wall+ sdl:*blue* sdl:*black*)))
(let ((r)
(color (case (wtype world-sector)
(:world-sector-normal-island brown-color)
(:world-sector-abandoned-island gray-color)
(:world-sector-corrupted-island purple-color)))
(glyph (case (wtype world-sector)
(:world-sector-normal-island +glyph-id-normal-house+)
(:world-sector-abandoned-island +glyph-id-abandoned-house+)
(:world-sector-corrupted-island +glyph-id-corrupted-house+))))
(loop for x from 1 to 3 do
(loop for y from 1 to 3 do
(setf r (random 8))
(case r
(0 (setf (aref displayed-cells x y) (list +glyph-id-campaign-house-1+ color sdl:*black*)))
(1 (setf (aref displayed-cells x y) (list +glyph-id-campaign-house-2+ color sdl:*black*)))
(2 (setf (aref displayed-cells x y) (list glyph color sdl:*black*)))
(t (setf (aref displayed-cells x y) (list 0 sdl:*black* sdl:*black*)))))))))
;; display outskirts sector
((:world-sector-normal-forest :world-sector-abandoned-forest :world-sector-corrupted-forest)
(progn
(let ((r)
(color-tree (case (wtype world-sector)
(:world-sector-normal-forest green-color)
(:world-sector-abandoned-forest gray-color)
(:world-sector-corrupted-forest purple-color)))
(color-house (case (wtype world-sector)
(:world-sector-normal-forest brown-color)
(:world-sector-abandoned-forest gray-color)
(:world-sector-corrupted-forest purple-color)))
(glyph (case (wtype world-sector)
(:world-sector-normal-forest +glyph-id-normal-tree+)
(:world-sector-abandoned-forest +glyph-id-abandoned-tree+)
(:world-sector-corrupted-forest +glyph-id-corrupted-tree+))))
(loop for x from 0 to 4 do
(loop for y from 0 to 4 do
(setf r (random 12))
(case r
(0 (setf (aref displayed-cells x y) (list +glyph-id-leaf-tree+ color-tree sdl:*black*)))
(1 (setf (aref displayed-cells x y) (list +glyph-id-pine-tree+ color-tree sdl:*black*)))
(2 (setf (aref displayed-cells x y) (list glyph color-tree sdl:*black*)))
(3 (setf (aref displayed-cells x y) (list +glyph-id-campaign-house-1+ color-house sdl:*black*)))
(4 (setf (aref displayed-cells x y) (list +glyph-id-campaign-house-2+ color-house sdl:*black*)))
(t (setf (aref displayed-cells x y) (list 0 sdl:*black* sdl:*black*)))))))))
;; display residential and seaport district
((:world-sector-normal-residential :world-sector-abandoned-residential :world-sector-corrupted-residential :world-sector-normal-port :world-sector-abandoned-port :world-sector-corrupted-port)
(progn
(let ((r)
(color (case (wtype world-sector)
((:world-sector-normal-residential :world-sector-normal-port) brown-color)
((:world-sector-abandoned-residential :world-sector-abandoned-port) gray-color)
((:world-sector-corrupted-residential :world-sector-corrupted-port) purple-color)))
(glyph (case (wtype world-sector)
((:world-sector-normal-residential :world-sector-normal-port) +glyph-id-normal-house+)
((:world-sector-abandoned-residential :world-sector-abandoned-port) +glyph-id-abandoned-house+)
((:world-sector-corrupted-residential :world-sector-corrupted-port) +glyph-id-corrupted-house+))))
(loop for x from 0 to 4 do
(loop for y from 0 to 4 do
(setf r (random 15))
(case r
(0 (setf (aref displayed-cells x y) (list +glyph-id-campaign-house-1+ color sdl:*black*)))
(1 (setf (aref displayed-cells x y) (list +glyph-id-campaign-house-2+ color sdl:*black*)))
(2 (setf (aref displayed-cells x y) (list glyph color sdl:*black*)))
(t (setf (aref displayed-cells x y) (list 0 sdl:*black* sdl:*black*)))))))
(when (and sea-feat
(or (eq (wtype world-sector) :world-sector-normal-port)
(eq (wtype world-sector) :world-sector-abandoned-port)
(eq (wtype world-sector) :world-sector-corrupted-port)))
(when (find :n (second sea-feat))
(setf (aref displayed-cells 0 1) (list 0 sdl:*black* sdl:*black*))
(setf (aref displayed-cells 1 1) (list +glyph-id-factory-icon+ gray-color sdl:*black*))
(setf (aref displayed-cells 2 1) (list +glyph-id-factory-icon+ gray-color sdl:*black*))
(setf (aref displayed-cells 3 1) (list +glyph-id-factory-icon+ gray-color sdl:*black*))
(setf (aref displayed-cells 4 1) (list 0 sdl:*black* sdl:*black*)))
(when (find :s (second sea-feat))
(setf (aref displayed-cells 0 3) (list 0 sdl:*black* sdl:*black*))
(setf (aref displayed-cells 1 3) (list +glyph-id-factory-icon+ gray-color sdl:*black*))
(setf (aref displayed-cells 2 3) (list +glyph-id-factory-icon+ gray-color sdl:*black*))
(setf (aref displayed-cells 3 3) (list +glyph-id-factory-icon+ gray-color sdl:*black*))
(setf (aref displayed-cells 4 3) (list 0 sdl:*black* sdl:*black*))
)
(when (find :w (second sea-feat))
(setf (aref displayed-cells 1 0) (list 0 sdl:*black* sdl:*black*))
(setf (aref displayed-cells 1 1) (list +glyph-id-factory-icon+ gray-color sdl:*black*))
(setf (aref displayed-cells 1 2) (list +glyph-id-factory-icon+ gray-color sdl:*black*))
(setf (aref displayed-cells 1 3) (list +glyph-id-factory-icon+ gray-color sdl:*black*))
(setf (aref displayed-cells 1 4) (list 0 sdl:*black* sdl:*black*)))
(when (find :e (second sea-feat))
(setf (aref displayed-cells 3 0) (list 0 sdl:*black* sdl:*black*))
(setf (aref displayed-cells 3 1) (list +glyph-id-factory-icon+ gray-color sdl:*black*))
(setf (aref displayed-cells 3 2) (list +glyph-id-factory-icon+ gray-color sdl:*black*))
(setf (aref displayed-cells 3 3) (list +glyph-id-factory-icon+ gray-color sdl:*black*))
(setf (aref displayed-cells 3 4) (list 0 sdl:*black* sdl:*black*))))))
;; display lake
((:world-sector-normal-lake :world-sector-abandoned-lake :world-sector-corrupted-lake)
(progn
(let ((r (random 12))
(color (case (wtype world-sector)
(:world-sector-normal-lake brown-color)
(:world-sector-abandoned-lake gray-color)
(:world-sector-corrupted-lake purple-color)))
(glyph (case (wtype world-sector)
(:world-sector-normal-lake +glyph-id-normal-house+)
(:world-sector-abandoned-lake +glyph-id-abandoned-house+)
(:world-sector-corrupted-lake +glyph-id-corrupted-house+))))
(loop for x from 0 to 4 do
(loop for y from 0 to 4 do
(setf r (random 12))
(case r
(0 (setf (aref displayed-cells x y) (list +glyph-id-campaign-house-1+ color sdl:*black*)))
(1 (setf (aref displayed-cells x y) (list +glyph-id-campaign-house-2+ color sdl:*black*)))
(2 (setf (aref displayed-cells x y) (list glyph color sdl:*black*)))
(t (setf (aref displayed-cells x y) (list 0 sdl:*black* sdl:*black*)))))))))
)
;; display barricades
(when barricade-feat
(when (find :n (second barricade-feat))
(setf (aref displayed-cells 0 0) (list +glyph-id-hash+ (sdl:color :r 139 :g 69 :b 19) sdl:*black*))
(setf (aref displayed-cells 1 0) (list +glyph-id-hash+ (sdl:color :r 139 :g 69 :b 19) sdl:*black*))
(setf (aref displayed-cells 2 0) (list +glyph-id-hash+ (sdl:color :r 139 :g 69 :b 19) sdl:*black*))
(setf (aref displayed-cells 3 0) (list +glyph-id-hash+ (sdl:color :r 139 :g 69 :b 19) sdl:*black*))
(setf (aref displayed-cells 4 0) (list +glyph-id-hash+ (sdl:color :r 139 :g 69 :b 19) sdl:*black*)))
(when (find :s (second barricade-feat))
(setf (aref displayed-cells 0 4) (list +glyph-id-hash+ (sdl:color :r 139 :g 69 :b 19) sdl:*black*))
(setf (aref displayed-cells 1 4) (list +glyph-id-hash+ (sdl:color :r 139 :g 69 :b 19) sdl:*black*))
(setf (aref displayed-cells 2 4) (list +glyph-id-hash+ (sdl:color :r 139 :g 69 :b 19) sdl:*black*))
(setf (aref displayed-cells 3 4) (list +glyph-id-hash+ (sdl:color :r 139 :g 69 :b 19) sdl:*black*))
(setf (aref displayed-cells 4 4) (list +glyph-id-hash+ (sdl:color :r 139 :g 69 :b 19) sdl:*black*)))
(when (find :w (second barricade-feat))
(setf (aref displayed-cells 0 0) (list +glyph-id-hash+ (sdl:color :r 139 :g 69 :b 19) sdl:*black*))
(setf (aref displayed-cells 0 1) (list +glyph-id-hash+ (sdl:color :r 139 :g 69 :b 19) sdl:*black*))
(setf (aref displayed-cells 0 2) (list +glyph-id-hash+ (sdl:color :r 139 :g 69 :b 19) sdl:*black*))
(setf (aref displayed-cells 0 3) (list +glyph-id-hash+ (sdl:color :r 139 :g 69 :b 19) sdl:*black*))
(setf (aref displayed-cells 0 4) (list +glyph-id-hash+ (sdl:color :r 139 :g 69 :b 19) sdl:*black*)))
(when (find :e (second barricade-feat))
(setf (aref displayed-cells 4 0) (list +glyph-id-hash+ (sdl:color :r 139 :g 69 :b 19) sdl:*black*))
(setf (aref displayed-cells 4 1) (list +glyph-id-hash+ (sdl:color :r 139 :g 69 :b 19) sdl:*black*))
(setf (aref displayed-cells 4 2) (list +glyph-id-hash+ (sdl:color :r 139 :g 69 :b 19) sdl:*black*))
(setf (aref displayed-cells 4 3) (list +glyph-id-hash+ (sdl:color :r 139 :g 69 :b 19) sdl:*black*))
(setf (aref displayed-cells 4 4) (list +glyph-id-hash+ (sdl:color :r 139 :g 69 :b 19) sdl:*black*))))
;; display rivers
(when river-feat
(when (find :n (second river-feat))
(setf (aref displayed-cells 2 0) (list +glyph-id-vertical-river+ water-color sdl:*black*))
(setf (aref displayed-cells 2 1) (list +glyph-id-vertical-river+ water-color sdl:*black*)))
(when (find :s (second river-feat))
(setf (aref displayed-cells 2 3) (list +glyph-id-vertical-river+ water-color sdl:*black*))
(setf (aref displayed-cells 2 4) (list +glyph-id-vertical-river+ water-color sdl:*black*)))
(when (find :w (second river-feat))
(setf (aref displayed-cells 0 2) (list +glyph-id-horizontal-river+ water-color sdl:*black*))
(setf (aref displayed-cells 1 2) (list +glyph-id-horizontal-river+ water-color sdl:*black*)))
(when (find :e (second river-feat))
(setf (aref displayed-cells 3 2) (list +glyph-id-horizontal-river+ water-color sdl:*black*))
(setf (aref displayed-cells 4 2) (list +glyph-id-horizontal-river+ water-color sdl:*black*))))
;; display seas for ports
(when (and sea-feat
(or (eq (wtype world-sector) :world-sector-normal-port)
(eq (wtype world-sector) :world-sector-abandoned-port)
(eq (wtype world-sector) :world-sector-corrupted-port)))
(when (find :n (second sea-feat))
(setf (aref displayed-cells 0 0) (list +glyph-id-wall+ sdl:*blue* sdl:*black*))
(setf (aref displayed-cells 1 0) (list +glyph-id-wall+ sdl:*blue* sdl:*black*))
(setf (aref displayed-cells 2 0) (list +glyph-id-wall+ sdl:*blue* sdl:*black*))
(setf (aref displayed-cells 3 0) (list +glyph-id-wall+ sdl:*blue* sdl:*black*))
(setf (aref displayed-cells 4 0) (list +glyph-id-wall+ sdl:*blue* sdl:*black*)))
(when (find :s (second sea-feat))
(setf (aref displayed-cells 0 4) (list +glyph-id-wall+ sdl:*blue* sdl:*black*))
(setf (aref displayed-cells 1 4) (list +glyph-id-wall+ sdl:*blue* sdl:*black*))
(setf (aref displayed-cells 2 4) (list +glyph-id-wall+ sdl:*blue* sdl:*black*))
(setf (aref displayed-cells 3 4) (list +glyph-id-wall+ sdl:*blue* sdl:*black*))
(setf (aref displayed-cells 4 4) (list +glyph-id-wall+ sdl:*blue* sdl:*black*)))
(when (find :w (second sea-feat))
(setf (aref displayed-cells 0 0) (list +glyph-id-wall+ sdl:*blue* sdl:*black*))
(setf (aref displayed-cells 0 1) (list +glyph-id-wall+ sdl:*blue* sdl:*black*))
(setf (aref displayed-cells 0 2) (list +glyph-id-wall+ sdl:*blue* sdl:*black*))
(setf (aref displayed-cells 0 3) (list +glyph-id-wall+ sdl:*blue* sdl:*black*))
(setf (aref displayed-cells 0 4) (list +glyph-id-wall+ sdl:*blue* sdl:*black*)))
(when (find :e (second sea-feat))
(setf (aref displayed-cells 4 0) (list +glyph-id-wall+ sdl:*blue* sdl:*black*))
(setf (aref displayed-cells 4 1) (list +glyph-id-wall+ sdl:*blue* sdl:*black*))
(setf (aref displayed-cells 4 2) (list +glyph-id-wall+ sdl:*blue* sdl:*black*))
(setf (aref displayed-cells 4 3) (list +glyph-id-wall+ sdl:*blue* sdl:*black*))
(setf (aref displayed-cells 4 4) (list +glyph-id-wall+ sdl:*blue* sdl:*black*))))
;; display lake
(when (or (eq (wtype world-sector) :world-sector-normal-lake)
(eq (wtype world-sector) :world-sector-abandoned-lake)
(eq (wtype world-sector) :world-sector-corrupted-lake))
(setf (aref displayed-cells 1 1) (list +glyph-id-wall+ water-color sdl:*black*))
(setf (aref displayed-cells 1 2) (list +glyph-id-wall+ water-color sdl:*black*))
(setf (aref displayed-cells 1 3) (list +glyph-id-wall+ water-color sdl:*black*))
(setf (aref displayed-cells 2 1) (list +glyph-id-wall+ water-color sdl:*black*))
(setf (aref displayed-cells 2 3) (list +glyph-id-wall+ water-color sdl:*black*))
(setf (aref displayed-cells 3 1) (list +glyph-id-wall+ water-color sdl:*black*))
(setf (aref displayed-cells 3 2) (list +glyph-id-wall+ water-color sdl:*black*))
(setf (aref displayed-cells 3 3) (list +glyph-id-wall+ water-color sdl:*black*)))
;; display controlled status
(cond
((= (controlled-by world-sector) +lm-controlled-by-demons+)
(progn
(setf (aref displayed-cells 1 1) (list +glyph-id-large-d+ sdl:*red* sdl:*black*))))
((= (controlled-by world-sector) +lm-controlled-by-military+)
(progn
(setf (aref displayed-cells 1 1) (list +glyph-id-large-m+ sdl:*green* sdl:*black*))))
)
;; display satanists, church, library, etc
;; do not show satanists lairs if they are hidden (the faction does not see them) and there is no mission there
(let ((feat-list (remove nil (list (if (or reveal-lair (mission world-sector))
satanists-feat
nil)
church-feat
library-feat
machine-feat
flesh-feat))))
(if (> (length feat-list) 1)
(progn
(setf (aref displayed-cells 1 3) (list +glyph-id-three-dots+ sdl:*white* sdl:*black*)))
(progn
(when (= (length feat-list) 1)
(cond
((eq (first feat-list) satanists-feat) (progn
(setf (aref displayed-cells 1 3) (list +glyph-id-sacrificial-circle+ sdl:*magenta* sdl:*black*))))
((eq (first feat-list) church-feat) (progn
(setf (aref displayed-cells 1 3) (list +glyph-id-church+ sdl:*white* sdl:*black*))))
((eq (first feat-list) library-feat) (progn
(setf (aref displayed-cells 1 3) (list +glyph-id-book+ sdl:*white* sdl:*black*))))
((eq (first feat-list) machine-feat) (progn
(setf (aref displayed-cells 1 3) (list +glyph-id-machine+ sdl:*white* sdl:*black*))))
((eq (first feat-list) flesh-feat) (progn
(setf (aref displayed-cells 1 3) (list +glyph-id-percent+ sdl:*magenta* sdl:*black*))))))))
)
(setf (aref displayed-cells 2 2) (list (glyph-idx (get-world-sector-type-by-id (wtype world-sector)))
(glyph-color (get-world-sector-type-by-id (wtype world-sector)))
sdl:*black*))
;; display items
(cond
((> (length (items world-sector)) 1) (progn
(setf (aref displayed-cells 3 3) (list +glyph-id-three-dots+ sdl:*white* sdl:*black*))))
((= (length (items world-sector)) 1) (cond
((= (first (items world-sector)) +lm-item-holy-relic+)
(setf (aref displayed-cells 3 3) (list +glyph-id-christ-cross+ sdl:*cyan* sdl:*black*)))
((= (first (items world-sector)) +lm-item-book-of-rituals+)
(setf (aref displayed-cells 3 3) (list +glyph-id-book+ sdl:*magenta* sdl:*black*)))
(t (setf (aref displayed-cells 3 3) (list +glyph-id-exclamation-mark+ sdl:*yellow* sdl:*black*))))))
;; display available mission
(when (mission world-sector)
(if (eq world-sector (world-sector (mission world-sector)))
(setf (aref displayed-cells 3 1) (list +glyph-id-crossed-swords+ sdl:*yellow* sdl:*black*))
(setf (aref displayed-cells 3 1) (list +glyph-id-portal+ (sdl:color :r 255 :g 75 :b 0) sdl:*black*))))
(loop for dy from 0 below max-disp-h do
(loop for dx from 0 below max-disp-w do
(draw-glyph (+ scr-x (* dx *glyph-w*)) (+ scr-y (* dy *glyph-h*)) (first (aref displayed-cells dx dy))
:front-color (second (aref displayed-cells dx dy))
:back-color (third (aref displayed-cells dx dy)))))
))
(defun draw-world-map (world-map scr-x scr-y &key (reveal-lairs nil))
(let ((*random-state* (make-random-state (world-map/random-state world-map))))
(loop with max-disp-w = 5
with max-disp-h = 5
for y from 0 below *max-y-world-map* do
(loop for x from 0 below *max-y-world-map*
for x1 = (+ scr-x (* x *glyph-w* max-disp-w))
for y1 = (+ scr-y (* y *glyph-h* max-disp-h))
for sector = (aref (cells world-map) x y)
do
(draw-world-map-cell sector x1 y1 :reveal-lair reveal-lairs))))
)
(defun window-use-item (item success-return-win)
(cond
((map-select-func item)
(progn
(setf *current-window* (make-instance 'map-select-window
:return-to *current-window*
:start-map-select (start-map-select-func item)
:cmd-str (list "[Enter] Use "
"")
:exec-func #'(lambda ()
(if (funcall (map-select-func item)
item)
(progn
(setf *current-window* success-return-win)
(make-output *current-window*)
t)
(progn
nil)))))
(make-output *current-window*)
(run-window *current-window*)))
(t
(progn
(clear-message-list (level/small-message-box (level *world*)))
(mob-use-item *player* nil item)
(setf *current-window* success-return-win)
(make-output *current-window*)
t))))
| 55,681
|
Common Lisp
|
.lisp
| 815
| 50.03681
| 198
| 0.513947
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
447861e97dccb4ea49a3d860e29538a08ecbef685297981af46feeadaa84279e
| 2,932
|
[
-1
] |
2,933
|
window-help.lisp
|
gwathlobal_CotD/src/windows/window-help.lisp
|
(in-package :cotd)
(defconstant +win-help-page-menu+ 0)
(defconstant +win-help-page-overview+ 1)
(defconstant +win-help-page-concepts-combat+ 2)
(defconstant +win-help-page-concepts-environment+ 3)
(defconstant +win-help-page-concepts-gods+ 4)
(defconstant +win-help-page-keybindings+ 5)
(defconstant +win-help-page-credits+ 6)
;; It is required for the help to be displayed correctly (without double newlines), that the help txt files are saved with Unix-style endlines
;; By default when cloning a repository from Github to Windows in creates txt files with Windows-style endlines
(defclass help-window (window)
((cur-page :initform +win-help-page-menu+ :accessor cur-page)
(cur-str :initform 0 :accessor cur-str)
(cur-sel :initform 0 :accessor cur-sel)
(menu-items :initform (list "Overview"
"Concepts: Combat"
"Concepts: Environment"
"Concepts: Gods"
"Keybindings"
"Credits")
:accessor menu-items)
(help-txt :initform (populate-txt-from-filelist (list "help/overview.txt"
"help/concept_combat.txt"
"help/concept_environment.txt"
"help/concept_gods.txt"
"help/keybindings.txt"
"help/credits.txt"))
:accessor help-txt)
))
(defun show-help-text (win txt-n)
(let ((str (nth txt-n (help-txt win)))
(max-str))
(sdl:with-rectangle (rect (sdl:rectangle :x 10 :y 20 :w (- *window-width* 20) :h (- *window-height* 20 30 (sdl:char-height sdl:*default-font*))))
;; calculate the maximum number of lines
(setf max-str (write-text str rect :count-only t))
(when (< max-str (+ (cur-str win) (truncate (sdl:height rect) (sdl:char-height sdl:*default-font*))))
(setf (cur-str win) (- max-str (truncate (sdl:height rect) (sdl:char-height sdl:*default-font*)))))
(when (< (cur-str win) 0)
(setf (cur-str win) 0))
(write-text str rect :start-line (cur-str win))
(sdl:draw-string-solid-* (format nil "~A[Esc] Exit" (if (> max-str (truncate (sdl:height rect) (sdl:char-height sdl:*default-font*)))
"[Shift+Up/Down] Page Up/Down [Up/Down] Scroll text "
""))
10 (- *window-height* 10 (sdl:char-height sdl:*default-font*)))
)))
(defmethod make-output ((win help-window))
(sdl:with-rectangle (a-rect (sdl:rectangle :x 0 :y 0 :w *window-width* :h *window-height*))
(sdl:fill-surface sdl:*black* :template a-rect))
(cond
;; draw overview page
((= (cur-page win) +win-help-page-overview+)
(sdl:draw-string-solid-* "OVERVIEW" (truncate *window-width* 2) 0 :justify :center)
(show-help-text win +win-help-page-overview+))
;; draw combat page
((= (cur-page win) +win-help-page-concepts-combat+)
(sdl:draw-string-solid-* "CONCEPTS: COMBAT" (truncate *window-width* 2) 0 :justify :center)
(show-help-text win +win-help-page-concepts-combat+))
;; draw environment page
((= (cur-page win) +win-help-page-concepts-environment+)
(sdl:draw-string-solid-* "CONCEPTS: ENVIRONMENT" (truncate *window-width* 2) 0 :justify :center)
(show-help-text win +win-help-page-concepts-environment+))
;; draw gods page
((= (cur-page win) +win-help-page-concepts-gods+)
(sdl:draw-string-solid-* "CONCEPTS: GODS" (truncate *window-width* 2) 0 :justify :center)
(show-help-text win +win-help-page-concepts-gods+))
;; draw keybindings page
((= (cur-page win) +win-help-page-keybindings+)
(sdl:draw-string-solid-* "KEYBINDINGS" (truncate *window-width* 2) 0 :justify :center)
(show-help-text win +win-help-page-keybindings+))
;; draw credits page
((= (cur-page win) +win-help-page-credits+)
(sdl:draw-string-solid-* "CREDITS" (truncate *window-width* 2) 0 :justify :center)
(show-help-text win +win-help-page-credits+))
(t ;; draw the menu
(sdl:draw-string-solid-* "HELP" (truncate *window-width* 2) 0 :justify :center)
(let ((cur-str) (color-list nil))
(setf cur-str (cur-sel win))
(dotimes (i (length (menu-items win)))
(if (= i cur-str)
(setf color-list (append color-list (list sdl:*yellow*)))
(setf color-list (append color-list (list sdl:*white*)))))
(draw-selection-list (menu-items win) cur-str (length (menu-items win)) 20 (+ 10 10) :color-list color-list :use-letters t))
(sdl:draw-string-solid-* (format nil "[Enter] Select [Up/Down] Move selection [Shift+Up/Down] Scroll page [Esc] Exit")
10 (- *window-height* 10 (sdl:char-height sdl:*default-font*))))
)
(sdl:update-display))
(defmethod run-window ((win help-window))
(sdl:with-events ()
(:quit-event () (funcall (quit-func win)) t)
(:key-down-event (:key key :mod mod :unicode unicode)
;; normalize mod
(loop while (>= mod sdl-key-mod-num) do
(decf mod sdl-key-mod-num))
(when (= (cur-page win) +win-help-page-menu+)
(setf (cur-sel win) (run-selection-list key mod unicode (cur-sel win) :start-page (truncate (cur-sel win) (length (menu-items win))) :max-str-per-page (length (menu-items win))))
(setf (cur-sel win) (adjust-selection-list (cur-sel win) (length (menu-items win)))))
(cond
((and (or (sdl:key= key :sdl-key-up) (sdl:key= key :sdl-key-kp8)) (= mod 0))
(when (or (= (cur-page win) +win-help-page-overview+)
(= (cur-page win) +win-help-page-concepts-combat+)
(= (cur-page win) +win-help-page-concepts-environment+)
(= (cur-page win) +win-help-page-concepts-gods+)
(= (cur-page win) +win-help-page-keybindings+)
(= (cur-page win) +win-help-page-credits+))
(decf (cur-str win))))
((and (or (sdl:key= key :sdl-key-up) (sdl:key= key :sdl-key-kp8)) (/= (logand mod sdl-cffi::sdl-key-mod-shift) 0))
(when (or (= (cur-page win) +win-help-page-overview+)
(= (cur-page win) +win-help-page-concepts-combat+)
(= (cur-page win) +win-help-page-concepts-environment+)
(= (cur-page win) +win-help-page-concepts-gods+)
(= (cur-page win) +win-help-page-keybindings+)
(= (cur-page win) +win-help-page-credits+))
(decf (cur-str win) 30)))
((and (or (sdl:key= key :sdl-key-down) (sdl:key= key :sdl-key-kp2)) (/= (logand mod sdl-cffi::sdl-key-mod-shift) 0))
(when (or (= (cur-page win) +win-help-page-overview+)
(= (cur-page win) +win-help-page-concepts-combat+)
(= (cur-page win) +win-help-page-concepts-environment+)
(= (cur-page win) +win-help-page-concepts-gods+)
(= (cur-page win) +win-help-page-keybindings+)
(= (cur-page win) +win-help-page-credits+))
(incf (cur-str win) 30)))
((and (or (sdl:key= key :sdl-key-down) (sdl:key= key :sdl-key-kp2)) (= mod 0))
(when (or (= (cur-page win) +win-help-page-overview+)
(= (cur-page win) +win-help-page-concepts-combat+)
(= (cur-page win) +win-help-page-concepts-environment+)
(= (cur-page win) +win-help-page-concepts-gods+)
(= (cur-page win) +win-help-page-keybindings+)
(= (cur-page win) +win-help-page-credits+))
(incf (cur-str win))))
;; escape - quit
((sdl:key= key :sdl-key-escape)
(if (= (cur-page win) +win-help-page-menu+)
(progn
(setf *current-window* (return-to win)) (make-output *current-window*) (return-from run-window nil))
(progn
(setf (cur-page win) +win-help-page-menu+))))
;; enter - select
((or (sdl:key= key :sdl-key-return) (sdl:key= key :sdl-key-kp-enter))
(when (= (cur-page win) +win-help-page-menu+)
(setf (cur-str win) 0)
(setf (cur-page win) (1+ (cur-sel win))))
))
(make-output *current-window*))
(:video-expose-event () (make-output *current-window*))))
| 9,615
|
Common Lisp
|
.lisp
| 144
| 47.1875
| 202
| 0.509881
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
2b42018606a3a0db67c2d34793b084f0b19cc21f65bd4d9d4bf1bd0857eb2a05
| 2,933
|
[
-1
] |
2,934
|
init-lvl-mod-weather.lisp
|
gwathlobal_CotD/src/level-modifiers/init-lvl-mod-weather.lisp
|
(in-package :cotd)
;;---------------------------------
;; Weather level modifiers
;;---------------------------------
(set-level-modifier :id +lm-weather-rain+ :type :level-mod-weather
:name "Rain"
:is-available-for-mission #'(lambda (world-sector-type-id mission-type-id world-time)
(declare (ignore mission-type-id))
(multiple-value-bind (year month day hour min sec) (get-current-date-time world-time)
(declare (ignore year day hour min sec))
(if (and (not (eq world-sector-type-id :world-sector-hell-jungle))
(and (> month 1) (< month 11)))
t
nil))
)
:random-available-for-mission #'(lambda ()
(if (< (random 100) 25)
t
nil))
:overall-post-process-func-list #'(lambda ()
(let ((func-list ()))
(push #'(lambda (level world-sector mission world)
(declare (ignore world-sector mission world))
(log:info "OVERALL-POST-PROCESS-FUNC: Add rain weather")
(pushnew +game-event-rain-falls+ (game-events level))
)
func-list)
func-list)))
(set-level-modifier :id +lm-weather-acid-rain+ :type :level-mod-weather
:name "Acid rain"
:is-available-for-mission #'(lambda (world-sector-type-id mission-type-id world-time)
(declare (ignore mission-type-id world-time))
(if (and (eq world-sector-type-id :world-sector-hell-jungle))
t
nil)
)
:random-available-for-mission #'(lambda ()
(if (< (random 100) 25)
t
nil))
:overall-post-process-func-list #'(lambda ()
(let ((func-list ()))
(push #'(lambda (level world-sector mission world)
(declare (ignore world-sector mission world))
(log:info "OVERALL-POST-PROCESS-FUNC: Add poison rain weather")
(pushnew +game-event-acid-falls+ (game-events level))
)
func-list)
func-list)))
(set-level-modifier :id +lm-weather-snow+ :type :level-mod-weather
:name "Snow"
:is-available-for-mission #'(lambda (world-sector-type-id mission-type-id world-time)
(declare (ignore mission-type-id))
(multiple-value-bind (year month day hour min sec) (get-current-date-time world-time)
(declare (ignore year day hour min sec))
(if (and (not (eq world-sector-type-id :world-sector-hell-jungle))
(or (= month 11) (= month 0) (= month 1)))
t
nil)))
:terrain-post-process-func-list (lambda ()
(let ((func-list ()))
(push #'change-level-to-snow func-list)
func-list))
:overall-post-process-func-list #'(lambda ()
(let ((func-list ()))
(push #'(lambda (level world-sector mission world)
(declare (ignore world-sector mission world))
(log:info "OVERALL-POST-PROCESS-FUNC: Add snow weather")
(pushnew +game-event-snow-falls+ (game-events level))
)
func-list)
func-list)))
| 6,239
|
Common Lisp
|
.lisp
| 72
| 33.333333
| 135
| 0.299895
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
5b05f3f2a3cf04904ea0bd2e673ee4b08b067692d66f8d128067ab7bf6bb66dd
| 2,934
|
[
-1
] |
2,935
|
init-lvl-mod-controlled-by.lisp
|
gwathlobal_CotD/src/level-modifiers/init-lvl-mod-controlled-by.lisp
|
(in-package :cotd)
;;---------------------------------
;; Controlled By level modifiers
;;---------------------------------
(set-level-modifier :id +lm-controlled-by-none+ :type :level-mod-controlled-by
:name "Uncontrolled"
:priority 25
:is-available-for-mission #'(lambda (world-sector-type-id mission-type-id world-time)
(declare (ignore mission-type-id world-time))
;; is not available for world sectors in hell
(if (world-sector-hell-p (get-world-sector-type-by-id world-sector-type-id))
nil
t)))
(set-level-modifier :id +lm-controlled-by-demons+ :type :level-mod-controlled-by
:name "Controlled by demons"
:faction-list-func #'(lambda (sector-type-id)
(declare (ignore sector-type-id))
(list (list +faction-type-demons+ :mission-faction-present)))
:priority 25
:overall-post-process-func-list #'(lambda ()
(let ((func-list ()))
;; add starting points for demons
(push #'(lambda (level world-sector mission world)
(declare (ignore world-sector world mission))
(log:info "OVERALL-POST-PROCESS-FUNC: Add starting points for demons")
(loop repeat 50
do
(loop with max-x = (array-dimension (terrain level) 0)
with max-y = (array-dimension (terrain level) 1)
for x = (random max-x)
for y = (random max-y)
for z = 2
until (and (and (> x 10) (< x (- max-x 10)) (> y 10) (< y (- max-y 10)))
(not (get-terrain-type-trait (get-terrain-* (level *world*) x y z) +terrain-trait-blocks-move+))
(not (get-mob-* level x y z))
(get-terrain-type-trait (get-terrain-* level x y z) +terrain-trait-blocks-move-floor+)
(/= (get-level-connect-map-value level x y z 1 +connect-map-move-walk+)
+connect-room-none+)
(loop for feature-id in (feature-id-list level)
for feature = (get-feature-by-id feature-id)
with result = t
when (and (= (feature-type feature) +feature-start-repel-demons+)
(< (get-distance x y (x feature) (y feature)) *repel-demons-dist*))
do
(setf result nil)
(loop-finish)
when (and (= (feature-type feature) +feature-start-strong-repel-demons+)
(< (get-distance x y (x feature) (y feature)) *repel-demons-dist-strong*))
do
(setf result nil)
(loop-finish)
when (and (get-feature-type-trait feature +feature-trait-remove-on-dungeon-generation+)
(< (get-distance x y (x feature) (y feature)) 2))
do
(setf result nil)
(loop-finish)
finally (return result)))
finally (add-feature-to-level-list level (make-instance 'feature :feature-type +feature-start-place-demons+ :x x :y y :z z))
))
)
func-list)
func-list))
:is-available-for-mission #'(lambda (world-sector-type-id mission-type-id world-time)
(declare (ignore mission-type-id world-time))
;; is not available for missions where demons attack
(if (or (world-sector-corrupted-p (get-world-sector-type-by-id world-sector-type-id))
(world-sector-hell-p (get-world-sector-type-by-id world-sector-type-id)))
t
nil)
)
:always-present-func #'(lambda (world-sector mission world-time)
(declare (ignore mission world-time))
(if (world-sector-hell-p world-sector)
t
nil))
)
(set-level-modifier :id +lm-controlled-by-military+ :type :level-mod-controlled-by
:name "Controlled by the military"
:faction-list-func #'(lambda (sector-type-id)
(declare (ignore sector-type-id))
(list (list +faction-type-military+ :mission-faction-present)))
:priority 25
:template-level-gen-func #'(lambda (template-level world-sector mission world)
(declare (ignore world-sector mission world))
(log:info "TEMPLATE LEVEL FUNC: LM CONTROLLED BY MILITARY")
(let ((building-id +building-city-army-post+)
(x-w 4)
(y-n 4)
(x-e (- (array-dimension template-level 0) 5))
(y-s (- (array-dimension template-level 1) 5)))
;; place nw post
(level-city-reserve-build-on-grid building-id x-w y-n 2 template-level)
;; place ne post
(level-city-reserve-build-on-grid building-id x-e y-n 2 template-level)
;; place sw post
(level-city-reserve-build-on-grid building-id x-w y-s 2 template-level)
;; place se post
(level-city-reserve-build-on-grid building-id x-e y-s 2 template-level)
)
)
:is-available-for-mission #'(lambda (world-sector-type-id mission-type-id world-time)
(declare (ignore mission-type-id world-time))
;; is not available for missions where military attack
(if (world-sector-normal-p (get-world-sector-type-by-id world-sector-type-id))
t
nil))
)
| 10,765
|
Common Lisp
|
.lisp
| 107
| 37.934579
| 204
| 0.292671
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
a6ceaee33ecd002334237bf8f8fda329f8545e469e2091b82ac9f50e47083c2e
| 2,935
|
[
-1
] |
2,936
|
level-modifier.lisp
|
gwathlobal_CotD/src/level-modifiers/level-modifier.lisp
|
(in-package :cotd)
;;---------------------------------
;; LEVEL-MOD-TYPE Constants
;;---------------------------------
(defenum:defenum level-mod-type-enum (:level-mod-controlled-by
:level-mod-sector-feat
:level-mod-sector-item
:level-mod-tod
:level-mod-weather
:level-mod-player-placement
:level-mod-misc))
(defconstant +level-mod-controlled-by+ 0)
(defconstant +level-mod-sector-feat+ 1)
(defconstant +level-mod-sector-item+ 2)
(defconstant +level-mod-time-of-day+ 3)
(defconstant +level-mod-weather+ 4)
(defconstant +level-mod-player-placement+ 5)
(defconstant +level-mod-misc+ 6)
;;---------------------------------
;; LEVEL-MODIFIER Constants
;;---------------------------------
(defconstant +lm-controlled-by-none+ 0)
(defconstant +lm-controlled-by-demons+ 1)
(defconstant +lm-controlled-by-military+ 2)
(defconstant +lm-feat-river+ 3)
(defconstant +lm-feat-sea+ 4)
(defconstant +lm-feat-barricade+ 5)
(defconstant +lm-feat-library+ 6)
(defconstant +lm-feat-church+ 7)
(defconstant +lm-feat-lair+ 8)
(defconstant +lm-item-book-of-rituals+ 9)
(defconstant +lm-item-holy-relic+ 10)
(defconstant +lm-tod-morning+ 11)
(defconstant +lm-tod-noon+ 12)
(defconstant +lm-tod-evening+ 13)
(defconstant +lm-tod-night+ 14)
(defconstant +lm-weather-rain+ 15)
(defconstant +lm-weather-snow+ 16)
(defconstant +lm-placement-player+ 17)
(defconstant +lm-placement-dead-player+ 18)
(defconstant +lm-placement-angel-chrome+ 19)
(defconstant +lm-placement-angel-trinity+ 20)
(defconstant +lm-placement-demon-crimson+ 21)
(defconstant +lm-placement-demon-shadow+ 22)
(defconstant +lm-placement-demon-malseraph+ 23)
(defconstant +lm-placement-military-chaplain+ 24)
(defconstant +lm-placement-military-scout+ 25)
(defconstant +lm-placement-priest+ 26)
(defconstant +lm-placement-satanist+ 27)
(defconstant +lm-placement-eater+ 28)
(defconstant +lm-placement-skinchanger+ 29)
(defconstant +lm-placement-thief+ 30)
(defconstant +lm-placement-ghost+ 31)
(defconstant +lm-placement-test+ 32)
(defconstant +lm-tod-hell+ 33)
(defconstant +lm-feat-hell-engine+ 34)
(defconstant +lm-feat-hell-flesh-storage+ 35)
(defconstant +lm-weather-acid-rain+ 36)
(defconstant +lm-misc-eater-incursion+ 37)
(defconstant +lm-misc-malseraphs-blessing+ 38)
(defparameter *level-modifiers* (make-array (list 0) :adjustable t))
(defclass level-modifier ()
((id :initarg :id :accessor id)
(name :initarg :name :accessor name)
(priority :initform 0 :initarg :priority :accessor priority)
(lm-type :initarg :lm-type :accessor lm-type :type level-mod-type-enum)
(lm-debug :initform nil :initarg :lm-debug :accessor lm-debug :type boolean)
(disabled :initform nil :initarg :disabled :accessor disabled :type boolean)
(template-level-gen-func :initform nil :initarg :template-level-gen-func :accessor template-level-gen-func)
(overall-post-process-func-list :initform nil :initarg :overall-post-process-func-list :accessor overall-post-process-func-list)
(terrain-post-process-func-list :initform nil :initarg :terrain-post-process-func-list :accessor terrain-post-process-func-list)
(faction-list-func :initform nil :initarg :faction-list-func :accessor faction-list-func) ;; the func that takes world-sector-type and returns a list of faction-ids
(is-available-for-mission :initform nil :initarg :is-available-for-mission :accessor is-available-for-mission) ;; takes world-sector-type-id, mission-type-id and world-time
(random-available-for-mission :initform nil :initarg :random-available-for-mission :accessor random-available-for-mission)
(scenario-enabled-func :initform nil :initarg :scenario-enabled-func :accessor scenario-enabled-func)
(scenario-disabled-func :initform nil :initarg :scenario-disabled-func :accessor scenario-disabled-func)
(depends-on-lvl-mod-func :initform nil :initarg :depends-on-lvl-mod-func :accessor depends-on-lvl-mod-func) ;; takes world-sector, mission-type-id and world-time
(always-present-func :initform nil :initarg :always-present-func :accessor always-present-func) ;; takes world-sector, mission and world-time
))
(defun set-level-modifier (&key id name type debug disabled priority template-level-gen-func overall-post-process-func-list terrain-post-process-func-list faction-list-func
(is-available-for-mission #'(lambda (world-sector mission-type-id world-time)
(declare (ignore world-sector mission-type-id world-time))
t))
random-available-for-mission
scenario-enabled-func scenario-disabled-func
(depends-on-lvl-mod-func #'(lambda (world-sector mission-type-id world-time)
(declare (ignore world-sector mission-type-id world-time))
nil))
(always-present-func #'(lambda (world-sector mission world-time)
(declare (ignore world-sector mission world-time))
nil)))
(unless id (error ":ID is an obligatory parameter!"))
(unless name (error ":NAME is an obligatory parameter!"))
(unless type (error ":TYPE is an obligatory parameter!"))
(when (>= id (length *level-modifiers*))
(adjust-array *level-modifiers* (list (1+ id)) :initial-element nil))
(setf (aref *level-modifiers* id) (make-instance 'level-modifier :id id :name name :lm-type type :lm-debug debug :disabled disabled :priority priority
:template-level-gen-func template-level-gen-func
:overall-post-process-func-list overall-post-process-func-list
:terrain-post-process-func-list terrain-post-process-func-list
:faction-list-func faction-list-func
:is-available-for-mission is-available-for-mission
:random-available-for-mission random-available-for-mission
:scenario-enabled-func scenario-enabled-func
:scenario-disabled-func scenario-disabled-func
:depends-on-lvl-mod-func depends-on-lvl-mod-func
:always-present-func always-present-func)))
(defun get-level-modifier-by-id (level-modifier-id)
(aref *level-modifiers* level-modifier-id))
(defun get-all-lvl-mods-list (&key (include-disabled nil))
(loop for lvl-mod across *level-modifiers*
when (or (not include-disabled)
(and include-disabled
(disabled lvl-mod)))
collect lvl-mod))
(defun change-level-to-snow (level world-sector mission world)
(declare (ignore world-sector mission world))
(loop for x from 0 below (array-dimension (terrain level) 0) do
(loop for y from 0 below (array-dimension (terrain level) 1) do
(loop for z from (1- (array-dimension (terrain level) 2)) downto 0 do
(cond
((= (aref (terrain level) x y z) +terrain-border-floor+) (setf (aref (terrain level) x y z) +terrain-border-floor-snow+))
((= (aref (terrain level) x y z) +terrain-border-grass+) (setf (aref (terrain level) x y z) +terrain-border-floor-snow+))
((= (aref (terrain level) x y z) +terrain-floor-dirt+) (setf (aref (terrain level) x y z) +terrain-floor-snow+))
((= (aref (terrain level) x y z) +terrain-floor-dirt-bright+) (setf (aref (terrain level) x y z) +terrain-floor-snow+))
((= (aref (terrain level) x y z) +terrain-floor-grass+) (setf (aref (terrain level) x y z) +terrain-floor-snow+))
((= (aref (terrain level) x y z) +terrain-tree-birch+) (setf (aref (terrain level) x y z) +terrain-tree-birch-snow+))
((= (aref (terrain level) x y z) +terrain-water-liquid+) (progn
(setf (aref (terrain level) x y z) +terrain-wall-ice+)
(when (and (< z (1- (array-dimension (terrain level) 2)))
(= (aref (terrain level) x y (1+ z)) +terrain-floor-air+))
(setf (aref (terrain level) x y (1+ z)) +terrain-water-ice+))))
((= (aref (terrain level) x y z) +terrain-floor-leaves+) (setf (aref (terrain level) x y z) +terrain-floor-leaves-snow+))))))
)
| 9,293
|
Common Lisp
|
.lisp
| 134
| 53.813433
| 175
| 0.591799
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
f7f2a60039089560525dc916f82d6de55fa7f2d223a524b14d8af8dd560ab5a1
| 2,936
|
[
-1
] |
2,937
|
init-lvl-mod-sector-feat.lisp
|
gwathlobal_CotD/src/level-modifiers/init-lvl-mod-sector-feat.lisp
|
(in-package :cotd)
;;---------------------------------
;; Sector Feat level modifiers
;;---------------------------------
(set-level-modifier :id +lm-feat-river+ :type :level-mod-sector-feat
:priority 10
:name "River"
:template-level-gen-func #'(lambda (template-level world-sector mission world)
(declare (ignore mission world))
(log:info "TEMPLATE LEVEL FUNC: LM FEAT RIVER")
(let ((river-params (second (find +lm-feat-river+ (feats world-sector) :key #'(lambda (a) (first a))))))
(when (find :n river-params)
(loop with max-y = (1- (truncate (array-dimension template-level 1) 2))
with min-y = 0
with center-x = (truncate (array-dimension template-level 0) 2)
for y from min-y below max-y
for building-type-id = (if (and (zerop (mod (1+ y) 4))
(/= y (1- max-y)))
+building-city-bridge+
+building-city-river+)
for building-at-point-1 = (aref template-level center-x y 2)
for building-at-point-2 = (aref template-level (1- center-x) y 2)
do
(when (or (eq building-at-point-1 nil)
(eq building-at-point-1 t)
(and (listp building-at-point-1)
(/= (first building-at-point-1) +building-city-central-lake+)))
(level-city-reserve-build-on-grid building-type-id center-x y 2 template-level))
(when (or (eq building-at-point-2 nil)
(eq building-at-point-2 t)
(and (listp building-at-point-2)
(/= (first building-at-point-2) +building-city-central-lake+)))
(level-city-reserve-build-on-grid building-type-id (1- center-x) y 2 template-level))
))
(when (find :s river-params)
(loop with max-y = (array-dimension template-level 1)
with min-y = (1- (truncate (array-dimension template-level 1) 2))
with center-x = (truncate (array-dimension template-level 0) 2)
for y from (+ min-y 2) below max-y
for building-type-id = (if (and (zerop (mod (1+ (- y min-y)) 4))
(/= y (1- max-y)))
+building-city-bridge+
+building-city-river+)
for building-at-point-1 = (aref template-level center-x y 2)
for building-at-point-2 = (aref template-level (1- center-x) y 2)
do
(when (or (eq building-at-point-1 nil)
(eq building-at-point-1 t)
(and (listp building-at-point-1)
(/= (first building-at-point-1) +building-city-central-lake+)))
(level-city-reserve-build-on-grid building-type-id center-x y 2 template-level))
(when (or (eq building-at-point-2 nil)
(eq building-at-point-2 t)
(and (listp building-at-point-2)
(/= (first building-at-point-2) +building-city-central-lake+)))
(level-city-reserve-build-on-grid building-type-id (1- center-x) y 2 template-level))
))
(when (find :e river-params)
(loop with max-x = (array-dimension template-level 0)
with min-x = (1- (truncate (array-dimension template-level 0) 2))
with center-y = (truncate (array-dimension template-level 1) 2)
for x from (+ min-x 2) below max-x
for building-type-id = (if (and (zerop (mod (1+ (- x min-x)) 4))
(/= x (1- max-x)))
+building-city-bridge+
+building-city-river+)
for building-at-point-1 = (aref template-level x (1- center-y) 2)
for building-at-point-2 = (aref template-level x center-y 2)
do
(when (or (eq building-at-point-1 nil)
(eq building-at-point-1 t)
(and (listp building-at-point-1)
(/= (first building-at-point-1) +building-city-central-lake+)))
(level-city-reserve-build-on-grid building-type-id x (1- center-y) 2 template-level))
(when (or (eq building-at-point-1 nil)
(eq building-at-point-1 t)
(and (listp building-at-point-1)
(/= (first building-at-point-1) +building-city-central-lake+)))
(level-city-reserve-build-on-grid building-type-id x center-y 2 template-level))
))
(when (find :w river-params)
(loop with max-x = (1- (truncate (array-dimension template-level 0) 2))
with min-x = 0
with center-y = (truncate (array-dimension template-level 1) 2)
for x from min-x below max-x
for building-type-id = (if (and (zerop (mod (1+ x) 4))
(/= x (1- max-x)))
+building-city-bridge+
+building-city-river+)
for building-at-point-1 = (aref template-level x (1- center-y) 2)
for building-at-point-2 = (aref template-level x center-y 2)
do
(when (or (eq building-at-point-1 nil)
(eq building-at-point-1 t)
(and (listp building-at-point-1)
(/= (first building-at-point-1) +building-city-central-lake+)))
(level-city-reserve-build-on-grid building-type-id x (1- center-y) 2 template-level))
(when (or (eq building-at-point-1 nil)
(eq building-at-point-1 t)
(and (listp building-at-point-1)
(/= (first building-at-point-1) +building-city-central-lake+)))
(level-city-reserve-build-on-grid building-type-id x center-y 2 template-level))
))
(let ((x (1- (truncate (array-dimension template-level 0) 2)))
(y (1- (truncate (array-dimension template-level 1) 2))))
(loop for off-x from 0 to 1 do
(loop for off-y from 0 to 1
for building-at-point = (aref template-level (+ x off-x) (+ y off-y) 2)
do
(when (or (eq building-at-point nil)
(eq building-at-point t)
(and (listp building-at-point)
(/= (first building-at-point) +building-city-central-lake+)))
(level-city-reserve-build-on-grid +building-city-river+ (+ x off-x) (+ y off-y) 2 template-level))
))
)
))
:is-available-for-mission #'(lambda (world-sector-type-id mission-type-id world-time)
(declare (ignore mission-type-id world-time))
;; is not available for islands
(if (or (eq world-sector-type-id :world-sector-normal-island)
(eq world-sector-type-id :world-sector-abandoned-island)
(eq world-sector-type-id :world-sector-corrupted-island)
(world-sector-hell-p (get-world-sector-type-by-id world-sector-type-id)))
nil
t))
:scenario-disabled-func #'(lambda (world-map x y)
;; remove all surrounding rivers (if any)
(setf (feats (aref (cells world-map) x (1- y))) (remove +lm-feat-river+ (feats (aref (cells world-map) x (1- y))) :key #'(lambda (a) (first a))))
(setf (feats (aref (cells world-map) x (1+ y))) (remove +lm-feat-river+ (feats (aref (cells world-map) x (1+ y))) :key #'(lambda (a) (first a))))
(setf (feats (aref (cells world-map) (1- x) y)) (remove +lm-feat-river+ (feats (aref (cells world-map) (1- x) y)) :key #'(lambda (a) (first a))))
(setf (feats (aref (cells world-map) (1+ x) y)) (remove +lm-feat-river+ (feats (aref (cells world-map) (1+ x) y)) :key #'(lambda (a) (first a)))))
:scenario-enabled-func #'(lambda (world-map x y)
(let ((river-list ()))
;; choose random sides where to add a river
(when (zerop (random 4))
(push :n river-list))
(when (zerop (random 4))
(push :s river-list))
(when (zerop (random 4))
(push :w river-list))
(when (zerop (random 4))
(push :e river-list))
(unless river-list
(push (nth (random 4) '(:n :s :e :w))
river-list))
;; add rivers to the chosen sides
(loop for side in river-list
when (eq side :n) do
(push (list +lm-feat-river+ nil) (feats (aref (cells world-map) x (1- y))))
when (eq side :s) do
(push (list +lm-feat-river+ nil) (feats (aref (cells world-map) x (1+ y))))
when (eq side :w) do
(push (list +lm-feat-river+ nil) (feats (aref (cells world-map) (1- x) y)))
when (eq side :e) do
(push (list +lm-feat-river+ nil) (feats (aref (cells world-map) (1+ x) y))))
)))
(set-level-modifier :id +lm-feat-sea+ :type :level-mod-sector-feat
:name "Pier"
:priority 0
:is-available-for-mission #'(lambda (world-sector-type-id mission-type-id world-time)
(declare (ignore mission-type-id world-time))
;; is not available for everybody other than seaports
(if (or (eq world-sector-type-id :world-sector-normal-port)
(eq world-sector-type-id :world-sector-abandoned-port)
(eq world-sector-type-id :world-sector-corrupted-port))
t
nil))
:always-present-func #'(lambda (world-sector mission world-time)
(declare (ignore mission world-time))
(if (or (eq (wtype world-sector) :world-sector-normal-port)
(eq (wtype world-sector) :world-sector-abandoned-port)
(eq (wtype world-sector) :world-sector-corrupted-port))
t
nil)))
(set-level-modifier :id +lm-feat-barricade+ :type :level-mod-sector-feat
:name "Barricade"
:priority 20
:template-level-gen-func #'(lambda (template-level world-sector mission world)
(declare (ignore mission world))
(log:info "TEMPLATE LEVEL FUNC: LM FEAT BARRICADE")
(let ((x1 1)
(x2 (- (array-dimension template-level 0) 2))
(y1 1)
(y2 (- (array-dimension template-level 1) 2))
(barricade-params (second (find +lm-feat-barricade+ (feats world-sector) :key #'(lambda (a) (first a))))))
(flet ((place-barricade (barricade-build-id x y)
(when (or (null (aref template-level x y 2))
(/= (first (aref template-level x y 2)) +building-city-sea+))
(level-city-reserve-build-on-grid barricade-build-id x y 2 template-level))))
;; set up barricade lines & entrances
(when (find :n barricade-params)
(loop with center-x = (truncate (array-dimension template-level 0) 2)
for x from x1 below (- center-x 2)
do
(place-barricade +building-city-barricade-we+ x y1))
(loop with center-x = (truncate (array-dimension template-level 0) 2)
for x from (+ center-x 2) to x2
do
(place-barricade +building-city-barricade-we+ x y1))
(loop with center-x = (truncate (array-dimension template-level 0) 2)
for off-x from -2 below 2
when (eq (aref template-level (+ center-x off-x) y1 2) nil)
do
(setf (aref template-level (+ center-x off-x) y1 2) t)))
(when (find :s barricade-params)
(loop with center-x = (truncate (array-dimension template-level 0) 2)
for x from x1 below (- center-x 2)
do
(place-barricade +building-city-barricade-we+ x y2))
(loop with center-x = (truncate (array-dimension template-level 0) 2)
for x from (+ center-x 2) to x2
do
(place-barricade +building-city-barricade-we+ x y2))
(loop with center-x = (truncate (array-dimension template-level 0) 2)
for off-x from -2 below 2
when (eq (aref template-level (+ center-x off-x) y2 2) nil)
do
(setf (aref template-level (+ center-x off-x) y2 2) t)))
(when (find :w barricade-params)
(loop with center-y = (truncate (array-dimension template-level 1) 2)
for y from y1 below (- center-y 2)
do
(place-barricade +building-city-barricade-ns+ x1 y))
(loop with center-y = (truncate (array-dimension template-level 1) 2)
for y from (+ center-y 2) to y2
do
(place-barricade +building-city-barricade-ns+ x1 y))
(loop with center-y = (truncate (array-dimension template-level 1) 2)
for off-y from -2 below 2
when (eq (aref template-level x1 (+ center-y off-y) 2) nil)
do
(setf (aref template-level x1 (+ center-y off-y) 2) t)))
(when (find :e barricade-params)
(loop with center-y = (truncate (array-dimension template-level 1) 2)
for y from y1 below (- center-y 2)
do
(place-barricade +building-city-barricade-ns+ x2 y))
(loop with center-y = (truncate (array-dimension template-level 1) 2)
for y from (+ center-y 2) to y2
do
(place-barricade +building-city-barricade-ns+ x2 y))
(loop with center-y = (truncate (array-dimension template-level 1) 2)
for off-y from -2 below 2
when (eq (aref template-level x2 (+ center-y off-y) 2) nil)
do
(setf (aref template-level x2 (+ center-y off-y) 2) t)))
;; set up barricade corners
(when (and (find :n barricade-params)
(find :w barricade-params))
(place-barricade +building-city-barricade-se+ x1 y1))
(when (and (find :n barricade-params)
(find :e barricade-params))
(place-barricade +building-city-barricade-sw+ x2 y1))
(when (and (find :s barricade-params)
(find :w barricade-params))
(place-barricade +building-city-barricade-ne+ x1 y2))
(when (and (find :s barricade-params)
(find :e barricade-params))
(place-barricade +building-city-barricade-nw+ x2 y2))
)))
:is-available-for-mission #'(lambda (world-sector-type-id mission-type-id world-time)
(declare (ignore mission-type-id world-time))
;; is not available for islands & corrupted & abandoned districts
(if (and (world-sector-normal-p (get-world-sector-type-by-id world-sector-type-id))
(not (eq world-sector-type-id :world-sector-normal-island)))
t
nil))
:scenario-disabled-func #'(lambda (world-map x y)
(when (= (controlled-by (aref (cells world-map) x (1- y))) +lm-controlled-by-demons+)
(setf (controlled-by (aref (cells world-map) x (1- y))) +lm-controlled-by-none+))
(when (= (controlled-by (aref (cells world-map) x (1+ y))) +lm-controlled-by-demons+)
(setf (controlled-by (aref (cells world-map) x (1+ y))) +lm-controlled-by-none+))
(when (= (controlled-by (aref (cells world-map) (1- x) y)) +lm-controlled-by-demons+)
(setf (controlled-by (aref (cells world-map) (1- x) y)) +lm-controlled-by-none+))
(when (= (controlled-by (aref (cells world-map) (1+ x) y)) +lm-controlled-by-demons+)
(setf (controlled-by (aref (cells world-map) (1+ x) y)) +lm-controlled-by-none+)))
:scenario-enabled-func #'(lambda (world-map x y)
(let ((demon-list ())
(side-list (list :n :s :w :e)))
;; remove a side where the sea or island is
(loop for (side dx dy) in '((:n 0 -1) (:s 0 1) (:w -1 0) (:e 1 0)) do
(when (or (eq (wtype (aref (cells world-map) (+ x dx) (+ y dy))) :world-sector-normal-sea)
(eq (wtype (aref (cells world-map) (+ x dx) (+ y dy))) :world-sector-normal-island)
(eq (wtype (aref (cells world-map) (+ x dx) (+ y dy))) :world-sector-abandoned-island)
(eq (wtype (aref (cells world-map) (+ x dx) (+ y dy))) :world-sector-corrupted-island))
(setf side-list (remove side side-list))))
;; choose random sides where to add a controlled by demons lvl-mod
(loop repeat 4
when (zerop (random 2))
do
(pushnew (nth (random (length side-list)) side-list) demon-list)
finally
(when (null demon-list)
(pushnew (nth (random (length side-list)) side-list) demon-list)))
;; add controlled by demon lvl-mod to the chosen sides
(loop for side in demon-list
when (eq side :n) do
(setf (controlled-by (aref (cells world-map) x (1- y))) +lm-controlled-by-demons+)
when (eq side :s) do
(setf (controlled-by (aref (cells world-map) x (1+ y))) +lm-controlled-by-demons+)
when (eq side :w) do
(setf (controlled-by (aref (cells world-map) (1- x) y)) +lm-controlled-by-demons+)
when (eq side :e) do
(setf (controlled-by (aref (cells world-map) (1+ x) y)) +lm-controlled-by-demons+))
)))
(set-level-modifier :id +lm-feat-library+ :type :level-mod-sector-feat
:name "Library"
:priority 30
:template-level-gen-func #'(lambda (template-level world-sector mission world)
(declare (ignore mission world))
(log:info "TEMPLATE LEVEL FUNC: LM FEAT LIBRARY")
(loop with library-types = (prepare-spec-build-id-list (cond
((world-sector-normal-p world-sector)
+building-type-library+)
((world-sector-abandoned-p world-sector)
+building-type-ruined-library+)
((world-sector-corrupted-p world-sector)
+building-type-corrupted-library+)))
for x = (random (array-dimension template-level 0))
for y = (random (array-dimension template-level 1))
for selected-library-type = (nth (random (length library-types)) library-types)
until (level-city-can-place-build-on-grid selected-library-type x y 2 template-level)
finally
(level-city-reserve-build-on-grid selected-library-type x y 2 template-level))
)
:is-available-for-mission #'(lambda (world-sector-type-id mission-type-id world-time)
(declare (ignore mission-type-id world-time))
;; is not available for hell districts
(if (world-sector-hell-p (get-world-sector-type-by-id world-sector-type-id))
nil
t)))
(set-level-modifier :id +lm-feat-church+ :type :level-mod-sector-feat
:name "Church"
:priority 30
:faction-list-func #'(lambda (sector-type-id)
(if (world-sector-normal-p (get-world-sector-type-by-id sector-type-id))
(list (list +faction-type-church+ :mission-faction-present))
nil)
)
:template-level-gen-func #'(lambda (template-level world-sector mission world)
(declare (ignore world-sector mission world))
(log:info "TEMPLATE LEVEL FUNC: Lvl Mod Church")
(loop with church-types = (prepare-spec-build-id-list +building-type-church+)
for x = (random (array-dimension template-level 0))
for y = (random (array-dimension template-level 1))
for selected-church-type = (nth (random (length church-types)) church-types)
until (level-city-can-place-build-on-grid selected-church-type x y 2 template-level)
finally
(level-city-reserve-build-on-grid selected-church-type x y 2 template-level))
)
:overall-post-process-func-list #'(lambda ()
(let ((func-list ()))
;; add priests if they are available
(push #'(lambda (level world-sector mission world)
(declare (ignore world-sector world))
(log:info "OVERALL-POST-PROCESS-FUNC: Add priests")
(loop with church-present = nil
for (faction-type faction-presence) in (faction-list mission)
when (and (= faction-type +faction-type-church+)
(eq faction-presence :mission-faction-present))
do
(setf church-present t)
finally
(unless church-present (return))
;; find all church start points and place priests there
(loop for feature-id in (feature-id-list level)
for lvl-feature = (get-feature-by-id feature-id)
for x = (x lvl-feature)
for y = (y lvl-feature)
for z = (z lvl-feature)
when (= (feature-type lvl-feature) +feature-start-place-church-priest+)
do
(add-mob-to-level-list level (make-instance 'mob :mob-type +mob-type-priest+
:x x :y y :z z)))
)
)
func-list)
func-list))
:is-available-for-mission #'(lambda (world-sector-type-id mission-type-id world-time)
(declare (ignore world-time))
;; is not available for celestial retrieval
(if (and (or (not (eq mission-type-id :mission-type-celestial-retrieval))
(and (eq mission-type-id :mission-type-celestial-retrieval)
(world-sector-abandoned-p (get-world-sector-type-by-id world-sector-type-id))))
(not (world-sector-hell-p (get-world-sector-type-by-id world-sector-type-id))))
t
nil))
)
(set-level-modifier :id +lm-feat-lair+ :type :level-mod-sector-feat
:name "Satanists' lair"
:priority 30
:faction-list-func #'(lambda (sector-type-id)
(declare (ignore sector-type-id))
(list (list +faction-type-satanists+ :mission-faction-present)))
:template-level-gen-func #'(lambda (template-level world-sector mission world)
(declare (ignore world-sector mission world))
(log:info "TEMPLATE LEVEL FUNC: LM FEAT SATANISTS LAIR")
(loop with lair-types = (prepare-spec-build-id-list +building-type-satanists+)
for x = (random (array-dimension template-level 0))
for y = (random (array-dimension template-level 1))
for selected-lair-type = (nth (random (length lair-types)) lair-types)
until (level-city-can-place-build-on-grid selected-lair-type x y 2 template-level)
finally
(level-city-reserve-build-on-grid selected-lair-type x y 2 template-level))
)
:overall-post-process-func-list #'(lambda ()
(let ((func-list ()))
;; add demonic runes
(push #'place-demonic-runes-on-level
func-list)
func-list))
:is-available-for-mission #'(lambda (world-sector-type-id mission-type-id world-time)
(declare (ignore mission-type-id world-time))
;; is not available for hell districts
(if (not (world-sector-hell-p (get-world-sector-type-by-id world-sector-type-id)))
t
nil))
:always-present-func #'(lambda (world-sector mission world-time)
(declare (ignore world-sector world-time))
(if (eq (mission-type-id mission) :mission-type-eliminate-satanists)
t
nil))
)
(set-level-modifier :id +lm-feat-hell-engine+ :type :level-mod-sector-feat
:name "Dimensional engine"
:priority 30
:faction-list-func #'(lambda (sector-type-id)
(declare (ignore sector-type-id))
nil
)
:template-level-gen-func #'(lambda (template-level world-sector mission world)
(declare (ignore world-sector mission world))
(log:info "TEMPLATE LEVEL FUNC: Lvl Mod Hell Engine")
(place-demonic-machines-on-template-level template-level)
)
:overall-post-process-func-list #'(lambda ()
(let ((func-list ()))
;; add demonic machines
(push #'place-demonic-machines-on-level
func-list)
;; add demonic sigils
(push #'place-demonic-sigils-on-level
func-list)
func-list))
:is-available-for-mission #'(lambda (world-sector-type-id mission-type-id world-time)
(declare (ignore world-time))
;; is not available for everybody other than hell jungle
(if (and (world-sector-hell-p (get-world-sector-type-by-id world-sector-type-id))
(eq mission-type-id :mission-type-celestial-sabotage))
t
nil))
:always-present-func #'(lambda (world-sector mission world-time)
(declare (ignore world-sector world-time))
(if (eq (mission-type-id mission) :mission-type-celestial-sabotage)
t
nil))
)
(set-level-modifier :id +lm-feat-hell-flesh-storage+ :type :level-mod-sector-feat
:name "Flesh storage"
:priority 30
:faction-list-func #'(lambda (sector-type-id)
(declare (ignore sector-type-id))
nil
)
:template-level-gen-func #'(lambda (template-level world-sector mission world)
(declare (ignore world-sector mission world))
(log:info "TEMPLATE LEVEL FUNC: Lvl Mod Flesh Storage")
(place-flesh-storages-on-template-level template-level)
)
:overall-post-process-func-list #'(lambda ()
(let ((func-list ()))
;; add flesh storages
(push #'place-flesh-storages-on-level
func-list)
;; add demonic sigils
(push #'place-demonic-sigils-on-level
func-list)
func-list))
:is-available-for-mission #'(lambda (world-sector-type-id mission-type-id world-time)
(declare (ignore world-time))
;; is not available for everybody other than hell jungle
(if (and (world-sector-hell-p (get-world-sector-type-by-id world-sector-type-id))
(eq mission-type-id :mission-type-military-sabotage))
t
nil))
:always-present-func #'(lambda (world-sector mission world-time)
(declare (ignore world-sector world-time))
(if (eq (mission-type-id mission) :mission-type-military-sabotage)
t
nil))
)
| 48,514
|
Common Lisp
|
.lisp
| 492
| 41.300813
| 195
| 0.316492
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
de38a5d67ebdc1142233682ed5f5546e1cfa0b54cde1d99a38abdc6f9d25eb16
| 2,937
|
[
-1
] |
2,938
|
init-lvl-mod-misc.lisp
|
gwathlobal_CotD/src/level-modifiers/init-lvl-mod-misc.lisp
|
(in-package :cotd)
(set-level-modifier :id +lm-misc-eater-incursion+ :type :level-mod-misc
:name "Primordial incursion"
:faction-list-func #'(lambda (sector-type-id)
(declare (ignore sector-type-id))
(list (list +faction-type-eater+ :mission-faction-present)))
:is-available-for-mission #'(lambda (world-sector-type-id mission-type-id world-time)
(declare (ignore world-time))
(if (and (not (world-sector-hell-p (get-world-sector-type-by-id world-sector-type-id)))
(not (eql mission-type-id :mission-type-eliminate-satanists)))
t
nil))
:random-available-for-mission #'(lambda ()
(if (< (random 100) 20)
t
nil))
:overall-post-process-func-list #'(lambda ()
(let ((func-list ()))
;; place mass eaters of the dead
(push #'place-mass-primordials-on-level
func-list)
func-list)))
(set-level-modifier :id +lm-misc-malseraphs-blessing+ :type :level-mod-misc
:name "Malseraph's blessing"
:is-available-for-mission #'(lambda (world-sector-type-id mission-type-id world-time)
(declare (ignore world-sector-type-id mission-type-id world-time))
t)
:random-available-for-mission #'(lambda ()
(if (< (random 100) 20)
t
nil))
:overall-post-process-func-list #'(lambda ()
(let ((func-list ()))
;; place mass eaters of the dead
(push #'(lambda (level world-sector mission world)
(declare (ignore world-sector mission world))
(pushnew +game-event-malseraphs-power-infusion+ (game-events level)))
func-list)
func-list)))
| 3,210
|
Common Lisp
|
.lisp
| 39
| 34.948718
| 137
| 0.333333
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
d4dc90d6d42757bc11d99001a03084b3d0b9a27754b5c7560c6780ae803a16b4
| 2,938
|
[
-1
] |
2,939
|
init-lvl-mod-sector-item.lisp
|
gwathlobal_CotD/src/level-modifiers/init-lvl-mod-sector-item.lisp
|
(in-package :cotd)
;;---------------------------------
;; Sector Item level modifiers
;;---------------------------------
(set-level-modifier :id +lm-item-book-of-rituals+ :type :level-mod-sector-item
:name "Book of Rituals"
:priority 100
:overall-post-process-func-list #'(lambda ()
(let ((func-list ()))
(push #'(lambda (level world-sector mission world)
(declare (ignore world-sector mission world))
(loop with item = nil
for feature-id in (feature-id-list level)
for lvl-feature = (get-feature-by-id feature-id)
when (= (feature-type lvl-feature) +feature-start-place-book-of-rituals+)
do
(setf item (make-instance 'item :item-type +item-type-book-of-rituals+ :x (x lvl-feature) :y (y lvl-feature) :z (z lvl-feature)))
(add-item-to-level-list level item)
(setf (level/book-id level) (id item))))
func-list)
(reverse func-list)))
:depends-on-lvl-mod-func #'(lambda (world-sector mission-type-id world-time)
(declare (ignore world-sector mission-type-id world-time))
(list +lm-feat-library+))
:is-available-for-mission #'(lambda (world-sector-type-id mission-type-id world-time)
(declare (ignore mission-type-id world-time))
;; is not available for hell districts
(if (not (world-sector-hell-p (get-world-sector-type-by-id world-sector-type-id)))
t
nil))
)
(set-level-modifier :id +lm-item-holy-relic+ :type :level-mod-sector-item
:name "Holy Relic"
:priority 100
:template-level-gen-func #'(lambda (template-level world-sector mission world)
(declare (ignore mission world))
(log:info "TEMPLATE LEVEL FUNC: Lvl Mod Relic")
(when (world-sector-corrupted-p world-sector)
(log:info " TEMPLATE LEVEL FUNC: Lvl Mod Relic in Corrupted District")
(loop with shrine-types = (prepare-spec-build-id-list +building-type-corrupted-shrine+)
for x = (random (array-dimension template-level 0))
for y = (random (array-dimension template-level 1))
for selected-shrine-type = (nth (random (length shrine-types)) shrine-types)
until (level-city-can-place-build-on-grid selected-shrine-type x y 2 template-level)
finally
(level-city-reserve-build-on-grid selected-shrine-type x y 2 template-level))
))
:overall-post-process-func-list #'(lambda ()
(let ((func-list ()))
(push #'(lambda (level world-sector mission world)
(declare (ignore world-sector mission world))
(loop with item = nil
for feature-id in (feature-id-list level)
for lvl-feature = (get-feature-by-id feature-id)
when (= (feature-type lvl-feature) +feature-start-place-relic+)
do
(setf item (make-instance 'item :item-type +item-type-church-reli—Å+ :x (x lvl-feature) :y (y lvl-feature) :z (z lvl-feature)))
(add-item-to-level-list level item)
(setf (level/relic-id level) (id item))))
func-list)
(reverse func-list)))
:depends-on-lvl-mod-func #'(lambda (world-sector mission-type-id world-time)
(declare (ignore mission-type-id world-time))
(if (not (world-sector-corrupted-p world-sector))
(list +lm-feat-church+)
nil))
:is-available-for-mission #'(lambda (world-sector-type-id mission-type-id world-time)
(declare (ignore mission-type-id world-time))
;; is not available for hell districts
(if (not (world-sector-hell-p (get-world-sector-type-by-id world-sector-type-id)))
t
nil))
:always-present-func #'(lambda (world-sector mission world-time)
(declare (ignore world-sector world-time))
(if (or (eq (mission-type-id mission) :mission-type-demonic-thievery)
(eq (mission-type-id mission) :mission-type-celestial-retrieval))
t
nil)))
| 7,258
|
Common Lisp
|
.lisp
| 78
| 42.448718
| 209
| 0.344452
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
5af9d2afea6ed300a6aa806c74d3327691b3dad016c561effb0616258421840b
| 2,939
|
[
-1
] |
2,940
|
init-lvl-mod-player-placement.lisp
|
gwathlobal_CotD/src/level-modifiers/init-lvl-mod-player-placement.lisp
|
(in-package :cotd)
(set-level-modifier :id +lm-placement-player+ :type :level-mod-player-placement
:name "Player"
:overall-post-process-func-list #'(lambda ()
(let ((func-list ()))
(push #'(lambda (level world-sector mission world)
(declare (ignore world-sector mission world))
(setf *player* (make-instance 'player :mob-type +mob-type-player+))
(find-unoccupied-place-outside level *player*)
)
func-list)
func-list)))
(set-level-modifier :id +lm-placement-dead-player+ :type :level-mod-player-placement
:name "Dead player"
:overall-post-process-func-list #'(lambda ()
(let ((func-list ()))
(push #'(lambda (level world-sector mission world)
(declare (ignore world-sector mission world))
(setf *player* (make-instance 'player :mob-type +mob-type-player+))
(find-unoccupied-place-outside level *player*)
(setf (cur-hp *player*) 0)
(make-dead *player* :corpse nil)
)
func-list)
func-list)))
(set-level-modifier :id +lm-placement-angel-chrome+ :type :level-mod-player-placement
:name "Celestial Communion (as Chrome angel)"
:overall-post-process-func-list #'(lambda ()
(let ((func-list ()))
(push #'(lambda (level world-sector mission world)
(place-angels-on-level level world-sector mission world (list (list +mob-type-angel+ 1 t))))
func-list)
func-list)))
(set-level-modifier :id +lm-placement-angel-trinity+ :type :level-mod-player-placement
:name "Celestial Communion (as Trinity mimics)"
:overall-post-process-func-list #'(lambda ()
(let ((func-list ()))
(push #'(lambda (level world-sector mission world)
(place-angels-on-level level world-sector mission world (list (list +mob-type-star-singer+ 1 t))))
func-list)
func-list)))
(set-level-modifier :id +lm-placement-demon-crimson+ :type :level-mod-player-placement
:name "Pandemonium Hierarchy (as Crimson imp)"
:overall-post-process-func-list #'(lambda ()
(let ((func-list ()))
(push #'(lambda (level world-sector mission world)
(place-demons-on-level level world-sector mission world (list (list +mob-type-imp+ 1 t))))
func-list)
func-list)))
(set-level-modifier :id +lm-placement-demon-shadow+ :type :level-mod-player-placement
:name "Pandemonium Hierarchy (as Shadow imp)"
:overall-post-process-func-list #'(lambda ()
(let ((func-list ()))
(push #'(lambda (level world-sector mission world)
(place-demons-on-level level world-sector mission world (list (list +mob-type-shadow-imp+ 1 t))))
func-list)
func-list)))
(set-level-modifier :id +lm-placement-demon-malseraph+ :type :level-mod-player-placement
:name "Pandemonium Hierarchy (as Malseraph's puppet)"
:overall-post-process-func-list #'(lambda ()
(let ((func-list ()))
(push #'(lambda (level world-sector mission world)
(place-demons-on-level level world-sector mission world (list (list +mob-type-malseraph-puppet+ 1 t))))
func-list)
func-list)))
(set-level-modifier :id +lm-placement-military-chaplain+ :type :level-mod-player-placement
:name "Military (as Chaplain)"
:overall-post-process-func-list #'(lambda ()
(let ((func-list ()))
(push #'(lambda (level world-sector mission world)
(place-military-on-level level world-sector mission world
(list (list (list +mob-type-chaplain+ 1 t)
(list +mob-type-sergeant+ 1 nil)
(list +mob-type-scout+ 1 nil)
(list +mob-type-soldier+ 3 nil)
(list +mob-type-gunner+ 1 nil)))
t))
func-list)
func-list)))
(set-level-modifier :id +lm-placement-military-scout+ :type :level-mod-player-placement
:name "Military (as Scout)"
:overall-post-process-func-list #'(lambda ()
(let ((func-list ()))
(push #'(lambda (level world-sector mission world)
(place-military-on-level level world-sector mission world
(list (list (list +mob-type-scout+ 1 t)))
nil))
func-list)
func-list)))
(set-level-modifier :id +lm-placement-priest+ :type :level-mod-player-placement
:name "Church"
:overall-post-process-func-list #'(lambda ()
(let ((func-list ()))
(push #'(lambda (level world-sector mission world)
(declare (ignore world-sector mission world))
(setf *player* (make-instance 'player :mob-type +mob-type-priest+))
(find-player-start-position level *player* +feature-start-church-player+))
func-list)
func-list)))
(set-level-modifier :id +lm-placement-satanist+ :type :level-mod-player-placement
:name "Satanists"
:overall-post-process-func-list #'(lambda ()
(let ((func-list ()))
(push #'(lambda (level world-sector mission world)
(declare (ignore world-sector mission world))
(setf *player* (make-instance 'player :mob-type +mob-type-satanist+))
(find-player-start-position level *player* +feature-start-satanist-player+))
func-list)
func-list)))
(set-level-modifier :id +lm-placement-eater+ :type :level-mod-player-placement
:name "Eater of the dead"
:overall-post-process-func-list #'(lambda ()
(let ((func-list ()))
(push #'(lambda (level world-sector mission world)
(declare (ignore world-sector mission world))
(setf *player* (make-instance 'player :mob-type +mob-type-eater-of-the-dead+))
(find-unoccupied-place-water level *player*))
func-list)
func-list)))
(set-level-modifier :id +lm-placement-skinchanger+ :type :level-mod-player-placement
:name "Skinchanger"
:overall-post-process-func-list #'(lambda ()
(let ((func-list ()))
(push #'(lambda (level world-sector mission world)
(declare (ignore world-sector mission world))
(setf *player* (make-instance 'player :mob-type +mob-type-skinchanger-melee+))
(find-unoccupied-place-water level *player*))
func-list)
func-list)))
(set-level-modifier :id +lm-placement-thief+ :type :level-mod-player-placement
:name "Thief"
:overall-post-process-func-list #'(lambda ()
(let ((func-list ()))
(push #'(lambda (level world-sector mission world)
(declare (ignore world-sector mission world))
(setf *player* (make-instance 'player :mob-type +mob-type-thief+))
(find-unoccupied-place-on-top level *player*))
func-list)
func-list)))
(set-level-modifier :id +lm-placement-ghost+ :type :level-mod-player-placement
:name "Lost soul"
:overall-post-process-func-list #'(lambda ()
(let ((func-list ()))
(push #'(lambda (level world-sector mission world)
(declare (ignore world-sector mission world))
(setf *player* (make-instance 'player :mob-type +mob-type-ghost+))
(find-unoccupied-place-inside level *player*))
func-list)
func-list)))
(set-level-modifier :id +lm-placement-test+ :type :level-mod-player-placement
:name "Test"
:overall-post-process-func-list #'(lambda ()
(let ((func-list ()))
(push #'(lambda (level world-sector mission world)
(declare (ignore world-sector mission level))
(test-level-place-mobs world)
)
func-list)
func-list)))
| 14,871
|
Common Lisp
|
.lisp
| 159
| 39.396226
| 171
| 0.331816
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
564226d56117595c3a449440ec24d2cd41676a38cfe506f355eec81599a32f1f
| 2,940
|
[
-1
] |
2,941
|
init-lvl-mod-time-of-day.lisp
|
gwathlobal_CotD/src/level-modifiers/init-lvl-mod-time-of-day.lisp
|
(in-package :cotd)
;;---------------------------------
;; Time of Day level modifiers
;;---------------------------------
(set-level-modifier :id +lm-tod-morning+ :type :level-mod-tod
:name "Morning"
:overall-post-process-func-list #'(lambda ()
(let ((func-list ()))
(push #'(lambda (level world-sector mission world)
(declare (ignore world-sector mission))
(multiple-value-bind (year month day hour min sec) (get-current-date-time (world-game-time world))
(setf hour 7)
(setf min (random 45))
(setf sec (random 60))
(setf (world-game-time world) (set-current-date-time year month day hour min sec)))
(set-up-outdoor-light level 50)
)
func-list)
(reverse func-list)))
:is-available-for-mission #'(lambda (world-sector-type-id mission-type-id world-time)
(declare (ignore mission-type-id world-time))
;; is not available for hell districts
(if (not (world-sector-hell-p (get-world-sector-type-by-id world-sector-type-id)))
t
nil)))
(set-level-modifier :id +lm-tod-noon+ :type :level-mod-tod
:name "Afternoon"
:overall-post-process-func-list #'(lambda ()
(let ((func-list ()))
(push #'(lambda (level world-sector mission world)
(declare (ignore world-sector mission))
(multiple-value-bind (year month day hour min sec) (get-current-date-time (world-game-time world))
(setf hour 12)
(setf min (random 45))
(setf sec (random 60))
(setf (world-game-time world) (set-current-date-time year month day hour min sec)))
(set-up-outdoor-light level 100)
)
func-list)
(reverse func-list)))
:is-available-for-mission #'(lambda (world-sector-type-id mission-type-id world-time)
(declare (ignore mission-type-id world-time))
;; is not available for hell districts
(if (not (world-sector-hell-p (get-world-sector-type-by-id world-sector-type-id)))
t
nil)))
(set-level-modifier :id +lm-tod-evening+ :type :level-mod-tod
:name "Evening"
:overall-post-process-func-list #'(lambda ()
(let ((func-list ()))
(push #'(lambda (level world-sector mission world)
(declare (ignore world-sector mission))
(multiple-value-bind (year month day hour min sec) (get-current-date-time (world-game-time world))
(setf hour 19)
(setf min (random 45))
(setf sec (random 60))
(setf (world-game-time world) (set-current-date-time year month day hour min sec)))
(set-up-outdoor-light level 50)
)
func-list)
(reverse func-list)))
:is-available-for-mission #'(lambda (world-sector-type-id mission-type-id world-time)
(declare (ignore mission-type-id world-time))
;; is not available for hell districts
(if (not (world-sector-hell-p (get-world-sector-type-by-id world-sector-type-id)))
t
nil)))
(set-level-modifier :id +lm-tod-night+ :type :level-mod-tod
:name "Midnight"
:overall-post-process-func-list #'(lambda ()
(let ((func-list ()))
(push #'(lambda (level world-sector mission world)
(declare (ignore world-sector mission))
(multiple-value-bind (year month day hour min sec) (get-current-date-time (world-game-time world))
(setf hour 0)
(setf min (random 45))
(setf sec (random 60))
(setf (world-game-time world) (set-current-date-time year month day hour min sec)))
(set-up-outdoor-light level 0)
)
func-list)
(reverse func-list)))
:is-available-for-mission #'(lambda (world-sector-type-id mission-type-id world-time)
(declare (ignore mission-type-id world-time))
;; is not available for hell districts
(if (not (world-sector-hell-p (get-world-sector-type-by-id world-sector-type-id)))
t
nil)))
(set-level-modifier :id +lm-tod-hell+ :type :level-mod-tod
:name "Hellday"
:overall-post-process-func-list #'(lambda ()
(let ((func-list ()))
(push #'(lambda (level world-sector mission world)
(declare (ignore world-sector mission))
(multiple-value-bind (year month day hour min sec) (get-current-date-time (world-game-time world))
(setf hour 12)
(setf min (random 45))
(setf sec (random 60))
(setf (world-game-time world) (set-current-date-time year month day hour min sec)))
(set-up-outdoor-light level 50)
(push +game-event-hellday+ (game-events level))
)
func-list)
(reverse func-list)))
:is-available-for-mission #'(lambda (world-sector-type-id mission-type-id world-time)
(declare (ignore mission-type-id world-time))
;; is only available for hell districts
(if (world-sector-hell-p (get-world-sector-type-by-id world-sector-type-id))
t
nil)))
| 9,876
|
Common Lisp
|
.lisp
| 110
| 37.254545
| 166
| 0.309735
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
851beeead0193a5a406ee67a1f68dc53fa97c0d19014ce89f4a5762d65ab0764
| 2,941
|
[
-1
] |
2,942
|
init-ai-packages.lisp
|
gwathlobal_CotD/src/ai/init-ai-packages.lisp
|
(in-package :cotd)
(set-ai-package (make-instance 'ai-package :id +ai-package-coward+
:priority 9
:on-check-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs)
(declare (ignore nearest-ally hostile-mobs allied-mobs))
(if (and nearest-enemy
(>= (strength nearest-enemy) (strength actor)))
t
nil))
:on-invoke-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs check-result)
(declare (ignore nearest-ally hostile-mobs allied-mobs check-result))
(log:info "AI-PACKAGE-COWARD: ~A [~A] is in fear with an enemy ~A [~A]." (name actor) (id actor) (name nearest-enemy) (id nearest-enemy))
(ai-mob-flee actor nearest-enemy)
)))
(set-ai-package (make-instance 'ai-package :id +ai-package-avoid-possession+
:priority 9
:on-check-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs)
(declare (ignore nearest-ally hostile-mobs allied-mobs))
(let ((free-cells ()))
(if (and nearest-enemy
(= (z actor) (z nearest-enemy))
(< (get-distance (x actor) (y actor) (x nearest-enemy) (y nearest-enemy)) 2)
(mob-ability-p actor +mob-abil-possessable+)
(mob-ability-p nearest-enemy +mob-abil-can-possess+)
(not (mob-effect-p actor +mob-effect-blessed+))
(not (mob-effect-p actor +mob-effect-divine-shield+)))
(progn
(check-surroundings (x actor) (y actor) nil #'(lambda (dx dy)
(let ((terrain (get-terrain-* (level *world*) dx dy (z actor))))
(when (and terrain
(get-terrain-type-trait terrain +terrain-trait-blocks-move-floor+)
(not (get-terrain-type-trait terrain +terrain-trait-blocks-move+))
(not (get-mob-* (level *world*) dx dy (z actor)))
(>= (get-distance dx dy (x nearest-enemy) (y nearest-enemy)) 2))
(push (list dx dy) free-cells)))
))
(if free-cells
free-cells
nil))
nil)))
:on-invoke-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs check-result)
(declare (ignore nearest-ally hostile-mobs allied-mobs))
(log:info "AI-PACKAGE-AVOID-POSSESSION: ~A [~A] does not want to be possessed by ~A [~A]." (name actor) (id actor) (name nearest-enemy) (id nearest-enemy))
(let ((cell (first check-result)))
(setf (path-dst actor) nil)
(setf (path actor) (list (list (first cell) (second cell) (z actor)))))
(ai-move-along-path actor)
)))
(set-ai-package (make-instance 'ai-package :id +ai-package-avoid-melee+
:priority 9
:on-check-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs)
(declare (ignore nearest-ally hostile-mobs allied-mobs))
(let ((free-cells ()))
(if (and nearest-enemy
(= (z actor) (z nearest-enemy))
(< (get-distance (x actor) (y actor) (x nearest-enemy) (y nearest-enemy)) 2)
(is-weapon-ranged actor)
(is-weapon-melee nearest-enemy))
(progn
(check-surroundings (x actor) (y actor) nil #'(lambda (dx dy)
(let ((terrain (get-terrain-* (level *world*) dx dy (z actor))))
(when (and terrain
(get-terrain-type-trait terrain +terrain-trait-blocks-move-floor+)
(not (get-terrain-type-trait terrain +terrain-trait-blocks-move+))
(not (get-mob-* (level *world*) dx dy (z actor)))
(>= (get-distance dx dy (x nearest-enemy) (y nearest-enemy)) 2))
(push (list dx dy) free-cells)))
))
(if free-cells
free-cells
nil))
nil)))
:on-invoke-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs check-result)
(declare (ignore nearest-ally hostile-mobs allied-mobs))
(log:info "AI-PACKAGE-AVOID-MELEE: ~A [~A] does not want to have melee combat with by ~A [~A]." (name actor) (id actor) (name nearest-enemy) (id nearest-enemy))
(let ((cell (first check-result)))
(setf (path-dst actor) nil)
(setf (path actor) (list (list (first cell) (second cell) (z actor)))))
(ai-move-along-path actor)
)))
(set-ai-package (make-instance 'ai-package :id +ai-package-swim-up+
:priority 8
:on-check-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs)
(declare (ignore nearest-ally nearest-enemy hostile-mobs allied-mobs))
(let ((target-cell ()))
(if (and (get-terrain-type-trait (get-terrain-* (level *world*) (x actor) (y actor) (z actor)) +terrain-trait-water+)
(not (mob-ability-p actor +mob-abil-no-breathe+))
(<= (cur-oxygen actor) 1)
(loop for z from (z actor) upto (array-dimension (terrain (level *world*)) 2)
when (or (get-terrain-type-trait (get-terrain-* (level *world*) (x actor) (y actor) z) +terrain-trait-blocks-move-floor+)
(get-terrain-type-trait (get-terrain-* (level *world*) (x actor) (y actor) z) +terrain-trait-blocks-move+))
do
(return nil)
when (and (not (get-terrain-type-trait (get-terrain-* (level *world*) (x actor) (y actor) z) +terrain-trait-blocks-move-floor+))
(not (get-terrain-type-trait (get-terrain-* (level *world*) (x actor) (y actor) z) +terrain-trait-blocks-move+))
(not (get-terrain-type-trait (get-terrain-* (level *world*) (x actor) (y actor) z) +terrain-trait-water+)))
do
(setf target-cell (list (x actor) (y actor) (1- z)))
(return t)
finally (return nil)
))
(if (and (= (x actor) (first target-cell))
(= (y actor) (second target-cell))
(= (z actor) (third target-cell)))
nil
(if (or (level-cells-connected-p (level *world*) (x actor) (y actor) (z actor) (first target-cell) (second target-cell) (third target-cell)
(if (riding-mob-id actor)
(map-size (get-mob-by-id (riding-mob-id actor)))
(map-size actor))
(get-mob-move-mode actor) :can-open-doors (can-open-doors actor))
(and (> (map-size actor) 1)
(ai-find-move-around actor (first target-cell) (second target-cell))))
target-cell
nil))
nil)))
:on-invoke-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs check-result)
(declare (ignore nearest-ally hostile-mobs allied-mobs nearest-enemy))
(log:info "AI-PACKAGE-SWIM-UP: ~A [~A] wants to swim up to ~A." (name actor) (id actor) check-result)
(loop with x-terrain = (first check-result)
with y-terrain = (second check-result)
with z-terrain = (third check-result)
with move-failed-once = nil
with move-result = nil
while t do
;; set path-dst to the target terrain if there is no path-dst or it is different from the item position
(when (or (null (path-dst actor))
(/= (first (path-dst actor)) x-terrain)
(/= (second (path-dst actor)) y-terrain)
(/= (third (path-dst actor)) z-terrain))
(ai-set-path-dst actor x-terrain y-terrain z-terrain))
;; exit (and move randomly) if the path-dst is still null after the previous set attempt
(when (null (path-dst actor))
(ai-mob-random-dir actor)
(loop-finish))
;; make a path to the destination target if there is no path plotted
(when (or (null (path actor))
(mob-ability-p actor +mob-abil-momentum+))
(ai-plot-path-to-dst actor (first (path-dst actor)) (second (path-dst actor)) (third (path-dst actor))))
;; make a step along the path to the path-dst
(setf move-result (ai-move-along-path actor))
(cond
;; if the move failed twice - move in a random direction
((and move-failed-once
(null move-result))
(ai-mob-random-dir actor)
(loop-finish))
;; if the move failed - reset path-dst and start anew
((and (null move-failed-once)
(null move-result))
(setf (path-dst actor) nil)
(setf move-failed-once t)
)
;; success
(t
(loop-finish))))
)))
(set-ai-package (make-instance 'ai-package :id +ai-package-horde+
:priority 8
:on-check-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs)
(declare (ignore nearest-enemy nearest-ally))
(let ((ally-str (strength actor))
(enemy-str 0))
(declare (type fixnum ally-str enemy-str))
(dolist (ally-id allied-mobs)
(declare (type fixnum ally-id))
(incf ally-str (strength (get-mob-by-id ally-id))))
(dolist (enemy-id hostile-mobs)
(incf enemy-str (strength (get-mob-type-by-id (face-mob-type-id (get-mob-by-id enemy-id))))))
(log:info "AI-PACKAGE-HORDE: ~A [~A] has horde behavior. Ally vs. Enemy strength is ~A vs ~A." (name actor) (id actor) ally-str enemy-str)
(if (< ally-str enemy-str)
t
nil))
)
:on-invoke-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs check-result)
(declare (ignore nearest-ally allied-mobs hostile-mobs check-result))
;; if the mob has horde behavior, compare relative strengths of allies to relative strength of enemies
;; if less - flee
(ai-mob-flee actor nearest-enemy)
)))
(set-ai-package (make-instance 'ai-package :id +ai-package-wants-bless+
:priority 8
:on-check-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs)
(declare (ignore nearest-ally hostile-mobs))
(let ((nearest-ally nil))
(loop for mob-id of-type fixnum in allied-mobs
for target-mob = (get-mob-by-id mob-id)
with vis-mob-type = nil
do
(setf vis-mob-type (get-mob-type-by-id (face-mob-type-id target-mob)))
;; when you are of the same faction, you know who is who
(when (= (faction actor) (faction target-mob))
(setf vis-mob-type (get-mob-type-by-id (mob-type target-mob))))
;; find the nearest allied unblessed mob mob
(when (and (mob-ability-p vis-mob-type +mob-abil-can-be-blessed+)
(not (mob-effect-p target-mob +mob-effect-blessed+))
(not (= (mob-type target-mob) +mob-type-ghost+)))
(unless nearest-ally
(setf nearest-ally target-mob))
(when (< (get-distance (x target-mob) (y target-mob) (x actor) (y actor))
(get-distance (x nearest-ally) (y nearest-ally) (x actor) (y actor)))
(setf nearest-ally target-mob)))
)
(log:info "AI-PACKAGE-WANTS-TO-BLESS: ~A [~A] thinks of giving blessings. Nearest unblessed ally ~A [~A]"
(name actor) (id actor) (if nearest-ally (name nearest-ally) nil) (if nearest-ally (id nearest-ally) nil))
(if (or (and nearest-ally
(not nearest-enemy))
(and nearest-ally
nearest-enemy
(< (get-distance (x actor) (y actor) (x nearest-ally) (y nearest-ally))
(get-distance (x actor) (y actor) (x nearest-enemy) (y nearest-enemy)))))
nearest-ally
nil)
))
:on-invoke-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs check-result)
(declare (ignore nearest-ally nearest-enemy hostile-mobs allied-mobs))
(log:info "AI-PACKAGE-WANTS-TO-BLESS: ~A [~A] decided to give blessings to ~A [~A]"
(name actor) (id actor) (if check-result (name check-result) nil) (if check-result (id check-result) nil))
(loop with move-failed-once = nil
with move-result = nil
while t do
;; set path-dst to the allied mob if there is no path-dst or it is different from the allied mob position
(when (or (null (path-dst actor))
(/= (first (path-dst actor)) (x check-result))
(/= (second (path-dst actor)) (y check-result))
(/= (third (path-dst actor)) (z check-result)))
(ai-set-path-dst actor (x check-result) (y check-result) (z check-result)))
;; exit (and move randomly) if the path-dst is still null after the previous set attempt
(when (null (path-dst actor))
(ai-mob-random-dir actor)
(loop-finish))
;; make a path to the destination target if there is no path plotted
(when (or (null (path actor))
(mob-ability-p actor +mob-abil-momentum+))
(ai-plot-path-to-dst actor (first (path-dst actor)) (second (path-dst actor)) (third (path-dst actor))))
;; make a step along the path to the path-dst
(setf move-result (ai-move-along-path actor))
(cond
;; if the move failed twice - move in a random direction
((and move-failed-once
(null move-result))
(ai-mob-random-dir actor)
(loop-finish))
;; if the move failed - reset path-dst and start anew
((and (null move-failed-once)
(null move-result))
(setf (path-dst actor) nil)
(setf move-failed-once t)
)
;; success
(t
(loop-finish))))
)))
(set-ai-package (make-instance 'ai-package :id +ai-package-cautious+
:priority +ai-priority-never+
))
(set-ai-package (make-instance 'ai-package :id +ai-package-trinity-mimic+
:priority +ai-priority-always+
:on-check-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs)
(declare (ignore actor nearest-enemy nearest-ally hostile-mobs allied-mobs))
t)
:on-invoke-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs check-result)
(declare (ignore nearest-enemy hostile-mobs nearest-ally allied-mobs check-result))
;; if the mob is a trinity mimic, assign the first one as a leader and make all others in the group follow it
(setf (order actor) nil)
(loop for mimic-id in (mimic-id-list actor)
for mimic = (get-mob-by-id mimic-id)
when (and (not (eq mimic actor))
(not (check-dead mimic))
(not (is-merged mimic)))
do
(setf (order actor) (list +mob-order-follow+ mimic-id))
(log:info "AI-PACKAGE-TRINITY-MIMIC: ~A [~A] has to follow ~A [~A]."
(name actor) (id actor) (name mimic) (id mimic))
(loop-finish))
)))
(set-ai-package (make-instance 'ai-package :id +ai-package-takes-valuable-items+
:priority 8
:on-check-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs)
(declare (ignore nearest-ally hostile-mobs allied-mobs))
(let ((valuable-items))
(if (and (null nearest-enemy)
(setf valuable-items (loop for item-id in (get-items-* (level *world*) (x actor) (y actor) (z actor))
for item = (get-item-by-id item-id)
when (not (zerop (value item)))
collect item)))
valuable-items
nil)))
:on-invoke-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs check-result)
(declare (ignore nearest-enemy hostile-mobs nearest-ally allied-mobs))
(log:info "AI-PACKAGE-TAKES-ITEMS: ~A [~A] decided to take item ~A [~A]."
(name actor) (id actor) (name (first check-result)) (id (first check-result)))
(mob-pick-item actor (first check-result))
)))
(set-ai-package (make-instance 'ai-package :id +ai-package-pick-corpses+
:priority 8
:on-check-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs)
(declare (ignore nearest-ally hostile-mobs allied-mobs))
(let ((corpse-items))
(if (and (null nearest-enemy)
(setf corpse-items (loop for item-id in (get-items-* (level *world*) (x actor) (y actor) (z actor))
for item = (get-item-by-id item-id)
when (item-ability-p item +item-abil-corpse+)
collect item)))
corpse-items
nil)))
:on-invoke-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs check-result)
(declare (ignore nearest-enemy hostile-mobs nearest-ally allied-mobs))
(log:info "AI-PACKAGE-TAKES-CORPSES: ~A [~A] decided to take item ~A [~A]."
(name actor) (id actor) (name (first check-result)) (id (first check-result)))
(mob-pick-item actor (first check-result))
)))
(set-ai-package (make-instance 'ai-package :id +ai-package-pick-relic+
:priority 8
:on-check-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs)
(declare (ignore nearest-ally hostile-mobs allied-mobs))
(let ((relic-items))
(if (and (null nearest-enemy)
(setf relic-items (loop for item-id in (get-items-* (level *world*) (x actor) (y actor) (z actor))
for item = (get-item-by-id item-id)
when (= (item-type item) +item-type-church-reliс+)
collect item)))
relic-items
nil)))
:on-invoke-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs check-result)
(declare (ignore nearest-enemy hostile-mobs nearest-ally allied-mobs))
(log:info "AI-PACKAGE-TAKES-RELIC: ~A [~A] decided to take item ~A [~A]."
(name actor) (id actor) (name (first check-result)) (id (first check-result)))
(mob-pick-item actor (first check-result))
)))
(set-ai-package (make-instance 'ai-package :id +ai-package-split-soul+
:priority 7
:on-check-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs)
(declare (ignore actor nearest-ally hostile-mobs allied-mobs))
(if nearest-enemy
t
nil))
:on-invoke-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs check-result)
(declare (ignore nearest-ally hostile-mobs allied-mobs check-result))
(log:info "AI-PACKAGE-SPLIT-SOUL: ~A [~A] is trying to move away from the enemy ~A [~A]." (name actor) (id actor) (name nearest-enemy) (id nearest-enemy))
(if (mob-ability-p actor +mob-abil-immobile+)
(move-mob actor 5)
(progn
;; 1) find the tile farthest from the nearest enemy
(let ((farthest-tile nil))
(check-surroundings (x actor) (y actor) nil #'(lambda (dx dy)
(when (eq (check-move-on-level actor dx dy (z actor)) t)
(unless farthest-tile
(setf farthest-tile (list dx dy (z actor))))
(when (> (get-distance dx dy (x nearest-enemy) (y nearest-enemy))
(get-distance (first farthest-tile) (second farthest-tile) (x nearest-enemy) (y nearest-enemy)))
(setf farthest-tile (list dx dy (z actor)))))))
(if farthest-tile
(setf (path-dst actor) farthest-tile)
(setf (path-dst actor) (list (x actor) (y actor) (z actor))))
)
;; 2) move to that tile
(move-mob actor (x-y-into-dir (- (first (path-dst actor)) (x actor))
(- (second (path-dst actor)) (y actor))))
))
)))
(set-ai-package (make-instance 'ai-package :id +ai-package-kleptomaniac+
:priority 7
:on-check-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs)
(declare (ignore nearest-ally hostile-mobs allied-mobs))
(let ((valuable-items))
(if (and (null nearest-enemy)
(setf valuable-items (loop for item-id in (visible-items actor)
for item = (get-item-by-id item-id)
when (and (not (zerop (value item)))
(not (and (= (x item) (x actor))
(= (y item) (y actor))
(= (z item) (z actor))))
(or (level-cells-connected-p (level *world*) (x actor) (y actor) (z actor) (x item) (y item) (z item)
(if (riding-mob-id actor)
(map-size (get-mob-by-id (riding-mob-id actor)))
(map-size actor))
(get-mob-move-mode actor) :can-open-doors (can-open-doors actor))
(and (> (map-size actor) 1)
(ai-find-move-around actor (x item) (y item)))))
collect item)))
valuable-items
nil)))
:on-invoke-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs check-result)
(declare (ignore nearest-enemy hostile-mobs nearest-ally allied-mobs))
;; when mob is kleptomaniac and has no target
;; sort all items by distance from the actor
(loop with visible-items = (stable-sort check-result #'(lambda (a b)
(if (< (get-distance-3d (x actor) (y actor) (z actor) (x a) (y a) (z a))
(get-distance-3d (x actor) (y actor) (z actor) (x b) (y b) (z b)))
t
nil)))
with item = (first visible-items)
with move-failed-once = nil
with move-result = nil
while t do
(log:info "AI-PACKAGE-KLEPTOMANIAC: Mob (~A ~A ~A) wants to get item ~A [~A] at (~A, ~A, ~A)"
(x actor) (y actor) (z actor) (name item) (id item) (x item) (y item) (z item))
;; set path-dst to the nearest item if there is no path-dst or it is different from the item position
(when (or (null (path-dst actor))
(/= (first (path-dst actor)) (x item))
(/= (second (path-dst actor)) (y item))
(/= (third (path-dst actor)) (z item)))
(ai-set-path-dst actor (x item) (y item) (z item)))
;; exit (and move randomly) if the path-dst is still null after the previous set attempt
(when (null (path-dst actor))
(ai-mob-random-dir actor)
(loop-finish))
;; make a path to the destination target if there is no path plotted
(when (or (null (path actor))
(mob-ability-p actor +mob-abil-momentum+))
(ai-plot-path-to-dst actor (first (path-dst actor)) (second (path-dst actor)) (third (path-dst actor))))
;; make a step along the path to the path-dst
(setf move-result (ai-move-along-path actor))
(cond
;; if the move failed twice - move in a random direction
((and move-failed-once
(null move-result))
(ai-mob-random-dir actor)
(loop-finish))
;; if the move failed - reset path-dst and start anew
((and (null move-failed-once)
(null move-result))
(setf (path-dst actor) nil)
(setf move-failed-once t)
)
;; success
(t
(loop-finish))))
)))
(set-ai-package (make-instance 'ai-package :id +ai-package-curious+
:priority 5
:on-check-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs)
(declare (ignore nearest-ally hostile-mobs allied-mobs))
(let ((heard-sounds))
(if (and (null nearest-enemy)
(setf heard-sounds (loop for sound in (heard-sounds actor)
when (and (not (and (= (sound-x sound) (x actor))
(= (sound-y sound) (y actor))
(= (sound-z sound) (z actor))))
(or (level-cells-connected-p (level *world*) (x actor) (y actor) (z actor) (sound-x sound) (sound-y sound) (sound-z sound)
(if (riding-mob-id actor)
(map-size (get-mob-by-id (riding-mob-id actor)))
(map-size actor))
(get-mob-move-mode actor) :can-open-doors (can-open-doors actor))
(and (> (map-size actor) 1)
(ai-find-move-around actor (sound-x sound) (sound-y sound)))))
collect sound))
)
heard-sounds
nil)))
:on-invoke-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs check-result)
(declare (ignore nearest-enemy hostile-mobs nearest-ally allied-mobs))
;; if the mob is curious and it has nothing to do - move to the nearest sound, if any
(loop with heard-sounds = (stable-sort check-result #'(lambda (a b)
(if (< (get-distance-3d (x actor) (y actor) (z actor) (sound-x a) (sound-y a) (sound-z a))
(get-distance-3d (x actor) (y actor) (z actor) (sound-x b) (sound-y b) (sound-z b)))
t
nil)))
with sound = (first heard-sounds)
with move-failed-once = nil
with move-result = nil
while t do
(log:info "AI-PACKAGE-CURIOUS: Mob (~A ~A ~A) wants to investigate sound at (~A, ~A, ~A)"
(x actor) (y actor) (z actor) (sound-x sound) (sound-y sound) (sound-z sound))
;; set path-dst to the nearest sound if there is no path-dst or it is different from the sound position
(when (or (null (path-dst actor))
(/= (first (path-dst actor)) (sound-x sound))
(/= (second (path-dst actor)) (sound-y sound))
(/= (third (path-dst actor)) (sound-z sound)))
(ai-set-path-dst actor (sound-x sound) (sound-y sound) (sound-z sound)))
;; exit (and move randomly) if the path-dst is still null after the previous set attempt
(when (null (path-dst actor))
(ai-mob-random-dir actor)
(loop-finish))
;; make a path to the destination target if there is no path plotted
(when (or (null (path actor))
(mob-ability-p actor +mob-abil-momentum+))
(ai-plot-path-to-dst actor (first (path-dst actor)) (second (path-dst actor)) (third (path-dst actor))))
;; make a step along the path to the path-dst
(setf move-result (ai-move-along-path actor))
(cond
;; if the move failed twice - move in a random direction
((and move-failed-once
(null move-result))
(ai-mob-random-dir actor)
(loop-finish))
;; if the move failed - reset path-dst and start anew
((and (null move-failed-once)
(null move-result))
(setf (path-dst actor) nil)
(setf move-failed-once t)
)
;; success
(t
(loop-finish))))
)))
(set-ai-package (make-instance 'ai-package :id +ai-package-search-corpses+
:priority 7
:on-check-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs)
(declare (ignore nearest-ally hostile-mobs allied-mobs))
(let ((corpse-items))
(if (and (null nearest-enemy)
(setf corpse-items (loop for item-id in (visible-items actor)
for item = (get-item-by-id item-id)
when (and (item-ability-p item +item-abil-corpse+)
(not (and (= (x item) (x actor))
(= (y item) (y actor))
(= (z item) (z actor))))
(or (level-cells-connected-p (level *world*) (x actor) (y actor) (z actor) (x item) (y item) (z item)
(if (riding-mob-id actor)
(map-size (get-mob-by-id (riding-mob-id actor)))
(map-size actor))
(get-mob-move-mode actor) :can-open-doors (can-open-doors actor))
(and (> (map-size actor) 1)
(ai-find-move-around actor (x item) (y item)))))
collect item)))
corpse-items
nil)))
:on-invoke-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs check-result)
(declare (ignore nearest-enemy hostile-mobs nearest-ally allied-mobs))
;; when mob is a cannibal go to the nearest visible item and try to eat it
(loop with visible-items = (stable-sort check-result #'(lambda (a b)
(if (< (get-distance-3d (x actor) (y actor) (z actor) (x a) (y a) (z a))
(get-distance-3d (x actor) (y actor) (z actor) (x b) (y b) (z b)))
t
nil)))
with item = (first visible-items)
with move-failed-once = nil
with move-result = nil
while t do
(log:info "AI-PACKAGE-SEARCH-CORPSES: Mob (~A ~A ~A) wants to get item ~A [~A] at (~A, ~A, ~A)"
(x actor) (y actor) (z actor) (name item) (id item) (x item) (y item) (z item))
;; set path-dst to the nearest item if there is no path-dst or it is different from the item position
(when (or (null (path-dst actor))
(/= (first (path-dst actor)) (x item))
(/= (second (path-dst actor)) (y item))
(/= (third (path-dst actor)) (z item)))
(ai-set-path-dst actor (x item) (y item) (z item)))
;; exit (and move randomly) if the path-dst is still null after the previous set attempt
(when (null (path-dst actor))
(ai-mob-random-dir actor)
(loop-finish))
;; make a path to the destination target if there is no path plotted
(when (or (null (path actor))
(mob-ability-p actor +mob-abil-momentum+))
(ai-plot-path-to-dst actor (first (path-dst actor)) (second (path-dst actor)) (third (path-dst actor))))
;; make a step along the path to the path-dst
(setf move-result (ai-move-along-path actor))
(cond
;; if the move failed twice - move in a random direction
((and move-failed-once
(null move-result))
(ai-mob-random-dir actor)
(loop-finish))
;; if the move failed - reset path-dst and start anew
((and (null move-failed-once)
(null move-result))
(setf (path-dst actor) nil)
(setf move-failed-once t)
)
;; success
(t
(loop-finish))))
)))
(set-ai-package (make-instance 'ai-package :id +ai-package-search-relic+
:priority 5
:on-check-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs)
(declare (ignore nearest-ally hostile-mobs allied-mobs))
(let ((relic-item))
(if (and (null nearest-enemy)
(level/relic-id (level *world*))
(setf relic-item (get-item-by-id (level/relic-id (level *world*))))
(null (inv-id relic-item))
(not (and (= (x relic-item) (x actor))
(= (y relic-item) (y actor))
(= (z relic-item) (z actor))))
(or (level-cells-connected-p (level *world*) (x actor) (y actor) (z actor)
(x relic-item)
(y relic-item)
(z relic-item)
(if (riding-mob-id actor)
(map-size (get-mob-by-id (riding-mob-id actor)))
(map-size actor))
(get-mob-move-mode actor)
:can-open-doors (can-open-doors actor))
(and (> (map-size actor) 1)
(ai-find-move-around actor (x relic-item) (y relic-item))))
)
relic-item
nil)))
:on-invoke-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs check-result)
(declare (ignore nearest-enemy hostile-mobs nearest-ally allied-mobs))
;; go to the nearest visible relic and try to pick it
(loop with item = check-result
with move-failed-once = nil
with move-result = nil
while t do
(log:info "AI-PACKAGE-SEARCH-RELIC: Mob (~A ~A ~A) wants to get item ~A [~A] at (~A, ~A, ~A)"
(x actor) (y actor) (z actor) (name item) (id item) (x item) (y item) (z item))
;; set path-dst to the nearest item if there is no path-dst or it is different from the item position
(when (or (null (path-dst actor))
(/= (first (path-dst actor)) (x item))
(/= (second (path-dst actor)) (y item))
(/= (third (path-dst actor)) (z item)))
(ai-set-path-dst actor (x item) (y item) (z item)))
;; exit (and move randomly) if the path-dst is still null after the previous set attempt
(when (null (path-dst actor))
(ai-mob-random-dir actor)
(loop-finish))
;; make a path to the destination target if there is no path plotted
(when (or (null (path actor))
(mob-ability-p actor +mob-abil-momentum+))
(ai-plot-path-to-dst actor (first (path-dst actor)) (second (path-dst actor)) (third (path-dst actor))))
;; make a step along the path to the path-dst
(setf move-result (ai-move-along-path actor))
(cond
;; if the move failed twice - move in a random direction
((and move-failed-once
(null move-result))
(ai-mob-random-dir actor)
(loop-finish))
;; if the move failed - reset path-dst and start anew
((and (null move-failed-once)
(null move-result))
(setf (path-dst actor) nil)
(setf move-failed-once t)
)
;; success
(t
(loop-finish))))
)))
(set-ai-package (make-instance 'ai-package :id +ai-package-find-sigil+
:priority 5
:on-check-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs)
(declare (ignore nearest-ally hostile-mobs allied-mobs))
(let ((sigil-mob))
(if (and (null nearest-enemy)
(setf sigil-mob (loop with sigil = nil
for mob-id in (demonic-sigils (level *world*))
for mob = (get-mob-by-id mob-id)
when (= (mob-type mob) +mob-type-demon-sigil+)
do
(unless sigil (setf sigil mob))
(when (< (get-distance (x actor) (y actor) (x mob) (y mob))
(get-distance (x actor) (y actor) (x sigil) (y sigil)))
(setf sigil mob))
finally (return sigil)))
(or (level-cells-connected-p (level *world*) (x actor) (y actor) (z actor)
(x sigil-mob)
(y sigil-mob)
(z sigil-mob)
(if (riding-mob-id actor)
(map-size (get-mob-by-id (riding-mob-id actor)))
(map-size actor))
(get-mob-move-mode actor)
:can-open-doors (can-open-doors actor))
(and (> (map-size actor) 1)
(ai-find-move-around actor (x sigil-mob) (y sigil-mob))))
)
sigil-mob
nil)))
:on-invoke-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs check-result)
(declare (ignore nearest-enemy hostile-mobs nearest-ally allied-mobs))
;; go to the nearest visible sigil
(loop with sigil = check-result
with move-failed-once = nil
with move-result = nil
while t do
(log:info "AI-PACKAGE-FIND-SIGIL: Mob (~A ~A ~A) wants to go to ~A [~A] at (~A, ~A, ~A)"
(x actor) (y actor) (z actor) (name sigil) (id sigil) (x sigil) (y sigil) (z sigil))
;; set path-dst to the nearest item if there is no path-dst or it is different from the item position
(when (or (null (path-dst actor))
(/= (first (path-dst actor)) (x sigil))
(/= (second (path-dst actor)) (y sigil))
(/= (third (path-dst actor)) (z sigil)))
(ai-set-path-dst actor (x sigil) (y sigil) (z sigil)))
;; exit (and move randomly) if the path-dst is still null after the previous set attempt
(when (null (path-dst actor))
(ai-mob-random-dir actor)
(loop-finish))
;; make a path to the destination target if there is no path plotted
(when (or (null (path actor))
(mob-ability-p actor +mob-abil-momentum+))
(ai-plot-path-to-dst actor (first (path-dst actor)) (second (path-dst actor)) (third (path-dst actor))))
;; make a step along the path to the path-dst
(setf move-result (ai-move-along-path actor))
(cond
;; if the move failed twice - move in a random direction
((and move-failed-once
(null move-result))
(ai-mob-random-dir actor)
(loop-finish))
;; if the move failed - reset path-dst and start anew
((and (null move-failed-once)
(null move-result))
(setf (path-dst actor) nil)
(setf move-failed-once t)
)
;; success
(t
(loop-finish))))
)))
(set-ai-package (make-instance 'ai-package :id +ai-package-find-machine+
:priority 5
:on-check-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs)
(declare (ignore nearest-ally hostile-mobs allied-mobs))
(let ((machine-mob))
(if (and (null nearest-enemy)
(setf machine-mob (loop with machine = nil
for mob-id in (demonic-machines (level *world*))
for mob = (get-mob-by-id mob-id)
when (= (mob-type mob) +mob-type-demon-machine+)
do
(unless machine (setf machine mob))
(when (< (get-distance (x actor) (y actor) (x mob) (y mob))
(get-distance (x actor) (y actor) (x machine) (y machine)))
(setf machine mob))
finally (return machine)))
(or (level-cells-connected-p (level *world*) (x actor) (y actor) (z actor)
(x machine-mob)
(y machine-mob)
(z machine-mob)
(if (riding-mob-id actor)
(map-size (get-mob-by-id (riding-mob-id actor)))
(map-size actor))
(get-mob-move-mode actor)
:can-open-doors (can-open-doors actor))
(and (> (map-size actor) 1)
(ai-find-move-around actor (x machine-mob) (y machine-mob))))
)
machine-mob
nil)))
:on-invoke-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs check-result)
(declare (ignore nearest-enemy hostile-mobs nearest-ally allied-mobs))
;; go to the nearest visible machine
(loop with machine = check-result
with move-failed-once = nil
with move-result = nil
while t do
(log:info "AI-PACKAGE-FIND-MACHINE: Mob (~A ~A ~A) wants to go to ~A [~A] at (~A, ~A, ~A)"
(x actor) (y actor) (z actor) (name machine) (id machine) (x machine) (y machine) (z machine))
;; set path-dst to the nearest item if there is no path-dst or it is different from the item position
(when (or (null (path-dst actor))
(/= (first (path-dst actor)) (x machine))
(/= (second (path-dst actor)) (y machine))
(/= (third (path-dst actor)) (z machine)))
(ai-set-path-dst actor (x machine) (y machine) (z machine)))
;; exit (and move randomly) if the path-dst is still null after the previous set attempt
(when (null (path-dst actor))
(ai-mob-random-dir actor)
(loop-finish))
;; make a path to the destination target if there is no path plotted
(when (or (null (path actor))
(mob-ability-p actor +mob-abil-momentum+))
(ai-plot-path-to-dst actor (first (path-dst actor)) (second (path-dst actor)) (third (path-dst actor))))
;; make a step along the path to the path-dst
(setf move-result (ai-move-along-path actor))
(cond
;; if the move failed twice - move in a random direction
((and move-failed-once
(null move-result))
(ai-mob-random-dir actor)
(loop-finish))
;; if the move failed - reset path-dst and start anew
((and (null move-failed-once)
(null move-result))
(setf (path-dst actor) nil)
(setf move-failed-once t)
)
;; success
(t
(loop-finish))))
)))
(set-ai-package (make-instance 'ai-package :id +ai-package-find-bomb-plant-location+
:priority 5
:on-check-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs)
(declare (ignore nearest-ally hostile-mobs allied-mobs))
(let ((target-feature))
(if (and (null nearest-enemy)
(setf target-feature (loop with target = nil
for feature-id in (bomb-plant-locations (level *world*))
for feature = (get-feature-by-id feature-id)
when (= (feature-type feature) +feature-bomb-plant-target+)
do
(unless target (setf target feature))
(when (< (get-distance (x actor) (y actor) (x feature) (y feature))
(get-distance (x actor) (y actor) (x target) (y target)))
(setf target feature))
finally (return target)))
(or (level-cells-connected-p (level *world*) (x actor) (y actor) (z actor)
(x target-feature)
(y target-feature)
(z target-feature)
(if (riding-mob-id actor)
(map-size (get-mob-by-id (riding-mob-id actor)))
(map-size actor))
(get-mob-move-mode actor)
:can-open-doors (can-open-doors actor))
(and (> (map-size actor) 1)
(ai-find-move-around actor (x target-feature) (y target-feature))))
)
target-feature
nil)))
:on-invoke-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs check-result)
(declare (ignore nearest-enemy hostile-mobs nearest-ally allied-mobs))
;;go to the nearest visible bomb location
(loop with target-feature = check-result
with move-failed-once = nil
with move-result = nil
while t do
(log:info "AI-PACKAGE-FIND-BOMB-PLANT-LOCATION: Mob (~A ~A ~A) wants to go to ~A [~A] at (~A, ~A, ~A)"
(x actor) (y actor) (z actor) (name target-feature) (id target-feature) (x target-feature) (y target-feature) (z target-feature))
;; set path-dst to the nearest item if there is no path-dst or it is different from the item position
(when (or (null (path-dst actor))
(/= (first (path-dst actor)) (x target-feature))
(/= (second (path-dst actor)) (y target-feature))
(/= (third (path-dst actor)) (z target-feature)))
(ai-set-path-dst actor (x target-feature) (y target-feature) (z target-feature)))
;; exit (and move randomly) if the path-dst is still null after the previous set attempt
(when (null (path-dst actor))
(ai-mob-random-dir actor)
(loop-finish))
;; make a path to the destination target if there is no path plotted
(when (or (null (path actor))
(mob-ability-p actor +mob-abil-momentum+))
(ai-plot-path-to-dst actor (first (path-dst actor)) (second (path-dst actor)) (third (path-dst actor))))
;; make a step along the path to the path-dst
(setf move-result (ai-move-along-path actor))
(cond
;; if the move failed twice - move in a random direction
((and move-failed-once
(null move-result))
(ai-mob-random-dir actor)
(loop-finish))
;; if the move failed - reset path-dst and start anew
((and (null move-failed-once)
(null move-result))
(setf (path-dst actor) nil)
(setf move-failed-once t)
)
;; success
(t
(loop-finish))))
)))
(set-ai-package (make-instance 'ai-package :id +ai-package-use-ability+
:priority 8
:on-check-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs)
(declare (ignore hostile-mobs allied-mobs))
(let ((ability-list (loop for ability-id in (get-mob-all-abilities actor)
for ability = (get-ability-type-by-id ability-id)
for func of-type function = (on-check-ai ability)
with check-result = nil
when (and func
(setf check-result (funcall func ability actor nearest-enemy nearest-ally)))
collect (list ability check-result))))
(if ability-list
ability-list
nil))
)
:on-invoke-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs check-result)
(declare (ignore hostile-mobs allied-mobs))
;; randomly choose one ability and invoke it
(let ((ability-list check-result)
(r 0))
(declare (type fixnum r)
(type list ability-list))
(setf r (random (length ability-list)))
(let ((ai-invoke-func (on-invoke-ai (first (nth r ability-list)))))
(declare (type function ai-invoke-func))
(log:info "AI-PACKAGE-USE-ABILITY: ~A [~A] decides to invoke ability ~A" (name actor) (id actor) (name (first (nth r ability-list))))
(funcall ai-invoke-func (first (nth r ability-list)) actor nearest-enemy nearest-ally (second (nth r ability-list))))
)
)))
(set-ai-package (make-instance 'ai-package :id +ai-package-use-item+
:priority 8
:on-check-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs)
(declare (ignore hostile-mobs allied-mobs))
(let ((item-list (loop for item-id in (inv actor)
for item = (get-item-by-id item-id)
for ai-check-func of-type function = (on-check-ai item)
for use-func of-type function = (on-use item)
with check-result = nil
when (and use-func
ai-check-func
(setf check-result (funcall ai-check-func actor item nearest-enemy nearest-ally)))
collect (list item check-result))))
(if item-list
item-list
nil))
)
:on-invoke-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs check-result)
(declare (ignore hostile-mobs allied-mobs))
;; randomly choose one item and invoke it
(let ((item-list check-result)
(r 0))
(declare (type fixnum r)
(type list item-list))
(setf r (random (length item-list)))
(let ((ai-invoke-func (ai-invoke-func (first (nth r item-list)))))
(log:info "AI-PACKAGE-USE-ITEM: ~A [~A] decides to use item ~A [~A]~%"
(name actor) (id actor) (name (first (nth r item-list))) (id (first (nth r item-list))))
(funcall ai-invoke-func actor (first (nth r item-list)) nearest-enemy nearest-ally (second (nth r item-list))))
)
)))
(set-ai-package (make-instance 'ai-package :id +ai-package-reload-ranged-weapon+
:priority 7
:on-check-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs)
(declare (ignore nearest-ally hostile-mobs allied-mobs))
(if (and (is-weapon-ranged actor)
(or (not (mob-can-shoot actor))
(and (not nearest-enemy)
(get-ranged-weapon-max-charges actor)
(< (get-ranged-weapon-charges actor) (get-ranged-weapon-max-charges actor)))))
t
nil)
)
:on-invoke-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs check-result)
(declare (ignore hostile-mobs allied-mobs nearest-enemy nearest-ally check-result))
;; if no bullets in magazine - reload
;; or
;; if no enemy in sight and the magazine is not full - reload it
(mob-reload-ranged-weapon actor)
)))
(set-ai-package (make-instance 'ai-package :id +ai-package-shoot-enemy+
:priority 7
:on-check-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs)
(declare (ignore nearest-ally hostile-mobs allied-mobs))
(if (and (is-weapon-ranged actor)
(mob-can-shoot actor)
nearest-enemy
(let ((tx 0) (ty 0) (tz 0)
(ex (x nearest-enemy)) (ey (y nearest-enemy)) (ez (z nearest-enemy)))
(declare (type fixnum tx ty tz ex ey ez))
(line-of-sight (x actor) (y actor) (z actor) (x nearest-enemy) (y nearest-enemy) (z nearest-enemy)
#'(lambda (dx dy dz prev-cell)
(declare (type fixnum dx dy dz))
(let ((exit-result t))
(block nil
(setf tx dx ty dy tz dz)
(unless (check-LOS-propagate dx dy dz prev-cell :check-projectile t)
(setf exit-result 'exit)
(return))
)
exit-result)))
(if (and (= tx ex)
(= ty ey)
(= tz ez))
t
nil)))
t
nil)
)
:on-invoke-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs check-result)
(declare (ignore hostile-mobs allied-mobs nearest-ally check-result))
;; if can shoot and there is an enemy in sight - shoot it
(mob-shoot-target actor nearest-enemy)
)))
(set-ai-package (make-instance 'ai-package :id +ai-package-follow-leader+
:priority 6
:on-check-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs)
(declare (ignore nearest-ally hostile-mobs allied-mobs))
(if (and (order actor)
(= (first (order actor)) +mob-order-follow+)
(not nearest-enemy))
(progn
;; a hack - while you check the conditions you also remove the order if the leader is dead
(let ((leader (get-mob-by-id (second (order actor)))))
(if (check-dead leader)
(progn
(setf (order actor) nil)
nil)
(progn
(if (and (< (get-distance (x actor) (y actor) (x leader) (y leader)) 8)
(> (get-distance (x actor) (y actor) (x leader) (y leader)) 2)
(or (level-cells-connected-p (level *world*) (x actor) (y actor) (z actor) (x leader) (y leader) (z leader)
(if (riding-mob-id actor)
(map-size (get-mob-by-id (riding-mob-id actor)))
(map-size actor))
(get-mob-move-mode actor)
:can-open-doors (can-open-doors actor))
(and (> (map-size actor) 1)
(ai-find-move-around actor (x leader) (y leader)))))
leader
nil)))
))
nil)
)
:on-invoke-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs check-result)
(declare (ignore nearest-enemy hostile-mobs allied-mobs nearest-ally))
(loop with leader = check-result
with move-failed-once = nil
with move-result = nil
while t do
(log:info "AI-PACKAGE-FOLLOW-LEADER: ~A [~A] (~A, ~A, ~A) wants to follow ~A [~A] at (~A, ~A, ~A)"
(name actor) (id actor) (x actor) (y actor) (z actor) (name leader) (id leader) (x leader) (y leader) (z leader))
;; set path-dst to the leader if there is no path-dst or it is different from the leader position
(when (or (null (path-dst actor))
(/= (first (path-dst actor)) (x leader))
(/= (second (path-dst actor)) (y leader))
(/= (third (path-dst actor)) (z leader)))
(ai-set-path-dst actor (x leader) (y leader) (z leader)))
;; exit (and move randomly) if the path-dst is still null after the previous set attempt
(when (null (path-dst actor))
(ai-mob-random-dir actor)
(loop-finish))
;; make a path to the destination target if there is no path plotted
(when (or (null (path actor))
(mob-ability-p actor +mob-abil-momentum+))
(ai-plot-path-to-dst actor (first (path-dst actor)) (second (path-dst actor)) (third (path-dst actor))))
;; make a step along the path to the path-dst
(setf move-result (ai-move-along-path actor))
(cond
;; if the move failed twice - move in a random direction
((and move-failed-once
(null move-result))
(ai-mob-random-dir actor)
(loop-finish))
;; if the move failed - reset path-dst and start anew
((and (null move-failed-once)
(null move-result))
(setf (path-dst actor) nil)
(setf move-failed-once t)
)
;; success
(t
(loop-finish))))
)))
(set-ai-package (make-instance 'ai-package :id +ai-package-approach-target+
:priority 6
:on-check-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs)
(declare (ignore nearest-enemy nearest-ally hostile-mobs allied-mobs))
(if (and (order actor)
(= (first (order actor)) +mob-order-target+))
(progn
;; a hack - while you check the conditions you also remove the order if the target is dead
(let ((target (get-mob-by-id (second (order actor)))))
(if (check-dead target)
(progn
(setf (order actor) nil)
nil)
(progn
(if (and (find (id target) (visible-mobs actor))
(or (level-cells-connected-p (level *world*) (x actor) (y actor) (z actor) (x target) (y target) (z target)
(if (riding-mob-id actor)
(map-size (get-mob-by-id (riding-mob-id actor)))
(map-size actor))
(get-mob-move-mode actor)
:can-open-doors (can-open-doors actor))
(and (> (map-size actor) 1)
(ai-find-move-around actor (x target) (y target)))))
target
nil)))
))
nil)
)
:on-invoke-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs check-result)
(declare (ignore nearest-enemy hostile-mobs allied-mobs nearest-ally))
(loop with target = check-result
with move-failed-once = nil
with move-result = nil
while t do
(log:info "AI-PACKAGE-APPROACH-TARGET: ~A [~A] (~A, ~A, ~A) wants to go to ~A [~A] at (~A, ~A, ~A)"
(name actor) (id actor) (x actor) (y actor) (z actor) (name target) (id target) (x target) (y target) (z target))
;; set path-dst to the target if there is no path-dst or it is different from the target position
(when (or (null (path-dst actor))
(/= (first (path-dst actor)) (x target))
(/= (second (path-dst actor)) (y target))
(/= (third (path-dst actor)) (z target)))
(ai-set-path-dst actor (x target) (y target) (z target)))
;; exit (and move randomly) if the path-dst is still null after the previous set attempt
(when (null (path-dst actor))
(ai-mob-random-dir actor)
(loop-finish))
;; make a path to the destination target if there is no path plotted
(when (or (null (path actor))
(mob-ability-p actor +mob-abil-momentum+))
(ai-plot-path-to-dst actor (first (path-dst actor)) (second (path-dst actor)) (third (path-dst actor))))
;; make a step along the path to the path-dst
(setf move-result (ai-move-along-path actor))
(cond
;; if the move failed twice - move in a random direction
((and move-failed-once
(null move-result))
(ai-mob-random-dir actor)
(loop-finish))
;; if the move failed - reset path-dst and start anew
((and (null move-failed-once)
(null move-result))
(setf (path-dst actor) nil)
(setf move-failed-once t)
)
;; success
(t
(loop-finish))))
)))
(set-ai-package (make-instance 'ai-package :id +ai-package-attack-nearest-enemy+
:priority 5
:on-check-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs)
(declare (ignore nearest-ally hostile-mobs allied-mobs))
(if (and nearest-enemy
(or (not (mob-get-ai-package actor +ai-package-cautious+))
(and (mob-get-ai-package actor +ai-package-cautious+)
(>= (strength actor) (strength nearest-enemy))))
(or (level-cells-connected-p (level *world*) (x actor) (y actor) (z actor) (x nearest-enemy) (y nearest-enemy) (z nearest-enemy)
(if (riding-mob-id actor)
(map-size (get-mob-by-id (riding-mob-id actor)))
(map-size actor))
(get-mob-move-mode actor)
:can-open-doors (can-open-doors actor))
(and (> (map-size actor) 1)
(ai-find-move-around actor (x nearest-enemy) (y nearest-enemy)))))
t
nil)
)
:on-invoke-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs check-result)
(declare (ignore hostile-mobs allied-mobs nearest-ally check-result))
(loop with target = nearest-enemy
with move-failed-once = nil
with move-result = nil
while t do
(log:info "AI-PACKAGE-ATTACK-NEAREST-ENEMY: ~A [~A] (~A, ~A, ~A) wants to attack ~A [~A] at (~A, ~A, ~A)"
(name actor) (id actor) (x actor) (y actor) (z actor) (name target) (id target) (x target) (y target) (z target))
;; set path-dst to the target if there is no path-dst or it is different from the target position
(when (or (null (path-dst actor))
(/= (first (path-dst actor)) (x target))
(/= (second (path-dst actor)) (y target))
(/= (third (path-dst actor)) (z target)))
(ai-set-path-dst actor (x target) (y target) (z target)))
;; exit (and move randomly) if the path-dst is still null after the previous set attempt
(when (null (path-dst actor))
(ai-mob-random-dir actor)
(loop-finish))
;; make a path to the destination target if there is no path plotted
(when (or (null (path actor))
(mob-ability-p actor +mob-abil-momentum+))
(ai-plot-path-to-dst actor (first (path-dst actor)) (second (path-dst actor)) (third (path-dst actor))))
;; make a step along the path to the path-dst
(setf move-result (ai-move-along-path actor))
(cond
;; if the move failed twice - move in a random direction
((and move-failed-once
(null move-result))
(ai-mob-random-dir actor)
(loop-finish))
;; if the move failed - reset path-dst and start anew
((and (null move-failed-once)
(null move-result))
(setf (path-dst actor) nil)
(setf move-failed-once t)
)
;; success
(t
(loop-finish))))
)))
(set-ai-package (make-instance 'ai-package :id +ai-package-return-corpses-to-portal+
:priority 6
:on-check-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs)
(declare (ignore nearest-ally hostile-mobs allied-mobs))
(if (and (or (eq (mission-type-id (mission (level *world*))) :mission-type-demonic-raid)
)
(not nearest-enemy)
(loop for item-id in (inv actor)
for item = (get-item-by-id item-id)
when (item-ability-p item +item-abil-corpse+)
do (return t)))
t
nil)
)
:on-invoke-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs check-result)
(declare (ignore nearest-enemy hostile-mobs allied-mobs nearest-ally check-result))
(log:info "AI-PACKAGE-RETURN-TO-PORTAL: Mob (~A, ~A, ~A) wants to return to the nearest portal" (x actor) (y actor) (z actor))
(block ai-function
;; iterate through all the portals to get to the nearest one
(when (null (path-dst actor))
(let ((rx 0)
(ry 0)
(rz 0)
(portal-list (stable-sort (loop for feature-id in (demonic-portals (level *world*))
for feature = (get-feature-by-id feature-id)
collect feature)
#'(lambda (a b)
(if (< (get-distance-3d (x actor) (y actor) (z actor) (x a) (y a) (z a))
(get-distance-3d (x actor) (y actor) (z actor) (x b) (y b) (z b)))
t
nil)))))
(declare (type fixnum rx ry rz))
(setf rx (x (first portal-list)) ry (y (first portal-list)) rz (z (first portal-list)))
(loop with portal-num = 0
while (or (get-terrain-type-trait (get-terrain-* (level *world*) rx ry rz) +terrain-trait-blocks-move+)
(and (get-terrain-type-trait (get-terrain-* (level *world*) (x actor) (y actor) (z actor)) +terrain-trait-water+)
(not (get-terrain-type-trait (get-terrain-* (level *world*) rx ry rz) +terrain-trait-water+))
(not (get-terrain-type-trait (get-terrain-* (level *world*) rx ry rz) +terrain-trait-blocks-move-floor+))
(not (mob-effect-p actor +mob-effect-flying+)))
(not (level-cells-connected-p (level *world*) (x actor) (y actor) (z actor) rx ry rz (if (riding-mob-id actor)
(map-size (get-mob-by-id (riding-mob-id actor)))
(map-size actor))
(get-mob-move-mode actor) :can-open-doors (can-open-doors actor))))
do
(log:debug "AI-PACKAGE-RETURN-TO-PORTAL: R (~A ~A ~A)~%TERRAIN = ~A, MOB ~A [~A], CONNECTED ~A"
rx ry rz
(get-terrain-* (level *world*) rx ry rz)
(get-mob-* (level *world*) rx ry rz) (if (get-mob-* (level *world*) rx ry rz)
(id (get-mob-* (level *world*) rx ry rz))
nil)
(level-cells-connected-p (level *world*) (x actor) (y actor) (z actor) rx ry rz (if (riding-mob-id actor)
(map-size (get-mob-by-id (riding-mob-id actor)))
(map-size actor))
(get-mob-move-mode actor) :can-open-doors (can-open-doors actor)))
(setf rx (x (nth portal-num portal-list)) ry (y (nth portal-num portal-list)) rz (z (nth portal-num portal-list)))
(incf portal-num)
(log:debug "AI-PACKAGE-RETURN-TO-PORTAL: NEW R (~A ~A ~A)" rx ry rz)
(when (>= portal-num (length portal-list))
(loop-finish))
finally (if (>= portal-num (length portal-list))
(progn
(setf (path-dst actor) nil)
(log:info "AI-PACKAGE-RETURN-TO-PORTAL: Mob cannot set the destination after exhausting all portals"))
(progn
(ai-set-path-dst actor rx ry rz)
(log:info "AI-PACKAGE-RETURN-TO-PORTAL: Mob's destination is set to (~A, ~A, ~A)"
(first (path-dst actor)) (second (path-dst actor)) (third (path-dst actor))))))
))
(let ((move-result nil))
;; exit (and move randomly) if the path-dst is still null after the previous set attempt
(when (null (path-dst actor))
(ai-mob-random-dir actor)
(return-from ai-function))
;; make a path to the destination target if there is no path plotted
(when (or (null (path actor))
(mob-ability-p actor +mob-abil-momentum+))
(ai-plot-path-to-dst actor (first (path-dst actor)) (second (path-dst actor)) (third (path-dst actor))))
;; make a step along the path to the path-dst
(setf move-result (ai-move-along-path actor))
(cond
;; if the move failed - move in a random direction
((null move-result)
(setf (path-dst actor) nil)
(ai-mob-random-dir actor)
(return-from ai-function)
)
;; success
(t
(return-from ai-function))))
))))
(set-ai-package (make-instance 'ai-package :id +ai-package-return-relic-to-portal+
:priority 6
:on-check-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs)
(declare (ignore nearest-enemy nearest-ally hostile-mobs allied-mobs))
(if (and (loop for item-id in (inv actor)
for item = (get-item-by-id item-id)
when (= (item-type item) +item-type-church-reliс+)
do (return t)))
t
nil)
)
:on-invoke-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs check-result)
(declare (ignore nearest-enemy hostile-mobs allied-mobs nearest-ally check-result))
(log:info "AI-PACKAGE-RETURN-TO-PORTAL: Mob (~A, ~A, ~A) wants to return to the nearest portal" (x actor) (y actor) (z actor))
(block ai-function
;; iterate through all the portals to get to the nearest one
(when (null (path-dst actor))
(let ((rx 0)
(ry 0)
(rz 0)
(portal-list (stable-sort (loop for feature-id in (demonic-portals (level *world*))
for feature = (get-feature-by-id feature-id)
collect feature)
#'(lambda (a b)
(if (< (get-distance-3d (x actor) (y actor) (z actor) (x a) (y a) (z a))
(get-distance-3d (x actor) (y actor) (z actor) (x b) (y b) (z b)))
t
nil)))))
(declare (type fixnum rx ry rz))
(setf rx (x (first portal-list)) ry (y (first portal-list)) rz (z (first portal-list)))
(loop with portal-num = 0
while (or (get-terrain-type-trait (get-terrain-* (level *world*) rx ry rz) +terrain-trait-blocks-move+)
(and (get-terrain-type-trait (get-terrain-* (level *world*) (x actor) (y actor) (z actor)) +terrain-trait-water+)
(not (get-terrain-type-trait (get-terrain-* (level *world*) rx ry rz) +terrain-trait-water+))
(not (get-terrain-type-trait (get-terrain-* (level *world*) rx ry rz) +terrain-trait-blocks-move-floor+))
(not (mob-effect-p actor +mob-effect-flying+)))
(not (level-cells-connected-p (level *world*) (x actor) (y actor) (z actor) rx ry rz (if (riding-mob-id actor)
(map-size (get-mob-by-id (riding-mob-id actor)))
(map-size actor))
(get-mob-move-mode actor) :can-open-doors (can-open-doors actor))))
do
(log:debug "AI-PACKAGE-RETURN-TO-PORTAL: R (~A ~A ~A) TERRAIN = ~A, MOB ~A [~A], CONNECTED ~A"
rx ry rz
(get-terrain-* (level *world*) rx ry rz)
(get-mob-* (level *world*) rx ry rz) (if (get-mob-* (level *world*) rx ry rz)
(id (get-mob-* (level *world*) rx ry rz))
nil)
(level-cells-connected-p (level *world*) (x actor) (y actor) (z actor) rx ry rz (if (riding-mob-id actor)
(map-size (get-mob-by-id (riding-mob-id actor)))
(map-size actor))
(get-mob-move-mode actor) :can-open-doors (can-open-doors actor)))
(setf rx (x (nth portal-num portal-list)) ry (y (nth portal-num portal-list)) rz (z (nth portal-num portal-list)))
(incf portal-num)
(log:debug "AI-PACKAGE-RETURN-TO-PORTAL: NEW R (~A ~A ~A)" rx ry rz)
(when (>= portal-num (length portal-list))
(loop-finish))
finally (if (>= portal-num (length portal-list))
(progn
(setf (path-dst actor) nil)
(log:info "AI-PACKAGE-RETURN-TO-PORTAL: Mob cannot set the destination after exhausting all portals"))
(progn
(ai-set-path-dst actor rx ry rz)
(log:info "AI-PACKAGE-RETURN-TO-PORTAL: Mob's destination is set to (~A, ~A, ~A)"
(first (path-dst actor)) (second (path-dst actor)) (third (path-dst actor))))))
))
(let ((move-result nil))
;; exit (and move randomly) if the path-dst is still null after the previous set attempt
(when (null (path-dst actor))
(ai-mob-random-dir actor)
(return-from ai-function))
;; make a path to the destination target if there is no path plotted
(when (or (null (path actor))
(mob-ability-p actor +mob-abil-momentum+))
(ai-plot-path-to-dst actor (first (path-dst actor)) (second (path-dst actor)) (third (path-dst actor))))
;; make a step along the path to the path-dst
(setf move-result (ai-move-along-path actor))
(cond
;; if the move failed - move in a random direction
((null move-result)
(setf (path-dst actor) nil)
(ai-mob-random-dir actor)
(return-from ai-function)
)
;; success
(t
(return-from ai-function))))
))))
(set-ai-package (make-instance 'ai-package :id +ai-package-escape-with-relic+
:priority 6
:on-check-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs)
(declare (ignore nearest-enemy nearest-ally hostile-mobs allied-mobs))
(if (and (loop for item-id in (inv actor)
for item = (get-item-by-id item-id)
when (= (item-type item) +item-type-church-reliс+)
do (return t)))
t
nil)
)
:on-invoke-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs check-result)
(declare (ignore nearest-enemy hostile-mobs allied-mobs nearest-ally check-result))
(log:info "AI-PACKAGE-ESCAPE-WITH-RELIC: Mob (~A, ~A, ~A) wants to return to the nearest map edge" (x actor) (y actor) (z actor))
(block ai-function
;; iterate through all the edges to get to the nearest one
(when (null (path-dst actor))
(let ((rx 0)
(ry 0)
(rz 0)
(edge-list (stable-sort (list (list 2 (y actor) 2)
(list (x actor) 2 2)
(list (- (array-dimension (terrain (level *world*)) 0) 2) (y actor) 2)
(list (x actor) (- (array-dimension (terrain (level *world*)) 1) 2) 2))
#'(lambda (a b)
(if (< (get-distance-3d (x actor) (y actor) (z actor) (first a) (second a) (third a))
(get-distance-3d (x actor) (y actor) (z actor) (first b) (second b) (third b)))
t
nil)))))
(declare (type fixnum rx ry rz))
(setf rx (first (first edge-list)) ry (second (first edge-list)) rz (third (first edge-list)))
(loop with edge-num = 0
while (or (get-terrain-type-trait (get-terrain-* (level *world*) rx ry rz) +terrain-trait-blocks-move+)
(and (get-terrain-type-trait (get-terrain-* (level *world*) (x actor) (y actor) (z actor)) +terrain-trait-water+)
(not (get-terrain-type-trait (get-terrain-* (level *world*) rx ry rz) +terrain-trait-water+))
(not (get-terrain-type-trait (get-terrain-* (level *world*) rx ry rz) +terrain-trait-blocks-move-floor+))
(not (mob-effect-p actor +mob-effect-flying+)))
(not (level-cells-connected-p (level *world*) (x actor) (y actor) (z actor) rx ry rz (if (riding-mob-id actor)
(map-size (get-mob-by-id (riding-mob-id actor)))
(map-size actor))
(get-mob-move-mode actor) :can-open-doors (can-open-doors actor))))
do
(log:debug "AI-PACKAGE-ESCAPE-WITH-RELIC: R (~A ~A ~A) TERRAIN = ~A, MOB ~A [~A], CONNECTED ~A"
rx ry rz
(get-terrain-* (level *world*) rx ry rz)
(get-mob-* (level *world*) rx ry rz) (if (get-mob-* (level *world*) rx ry rz)
(id (get-mob-* (level *world*) rx ry rz))
nil)
(level-cells-connected-p (level *world*) (x actor) (y actor) (z actor) rx ry rz (if (riding-mob-id actor)
(map-size (get-mob-by-id (riding-mob-id actor)))
(map-size actor))
(get-mob-move-mode actor) :can-open-doors (can-open-doors actor)))
(setf rx (first (nth edge-num edge-list)) ry (second (nth edge-num edge-list)) rz (third (nth edge-num edge-list)))
(incf edge-num)
(log:debug "AI-PACKAGE-ESCAPE-WITH-RELIC: NEW R (~A ~A ~A)" rx ry rz)
(when (>= edge-num (length edge-list))
(loop-finish))
finally (if (>= edge-num (length edge-list))
(progn
(setf (path-dst actor) nil)
(log:info "AI-PACKAGE-ESCAPE-WITH-RELIC: Mob cannot set the destination after exhausting all edges"))
(progn
(ai-set-path-dst actor rx ry rz)
(log:info "AI-PACKAGE-ESCAPE-WITH-RELIC: Mob's destination is set to (~A, ~A, ~A)"
(first (path-dst actor)) (second (path-dst actor)) (third (path-dst actor))))))
))
(let ((move-result nil))
;; exit (and move randomly) if the path-dst is still null after the previous set attempt
(when (null (path-dst actor))
(ai-mob-random-dir actor)
(return-from ai-function))
;; make a path to the destination target if there is no path plotted
(when (or (null (path actor))
(mob-ability-p actor +mob-abil-momentum+))
(ai-plot-path-to-dst actor (first (path-dst actor)) (second (path-dst actor)) (third (path-dst actor))))
;; make a step along the path to the path-dst
(setf move-result (ai-move-along-path actor))
(cond
;; if the move failed - move in a random direction
((null move-result)
(setf (path-dst actor) nil)
(ai-mob-random-dir actor)
(return-from ai-function)
)
;; success
(t
(return-from ai-function))))
))))
(set-ai-package (make-instance 'ai-package :id +ai-package-patrol-district+
:priority 4
:on-check-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs)
(declare (ignore nearest-ally hostile-mobs allied-mobs))
(if (and (not nearest-enemy)
(not (mob-ability-p actor +mob-abil-immobile+))
(not (mob-effect-p actor +mob-abil-immobile+))
)
t
nil)
)
:on-invoke-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs check-result)
(declare (ignore nearest-enemy hostile-mobs allied-mobs nearest-ally check-result))
(log:info "AI-PACKAGE-PATROL-DISTRICT: Mob (~A, ~A, ~A) wants to patrol the district" (x actor) (y actor) (z actor))
(block ai-function
;; take N attempts to find a random destination spot in the nearest sector that has not been visited recently if no path is set
(when (null (path-dst actor))
(let ((nearest-sector nil)
(rx 0)
(ry 0)
(rz 0)
(evil-mob (if (sense-evil-id actor) (get-mob-by-id (sense-evil-id actor)) nil))
(good-mob (if (sense-good-id actor) (get-mob-by-id (sense-good-id actor)) nil)))
(declare (type fixnum rx ry rz))
(cond
;; senses evil
(evil-mob
(setf nearest-sector (list (truncate (x evil-mob) 10) (truncate (y evil-mob) 10) (aref (memory-map actor) (truncate (x evil-mob) 10) (truncate (y evil-mob) 10)))))
;; senses good
(good-mob
(setf nearest-sector (list (truncate (x good-mob) 10) (truncate (y good-mob) 10) (aref (memory-map actor) (truncate (x good-mob) 10) (truncate (y good-mob) 10)))))
;; senses nothing
(t
(loop for dx from 0 below (array-dimension (memory-map actor) 0) do
(loop for dy from 0 below (array-dimension (memory-map actor) 1) do
(unless nearest-sector
(setf nearest-sector (list dx dy (aref (memory-map actor) dx dy))))
(cond
((< (aref (memory-map actor) dx dy)
(third nearest-sector))
(progn
(setf nearest-sector (list dx dy (aref (memory-map actor) dx dy)))))
((and (= (aref (memory-map actor) dx dy)
(third nearest-sector))
(< (get-distance (truncate (x actor) 10) (truncate (y actor) 10) dx dy)
(get-distance (truncate (x actor) 10) (truncate (y actor) 10) (first nearest-sector) (second nearest-sector))))
(progn
(setf nearest-sector (list dx dy (aref (memory-map actor) dx dy))))))
))))
(log:debug "AI-PACKAGE-PATROL-DISTRICT: NEAREST-SECTOR ~A vs CUR-SECTOR ~A" nearest-sector (list (truncate (x actor) 10) (truncate (y actor) 10)))
(setf rx (+ (* (first nearest-sector) 10) (random 10)))
(setf ry (+ (* (second nearest-sector) 10) (random 10)))
(setf rz (- (+ 5 (z actor)) (1+ (random 10))))
(log:debug "AI-PACKAGE-PATROL-DISTRICT: TERRAIN ~A" (get-terrain-* (level *world*) (x actor) (y actor) (z actor)))
(loop with attempt-num = 0
while (or (< rx 0) (< ry 0) (< rz 0)
(>= rx (array-dimension (terrain (level *world*)) 0))
(>= ry (array-dimension (terrain (level *world*)) 1))
(>= rz (array-dimension (terrain (level *world*)) 2))
(get-terrain-type-trait (get-terrain-* (level *world*) rx ry rz) +terrain-trait-blocks-move+)
(and (not (get-terrain-type-trait (get-terrain-* (level *world*) rx ry rz) +terrain-trait-water+))
(not (get-terrain-type-trait (get-terrain-* (level *world*) rx ry rz) +terrain-trait-blocks-move-floor+))
(not (mob-effect-p actor +mob-effect-flying+)))
(and (get-terrain-type-trait (get-terrain-* (level *world*) (x actor) (y actor) (z actor)) +terrain-trait-water+)
(not (get-terrain-type-trait (get-terrain-* (level *world*) rx ry rz) +terrain-trait-water+))
(not (get-terrain-type-trait (get-terrain-* (level *world*) rx ry rz) +terrain-trait-blocks-move-floor+))
(not (mob-effect-p actor +mob-effect-flying+)))
(not (level-cells-connected-p (level *world*) (x actor) (y actor) (z actor) rx ry rz (if (riding-mob-id actor)
(map-size (get-mob-by-id (riding-mob-id actor)))
(map-size actor))
(get-mob-move-mode actor) :can-open-doors (can-open-doors actor))))
do
(log:debug "AI-PACKAGE-PATROL-DISTRICT: R (~A ~A ~A) TERRAIN = ~A, MOB ~A [~A], CONNECTED ~A"
rx ry rz
(get-terrain-* (level *world*) rx ry rz)
(get-mob-* (level *world*) rx ry rz) (if (get-mob-* (level *world*) rx ry rz)
(id (get-mob-* (level *world*) rx ry rz))
nil)
(level-cells-connected-p (level *world*) (x actor) (y actor) (z actor) rx ry rz (if (riding-mob-id actor)
(map-size (get-mob-by-id (riding-mob-id actor)))
(map-size actor))
(get-mob-move-mode actor) :can-open-doors (can-open-doors actor)))
(setf rx (+ (* (first nearest-sector) 10) (random 10)))
(setf ry (+ (* (second nearest-sector) 10) (random 10)))
(setf rz (- (+ 5 (z actor)) (1+ (random 10))))
(incf attempt-num)
(log:debug "AI-PACKAGE-PATROL-DISTRICT: NEW R (~A ~A ~A)" rx ry rz)
(when (> attempt-num 200)
(loop-finish))
finally (if (> attempt-num 200)
(progn
(setf (path-dst actor) nil)
(log:info "AI-PACKAGE-PATROL-DISTRICT: Mob cannot set the destination after 200 attempts"))
(progn
(ai-set-path-dst actor rx ry rz)
(log:info "AI-PACKAGE-PATROL-DISTRICT: Mob's destination is randomly set to (~A, ~A, ~A)"
(first (path-dst actor)) (second (path-dst actor)) (third (path-dst actor))))))
))
(let ((move-result nil))
;; exit (and move randomly) if the path-dst is still null after the previous set attempt
(when (null (path-dst actor))
(ai-mob-random-dir actor)
(return-from ai-function))
;; make a path to the destination target if there is no path plotted
(when (or (null (path actor))
(mob-ability-p actor +mob-abil-momentum+))
(ai-plot-path-to-dst actor (first (path-dst actor)) (second (path-dst actor)) (third (path-dst actor))))
;; make a step along the path to the path-dst
(setf move-result (ai-move-along-path actor))
(cond
;; if the move failed - move in a random direction
((null move-result)
(setf (path-dst actor) nil)
(ai-mob-random-dir actor)
(return-from ai-function)
)
;; success
(t
(return-from ai-function))))
))))
(set-ai-package (make-instance 'ai-package :id +ai-package-find-random-location+
:priority 3
:on-check-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs)
(declare (ignore actor nearest-ally hostile-mobs allied-mobs))
(if (and (not nearest-enemy)
)
t
nil)
)
:on-invoke-ai #'(lambda (actor nearest-enemy nearest-ally hostile-mobs allied-mobs check-result)
(declare (ignore nearest-enemy hostile-mobs allied-mobs nearest-ally check-result))
(log:info "AI-PACKAGE-FIND-RANDOM-LOCATION: Mob (~A, ~A, ~A) wants to go to a random nearby place" (x actor) (y actor) (z actor))
(block ai-function
;; take N attempts to find a random destination spot if no path is set
(unless (path-dst actor)
(let ((rx (- (+ 10 (x actor))
(1+ (random 20))))
(ry (- (+ 10 (y actor))
(1+ (random 20))))
(rz (- (+ 5 (z actor))
(1+ (random 10))))
)
(declare (type fixnum rx ry rz))
(log:debug "AI-PACKAGE-FIND-RANDOM-LOCATION: TERRAIN ~A" (get-terrain-* (level *world*) (x actor) (y actor) (z actor)))
(loop while (or (< rx 0) (< ry 0) (< rz 0)
(>= rx (array-dimension (terrain (level *world*)) 0))
(>= ry (array-dimension (terrain (level *world*)) 1))
(>= rz (array-dimension (terrain (level *world*)) 2))
(get-terrain-type-trait (get-terrain-* (level *world*) rx ry rz) +terrain-trait-blocks-move+)
(and (get-terrain-type-trait (get-terrain-* (level *world*) (x actor) (y actor) (z actor)) +terrain-trait-water+)
(not (get-terrain-type-trait (get-terrain-* (level *world*) rx ry rz) +terrain-trait-water+))
(not (get-terrain-type-trait (get-terrain-* (level *world*) rx ry rz) +terrain-trait-blocks-move-floor+))
(not (mob-effect-p actor +mob-effect-flying+)))
(not (level-cells-connected-p (level *world*) (x actor) (y actor) (z actor) rx ry rz (if (riding-mob-id actor)
(map-size (get-mob-by-id (riding-mob-id actor)))
(map-size actor))
(get-mob-move-mode actor) :can-open-doors (can-open-doors actor)))
)
do
(log:debug "AI-PACKAGE-FIND-RANDOM-LOCATION: R (~A ~A ~A) TERRAIN = ~A, MOB ~A [~A], CONNECTED ~A"
rx ry rz
(get-terrain-* (level *world*) rx ry rz)
(get-mob-* (level *world*) rx ry rz) (if (get-mob-* (level *world*) rx ry rz)
(id (get-mob-* (level *world*) rx ry rz))
nil)
(level-cells-connected-p (level *world*) (x actor) (y actor) (z actor) rx ry rz (if (riding-mob-id actor)
(map-size (get-mob-by-id (riding-mob-id actor)))
(map-size actor))
(get-mob-move-mode actor) :can-open-doors (can-open-doors actor)))
(setf rx (- (+ 10 (x actor))
(1+ (random 20))))
(setf ry (- (+ 10 (y actor))
(1+ (random 20))))
(setf rz (- (+ 5 (z actor))
(1+ (random 10))))
(log:debug "AI-PACKAGE-FIND-RANDOM-LOCATION: NEW R (~A ~A ~A)~%" rx ry rz))
(ai-set-path-dst actor rx ry rz)
(log:info "AI-PACKAGE-FIND-RANDOM-LOCATION: Mob's destination is randomly set to (~A, ~A, ~A)"
(first (path-dst actor)) (second (path-dst actor)) (third (path-dst actor)))))
(let ((move-result nil))
;; exit (and move randomly) if the path-dst is still null after the previous set attempt
(when (null (path-dst actor))
(ai-mob-random-dir actor)
(return-from ai-function))
;; make a path to the destination target if there is no path plotted
(when (or (null (path actor))
(mob-ability-p actor +mob-abil-momentum+))
(ai-plot-path-to-dst actor (first (path-dst actor)) (second (path-dst actor)) (third (path-dst actor))))
;; make a step along the path to the path-dst
(setf move-result (ai-move-along-path actor))
(cond
;; if the move failed - move in a random direction
((null move-result)
(setf (path-dst actor) nil)
(ai-mob-random-dir actor)
(return-from ai-function)
)
;; success
(t
(return-from ai-function))))
))))
| 192,829
|
Common Lisp
|
.lisp
| 1,620
| 41.345679
| 233
| 0.257614
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
8cf238e08dd2afd11a810cc3ddd280e14b9b4a5e680e93de7713225e2e0b3530
| 2,942
|
[
-1
] |
2,943
|
ai-player.lisp
|
gwathlobal_CotD/src/ai/ai-player.lisp
|
(in-package :cotd)
(defmethod ai-function ((player player))
(log:info "~%AI-Function Player")
;(log:info (format nil "~%TIME-ELAPSED BEFORE: ~A~%" (- (get-internal-real-time) *time-at-end-of-player-turn*)))
(log:info "~%TIME-ELAPSED BEFORE: ~A" (- (get-internal-real-time) *time-at-end-of-player-turn*))
;; this should be done in this order for the lit-unlit tiles to be displayed properly
;; because update-visible-area actually sets the glyphs and colors of the player screen
;; while update-visible-mobs prepares the lit-unlit status of the tiles
(update-visible-mobs player)
(update-visible-area (level *world*) (x player) (y player) (z player))
(log:info "TIME-ELAPSED AFTER: ~A" (- (get-internal-real-time) *time-at-end-of-player-turn*))
(when (mob-ability-p player +mob-abil-strength-in-numbers+)
(loop with demons = 0
with bonus-per-demon = (if (mob-ability-p player +mob-abil-coward+)
20
10)
for mob-id of-type fixnum in (visible-mobs player)
for tmob = (get-mob-by-id mob-id)
when (and (mob-ability-p tmob +mob-abil-demon+)
(= (faction player) (faction tmob)))
do
(incf demons)
finally
(if (zerop demons)
(rem-mob-effect player +mob-effect-strength-in-numbers+)
(progn
(rem-mob-effect player +mob-effect-strength-in-numbers+)
(set-mob-effect player :effect-type-id +mob-effect-strength-in-numbers+ :actor-id (id player) :param1 (* demons bonus-per-demon))))))
;(format t "TIME-INSIDE PATH FUNCS: ~A~%" *ms-inside-path*)
;(setf *ms-inside-path* 0)
;; find the nearest enemy
;;(when (mob-ability-p *player* +mob-abil-detect-good+)
;; (sense-good))
;;(when (mob-ability-p *player* +mob-abil-detect-evil+)
;; (sense-evil))
(when (mob-ability-p *player* +mob-abil-detect-unnatural+)
(sense-unnatural))
(when (and (or (= (loyal-faction *player*) +faction-type-demons+)
(= (loyal-faction *player*) +faction-type-satanists+))
(or (eql (mission-type-id (mission (level *world*))) :mission-type-demonic-thievery)
(eql (mission-type-id (mission (level *world*))) :mission-type-demonic-raid)))
(sense-portal))
(when (and (or (= (loyal-faction *player*) +faction-type-demons+)
(= (loyal-faction *player*) +faction-type-angels+)
(= (loyal-faction *player*) +faction-type-church+)
(= (loyal-faction *player*) +faction-type-satanists+)
(= (loyal-faction *player*) +faction-type-military+))
(or (eql (mission-type-id (mission (level *world*))) :mission-type-demonic-thievery)
(eql (mission-type-id (mission (level *world*))) :mission-type-celestial-retrieval)))
(sense-relic))
(when (and (or (= (loyal-faction *player*) +faction-type-demons+)
(= (loyal-faction *player*) +faction-type-angels+)
(= (loyal-faction *player*) +faction-type-church+)
(= (loyal-faction *player*) +faction-type-satanists+)
(= (loyal-faction *player*) +faction-type-military+))
(or (eql (mission-type-id (mission (level *world*))) :mission-type-demonic-conquest)
(eql (mission-type-id (mission (level *world*))) :mission-type-celestial-purge)
(eql (mission-type-id (mission (level *world*))) :mission-type-military-conquest)))
(sense-sigil))
(when (and (or (= (loyal-faction *player*) +faction-type-demons+)
(= (loyal-faction *player*) +faction-type-angels+)
(= (loyal-faction *player*) +faction-type-church+)
(= (loyal-faction *player*) +faction-type-satanists+)
(= (loyal-faction *player*) +faction-type-military+))
(eql (mission-type-id (mission (level *world*))) :mission-type-celestial-sabotage))
(sense-machines))
(when (and (or (= (loyal-faction *player*) +faction-type-demons+)
(= (loyal-faction *player*) +faction-type-angels+)
(= (loyal-faction *player*) +faction-type-church+)
(= (loyal-faction *player*) +faction-type-satanists+)
(= (loyal-faction *player*) +faction-type-military+))
(eql (mission-type-id (mission (level *world*))) :mission-type-military-sabotage))
(sense-stockpiles))
;; print out the items on the player's tile
(loop for item-id in (get-items-* (level *world*) (x *player*) (y *player*) (z *player*))
for item = (get-item-by-id item-id)
with n = 0
do
(when (zerop n)
(add-message "You see " (sdl:color :r 100 :g 100 :b 100)))
(when (not (zerop n))
(add-message ", " (sdl:color :r 100 :g 100 :b 100)))
(add-message (format nil "~A" (prepend-article +article-a+ (visible-name item))) (sdl:color :r 100 :g 100 :b 100))
(incf n)
finally (when (not (zerop n))
(add-message (format nil ".~%") (sdl:color :r 100 :g 100 :b 100))))
(make-output *current-window*)
;; if player is fearing somebody & there is an enemy nearby
;; wait for a meaningful action and move randomly instead
(when (mob-effect-p *player* +mob-effect-fear+)
(log:info "AI-FUNCTION: ~A [~A] is under effects of fear." (name player) (id player))
(let ((nearest-enemy nil))
(loop for mob-id of-type fixnum in (visible-mobs *player*)
for mob = (get-mob-by-id mob-id)
with vis-mob-type = nil
do
;; inspect a mob appearance
(setf vis-mob-type (get-mob-type-by-id (face-mob-type-id mob)))
;; however is you are of the same faction, you know who is who
(when (= (faction *player*) (faction mob))
(setf vis-mob-type (get-mob-type-by-id (mob-type mob))))
(when (not (get-faction-relation (faction *player*) (faction vis-mob-type)))
;; find the nearest hostile mob
(unless nearest-enemy
(setf nearest-enemy mob))
(when (< (get-distance (x mob) (y mob) (x *player*) (y *player*))
(get-distance (x nearest-enemy) (y nearest-enemy) (x *player*) (y *player*)))
(setf nearest-enemy mob))
))
(when nearest-enemy
(log:info "AI-FUNCTION: ~A [~A] fears ~A [~A]." (name player) (id player) (name nearest-enemy) (id nearest-enemy))
(setf (can-move-if-possessed player) t)
(loop while (can-move-if-possessed player) do
(get-input-player))
(ai-mob-flee *player* nearest-enemy)
(return-from ai-function nil))))
;; if the player is confused and the RNG is right
;; wait for a meaningful action and move randomly instead
(when (and (mob-effect-p player +mob-effect-confuse+)
(zerop (random 2)))
(log:info "AI-FUNCTION: ~A [~A] is under effects of confusion." (name player) (id player))
(setf (can-move-if-possessed player) t)
(loop while (can-move-if-possessed player) do
(get-input-player))
(print-visible-message (x player) (y player) (z player) (level *world*)
(format nil "~A is confused. " (capitalize-name (name player))))
(ai-mob-random-dir *player*)
(return-from ai-function nil))
;; if the player is irradiated and the RNG is right
;; wait for a meaningful action and wait a turn instead
(when (and (mob-effect-p player +mob-effect-irradiated+)
(< (random 100) (* 2 (param1 (get-effect-by-id (mob-effect-p player +mob-effect-irradiated+))))))
(log:info "AI-FUNCTION: ~A [~A] is under effects of irradiation." (name player) (id player))
(setf (can-move-if-possessed player) t)
(loop while (can-move-if-possessed player) do
(get-input-player))
(print-visible-message (x player) (y player) (z player) (level *world*)
(format nil "~A feels sick. " (capitalize-name (name player))))
(move-mob player 5)
(return-from ai-function nil))
;; if possessed & unable to revolt - wait till the player makes a meaningful action
;; then skip and invoke the master AI
(log:info "AI-FUNCTION: MASTER ID ~A, SLAVE ID ~A" (master-mob-id player) (slave-mob-id player))
(when (master-mob-id player)
(log:info "AI-FUNCTION: ~A [~A] is being possessed by ~A [~A]." (name player) (id player) (name (get-mob-by-id (master-mob-id player))) (master-mob-id player))
(setf (x player) (x (get-mob-by-id (master-mob-id player))) (y player) (y (get-mob-by-id (master-mob-id player))) (z player) (z (get-mob-by-id (master-mob-id player))))
(setf (can-move-if-possessed player) t)
(loop while (can-move-if-possessed player) do
(get-input-player))
(let ((rebel-chance-level (cond
((mob-ability-value (get-mob-by-id (master-mob-id player)) +mob-abil-can-possess+) (mob-ability-value (get-mob-by-id (master-mob-id player)) +mob-abil-can-possess+))
((mob-ability-p (get-mob-by-id (master-mob-id player)) +mob-abil-ghost-possess+) 1)
(t 0))
))
(if (and (not (zerop rebel-chance-level))
(zerop (random (* *possessed-revolt-chance* rebel-chance-level))))
(progn
(log:info "AI-FUNCTION: ~A [~A] revolts against ~A [~A]." (name player) (id player) (name (get-mob-by-id (master-mob-id player))) (master-mob-id player))
(print-visible-message (x player) (y player) (z player) (level *world*)
(format nil "~A revolts against ~A. " (capitalize-name (name player)) (name (get-mob-by-id (master-mob-id player))) ))
(ai-mob-random-dir (get-mob-by-id (master-mob-id player)))
(setf (x player) (x (get-mob-by-id (master-mob-id player))) (y player) (y (get-mob-by-id (master-mob-id player))) (z player) (z (get-mob-by-id (master-mob-id player))))
(setf (path (get-mob-by-id (master-mob-id player))) nil)
(return-from ai-function nil)
)
(progn
(log:info "AI-FUNCTION: ~A [~A] was unable to revolt against ~A [~A]." (name player) (id player) (name (get-mob-by-id (master-mob-id player))) (master-mob-id player))
(ai-function (get-mob-by-id (master-mob-id player)))
(when (master-mob-id player)
(setf (x player) (x (get-mob-by-id (master-mob-id player))) (y player) (y (get-mob-by-id (master-mob-id player))) (z player) (z (get-mob-by-id (master-mob-id player)))))
(make-act player +normal-ap+)
(return-from ai-function nil)))
))
;; if player possesses somebody & the slave revolts
;; wait for a meaningful action and move randomly instead
(when (slave-mob-id player)
(let ((rebel-chance-level (cond
((mob-ability-value player +mob-abil-can-possess+) (mob-ability-value player +mob-abil-can-possess+))
((mob-ability-p player +mob-abil-ghost-possess+) (if (and (slave-mob-id player)
(mob-ability-p (get-mob-by-id (slave-mob-id player)) +mob-abil-undead+))
0
1))
(t 0))
))
(when (and (not (zerop rebel-chance-level))
(zerop (random (* *possessed-revolt-chance* rebel-chance-level))))
(log:info "AI-FUNCTION: ~A [~A] possesses ~A [~A], but the slave revolts." (name player) (id player) (name (get-mob-by-id (slave-mob-id player))) (slave-mob-id player))
(setf (can-move-if-possessed player) t)
(loop while (can-move-if-possessed player) do
(get-input-player))
(print-visible-message (x player) (y player) (z player) (level *world*)
(format nil "~A revolts against ~A. " (capitalize-name (name (get-mob-by-id (slave-mob-id player)))) (name player)))
(ai-mob-random-dir player)
(return-from ai-function nil)
))
)
;; player is able to move freely
;; pester the player until it makes some meaningful action that can trigger the event chain
(loop until (made-turn player) do
(setf (can-move-if-possessed player) nil)
(get-input-player))
(setf *time-at-end-of-player-turn* (get-internal-real-time))
)
| 13,098
|
Common Lisp
|
.lisp
| 203
| 50.630542
| 198
| 0.571686
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
0131c479f2a2d54e6530241fe330d706c0c5ff253a98113c51da4318eff4c2fc
| 2,943
|
[
-1
] |
2,944
|
ai-npc.lisp
|
gwathlobal_CotD/src/ai/ai-npc.lisp
|
(in-package :cotd)
(defmethod ai-function ((mob mob))
;(declare (optimize (speed 3)))
;;(setf *ms-inside-path-start* (get-internal-real-time))
;;(format t "~%TIME-ELAPSED AI ~A [~A] BEFORE : ~A~%" (name mob) (id mob) (- (get-internal-real-time) *time-at-end-of-player-turn*))
(log:info "~%AI-Function Computer ~A [~A] (~A ~A ~A)" (name mob) (id mob) (x mob) (y mob) (z mob))
;; skip and invoke the master AI
(when (master-mob-id mob)
(log:info "AI-FUNCTION: ~A [~A] is being possessed by ~A [~A], skipping its turn." (name mob) (id mob) (name (get-mob-by-id (master-mob-id mob))) (master-mob-id mob))
(make-act mob +normal-ap+)
(return-from ai-function nil))
(when (and (path-dst mob)
(= (x mob) (first (path-dst mob)))
(= (y mob) (second (path-dst mob)))
(= (z mob) (third (path-dst mob))))
(setf (path-dst mob) nil))
;; skip turn if being ridden
(when (mounted-by-mob-id mob)
(log:info "AI-FUNCTION: ~A [~A] is being ridden by ~A [~A], moving according to the direction." (name mob) (id mob) (name (get-mob-by-id (mounted-by-mob-id mob))) (mounted-by-mob-id mob))
(move-mob mob (x-y-into-dir 0 0))
(return-from ai-function nil)
)
(update-visible-mobs mob)
(update-visible-items mob)
(when (mob-ability-p mob +mob-abil-strength-in-numbers+)
(loop with demons = 0
with bonus-per-demon = (if (mob-ability-p mob +mob-abil-coward+)
20
10)
for mob-id of-type fixnum in (visible-mobs mob)
for tmob = (get-mob-by-id mob-id)
when (and (mob-ability-p tmob +mob-abil-demon+)
(= (faction mob) (faction tmob)))
do
(incf demons)
finally
(if (zerop demons)
(rem-mob-effect mob +mob-effect-strength-in-numbers+)
(progn
(rem-mob-effect mob +mob-effect-strength-in-numbers+)
(set-mob-effect mob :effect-type-id +mob-effect-strength-in-numbers+ :actor-id (id mob) :param1 (* demons bonus-per-demon))))))
(setf (aref (memory-map mob) (truncate (x mob) 10) (truncate (y mob) 10)) (player-game-time (level *world*)))
;; if the mob is blind - move in random direction
(when (mob-effect-p mob +mob-effect-blind+)
(log:info "AI-FUNCTION: ~A [~A] is blind, moving in random direction." (name mob) (id mob))
(ai-mob-random-dir mob)
(setf (path mob) nil)
(return-from ai-function nil))
;; if the mob is confused - 33% chance to move in random direction
(when (and (mob-effect-p mob +mob-effect-confuse+)
(zerop (random 2)))
(log:info "AI-FUNCTION: ~A [~A] is confused, moving in random direction.~%" (name mob) (id mob))
(ai-mob-random-dir mob)
(setf (path mob) nil)
(return-from ai-function nil))
;; if the mob is heavily irradiated - (2% * irradiation power) chance to take no action
(when (and (mob-effect-p mob +mob-effect-irradiated+)
(< (random 100) (* 2 (param1 (get-effect-by-id (mob-effect-p mob +mob-effect-irradiated+))))))
(log:info "AI-FUNCTION: ~A [~A] is irradiated, loses turn.~%" (name mob) (id mob))
(print-visible-message (x mob) (y mob) (z mob) (level *world*)
(format nil "~A is sick. " (capitalize-name (prepend-article +article-the+ (name mob))))
:color sdl:*white*
:tags (list (when (if-cur-mob-seen-through-shared-vision *player*)
:singlemind)))
(move-mob mob 5)
(setf (path mob) nil)
(return-from ai-function nil))
;; if the mob possesses smb, there is a chance that the slave will revolt and move randomly
(let ((rebel-chance-level (cond
((mob-ability-value mob +mob-abil-can-possess+) (mob-ability-value mob +mob-abil-can-possess+))
((mob-ability-p mob +mob-abil-ghost-possess+) (if (and (slave-mob-id mob)
(mob-ability-p (get-mob-by-id (slave-mob-id mob)) +mob-abil-undead+))
0
1))
(t 0))
))
(when (and (slave-mob-id mob)
(not (zerop rebel-chance-level))
(zerop (random (* *possessed-revolt-chance* rebel-chance-level))))
(log:info "AI-FUNCTION: ~A [~A] is revolting against ~A [~A]." (name (get-mob-by-id (slave-mob-id mob))) (slave-mob-id mob) (name mob) (id mob))
(when (and (check-mob-visible mob :observer *player*)
(or (mob-effect-p mob +mob-effect-reveal-true-form+)
(get-faction-relation (faction mob) (faction *player*))))
(print-visible-message (x mob) (y mob) (z mob) (level *world*)
(format nil "~A revolts against ~A. " (capitalize-name (prepend-article +article-the+ (name (get-mob-by-id (slave-mob-id mob))))) (prepend-article +article-the+ (name mob)))
:color sdl:*white*
:tags (list (when (if-cur-mob-seen-through-shared-vision *player*)
:singlemind))))
(setf (path mob) nil)
(ai-mob-random-dir mob)
(return-from ai-function nil)
)
)
;; calculate a list of hostile & allied mobs
(let ((hostile-mobs nil)
(allied-mobs nil)
(nearest-enemy nil)
(nearest-ally nil))
(loop for mob-id of-type fixnum in (visible-mobs mob)
for target-mob = (get-mob-by-id mob-id)
with vis-mob-type = nil
do
;; inspect a mob appearance
(setf vis-mob-type (get-mob-type-by-id (face-mob-type-id target-mob)))
;; however is you are of the same faction, you know who is who
(when (= (faction mob) (faction target-mob))
(setf vis-mob-type (get-mob-type-by-id (mob-type target-mob))))
(if (or (get-faction-relation (faction mob) (faction vis-mob-type))
(and (mounted-by-mob-id target-mob)
(get-faction-relation (faction mob) (faction (get-mob-by-id (mounted-by-mob-id target-mob))))))
(progn
(pushnew mob-id allied-mobs)
;; find the nearest allied mob
(unless nearest-ally
(setf nearest-ally target-mob))
(when (< (get-distance (x target-mob) (y target-mob) (x mob) (y mob))
(get-distance (x nearest-ally) (y nearest-ally) (x mob) (y mob)))
(setf nearest-ally target-mob))
)
(progn
(pushnew mob-id hostile-mobs)
;; find the nearest hostile mob
(unless nearest-enemy
(setf nearest-enemy target-mob))
(when (< (get-distance (x target-mob) (y target-mob) (x mob) (y mob))
(get-distance (x nearest-enemy) (y nearest-enemy) (x mob) (y mob)))
(setf nearest-enemy target-mob))
)))
;; if the mob is feared, move away from the nearest enemy
(when (and nearest-enemy (mob-effect-p mob +mob-effect-fear+))
(log:info "AI-FUNCTION: ~A [~A] is in fear with an enemy ~A [~A] in sight." (name mob) (id mob) (name nearest-enemy) (id nearest-enemy))
(ai-mob-flee mob nearest-enemy)
(return-from ai-function))
;; find and apply the AI package
(let ((ai-package-array (make-array (list (1+ +ai-priority-always+)) :initial-element ())))
;;(format t "~%TIME-ELAPSED AI ~A [~A] before ai package sort: ~A~%" (name mob) (id mob) (- (get-internal-real-time) *time-at-end-of-player-turn*))
;; sort all AI packages according to priorities (and do not include 'never' packages)
(loop for ai-package-id being the hash-key in (ai-packages mob)
for ai-package = (get-ai-package-by-id ai-package-id)
when (/= (priority ai-package) +ai-priority-never+)
do
(setf (aref ai-package-array (priority ai-package)) (pushnew ai-package (aref ai-package-array (priority ai-package)))))
;; adding objective packages
(when (get-ai-based-on-faction (loyal-faction mob) (mission-type-id (mission (level *world*))))
(loop for ai-objective-package-id in (get-ai-based-on-faction (loyal-faction mob) (mission-type-id (mission (level *world*)))) do
(setf (aref ai-package-array (priority (get-ai-package-by-id ai-objective-package-id)))
(pushnew (get-ai-package-by-id ai-objective-package-id) (aref ai-package-array (priority (get-ai-package-by-id ai-objective-package-id)))))))
(unless *cotd-release*
(log:info "AI-FUNCTION: ai-package-array")
(loop for priority from 0 below (length ai-package-array)
when (aref ai-package-array priority)
do
(log:info " Priority ~A. ~A." priority (loop for ai-package in (aref ai-package-array priority)
collect (format nil "~A " (id ai-package))))))
;;(format t "~%TIME-ELAPSED AI ~A [~A] after ai package sort: ~A~%" (name mob) (id mob) (- (get-internal-real-time) *time-at-end-of-player-turn*))
;; invoke all 'always' packages if possible
(loop for ai-package in (aref ai-package-array +ai-priority-always+)
for ai-check-func of-type function = (on-check-ai ai-package)
for ai-invoke-func of-type function = (on-invoke-ai ai-package)
with check-result = nil
when (and ai-check-func
ai-invoke-func
(setf check-result (funcall ai-check-func mob nearest-enemy nearest-ally hostile-mobs allied-mobs)))
do
;;(format t "~%TIME-ELAPSED AI ~A [~A] after ai check func [~A]: ~A~%" (name mob) (id mob) (id ai-package) (- (get-internal-real-time) *time-at-end-of-player-turn*))
(funcall ai-invoke-func mob nearest-enemy nearest-ally hostile-mobs allied-mobs check-result)
;;(format t "~%TIME-ELAPSED AI ~A [~A] after ai invoke func [~A]: ~A~%" (name mob) (id mob) (id ai-package) (- (get-internal-real-time) *time-at-end-of-player-turn*))
)
;; for each priority check try to invoke a random ai-package in this priority
(loop for priority from 9 downto 1
for ai-package-list = (aref ai-package-array priority)
with r of-type fixnum = 0
when ai-package-list
do
;; find all applicable AI packages on this priority level
(setf ai-package-list (loop for ai-package in ai-package-list
for ai-check-func of-type function = (on-check-ai ai-package)
with check-result = nil
when (and ai-check-func
(setf check-result (funcall ai-check-func mob nearest-enemy nearest-ally hostile-mobs allied-mobs)))
collect (list ai-package check-result)))
;;(format t "~%TIME-ELAPSED AI ~A [~A] after ai check funcs with priority ~A: ~A~%" (name mob) (id mob) priority (- (get-internal-real-time) *time-at-end-of-player-turn*))
(when ai-package-list
;; if there are several of them choose one randomly
(setf r (random (length ai-package-list)))
(let ((ai-invoke-func (on-invoke-ai (first (nth r ai-package-list))))
(check-result (second (nth r ai-package-list))))
(declare (type function ai-invoke-func))
(funcall ai-invoke-func mob nearest-enemy nearest-ally hostile-mobs allied-mobs check-result)
;;(format t "~%TIME-ELAPSED AI ~A [~A] after ai invoke func [~A]: ~A~%" (name mob) (id mob) (id (first (nth r ai-package-list))) (- (get-internal-real-time) *time-at-end-of-player-turn*))
(return-from ai-function))))
)
;; if there are no hostile mobs move randomly
;; pester the AI until it makes some meaningful action
(ai-mob-random-dir mob))
;;(format t "~%TIME-ELAPSED AI ~A [~A] AFTER : ~A~%" (name mob) (id mob) (- (get-internal-real-time) *time-at-end-of-player-turn*))
)
| 13,119
|
Common Lisp
|
.lisp
| 197
| 49.862944
| 209
| 0.546793
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
5eada2b2623afc4f16d32d43013d9d801fd0c5677ceb4c08c93f8df3db8ada02
| 2,944
|
[
-1
] |
2,945
|
ai-packages.lisp
|
gwathlobal_CotD/src/ai/ai-packages.lisp
|
(in-package :cotd)
(defclass ai-package ()
((id :initarg :id :accessor id)
(priority :initform 0 :initarg :priority :accessor priority)
(on-check-ai :initform nil :initarg :on-check-ai :accessor on-check-ai) ;; a function that checks for the AI package if it can and should be invoked now
(on-invoke-ai :initform nil :initarg :on-invoke-ai :accessor on-invoke-ai) ;; a function that invokes the AI package
))
(defun set-ai-package (ai-package)
(when (>= (id ai-package) (length *ai-packages*))
(adjust-array *ai-packages* (list (1+ (id ai-package)))))
(setf (aref *ai-packages* (id ai-package)) ai-package))
(defun get-ai-package-by-id (ai-package-id)
(aref *ai-packages* ai-package-id))
| 717
|
Common Lisp
|
.lisp
| 13
| 52
| 156
| 0.700428
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
b52361fc3b3e19f448b378f2aa9cc5acd2a5904223c5006f5ed04bb30c200aa5
| 2,945
|
[
-1
] |
2,946
|
ai-common.lisp
|
gwathlobal_CotD/src/ai/ai-common.lisp
|
(in-package :cotd)
(defgeneric ai-function (mob))
(defparameter *ms-inside-path* 0)
(defparameter *ms-inside-path-start* 0)
(defun check-move-for-ai (mob dx dy dz cx cy cz &key (final-dst nil))
(declare (optimize (speed 3))
(type fixnum dx dy dz cx cy cz))
(let ((sx 0) (sy 0) (move-result nil)
(map-size (if (riding-mob-id mob)
(map-size (get-mob-by-id (riding-mob-id mob)))
(map-size mob))))
(declare (type fixnum sx sy map-size))
;; calculate the coords of the mob's NE corner
(setf sx (- dx (truncate (1- map-size) 2)))
(setf sy (- dy (truncate (1- map-size) 2)))
(loop for nx of-type fixnum from sx below (+ sx map-size) do
(loop for ny of-type fixnum from sy below (+ sy map-size) do
;; cant move beyond level borders
(when (or (< nx 0) (< ny 0) (< dz 0) (>= nx (array-dimension (terrain (level *world*)) 0)) (>= ny (array-dimension (terrain (level *world*)) 1)) (>= dz (array-dimension (terrain (level *world*)) 2)))
(return-from check-move-for-ai nil))
(setf move-result nil)
;; can move if not impassable
(when (not (get-terrain-type-trait (get-terrain-* (level *world*) nx ny dz) +terrain-trait-blocks-move+))
(setf move-result t))
;; can move if a door (not important if open or closed)
(when (get-terrain-type-trait (get-terrain-* (level *world*) nx ny dz) +terrain-trait-openable-door+)
(setf move-result t))
;; can move if a window & you can open windows
(when (and (get-terrain-type-trait (get-terrain-* (level *world*) nx ny dz) +terrain-trait-openable-window+)
(mob-ability-p mob +mob-abil-open-close-window+))
(setf move-result t))
(unless move-result
(return-from check-move-for-ai nil))
(setf move-result nil)
;; can go anywhere horizontally or directly up/below if the current tile is water
(when (and (or (= (- cz dz) 0)
(and (/= (- cz dz) 0)
(= nx cx)
(= ny cy))
)
(get-terrain-type-trait (get-terrain-* (level *world*) cx cy cz) +terrain-trait-water+)
(get-terrain-type-trait (get-terrain-* (level *world*) nx ny dz) +terrain-trait-water+))
(setf move-result t))
;; can go from down to up if the source tile is water and the landing tile has floor and is not directly above the source tile
(when (and (> (- dz cz) 0)
(not (and (= cx nx)
(= cy ny)))
(not (get-terrain-type-trait (get-terrain-* (level *world*) nx ny dz) +terrain-trait-blocks-move+))
(get-terrain-type-trait (get-terrain-* (level *world*) nx ny cz) +terrain-trait-blocks-move+)
(get-terrain-type-trait (get-terrain-* (level *world*) cx cy cz) +terrain-trait-water+)
(not (get-terrain-type-trait (get-terrain-* (level *world*) cx cy (1+ cz)) +terrain-trait-blocks-move-floor+)))
(setf move-result t))
;; can go from up to down if the landing tile is water and is not directly below the source tile
(when (and (< (- dz cz) 0)
(or (/= (- dx cx) 0)
(/= (- dy cy) 0))
(get-terrain-type-trait (get-terrain-* (level *world*) nx ny dz) +terrain-trait-water+)
(not (get-terrain-type-trait (get-terrain-* (level *world*) nx ny cz) +terrain-trait-blocks-move-floor+))
(not (get-terrain-type-trait (get-terrain-* (level *world*) nx ny cz) +terrain-trait-water+)))
(setf move-result t))
;; can go from down to up if the source tile is slope up and the landing tile has floor and is not directly above the source tile
(when (and (> (- dz cz) 0)
(not (and (= cx nx)
(= cy ny)))
(get-terrain-type-trait (get-terrain-* (level *world*) nx ny dz) +terrain-trait-blocks-move-floor+)
(get-terrain-type-trait (get-terrain-* (level *world*) nx ny cz) +terrain-trait-blocks-move+)
(get-terrain-type-trait (get-terrain-* (level *world*) cx cy cz) +terrain-trait-slope-up+)
(not (get-terrain-type-trait (get-terrain-* (level *world*) cx cy (1+ cz)) +terrain-trait-blocks-move-floor+)))
(setf move-result t))
;; can go from up to down if the landing tile is floor and is not directly below the source tile
(when (and (< (- dz cz) 0)
(or (/= (- dx cx) 0)
(/= (- dy cy) 0))
(get-terrain-type-trait (get-terrain-* (level *world*) nx ny dz) +terrain-trait-blocks-move-floor+)
(not (get-terrain-type-trait (get-terrain-* (level *world*) nx ny cz) +terrain-trait-blocks-move-floor+)))
(setf move-result t))
;; can go horizontally if the landing tile has opaque floor and there is no final destination
;; or can go horizontally if the landing tile has opaque floor and it is NOT the final distination
;; or can go horizontally if the landing tile is the final destination (and we do not care about the floor)
(when (or (and (= (- dz cz) 0)
(get-terrain-type-trait (get-terrain-* (level *world*) nx ny dz) +terrain-trait-blocks-move-floor+)
(not final-dst))
(and (= (- dz cz) 0)
final-dst
(get-terrain-type-trait (get-terrain-* (level *world*) nx ny dz) +terrain-trait-blocks-move-floor+)
(not (and (= nx (first final-dst))
(= ny (second final-dst))
(= dz (third final-dst)))))
(and (= (- dz cz) 0)
final-dst
(and (= nx (first final-dst))
(= ny (second final-dst))
(= dz (third final-dst)))))
(setf move-result t))
;; you can go anywhere horizontaly or directly up/down if you are climbing and there is a wall or floor next to you
(when (and (not move-result)
(mob-effect-p mob +mob-effect-climbing-mode+)
(or (= (- cz dz) 0)
(and (/= (- cz dz) 0)
(= nx cx)
(= ny cy))
)
(check-move-along-z cx cy cz nx ny dz)
(funcall #'(lambda ()
(let ((result nil))
(check-surroundings nx ny nil #'(lambda (dx dy)
(when (and (not (get-terrain-type-trait (get-terrain-* (level *world*) dx dy dz) +terrain-trait-not-climable+))
(or (get-terrain-type-trait (get-terrain-* (level *world*) dx dy dz) +terrain-trait-blocks-move-floor+)
(get-terrain-type-trait (get-terrain-* (level *world*) dx dy dz) +terrain-trait-blocks-move+)))
(setf result t))))
result))))
(setf move-result t))
;; you can go anywhere horizontaly or directly up/down if you are flying
(when (and (not move-result)
(mob-effect-p mob +mob-effect-flying+)
(or (= (- cz dz) 0)
(and (/= (- cz dz) 0)
(= nx cx)
(= ny cy))
)
(check-move-along-z cx cy cz nx ny dz)
)
(setf move-result t))
(when (and (not move-result)
(mob-effect-p mob +mob-effect-flying+)
(> (map-size mob) 1)
(/= (- cz dz) 0)
(check-move-along-z nx ny cz nx ny dz)
)
(setf move-result t))
;; you can not go directly up if the you are under effect of gravity pull
(when (and (and (< (- cz dz) 0)
(= nx cx)
(= ny cy))
(mob-effect-p mob +mob-effect-gravity-pull+))
(setf move-result nil))
(unless move-result
(return-from check-move-for-ai nil))
))
t))
(defun ai-find-move-around (mob tx ty)
(declare (optimize (speed 3))
(type fixnum tx ty))
(let* ((cell-list)
(map-size (map-size mob))
(half-size (truncate (1- map-size) 2)))
(declare (type list cell-list)
(type fixnum map-size half-size))
;; collect all cells that constitute the perimeter of the mob around the target cell
(loop for off of-type fixnum from (- half-size) to (+ half-size)
for x of-type fixnum = (+ tx off)
for y-up of-type fixnum = (- ty half-size)
for y-down of-type fixnum = (+ ty half-size)
for y of-type fixnum = (+ ty off)
for x-up of-type fixnum = (- tx half-size)
for x-down of-type fixnum = (+ tx half-size)
do
(push (cons x y-up) cell-list)
(push (cons x y-down) cell-list)
(push (cons x-up y) cell-list)
(push (cons x-down y) cell-list))
;(format t "AI-FIND-MOVE-AROUND: Cell list with duplicates ~A~%" cell-list)
;; remove all duplicates from the list
(setf cell-list (remove-duplicates cell-list :test #'(lambda (a b)
(let ((x1 (car a))
(x2 (car b))
(y1 (cdr a))
(y2 (cdr b)))
(declare (type fixnum x1 x2 y1 y2))
(if (and (= x1 x2)
(= y1 y2))
t
nil)))))
;(format t "AI-FIND-MOVE-AROUND: Cell list without duplicates ~A~%" cell-list)
;; sort them so that the closest to the mob are checked first
(setf cell-list (stable-sort cell-list #'(lambda (a b)
(if (< (get-distance (x mob) (y mob) (car a) (cdr a))
(get-distance (x mob) (y mob) (car b) (cdr b)))
t
nil))))
;;(format t "AI-FIND-MOVE-AROUND: Cell list sorted ~A~%" cell-list)
;; check each cell for passability
(loop for (dx . dy) in cell-list
when (and (level-cells-connected-p (level *world*) dx dy (z mob) (x mob) (y mob) (z mob) map-size (get-mob-move-mode mob) :can-open-doors (can-open-doors mob))
(check-move-for-ai mob dx dy (z mob) dx dy (z mob)))
do
;;(format t "AI-FIND-MOVE-AROUND: Return value ~A~%" (cons dx dy))
(return-from ai-find-move-around (list dx dy (z mob))))
;;(format t "AI-FIND-MOVE-AROUND: Return value ~A~%" nil)
nil))
(defun ai-mob-flee (mob nearest-enemy)
(unless nearest-enemy
(return-from ai-mob-flee nil))
(log:info "~A [~A] tries to flee away from ~A [~A]." (name mob) (id mob) (name nearest-enemy) (id nearest-enemy))
(let ((step-x 0)
(step-y 0))
(setf (path mob) nil)
(setf (path-dst mob) nil)
(setf step-x (if (> (x nearest-enemy) (x mob)) -1 1))
(setf step-y (if (> (y nearest-enemy) (y mob)) -1 1))
(when (and (zerop (random 10))
(mob-ability-p mob +mob-abil-human+))
(if (check-mob-visible mob :observer *player* :complete-check t)
(generate-sound mob (x mob) (y mob) (z mob) 100 #'(lambda (str)
(format nil "~A cries: \"Help! Help!\"~A. " (capitalize-name (prepend-article +article-the+ (visible-name mob))) str))
:force-sound t)
(generate-sound mob (x mob) (y mob) (z mob) 100 #'(lambda (str)
(format nil "Somebody cries: \"Help! Help!\"~A. " str))
:force-sound t))
;(print-visible-message (x mob) (y mob) (z mob) (level *world*) (format nil "~A cries: \"Help! Help!\" " (visible-name mob)))
)
(if (mob-ability-p mob +mob-abil-immobile+)
(move-mob mob 5)
;; if can't move away - try any random direction
(unless (move-mob mob (x-y-into-dir step-x step-y))
(log:info "~A [~A] could not flee. Try to move randomly." (name mob) (id mob))
(ai-mob-random-dir mob)))
))
(defun ai-mob-random-dir (mob)
(log:info "~A [~A] tries to move randomly." (name mob) (id mob))
(if (mob-ability-p mob +mob-abil-immobile+)
(move-mob mob 5)
(loop for dir = (+ (random 9) 1)
until (move-mob mob dir))))
(defun thread-path-loop ()
(loop while t do
(bt:with-lock-held ((path-lock *world*))
(if (and (< (cur-mob-path *world*) (length (mob-id-list (level *world*)))) (not (made-turn *player*)))
(progn
(when (and (not (eq *player* (get-mob-by-id (cur-mob-path *world*))))
(not (dead= (get-mob-by-id (cur-mob-path *world*))))
(not (path (get-mob-by-id (cur-mob-path *world*)))))
(log:debug "Mob ~A [~A] calculates paths" (name (get-mob-by-id (cur-mob-path *world*))) (id (get-mob-by-id (cur-mob-path *world*))))
(let* ((mob (get-mob-by-id (cur-mob-path *world*)))
(rx (- (+ 10 (x mob))
(1+ (random 20))))
(ry (- (+ 10 (y mob))
(1+ (random 20))))
(rz (- (+ 5 (z mob))
(1+ (random 10))))
)
(declare (type fixnum rx ry))
;; if the mob destination is not set, choose a random destination
(unless (path-dst mob)
(loop while (or (< rx 0) (< ry 0) (< rz 0) (>= rx (array-dimension (terrain (level *world*)) 0)) (>= ry (array-dimension (terrain (level *world*)) 1)) (>= rz (array-dimension (terrain (level *world*)) 2))
(get-terrain-type-trait (get-terrain-* (level *world*) rx ry rz) +terrain-trait-blocks-move+)
;(not (get-terrain-type-trait (get-terrain-* (level *world*) rx ry rz) +terrain-trait-blocks-move-floor+))
(and (get-terrain-type-trait (get-terrain-* (level *world*) (x mob) (y mob) (z mob)) +terrain-trait-water+)
(not (get-terrain-type-trait (get-terrain-* (level *world*) rx ry rz) +terrain-trait-water+))
(not (get-terrain-type-trait (get-terrain-* (level *world*) rx ry rz) +terrain-trait-blocks-move-floor+))
(not (mob-effect-p mob +mob-effect-flying+)))
(not (level-cells-connected-p (level *world*) (x mob) (y mob) (z mob) rx ry rz (if (riding-mob-id mob)
(map-size (get-mob-by-id (riding-mob-id mob)))
(map-size mob))
(get-mob-move-mode mob) :can-open-doors (can-open-doors mob)))
)
do
(setf rx (- (+ 10 (x mob))
(1+ (random 20))))
(setf ry (- (+ 10 (y mob))
(1+ (random 20))))
(setf rz (- (+ 5 (z mob))
(1+ (random 10)))))
(setf (path-dst mob) (list rx ry rz)))
(when (level-cells-connected-p (level *world*) (x mob) (y mob) (z mob) (first (path-dst mob)) (second (path-dst mob)) (third (path-dst mob)) (if (riding-mob-id mob)
(map-size (get-mob-by-id (riding-mob-id mob)))
(map-size mob))
(get-mob-move-mode mob) :can-open-doors (can-open-doors mob))
(log:debug "Mob (~A, ~A, ~A) wants to go to (~A, ~A, ~A)" (x mob) (y mob) (z mob) (first (path-dst mob)) (second (path-dst mob)) (third (path-dst mob)))
(ai-plot-path-to-dst mob (first (path-dst mob)) (second (path-dst mob)) (third (path-dst mob)))
))
)
(incf (cur-mob-path *world*))
(log:debug "cur-mob-path - ~A" (cur-mob-path *world*)))
(progn
(log:debug "Done calculating paths")
(setf (cur-mob-path *world*) (length (mob-id-list (level *world*))))
(bt:condition-wait (path-cv *world*) (path-lock *world*)))
))))
(defun ai-set-path-dst (actor tx ty tz)
(log:debug "level-connected-p = ~A, level-connected actor = ~A, level-connected target = ~A"
(level-cells-connected-p (level *world*) (x actor) (y actor) (z actor) tx ty tz (if (riding-mob-id actor)
(map-size (get-mob-by-id (riding-mob-id actor)))
(map-size actor))
(get-mob-move-mode actor) :can-open-doors (can-open-doors actor))
(get-level-connect-map-value (level *world*) (x actor) (y actor) (z actor) (if (riding-mob-id actor)
(map-size (get-mob-by-id (riding-mob-id actor)))
(map-size actor))
(get-mob-move-mode actor))
(get-level-connect-map-value (level *world*) tx ty tz (if (riding-mob-id actor)
(map-size (get-mob-by-id (riding-mob-id actor)))
(map-size actor))
(get-mob-move-mode actor)))
(cond
((= +connect-room-none+ (get-level-connect-map-value (level *world*) (x actor) (y actor) (z actor) (if (riding-mob-id actor)
(map-size (get-mob-by-id (riding-mob-id actor)))
(map-size actor))
(get-mob-move-mode actor)))
(log:info "level-connected actor = ~A, need to move randomly" +connect-room-none+)
(setf (path-dst actor) nil)
(setf (path actor) nil))
((level-cells-connected-p (level *world*) (x actor) (y actor) (z actor) tx ty tz (if (riding-mob-id actor)
(map-size (get-mob-by-id (riding-mob-id actor)))
(map-size actor))
(get-mob-move-mode actor) :can-open-doors (can-open-doors actor))
(setf (path-dst actor) (list tx ty tz))
(setf (path actor) nil))
((and (> (map-size actor) 1)
(ai-find-move-around actor tx ty))
(setf (path-dst actor) (ai-find-move-around actor tx ty))
(setf (path actor) nil))
(t
(setf (path-dst actor) nil)
(setf (path actor) nil))))
(defun ai-plot-path-to-dst (actor tx ty tz)
(let ((path nil))
(when (level-cells-connected-p (level *world*) (x actor) (y actor) (z actor) tx ty tz (if (riding-mob-id actor)
(map-size (get-mob-by-id (riding-mob-id actor)))
(map-size actor))
(get-mob-move-mode actor) :can-open-doors (can-open-doors actor))
(log:info "Mob (~A, ~A, ~A) wants to go to (~A, ~A, ~A)" (x actor) (y actor) (z actor) tx ty tz)
;;(format t "~%TIME-ELAPSED AI ~A [~A] before AI-PLOT-PATH-TO-DST:: ~A~%" (name actor) (id actor) (- (get-internal-real-time) *time-at-end-of-player-turn*))
(setf path (a-star (list (x actor) (y actor) (z actor)) (list tx ty tz)
#'(lambda (dx dy dz cx cy cz)
;; checking for impassable objects
(check-move-for-ai actor dx dy dz cx cy cz :final-dst (list tx ty tz))
)
#'(lambda (dx dy dz)
;; a magic hack here - as values of more than 10 give an unexplainable slowdown
(* (get-terrain-type-trait (get-terrain-* (level *world*) dx dy dz) +terrain-trait-move-cost-factor+)
(move-spd (get-mob-type-by-id (mob-type actor)))
1/10))))
(pop path)
(log:info "Set mob path - ~A" path)
;;(format t "~%TIME-ELAPSED AI ~A [~A] after AI-PLOT-PATH-TO-DST:: ~A~%" (name actor) (id actor) (- (get-internal-real-time) *time-at-end-of-player-turn*))
(setf (path actor) path)
)))
(defun ai-move-along-path (actor)
(when (path actor)
(let ((step) (step-x) (step-y) (step-z) (move-result nil))
(log:info "Mob path - ~A" (path actor))
(setf step (pop (path actor)))
(setf step-x (- (first step) (x actor)))
(setf step-y (- (second step) (y actor)))
(setf step-z (- (third step) (z actor)))
(setf move-result (check-move-on-level actor (first step) (second step) (third step)))
(unless move-result
(log:info "Can't move to target - (~A ~A ~A)" (first step) (second step) (third step))
(setf (path actor) nil)
(setf (path-dst actor) nil)
(return-from ai-move-along-path nil))
(unless (x-y-into-dir step-x step-y)
(log:info "Wrong direction supplied (~A ~A)" (first step) (second step))
(setf (path actor) nil)
(setf (path-dst actor) nil)
(return-from ai-move-along-path nil))
;; check if there is somebody on the target square
(log:debug "MOVE-RESULT = ~A, NOT T = ~A, FACTION-RELATION = ~A, NOT LOVES-INFIGHTING = ~A, BLESS+BLESSED = ~A"
move-result
(not (eq move-result t))
(if (and move-result
(not (eq move-result t))
(eq (first move-result) :mobs))
(get-faction-relation (faction actor) (get-visible-faction (first (second move-result))))
nil)
(not (mob-ability-p actor +mob-abil-loves-infighting+))
(if (and move-result
(not (eq move-result t))
(eq (first move-result) :mobs))
(or (not (mob-ability-p actor +mob-abil-blessing-touch+))
(and (mob-ability-p actor +mob-abil-blessing-touch+)
(mob-effect-p (first (second move-result)) +mob-effect-blessed+)
(mob-ability-p (first (second move-result)) +mob-abil-can-be-blessed+))
(and (mob-ability-p actor +mob-abil-blessing-touch+)
(not (mob-ability-p (first (second move-result)) +mob-abil-can-be-blessed+))))
nil))
;;(format t "~%TIME-ELAPSED AI ~A [~A] before AI-MOVE-AlONG-PATH: ~A~%" (name actor) (id actor) (- (get-internal-real-time) *time-at-end-of-player-turn*))
(when (and move-result
(not (eq move-result t))
(eq (first move-result) :mobs)
(get-faction-relation (faction actor) (get-visible-faction (first (second move-result))))
(not (mob-ability-p actor +mob-abil-loves-infighting+))
(or (not (mob-ability-p actor +mob-abil-blessing-touch+))
(and (mob-ability-p actor +mob-abil-blessing-touch+)
(mob-effect-p (first (second move-result)) +mob-effect-blessed+)
(mob-ability-p (first (second move-result)) +mob-abil-can-be-blessed+))
(and (mob-ability-p actor +mob-abil-blessing-touch+)
(not (mob-ability-p (first (second move-result)) +mob-abil-can-be-blessed+))))
)
(let ((final-cell nil))
(when (and (path-dst actor)
(>= (get-distance-3d (x actor) (y actor) (z actor) (first (path-dst actor)) (second (path-dst actor)) (third (path-dst actor)))
2))
;;(format t "~%TIME-ELAPSED AI ~A [~A] inside AI-MOVE-AlONG-PATH: ~A~%" (name actor) (id actor) (- (get-internal-real-time) *time-at-end-of-player-turn*))
(check-surroundings (x actor) (y actor) nil #'(lambda (dx dy)
(when (eq (check-move-on-level actor dx dy (z actor)) t)
(unless final-cell
(setf final-cell (list dx dy)))
(when (< (get-distance-3d dx dy (z actor)
(first (path-dst actor)) (second (path-dst actor)) (third (path-dst actor)))
(get-distance-3d (first final-cell) (second final-cell) (z actor)
(first (path-dst actor)) (second (path-dst actor)) (third (path-dst actor))))
(setf final-cell (list dx dy)))))))
(when final-cell
(setf step-x (- (first final-cell) (x actor)))
(setf step-y (- (second final-cell) (y actor))))
))
(setf move-result (move-mob actor (x-y-into-dir step-x step-y) :dir-z step-z))
(log:info "PATH-DST ~A, MOB (~A ~A ~A), MOVE-RESULT ~A" (path-dst actor) (x actor) (y actor) (z actor) move-result)
;;(format t "~%TIME-ELAPSED AI ~A [~A] after AI-MOVE-AlONG-PATH: ~A~%" (name actor) (id actor) (- (get-internal-real-time) *time-at-end-of-player-turn*))
(if move-result
(progn
(when (and (path-dst actor)
(= (x actor) (first (path-dst actor)))
(= (y actor) (second (path-dst actor)))
(= (z actor) (third (path-dst actor))))
(setf (path-dst actor) nil))
(return-from ai-move-along-path t))
(progn
(log:info "Move failed ~A" move-result)
(setf (path-dst actor) nil)
(setf (path actor) nil)
(return-from ai-move-along-path nil)))
)
nil))
| 28,823
|
Common Lisp
|
.lisp
| 425
| 44.835294
| 221
| 0.459679
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
60908b0e91753e15f520531f68b9241d50265cac40e79881d803b46cc9700ef3
| 2,946
|
[
-1
] |
2,947
|
cotd.asd
|
gwathlobal_CotD/src/cotd.asd
|
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
(defpackage cotd
(:use :common-lisp :asdf)
(:export
:cotd-main
:make-exec))
(in-package :cotd)
(defsystem cotd
:name "The City of the Damned"
:description "A roguelike battle of Angels and Demons in the streets of a Human city."
:version "1.0.5"
:author "Gwathlobal"
:depends-on (lispbuilder-sdl bordeaux-threads defenum cl-store log4cl)
:components
((:file "astar")
(:file "glyph-globals")
(:file "globals")
(:file "world-globals")
(:file "colored-text")
(:file "message-box")
(:file "options")
(:file "game-events/game-events")
(:file "file-storage")
(:file "world" :depends-on ("globals"))
(:file "save-load-game" :depends-on ("world"))
(:file "factions" :depends-on ("globals"))
(:file "mobs" :depends-on ("globals"))
(:file "abilities" :depends-on ("globals"))
(:file "effects" :depends-on ("globals"))
(:file "terrain" :depends-on ("globals"))
(:file "lvl-features" :depends-on ("globals"))
(:file "items" :depends-on ("globals"))
(:file "cards" :depends-on ("globals"))
(:file "gods" :depends-on ("globals"))
(:file "los-fov" :depends-on ("globals" "world" "mobs"))
(:file "hearing" :depends-on ("los-fov"))
(:file "animations" :depends-on ("globals"))
(:file "base-methods" :depends-on ("message-box" "mobs" "world" "abilities" "terrain" "animations" "lvl-features" "los-fov"))
(:file "character-dump" :depends-on ("base-methods"))
(:module "buildings" :depends-on ("globals")
:components ((:file "buildings")
(:file "init-common-building-types" :depends-on ("buildings"))
(:file "init-normal-building-types" :depends-on ("buildings"))
(:file "init-ruined-building-types" :depends-on ("buildings"))
(:file "init-corrupted-building-types" :depends-on ("buildings"))
(:file "init-hell-building-types" :depends-on ("buildings"))))
(:file "level-city" :depends-on ("buildings"))
(:file "level-test" :depends-on ("base-methods"))
(:module "level-modifiers"
:components ((:file "level-modifier")
(:file "init-lvl-mod-controlled-by" :depends-on ("level-modifier"))
(:file "init-lvl-mod-sector-feat" :depends-on ("level-modifier"))
(:file "init-lvl-mod-sector-item" :depends-on ("level-modifier"))
(:file "init-lvl-mod-time-of-day" :depends-on ("level-modifier"))
(:file "init-lvl-mod-weather" :depends-on ("level-modifier"))
(:file "init-lvl-mod-player-placement" :depends-on ("level-modifier"))
(:file "init-lvl-mod-misc" :depends-on ("level-modifier"))))
(:file "mission-type")
(:file "highscores")
(:file "mission")
(:file "world-sector")
(:file "world-map")
(:file "win-condition")
(:file "generate-level")
(:file "random-scenario")
(:file "campaign-effects")
(:file "campaign-command")
(:file "init-win-conditions" :depends-on ("win-condition"))
(:file "init-world-sectors" :depends-on ("world-map"))
(:file "init-faction-types" :depends-on ("base-methods"))
(:file "init-mob-types" :depends-on ("base-methods"))
(:file "init-feature-types" :depends-on ("base-methods"))
(:file "init-terrain-types" :depends-on ("base-methods"))
(:file "init-item-types" :depends-on ("base-methods"))
(:file "init-card-types" :depends-on ("base-methods"))
(:file "init-gods" :depends-on ("base-methods"))
(:file "init-mission-types" :depends-on ("mission-type"))
(:file "init-campaign-effect-types" :depends-on ("campaign-effects"))
(:file "init-campaign-commands" :depends-on ("campaign-command"))
(:file "game-state")
(:module "windows" :depends-on ("base-methods")
:components ((:file "window-classes")
(:file "window-methods" :depends-on ("window-classes"))
(:file "window-display-msg" :depends-on ("window-classes"))
(:file "window-main-menu" :depends-on ("window-methods"))
(:file "window-select-faction" :depends-on ("window-methods"))
(:file "window-messages" :depends-on ("window-methods"))
(:file "window-level" :depends-on ("window-methods"))
(:file "window-map-select" :depends-on ("window-level"))
(:file "window-loading" :depends-on ("window-methods"))
(:file "window-character" :depends-on ("window-methods"))
(:file "window-select-obj" :depends-on ("window-methods"))
(:file "window-game-over" :depends-on ("window-methods"))
(:file "window-help" :depends-on ("window-methods"))
(:file "window-custom-scenario" :depends-on ("window-methods"))
(:file "window-inventory" :depends-on ("window-methods"))
(:file "window-input-str" :depends-on ("window-methods"))
(:file "window-highscores" :depends-on ("window-methods"))
(:file "window-settings" :depends-on ("window-methods"))
(:file "window-journal" :depends-on ("window-methods"))
(:file "window-campaign" :depends-on ("window-methods"))
(:file "window-load-game" :depends-on ("window-methods"))
(:file "window-campaign-over" :depends-on ("window-methods"))))
(:module "ai" :depends-on ("base-methods" "windows")
:components ((:file "ai-common")
(:file "ai-packages" :depends-on ("ai-common"))
(:file "ai-npc" :depends-on ("ai-common"))
(:file "ai-player" :depends-on ("ai-common"))
(:file "init-ai-packages" :depends-on ("ai-packages"))))
(:file "game-events/init-game-events-common" :depends-on ("game-events/game-events" "windows"))
(:file "game-events/init-game-events-demonic-attack" :depends-on ("game-events/game-events" "windows"))
(:file "game-events/init-game-events-demonic-raid" :depends-on ("game-events/game-events" "windows"))
(:file "game-events/init-game-events-demonic-steal" :depends-on ("game-events/game-events" "windows"))
(:file "game-events/init-game-events-demonic-conquest" :depends-on ("game-events/game-events" "windows"))
(:file "game-events/init-game-events-military-conquest" :depends-on ("game-events/game-events" "windows"))
(:file "game-events/init-game-events-military-raid" :depends-on ("game-events/game-events" "windows"))
(:file "game-events/init-game-events-angelic-steal" :depends-on ("game-events/game-events" "windows"))
(:file "game-events/init-game-events-eliminate-satanists" :depends-on ("game-events/game-events" "windows"))
(:file "game-events/init-game-events-angelic-sabotage" :depends-on ("game-events/game-events" "windows"))
(:file "game-events/init-game-events-military-sabotage" :depends-on ("game-events/game-events" "windows"))
(:file "game-events/init-game-events-campaign-win" :depends-on ("game-events/game-events" "windows"))
(:file "game-events/init-game-events-campaign" :depends-on ("game-events/game-events" "windows"))
(:file "init-animation-types" :depends-on ("animations" "windows"))
(:file "init-ability-types" :depends-on ("base-methods" "windows"))
(:file "init-effect-types" :depends-on ("base-methods" "windows"))
(:file "cotd")
))
| 7,769
|
Common Lisp
|
.asd
| 127
| 50.251969
| 131
| 0.59269
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
e295aa7ec4ac64bd50e16685a0688f4de140096750307422722f67faa4fc84f0
| 2,947
|
[
-1
] |
3,002
|
military_scout.txt
|
gwathlobal_CotD/src/data/descriptions/military_scout.txt
|
SCOUT, THE MILITARY
- The military arrives towards the end of the battle for the City. It is allied with the citizens but opposes both angels and demons.
- The military is comprised of five units: Soldiers, Scouts, Sergeants, Machine-gunners, and Chaplains. All of them are capable of ranged combat but do not gain power whatsoever.
- Soldiers are armed with single-shot rifles and need to reload every other turn.
- Sergeants wield six-round revolvers that deal less damage than a rifle but do not need to be reloaded so often.
- Machine-gunners carry a light machine gun capable of firing the whole magazine in one turn. Alas, its accuracy leaves to be desired.
- Chaplains are also armed with six-round revolvers but, more importantly, are able to pray to reveal disguised supernatural enemies or to grant divine protection to allies (similar to priests). They can also issue a "Follow me" order to lead other troops across the battlefield.
- You start as a scout who has a more powerful rifle than soldiers, are able to reveal the true form of a single enemy, call for an artillery strike and enter the battle riding a horse.
- Scouts start alone but compensate that with unsurpassed speed. Be careful, though - unlike a Chaplain, you do not have protection from possession. So if a demon traps you in your own body, the you will have to travel with that demon until you are killed with it or freed from it by some angel.
| 1,436
|
Common Lisp
|
.l
| 9
| 157.444444
| 296
| 0.789916
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
34d1f7a04b728cc6a642eb8466fbb2fcbc21b510a789e347c50ca9bc9ebe6667
| 3,002
|
[
-1
] |
3,003
|
primordials_eater.txt
|
gwathlobal_CotD/src/data/descriptions/primordials_eater.txt
|
EATER OF THE DEAD, PRIMORDIALS
- In the taiga bogs and forests of the East live strange creatures that had walked the Earth before any ape could be called sapient. Now they slumber, waiting for the time when the cycle of humankind is complete and they are able to reign the land once more. The natives fear, worship and offer sacrifices to them. But when the outsiders from beyond Earth arrived in the City, the primordials rose once more to drive the invaders out of what they consider their own domain.
- You can start as an Eater of the dead, a tentacled monster, weakened by the millennia of inactivity.
- You are able to feast on the corpses of the fallen to gain HP and power and mutate yourself gaining various abilities.
- You equally hate everybody in the City and are hated by everyone.
- Your goal is to destroy all angels and demons.
| 851
|
Common Lisp
|
.l
| 6
| 140
| 474
| 0.793144
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
d6e0bcea8761365a59dca6438e5fc468e816c7b16326634795302eedd451f67a
| 3,003
|
[
-1
] |
3,004
|
military_chaplain.txt
|
gwathlobal_CotD/src/data/descriptions/military_chaplain.txt
|
CHAPLAIN, THE MILITARY
- The military arrives towards the end of the battle for the City. It is allied with the citizens but opposes both angels and demons.
- The military is comprised of five units: Soldiers, Scouts, Sergeants, Machine-gunners, and Chaplains. All of them are capable of ranged combat but do not gain power whatsoever.
- Soldiers are armed with single-shot rifles and need to reload every other turn.
- Scouts have a more powerful rifle than soldiers, are able to reveal the true form of a single enemy, call for an artillery strike and enter the battle riding a horse.
- Sergeants wield six-round revolvers that deal less damage than a rifle but do not need to be reloaded so often.
- Machine-gunners carry a light machine gun capable of firing the whole magazine in one turn. Alas, its accuracy leaves to be desired.
- You start as a chaplain are also armed with six-round revolvers but, more importantly, are able to pray to reveal disguised supernatural enemies or to grant divine protection to allies (similar to priests). They can also issue a "Follow me" order to lead other troops across the battlefield.
- Chaplains are accompanied by a host of loyal troops.
| 1,196
|
Common Lisp
|
.l
| 9
| 130.666667
| 294
| 0.791246
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
4566b7c96cb7fd13c7621f1e6b3ce2e797be83bf01d6ea5cd7fa1c4b9e4c46df
| 3,004
|
[
-1
] |
3,005
|
lostsoul.txt
|
gwathlobal_CotD/src/data/descriptions/lostsoul.txt
|
THE LOST SOUL
- You were the one who triggered the whole invasion. The satanists have sacrificed your body to open the gates to Hell, but your soul lingered in this world.
- You start as a frail ghost that will be attacked by everybody and need only one hit to die.
- As a ghost, you can pass through walls and solid obstacles and turn yourself invisible for a short time.
- You can also possess humans and dead bodies from a distance. Your possession ability is improved as compared to the demons because you retain all the traits and capabilities of your host as well as its faction alliances. As a human citizen, you will be hated by demons but blessed by angels, as a zombie you will be hated by angels but tolerated by demons.
- Your task is to find the Book of Rituals and recite certain passages from it while standing on the sacrificial circle, the place of your death, to find the final rest.
| 907
|
Common Lisp
|
.l
| 6
| 149.333333
| 359
| 0.790466
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
f2989c0a9bf4d7fd420f238d9cc1004941e397258a8277020876084262ec4042
| 3,005
|
[
-1
] |
3,006
|
criminals.txt
|
gwathlobal_CotD/src/data/descriptions/criminals.txt
|
THE CRIMINALS
- The criminals (who are opposed to the citizens and the military, but will not attack the Communion) are kept mainly in the prison (except for the Thief).
- You may start as the Thief, who is found somewhere on the rooftops of the City.
- Though the Thief is armed with a knife, his primary weapons are stealth and an ability to climb walls. Unlike all other characters, he is able to evade any conflict by hiding in the shadows or getting some place he can not be reached.
- Note that the citizens, the Communion units, and the military radiate light, while the Demons do not.
- As the Thief, you always start at night but a new day will come eventually that will severely hinder your ability to hide.
- To win, grab enough gold and get to the edge of the map to leave this accursed City.
- But beware - the Thief is rather frail and is not immune to possession.
| 887
|
Common Lisp
|
.l
| 8
| 108.875
| 237
| 0.775
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
d94312e12dab7fcf1e03649d3a0a6de1802275c35a326670f88a7b1f515f5756
| 3,006
|
[
-1
] |
3,007
|
primordials_skinchanger.txt
|
gwathlobal_CotD/src/data/descriptions/primordials_skinchanger.txt
|
SKINCHANGER, PRIMORDIALS
- In the taiga bogs and forests of the East live strange creatures that had walked the Earth before any ape could be called sapient. Now they slumber, waiting for the time when the cycle of humankind is complete and they are able to reign the land once more. The natives fear, worship and offer sacrifices to them. But when the outsiders from beyond Earth arrived in the City, the primordials rose once more to drive the invaders out of what they consider their own domain.
- You can start as a Skinchanger, who can shift between different forms depending on the situation.
- You are able to feast on the corpses of the fallen to gain HP and power and mutate yourself gaining various abilities.
- You equally hate everybody in the City and are hated by everyone.
- Your goal is to destroy all angels and demons.
| 842
|
Common Lisp
|
.l
| 6
| 138.5
| 474
| 0.798088
|
gwathlobal/CotD
| 79
| 3
| 0
|
GPL-3.0
|
9/19/2024, 11:25:50 AM (Europe/Amsterdam)
|
a280bcf78b8eca40af35c0d4717f0885e87a08ca3dc615a2d78d3301ecf1190c
| 3,007
|
[
-1
] |
3,077
|
tokenizer.lisp
|
rotatef_cl-html5-parser/tokenizer.lisp
|
;;;; HTML5 parser for Common Lisp
;;;;
;;;; Copyright (C) 2012 Thomas Bakketun <thomas.bakketun@copyleft.no>
;;;; Copyright (C) 2012 Asgeir Bj√∏rlykke <asgeir@copyleft.no>
;;;; Copyright (C) 2012 Mathias Hellevang
;;;; Copyright (C) 2012 Stian Sletner <stian@copyleft.no>
;;;;
;;;; This library is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Lesser General Public License as published
;;;; by the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This library 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 library. If not, see <http://www.gnu.org/licenses/>.
(in-package :html5-parser)
(defclass html-tokenizer ()
((stream :initarg :stream :reader tokenizer-stream)
(cdata-switch-helper :initarg :cdata-switch-helper
:initform (constantly nil))
(lowercase-element-name :initform t)
(lowercase-attr-name :initform t)
(escape-flag :initform nil)
(last-four-chars :initform nil)
(state :initform :data-state :accessor tokenizer-state)
(escape :initform nil)
(current-token :initform nil)
(token-queue :initform nil)
(temporary-buffer :initform nil)))
(defun make-html-tokenizer (source &key encoding cdata-switch-helper)
(make-instance 'html-tokenizer
:stream (make-html-input-stream source :override-encoding encoding)
:cdata-switch-helper cdata-switch-helper))
(defun map-tokens (tokenizer function)
"Return next token or NIL on eof"
(with-slots (token-queue stream) tokenizer
(loop while (run-state tokenizer) do
(setf token-queue (nreverse token-queue))
(loop while (html5-stream-errors stream)
do (funcall function (list :type :parse-error :data (pop (html5-stream-errors stream)))))
(loop while token-queue
do (funcall function (pop token-queue))))))
(defun run-state (tokenizer)
(run-state* tokenizer (slot-value tokenizer 'state)))
(defgeneric run-state* (tokenizer state))
(defmacro defstate (state (&rest slots) &body body)
`(defmethod run-state* (self (state (eql ,state)))
(with-slots (,@slots) self
(block nil
,@body
t))))
(defun push-token (self token)
(with-slots (token-queue) self
(push token token-queue)))
(defun make-growable-string (&optional (init ""))
"Make an adjustable string with a fill pointer.
Given INIT, a string, return an adjustable version of it with the fill
pointer at the end."
(let ((string
(make-array (max 5 (length init))
:element-type 'character
:adjustable t
:fill-pointer (length init))))
(when init
(replace string init))
string))
(defun nconcat (string &rest data)
"Destructively concatenate DATA, string designators, to STRING."
(declare (optimize speed))
(unless (array-has-fill-pointer-p string)
(setf string (make-growable-string string)))
(labels ((conc (string x)
(typecase x
(character
(vector-push-extend x string))
(string
(let ((len (length x)))
(loop for c across x do
(vector-push-extend c string len))))
(symbol (conc string (string x))))))
(dolist (x data string)
(conc string x))))
(define-modify-macro nconcatf (&rest data) nconcat)
(defun push-token* (self type &rest data)
"Push a token with :type type and :data the a string concatenation of data"
(push-token self (list :type type
:data (apply #'nconcat (make-growable-string) data))))
(defun add-attribute (token name)
(setf (getf token :data) (append (getf token :data)
(list (cons (make-growable-string (string name))
(make-growable-string))))))
(defun add-to-attr-name (token &rest data)
(setf (caar (last (getf token :data)))
(apply #'nconcat
(caar (last (getf token :data)))
data)))
(defun add-to-attr-value (token &rest data)
(setf (cdar (last (getf token :data)))
(apply #'nconcat
(cdar (last (getf token :data)))
data)))
(defun add-to (token indicator &rest data)
(setf (getf token indicator)
(apply #'nconcat
(getf token indicator)
data)))
(defun consume-number-entity (self is-hex)
"This function returns either U+FFFD or the character based on the
decimal or hexadecimal representation. It also discards \";\" if present.
If not present a token (:type :parse-error) is emitted.
"
(with-slots (stream) self
(let ((allowed +digits+)
(radix 10)
(char-stack)
(c)
(char-as-int)
(char))
(when is-hex
(setf allowed +hex-digits+)
(setf radix 16))
;; Consume all the characters that are in range while making sure we
;; don't hit an EOF.
(setf c (html5-stream-char stream))
(loop while (and (find c allowed) (not (eql c +eof+))) do
(push c char-stack)
(setf c (html5-stream-char stream)))
;; Convert the set of characters consumed to an int.
(setf char-as-int (parse-integer (coerce (nreverse char-stack) 'string) :radix radix))
;; Certain characters get replaced with others
(cond ((find char-as-int +replacement-characters+)
(setf char (getf +replacement-characters+ char-as-int))
(push-token self `(:type :parse-error
:data :illegal-codepoint-for-numeric-entity
:datavars '(:char-as-int ,char-as-int))))
((or (<= #xD800 char-as-int #xDFFF)
(> char-as-int #x10FFFF))
(setf char #\uFFFD)
(push-token self `(:type :parse-error
:data :illegal-codepoint-for-numeric-entity
:datavars '(:char-as-int ,char-as-int))))
(t
;; Python comment: Should speed up this check somehow (e.g. move the set to a constant)
(when (or (<= #x0001 char-as-int #x0008)
(<= #x000E char-as-int #x001F)
(<= #x007F char-as-int #x009F)
(<= #xFDD0 char-as-int #xFDEF)
(find char-as-int
#(#x000B #xFFFE #xFFFF #x1FFFE
#x1FFFF #x2FFFE #x2FFFF #x3FFFE
#x3FFFF #x4FFFE #x4FFFF #x5FFFE
#x5FFFF #x6FFFE #x6FFFF #x7FFFE
#x7FFFF #x8FFFE #x8FFFF #x9FFFE
#x9FFFF #xAFFFE #xAFFFF #xBFFFE
#xBFFFF #xCFFFE #xCFFFF #xDFFFE
#xDFFFF #xEFFFE #xEFFFF #xFFFFE
#xFFFFF #x10FFFE #x10FFFF)))
(push-token self `(:type :parse-error
:data :illegal-codepoint-for-numeric-entity
:datavars '(:char-as-int ,char-as-int))))
;; Assume char-code-limit >= 1114112
(setf char (code-char char-as-int))))
;; Discard the ; if present. Otherwise, put it back on the queue and
;; invoke parseError on parser.
(unless (eql c #\;)
(push-token self `(:type :parse-error :data :numeric-entity-without-semicolon))
(html5-stream-unget stream c))
(string char))))
(defun consume-entity (self &key allowed-char from-attribute)
(with-slots (stream current-token) self
(let ((output "&")
(stack (list (html5-stream-char stream))))
(cond ((or (find (car stack) +space-characters+)
(find (car stack) '(+eof+ #\< #\&))
(and allowed-char (eql allowed-char (car stack))))
(html5-stream-unget stream (car stack)))
((eql (car stack) #\#)
(push (html5-stream-char stream) stack)
(let ((is-hex (find (car stack) "xX")))
(when is-hex
(push (html5-stream-char stream) stack))
(cond ((find (car stack) (if is-hex +hex-digits+ +digits+))
(html5-stream-unget stream (car stack))
(setf output (consume-number-entity self is-hex)))
(t
(push-token self '(:type :parse-error :data :expected-numeric-entity))
(html5-stream-unget stream (pop stack))
(when is-hex
(html5-stream-unget stream (pop stack)))
(html5-stream-unget stream (pop stack))))))
(t
;; Consume the maximum number of characters possible, with the
;; consumed characters matching one of the identifiers in the first
;; column of the named character references table
;; (in a case-sensitive manner).
(let ((entity)
(match-at 0))
(loop with node = *entities-tree*
for char = (car stack) then (car (push (html5-stream-char stream)
stack))
for next-node = (assoc char node)
while next-node
do (when (second next-node)
(setf entity (second next-node))
(setf match-at (length stack)))
do (setf node (cddr next-node)))
(let ((next-char))
;; Unconsume those characters that are not part of the match
;; This unconsumes everything if there where no match
(loop until (= (length stack) match-at) do
(setf next-char (car stack))
(html5-stream-unget stream (pop stack)))
(cond ((not entity)
;; If no match can be made, then no characters are consumed, and nothing is returned.
;; Is this always a parse error really?
(push-token self '(:type :parse-error :data :expected-named-entity)))
((and from-attribute
(not (eql #\; (car stack)))
(or (eql next-char #\=)
(find next-char +digits+)
(ascii-letter-p next-char)))
; Is this a parse error really?
(push-token self '(:type :parse-error :data :bogus))
(setf output (concatenate 'string "&" (reverse stack))))
(t
(unless (eql #\; (car stack))
(push-token self '(:type :parse-error
:data :named-entity-without-semicolon)))
(setf output entity)))))))
(cond (from-attribute
(add-to-attr-value current-token output))
(t
(push-token* self (if (find (char output 0) +space-characters+)
:space-characters
:characters)
output))))))
(defun process-entity-in-attribute (self &key allowed-char)
(consume-entity self :allowed-char allowed-char :from-attribute t))
(defun emit-current-token (self)
"This method is a generic handler for emitting the tags. It also sets
the state to :data because that's what's needed after a token has been
emitted.
"
(with-slots (current-token state lowercase-element-name) self
(let ((token current-token))
;; Add token to the queue to be yielded
(when (find (getf token :type) +tag-token-types+)
(when lowercase-element-name
(setf (getf token :name) (ascii-upper-2-lower (getf token :name))))
(when (eql (getf token :type) :end-tag)
(when (getf token :data)
(push-token self '(:type :parse-error :data :attributes-in-end-tag)))
(when (getf token :self-closing)
(push-token self '(:type :parse-error :data :self-closing-flag-on-end-tag)))))
(push-token self token)
(setf state :data-state))))
;;;
;;; Below are the various tokenizer states worked out.
;;;
(defstate :data-state (stream state)
(let ((data (html5-stream-char stream)))
(cond ((eql data #\&)
(setf state :entity-data-state))
((eql data #\<)
(setf state :tag-open-state))
((eql data #\u0000)
(push-token self '(:type :parse-error :data :invalid-codepoint))
(push-token* self :characters #\u0000))
((eql data +eof+)
;; Tokenization ends.
(return nil))
((find data +space-characters+)
;; Directly after emitting a token you switch back to the "data
;; state". At that point spaceCharacters are important so they are
;; emitted separately.
(push-token* self :space-characters
data
(html5-stream-chars-until stream +space-characters+ t))
;; No need to update lastFourChars here, since the first space will
;; have already been appended to lastFourChars and will have broken
;; any <!-- or --> sequences
)
(t
(push-token* self :characters
data
(html5-stream-chars-until stream '(#\& #\< #\u0000)))))))
(defstate :entity-data-state (state)
(consume-entity self)
(setf state :data-state))
(defstate :rcdata-state (stream state)
(let ((data (html5-stream-char stream)))
(cond ((eql data #\&)
(setf state :character-reference-in-rcdata))
((eql data #\<)
(setf state :rcdata-less-than-sign-state))
((eql data +eof+)
;; Tokenization ends.
(return nil))
((eql data #\u0000)
(push-token self '(:type :parse-error :data :invalid-codepoint))
(push-token* self :characters #\uFFFD))
((find data +space-characters+)
;; Directly after emitting a token you switch back to the "data
;; state". At that point spaceCharacters are important so they are
;; emitted separately.
(push-token* self :space-characters
data
(html5-stream-chars-until stream +space-characters+ t))
;; No need to update lastFourChars here, since the first space will
;; have already been appended to lastFourChars and will have broken
;; any <!-- or --> sequences
)
(t
(push-token* self :characters
data
(html5-stream-chars-until stream '(#\& #\<)))))))
(defstate :character-reference-in-rcdata (state)
(consume-entity self)
(setf state :rcdata-state))
(defstate :rawtext-state (stream state)
(let ((data (html5-stream-char stream)))
(cond ((eql data #\<)
(setf state :rawtext-less-than-sign-state))
((eql data #\u0000)
(push-token self '(:type :parse-error :data :invalid-codepoint))
(push-token* self :characters #\uFFFD))
((eql data +eof+)
;; Tokenization ends.
(return nil))
(t
(push-token* self :characters
data
(html5-stream-chars-until stream '(#\< #\u0000)))))))
(defstate :script-data-state (stream state)
(let ((data (html5-stream-char stream)))
(cond ((eql data #\<)
(setf state :script-data-less-than-sign-state))
((eql data #\u0000)
(push-token self '(:type :parse-error :data :invalid-codepoint))
(push-token* self :characters #\uFFFD))
((eql data +eof+)
;; Tokenization ends.
(return nil))
(t
(push-token* self :characters
data
(html5-stream-chars-until stream '(#\< #\u0000)))))))
(defstate :plaintext-state (stream)
(let ((data (html5-stream-char stream)))
(cond ((eql data +eof+)
;; Tokenization ends.
(return nil))
((eql data #\u0000)
(push-token self '(:type :parse-error :data :invalid-codepoint))
(push-token* self :characters #\uFFFD))
(t
(push-token* self :characters
data
(html5-stream-chars-until stream '(#\u0000)))))))
(defstate :tag-open-state (stream state current-token)
(let ((data (html5-stream-char stream)))
(cond ((eql data #\!)
(setf state :markup-declaration-open-state))
((eql data #\/)
(setf state :close-tag-open-state))
((ascii-letter-p data)
(setf current-token (list :type :start-tag
:name (make-array 1 :element-type 'character
:initial-element data
:fill-pointer t
:adjustable t)
:data '()
:self-closing nil
:self-closing-acknowledged nil))
(setf state :tag-name-state))
((eql data #\>)
;; XXX In theory it could be something besides a tag name. But
;; do we really care?
(push-token self '(:type :parse-error :data :expected-tag-name-but-got-right-bracket))
(push-token* self :characters "<>")
(setf state :data-state))
((eql data #\?)
;; XXX In theory it could be something besides a tag name. But
;; do we really care?
(push-token self '(:type :parse-error :data :expected-tag-name-but-got-question-mark))
(html5-stream-unget stream data)
(setf state :bogus-comment-state))
(t
;; XXX
(push-token self '(:type :parse-error :data :expected-tag-name))
(push-token* self :characters "<")
(html5-stream-unget stream data)
(setf state :data-state)))))
(defstate :close-tag-open-state
(stream state current-token)
(let ((data (html5-stream-char stream)))
(cond ((ascii-letter-p data)
(setf current-token (list :type :end-tag
:name (make-array 1 :element-type 'character
:initial-element data
:fill-pointer t
:adjustable t)
:data '()
:self-closing nil))
(setf state :tag-name-state))
((eql data #\>)
(push-token self '(:type :parse-error :data :expected-closing-tag-but-got-right-bracket))
(setf state :data-state))
((eql data +eof+)
(push-token self '(:type :parse-error :data :expected-closing-tag-but-got-eof))
(push-token* self :characters "</")
(setf state :data-state))
(t
;; XXX data can be _'_...
(push-token self `(:type :parse-error :data :expected-closing-tag-but-got-char
:datavars (:data ,data)))
(html5-stream-unget stream data)
(setf state :bogus-comment-state))))
t)
(defstate :tag-name-state (stream state current-token)
(let ((data (html5-stream-char stream)))
(cond ((find data +space-characters+)
(setf state :before-attribute-name-state))
((eql data #\>)
(emit-current-token self))
((eql data +eof+)
(push-token self '(:type :parse-error :data :eof-in-tag-name))
(setf state :data-state))
((eql data #\/)
(setf state :self-closing-start-tag-state))
((eql data #\u0000)
(push-token self '(:type :parse-error :data :invalid-codepoint))
(vector-push-extend #\uFFFD (getf current-token :name)))
(t
(vector-push-extend data (getf current-token :name))
;; (Don't use charsUntil here, because tag names are
;; very short and it's faster to not do anything fancy)
))))
(defstate :rcdata-less-than-sign-state (stream state temporary-buffer)
(let ((data (html5-stream-char stream)))
(cond ((eql data #\/)
(setf temporary-buffer (make-growable-string))
(setf state :rcdata-end-tag-open-state))
(t
(push-token* self :characters "<")
(html5-stream-unget stream data)
(setf state :rcdata-state)))))
(defstate :rcdata-end-tag-open-state (stream state temporary-buffer)
(let ((data (html5-stream-char stream)))
(cond ((ascii-letter-p data)
(nconcatf temporary-buffer (string data))
(setf state :rcdata-end-tag-name-state))
(t
(push-token* self :characters "</")
(html5-stream-unget stream data)
(setf state :rcdata-state)))))
(defstate :rcdata-end-tag-name-state (stream state temporary-buffer current-token)
(let ((appropriate (and current-token
(string-equal (getf current-token :name)
temporary-buffer)))
(data (html5-stream-char stream)))
(cond ((and (find data +space-characters+)
appropriate)
(setf current-token (list :type :end-tag
:name temporary-buffer
:data '()
:self-closing nil))
(setf state :before-attribute-name-state))
((and (eql data #\/)
appropriate)
(setf current-token (list :type :end-tag
:name temporary-buffer
:data '()
:self-closing nil))
(setf state :self-closing-start-tag-state))
((and (eql data #\>)
appropriate)
(setf current-token (list :type :end-tag
:name temporary-buffer
:data '()
:self-closing nil))
(emit-current-token self)
(setf state :data-state))
((ascii-letter-p data)
(nconcatf temporary-buffer data))
(t
(push-token* self :characters "</" temporary-buffer)
(html5-stream-unget stream data)
(setf state :rcdata-state)))))
(defstate :rawtext-less-than-sign-state (stream state temporary-buffer)
(let ((data (html5-stream-char stream)))
(cond ((eql data #\/)
(setf temporary-buffer (make-growable-string))
(setf state :rawtext-end-tag-open-state))
(t
(push-token* self :characters "<")
(html5-stream-unget stream data)
(setf state :rawtext-state)))))
(defstate :rawtext-end-tag-open-state (stream state temporary-buffer)
(let ((data (html5-stream-char stream)))
(cond ((ascii-letter-p data)
(nconcatf temporary-buffer (string data))
(setf state :rawtext-end-tag-name-state))
(t
(push-token* self :characters "</")
(html5-stream-unget stream data)
(setf state :rawtext-state)))))
(defstate :rawtext-end-tag-name-state (stream state temporary-buffer current-token)
(let ((appropriate (and current-token
(string-equal (getf current-token :name)
temporary-buffer)))
(data (html5-stream-char stream)))
(cond ((and (find data +space-characters+)
appropriate)
(setf current-token (list :type :end-tag
:name temporary-buffer
:data '()
:self-closing nil))
(setf state :before-attribute-name-state))
((and (eql data #\/)
appropriate)
(setf current-token (list :type :end-tag
:name temporary-buffer
:data '()
:self-closing nil))
(setf state :self-closing-start-tag-state))
((and (eql data #\>)
appropriate)
(setf current-token (list :type :end-tag
:name temporary-buffer
:data '()
:self-closing nil))
(emit-current-token self)
(setf state :data-state))
((ascii-letter-p data)
(nconcatf temporary-buffer data))
(t
(push-token* self :characters "</" temporary-buffer)
(html5-stream-unget stream data)
(setf state :rawtext-state)))))
(defstate :script-data-less-than-sign-state (stream state temporary-buffer)
(let ((data (html5-stream-char stream)))
(cond ((eql data #\/)
(setf temporary-buffer (make-growable-string))
(setf state :script-data-end-tag-open-state))
((eql data #\!)
(push-token* self :characters "<!")
(setf state :script-data-escape-start-state))
(t
(push-token* self :characters "<")
(html5-stream-unget stream data)
(setf state :script-data-state)))))
(defstate :script-data-end-tag-open-state (stream state temporary-buffer)
(let ((data (html5-stream-char stream)))
(cond ((ascii-letter-p data)
(nconcatf temporary-buffer data)
(setf state :script-data-end-tag-name-state))
(t
(push-token* self :characters "</")
(html5-stream-unget stream data)
(setf state :script-data-state)))))
(defstate :script-data-end-tag-name-state (stream state temporary-buffer current-token)
(let ((appropriate (and current-token
(string-equal (getf current-token :name)
temporary-buffer)))
(data (html5-stream-char stream)))
(cond ((and (find data +space-characters+)
appropriate)
(setf current-token (list :type :end-tag
:name temporary-buffer
:data '()
:self-closing nil))
(setf state :before-attribute-name-state))
((and (eql data #\/)
appropriate)
(setf current-token (list :type :end-tag
:name temporary-buffer
:data '()
:self-closing nil))
(setf state :self-closing-start-tag-state))
((and (eql data #\>)
appropriate)
(setf current-token (list :type :end-tag
:name temporary-buffer
:data '()
:self-closing nil))
(emit-current-token self)
(setf state :data-state))
((ascii-letter-p data)
(nconcatf temporary-buffer data))
(t
(push-token* self :characters "</" temporary-buffer)
(html5-stream-unget stream data)
(setf state :script-data-state)))))
(defstate :script-data-escape-start-state (stream state)
(let ((data (html5-stream-char stream)))
(cond ((eql data #\-)
(push-token* self :characters "-")
(setf state :script-data-escape-start-dash-state))
(t
(html5-stream-unget stream data)
(setf state :script-data-state)))))
(defstate :script-data-escape-start-dash-state (stream state)
(let ((data (html5-stream-char stream)))
(cond ((eql data #\-)
(push-token* self :characters "-")
(setf state :script-data-escaped-dash-dash-state))
(t
(html5-stream-unget stream data)
(setf state :script-data-state)))))
(defstate :script-data-escaped-state (stream state)
(let ((data (html5-stream-char stream)))
(cond ((eql data #\-)
(push-token* self :characters "-")
(setf state :script-data-escaped-dash-state))
((eql data #\<)
(setf state :script-data-escaped-less-than-sign-state))
((eql data #\u0000)
(push-token self '(:type :parse-error :data :invalid-codepoint))
(push-token* self :characters #\uFFFD))
((eql data +eof+)
(setf state :data-state))
(t
(push-token* self :characters data (html5-stream-chars-until stream '(#\< #\- #\u0000)))))))
(defstate :script-data-escaped-dash-state (stream state)
(let ((data (html5-stream-char stream)))
(cond ((eql data #\-)
(push-token* self :characters "-")
(setf state :script-data-escaped-dash-dash-state))
((eql data #\<)
(setf state :script-data-escaped-less-than-sign-state))
((eql data #\u0000)
(push-token self '(:type :parse-error :data :invalid-codepoint))
(push-token* self :characters #\uFFFD)
(setf state :script-data-escaped-state))
((eql data +eof+)
(setf state :data-state))
(t
(push-token* self :characters data (html5-stream-chars-until stream '(#\< #\- #\u0000)))
(setf state :script-data-escaped-state)))))
(defstate :script-data-escaped-dash-dash-state (stream state)
(let ((data (html5-stream-char stream)))
(cond ((eql data #\-)
(push-token* self :characters "-"))
((eql data #\<)
(setf state :script-data-escaped-less-than-sign-state))
((eql data #\>)
(push-token* self :characters ">")
(setf state :script-data-state))
((eql data #\u0000)
(push-token self '(:type :parse-error :data :invalid-codepoint))
(push-token* self :characters #\uFFFD)
(setf state :script-data-escaped-state))
((eql data +eof+)
(setf state :data-state))
(t
(push-token* self :characters data (html5-stream-chars-until stream '(#\< #\- #\u0000)))
(setf state :script-data-escaped-state)))))
(defstate :script-data-escaped-less-than-sign-state (stream state temporary-buffer)
(let ((data (html5-stream-char stream)))
(cond ((eql data #\/)
(setf temporary-buffer (make-growable-string))
(setf state :script-data-escaped-end-tag-open-state))
((ascii-letter-p data)
(push-token* self :characters "<" data)
(setf temporary-buffer (ascii-upper-2-lower (string data)))
(setf state :script-data-double-escape-start-state))
(t
(push-token* self :characters "<")
(html5-stream-unget stream data)
(setf state :script-data-escaped-state)))))
(defstate :script-data-escaped-end-tag-open-state (stream state temporary-buffer)
(let ((data (html5-stream-char stream)))
(cond ((ascii-letter-p data)
(setf temporary-buffer (string data))
(setf state :script-data-escaped-end-tag-name-state))
(t
(push-token* self :characters "</")
(html5-stream-unget stream data)
(setf state :script-data-escaped-state)))))
(defstate :script-data-escaped-end-tag-name-state (stream state temporary-buffer current-token)
(let ((appropriate (and current-token
(string-equal (getf current-token :name)
temporary-buffer)))
(data (html5-stream-char stream)))
(cond ((and (find data +space-characters+)
appropriate)
(setf current-token (list :type :end-tag
:name temporary-buffer
:data '()
:self-closing nil))
(setf state :before-attribute-name-state))
((and (eql data #\/)
appropriate)
(setf current-token (list :type :end-tag
:name temporary-buffer
:data '()
:self-closing nil))
(setf state :self-closing-start-tag-state))
((and (eql data #\>)
appropriate)
(setf current-token (list :type :end-tag
:name temporary-buffer
:data '()
:self-closing nil))
(emit-current-token self)
(setf state :data-state))
((ascii-letter-p data)
(nconcatf temporary-buffer data))
(t
(push-token* self :characters "</" temporary-buffer)
(html5-stream-unget stream data)
(setf state :script-data-escaped-state)))))
(defstate :script-data-double-escape-start-state (stream state temporary-buffer)
(let ((data (html5-stream-char stream)))
(cond ((or (find data +space-characters+)
(find data '(#\/ #\>)))
(push-token* self :characters data)
(if (string= (string-downcase temporary-buffer) "script")
(setf state :script-data-double-escaped-state)
(setf state :script-data-escaped-state)))
((ascii-letter-p data)
(push-token* self :characters data)
(nconcatf temporary-buffer (string data)))
(t
(html5-stream-unget stream data)
(setf state :script-data-escaped-state)))))
(defstate :script-data-double-escaped-state (stream state)
(let ((data (html5-stream-char stream)))
(cond ((eql data #\-)
(push-token* self :characters "-")
(setf state :script-data-double-escaped-dash-state))
((eql data #\<)
(push-token* self :characters "<")
(setf state :script-data-double-escaped-less-than-sign-state))
((eql data #\u0000)
(push-token self '(:type :parse-error :data :invalid-codepoint))
(push-token* self :characters #\uFFFD))
((eql data +eof+)
(push-token self '(:type :parse-error :data :eof-in-script-in-script))
(setf state :data-state))
(t
(push-token* self :characters data)))))
(defstate :script-data-double-escaped-dash-state (stream state)
(let ((data (html5-stream-char stream)))
(cond ((eql data #\-)
(push-token* self :characters "-")
(setf state :script-data-double-escaped-dash-dash-state))
((eql data #\<)
(push-token* self :characters "<")
(setf state :script-data-double-escaped-less-than-sign-state))
((eql data #\u0000)
(push-token self '(:type :parse-error :data :invalid-codepoint))
(push-token* self :characters #\uFFFD)
(setf state :script-data-double-escaped-state))
((eql data +eof+)
(push-token self '(:type :parse-error :data :eof-in-script-in-script))
(setf state :data-state))
(t
(push-token* self :characters data)
(setf state :script-data-double-escaped-state)))))
;; FIXME: Incorrectly named in Python code: scriptDataDoubleEscapedDashState (same the one above)
(defstate :script-data-double-escaped-dash-dash-state (stream state)
(let ((data (html5-stream-char stream)))
(cond ((eql data #\-)
(push-token* self :characters "-")
(setf state :script-data-double-escaped-dash-dash-state))
((eql data #\<)
(push-token* self :characters "<")
(setf state :script-data-double-escaped-less-than-sign-state))
((eql data #\>)
(push-token* self :characters ">")
(setf state :script-data-state))
((eql data #\u0000)
(push-token self '(:type :parse-error :data :invalid-codepoint))
(push-token* self :characters #\uFFFD)
(setf state :script-data-double-escaped-state))
((eql data +eof+)
(push-token self '(:type :parse-error :data :eof-in-script-in-script))
(setf state :data-state))
(t
(push-token* self :characters data)
(setf state :script-data-double-escaped-state)))))
(defstate :script-data-double-escaped-less-than-sign-state (stream state temporary-buffer)
(let ((data (html5-stream-char stream)))
(cond ((eql data #\/)
(push-token* self :characters "/")
(setf temporary-buffer (make-growable-string))
(setf state :script-data-double-escape-end-state))
(t
(html5-stream-unget stream data)
(setf state :script-data-double-escaped-state)))))
(defstate :script-data-double-escape-end-state (stream state temporary-buffer)
(let ((data (html5-stream-char stream)))
(cond ((or (find data +space-characters+)
(find data '(#\/ #\>)))
(push-token* self :characters data)
(if (string= (string-downcase temporary-buffer) "script")
(setf state :script-data-escaped-state)
(setf state :script-data-double-escaped-state)))
((ascii-letter-p data)
(push-token* self :characters data)
(nconcatf temporary-buffer data))
(t
(html5-stream-unget stream data)
(setf state :script-data-double-escaped-state)))))
(defstate :before-attribute-name-state (stream state current-token)
(let ((data (html5-stream-char stream)))
(cond ((find data +space-characters+)
(html5-stream-chars-until stream +space-characters+ t))
((ascii-letter-p data)
(add-attribute current-token data)
(setf state :attribute-name-state))
((eql data #\>)
(emit-current-token self))
((eql data #\/)
(setf state :self-closing-start-tag-state))
((find data '(#\' #\" #\= #\<))
(push-token self '(:type :parse-error :data :invalid-character-in-attribute-name))
(add-attribute current-token data)
(setf state :attribute-name-state))
((eql data #\u0000)
(push-token self '(:type :parse-error :data :invalid-codepoint))
(add-attribute current-token #\uFFFD)
(setf state :attribute-name-state))
((eql data +eof+)
(push-token self '(:type :parse-error :data :expected-attribute-name-but-got-eof))
(setf state :data-state))
(t
(add-attribute current-token data)
(setf state :attribute-name-state)))))
(defstate :attribute-name-state (stream state current-token lowercase-attr-name)
(let ((data (html5-stream-char stream))
(leaving-this-state t)
(emit-token nil))
(cond ((eql data #\=)
(setf state :before-attribute-value-state))
((ascii-letter-p data)
(add-to-attr-name current-token data
(html5-stream-chars-until stream +ascii-letters+ t))
(setf leaving-this-state nil))
((eql data #\>)
;; XXX If we emit here the attributes are converted to a dict
;; without being checked and when the code below runs we error
;; because data is a dict not a list
(setf emit-token t))
((find data +space-characters+)
(setf state :after-attribute-name-state))
((eql data #\/)
(setf state :self-closing-start-tag-state))
((eql data #\u0000)
(push-token self '(:type :parse-error :data :invalid-codepoint))
(add-to-attr-name current-token #\uFFFD)
(setf leaving-this-state nil))
((find data '(#\' #\" #\<))
(push-token self '(:type :parse-error :data :invalid-character-in-attribute-name))
(add-to-attr-name current-token data)
(setf leaving-this-state nil))
((eql data +eof+)
(push-token self '(:type :parse-error :data :eof-in-attribute-name))
(setf state :data-state))
(t
(add-to-attr-name current-token data)
(setf leaving-this-state nil)))
(when leaving-this-state
;; Attributes are not dropped at this stage. That happens when the
;; start tag token is emitted so values can still be safely appended
;; to attributes, but we do want to report the parse error in time.
(when lowercase-attr-name
(setf (caar (last (getf current-token :data)))
(ascii-upper-2-lower (caar (last (getf current-token :data))))))
(loop for (name . value) in (butlast (getf current-token :data)) do
(when (string= (caar (last (getf current-token :data))) name)
(push-token self '(:type :parse-error :data :duplicate-attribute))
(return)))
;; XXX Fix for above XXX
(when emit-token
(emit-current-token self)))))
(defstate :after-attribute-name-state (stream state current-token)
(let ((data (html5-stream-char stream)))
(cond ((find data +space-characters+)
(html5-stream-chars-until stream +space-characters+ t))
((eql data #\=)
(setf state :before-attribute-value-state))
((eql data #\>)
(emit-current-token self))
((ascii-letter-p data)
(add-attribute current-token data)
(setf state :attribute-name-state))
((eql data #\/)
(setf state :self-closing-start-tag-state))
((eql data #\u0000)
(push-token self '(:type :parse-error :data :invalid-codepoint))
(add-attribute current-token #\uFFFD)
(setf state :attribute-name-state))
((find data '(#\' #\" #\<))
(push-token self '(:type :parse-error :data :invalid-character-after-attribute-name))
(add-attribute current-token data)
(setf state :attribute-name-state))
((eql data +eof+)
(push-token self '(:type :parse-error :data :expected-end-of-tag-but-got-eof))
(setf state :data-state))
(t
(add-attribute current-token data)
(setf state :attribute-name-state)))))
(defstate :before-attribute-value-state (stream state current-token)
(let ((data (html5-stream-char stream)))
(cond ((find data +space-characters+)
(html5-stream-chars-until stream +space-characters+ t))
((eql data #\")
(setf state :attribute-value-double-quoted-state))
((eql data #\&)
(setf state :attribute-value-un-quoted-state)
(html5-stream-unget stream data))
((eql data #\')
(setf state :attribute-value-single-quoted-state))
((eql data #\>)
(push-token self '(:type :parse-error :data :expected-attribute-value-but-got-right-bracket))
(emit-current-token self))
((eql data #\u0000)
(push-token self '(:type :parse-error :data :invalid-codepoint))
(add-to-attr-value current-token #\uFFFD)
(setf state :attribute-value-un-quoted-state))
((find data '(#\= #\< #\`))
(push-token self '(:type :parse-error :data :equals-in-unquoted-attribute-value))
(add-to-attr-value current-token data)
(setf state :attribute-value-un-quoted-state))
((eql data +eof+)
(push-token self '(:type :parse-error :data :expected-attribute-value-but-got-eof))
(setf state :data-state))
(t
(add-to-attr-value current-token data)
(setf state :attribute-value-un-quoted-state)))))
(defstate :attribute-value-double-quoted-state (stream state current-token)
(let ((data (html5-stream-char stream)))
(cond ((eql data #\")
(setf state :after-attribute-value-state))
((eql data #\&)
(process-entity-in-attribute self :allowed-char #\"))
((eql data #\u0000)
(push-token self '(:type :parse-error :data :invalid-codepoint))
(add-to-attr-value current-token #\uFFFD))
((eql data +eof+)
(push-token self '(:type :parse-error :data :eof-in-attribute-value-double-quote))
(setf state :data-state))
(t
(add-to-attr-value current-token
data
(html5-stream-chars-until stream '(#\" #\&)))))))
(defstate :attribute-value-single-quoted-state (stream state current-token)
(let ((data (html5-stream-char stream)))
(cond ((eql data #\')
(setf state :after-attribute-value-state))
((eql data #\&)
(process-entity-in-attribute self :allowed-char #\'))
((eql data #\u0000)
(push-token self '(:type :parse-error :data :invalid-codepoint))
(add-to-attr-value current-token #\uFFFD))
((eql data +eof+)
(push-token self '(:type :parse-error :data :eof-in-attribute-value-single-quote))
(setf state :data-state))
(t
(add-to-attr-value current-token
data
(html5-stream-chars-until stream '(#\' #\&)))))))
(defstate :attribute-value-un-quoted-state (stream state current-token)
(let ((data (html5-stream-char stream)))
(cond ((find data +space-characters+)
(setf state :before-attribute-name-state))
((eql data #\&)
(process-entity-in-attribute self :allowed-char #\>))
((eql data #\>)
(emit-current-token self))
((find data '(#\" #\' #\= #\< #\`))
(push-token self '(:type :parse-error :data :unexpected-character-in-unquoted-attribute-value))
(add-to-attr-value current-token data))
((eql data #\u0000)
(push-token self '(:type :parse-error :data :invalid-codepoint))
(add-to-attr-value current-token #\uFFFD))
((eql data +eof+)
(push-token self '(:type :parse-error :data :eof-in-attribute-value-no-quotes))
(setf state :data-state))
(t
(add-to-attr-value current-token
data
(html5-stream-chars-until stream `(#\& #\> #\" #\' #\= #\< #\`
,@+space-characters+)))))))
(defstate :after-attribute-value-state (stream state current-token)
(let ((data (html5-stream-char stream)))
(cond ((find data +space-characters+)
(setf state :before-attribute-name-state))
((eql data #\>)
(emit-current-token self))
((eql data #\/)
(setf state :self-closing-start-tag-state))
((eql data +eof+)
(push-token self '(:type :parse-error :data :unexpected-EOF-after-attribute-value))
(html5-stream-unget stream data)
(setf state :data-state))
(t
(push-token self '(:type :parse-error :data :unexpected-character-after-attribute-value))
(html5-stream-unget stream data)
(setf state :before-attribute-name-state)))))
(defstate :self-closing-start-tag-state (stream state current-token)
(let ((data (html5-stream-char stream)))
(cond ((eql data #\>)
(setf (getf current-token :self-closing) t)
(emit-current-token self))
((eql data +eof+)
(push-token self '(:type :parse-error :data :unexpected-EOF-after-solidus-in-tag))
(html5-stream-unget stream data)
(setf state :data-state))
(t
(push-token self '(:type :parse-error :data :unexpected-character-after-soldius-in-tag))
(html5-stream-unget stream data)
(setf state :before-attribute-name-state)))))
(defstate :bogus-comment-state (stream state current-token)
;; Make a new comment token and give it as value all the characters
;; until the first > or EOF (charsUntil checks for EOF automatically)
;; and emit it.
(let ((data (html5-stream-chars-until stream '(#\>))))
(setf data (substitute #\uFFFD #\u0000 data))
(push-token* self :comment data)
;; Eat the character directly after the bogus comment which is either a
;; ">" or an EOF.
(html5-stream-char stream)
(setf state :data-state)))
(defstate :markup-declaration-open-state (stream state current-token
cdata-switch-helper)
(let ((char-stack (make-array 1
:initial-element (html5-stream-char stream)
:fill-pointer 1
:adjustable t)))
(cond ((eql (aref char-stack (1- (length char-stack))) #\-)
(vector-push-extend (html5-stream-char stream) char-stack)
(when (eql (aref char-stack (1- (length char-stack))) #\-)
(setf current-token (list :type :comment :data ""))
(setf state :comment-start-state)
(return t)))
((find (aref char-stack (1- (length char-stack))) '(#\d #\D))
(let ((matched t))
(loop for expected in '((#\o #\O) (#\c #\C) (#\t #\T) (#\y #\Y) (#\p #\P) (#\e #\E)) do
(vector-push-extend (html5-stream-char stream) char-stack)
(unless (find (aref char-stack (1- (length char-stack))) expected)
(setf matched nil)
(return)))
(when matched
(setf current-token (list :type :doctype
:name ""
:public-id nil
:system-id nil
:correct t))
(setf state :doctype-state)
(return t))))
((and (eql (aref char-stack (1- (length char-stack))) #\[)
(funcall cdata-switch-helper))
(let ((matched t))
(loop for expected across "CDATA[" do
(vector-push-extend (html5-stream-char stream) char-stack)
(unless (eql (aref char-stack (1- (length char-stack))) expected)
(setf matched nil)
(return)))
(when matched
(setf state :cdata-section-state)
(return t)))))
(push-token self '(:type :parse-error :data :expected-dashes-or-doctype))
(loop while (plusp (length char-stack)) do
(html5-stream-unget stream (vector-pop char-stack)))
(setf state :bogus-comment-state)))
(defstate :comment-start-state (stream state current-token)
(let ((data (html5-stream-char stream)))
(cond ((eql data #\-)
(setf state :comment-start-dash-state))
((eql data #\u0000)
(push-token self '(:type :parse-error :data :invalid-codepoint))
(add-to current-token :data #\uFFFD))
((eql data #\>)
(push-token self '(:type :parse-error :data :incorrect-comment))
(push-token self current-token)
(setf state :data-state))
((eql data +eof+)
(push-token self '(:type :parse-error :data :eof-in-comment))
(push-token self current-token)
(setf state :data-state))
(t
(add-to current-token :data data)
(setf state :comment-state)))))
(defstate :comment-start-dash-state (stream state current-token)
(let ((data (html5-stream-char stream)))
(cond ((eql data #\-)
(setf state :comment-end-state))
((eql data #\u0000)
(push-token self '(:type :parse-error :data :invalid-codepoint))
(add-to current-token :data "-" #\uFFFD))
((eql data #\>)
(push-token self '(:type :parse-error :data :incorrect-comment))
(push-token self current-token)
(setf state :data-state))
((eql data +eof+)
(push-token self '(:type :parse-error :data :eof-in-comment))
(push-token self current-token)
(setf state :data-state))
(t
(add-to current-token :data "-" data)
(setf state :comment-state)))))
(defstate :comment-state (stream state current-token)
(let ((data (html5-stream-char stream)))
(cond ((eql data #\-)
(setf state :comment-end-dash-state))
((eql data #\u0000)
(push-token self '(:type :parse-error :data :invalid-codepoint))
(add-to current-token :data #\uFFFD))
((eql data +eof+)
(push-token self '(:type :parse-error :data :eof-in-comment))
(push-token self current-token)
(setf state :data-state))
(t
(add-to current-token :data data
(html5-stream-chars-until stream '(#\- #\u0000)))))))
(defstate :comment-end-dash-state (stream state current-token)
(let ((data (html5-stream-char stream)))
(cond ((eql data #\-)
(setf state :comment-end-state))
((eql data #\u0000)
(push-token self '(:type :parse-error :data :invalid-codepoint))
(add-to current-token :data "-" #\uFFFD))
((eql data +eof+)
(push-token self '(:type :parse-error :data :eof-in-comment-end-dash))
(push-token self current-token)
(setf state :data-state))
(t
(add-to current-token :data "-" data)
(setf state :comment-state)))))
(defstate :comment-end-state (stream state current-token)
(let ((data (html5-stream-char stream)))
(cond ((eql data #\>)
(push-token self current-token)
(setf state :data-state))
((eql data #\u0000)
(push-token self '(:type :parse-error :data :invalid-codepoint))
(add-to current-token :data "--" #\uFFFD)
(setf state :comment-state))
((eql data #\!)
(push-token self '(:type :parse-error :data :unexpected-bang-after-double-dash-in-comment))
(setf state :comment-end-bang-state))
((eql data #\-)
(push-token self '(:type :parse-error :data :unexpected-dash-after-double-dash-in-comment))
(add-to current-token :data data))
((eql data +eof+)
(push-token self '(:type :parse-error :data :eof-in-comment-double-dash))
(push-token self current-token)
(setf state :data-state))
(t
;; XXX
(push-token self '(:type :parse-error :data :unexpected-char-in-comment))
(add-to current-token :data "--" data)
(setf state :comment-state)))))
(defstate :comment-end-bang-state (stream state current-token)
(let ((data (html5-stream-char stream)))
(cond ((eql data #\>)
(push-token self current-token)
(setf state :data-state))
((eql data #\-)
(add-to current-token :data "--!")
(setf state :comment-end-dash-state))
((eql data #\u0000)
(push-token self '(:type :parse-error :data :invalid-codepoint))
(add-to current-token :data "--!" #\uFFFD)
(setf state :comment-state))
((eql data +eof+)
(push-token self '(:type :parse-error :data :eof-in-comment-end-bang-state))
(push-token self current-token)
(setf state :data-state))
(t
(add-to current-token :data "--!" data)
(setf state :comment-state)))))
(defstate :doctype-state (stream state current-token)
(let ((data (html5-stream-char stream)))
(cond ((find data +space-characters+)
(setf state :before-doctype-name-state))
((eql data +eof+)
(push-token self '(:type :parse-error :data :expected-doctype-name-but-got-eof))
(setf (getf current-token :correct) nil)
(push-token self current-token)
(setf state :data-state))
(t
(push-token self '(:type :parse-error :data :need-space-after-doctype))
(html5-stream-unget stream data)
(setf state :before-doctype-name-state)))))
(defstate :before-doctype-name-state (stream state current-token)
(let ((data (html5-stream-char stream)))
(cond ((find data +space-characters+)
;; pass
)
((eql data #\>)
(push-token self '(:type :parse-error :data :expected-doctype-name-but-got-right-bracket))
(setf (getf current-token :correct) nil)
(push-token self current-token)
(setf state :data-state))
((eql data #\u0000)
(push-token self '(:type :parse-error :data :invalid-codepoint))
(add-to current-token :name #\uFFFD)
(setf state :doctype-name-state))
((eql data +eof+)
(push-token self '(:type :parse-error :data :expected-doctype-name-but-got-eof))
(setf (getf current-token :correct) nil)
(push-token self current-token)
(setf state :data-state))
(t
(setf (getf current-token :name) (string data))
(setf state :doctype-name-state)))))
(defstate :doctype-name-state (stream state current-token)
(let ((data (html5-stream-char stream)))
(cond ((find data +space-characters+)
(setf (getf current-token :name) (ascii-upper-2-lower (getf current-token :name)))
(setf state :after-doctype-name-state))
((eql data #\>)
(setf (getf current-token :name) (ascii-upper-2-lower (getf current-token :name)))
(push-token self current-token)
(setf state :data-state))
((eql data #\u0000)
(push-token self '(:type :parse-error :data :invalid-codepoint))
(add-to current-token :name #\uFFFD)
(setf state :doctype-name-state))
((eql data +eof+)
(push-token self '(:type :parse-error :data :eof-in-doctype-name))
(setf (getf current-token :correct) nil)
(setf (getf current-token :name) (ascii-upper-2-lower (getf current-token :name)))
(push-token self current-token)
(setf state :data-state))
(t
(add-to current-token :name data)))))
(defstate :after-doctype-name-state (stream state current-token)
(let ((data (html5-stream-char stream)))
(cond ((find data +space-characters+)
;; pass
)
((eql data #\>)
(push-token self current-token)
(setf state :data-state))
((eql data +eof+)
(setf (getf current-token :correct) nil)
(html5-stream-unget stream data)
(push-token self '(:type :parse-error :data :eof-in-doctype))
(push-token self current-token)
(setf state :data-state))
(t
(cond ((find data '(#\p #\P))
(let ((matched t))
(loop for expected in '((#\u #\U) (#\b #\B) (#\l #\L) (#\i #\I) (#\c #\C)) do
(setf data (html5-stream-char stream))
(unless (find data expected)
(setf matched nil)
(return)))
(when matched
(setf state :after-doctype-public-keyword-state)
(return t))))
((find data '(#\s #\S))
(let ((matched t))
(loop for expected in '((#\y #\Y) (#\s #\S) (#\t #\T) (#\e #\E) (#\m #\M)) do
(setf data (html5-stream-char stream))
(unless (find data expected)
(setf matched nil)
(return)))
(when matched
(setf state :after-doctype-system-keyword-state)
(return t)))))
;; All the characters read before the current 'data' will be
;; [a-zA-Z], so they're garbage in the bogus doctype and can be
;; discarded; only the latest character might be '>' or EOF
;; and needs to be ungetted
(html5-stream-unget stream data)
(push-token self `(:type :parse-error :data :expected-space-or-right-bracket-in-doctype
:datavars (:data ,data)))
(setf (getf current-token :correct) nil)
(setf state :bogus-doctype-state)))))
(defstate :after-doctype-public-keyword-state (stream state current-token)
(let ((data (html5-stream-char stream)))
(cond ((find data +space-characters+)
(setf state :before-doctype-public-identifier-state))
((find data '(#\' #\"))
(push-token self '(:type :parse-error :data :unexpected-char-in-doctype))
(html5-stream-unget stream data)
(setf state :before-doctype-public-identifier-state))
((eql data +eof+)
(push-token self '(:type :parse-error :data :eof-in-doctype))
(setf (getf current-token :correct) nil)
(push-token self current-token)
(setf state :data-state))
(t
(html5-stream-unget stream data)
(setf state :before-doctype-public-identifier-state)))))
(defstate :before-doctype-public-identifier-state (stream state current-token)
(let ((data (html5-stream-char stream)))
(cond ((find data +space-characters+)
;; pass
)
((eql data #\")
(setf (getf current-token :public-id) "")
(setf state :doctype-public-identifier-double-quoted-state))
((eql data #\')
(setf (getf current-token :public-id) "")
(setf state :doctype-public-identifier-single-quoted-state))
((eql data #\>)
(push-token self '(:type :parse-error :data :unexpected-end-of-doctype))
(setf (getf current-token :correct) nil)
(push-token self current-token)
(setf state :data-state))
((eql data +eof+)
(push-token self '(:type :parse-error :data :eof-in-doctype))
(setf (getf current-token :correct) nil)
(push-token self current-token)
(setf state :data-state))
(t
(push-token self '(:type :parse-error :data :unexpected-char-in-doctype))
(setf (getf current-token :correct) nil)
(setf state :bogus-doctype-state)))))
(defstate :doctype-public-identifier-double-quoted-state (stream state current-token)
(let ((data (html5-stream-char stream)))
(cond ((eql data #\")
(setf state :after-doctype-public-identifier-state))
((eql data #\u0000)
(push-token self '(:type :parse-error :data :invalid-codepoint))
(add-to current-token :public-id #\uFFFD))
((eql data #\>)
(push-token self '(:type :parse-error :data :unexpected-end-of-doctype))
(setf (getf current-token :correct) nil)
(push-token self current-token)
(setf state :data-state))
((eql data +eof+)
(push-token self '(:type :parse-error :data :eof-in-doctype))
(setf (getf current-token :correct) nil)
(push-token self current-token)
(setf state :data-state))
(t
(add-to current-token :public-id data)))))
(defstate :doctype-public-identifier-single-quoted-state (stream state current-token)
(let ((data (html5-stream-char stream)))
(cond ((eql data #\')
(setf state :after-doctype-public-identifier-state))
((eql data #\u0000)
(push-token self '(:type :parse-error :data :invalid-codepoint))
(add-to current-token :public-id #\uFFFD))
((eql data #\>)
(push-token self '(:type :parse-error :data :unexpected-end-of-doctype))
(setf (getf current-token :correct) nil)
(push-token self current-token)
(setf state :data-state))
((eql data +eof+)
(push-token self '(:type :parse-error :data :eof-in-doctype))
(setf (getf current-token :correct) nil)
(push-token self current-token)
(setf state :data-state))
(t
(add-to current-token :public-id data)))))
(defstate :after-doctype-public-identifier-state (stream state current-token)
(let ((data (html5-stream-char stream)))
(cond ((find data +space-characters+)
(setf state :between-doctype-public-and-system-identifiers-state))
((eql data #\>)
(push-token self current-token)
(setf state :data-state))
((eql data #\")
(push-token self '(:type :parse-error :data :unexpected-char-in-doctype))
(setf (getf current-token :system-id) "")
(setf state :doctype-system-identifier-double-quoted-state))
((eql data #\')
(push-token self '(:type :parse-error :data :unexpected-char-in-doctype))
(setf (getf current-token :system-id) "")
(setf state :doctype-system-identifier-single-quoted-state))
((eql data +eof+)
(push-token self '(:type :parse-error :data :eof-in-doctype))
(setf (getf current-token :correct) nil)
(push-token self current-token)
(setf state :data-state))
(t
(push-token self '(:type :parse-error :data :unexpected-char-in-doctype))
(setf (getf current-token :correct) nil)
(setf state :bogus-doctype-state)))))
(defstate :between-doctype-public-and-system-identifiers-state (stream state current-token)
(let ((data (html5-stream-char stream)))
(cond ((find data +space-characters+)
;; pass
)
((eql data #\>)
(push-token self current-token)
(setf state :data-state))
((eql data #\")
(setf (getf current-token :system-id) "")
(setf state :doctype-system-identifier-double-quoted-state))
((eql data #\')
(setf (getf current-token :system-id) "")
(setf state :doctype-system-identifier-single-quoted-state))
((eql data +eof+)
(push-token self '(:type :parse-error :data :eof-in-doctype))
(setf (getf current-token :correct) nil)
(push-token self current-token)
(setf state :data-state))
(t
(push-token self '(:type :parse-error :data :unexpected-char-in-doctype))
(setf (getf current-token :correct) nil)
(setf state :bogus-doctype-state)))))
(defstate :after-doctype-system-keyword-state (stream state current-token)
(let ((data (html5-stream-char stream)))
(cond ((find data +space-characters+)
(setf state :before-doctype-system-identifier-state))
((find data '(#\' #\"))
(push-token self '(:type :parse-error :data :unexpected-char-in-doctype))
(html5-stream-unget stream data)
(setf state :before-doctype-system-identifier-state))
((eql data +eof+)
(push-token self '(:type :parse-error :data :eof-in-doctype))
(setf (getf current-token :correct) nil)
(push-token self current-token)
(setf state :data-state))
(t
(html5-stream-unget stream data)
(setf state :before-doctype-system-identifier-state)))))
(defstate :before-doctype-system-identifier-state (stream state current-token)
(let ((data (html5-stream-char stream)))
(cond ((find data +space-characters+)
;; pass
)
((eql data #\")
(setf (getf current-token :system-id) "")
(setf state :doctype-system-identifier-double-quoted-state))
((eql data #\')
(setf (getf current-token :system-id) "")
(setf state :doctype-system-identifier-single-quoted-state))
((eql data #\>)
(push-token self '(:type :parse-error :data :unexpected-end-of-doctype))
(setf (getf current-token :correct) nil)
(push-token self current-token)
(setf state :data-state))
((eql data +eof+)
(push-token self '(:type :parse-error :data :eof-in-doctype))
(setf (getf current-token :correct) nil)
(push-token self current-token)
(setf state :data-state))
(t
(push-token self '(:type :parse-error :data :unexpected-char-in-doctype))
(setf (getf current-token :correct) nil)
(setf state :bogus-doctype-state)))))
(defstate :doctype-system-identifier-double-quoted-state (stream state current-token)
(let ((data (html5-stream-char stream)))
(cond ((eql data #\")
(setf state :after-doctype-system-identifier-state))
((eql data #\u0000)
(push-token self '(:type :parse-error :data :invalid-codepoint))
(add-to current-token :system-id #\uFFFD))
((eql data #\>)
(push-token self '(:type :parse-error :data :unexpected-end-of-doctype))
(setf (getf current-token :correct) nil)
(push-token self current-token)
(setf state :data-state))
((eql data +eof+)
(push-token self '(:type :parse-error :data :eof-in-doctype))
(setf (getf current-token :correct) nil)
(push-token self current-token)
(setf state :data-state))
(t
(add-to current-token :system-id data)))))
(defstate :doctype-system-identifier-single-quoted-state (stream state current-token)
(let ((data (html5-stream-char stream)))
(cond ((eql data #\')
(setf state :after-doctype-system-identifier-state))
((eql data #\u0000)
(push-token self '(:type :parse-error :data :invalid-codepoint))
(add-to current-token :system-id #\uFFFD))
((eql data #\>)
(push-token self '(:type :parse-error :data :unexpected-end-of-doctype))
(setf (getf current-token :correct) nil)
(push-token self current-token)
(setf state :data-state))
((eql data +eof+)
(push-token self '(:type :parse-error :data :eof-in-doctype))
(setf (getf current-token :correct) nil)
(push-token self current-token)
(setf state :data-state))
(t
(add-to current-token :system-id data)))))
(defstate :after-doctype-system-identifier-state (stream state current-token)
(let ((data (html5-stream-char stream)))
(cond ((find data +space-characters+)
;; pass
)
((eql data #\>)
(push-token self current-token)
(setf state :data-state))
((eql data +eof+)
(push-token self '(:type :parse-error :data :eof-in-doctype))
(setf (getf current-token :correct) nil)
(push-token self current-token)
(setf state :data-state))
(t
(push-token self '(:type :parse-error :data :unexpected-char-in-doctype))
(setf state :bogus-doctype-state)))))
(defstate :bogus-doctype-state (stream state current-token)
(let ((data (html5-stream-char stream)))
(cond ((eql data #\>)
(push-token self current-token)
(setf state :data-state))
((eql data +eof+)
;; XXX EMIT
(html5-stream-unget stream data)
(push-token self current-token)
(setf state :data-state))
(t
;; pass
))))
(defstate :cdata-section-state (stream state current-token)
(let ((data '()))
(loop
(push (html5-stream-chars-until stream '(#\])) data)
(let ((char-stack '())
(matched t))
(loop for expected across "]]>" do
(push (html5-stream-char stream) char-stack)
(cond ((eql (car char-stack) +eof+)
(pop char-stack)
(setf data (append char-stack data))
(return))
((not (eql (car char-stack) expected))
(setf matched nil)
(setf data (append char-stack data))
(return))))
(when matched
(return))))
(setf data (apply #'concatenate 'string (mapcar #'string (nreverse data))))
;; Deal with null here rather than in the parser
(let ((null-count (count #\u0000 data)))
(when (plusp null-count)
(push-token self '(:type :parse-error :data :invalid-codepoint))
(setf data (nsubstitute #\uFFFD #\u0000 data))))
(when (plusp (length data))
(push-token* self :characters data))
(setf state :data-state)))
| 73,626
|
Common Lisp
|
.lisp
| 1,541
| 35.303699
| 109
| 0.551958
|
rotatef/cl-html5-parser
| 55
| 14
| 11
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
f73c482c4b5f38a4e283b48d78bbaf27dc031bfd1e226a83872e39d859adc85b
| 3,077
|
[
-1
] |
3,078
|
entities.lisp
|
rotatef_cl-html5-parser/entities.lisp
|
;;;; HTML5 parser for Common Lisp
;;;;
;;;; Copyright (C) 2012 Thomas Bakketun <thomas.bakketun@copyleft.no>
;;;; Copyright (C) 2012 Asgeir Bj√∏rlykke <asgeir@copyleft.no>
;;;; Copyright (C) 2012 Mathias Hellevang
;;;; Copyright (C) 2012 Stian Sletner <stian@copyleft.no>
;;;;
;;;; This library is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Lesser General Public License as published
;;;; by the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This library 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 library. If not, see <http://www.gnu.org/licenses/>.
(in-package :html5-parser)
(defun convert-to-trie (char-list value)
(if (cdr char-list)
(list (car char-list)
nil
(convert-to-trie (rest char-list) value))
(list (car char-list)
value)))
(defun insert-into-trie (char-list value trie)
(let ((sub-trie (assoc (car char-list) trie)))
(if sub-trie
(append (remove sub-trie trie)
(list (list* (car sub-trie)
(cadr sub-trie)
(insert-into-trie (rest char-list) value (cddr sub-trie)))))
(append trie
(list (convert-to-trie char-list value))))))
(defun convert-entities-list (entities)
(loop for (name . values) in entities
collect (cons (coerce name 'list)
(map 'string #'code-char values))))
(defun make-entities-trie (entities)
(let (trie)
(dolist (entity (convert-entities-list entities))
(destructuring-bind (char-list . value) entity
(setf trie (insert-into-trie char-list value trie))))
trie))
(defparameter *entities*
'(("AElig" 198)
("AElig;" 198)
("AMP" 38)
("AMP;" 38)
("Aacute" 193)
("Aacute;" 193)
("Abreve;" 258)
("Acirc" 194)
("Acirc;" 194)
("Acy;" 1040)
("Afr;" 120068)
("Agrave" 192)
("Agrave;" 192)
("Alpha;" 913)
("Amacr;" 256)
("And;" 10835)
("Aogon;" 260)
("Aopf;" 120120)
("ApplyFunction;" 8289)
("Aring" 197)
("Aring;" 197)
("Ascr;" 119964)
("Assign;" 8788)
("Atilde" 195)
("Atilde;" 195)
("Auml" 196)
("Auml;" 196)
("Backslash;" 8726)
("Barv;" 10983)
("Barwed;" 8966)
("Bcy;" 1041)
("Because;" 8757)
("Bernoullis;" 8492)
("Beta;" 914)
("Bfr;" 120069)
("Bopf;" 120121)
("Breve;" 728)
("Bscr;" 8492)
("Bumpeq;" 8782)
("CHcy;" 1063)
("COPY" 169)
("COPY;" 169)
("Cacute;" 262)
("Cap;" 8914)
("CapitalDifferentialD;" 8517)
("Cayleys;" 8493)
("Ccaron;" 268)
("Ccedil" 199)
("Ccedil;" 199)
("Ccirc;" 264)
("Cconint;" 8752)
("Cdot;" 266)
("Cedilla;" 184)
("CenterDot;" 183)
("Cfr;" 8493)
("Chi;" 935)
("CircleDot;" 8857)
("CircleMinus;" 8854)
("CirclePlus;" 8853)
("CircleTimes;" 8855)
("ClockwiseContourIntegral;" 8754)
("CloseCurlyDoubleQuote;" 8221)
("CloseCurlyQuote;" 8217)
("Colon;" 8759)
("Colone;" 10868)
("Congruent;" 8801)
("Conint;" 8751)
("ContourIntegral;" 8750)
("Copf;" 8450)
("Coproduct;" 8720)
("CounterClockwiseContourIntegral;" 8755)
("Cross;" 10799)
("Cscr;" 119966)
("Cup;" 8915)
("CupCap;" 8781)
("DD;" 8517)
("DDotrahd;" 10513)
("DJcy;" 1026)
("DScy;" 1029)
("DZcy;" 1039)
("Dagger;" 8225)
("Darr;" 8609)
("Dashv;" 10980)
("Dcaron;" 270)
("Dcy;" 1044)
("Del;" 8711)
("Delta;" 916)
("Dfr;" 120071)
("DiacriticalAcute;" 180)
("DiacriticalDot;" 729)
("DiacriticalDoubleAcute;" 733)
("DiacriticalGrave;" 96)
("DiacriticalTilde;" 732)
("Diamond;" 8900)
("DifferentialD;" 8518)
("Dopf;" 120123)
("Dot;" 168)
("DotDot;" 8412)
("DotEqual;" 8784)
("DoubleContourIntegral;" 8751)
("DoubleDot;" 168)
("DoubleDownArrow;" 8659)
("DoubleLeftArrow;" 8656)
("DoubleLeftRightArrow;" 8660)
("DoubleLeftTee;" 10980)
("DoubleLongLeftArrow;" 10232)
("DoubleLongLeftRightArrow;" 10234)
("DoubleLongRightArrow;" 10233)
("DoubleRightArrow;" 8658)
("DoubleRightTee;" 8872)
("DoubleUpArrow;" 8657)
("DoubleUpDownArrow;" 8661)
("DoubleVerticalBar;" 8741)
("DownArrow;" 8595)
("DownArrowBar;" 10515)
("DownArrowUpArrow;" 8693)
("DownBreve;" 785)
("DownLeftRightVector;" 10576)
("DownLeftTeeVector;" 10590)
("DownLeftVector;" 8637)
("DownLeftVectorBar;" 10582)
("DownRightTeeVector;" 10591)
("DownRightVector;" 8641)
("DownRightVectorBar;" 10583)
("DownTee;" 8868)
("DownTeeArrow;" 8615)
("Downarrow;" 8659)
("Dscr;" 119967)
("Dstrok;" 272)
("ENG;" 330)
("ETH" 208)
("ETH;" 208)
("Eacute" 201)
("Eacute;" 201)
("Ecaron;" 282)
("Ecirc" 202)
("Ecirc;" 202)
("Ecy;" 1069)
("Edot;" 278)
("Efr;" 120072)
("Egrave" 200)
("Egrave;" 200)
("Element;" 8712)
("Emacr;" 274)
("EmptySmallSquare;" 9723)
("EmptyVerySmallSquare;" 9643)
("Eogon;" 280)
("Eopf;" 120124)
("Epsilon;" 917)
("Equal;" 10869)
("EqualTilde;" 8770)
("Equilibrium;" 8652)
("Escr;" 8496)
("Esim;" 10867)
("Eta;" 919)
("Euml" 203)
("Euml;" 203)
("Exists;" 8707)
("ExponentialE;" 8519)
("Fcy;" 1060)
("Ffr;" 120073)
("FilledSmallSquare;" 9724)
("FilledVerySmallSquare;" 9642)
("Fopf;" 120125)
("ForAll;" 8704)
("Fouriertrf;" 8497)
("Fscr;" 8497)
("GJcy;" 1027)
("GT" 62)
("GT;" 62)
("Gamma;" 915)
("Gammad;" 988)
("Gbreve;" 286)
("Gcedil;" 290)
("Gcirc;" 284)
("Gcy;" 1043)
("Gdot;" 288)
("Gfr;" 120074)
("Gg;" 8921)
("Gopf;" 120126)
("GreaterEqual;" 8805)
("GreaterEqualLess;" 8923)
("GreaterFullEqual;" 8807)
("GreaterGreater;" 10914)
("GreaterLess;" 8823)
("GreaterSlantEqual;" 10878)
("GreaterTilde;" 8819)
("Gscr;" 119970)
("Gt;" 8811)
("HARDcy;" 1066)
("Hacek;" 711)
("Hat;" 94)
("Hcirc;" 292)
("Hfr;" 8460)
("HilbertSpace;" 8459)
("Hopf;" 8461)
("HorizontalLine;" 9472)
("Hscr;" 8459)
("Hstrok;" 294)
("HumpDownHump;" 8782)
("HumpEqual;" 8783)
("IEcy;" 1045)
("IJlig;" 306)
("IOcy;" 1025)
("Iacute" 205)
("Iacute;" 205)
("Icirc" 206)
("Icirc;" 206)
("Icy;" 1048)
("Idot;" 304)
("Ifr;" 8465)
("Igrave" 204)
("Igrave;" 204)
("Im;" 8465)
("Imacr;" 298)
("ImaginaryI;" 8520)
("Implies;" 8658)
("Int;" 8748)
("Integral;" 8747)
("Intersection;" 8898)
("InvisibleComma;" 8291)
("InvisibleTimes;" 8290)
("Iogon;" 302)
("Iopf;" 120128)
("Iota;" 921)
("Iscr;" 8464)
("Itilde;" 296)
("Iukcy;" 1030)
("Iuml" 207)
("Iuml;" 207)
("Jcirc;" 308)
("Jcy;" 1049)
("Jfr;" 120077)
("Jopf;" 120129)
("Jscr;" 119973)
("Jsercy;" 1032)
("Jukcy;" 1028)
("KHcy;" 1061)
("KJcy;" 1036)
("Kappa;" 922)
("Kcedil;" 310)
("Kcy;" 1050)
("Kfr;" 120078)
("Kopf;" 120130)
("Kscr;" 119974)
("LJcy;" 1033)
("LT" 60)
("LT;" 60)
("Lacute;" 313)
("Lambda;" 923)
("Lang;" 10218)
("Laplacetrf;" 8466)
("Larr;" 8606)
("Lcaron;" 317)
("Lcedil;" 315)
("Lcy;" 1051)
("LeftAngleBracket;" 10216)
("LeftArrow;" 8592)
("LeftArrowBar;" 8676)
("LeftArrowRightArrow;" 8646)
("LeftCeiling;" 8968)
("LeftDoubleBracket;" 10214)
("LeftDownTeeVector;" 10593)
("LeftDownVector;" 8643)
("LeftDownVectorBar;" 10585)
("LeftFloor;" 8970)
("LeftRightArrow;" 8596)
("LeftRightVector;" 10574)
("LeftTee;" 8867)
("LeftTeeArrow;" 8612)
("LeftTeeVector;" 10586)
("LeftTriangle;" 8882)
("LeftTriangleBar;" 10703)
("LeftTriangleEqual;" 8884)
("LeftUpDownVector;" 10577)
("LeftUpTeeVector;" 10592)
("LeftUpVector;" 8639)
("LeftUpVectorBar;" 10584)
("LeftVector;" 8636)
("LeftVectorBar;" 10578)
("Leftarrow;" 8656)
("Leftrightarrow;" 8660)
("LessEqualGreater;" 8922)
("LessFullEqual;" 8806)
("LessGreater;" 8822)
("LessLess;" 10913)
("LessSlantEqual;" 10877)
("LessTilde;" 8818)
("Lfr;" 120079)
("Ll;" 8920)
("Lleftarrow;" 8666)
("Lmidot;" 319)
("LongLeftArrow;" 10229)
("LongLeftRightArrow;" 10231)
("LongRightArrow;" 10230)
("Longleftarrow;" 10232)
("Longleftrightarrow;" 10234)
("Longrightarrow;" 10233)
("Lopf;" 120131)
("LowerLeftArrow;" 8601)
("LowerRightArrow;" 8600)
("Lscr;" 8466)
("Lsh;" 8624)
("Lstrok;" 321)
("Lt;" 8810)
("Map;" 10501)
("Mcy;" 1052)
("MediumSpace;" 8287)
("Mellintrf;" 8499)
("Mfr;" 120080)
("MinusPlus;" 8723)
("Mopf;" 120132)
("Mscr;" 8499)
("Mu;" 924)
("NJcy;" 1034)
("Nacute;" 323)
("Ncaron;" 327)
("Ncedil;" 325)
("Ncy;" 1053)
("NegativeMediumSpace;" 8203)
("NegativeThickSpace;" 8203)
("NegativeThinSpace;" 8203)
("NegativeVeryThinSpace;" 8203)
("NestedGreaterGreater;" 8811)
("NestedLessLess;" 8810)
("NewLine;" 10)
("Nfr;" 120081)
("NoBreak;" 8288)
("NonBreakingSpace;" 160)
("Nopf;" 8469)
("Not;" 10988)
("NotCongruent;" 8802)
("NotCupCap;" 8813)
("NotDoubleVerticalBar;" 8742)
("NotElement;" 8713)
("NotEqual;" 8800)
("NotEqualTilde;" 8770 824)
("NotExists;" 8708)
("NotGreater;" 8815)
("NotGreaterEqual;" 8817)
("NotGreaterFullEqual;" 8807 824)
("NotGreaterGreater;" 8811 824)
("NotGreaterLess;" 8825)
("NotGreaterSlantEqual;" 10878 824)
("NotGreaterTilde;" 8821)
("NotHumpDownHump;" 8782 824)
("NotHumpEqual;" 8783 824)
("NotLeftTriangle;" 8938)
("NotLeftTriangleBar;" 10703 824)
("NotLeftTriangleEqual;" 8940)
("NotLess;" 8814)
("NotLessEqual;" 8816)
("NotLessGreater;" 8824)
("NotLessLess;" 8810 824)
("NotLessSlantEqual;" 10877 824)
("NotLessTilde;" 8820)
("NotNestedGreaterGreater;" 10914 824)
("NotNestedLessLess;" 10913 824)
("NotPrecedes;" 8832)
("NotPrecedesEqual;" 10927 824)
("NotPrecedesSlantEqual;" 8928)
("NotReverseElement;" 8716)
("NotRightTriangle;" 8939)
("NotRightTriangleBar;" 10704 824)
("NotRightTriangleEqual;" 8941)
("NotSquareSubset;" 8847 824)
("NotSquareSubsetEqual;" 8930)
("NotSquareSuperset;" 8848 824)
("NotSquareSupersetEqual;" 8931)
("NotSubset;" 8834 8402)
("NotSubsetEqual;" 8840)
("NotSucceeds;" 8833)
("NotSucceedsEqual;" 10928 824)
("NotSucceedsSlantEqual;" 8929)
("NotSucceedsTilde;" 8831 824)
("NotSuperset;" 8835 8402)
("NotSupersetEqual;" 8841)
("NotTilde;" 8769)
("NotTildeEqual;" 8772)
("NotTildeFullEqual;" 8775)
("NotTildeTilde;" 8777)
("NotVerticalBar;" 8740)
("Nscr;" 119977)
("Ntilde" 209)
("Ntilde;" 209)
("Nu;" 925)
("OElig;" 338)
("Oacute" 211)
("Oacute;" 211)
("Ocirc" 212)
("Ocirc;" 212)
("Ocy;" 1054)
("Odblac;" 336)
("Ofr;" 120082)
("Ograve" 210)
("Ograve;" 210)
("Omacr;" 332)
("Omega;" 937)
("Omicron;" 927)
("Oopf;" 120134)
("OpenCurlyDoubleQuote;" 8220)
("OpenCurlyQuote;" 8216)
("Or;" 10836)
("Oscr;" 119978)
("Oslash" 216)
("Oslash;" 216)
("Otilde" 213)
("Otilde;" 213)
("Otimes;" 10807)
("Ouml" 214)
("Ouml;" 214)
("OverBar;" 8254)
("OverBrace;" 9182)
("OverBracket;" 9140)
("OverParenthesis;" 9180)
("PartialD;" 8706)
("Pcy;" 1055)
("Pfr;" 120083)
("Phi;" 934)
("Pi;" 928)
("PlusMinus;" 177)
("Poincareplane;" 8460)
("Popf;" 8473)
("Pr;" 10939)
("Precedes;" 8826)
("PrecedesEqual;" 10927)
("PrecedesSlantEqual;" 8828)
("PrecedesTilde;" 8830)
("Prime;" 8243)
("Product;" 8719)
("Proportion;" 8759)
("Proportional;" 8733)
("Pscr;" 119979)
("Psi;" 936)
("QUOT" 34)
("QUOT;" 34)
("Qfr;" 120084)
("Qopf;" 8474)
("Qscr;" 119980)
("RBarr;" 10512)
("REG" 174)
("REG;" 174)
("Racute;" 340)
("Rang;" 10219)
("Rarr;" 8608)
("Rarrtl;" 10518)
("Rcaron;" 344)
("Rcedil;" 342)
("Rcy;" 1056)
("Re;" 8476)
("ReverseElement;" 8715)
("ReverseEquilibrium;" 8651)
("ReverseUpEquilibrium;" 10607)
("Rfr;" 8476)
("Rho;" 929)
("RightAngleBracket;" 10217)
("RightArrow;" 8594)
("RightArrowBar;" 8677)
("RightArrowLeftArrow;" 8644)
("RightCeiling;" 8969)
("RightDoubleBracket;" 10215)
("RightDownTeeVector;" 10589)
("RightDownVector;" 8642)
("RightDownVectorBar;" 10581)
("RightFloor;" 8971)
("RightTee;" 8866)
("RightTeeArrow;" 8614)
("RightTeeVector;" 10587)
("RightTriangle;" 8883)
("RightTriangleBar;" 10704)
("RightTriangleEqual;" 8885)
("RightUpDownVector;" 10575)
("RightUpTeeVector;" 10588)
("RightUpVector;" 8638)
("RightUpVectorBar;" 10580)
("RightVector;" 8640)
("RightVectorBar;" 10579)
("Rightarrow;" 8658)
("Ropf;" 8477)
("RoundImplies;" 10608)
("Rrightarrow;" 8667)
("Rscr;" 8475)
("Rsh;" 8625)
("RuleDelayed;" 10740)
("SHCHcy;" 1065)
("SHcy;" 1064)
("SOFTcy;" 1068)
("Sacute;" 346)
("Sc;" 10940)
("Scaron;" 352)
("Scedil;" 350)
("Scirc;" 348)
("Scy;" 1057)
("Sfr;" 120086)
("ShortDownArrow;" 8595)
("ShortLeftArrow;" 8592)
("ShortRightArrow;" 8594)
("ShortUpArrow;" 8593)
("Sigma;" 931)
("SmallCircle;" 8728)
("Sopf;" 120138)
("Sqrt;" 8730)
("Square;" 9633)
("SquareIntersection;" 8851)
("SquareSubset;" 8847)
("SquareSubsetEqual;" 8849)
("SquareSuperset;" 8848)
("SquareSupersetEqual;" 8850)
("SquareUnion;" 8852)
("Sscr;" 119982)
("Star;" 8902)
("Sub;" 8912)
("Subset;" 8912)
("SubsetEqual;" 8838)
("Succeeds;" 8827)
("SucceedsEqual;" 10928)
("SucceedsSlantEqual;" 8829)
("SucceedsTilde;" 8831)
("SuchThat;" 8715)
("Sum;" 8721)
("Sup;" 8913)
("Superset;" 8835)
("SupersetEqual;" 8839)
("Supset;" 8913)
("THORN" 222)
("THORN;" 222)
("TRADE;" 8482)
("TSHcy;" 1035)
("TScy;" 1062)
("Tab;" 9)
("Tau;" 932)
("Tcaron;" 356)
("Tcedil;" 354)
("Tcy;" 1058)
("Tfr;" 120087)
("Therefore;" 8756)
("Theta;" 920)
("ThickSpace;" 8287 8202)
("ThinSpace;" 8201)
("Tilde;" 8764)
("TildeEqual;" 8771)
("TildeFullEqual;" 8773)
("TildeTilde;" 8776)
("Topf;" 120139)
("TripleDot;" 8411)
("Tscr;" 119983)
("Tstrok;" 358)
("Uacute" 218)
("Uacute;" 218)
("Uarr;" 8607)
("Uarrocir;" 10569)
("Ubrcy;" 1038)
("Ubreve;" 364)
("Ucirc" 219)
("Ucirc;" 219)
("Ucy;" 1059)
("Udblac;" 368)
("Ufr;" 120088)
("Ugrave" 217)
("Ugrave;" 217)
("Umacr;" 362)
("UnderBar;" 95)
("UnderBrace;" 9183)
("UnderBracket;" 9141)
("UnderParenthesis;" 9181)
("Union;" 8899)
("UnionPlus;" 8846)
("Uogon;" 370)
("Uopf;" 120140)
("UpArrow;" 8593)
("UpArrowBar;" 10514)
("UpArrowDownArrow;" 8645)
("UpDownArrow;" 8597)
("UpEquilibrium;" 10606)
("UpTee;" 8869)
("UpTeeArrow;" 8613)
("Uparrow;" 8657)
("Updownarrow;" 8661)
("UpperLeftArrow;" 8598)
("UpperRightArrow;" 8599)
("Upsi;" 978)
("Upsilon;" 933)
("Uring;" 366)
("Uscr;" 119984)
("Utilde;" 360)
("Uuml" 220)
("Uuml;" 220)
("VDash;" 8875)
("Vbar;" 10987)
("Vcy;" 1042)
("Vdash;" 8873)
("Vdashl;" 10982)
("Vee;" 8897)
("Verbar;" 8214)
("Vert;" 8214)
("VerticalBar;" 8739)
("VerticalLine;" 124)
("VerticalSeparator;" 10072)
("VerticalTilde;" 8768)
("VeryThinSpace;" 8202)
("Vfr;" 120089)
("Vopf;" 120141)
("Vscr;" 119985)
("Vvdash;" 8874)
("Wcirc;" 372)
("Wedge;" 8896)
("Wfr;" 120090)
("Wopf;" 120142)
("Wscr;" 119986)
("Xfr;" 120091)
("Xi;" 926)
("Xopf;" 120143)
("Xscr;" 119987)
("YAcy;" 1071)
("YIcy;" 1031)
("YUcy;" 1070)
("Yacute" 221)
("Yacute;" 221)
("Ycirc;" 374)
("Ycy;" 1067)
("Yfr;" 120092)
("Yopf;" 120144)
("Yscr;" 119988)
("Yuml;" 376)
("ZHcy;" 1046)
("Zacute;" 377)
("Zcaron;" 381)
("Zcy;" 1047)
("Zdot;" 379)
("ZeroWidthSpace;" 8203)
("Zeta;" 918)
("Zfr;" 8488)
("Zopf;" 8484)
("Zscr;" 119989)
("aacute" 225)
("aacute;" 225)
("abreve;" 259)
("ac;" 8766)
("acE;" 8766 819)
("acd;" 8767)
("acirc" 226)
("acirc;" 226)
("acute" 180)
("acute;" 180)
("acy;" 1072)
("aelig" 230)
("aelig;" 230)
("af;" 8289)
("afr;" 120094)
("agrave" 224)
("agrave;" 224)
("alefsym;" 8501)
("aleph;" 8501)
("alpha;" 945)
("amacr;" 257)
("amalg;" 10815)
("amp" 38)
("amp;" 38)
("and;" 8743)
("andand;" 10837)
("andd;" 10844)
("andslope;" 10840)
("andv;" 10842)
("ang;" 8736)
("ange;" 10660)
("angle;" 8736)
("angmsd;" 8737)
("angmsdaa;" 10664)
("angmsdab;" 10665)
("angmsdac;" 10666)
("angmsdad;" 10667)
("angmsdae;" 10668)
("angmsdaf;" 10669)
("angmsdag;" 10670)
("angmsdah;" 10671)
("angrt;" 8735)
("angrtvb;" 8894)
("angrtvbd;" 10653)
("angsph;" 8738)
("angst;" 197)
("angzarr;" 9084)
("aogon;" 261)
("aopf;" 120146)
("ap;" 8776)
("apE;" 10864)
("apacir;" 10863)
("ape;" 8778)
("apid;" 8779)
("apos;" 39)
("approx;" 8776)
("approxeq;" 8778)
("aring" 229)
("aring;" 229)
("ascr;" 119990)
("ast;" 42)
("asymp;" 8776)
("asympeq;" 8781)
("atilde" 227)
("atilde;" 227)
("auml" 228)
("auml;" 228)
("awconint;" 8755)
("awint;" 10769)
("bNot;" 10989)
("backcong;" 8780)
("backepsilon;" 1014)
("backprime;" 8245)
("backsim;" 8765)
("backsimeq;" 8909)
("barvee;" 8893)
("barwed;" 8965)
("barwedge;" 8965)
("bbrk;" 9141)
("bbrktbrk;" 9142)
("bcong;" 8780)
("bcy;" 1073)
("bdquo;" 8222)
("becaus;" 8757)
("because;" 8757)
("bemptyv;" 10672)
("bepsi;" 1014)
("bernou;" 8492)
("beta;" 946)
("beth;" 8502)
("between;" 8812)
("bfr;" 120095)
("bigcap;" 8898)
("bigcirc;" 9711)
("bigcup;" 8899)
("bigodot;" 10752)
("bigoplus;" 10753)
("bigotimes;" 10754)
("bigsqcup;" 10758)
("bigstar;" 9733)
("bigtriangledown;" 9661)
("bigtriangleup;" 9651)
("biguplus;" 10756)
("bigvee;" 8897)
("bigwedge;" 8896)
("bkarow;" 10509)
("blacklozenge;" 10731)
("blacksquare;" 9642)
("blacktriangle;" 9652)
("blacktriangledown;" 9662)
("blacktriangleleft;" 9666)
("blacktriangleright;" 9656)
("blank;" 9251)
("blk12;" 9618)
("blk14;" 9617)
("blk34;" 9619)
("block;" 9608)
("bne;" 61 8421)
("bnequiv;" 8801 8421)
("bnot;" 8976)
("bopf;" 120147)
("bot;" 8869)
("bottom;" 8869)
("bowtie;" 8904)
("boxDL;" 9559)
("boxDR;" 9556)
("boxDl;" 9558)
("boxDr;" 9555)
("boxH;" 9552)
("boxHD;" 9574)
("boxHU;" 9577)
("boxHd;" 9572)
("boxHu;" 9575)
("boxUL;" 9565)
("boxUR;" 9562)
("boxUl;" 9564)
("boxUr;" 9561)
("boxV;" 9553)
("boxVH;" 9580)
("boxVL;" 9571)
("boxVR;" 9568)
("boxVh;" 9579)
("boxVl;" 9570)
("boxVr;" 9567)
("boxbox;" 10697)
("boxdL;" 9557)
("boxdR;" 9554)
("boxdl;" 9488)
("boxdr;" 9484)
("boxh;" 9472)
("boxhD;" 9573)
("boxhU;" 9576)
("boxhd;" 9516)
("boxhu;" 9524)
("boxminus;" 8863)
("boxplus;" 8862)
("boxtimes;" 8864)
("boxuL;" 9563)
("boxuR;" 9560)
("boxul;" 9496)
("boxur;" 9492)
("boxv;" 9474)
("boxvH;" 9578)
("boxvL;" 9569)
("boxvR;" 9566)
("boxvh;" 9532)
("boxvl;" 9508)
("boxvr;" 9500)
("bprime;" 8245)
("breve;" 728)
("brvbar" 166)
("brvbar;" 166)
("bscr;" 119991)
("bsemi;" 8271)
("bsim;" 8765)
("bsime;" 8909)
("bsol;" 92)
("bsolb;" 10693)
("bsolhsub;" 10184)
("bull;" 8226)
("bullet;" 8226)
("bump;" 8782)
("bumpE;" 10926)
("bumpe;" 8783)
("bumpeq;" 8783)
("cacute;" 263)
("cap;" 8745)
("capand;" 10820)
("capbrcup;" 10825)
("capcap;" 10827)
("capcup;" 10823)
("capdot;" 10816)
("caps;" 8745 65024)
("caret;" 8257)
("caron;" 711)
("ccaps;" 10829)
("ccaron;" 269)
("ccedil" 231)
("ccedil;" 231)
("ccirc;" 265)
("ccups;" 10828)
("ccupssm;" 10832)
("cdot;" 267)
("cedil" 184)
("cedil;" 184)
("cemptyv;" 10674)
("cent" 162)
("cent;" 162)
("centerdot;" 183)
("cfr;" 120096)
("chcy;" 1095)
("check;" 10003)
("checkmark;" 10003)
("chi;" 967)
("cir;" 9675)
("cirE;" 10691)
("circ;" 710)
("circeq;" 8791)
("circlearrowleft;" 8634)
("circlearrowright;" 8635)
("circledR;" 174)
("circledS;" 9416)
("circledast;" 8859)
("circledcirc;" 8858)
("circleddash;" 8861)
("cire;" 8791)
("cirfnint;" 10768)
("cirmid;" 10991)
("cirscir;" 10690)
("clubs;" 9827)
("clubsuit;" 9827)
("colon;" 58)
("colone;" 8788)
("coloneq;" 8788)
("comma;" 44)
("commat;" 64)
("comp;" 8705)
("compfn;" 8728)
("complement;" 8705)
("complexes;" 8450)
("cong;" 8773)
("congdot;" 10861)
("conint;" 8750)
("copf;" 120148)
("coprod;" 8720)
("copy" 169)
("copy;" 169)
("copysr;" 8471)
("crarr;" 8629)
("cross;" 10007)
("cscr;" 119992)
("csub;" 10959)
("csube;" 10961)
("csup;" 10960)
("csupe;" 10962)
("ctdot;" 8943)
("cudarrl;" 10552)
("cudarrr;" 10549)
("cuepr;" 8926)
("cuesc;" 8927)
("cularr;" 8630)
("cularrp;" 10557)
("cup;" 8746)
("cupbrcap;" 10824)
("cupcap;" 10822)
("cupcup;" 10826)
("cupdot;" 8845)
("cupor;" 10821)
("cups;" 8746 65024)
("curarr;" 8631)
("curarrm;" 10556)
("curlyeqprec;" 8926)
("curlyeqsucc;" 8927)
("curlyvee;" 8910)
("curlywedge;" 8911)
("curren" 164)
("curren;" 164)
("curvearrowleft;" 8630)
("curvearrowright;" 8631)
("cuvee;" 8910)
("cuwed;" 8911)
("cwconint;" 8754)
("cwint;" 8753)
("cylcty;" 9005)
("dArr;" 8659)
("dHar;" 10597)
("dagger;" 8224)
("daleth;" 8504)
("darr;" 8595)
("dash;" 8208)
("dashv;" 8867)
("dbkarow;" 10511)
("dblac;" 733)
("dcaron;" 271)
("dcy;" 1076)
("dd;" 8518)
("ddagger;" 8225)
("ddarr;" 8650)
("ddotseq;" 10871)
("deg" 176)
("deg;" 176)
("delta;" 948)
("demptyv;" 10673)
("dfisht;" 10623)
("dfr;" 120097)
("dharl;" 8643)
("dharr;" 8642)
("diam;" 8900)
("diamond;" 8900)
("diamondsuit;" 9830)
("diams;" 9830)
("die;" 168)
("digamma;" 989)
("disin;" 8946)
("div;" 247)
("divide" 247)
("divide;" 247)
("divideontimes;" 8903)
("divonx;" 8903)
("djcy;" 1106)
("dlcorn;" 8990)
("dlcrop;" 8973)
("dollar;" 36)
("dopf;" 120149)
("dot;" 729)
("doteq;" 8784)
("doteqdot;" 8785)
("dotminus;" 8760)
("dotplus;" 8724)
("dotsquare;" 8865)
("doublebarwedge;" 8966)
("downarrow;" 8595)
("downdownarrows;" 8650)
("downharpoonleft;" 8643)
("downharpoonright;" 8642)
("drbkarow;" 10512)
("drcorn;" 8991)
("drcrop;" 8972)
("dscr;" 119993)
("dscy;" 1109)
("dsol;" 10742)
("dstrok;" 273)
("dtdot;" 8945)
("dtri;" 9663)
("dtrif;" 9662)
("duarr;" 8693)
("duhar;" 10607)
("dwangle;" 10662)
("dzcy;" 1119)
("dzigrarr;" 10239)
("eDDot;" 10871)
("eDot;" 8785)
("eacute" 233)
("eacute;" 233)
("easter;" 10862)
("ecaron;" 283)
("ecir;" 8790)
("ecirc" 234)
("ecirc;" 234)
("ecolon;" 8789)
("ecy;" 1101)
("edot;" 279)
("ee;" 8519)
("efDot;" 8786)
("efr;" 120098)
("eg;" 10906)
("egrave" 232)
("egrave;" 232)
("egs;" 10902)
("egsdot;" 10904)
("el;" 10905)
("elinters;" 9191)
("ell;" 8467)
("els;" 10901)
("elsdot;" 10903)
("emacr;" 275)
("empty;" 8709)
("emptyset;" 8709)
("emptyv;" 8709)
("emsp13;" 8196)
("emsp14;" 8197)
("emsp;" 8195)
("eng;" 331)
("ensp;" 8194)
("eogon;" 281)
("eopf;" 120150)
("epar;" 8917)
("eparsl;" 10723)
("eplus;" 10865)
("epsi;" 949)
("epsilon;" 949)
("epsiv;" 1013)
("eqcirc;" 8790)
("eqcolon;" 8789)
("eqsim;" 8770)
("eqslantgtr;" 10902)
("eqslantless;" 10901)
("equals;" 61)
("equest;" 8799)
("equiv;" 8801)
("equivDD;" 10872)
("eqvparsl;" 10725)
("erDot;" 8787)
("erarr;" 10609)
("escr;" 8495)
("esdot;" 8784)
("esim;" 8770)
("eta;" 951)
("eth" 240)
("eth;" 240)
("euml" 235)
("euml;" 235)
("euro;" 8364)
("excl;" 33)
("exist;" 8707)
("expectation;" 8496)
("exponentiale;" 8519)
("fallingdotseq;" 8786)
("fcy;" 1092)
("female;" 9792)
("ffilig;" 64259)
("fflig;" 64256)
("ffllig;" 64260)
("ffr;" 120099)
("filig;" 64257)
("fjlig;" 102 106)
("flat;" 9837)
("fllig;" 64258)
("fltns;" 9649)
("fnof;" 402)
("fopf;" 120151)
("forall;" 8704)
("fork;" 8916)
("forkv;" 10969)
("fpartint;" 10765)
("frac12" 189)
("frac12;" 189)
("frac13;" 8531)
("frac14" 188)
("frac14;" 188)
("frac15;" 8533)
("frac16;" 8537)
("frac18;" 8539)
("frac23;" 8532)
("frac25;" 8534)
("frac34" 190)
("frac34;" 190)
("frac35;" 8535)
("frac38;" 8540)
("frac45;" 8536)
("frac56;" 8538)
("frac58;" 8541)
("frac78;" 8542)
("frasl;" 8260)
("frown;" 8994)
("fscr;" 119995)
("gE;" 8807)
("gEl;" 10892)
("gacute;" 501)
("gamma;" 947)
("gammad;" 989)
("gap;" 10886)
("gbreve;" 287)
("gcirc;" 285)
("gcy;" 1075)
("gdot;" 289)
("ge;" 8805)
("gel;" 8923)
("geq;" 8805)
("geqq;" 8807)
("geqslant;" 10878)
("ges;" 10878)
("gescc;" 10921)
("gesdot;" 10880)
("gesdoto;" 10882)
("gesdotol;" 10884)
("gesl;" 8923 65024)
("gesles;" 10900)
("gfr;" 120100)
("gg;" 8811)
("ggg;" 8921)
("gimel;" 8503)
("gjcy;" 1107)
("gl;" 8823)
("glE;" 10898)
("gla;" 10917)
("glj;" 10916)
("gnE;" 8809)
("gnap;" 10890)
("gnapprox;" 10890)
("gne;" 10888)
("gneq;" 10888)
("gneqq;" 8809)
("gnsim;" 8935)
("gopf;" 120152)
("grave;" 96)
("gscr;" 8458)
("gsim;" 8819)
("gsime;" 10894)
("gsiml;" 10896)
("gt" 62)
("gt;" 62)
("gtcc;" 10919)
("gtcir;" 10874)
("gtdot;" 8919)
("gtlPar;" 10645)
("gtquest;" 10876)
("gtrapprox;" 10886)
("gtrarr;" 10616)
("gtrdot;" 8919)
("gtreqless;" 8923)
("gtreqqless;" 10892)
("gtrless;" 8823)
("gtrsim;" 8819)
("gvertneqq;" 8809 65024)
("gvnE;" 8809 65024)
("hArr;" 8660)
("hairsp;" 8202)
("half;" 189)
("hamilt;" 8459)
("hardcy;" 1098)
("harr;" 8596)
("harrcir;" 10568)
("harrw;" 8621)
("hbar;" 8463)
("hcirc;" 293)
("hearts;" 9829)
("heartsuit;" 9829)
("hellip;" 8230)
("hercon;" 8889)
("hfr;" 120101)
("hksearow;" 10533)
("hkswarow;" 10534)
("hoarr;" 8703)
("homtht;" 8763)
("hookleftarrow;" 8617)
("hookrightarrow;" 8618)
("hopf;" 120153)
("horbar;" 8213)
("hscr;" 119997)
("hslash;" 8463)
("hstrok;" 295)
("hybull;" 8259)
("hyphen;" 8208)
("iacute" 237)
("iacute;" 237)
("ic;" 8291)
("icirc" 238)
("icirc;" 238)
("icy;" 1080)
("iecy;" 1077)
("iexcl" 161)
("iexcl;" 161)
("iff;" 8660)
("ifr;" 120102)
("igrave" 236)
("igrave;" 236)
("ii;" 8520)
("iiiint;" 10764)
("iiint;" 8749)
("iinfin;" 10716)
("iiota;" 8489)
("ijlig;" 307)
("imacr;" 299)
("image;" 8465)
("imagline;" 8464)
("imagpart;" 8465)
("imath;" 305)
("imof;" 8887)
("imped;" 437)
("in;" 8712)
("incare;" 8453)
("infin;" 8734)
("infintie;" 10717)
("inodot;" 305)
("int;" 8747)
("intcal;" 8890)
("integers;" 8484)
("intercal;" 8890)
("intlarhk;" 10775)
("intprod;" 10812)
("iocy;" 1105)
("iogon;" 303)
("iopf;" 120154)
("iota;" 953)
("iprod;" 10812)
("iquest" 191)
("iquest;" 191)
("iscr;" 119998)
("isin;" 8712)
("isinE;" 8953)
("isindot;" 8949)
("isins;" 8948)
("isinsv;" 8947)
("isinv;" 8712)
("it;" 8290)
("itilde;" 297)
("iukcy;" 1110)
("iuml" 239)
("iuml;" 239)
("jcirc;" 309)
("jcy;" 1081)
("jfr;" 120103)
("jmath;" 567)
("jopf;" 120155)
("jscr;" 119999)
("jsercy;" 1112)
("jukcy;" 1108)
("kappa;" 954)
("kappav;" 1008)
("kcedil;" 311)
("kcy;" 1082)
("kfr;" 120104)
("kgreen;" 312)
("khcy;" 1093)
("kjcy;" 1116)
("kopf;" 120156)
("kscr;" 120000)
("lAarr;" 8666)
("lArr;" 8656)
("lAtail;" 10523)
("lBarr;" 10510)
("lE;" 8806)
("lEg;" 10891)
("lHar;" 10594)
("lacute;" 314)
("laemptyv;" 10676)
("lagran;" 8466)
("lambda;" 955)
("lang;" 10216)
("langd;" 10641)
("langle;" 10216)
("lap;" 10885)
("laquo" 171)
("laquo;" 171)
("larr;" 8592)
("larrb;" 8676)
("larrbfs;" 10527)
("larrfs;" 10525)
("larrhk;" 8617)
("larrlp;" 8619)
("larrpl;" 10553)
("larrsim;" 10611)
("larrtl;" 8610)
("lat;" 10923)
("latail;" 10521)
("late;" 10925)
("lates;" 10925 65024)
("lbarr;" 10508)
("lbbrk;" 10098)
("lbrace;" 123)
("lbrack;" 91)
("lbrke;" 10635)
("lbrksld;" 10639)
("lbrkslu;" 10637)
("lcaron;" 318)
("lcedil;" 316)
("lceil;" 8968)
("lcub;" 123)
("lcy;" 1083)
("ldca;" 10550)
("ldquo;" 8220)
("ldquor;" 8222)
("ldrdhar;" 10599)
("ldrushar;" 10571)
("ldsh;" 8626)
("le;" 8804)
("leftarrow;" 8592)
("leftarrowtail;" 8610)
("leftharpoondown;" 8637)
("leftharpoonup;" 8636)
("leftleftarrows;" 8647)
("leftrightarrow;" 8596)
("leftrightarrows;" 8646)
("leftrightharpoons;" 8651)
("leftrightsquigarrow;" 8621)
("leftthreetimes;" 8907)
("leg;" 8922)
("leq;" 8804)
("leqq;" 8806)
("leqslant;" 10877)
("les;" 10877)
("lescc;" 10920)
("lesdot;" 10879)
("lesdoto;" 10881)
("lesdotor;" 10883)
("lesg;" 8922 65024)
("lesges;" 10899)
("lessapprox;" 10885)
("lessdot;" 8918)
("lesseqgtr;" 8922)
("lesseqqgtr;" 10891)
("lessgtr;" 8822)
("lesssim;" 8818)
("lfisht;" 10620)
("lfloor;" 8970)
("lfr;" 120105)
("lg;" 8822)
("lgE;" 10897)
("lhard;" 8637)
("lharu;" 8636)
("lharul;" 10602)
("lhblk;" 9604)
("ljcy;" 1113)
("ll;" 8810)
("llarr;" 8647)
("llcorner;" 8990)
("llhard;" 10603)
("lltri;" 9722)
("lmidot;" 320)
("lmoust;" 9136)
("lmoustache;" 9136)
("lnE;" 8808)
("lnap;" 10889)
("lnapprox;" 10889)
("lne;" 10887)
("lneq;" 10887)
("lneqq;" 8808)
("lnsim;" 8934)
("loang;" 10220)
("loarr;" 8701)
("lobrk;" 10214)
("longleftarrow;" 10229)
("longleftrightarrow;" 10231)
("longmapsto;" 10236)
("longrightarrow;" 10230)
("looparrowleft;" 8619)
("looparrowright;" 8620)
("lopar;" 10629)
("lopf;" 120157)
("loplus;" 10797)
("lotimes;" 10804)
("lowast;" 8727)
("lowbar;" 95)
("loz;" 9674)
("lozenge;" 9674)
("lozf;" 10731)
("lpar;" 40)
("lparlt;" 10643)
("lrarr;" 8646)
("lrcorner;" 8991)
("lrhar;" 8651)
("lrhard;" 10605)
("lrm;" 8206)
("lrtri;" 8895)
("lsaquo;" 8249)
("lscr;" 120001)
("lsh;" 8624)
("lsim;" 8818)
("lsime;" 10893)
("lsimg;" 10895)
("lsqb;" 91)
("lsquo;" 8216)
("lsquor;" 8218)
("lstrok;" 322)
("lt" 60)
("lt;" 60)
("ltcc;" 10918)
("ltcir;" 10873)
("ltdot;" 8918)
("lthree;" 8907)
("ltimes;" 8905)
("ltlarr;" 10614)
("ltquest;" 10875)
("ltrPar;" 10646)
("ltri;" 9667)
("ltrie;" 8884)
("ltrif;" 9666)
("lurdshar;" 10570)
("luruhar;" 10598)
("lvertneqq;" 8808 65024)
("lvnE;" 8808 65024)
("mDDot;" 8762)
("macr" 175)
("macr;" 175)
("male;" 9794)
("malt;" 10016)
("maltese;" 10016)
("map;" 8614)
("mapsto;" 8614)
("mapstodown;" 8615)
("mapstoleft;" 8612)
("mapstoup;" 8613)
("marker;" 9646)
("mcomma;" 10793)
("mcy;" 1084)
("mdash;" 8212)
("measuredangle;" 8737)
("mfr;" 120106)
("mho;" 8487)
("micro" 181)
("micro;" 181)
("mid;" 8739)
("midast;" 42)
("midcir;" 10992)
("middot" 183)
("middot;" 183)
("minus;" 8722)
("minusb;" 8863)
("minusd;" 8760)
("minusdu;" 10794)
("mlcp;" 10971)
("mldr;" 8230)
("mnplus;" 8723)
("models;" 8871)
("mopf;" 120158)
("mp;" 8723)
("mscr;" 120002)
("mstpos;" 8766)
("mu;" 956)
("multimap;" 8888)
("mumap;" 8888)
("nGg;" 8921 824)
("nGt;" 8811 8402)
("nGtv;" 8811 824)
("nLeftarrow;" 8653)
("nLeftrightarrow;" 8654)
("nLl;" 8920 824)
("nLt;" 8810 8402)
("nLtv;" 8810 824)
("nRightarrow;" 8655)
("nVDash;" 8879)
("nVdash;" 8878)
("nabla;" 8711)
("nacute;" 324)
("nang;" 8736 8402)
("nap;" 8777)
("napE;" 10864 824)
("napid;" 8779 824)
("napos;" 329)
("napprox;" 8777)
("natur;" 9838)
("natural;" 9838)
("naturals;" 8469)
("nbsp" 160)
("nbsp;" 160)
("nbump;" 8782 824)
("nbumpe;" 8783 824)
("ncap;" 10819)
("ncaron;" 328)
("ncedil;" 326)
("ncong;" 8775)
("ncongdot;" 10861 824)
("ncup;" 10818)
("ncy;" 1085)
("ndash;" 8211)
("ne;" 8800)
("neArr;" 8663)
("nearhk;" 10532)
("nearr;" 8599)
("nearrow;" 8599)
("nedot;" 8784 824)
("nequiv;" 8802)
("nesear;" 10536)
("nesim;" 8770 824)
("nexist;" 8708)
("nexists;" 8708)
("nfr;" 120107)
("ngE;" 8807 824)
("nge;" 8817)
("ngeq;" 8817)
("ngeqq;" 8807 824)
("ngeqslant;" 10878 824)
("nges;" 10878 824)
("ngsim;" 8821)
("ngt;" 8815)
("ngtr;" 8815)
("nhArr;" 8654)
("nharr;" 8622)
("nhpar;" 10994)
("ni;" 8715)
("nis;" 8956)
("nisd;" 8954)
("niv;" 8715)
("njcy;" 1114)
("nlArr;" 8653)
("nlE;" 8806 824)
("nlarr;" 8602)
("nldr;" 8229)
("nle;" 8816)
("nleftarrow;" 8602)
("nleftrightarrow;" 8622)
("nleq;" 8816)
("nleqq;" 8806 824)
("nleqslant;" 10877 824)
("nles;" 10877 824)
("nless;" 8814)
("nlsim;" 8820)
("nlt;" 8814)
("nltri;" 8938)
("nltrie;" 8940)
("nmid;" 8740)
("nopf;" 120159)
("not" 172)
("not;" 172)
("notin;" 8713)
("notinE;" 8953 824)
("notindot;" 8949 824)
("notinva;" 8713)
("notinvb;" 8951)
("notinvc;" 8950)
("notni;" 8716)
("notniva;" 8716)
("notnivb;" 8958)
("notnivc;" 8957)
("npar;" 8742)
("nparallel;" 8742)
("nparsl;" 11005 8421)
("npart;" 8706 824)
("npolint;" 10772)
("npr;" 8832)
("nprcue;" 8928)
("npre;" 10927 824)
("nprec;" 8832)
("npreceq;" 10927 824)
("nrArr;" 8655)
("nrarr;" 8603)
("nrarrc;" 10547 824)
("nrarrw;" 8605 824)
("nrightarrow;" 8603)
("nrtri;" 8939)
("nrtrie;" 8941)
("nsc;" 8833)
("nsccue;" 8929)
("nsce;" 10928 824)
("nscr;" 120003)
("nshortmid;" 8740)
("nshortparallel;" 8742)
("nsim;" 8769)
("nsime;" 8772)
("nsimeq;" 8772)
("nsmid;" 8740)
("nspar;" 8742)
("nsqsube;" 8930)
("nsqsupe;" 8931)
("nsub;" 8836)
("nsubE;" 10949 824)
("nsube;" 8840)
("nsubset;" 8834 8402)
("nsubseteq;" 8840)
("nsubseteqq;" 10949 824)
("nsucc;" 8833)
("nsucceq;" 10928 824)
("nsup;" 8837)
("nsupE;" 10950 824)
("nsupe;" 8841)
("nsupset;" 8835 8402)
("nsupseteq;" 8841)
("nsupseteqq;" 10950 824)
("ntgl;" 8825)
("ntilde" 241)
("ntilde;" 241)
("ntlg;" 8824)
("ntriangleleft;" 8938)
("ntrianglelefteq;" 8940)
("ntriangleright;" 8939)
("ntrianglerighteq;" 8941)
("nu;" 957)
("num;" 35)
("numero;" 8470)
("numsp;" 8199)
("nvDash;" 8877)
("nvHarr;" 10500)
("nvap;" 8781 8402)
("nvdash;" 8876)
("nvge;" 8805 8402)
("nvgt;" 62 8402)
("nvinfin;" 10718)
("nvlArr;" 10498)
("nvle;" 8804 8402)
("nvlt;" 60 8402)
("nvltrie;" 8884 8402)
("nvrArr;" 10499)
("nvrtrie;" 8885 8402)
("nvsim;" 8764 8402)
("nwArr;" 8662)
("nwarhk;" 10531)
("nwarr;" 8598)
("nwarrow;" 8598)
("nwnear;" 10535)
("oS;" 9416)
("oacute" 243)
("oacute;" 243)
("oast;" 8859)
("ocir;" 8858)
("ocirc" 244)
("ocirc;" 244)
("ocy;" 1086)
("odash;" 8861)
("odblac;" 337)
("odiv;" 10808)
("odot;" 8857)
("odsold;" 10684)
("oelig;" 339)
("ofcir;" 10687)
("ofr;" 120108)
("ogon;" 731)
("ograve" 242)
("ograve;" 242)
("ogt;" 10689)
("ohbar;" 10677)
("ohm;" 937)
("oint;" 8750)
("olarr;" 8634)
("olcir;" 10686)
("olcross;" 10683)
("oline;" 8254)
("olt;" 10688)
("omacr;" 333)
("omega;" 969)
("omicron;" 959)
("omid;" 10678)
("ominus;" 8854)
("oopf;" 120160)
("opar;" 10679)
("operp;" 10681)
("oplus;" 8853)
("or;" 8744)
("orarr;" 8635)
("ord;" 10845)
("order;" 8500)
("orderof;" 8500)
("ordf" 170)
("ordf;" 170)
("ordm" 186)
("ordm;" 186)
("origof;" 8886)
("oror;" 10838)
("orslope;" 10839)
("orv;" 10843)
("oscr;" 8500)
("oslash" 248)
("oslash;" 248)
("osol;" 8856)
("otilde" 245)
("otilde;" 245)
("otimes;" 8855)
("otimesas;" 10806)
("ouml" 246)
("ouml;" 246)
("ovbar;" 9021)
("par;" 8741)
("para" 182)
("para;" 182)
("parallel;" 8741)
("parsim;" 10995)
("parsl;" 11005)
("part;" 8706)
("pcy;" 1087)
("percnt;" 37)
("period;" 46)
("permil;" 8240)
("perp;" 8869)
("pertenk;" 8241)
("pfr;" 120109)
("phi;" 966)
("phiv;" 981)
("phmmat;" 8499)
("phone;" 9742)
("pi;" 960)
("pitchfork;" 8916)
("piv;" 982)
("planck;" 8463)
("planckh;" 8462)
("plankv;" 8463)
("plus;" 43)
("plusacir;" 10787)
("plusb;" 8862)
("pluscir;" 10786)
("plusdo;" 8724)
("plusdu;" 10789)
("pluse;" 10866)
("plusmn" 177)
("plusmn;" 177)
("plussim;" 10790)
("plustwo;" 10791)
("pm;" 177)
("pointint;" 10773)
("popf;" 120161)
("pound" 163)
("pound;" 163)
("pr;" 8826)
("prE;" 10931)
("prap;" 10935)
("prcue;" 8828)
("pre;" 10927)
("prec;" 8826)
("precapprox;" 10935)
("preccurlyeq;" 8828)
("preceq;" 10927)
("precnapprox;" 10937)
("precneqq;" 10933)
("precnsim;" 8936)
("precsim;" 8830)
("prime;" 8242)
("primes;" 8473)
("prnE;" 10933)
("prnap;" 10937)
("prnsim;" 8936)
("prod;" 8719)
("profalar;" 9006)
("profline;" 8978)
("profsurf;" 8979)
("prop;" 8733)
("propto;" 8733)
("prsim;" 8830)
("prurel;" 8880)
("pscr;" 120005)
("psi;" 968)
("puncsp;" 8200)
("qfr;" 120110)
("qint;" 10764)
("qopf;" 120162)
("qprime;" 8279)
("qscr;" 120006)
("quaternions;" 8461)
("quatint;" 10774)
("quest;" 63)
("questeq;" 8799)
("quot" 34)
("quot;" 34)
("rAarr;" 8667)
("rArr;" 8658)
("rAtail;" 10524)
("rBarr;" 10511)
("rHar;" 10596)
("race;" 8765 817)
("racute;" 341)
("radic;" 8730)
("raemptyv;" 10675)
("rang;" 10217)
("rangd;" 10642)
("range;" 10661)
("rangle;" 10217)
("raquo" 187)
("raquo;" 187)
("rarr;" 8594)
("rarrap;" 10613)
("rarrb;" 8677)
("rarrbfs;" 10528)
("rarrc;" 10547)
("rarrfs;" 10526)
("rarrhk;" 8618)
("rarrlp;" 8620)
("rarrpl;" 10565)
("rarrsim;" 10612)
("rarrtl;" 8611)
("rarrw;" 8605)
("ratail;" 10522)
("ratio;" 8758)
("rationals;" 8474)
("rbarr;" 10509)
("rbbrk;" 10099)
("rbrace;" 125)
("rbrack;" 93)
("rbrke;" 10636)
("rbrksld;" 10638)
("rbrkslu;" 10640)
("rcaron;" 345)
("rcedil;" 343)
("rceil;" 8969)
("rcub;" 125)
("rcy;" 1088)
("rdca;" 10551)
("rdldhar;" 10601)
("rdquo;" 8221)
("rdquor;" 8221)
("rdsh;" 8627)
("real;" 8476)
("realine;" 8475)
("realpart;" 8476)
("reals;" 8477)
("rect;" 9645)
("reg" 174)
("reg;" 174)
("rfisht;" 10621)
("rfloor;" 8971)
("rfr;" 120111)
("rhard;" 8641)
("rharu;" 8640)
("rharul;" 10604)
("rho;" 961)
("rhov;" 1009)
("rightarrow;" 8594)
("rightarrowtail;" 8611)
("rightharpoondown;" 8641)
("rightharpoonup;" 8640)
("rightleftarrows;" 8644)
("rightleftharpoons;" 8652)
("rightrightarrows;" 8649)
("rightsquigarrow;" 8605)
("rightthreetimes;" 8908)
("ring;" 730)
("risingdotseq;" 8787)
("rlarr;" 8644)
("rlhar;" 8652)
("rlm;" 8207)
("rmoust;" 9137)
("rmoustache;" 9137)
("rnmid;" 10990)
("roang;" 10221)
("roarr;" 8702)
("robrk;" 10215)
("ropar;" 10630)
("ropf;" 120163)
("roplus;" 10798)
("rotimes;" 10805)
("rpar;" 41)
("rpargt;" 10644)
("rppolint;" 10770)
("rrarr;" 8649)
("rsaquo;" 8250)
("rscr;" 120007)
("rsh;" 8625)
("rsqb;" 93)
("rsquo;" 8217)
("rsquor;" 8217)
("rthree;" 8908)
("rtimes;" 8906)
("rtri;" 9657)
("rtrie;" 8885)
("rtrif;" 9656)
("rtriltri;" 10702)
("ruluhar;" 10600)
("rx;" 8478)
("sacute;" 347)
("sbquo;" 8218)
("sc;" 8827)
("scE;" 10932)
("scap;" 10936)
("scaron;" 353)
("sccue;" 8829)
("sce;" 10928)
("scedil;" 351)
("scirc;" 349)
("scnE;" 10934)
("scnap;" 10938)
("scnsim;" 8937)
("scpolint;" 10771)
("scsim;" 8831)
("scy;" 1089)
("sdot;" 8901)
("sdotb;" 8865)
("sdote;" 10854)
("seArr;" 8664)
("searhk;" 10533)
("searr;" 8600)
("searrow;" 8600)
("sect" 167)
("sect;" 167)
("semi;" 59)
("seswar;" 10537)
("setminus;" 8726)
("setmn;" 8726)
("sext;" 10038)
("sfr;" 120112)
("sfrown;" 8994)
("sharp;" 9839)
("shchcy;" 1097)
("shcy;" 1096)
("shortmid;" 8739)
("shortparallel;" 8741)
("shy" 173)
("shy;" 173)
("sigma;" 963)
("sigmaf;" 962)
("sigmav;" 962)
("sim;" 8764)
("simdot;" 10858)
("sime;" 8771)
("simeq;" 8771)
("simg;" 10910)
("simgE;" 10912)
("siml;" 10909)
("simlE;" 10911)
("simne;" 8774)
("simplus;" 10788)
("simrarr;" 10610)
("slarr;" 8592)
("smallsetminus;" 8726)
("smashp;" 10803)
("smeparsl;" 10724)
("smid;" 8739)
("smile;" 8995)
("smt;" 10922)
("smte;" 10924)
("smtes;" 10924 65024)
("softcy;" 1100)
("sol;" 47)
("solb;" 10692)
("solbar;" 9023)
("sopf;" 120164)
("spades;" 9824)
("spadesuit;" 9824)
("spar;" 8741)
("sqcap;" 8851)
("sqcaps;" 8851 65024)
("sqcup;" 8852)
("sqcups;" 8852 65024)
("sqsub;" 8847)
("sqsube;" 8849)
("sqsubset;" 8847)
("sqsubseteq;" 8849)
("sqsup;" 8848)
("sqsupe;" 8850)
("sqsupset;" 8848)
("sqsupseteq;" 8850)
("squ;" 9633)
("square;" 9633)
("squarf;" 9642)
("squf;" 9642)
("srarr;" 8594)
("sscr;" 120008)
("ssetmn;" 8726)
("ssmile;" 8995)
("sstarf;" 8902)
("star;" 9734)
("starf;" 9733)
("straightepsilon;" 1013)
("straightphi;" 981)
("strns;" 175)
("sub;" 8834)
("subE;" 10949)
("subdot;" 10941)
("sube;" 8838)
("subedot;" 10947)
("submult;" 10945)
("subnE;" 10955)
("subne;" 8842)
("subplus;" 10943)
("subrarr;" 10617)
("subset;" 8834)
("subseteq;" 8838)
("subseteqq;" 10949)
("subsetneq;" 8842)
("subsetneqq;" 10955)
("subsim;" 10951)
("subsub;" 10965)
("subsup;" 10963)
("succ;" 8827)
("succapprox;" 10936)
("succcurlyeq;" 8829)
("succeq;" 10928)
("succnapprox;" 10938)
("succneqq;" 10934)
("succnsim;" 8937)
("succsim;" 8831)
("sum;" 8721)
("sung;" 9834)
("sup1" 185)
("sup1;" 185)
("sup2" 178)
("sup2;" 178)
("sup3" 179)
("sup3;" 179)
("sup;" 8835)
("supE;" 10950)
("supdot;" 10942)
("supdsub;" 10968)
("supe;" 8839)
("supedot;" 10948)
("suphsol;" 10185)
("suphsub;" 10967)
("suplarr;" 10619)
("supmult;" 10946)
("supnE;" 10956)
("supne;" 8843)
("supplus;" 10944)
("supset;" 8835)
("supseteq;" 8839)
("supseteqq;" 10950)
("supsetneq;" 8843)
("supsetneqq;" 10956)
("supsim;" 10952)
("supsub;" 10964)
("supsup;" 10966)
("swArr;" 8665)
("swarhk;" 10534)
("swarr;" 8601)
("swarrow;" 8601)
("swnwar;" 10538)
("szlig" 223)
("szlig;" 223)
("target;" 8982)
("tau;" 964)
("tbrk;" 9140)
("tcaron;" 357)
("tcedil;" 355)
("tcy;" 1090)
("tdot;" 8411)
("telrec;" 8981)
("tfr;" 120113)
("there4;" 8756)
("therefore;" 8756)
("theta;" 952)
("thetasym;" 977)
("thetav;" 977)
("thickapprox;" 8776)
("thicksim;" 8764)
("thinsp;" 8201)
("thkap;" 8776)
("thksim;" 8764)
("thorn" 254)
("thorn;" 254)
("tilde;" 732)
("times" 215)
("times;" 215)
("timesb;" 8864)
("timesbar;" 10801)
("timesd;" 10800)
("tint;" 8749)
("toea;" 10536)
("top;" 8868)
("topbot;" 9014)
("topcir;" 10993)
("topf;" 120165)
("topfork;" 10970)
("tosa;" 10537)
("tprime;" 8244)
("trade;" 8482)
("triangle;" 9653)
("triangledown;" 9663)
("triangleleft;" 9667)
("trianglelefteq;" 8884)
("triangleq;" 8796)
("triangleright;" 9657)
("trianglerighteq;" 8885)
("tridot;" 9708)
("trie;" 8796)
("triminus;" 10810)
("triplus;" 10809)
("trisb;" 10701)
("tritime;" 10811)
("trpezium;" 9186)
("tscr;" 120009)
("tscy;" 1094)
("tshcy;" 1115)
("tstrok;" 359)
("twixt;" 8812)
("twoheadleftarrow;" 8606)
("twoheadrightarrow;" 8608)
("uArr;" 8657)
("uHar;" 10595)
("uacute" 250)
("uacute;" 250)
("uarr;" 8593)
("ubrcy;" 1118)
("ubreve;" 365)
("ucirc" 251)
("ucirc;" 251)
("ucy;" 1091)
("udarr;" 8645)
("udblac;" 369)
("udhar;" 10606)
("ufisht;" 10622)
("ufr;" 120114)
("ugrave" 249)
("ugrave;" 249)
("uharl;" 8639)
("uharr;" 8638)
("uhblk;" 9600)
("ulcorn;" 8988)
("ulcorner;" 8988)
("ulcrop;" 8975)
("ultri;" 9720)
("umacr;" 363)
("uml" 168)
("uml;" 168)
("uogon;" 371)
("uopf;" 120166)
("uparrow;" 8593)
("updownarrow;" 8597)
("upharpoonleft;" 8639)
("upharpoonright;" 8638)
("uplus;" 8846)
("upsi;" 965)
("upsih;" 978)
("upsilon;" 965)
("upuparrows;" 8648)
("urcorn;" 8989)
("urcorner;" 8989)
("urcrop;" 8974)
("uring;" 367)
("urtri;" 9721)
("uscr;" 120010)
("utdot;" 8944)
("utilde;" 361)
("utri;" 9653)
("utrif;" 9652)
("uuarr;" 8648)
("uuml" 252)
("uuml;" 252)
("uwangle;" 10663)
("vArr;" 8661)
("vBar;" 10984)
("vBarv;" 10985)
("vDash;" 8872)
("vangrt;" 10652)
("varepsilon;" 1013)
("varkappa;" 1008)
("varnothing;" 8709)
("varphi;" 981)
("varpi;" 982)
("varpropto;" 8733)
("varr;" 8597)
("varrho;" 1009)
("varsigma;" 962)
("varsubsetneq;" 8842 65024)
("varsubsetneqq;" 10955 65024)
("varsupsetneq;" 8843 65024)
("varsupsetneqq;" 10956 65024)
("vartheta;" 977)
("vartriangleleft;" 8882)
("vartriangleright;" 8883)
("vcy;" 1074)
("vdash;" 8866)
("vee;" 8744)
("veebar;" 8891)
("veeeq;" 8794)
("vellip;" 8942)
("verbar;" 124)
("vert;" 124)
("vfr;" 120115)
("vltri;" 8882)
("vnsub;" 8834 8402)
("vnsup;" 8835 8402)
("vopf;" 120167)
("vprop;" 8733)
("vrtri;" 8883)
("vscr;" 120011)
("vsubnE;" 10955 65024)
("vsubne;" 8842 65024)
("vsupnE;" 10956 65024)
("vsupne;" 8843 65024)
("vzigzag;" 10650)
("wcirc;" 373)
("wedbar;" 10847)
("wedge;" 8743)
("wedgeq;" 8793)
("weierp;" 8472)
("wfr;" 120116)
("wopf;" 120168)
("wp;" 8472)
("wr;" 8768)
("wreath;" 8768)
("wscr;" 120012)
("xcap;" 8898)
("xcirc;" 9711)
("xcup;" 8899)
("xdtri;" 9661)
("xfr;" 120117)
("xhArr;" 10234)
("xharr;" 10231)
("xi;" 958)
("xlArr;" 10232)
("xlarr;" 10229)
("xmap;" 10236)
("xnis;" 8955)
("xodot;" 10752)
("xopf;" 120169)
("xoplus;" 10753)
("xotime;" 10754)
("xrArr;" 10233)
("xrarr;" 10230)
("xscr;" 120013)
("xsqcup;" 10758)
("xuplus;" 10756)
("xutri;" 9651)
("xvee;" 8897)
("xwedge;" 8896)
("yacute" 253)
("yacute;" 253)
("yacy;" 1103)
("ycirc;" 375)
("ycy;" 1099)
("yen" 165)
("yen;" 165)
("yfr;" 120118)
("yicy;" 1111)
("yopf;" 120170)
("yscr;" 120014)
("yucy;" 1102)
("yuml" 255)
("yuml;" 255)
("zacute;" 378)
("zcaron;" 382)
("zcy;" 1079)
("zdot;" 380)
("zeetrf;" 8488)
("zeta;" 950)
("zfr;" 120119)
("zhcy;" 1078)
("zigrarr;" 8669)
("zopf;" 120171)
("zscr;" 120015)
("zwj;" 8205)
("zwnj;" 8204)))
(defparameter *entities-tree* (make-entities-trie *entities*))
| 50,640
|
Common Lisp
|
.lisp
| 2,279
| 17.206231
| 89
| 0.524001
|
rotatef/cl-html5-parser
| 55
| 14
| 11
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
b3f21a7c1642f00e59326c1a4f695a77485ef04988bb82028848e51c2c86f48a
| 3,078
|
[
-1
] |
3,079
|
inputstream.lisp
|
rotatef_cl-html5-parser/inputstream.lisp
|
;;;; HTML5 parser for Common Lisp
;;;;
;;;; Copyright (C) 2012 Thomas Bakketun <thomas.bakketun@copyleft.no>
;;;; Copyright (C) 2012 Asgeir Bj√∏rlykke <asgeir@copyleft.no>
;;;; Copyright (C) 2012 Mathias Hellevang
;;;; Copyright (C) 2012 Stian Sletner <stian@copyleft.no>
;;;;
;;;; This library is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Lesser General Public License as published
;;;; by the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This library 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 library. If not, see <http://www.gnu.org/licenses/>.
(in-package :html5-parser)
(deftype array-length ()
"Type of an array index."
'(integer 0 #.array-dimension-limit))
(deftype chunk ()
"Type of the input stream buffer."
'(vector character *))
(defparameter *default-encoding* :utf-8)
(defclass html-input-stream ()
((source :initarg :source)
(encoding :reader html5-stream-encoding)
(char-stream :initform nil)
(chunk)
(chunk-offset)
(pending-cr)
(errors :initform nil :accessor html5-stream-errors)))
(defun make-html-input-stream (source &key override-encoding fallback-encoding)
(when (stringp source)
;; Encoding is not relevant when input is a string,
;; but we set it utf-8 here to avoid auto detecting taking place.
(setf override-encoding :utf-8))
(let ((self (make-instance 'html-input-stream :source source)))
(with-slots (encoding stream) self
(setf encoding (detect-encoding self
(find-encoding override-encoding)
(find-encoding fallback-encoding)))
(open-char-stream self))
self))
;; 12.2.2.2 Character encodings
(defun find-encoding (encoding-name)
;; Normalize the string designator
(setf encoding-name (string-upcase (substitute #\- #\_ (string-trim +space-characters+ (string encoding-name)))))
;; All known encoding will already be interned in the keyword package so find-symbol is fine here
(setf encoding-name (find-symbol encoding-name :keyword))
(handler-case
;; Verfiy that flexi-streams knows the encoding and resolve aliases
(case (flex:external-format-name (flex:make-external-format encoding-name))
;; Some encoding should be replaced by some other.
;; Only those supported by flexi-streams are listed here.
;; iso-8859-11 should be replaced by windows-874, but flexi-streams doesn't that encoding.
(:iso-8859-1 :windows-1252)
(:iso-8859-9 :windows-1254)
(:us-ascii :windows-1252)
(otherwise encoding-name))
(flex:external-format-error ())))
;; 12.2.2.1 Determining the character encoding
(defun detect-encoding (stream override-encoding fallback-encoding)
(with-slots (encoding) stream
(block nil
;; 1. and 2. encoding overridden by user or transport layer
(when override-encoding
(return (cons override-encoding :certain)))
;; 3. wait for 1024 bytes, not implemented
;; 4. Detect BOM
(let ((bom-encoding (detect-bom stream)))
(when bom-encoding
(return (cons bom-encoding :certain))))
;; 5. Prescan not implemented
;; 6. Use fallback encoding
(when fallback-encoding
(return (cons encoding :tentative)))
;; 7. Autodect not implemented
;; 8. Implementation-defined default
(return (cons *default-encoding* :tentative)))))
(defmacro handle-encoding-errors (stream &body body)
`(handler-bind ((flex:external-format-encoding-error
(lambda (x)
(declare (ignore x))
(push :invalid-codepoint (html5-stream-errors ,stream))
(use-value #\uFFFD))))
,@body))
(defun open-char-stream (self)
(with-slots (source encoding char-stream chunk chunk-offset pending-cr) self
(setf chunk (make-array (* 10 1024) :element-type 'character :fill-pointer 0))
(setf chunk-offset 0)
(setf pending-cr nil)
(when char-stream
(close char-stream))
(setf char-stream
(if (stringp source)
(make-string-input-stream source)
(flex:make-flexi-stream
(etypecase source
(pathname
(open source :element-type '(unsigned-byte 8)))
(stream
source)
(vector
(flex:make-in-memory-input-stream source)))
:external-format (flex:make-external-format (car encoding) :eol-style :lf))))
;; 12.2.2.4 says we should always skip the first byte order mark
(handle-encoding-errors self
(let ((first-char (peek-char nil char-stream nil)))
(when (eql first-char #\ufeff)
(read-char char-stream))))))
(defun detect-bom (self)
(with-slots (source) self
(let (byte-0 byte-1 byte-2)
(etypecase source
(vector
(when (> (length source) 0) (setf byte-0 (aref source 0)))
(when (> (length source) 1) (setf byte-1 (aref source 1)))
(when (> (length source) 2) (setf byte-2 (aref source 2))))
(pathname
(with-open-file (in source :element-type '(unsigned-byte 8))
(setf byte-0 (read-byte in nil))
(setf byte-1 (read-byte in nil))
(setf byte-2 (read-byte in nil))))
(stream
(error "Can't detect encoding when source is a stream.")))
(cond ((and (eql byte-0 #xfe)
(eql byte-1 #xff))
:utf-16be)
((and (eql byte-0 #xff)
(eql byte-1 #xfe))
:utf-16le)
((and (eql byte-0 #xef)
(eql byte-1 #xbb)
(eql byte-2 #xbf))
:utf-8)))))
;; 12.2.2.3 Changing the encoding while parsing
(defun html5-stream-change-encoding (stream new-encoding)
(setf new-encoding (find-encoding new-encoding))
(with-slots (encoding char-stream) stream
;; 1.
(when (member (car encoding) '(:utf-16le :utf-16be))
(setf encoding (cons (car encoding) :certain))
(return-from html5-stream-change-encoding))
;; 2.
(when (member new-encoding '(:utf-16le :utf-16be))
(setf new-encoding :utf-8))
;; 3.
(when (eql (car encoding) new-encoding)
(setf encoding (cons (car encoding) :certain))
(return-from html5-stream-change-encoding))
;; 4. Not impleneted
;; 5. Restart paring from scratch
(setf encoding (cons new-encoding :certain))
(open-char-stream stream)
(throw 'please-reparse t)))
(defun html5-stream-char (stream)
(with-slots (chunk chunk-offset) stream
(when (>= chunk-offset (length chunk))
(unless (read-chunk stream)
(return-from html5-stream-char +eof+)))
(prog1 (char chunk chunk-offset)
(incf chunk-offset))))
(defun our-scan (chars opposite-p chunk &key start)
(loop for i from start below (length chunk)
for char = (char chunk i)
while (if opposite-p
(position char chars)
(not (position char chars)))
finally (return i)))
(defun html5-stream-chars-until (stream characters &optional opposite-p)
"Returns a string of characters from the stream up to but not
including any character in characters or end of file.
"
(with-slots (chunk chunk-offset) stream
(declare (array-length chunk-offset) (chunk chunk))
(with-output-to-string (data)
(loop for end = (our-scan characters opposite-p chunk :start chunk-offset) do
;; If nothing matched, and it wasn't because we ran out of chunk,
;; then stop
(when (and (not end)
(/= chunk-offset (length chunk)))
(return))
;; If not the whole chunk matched, return everything
;; up to the part that didn't match
(when (and end
(/= chunk-offset (length chunk)))
(write-string chunk data :start chunk-offset :end end)
(setf chunk-offset end)
(return))
;; If the whole remainder of the chunk matched,
;; use it all and read the next chunk
(write-string chunk data :start chunk-offset)
(unless (read-chunk stream)
(return))))))
(defun html5-stream-unget (stream char)
(with-slots (chunk chunk-offset) stream
(unless (eql char +eof+)
(cond ((zerop chunk-offset)
(cond ((< (fill-pointer chunk) (array-dimension chunk 0))
(incf (fill-pointer chunk))
(replace chunk chunk :start1 1))
(t
(let ((new-chunk (make-array (1+ (array-dimension chunk 0))
:element-type 'character
:fill-pointer (1+ (fill-pointer chunk)))))
(replace new-chunk chunk :start1 1)
(setf chunk new-chunk))))
(setf (char chunk 0) char))
(t
(decf chunk-offset)
(assert (char= char (char chunk chunk-offset))))))))
(defun read-chunk (stream)
(declare (optimize speed))
(with-slots (char-stream chunk chunk-offset pending-cr) stream
(declare (array-length chunk-offset)
(chunk chunk))
(setf chunk-offset 0)
(let ((start 0))
(when pending-cr
(setf (char chunk 0) #\Return)
(setf start 1)
(setf pending-cr nil))
(setf (fill-pointer chunk) (array-dimension chunk 0))
(handle-encoding-errors stream
(setf (fill-pointer chunk) (read-sequence chunk char-stream :start start)))
(unless (zerop (length chunk))
;; check if last char is CR and EOF was not reached
(when (and (= (length chunk) (array-dimension chunk 0))
(eql (char chunk (1- (length chunk))) #\Return))
(setf pending-cr t)
(decf (fill-pointer chunk)))
(report-character-errors stream chunk)
;; Python code replaces surrugate pairs with U+FFFD here. Why?
;; Normalize line endings (CR LF)
(loop for previous = nil then current
for current across chunk
for index of-type array-length from 0
with offset of-type array-length = 0
do (unless (and (eql previous #\Return)
(eql current #\Newline))
(unless (= index offset)
(setf (char chunk offset) current))
(when (eql current #\Return)
(setf (char chunk offset) #\Newline))
(incf offset))
finally (setf (fill-pointer chunk) offset))
t))))
(defun char-range (char1 char2)
(loop for i from (char-code char1) to (char-code char2)
collect (code-char i)))
(defparameter *invalid-unicode*
`(,@(char-range #\u0001 #\u0008)
#\u000B
,@(char-range #\u000E #\u001F)
,@(char-range #\u007F #\u009F)
;; The following are noncharacter as defined by Unicode.
;; Clozure Common Lisp doesn't like them.
#-(or abcl ccl mezzano) ,@`(
,@(char-range #\uD800 #\uDFFF)
,@(char-range #\uFDD0 #\uFDEF)
#\uFFFE
#\uFFFF
#\u0001FFFE
#\u0001FFFF
#\u0002FFFE
#\u0002FFFF
#\u0003FFFE
#\u0003FFFF
#\u0004FFFE
#\u0004FFFF
#\u0005FFFE
#\u0005FFFF
#\u0006FFFE
#\u0006FFFF
#\u0007FFFE
#\u0007FFFF
#\u0008FFFE
#\u0008FFFF
#\u0009FFFE
#\u0009FFFF
#\u000AFFFE
#\u000AFFFF
#\u000BFFFE
#\u000BFFFF
#\u000CFFFE
#\u000CFFFF
#\u000DFFFE
#\u000DFFFF
#\u000EFFFE
#\u000EFFFF
#\u000FFFFE
#\u000FFFFF
#\u0010FFFE
#\u0010FFFF)))
(defparameter *invalid-unicode-hash* (make-hash-table))
(dolist (char *invalid-unicode*)
(setf (gethash char *invalid-unicode-hash*) char))
(defun report-character-errors (stream data)
(loop for char across data
when (gethash char *invalid-unicode-hash*)
do (push :invalid-codepoint (html5-stream-errors stream))))
| 12,457
|
Common Lisp
|
.lisp
| 305
| 32.567213
| 115
| 0.613143
|
rotatef/cl-html5-parser
| 55
| 14
| 11
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
6f0789db275f6ad66433314bdc72a8e882ca7ea09c02b29a5dc85e62dec94b48
| 3,079
|
[
-1
] |
3,080
|
html5-parser-class.lisp
|
rotatef_cl-html5-parser/html5-parser-class.lisp
|
;;;; HTML5 parser for Common Lisp
;;;;
;;;; Copyright (C) 2012 Thomas Bakketun <thomas.bakketun@copyleft.no>
;;;; Copyright (C) 2012 Asgeir Bj√∏rlykke <asgeir@copyleft.no>
;;;; Copyright (C) 2012 Mathias Hellevang
;;;; Copyright (C) 2012 Stian Sletner <stian@copyleft.no>
;;;;
;;;; This library is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Lesser General Public License as published
;;;; by the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This library 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 library. If not, see <http://www.gnu.org/licenses/>.
(in-package :html5-parser)
(defvar *parser*)
(defclass html-parser ()
((html-namespace :initform (find-namespace "html"))
(strict :initarg :strict)
(inner-html-mode)
(container :initform "div")
(tokenizer)
(document :initform (make-document))
(errors :initform '())
(phase :accessor parser-phase)
first-start-tag
compat-mode
inner-html
last-phase
original-phase
before-rcdata-phase
(character-tokens :initform nil)
frameset-ok
open-elements
active-formatting-elements
head-pointer
form-pointer
insert-from-table
(in-body-process-space-characters-mode :initform :non-pre)))
| 1,610
|
Common Lisp
|
.lisp
| 44
| 34.045455
| 78
| 0.71913
|
rotatef/cl-html5-parser
| 55
| 14
| 11
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
c0edf53230a8afa62cb527f6f563c47634835998365484e4261e788dfb9c4129
| 3,080
|
[
-1
] |
3,081
|
xmls.lisp
|
rotatef_cl-html5-parser/xmls.lisp
|
;;;; HTML5 parser for Common Lisp
;;;;
;;;; Copyright (C) 2012 Thomas Bakketun <thomas.bakketun@copyleft.no>
;;;; Copyright (C) 2012 Asgeir Bj√∏rlykke <asgeir@copyleft.no>
;;;; Copyright (C) 2012 Mathias Hellevang
;;;; Copyright (C) 2012 Stian Sletner <stian@copyleft.no>
;;;;
;;;; This library is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Lesser General Public License as published
;;;; by the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This library 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 library. If not, see <http://www.gnu.org/licenses/>.
(in-package #:html5-parser)
(defmethod transform-html5-dom ((to-type (eql :xmls)) node
&key namespace comments)
"Convert a node into an XMLS-compatible tree of conses, starting
at. If the node is a document-fragement a list of XMLS trees is returned."
(labels ((node-to-xmls (node parent-ns xlink-defined)
(ecase (node-type node)
(:document
(let (root)
(element-map-children (lambda (n)
(when (string= (node-name n) "html")
(setf root n)))
node)
(assert root)
(node-to-xmls root parent-ns xlink-defined)))
(:document-fragment
(let (xmls-nodes)
(element-map-children (lambda (node)
(push (node-to-xmls node parent-ns xlink-defined)
xmls-nodes))
node)
(nreverse xmls-nodes)))
(:element
(let (attrs children)
(element-map-attributes (lambda (name node-namespace value)
(when (and namespace
(not xlink-defined)
(equal node-namespace (html5-constants:find-namespace "xlink")))
(push '#.(list "xmlns:xlink" (html5-constants:find-namespace "xlink")) attrs)
(setf xlink-defined t))
(push (list (if node-namespace
name
(xml-escape-name name))
value)
attrs))
node)
(element-map-children (lambda (c)
(push c children))
node)
(apply #'list
(if (and namespace
(not (equal parent-ns (node-namespace node))))
(cons (node-name node) (node-namespace node))
(xml-escape-name (node-name node)))
attrs
(mapcar (lambda (c)
(node-to-xmls c (node-namespace node) xlink-defined))
(nreverse children)))))
(:text
(node-value node))
(:comment
(when comments
(list :comment nil (node-value node)))))))
(node-to-xmls node nil nil)))
(defmethod transform-html5-dom ((to-type (eql :xmls-ns)) node &key)
(transform-html5-dom :xmls node :namespace t))
| 4,003
|
Common Lisp
|
.lisp
| 75
| 33.506667
| 121
| 0.472718
|
rotatef/cl-html5-parser
| 55
| 14
| 11
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
132a53a9914000d9e24bffaf86d6bbc9b7b864f9191b5d4a0435b7735c2c83db
| 3,081
|
[
-1
] |
3,082
|
html5-parser.lisp
|
rotatef_cl-html5-parser/html5-parser.lisp
|
;;;; HTML5 parser for Common Lisp
;;;;
;;;; Copyright (C) 2012 Thomas Bakketun <thomas.bakketun@copyleft.no>
;;;; Copyright (C) 2012 Asgeir Bj√∏rlykke <asgeir@copyleft.no>
;;;; Copyright (C) 2012 Mathias Hellevang
;;;; Copyright (C) 2012 Stian Sletner <stian@copyleft.no>
;;;;
;;;; This library is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Lesser General Public License as published
;;;; by the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This library 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 library. If not, see <http://www.gnu.org/licenses/>.
(in-package :html5-parser)
;; external interface
(defun parse-html5 (source &key encoding strictp container dom)
(parse-html5-from-source source
:encoding encoding
:strictp strictp
:container container
:dom dom))
(defun parse-html5-fragment (source &key encoding strictp (container "div") dom)
(parse-html5-from-source source
:encoding encoding
:strictp strictp
:container container
:dom dom))
(defgeneric transform-html5-dom (to-type node &key)
(:method ((to-type cons) node &key)
(apply #'transform-html5-dom (car to-type) node (cdr to-type)))
(:method (to-type node &key &allow-other-keys)
(error "No TRANSFORM-HTML5-DOM method defined for dom type ~S." to-type)))
;; internal
(defun parse-html5-from-source (source &key container encoding strictp dom)
(let ((*parser* (make-instance 'html-parser
:strict strictp)))
(parser-parse source
:fragment-p container
:encoding encoding)
(with-slots (open-elements errors) *parser*
(let ((document
(if container
(let ((fragment (make-fragment (document*))))
(node-reparent-children (first open-elements) fragment)
fragment)
(document*))))
(values (if dom
(transform-html5-dom dom document)
document)
(reverse errors))))))
(defvar *phase*)
(defun ascii-ichar= (char1 char2)
"ASCII case-insensitive char="
(or (char= char1 char2)
(and (or (char<= #\A char1 #\Z)
(char<= #\A char2 #\Z))
(char= (char-downcase char1)
(char-downcase char2)))))
(defun ascii-istring= (string1 string2)
"ASCII case-insensitive string="
(every #'ascii-ichar= string1 string2))
(defun cdata-switch-helper ()
(and (last-open-element)
(not (equal (node-namespace (last-open-element))
(slot-value *parser* 'html-namespace)))))
(defun parser-parse (source &key fragment-p encoding)
(with-slots (inner-html-mode container tokenizer)
*parser*
(setf inner-html-mode fragment-p)
(when (stringp fragment-p)
(setf container fragment-p))
(setf tokenizer (make-html-tokenizer source
:encoding encoding
:cdata-switch-helper #'cdata-switch-helper))
(parser-reset)
(loop
;; The input stream will throw please-reparse with result true
;; if the encoding is changed
while (catch 'please-reparse
(main-loop)
nil)
do (parser-reset))))
(defun parser-reset ()
(with-slots (open-elements active-formatting-elements
head-pointer form-pointer insert-from-table
first-start-tag errors compat-mode inner-html-mode
inner-html container tokenizer phase last-phase
before-rcdata-phase frameset-ok
html-namespace)
*parser*
(setf open-elements '())
(setf active-formatting-elements '())
(setf head-pointer nil)
(setf form-pointer nil)
(setf insert-from-table nil)
(setf first-start-tag nil)
(setf errors '())
(setf compat-mode :no-quirks)
(cond (inner-html-mode
(setf inner-html (string-downcase container))
(cond ((member inner-html +cdata-elements+ :test #'string=)
(setf (slot-value tokenizer 'state) :rcdata-state))
((member inner-html +rcdata-elements+ :test #'string=)
(setf (slot-value tokenizer 'state) :rawtext-state))
((string= inner-html "plaintext")
(setf (slot-value tokenizer 'state) :plaintext-state)))
(insert-root (implied-tag-token "html" :start-tag))
(setf phase :before-head)
(reset-insertion-mode))
(t
(setf inner-html nil)
(setf phase :initial)))
(setf last-phase nil)
(setf before-rcdata-phase nil)
(setf frameset-ok t)))
(defun is-html-integration-point (element)
(if (and (string= (node-name element) "annotation-xml")
(string= (node-namespace element) (find-namespace "mathml")))
(and (element-attribute element "encoding")
(member (ascii-upper-2-lower (element-attribute element "encoding"))
'("text/html" "application/xhtml+xml")
:test #'string=))
(member (node-name-tuple element)
+html-integration-point-elements+
:test #'equal)))
(defun is-math-ml-text-integration-point (element)
(member (node-name-tuple element)
+mathml-text-integration-point-elements+
:test #'equal))
(defun main-loop ()
(with-slots (tokenizer phase)
*parser*
(map-tokens tokenizer (lambda (token)
(process-token (normalize-token token))))
(loop with reprocess = t
with phases = '()
while reprocess do
(push phase phases)
(setf reprocess (process-eof nil :phase phase))
(when reprocess
(assert (not (member phase phases)))))))
(defun process-token (token)
(with-slots (tokenizer last-open-element html-namespace)
*parser*
(let ((new-token token)
(type))
(loop while new-token do
(let* ((current-node (last-open-element))
(current-node-namespace (if current-node (node-namespace current-node)))
(current-node-name (if current-node (node-name current-node))))
(setf type (getf new-token :type))
(cond ((eql type :parse-error)
(parser-parse-error (getf token :data) (getf token :datavars))
(setf new-token nil))
(t
(let (phase)
(if (or (null (slot-value *parser* 'open-elements))
(equal current-node-namespace html-namespace)
(and (is-math-ml-text-integration-point current-node)
(or (and (eql type :start-tag)
(not (member (getf token :name) '("mglyph" "malignmark") :test #'string=)))
(eql type :characters)
(eql type :space-characters)))
(and (equal current-node-namespace (find-namespace "mathml"))
(equal current-node-name "annotation-xml")
(eql type :start-tag)
(equal (getf token :name) "svg"))
(and (is-html-integration-point current-node)
(member type '(:start-tag :characters :space-characters))))
(setf phase (slot-value *parser* 'phase))
(setf phase :in-foreign-content))
;(format t "~&phase ~S token ~S~%" phase new-token)
(setf new-token
(ecase type
(:characters
(process-characters new-token :phase phase))
(:space-characters
(process-space-characters new-token :phase phase))
(:start-tag
(process-start-tag new-token :phase phase))
(:end-tag
(process-end-tag new-token :phase phase))
(:comment
(process-comment new-token :phase phase))
(:doctype
(process-doctype new-token :phase phase))))
;(format t " phase returned ~S new-token ~S~%" phase new-token)
))))
(when (and (eql type :start-tag)
(getf token :self-closing)
(not (getf token :self-closing-acknowledged)))
(parser-parse-error :non-void-element-with-trailing-solidus
`(:name ,(getf token :name))))))))
(defun parser-parse-error (error-code &optional datavars)
(with-slots (errors) *parser*
(push (list error-code datavars) errors)))
;; TODO rename to a longer and more descriptive name when we are done writing the code
(defun perror (error-code &rest datavars)
(parser-parse-error error-code datavars))
(defun normalize-token (token)
(when (getf token :start-tag)
;; Remove duplicate attributes
(setf (getf token :data) (remove-duplicates (getf token :data)
:key #'car
:test #'string=
:from-end t)))
token)
(defun adjust-attributes (token replacements)
(setf (getf token :data)
(loop for (name . value) in (getf token :data)
collect (cons (or (cdr (assoc name replacements :test #'string=))
name)
value))))
(defun adjust-math-ml-attributes (token)
(adjust-attributes token '(("definitionurl" ."definitionURL"))))
(defun adjust-svg-attributes (token)
(adjust-attributes token '(("attributename" . "attributeName")
("attributetype" . "attributeType")
("basefrequency" . "baseFrequency")
("baseprofile" . "baseProfile")
("calcmode" . "calcMode")
("clippathunits" . "clipPathUnits")
("contentscripttype" . "contentScriptType")
("contentstyletype" . "contentStyleType")
("diffuseconstant" . "diffuseConstant")
("edgemode" . "edgeMode")
("externalresourcesrequired" . "externalResourcesRequired")
("filterres" . "filterRes")
("filterunits" . "filterUnits")
("glyphref" . "glyphRef")
("gradienttransform" . "gradientTransform")
("gradientunits" . "gradientUnits")
("kernelmatrix" . "kernelMatrix")
("kernelunitlength" . "kernelUnitLength")
("keypoints" . "keyPoints")
("keysplines" . "keySplines")
("keytimes" . "keyTimes")
("lengthadjust" . "lengthAdjust")
("limitingconeangle" . "limitingConeAngle")
("markerheight" . "markerHeight")
("markerunits" . "markerUnits")
("markerwidth" . "markerWidth")
("maskcontentunits" . "maskContentUnits")
("maskunits" . "maskUnits")
("numoctaves" . "numOctaves")
("pathlength" . "pathLength")
("patterncontentunits" . "patternContentUnits")
("patterntransform" . "patternTransform")
("patternunits" . "patternUnits")
("pointsatx" . "pointsAtX")
("pointsaty" . "pointsAtY")
("pointsatz" . "pointsAtZ")
("preservealpha" . "preserveAlpha")
("preserveaspectratio" . "preserveAspectRatio")
("primitiveunits" . "primitiveUnits")
("refx" . "refX")
("refy" . "refY")
("repeatcount" . "repeatCount")
("repeatdur" . "repeatDur")
("requiredextensions" . "requiredExtensions")
("requiredfeatures" . "requiredFeatures")
("specularconstant" . "specularConstant")
("specularexponent" . "specularExponent")
("spreadmethod" . "spreadMethod")
("startoffset" . "startOffset")
("stddeviation" . "stdDeviation")
("stitchtiles" . "stitchTiles")
("surfacescale" . "surfaceScale")
("systemlanguage" . "systemLanguage")
("tablevalues" . "tableValues")
("targetx" . "targetX")
("targety" . "targetY")
("textlength" . "textLength")
("viewbox" . "viewBox")
("viewtarget" . "viewTarget")
("xchannelselector" . "xChannelSelector")
("ychannelselector" . "yChannelSelector")
("zoomandpan" . "zoomAndPan"))))
(defun adjust-foreign-attributes (token)
(adjust-attributes token `(("xlink:actuate" . ("xlink" "actuate" ,(find-namespace "xlink")))
("xlink:arcrole" . ("xlink" "arcrole" ,(find-namespace "xlink")))
("xlink:href" . ("xlink" "href" ,(find-namespace "xlink")))
("xlink:role" . ("xlink" "role" ,(find-namespace "xlink")))
("xlink:show" . ("xlink" "show" ,(find-namespace "xlink")))
("xlink:title" . ("xlink" "title" ,(find-namespace "xlink")))
("xlink:type" . ("xlink" "type" ,(find-namespace "xlink")))
("xml:base" . ("xml" "base" ,(find-namespace "xml")))
("xml:lang" . ("xml" "lang" ,(find-namespace "xml")))
("xml:space" . ("xml" "space" ,(find-namespace "xml")))
("xmlns" . (nil "xmlns" ,(find-namespace "xmlns")))
("xmlns:xlink" . ("xmlns" "xlink" ,(find-namespace "xmlns"))))))
(defun reset-insertion-mode ()
(with-slots (inner-html html-namespace phase open-elements) *parser*
(let ((last nil)
(new-phase nil)
(new-modes '(("select" . :in-select)
("td" . :in-cell)
("th" . :in-cell)
("tr" . :in-row)
("tbody" . :in-table-body)
("thead" . :in-table-body)
("tfoot" . :in-table-body)
("caption" . :in-caption)
("colgroup" . :in-column-group)
("table" . :in-table)
("head" . :in-body)
("body" . :in-body)
("frameset" . :in-frameset)
("html" . :before-head))))
(loop for node in (reverse open-elements)
for node-name = (node-name node)
do
(when (eql node (first open-elements))
(assert inner-html)
(setf last t)
(setf node-name inner-html))
;; Check for conditions that should only happen in the innerHTML
;; case
(when (member node-name '("select" "colgroup" "head" "html") :test #'string=)
(assert inner-html))
(unless (and (not last)
(string/= (node-namespace node) html-namespace))
(let ((match (cdr (assoc node-name new-modes :test #'string=))))
(when match
(setf new-phase match)
(return))
(when last
(setf new-phase :in-body)
(return)))))
(setf phase new-phase))))
(defun parse-rc-data-raw-text (token content-type)
(assert (member content-type '(:rawtext :rcdata)))
(with-slots (tokenizer original-phase phase) *parser*
(insert-element token)
(setf (tokenizer-state tokenizer) (ecase content-type
(:rawtext :rawtext-state)
(:rcdata :rcdata-state)))
(setf original-phase phase)
(setf phase :text)
nil))
;; Phases --------------------------------------------------------------------
(defun implied-tag-token (name &optional (type :end-tag))
(list :type type :name name :data '() :self-closing nil))
(defun implied-tag-token/full (name type
&key (attributes '()) (self-closing nil))
(list :type type :name name :data attributes :self-closing self-closing))
(eval-when (:compile-toplevel :execute)
(defun phase-process-method-name (function-name)
(intern (concatenate 'string
"%"
(symbol-name function-name))
(symbol-package function-name))))
(defvar *phase-indent* 0)
(defun call-phase-method (name phase token)
;(format *trace-output* "~&~vTcall: ~S ~S ~S" *phase-indent* name phase token)
;(break)
(let ((result (let ((*phase-indent* (+ 4 *phase-indent*)))
(funcall name phase token))))
;(format *trace-output* "~&~vTreturn: ~S ~S" *phase-indent* name result)
result))
(defmacro define-phase-process-functions (&body defs)
`(progn
,@(loop for function-name in defs
for method-name = (phase-process-method-name function-name)
collect `(defgeneric ,method-name (phase token))
collect `(defun ,function-name (token &key (phase *phase*))
(call-phase-method #',method-name phase token)))))
(define-phase-process-functions
add-formatting-element
end-tag-applet-marquee-object
end-tag-block
end-tag-body
end-tag-br
end-tag-caption
end-tag-col
end-tag-colgroup
end-tag-form
end-tag-formatting
end-tag-frameset
end-tag-head
end-tag-heading
end-tag-html
end-tag-html-body-br
end-tag-ignore
end-tag-imply
end-tag-imply-head
end-tag-list-item
end-tag-optgroup
end-tag-option
end-tag-other
end-tag-p
end-tag-script
end-tag-select
end-tag-table
end-tag-table-cell
end-tag-table-row-group
end-tag-tr
insert-text
process-characters
process-comment
process-doctype
process-end-tag
process-eof
process-space-characters
process-start-tag
start-tag-a
start-tag-applet-marquee-object
start-tag-base-link-command
start-tag-body
start-tag-button
start-tag-caption
start-tag-close-p
start-tag-col
start-tag-colgroup
start-tag-form
start-tag-formatting
start-tag-frame
start-tag-frameset
start-tag-from-head
start-tag-head
start-tag-heading
start-tag-hr
start-tag-html
start-tag-i-frame
start-tag-image
start-tag-imply-tbody
start-tag-input
start-tag-is-index
start-tag-list-item
start-tag-math
start-tag-meta
start-tag-misplaced
start-tag-no-script-no-frames-style
start-tag-nobr
start-tag-noframes
start-tag-opt
start-tag-optgroup
start-tag-option
start-tag-other
start-tag-param-source
start-tag-plaintext
start-tag-pre-listing
start-tag-process-in-head
start-tag-rawtext
start-tag-row-group
start-tag-rp-rt
start-tag-script
start-tag-select
start-tag-style-script
start-tag-svg
start-tag-table
start-tag-table-cell
start-tag-table-element
start-tag-table-other
start-tag-textarea
start-tag-title
start-tag-tr
start-tag-void-formatting
start-tag-xmp)
(defmacro def (phase name (&rest slots) &body body)
`(defmethod ,(phase-process-method-name name) ((*phase* (eql ,phase)) token)
(with-slots (,@slots) *parser*
,@body)))
(defmacro tagname-dispatch (phase name &body cases)
`(def ,phase ,name ()
(let ((tagname (getf token :name)))
(declare (ignorable tagname))
,(let* ((default '(error "Unhandled tag ~S" tagname))
(string-cases
(loop for (tagnames function) in cases
append (cond ((stringp tagnames)
`((,tagnames (,function token))))
((consp tagnames)
(loop for tag in tagnames
collect `(,tag (,function token))))
((eql 'default tagnames)
(setf default `(,function token))
nil)
(t (error "Invalid tag name clause ~S" tagnames))))))
(if (not string-cases)
default
`(string-case:string-case
(tagname :default ,default)
,@string-cases))))))
;; Default methods
(defmethod %process-comment (*phase* token)
;; For most phases the following is correct. Where it's not it will be
;; overridden.
(insert-comment token (last-open-element))
nil)
(defmethod %process-doctype (*phase* token)
(parser-parse-error :unexpected-doctype)
nil)
(defmethod %process-characters (*phase* token)
(parser-insert-text (getf token :data))
nil)
(defmethod %process-space-characters (*phase* token)
(parser-insert-text (getf token :data))
nil)
(defmethod %start-tag-html (*phase* token)
(with-slots (first-start-tag open-elements)
*parser*
(when (and (not first-start-tag)
(string= (getf token :name) "html"))
(parser-parse-error :non-html-root))
;; XXX Need a check here to see if the first start tag token emitted is
;; this token... If it's not, invoke self.parser.parseError().
(let ((root-element (first open-elements)))
(loop for (name . value) in (getf token :data)
do (unless (element-attribute root-element name)
(setf (element-attribute root-element name) value))))
(setf first-start-tag nil)
nil))
;; InitialPhase
(def :initial process-space-characters ()
nil)
(def :initial process-comment ()
(insert-comment token (document*))
nil)
(def :initial process-doctype (compat-mode phase)
(destructuring-bind (&key name public-id system-id correct &allow-other-keys)
token
(when (or (string/= name "html")
public-id
(and system-id (string/= system-id "about:legacy-compat")))
(parser-parse-error :unknown-doctype))
(unless public-id
(setf public-id ""))
(insert-doctype token)
(setf public-id (ascii-upper-2-lower public-id))
(cond ((or (not correct)
(string/= name "html")
(cl-ppcre:scan +quirks-mode-doctypes-regexp+ public-id)
(member public-id '("-//w3o//dtd w3 html strict 3.0//en//"
"-/w3c/dtd html 4.0 transitional/en"
"html")
:test #'string=)
(and (not system-id)
(cl-ppcre:scan '(:sequence :start-anchor (:alternation
"-//w3c//dtd html 4.01 frameset//"
"-//w3c//dtd html 4.01 transitional//"))
public-id))
(and system-id
(equal (ascii-upper-2-lower system-id)
"http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd")))
(setf compat-mode :quirks))
((or (cl-ppcre:scan '(:sequence :start-anchor (:alternation
"-//w3c//dtd xhtml 1.0 frameset//"
"-//w3c//dtd xhtml 1.0 transitional//"))
public-id)
(and system-id
(cl-ppcre:scan '(:sequence :start-anchor (:alternation
"-//w3c//dtd html 4.01 frameset//"
"-//w3c//dtd html 4.01 transitional//"))
public-id)))
(setf compat-mode :limited-quirks)))
(setf phase :before-html)
nil))
(flet ((anything-else ()
(with-slots (compat-mode phase)
*parser*
(setf compat-mode :quirks)
(setf phase :before-html))))
(def :initial process-characters ()
(parser-parse-error :expected-doctype-but-got-chars)
(anything-else)
token)
(def :initial process-start-tag ()
(parser-parse-error :expected-doctype-but-got-start-tag
(list :name (getf token :name)))
(anything-else)
token)
(def :initial process-end-tag ()
(parser-parse-error :expected-doctype-but-got-end-tag
(list :name (getf token :name)))
(anything-else)
token)
(def :initial process-eof ()
(parser-parse-error :expected-doctype-but-got-eof)
(anything-else)
t))
;; BeforeHtmlPhase
(flet ((insert-html-element ()
(insert-root (implied-tag-token "html" :start-tag))
(setf (parser-phase *parser*) :before-head)))
(def :before-html process-eof ()
(insert-html-element)
t)
(def :before-html process-comment ()
(insert-comment token (document*))
nil)
(def :before-html process-space-characters ()
nil)
(def :before-html process-characters ()
(insert-html-element)
token)
(def :before-html process-start-tag (first-start-tag)
(when (string= (getf token :name) "html")
(setf first-start-tag t))
(insert-html-element)
token)
(def :before-html process-end-tag ()
(cond ((not (member (getf token :name) '("head" "body" "html" "br") :test #'string=))
(parser-parse-error :unexpected-end-tag-before-html `(:name ,(getf token :name)))
nil)
(t
(insert-html-element)
token))))
;; BeforeHeadPhase
(tagname-dispatch :before-head process-start-tag
("html" start-tag-html)
("head" start-tag-head token)
(default start-tag-other))
(tagname-dispatch :before-head process-end-tag
(("head" "body" "html" "br") end-tag-imply-head)
(default end-tag-other))
(def :before-head process-eof ()
(start-tag-head (implied-tag-token "head" :start-tag))
t)
(def :before-head process-space-characters ()
nil)
(def :before-head process-characters ()
(start-tag-head (implied-tag-token "head" :start-tag))
token)
(def :before-head start-tag-html ()
(process-start-tag token :phase :in-body))
(def :before-head start-tag-head (head-pointer)
(insert-element token)
(setf head-pointer (last-open-element))
(setf (parser-phase *parser*) :in-head)
nil)
(def :before-head start-tag-other ()
(start-tag-head (implied-tag-token "head" :start-tag))
token)
(def :before-head end-tag-imply-head ()
(start-tag-head (implied-tag-token "head" :start-tag))
token)
(def :before-head end-tag-other ()
(parser-parse-error :end-tag-after-implied-root `(:name ,(getf token :name)))
nil)
;; InHeadPhase
(tagname-dispatch :in-head process-start-tag
("html" start-tag-html)
("title" start-tag-title)
(("noscript" "noframes" "style") start-tag-no-script-no-frames-style)
("script" start-tag-script)
(("base" "basefont" "bgsound" "command" "link") start-tag-base-link-command)
("meta" start-tag-meta)
("head" start-tag-head)
(default start-tag-other))
(tagname-dispatch :in-head process-end-tag
("head" end-tag-head)
(("br" "html" "body") end-tag-html-body-br)
(default end-tag-other))
(flet ((anything-else ()
(end-tag-head (implied-tag-token "head"))))
;; the real thing
(def :in-head process-eof ()
(anything-else)
t)
(def :in-head process-characters ()
(anything-else)
token)
(def :in-head start-tag-html ()
(process-start-tag token :phase :in-body))
(def :in-head start-tag-head ()
(parser-parse-error :two-heads-are-not-better-than-one)
nil)
(def :in-head start-tag-base-link-command (open-elements)
(insert-element token)
(pop-end open-elements)
(setf (getf token :self-closing-acknowledged) t)
nil)
(defun parse-content-attr (string)
"The algorithm for extracting an encoding from a meta element"
(let ((position 0)) ; Step 1
(labels ((char-at (index)
(and (< position (length string))
(char string index)))
(skip-space ()
(loop while (member (char-at position) +space-characters+)
do (incf position))))
;; Step 2
(loop
(setf position (search "charset" string :start2 position))
(unless position
(return-from parse-content-attr))
;; Set position to after charset
(incf position 7)
;; Step 3
(skip-space)
;; Step 4
(when (eql (char-at position) #\=)
(return))
(decf position))
;; Step 5
(incf position)
(skip-space)
;; Step 6
(let ((next-char (char-at position)))
(cond ((or (eql #\' next-char)
(eql #\" next-char))
(incf position)
(let ((end (position next-char string :start position)))
(when end
(subseq string position end))))
(next-char
(let ((start position))
(loop until (or (= position (length string))
(member (char-at position) +space-characters+))
do (incf position))
(subseq string start position))))))))
(def :in-head start-tag-meta (tokenizer open-elements)
(insert-element token)
(pop-end open-elements)
(setf (getf token :self-closing-acknowledged) t)
(let ((attributes (getf token :data)))
(when (eql (cdr (html5-stream-encoding (tokenizer-stream tokenizer))) :tentative)
(cond ((assoc "charset" attributes :test #'string=)
(html5-stream-change-encoding (tokenizer-stream tokenizer)
(cdr (assoc "charset" attributes :test #'string=))))
((and (assoc "http-equiv" attributes :test #'string=)
(ascii-istring= (cdr (assoc "http-equiv" attributes :test #'string=))
"Content-Type")
(assoc "content" attributes :test #'string=))
(let* ((content (cdr (assoc "content" attributes :test #'string=)))
(new-encoding (parse-content-attr content)))
(if new-encoding
(html5-stream-change-encoding (tokenizer-stream tokenizer)
new-encoding)
(parser-parse-error :invalid-encoding-declaration
`(:content ,content))))))))
nil)
(def :in-head start-tag-title ()
(parse-rc-data-raw-text token :rcdata)
nil)
(def :in-head start-tag-no-script-no-frames-style ()
;; Need to decide whether to implement the scripting-disabled case
(parse-rc-data-raw-text token :rawtext))
(def :in-head start-tag-script (tokenizer original-phase phase)
(insert-element token)
(setf (tokenizer-state tokenizer) :script-data-state)
(setf original-phase phase)
(setf phase :text)
nil)
(def :in-head start-tag-other ()
(anything-else)
token)
(def :in-head end-tag-head (phase open-elements)
(let ((node (pop-end open-elements)))
(assert (string= (node-name node) "head") () "Expected head got ~S" (node-name node))
(setf phase :after-head)
nil))
(def :in-head end-tag-html-body-br ()
(anything-else)
token)
(def :in-head end-tag-other ()
(parser-parse-error :unexpected-end-tag `(:name ,(getf token :name)))
nil))
;; XXX If we implement a parser for which scripting is disabled we need to
;; implement this phase.
;;
;; InHeadNoScriptPhase
;; AfterHeadPhase
(tagname-dispatch :after-head process-start-tag
("html" start-tag-html)
("body" start-tag-body)
("frameset" start-tag-frameset)
(("base" "basefont" "bgsound" "link" "meta"
"noframes" "script" "style" "title")
start-tag-from-head)
("head" start-tag-head)
(default start-tag-other))
(tagname-dispatch :after-head process-end-tag
(("body" "html" "br") end-tag-html-body-br)
(default end-tag-other))
(flet ((anything-else ()
(with-slots (phase frameset-ok) *parser*
(insert-element (implied-tag-token "body" :start-tag))
(setf phase :in-body)
(setf frameset-ok t))))
(def :after-head process-eof ()
(anything-else)
t)
(def :after-head process-characters ()
(anything-else)
token)
(def :after-head start-tag-html ()
(process-start-tag token :phase :in-body))
(def :after-head start-tag-body (phase frameset-ok)
(setf frameset-ok nil)
(insert-element token)
(setf phase :in-body)
nil)
(def :after-head start-tag-frameset (phase)
(insert-element token)
(setf phase :in-frameset)
nil)
(def :after-head start-tag-from-head (head-pointer open-elements)
(parser-parse-error :unexpected-start-tag-out-of-my-head
`(:name ,(getf token :name)))
(push-end head-pointer open-elements)
(process-start-tag token :phase :in-head)
(loop for node in (reverse open-elements)
do (when (string= "head" (node-name node))
(setf open-elements
(remove node open-elements :test #'equal))
(return)))
nil)
(def :after-head start-tag-head ()
(parser-parse-error :unexpected-start-tag
`(:name ,(getf token :name)))
nil)
(def :after-head start-tag-other ()
(anything-else)
token)
(def :after-head end-tag-html-body-br ()
(anything-else)
token)
(def :after-head end-tag-other ()
(parser-parse-error :unexpected-end-tag
`(:name ,(getf token :name)))
nil))
;; InBodyPhase
(tagname-dispatch :in-body process-start-tag
("html" start-tag-html)
(("base" "basefont" "bgsound" "command" "link"
"meta" "noframes" "script" "style" "title")
start-tag-process-in-head)
("body" start-tag-body)
("frameset" start-tag-frameset)
(("address" "article" "aside" "blockquote" "center" "details"
"dir" "div" "dl" "fieldset" "figcaption" "figure"
"footer" "header" "hgroup" "menu" "nav" "ol" "p"
"section" "summary" "ul")
start-tag-close-p)
(#.+heading-elements+ start-tag-heading)
(("pre" "listing") start-tag-pre-listing)
("form" start-tag-form)
(("li" "dd" "dt") start-tag-list-item)
("plaintext" start-tag-plaintext)
("a" start-tag-a)
(("b" "big" "code" "em" "font" "i" "s" "small" "strike"
"strong" "tt" "u")
start-tag-formatting)
("nobr" start-tag-nobr)
("button" start-tag-button)
(("applet" "marquee" "object") start-tag-applet-marquee-object)
("xmp" start-tag-xmp)
("table" start-tag-table)
(("area" "br" "embed" "img" "keygen" "wbr")
start-tag-void-formatting)
(("param" "source" "track") start-tag-param-source)
("input" start-tag-input)
("hr" start-tag-hr)
("image" start-tag-image)
("isindex" start-tag-is-index)
("textarea" start-tag-textarea)
("iframe" start-tag-i-frame)
(("noembed" "noscript") start-tag-rawtext)
("select" start-tag-select)
(("rp" "rt") start-tag-rp-rt)
(("option" "optgroup") start-tag-opt)
(("math") start-tag-math)
(("svg") start-tag-svg)
(("caption" "col" "colgroup" "frame" "head"
"tbody" "td" "tfoot" "th" "thead"
"tr")
start-tag-misplaced)
(default start-tag-other))
(tagname-dispatch :in-body process-end-tag
("body" end-tag-body)
("html" end-tag-html)
(("address" "article" "aside" "blockquote" "button" "center"
"details" "dir" "div" "dl" "fieldset" "figcaption" "figure"
"footer" "header" "hgroup" "listing" "menu" "nav" "ol" "pre"
"section" "summary" "ul")
end-tag-block)
("form" end-tag-form)
("p" end-tag-p)
(("dd" "dt" "li") end-tag-list-item)
(#.+heading-elements+ end-tag-heading)
(("a" "b" "big" "code" "em" "font" "i" "nobr" "s" "small"
"strike" "strong" "tt" "u")
end-tag-formatting)
(("applet" "marquee" "object") end-tag-applet-marquee-object)
("br" end-tag-br)
(default end-tag-other))
(flet ((is-matching-formatting-element (node1 node2)
(and (equal (node-name node1) (node-name node2))
(equal (node-namespace node1) (node-namespace node2))
(node-attributes= node1 node2))))
(def :in-body add-formatting-element (reverse active-formatting-elements)
(insert-element token)
(let ((element (last-open-element))
matching-elements)
(loop for node in (reverse active-formatting-elements)
do (if (eq node :marker)
(return)
(when (is-matching-formatting-element node element)
(push-end node matching-elements))))
(assert (<= (length matching-elements) 3))
(when (= (length matching-elements) 3)
(setf active-formatting-elements
(remove (car (last matching-elements))
active-formatting-elements)))
(assert element)
(push-end element active-formatting-elements))
nil))
(def :in-body process-eof (open-elements)
(let ((allowed-elements '("dd" "dt" "li" "p" "tbody" "td"
"tfoot" "th" "thead" "tr" "body" "html")))
(loop for node in (reverse open-elements)
do (when (not (member (node-name node)
allowed-elements
:test #'string=))
(parser-parse-error :expected-closing-tag-but-got-eof)
(return))))
nil)
(def :in-body process-characters (frameset-ok)
(let ((data (getf token :data)))
(if (equal data (string #\u0000))
nil
(progn
(reconstruct-active-formatting-elements)
(parser-insert-text data)
;;This must be bad for performance
(when (and frameset-ok
(notevery (lambda (char)
(find char +space-characters+))
data))
(setf frameset-ok nil))
nil))))
(def :in-body process-space-characters (in-body-process-space-characters-mode)
(ecase in-body-process-space-characters-mode
(:non-pre
(reconstruct-active-formatting-elements)
(parser-insert-text (getf token :data)))
(:drop-newline
(let ((data (getf token :data)))
(setf in-body-process-space-characters-mode :non-pre)
(when (and (plusp (length data))
(char= #\Newline (char data 0))
(member (node-name (last-open-element))
'("pre" "listing" "textarea")
:test #'string=)
(not (node-has-content (last-open-element))))
(setf data (subseq data 1)))
(when (plusp (length data))
(reconstruct-active-formatting-elements)
(parser-insert-text data)))))
nil)
(def :in-body start-tag-process-in-head ()
(process-start-tag token :phase :in-head))
(def :in-body start-tag-body (frameset-ok open-elements)
(parser-parse-error :unexpected-start-tag
`(:name ,(getf token :name)))
(if (or (= 1 (length open-elements))
(string/= (node-name (second open-elements)) "body"))
(assert (slot-value *parser* 'inner-html))
(progn
(setf frameset-ok nil)
(loop for (name . value) in (getf token :data)
do (unless (element-attribute (second open-elements) name)
(setf (element-attribute (second open-elements) name) value)))))
nil)
(def :in-body start-tag-frameset (frameset-ok phase open-elements)
(parser-parse-error :unexpected-start-tag
`(:name ,(getf token :name)))
(cond ((or (= 1 (length open-elements))
(string/= (node-name (second open-elements)) "body"))
(assert (slot-value *parser* 'inner-html)))
((not frameset-ok)
nil)
(t
(when (node-parent (second open-elements))
(node-remove-child (node-parent (second open-elements))
(second open-elements)))
(loop until (string= (node-name (last-open-element))
"html")
do (pop-end open-elements))
(insert-element token)
(setf phase :in-frameset)))
nil)
(def :in-body start-tag-close-p ()
(when (element-in-scope "p" "button")
(end-tag-p (implied-tag-token "p")))
(insert-element token)
nil)
(def :in-body start-tag-pre-listing (in-body-process-space-characters-mode frameset-ok)
(when (element-in-scope "p" "button")
(end-tag-p (implied-tag-token "p")))
(insert-element token)
(setf frameset-ok nil)
(setf in-body-process-space-characters-mode :drop-newline)
nil)
(def :in-body start-tag-form (form-pointer)
(if form-pointer
(parser-parse-error :unexpected-start-tag
`(:name ,(getf token :name)))
(progn
(when (element-in-scope "p" "button")
(end-tag-p (implied-tag-token "p")))
(insert-element token)
(setf form-pointer (last-open-element))))
nil)
(def :in-body start-tag-list-item (phase frameset-ok open-elements)
(setf frameset-ok nil)
(let ((stop-names (cond ((string= (getf token :name) "li")
'("li"))
((string= (getf token :name) "dt")
'("dt" "dd"))
((string= (getf token :name) "dd")
'("dt" "dd")))))
(loop for node in (reverse open-elements)
do (cond ((member (node-name node) stop-names :test #'string=)
(process-end-tag (implied-tag-token (node-name node)) :phase phase)
(return))
((and (member (node-name-tuple node) +special-elements+
:test #'equal)
(not (member (node-name node)
'("address" "div" "p")
:test #'string=)))
(return)))))
(when (element-in-scope "p" "button")
(process-end-tag (implied-tag-token "p") :phase phase))
(insert-element token)
nil)
(def :in-body start-tag-plaintext (tokenizer)
(when (element-in-scope "p" "button")
(end-tag-p (implied-tag-token "p")))
(insert-element token)
(setf (tokenizer-state tokenizer) :plaintext-state)
nil)
(def :in-body start-tag-heading (open-elements)
(when (element-in-scope "p" "button")
(end-tag-p (implied-tag-token "p")))
(when (member (node-name (last-open-element)) +heading-elements+
:test #'string=)
(perror :unexpected-start-tag :name (getf token :name))
(pop-end open-elements))
(insert-element token)
nil)
(def :in-body start-tag-a (open-elements active-formatting-elements)
(let ((afe-a-element (element-in-active-formatting-elements "a")))
(when afe-a-element
(perror :unexpected-start-tag-implies-end-tag
:start-name "a" :end-name "a")
(end-tag-formatting (implied-tag-token "a"))
(when (member afe-a-element open-elements)
(setf open-elements
(remove afe-a-element open-elements)))
(when (member afe-a-element active-formatting-elements)
(setf active-formatting-elements
(remove afe-a-element active-formatting-elements))))
(reconstruct-active-formatting-elements)
(add-formatting-element token))
nil)
(def :in-body start-tag-formatting ()
(reconstruct-active-formatting-elements)
(add-formatting-element token)
nil)
(def :in-body start-tag-nobr ()
(reconstruct-active-formatting-elements)
(when (element-in-scope "nobr")
(perror :unexpected-start-tag-implies-end-tag
:start-name "nobr" :end-name "nobr")
(process-end-tag (implied-tag-token "nobr"))
;; XXX Need tests that trigger the following
(reconstruct-active-formatting-elements))
(add-formatting-element token)
nil)
(def :in-body start-tag-button (frameset-ok)
(cond ((element-in-scope "button")
(perror :unexpected-start-tag-implies-end-tag
:start-name "button" :end-name "button")
(process-end-tag (implied-tag-token "button"))
token)
(t
(reconstruct-active-formatting-elements)
(insert-element token)
(setf frameset-ok nil)
nil)))
(def :in-body start-tag-applet-marquee-object (frameset-ok active-formatting-elements)
(reconstruct-active-formatting-elements)
(insert-element token)
(push-end :marker active-formatting-elements)
(setf frameset-ok nil)
nil)
(def :in-body start-tag-xmp (frameset-ok)
(when (element-in-scope "p" "button")
(end-tag-p (implied-tag-token "p")))
(reconstruct-active-formatting-elements)
(setf frameset-ok nil)
(parse-rc-data-raw-text token :rawtext)
nil)
(def :in-body start-tag-table (frameset-ok compat-mode phase)
(when (not (eq compat-mode :quirks))
(when (element-in-scope "p" "button")
(end-tag-p (implied-tag-token "p"))))
(insert-element token)
(setf frameset-ok nil)
(setf phase :in-table)
nil)
(def :in-body start-tag-void-formatting (frameset-ok open-elements)
(reconstruct-active-formatting-elements)
(insert-element token)
(pop-end open-elements)
(setf (getf token :self-closing-acknowledged) t)
(setf frameset-ok nil)
nil)
(def :in-body start-tag-input (frameset-ok)
(let ((old-frameset-ok frameset-ok))
(start-tag-void-formatting token)
(let ((type (assoc "type" (getf token :data) :test #'string=)))
(when (and type
(string= (ascii-upper-2-lower (cdr type)) "hidden"))
;;input type=hidden doesn't change framesetOK
(setf frameset-ok old-frameset-ok))))
nil)
(def :in-body start-tag-param-source (open-elements)
(insert-element token)
(pop-end open-elements)
(setf (getf token :self-closing-acknowledged) t)
nil)
(def :in-body start-tag-hr (frameset-ok open-elements)
(when (element-in-scope "p" "button")
(end-tag-p (implied-tag-token "p")))
(insert-element token)
(pop-end open-elements)
(setf (getf token :self-closing-acknowledged) t)
(setf frameset-ok nil)
nil)
(def :in-body start-tag-image ()
(perror :unexpected-start-tag-treated-as
:original-name "image" :new-name "img")
(process-start-tag (implied-tag-token/full
"img" :start-tag
:attributes (getf token :data)
:self-closing (getf token :self-closing)))
nil)
(def :in-body start-tag-is-index (form-pointer)
(block nil
(perror :deprecated-tag :name "isindex")
(when form-pointer
(return nil))
(let (attrs)
(when (assoc "action" (getf token :data) :test #'string=)
(setf attrs (list (assoc "action" (getf token :data) :test #'string=))))
(process-start-tag (implied-tag-token/full "form" :start-tag
:attributes attrs)))
(process-start-tag (implied-tag-token "hr" :start-tag))
(process-start-tag (implied-tag-token "label" :start-tag))
;; XXX Localization ...
(let ((prompt (if (assoc "prompt" (getf token :data) :test #'string=)
(cdr (assoc "prompt" (getf token :data) :test #'string=))
"This is a searchable index. Enter search keywords: ")))
(process-characters (list :type :characters :data prompt)))
(let ((attrs (append (remove-if (lambda (el)
(member (car el) '("action" "prompt" "name")
:test #'string=))
(copy-list (getf token :data)))
(copy-list '(("name" . "isindex"))))))
(process-start-tag (implied-tag-token/full "input" :start-tag
:attributes attrs
:self-closing
(getf token :self-closing))))
(process-end-tag (implied-tag-token "label"))
(process-start-tag (implied-tag-token "hr" :start-tag))
(process-end-tag (implied-tag-token "form")))
nil)
(def :in-body start-tag-textarea (tokenizer
in-body-process-space-characters-mode
frameset-ok)
(insert-element token)
(setf (tokenizer-state tokenizer) :rcdata-state)
(setf in-body-process-space-characters-mode :drop-newline)
(setf frameset-ok nil)
nil)
(def :in-body start-tag-i-frame (frameset-ok)
(setf frameset-ok nil)
(start-tag-rawtext token)
nil)
(def :in-body start-tag-rawtext ()
;;;iframe, noembed noframes, noscript(if scripting enabled)
(parse-rc-data-raw-text token :rawtext)
nil)
(def :in-body start-tag-opt (phase)
(when (string= (node-name (last-open-element)) "option")
(process-end-tag (implied-tag-token "option") :phase phase))
(reconstruct-active-formatting-elements)
(insert-element token)
nil)
(def :in-body start-tag-select (frameset-ok)
(reconstruct-active-formatting-elements)
(insert-element token)
(setf frameset-ok nil)
(if (member (parser-phase *parser*) '(:in-table :in-caption :in-column-group
:in-table-body :in-row :in-cell))
(setf (parser-phase *parser*) :in-select-in-table)
(setf (parser-phase *parser*) :in-select))
nil)
(def :in-body start-tag-rp-rt ()
(when (element-in-scope "ruby")
(generate-implied-end-tags)
(when (string/= (node-name (last-open-element)) "ruby")
(perror :expected-ruby-tag)))
(insert-element token)
nil)
(def :in-body start-tag-math (open-elements)
(reconstruct-active-formatting-elements)
(adjust-math-ml-attributes token)
(adjust-foreign-attributes token)
(setf (getf token :namespace) (find-namespace "mathml"))
(insert-element token)
;;Need to get the parse error right for the case where the token
;;has a namespace not equal to the xmlns attribute
(when (getf token :self-closing)
(pop-end open-elements)
(setf (getf token :self-closing-acknowledged) t))
nil)
(def :in-body start-tag-svg (open-elements)
(reconstruct-active-formatting-elements)
(adjust-svg-attributes token)
(adjust-foreign-attributes token)
(setf (getf token :namespace) (find-namespace "svg"))
(insert-element token)
;;Need to get the parse error right for the case where the token
;;has a namespace not equal to the xmlns attribute
(when (getf token :self-closing)
(pop-end open-elements)
(setf (getf token :self-closing-acknowledged) t))
nil)
(def :in-body start-tag-misplaced ()
;;; Elements that should be children of other elements that have a
;;; different insertion mode; here they are ignored
;;; "caption", "col", "colgroup", "frame", "frameset", "head",
;;; "option", "optgroup", "tbody", "td", "tfoot", "th", "thead",
;;; "tr", "noscript"
(perror :unexpected-start-tag-ignored :name (getf token :name))
nil)
(def :in-body start-tag-other ()
(reconstruct-active-formatting-elements)
(insert-element token)
nil)
(def :in-body end-tag-p (open-elements)
(cond ((not (element-in-scope "p" "button"))
(start-tag-close-p (implied-tag-token "p" :start-tag))
(perror :unexpected-end-tag :name "p")
(end-tag-p (implied-tag-token "p")))
(t
(generate-implied-end-tags "p")
(when (string/= (node-name (last-open-element)) "p")
(perror :unexpected-end-tag :name "p"))
(let ((node (pop-end open-elements)))
(loop until (string= (node-name node) "p")
do (setf node (pop-end open-elements))))))
nil)
(def :in-body end-tag-body (open-elements)
(block nil
(when (not (element-in-scope "body"))
(perror :unexpected-scope)
(return nil))
(when (string/= (node-name (last-open-element)) "body")
(loop for node in (cddr open-elements)
do (when (member (node-name node)
'("dd" "dt" "li" "optgroup" "option" "p" "rp"
"rt" "tbody" "td" "tfoot" "th" "thead" "tr"
"body" "html")
:test #'string=)
;;Not sure this is the correct name for the parse error
(perror :expected-one-end-tag-but-got-another
:expected-name "body" :got-name (node-name node))
(return)))))
(setf (parser-phase *parser*) :after-body)
nil)
(def :in-body end-tag-html ()
;;We repeat the test for the body end tag token being ignored here
(cond ((element-in-scope "body")
(end-tag-body (implied-tag-token "body"))
token)
(t nil)))
(def :in-body end-tag-block (in-body-process-space-characters-mode open-elements)
;;Put us back in the right whitespace handling mode
(when (string= (getf token :name) "pre")
(setf in-body-process-space-characters-mode :non-pre))
(let ((in-scope (element-in-scope (getf token :name))))
(when in-scope
(generate-implied-end-tags))
(when (string/= (node-name (last-open-element))
(getf token :name))
(perror :end-tag-too-early :name (getf token :name)))
(when in-scope
(let ((node (pop-end open-elements)))
(loop until (string= (node-name node) (getf token :name))
do (setf node (pop-end open-elements))))))
nil)
(def :in-body end-tag-form (form-pointer open-elements)
(let ((node form-pointer))
(setf form-pointer nil)
(if (or (null node) (not (element-in-scope (node-name node))))
(perror :unexpected-end-tag :name "form")
(progn
(generate-implied-end-tags)
(when (not (equal (last-open-element) node))
(perror :end-tag-too-early-ignored :name "form"))
(setf open-elements
(remove node open-elements)))))
nil)
;;; Note to self:
;;; - A token is a plist.
;;; - A property is an alist.
;;; - A node is an object.
;;; - An element is a node.
(def :in-body end-tag-list-item (open-elements)
(let ((variant (if (string= (getf token :name) "li")
"list"
nil)))
(if (not (element-in-scope (getf token :name) variant))
(perror :unexpected-end-tag :name (getf token :name))
(progn
(generate-implied-end-tags (getf token :name))
(when (string/= (node-name (last-open-element))
(getf token :name))
(perror :end-tag-too-early :name (getf token :name)))
(let ((node (pop-end open-elements)))
(loop until (string= (node-name node) (getf token :name))
do (setf node (pop-end open-elements)))))))
nil)
(def :in-body end-tag-heading (open-elements)
(loop for item in +heading-elements+
do (when (element-in-scope item)
(generate-implied-end-tags)
(return)))
(when (string/= (node-name (last-open-element))
(getf token :name))
(perror :end-tag-too-early :name (getf token :name)))
(loop for item in +heading-elements+
do (when (element-in-scope item)
(let ((item (pop-end open-elements)))
(loop until (member (node-name item) +heading-elements+
:test #'string=)
do (setf item (pop-end open-elements))))))
nil)
(defmacro insert-elt-at (object index place)
(let ((tmp (gensym "TMP"))
(object-symbol (gensym "OBJECT"))
(index-symbol (gensym "INDEX")))
`(let ((,object-symbol ,object)
(,index-symbol ,index)
(,tmp ,place))
(setf ,place (append (subseq ,tmp 0 (min ,index-symbol (length ,tmp)))
(list ,object-symbol)
(nthcdr ,index-symbol ,tmp))))))
(def :in-body end-tag-formatting (active-formatting-elements open-elements)
;; The much-feared adoption agency algorithm
;; http://www.whatwg.org/specs/web-apps/current-work/#adoptionAgency
;; XXX Better parseError messages appreciated.
(loop named outer
with name = (getf token :name)
with outer-loop-counter = 0
with formatting-element
with afe-index
with furthest-block
with bookmark
with last-node
with inner-loop-counter
with index
with node
with common-ancestor
with clone
while (< outer-loop-counter 8)
do
(incf outer-loop-counter)
;; Step 1 paragraph 1
(setf formatting-element
(element-in-active-formatting-elements name))
(cond ((or (not formatting-element)
(and (member formatting-element
open-elements)
(not (element-in-scope
(node-name formatting-element)))))
(perror :adoption-agency-1.1 :name name)
(return-from outer nil))
;; Step 1 paragraph 2
((not (member formatting-element
open-elements))
(perror :adoption-agency-1.2 :name name)
(setf active-formatting-elements
(remove formatting-element active-formatting-elements))
(return-from outer nil)))
;; Step 1 paragraph 3
(unless (eql formatting-element
(last-open-element))
(perror :adoption-agency-1.3 :name name))
;; Step 2
;; Start of the adoption agency algorithm proper
(setf afe-index (position formatting-element
open-elements))
(setf furthest-block nil)
(loop for element in (subseq open-elements
afe-index)
do (when (member (node-name-tuple element)
+special-elements+
:test #'equal)
(setf furthest-block element)
(return)))
;; Step 3
(when (null furthest-block)
(loop for element = (pop-end open-elements)
until (eql formatting-element element)
finally (setf active-formatting-elements
(remove element
active-formatting-elements)))
(return-from outer nil))
(setf common-ancestor (elt open-elements (- afe-index 1)))
;; Step 5
;;if furthestBlock.parent:
;; furthestBlock.parent.removeChild(furthestBlock)
;; Step 5
;; The bookmark is supposed to help us
;; identify where to reinsert nodes in step
;; 12. We have to ensure that we reinsert
;; nodes after the node before the active
;; formatting element. Note the bookmark can
;; move in step 7.4
(setf bookmark (position formatting-element
active-formatting-elements))
;; Step 6
(setf node furthest-block)
(setf last-node node)
(setf inner-loop-counter 0)
(setf index (position node open-elements))
(loop named inner
while (< inner-loop-counter 3)
do
(block continue
(incf inner-loop-counter)
;; Node is element before node in open elements
(decf index)
(setf node (elt open-elements index))
(when (not (member node active-formatting-elements))
(setf open-elements
(remove node open-elements))
(return-from continue))
;; Step 6.3
(when (eql node formatting-element)
(return-from inner))
;; Step 6.4
(when (eql last-node furthest-block)
(setf bookmark (1+ (position node
active-formatting-elements))))
;; Step 6.5
(setf clone (node-clone* node))
;; Replace node with clone
(symbol-macrolet
((af active-formatting-elements)
(oe open-elements))
(setf (elt af (position node af)) clone)
(setf (elt oe (position node oe)) clone))
(setf node clone)
;; Step 6.6
;; Remove lastNode from its parents, if any
(when (node-parent last-node)
(node-remove-child (node-parent last-node)
last-node))
(node-append-child node last-node)
;; Step 7.7
(setf last-node node)
;; End of inner loop
))
;; Step 7
;; Foster parent lastNode if commonAncestor is a
;; table, tbody, tfoot, thead, or tr we need to
;; foster parent the lastNode
(when (node-parent last-node)
(node-remove-child (node-parent last-node)
last-node))
(if (member (node-name common-ancestor)
'("table" "tbody" "tfoot" "thead" "tr")
:test #'string=)
(multiple-value-bind (parent insert-before)
(get-table-misnested-nodeposition)
(node-insert-before* parent last-node insert-before))
(node-append-child* common-ancestor last-node))
;; Step 8
(setf clone (node-clone* formatting-element))
;; Step 9
(node-reparent-children furthest-block clone)
;; Step 10
(node-append-child* furthest-block clone)
;; Step 11
(setf active-formatting-elements
(remove formatting-element
active-formatting-elements))
(insert-elt-at clone bookmark active-formatting-elements)
;; Step 12
(setf open-elements
(remove formatting-element
open-elements))
(insert-elt-at clone
(1+ (position furthest-block
open-elements))
open-elements))
nil)
(def :in-body end-tag-applet-marquee-object (open-elements)
(when (element-in-scope (getf token :name))
(generate-implied-end-tags))
(when (string/= (node-name (last-open-element))
(getf token :name))
(perror :end-tag-too-early :name (getf token :name)))
(when (element-in-scope (getf token :name))
(let ((element (pop-end open-elements)))
(loop until (string= (node-name element) (getf token :name))
do (setf element (pop-end open-elements))))
(clear-active-formatting-elements))
nil)
(def :in-body end-tag-br (open-elements)
(perror :unexpected-end-tag-treated-as
:original-name "br" :new-name "br element")
(reconstruct-active-formatting-elements)
(insert-element (implied-tag-token "br" :start-tag))
(pop-end open-elements)
nil)
(def :in-body end-tag-other (open-elements)
(loop for node in (reverse open-elements)
do (cond ((string= (node-name node) (getf token :name))
(generate-implied-end-tags (getf token :name))
(when (string/= (node-name (last-open-element))
(getf token :name))
(perror :unexpected-end-tag :name (getf token :name)))
(loop while (not (eq node
(pop-end open-elements))))
(return))
(t
(when (member (node-name-tuple node) +special-elements+
:test #'equal)
(perror :unexpected-end-tag :name (getf token :name))
(return)))))
nil)
;; TextPhase
(tagname-dispatch :text process-start-tag
(default start-tag-other))
(tagname-dispatch :text process-end-tag
("script" end-tag-script)
(default end-tag-other))
(def :text process-characters ()
(parser-insert-text (getf token :data))
nil)
(def :text process-eof (phase original-phase open-elements)
(perror :expected-named-closing-tag-but-got-eof
(node-name (last-open-element)))
(pop-end open-elements)
(setf phase original-phase)
t)
(def :text start-tag-other ()
(error "Tried to process start tag ~S in RCDATA/RAWTEXT mode" (getf token :name)))
(def :text end-tag-script (phase original-phase open-elements)
(assert (string= (node-name (pop-end open-elements))
"script"))
(setf phase original-phase)
;; The rest of this method is all stuff that only happens if
;; document.write works
nil)
(def :text end-tag-other (phase original-phase open-elements)
(pop-end open-elements)
(setf phase original-phase)
nil)
;; InTablePhase
;; http://www.whatwg.org/specs/web-apps/current-work/#in-table
(tagname-dispatch :in-table process-start-tag
("html" start-tag-html)
("caption" start-tag-caption)
("colgroup" start-tag-colgroup)
("col" start-tag-col)
(("tbody" "tfoot" "thead") start-tag-row-group)
(("td" "th" "tr") start-tag-imply-tbody)
("table" start-tag-table)
(("style" "script") start-tag-style-script)
("input" start-tag-input)
("form" start-tag-form)
(default start-tag-other))
(tagname-dispatch :in-table process-end-tag
("table" end-Tag-Table)
(("body" "caption" "col" "colgroup" "html" "tbody" "td"
"tfoot" "th" "thead" "tr") end-Tag-Ignore)
(default end-tag-other))
(flet ((clear-stack-to-table-context ()
;; clear the stack back to a table context
(loop until (member (node-name (last-open-element))
'("table" "html")
:test #'string=)
do
;;(perror :unexpected-implied-end-tag-in-table
;; :name (node-name* (last-open-element)))
(pop-end (slot-value *parser* 'open-elements)))
;; When the current node is <html> it's an innerHTML case
))
(def :in-table process-eof (inner-html)
(if (string/= (node-name (last-open-element)) "html")
(perror :eof-in-table)
(assert inner-html))
;; Stop parsing
nil)
(def :in-table process-space-characters (phase original-phase)
(setf original-phase phase)
(setf phase :in-table-text)
(process-space-characters token :phase phase)
nil)
(def :in-table process-characters (phase original-phase)
(setf original-phase phase)
(setf phase :in-table-text)
(process-characters token :phase phase)
nil)
(def :in-table insert-text (insert-from-table)
;; If we get here there must be at least one non-whitespace character
;; Do the table magic!
(setf insert-from-table t)
(process-characters token :phase :in-body)
(setf insert-from-table nil)
nil)
(def :in-table start-tag-caption (phase active-formatting-elements)
(clear-stack-to-table-context)
(push-end :marker active-formatting-elements)
(insert-element token)
(setf phase :in-caption)
nil)
(def :in-table start-tag-colgroup (phase)
(clear-stack-to-table-context)
(insert-element token)
(setf phase :in-column-group)
nil)
(def :in-table start-tag-col ()
(start-tag-colgroup (implied-tag-token "colgroup" :start-tag))
token)
(def :in-table start-tag-row-group (phase)
(clear-stack-to-table-context)
(insert-element token)
(setf phase :in-table-body)
nil)
(def :in-table start-tag-imply-tbody ()
(start-tag-row-group (implied-tag-token "tbody" :start-tag))
token)
(def :in-table start-tag-table (phase inner-html)
(perror :unexpected-start-tag-implies-end-tag
:start-name "table"
:end-name "table")
(process-end-tag (implied-tag-token "table") :phase phase)
(unless inner-html
token))
(def :in-table start-tag-style-script ()
(process-start-tag token :phase :in-head))
(def :in-table start-tag-input (open-elements)
(let ((type (assoc "type" (getf token :data) :test #'string=)))
(cond ((and type
(string= (ascii-upper-2-lower (cdr type)) "hidden"))
(perror :unexpected-hidden-input-in-table)
(insert-element token)
;; XXX associate with form
(pop-end open-elements))
(t
(start-tag-other token))))
nil)
(def :in-table start-tag-form (form-pointer open-elements)
(perror :unexpected-form-in-table)
(unless form-pointer
(insert-element token)
(setf form-pointer (last-open-element))
(pop-end open-elements))
nil)
(def :in-table start-tag-other (insert-from-table)
(perror :unexpected-start-tag-implies-table-voodoo :name (getf token :name))
;; Do the table magic!
(setf insert-from-table t)
(process-start-tag token :phase :in-body)
(setf insert-from-table nil)
nil)
(def :in-table end-tag-table (inner-html open-elements)
(cond ((element-in-scope "table" "table")
(generate-implied-end-tags)
(unless (equal (node-name (last-open-element)) "table")
(perror :end-tag-too-early-named
:got-name "table"
:expected-name (node-name (last-open-element))))
(loop until (equal (node-name (last-open-element)) "table")
do (pop-end open-elements))
(pop-end open-elements)
(reset-insertion-mode))
(t
;; innerHTML case
(assert inner-html)
(perror :end-tag-table-in-table-inner-html-case)))
nil)
(def :in-table end-tag-ignore ()
(perror :unexpected-end-tag :name (getf token :name))
nil)
(def :in-table end-tag-other (insert-from-table)
(perror :unexpected-end-tag-implies-table-voodoo :name (getf token :name))
;; Do the table magic!
(setf insert-from-table t)
(process-end-tag token :phase :in-body)
(setf insert-from-table nil)
nil))
;; InTableTextPhase
(defun flush-characters ()
(with-slots (character-tokens) *parser*
(let ((data (apply #'concatenate 'string
(loop for item in (reverse character-tokens)
collect (getf item :data)))))
(if (not (only-space-characters-p data))
(insert-text (list :type :characters
:data data)
:phase :in-table)
(parser-insert-text data)))
(setf character-tokens nil)))
(def :in-table-text process-comment (phase original-phase)
(flush-characters)
(setf phase original-phase)
token)
(def :in-table-text process-eof (phase original-phase)
(flush-characters)
(setf phase original-phase)
t)
(def :in-table-text process-characters (character-tokens)
(unless (equal (getf token :data) (string #\u0000))
(push token character-tokens))
nil)
(def :in-table-text process-space-characters (character-tokens)
;; pretty sure we should never reach here
(push token character-tokens)
nil)
(def :in-table-text process-start-tag (phase original-phase)
(flush-characters)
(setf phase original-phase)
token)
(def :in-table-text process-end-tag (phase original-phase)
(flush-characters)
(setf phase original-phase)
token)
;; InCaptionPhase
;; http://www.whatwg.org/specs/web-apps/current-work/#in-caption
(tagname-dispatch :in-caption process-start-tag
("html" start-tag-html)
(("caption" "col" "colgroup" "tbody" "td" "tfoot" "th"
"thead" "tr") start-tag-table-element)
(default start-tag-other))
(tagname-dispatch :in-caption process-end-tag
("caption" end-tag-caption)
("table" end-tag-table)
(("body" "col" "colgroup" "html" "tbody" "td" "tfoot" "th"
"thead" "tr") end-tag-ignore)
(default end-tag-other))
(flet ((ignore-end-tag-caption ()
(not (element-in-scope "caption" "table"))))
(def :in-caption process-eof ()
(process-eof token :phase :in-body))
(def :in-caption process-characters ()
(process-characters token :phase :in-body))
(def :in-caption start-tag-table-element (phase)
(perror :start-tag-table-element-in-caption)
;; XXX Have to duplicate logic here to find out if the tag is ignored
(prog1 (unless (ignore-end-tag-caption)
token)
(process-end-tag (implied-tag-token "caption") :phase phase)))
(def :in-caption start-tag-other ()
(process-start-tag token :phase :in-body))
(def :in-caption end-tag-caption (phase inner-html open-elements)
(cond ((not (ignore-end-tag-caption))
;; AT this code is quite similar to endTagTable in "InTable"
(generate-implied-end-tags)
(unless (equal (node-name (last-open-element)) "caption")
(perror :expected-one-end-tag-but-got-another
:got-name "caption"
:expected-name (node-name (last-open-element))))
(loop until (equal (node-name (last-open-element)) "caption")
do (pop-end open-elements))
(clear-active-formatting-elements)
(setf phase :in-table))
(t
;; innerHTML case
(assert inner-html)
(perror :end-tag-caption-in-caption-inner-html-mode)))
nil)
(def :in-caption end-tag-table (phase)
(perror :end-tag-table-in-caption)
(prog1 (unless (ignore-end-tag-caption)
token)
(process-end-tag (implied-tag-token "caption") :phase phase)))
(def :in-caption end-tag-ignore ()
(perror :unexpected-end-tag :name (getf token :name))
nil)
(def :in-caption end-tag-other ()
(process-end-tag token :phase :in-body)))
;; InColumnGroupPhase
;; http://www.whatwg.org/specs/web-apps/current-work/#in-column
(tagname-dispatch :in-column-group process-start-tag
("html" start-tag-html)
("col" start-tag-col)
(default start-tag-other))
(tagname-dispatch :in-column-group process-end-tag
("colgroup" end-tag-colgroup)
("col" end-tag-col)
(default end-tag-other))
(flet ((ignore-end-tag-colgroup ()
(string= (node-name (last-open-element)) "html")))
(def :in-column-group process-eof (inner-html)
(cond ((string= (node-name (last-open-element)) "html")
(assert inner-html)
nil)
(t
(let ((ignore-end-tag (ignore-end-tag-colgroup)))
(end-tag-colgroup (implied-tag-token "colgroup"))
(not ignore-end-tag)))))
(def :in-column-group process-characters ()
(prog1 (unless (ignore-end-tag-colgroup)
token)
(end-tag-colgroup (implied-tag-token "colgroup"))))
(def :in-column-group start-tag-col (open-elements)
(insert-element token)
(pop-end open-elements)
nil)
(def :in-column-group start-tag-other ()
(prog1 (unless (ignore-end-tag-colgroup)
token)
(end-tag-colgroup (implied-tag-token "colgroup"))))
(def :in-column-group end-tag-colgroup (phase open-elements)
(cond ((ignore-end-tag-colgroup)
;; innerHTML case
(perror :end-tag-colgroup-in-column-group-inner-html-mode))
(t
(pop-end open-elements)
(setf phase :in-table)))
nil)
(def :in-column-group end-tag-col ()
(perror :no-end-tag :name "col")
nil)
(def :in-column-group end-tag-other ()
(prog1 (unless (ignore-end-tag-colgroup)
token)
(end-tag-colgroup (implied-tag-token "colgroup")))))
;; InTableBodyPhase
;; http://www.whatwg.org/specs/web-apps/current-work/#in-table0
(tagname-dispatch :in-table-body process-start-tag
("html" start-tag-html)
("tr" start-tag-tr)
(("td" "th") start-tag-table-cell)
(("caption" "col" "colgroup" "tbody" "tfoot" "thead") start-tag-table-other)
(default start-tag-other))
(tagname-dispatch :in-table-body process-end-tag
(("tbody" "tfoot" "thead") end-Tag-Table-Row-Group)
("table" end-Tag-Table)
(("body" "caption" "col" "colgroup" "html" "td" "th" "tr") end-Tag-Ignore)
(default end-tag-other))
(flet ((clear-stack-to-table-body-context ()
(loop until (member (node-name (last-open-element))
'("tbody" "tfoot" "thead" "html")
:test #'string=)
do
;;(perror :unexpected-implied-end-tag-in-table
;; :name (node-name (last-open-element)))
(pop-end (slot-value *parser* 'open-elements)))
(when (string= (node-name (last-open-element)) "html")
(assert (slot-value *parser* 'inner-html)))))
(def :in-table-body process-eof ()
(process-eof token :phase :in-table))
(def :in-table-body process-space-characters ()
(process-space-characters token :phase :in-table))
(def :in-table-body process-characters ()
(process-characters token :phase :in-table))
(def :in-table-body start-tag-tr (phase)
(clear-stack-to-table-body-context)
(insert-element token)
(setf phase :in-row)
nil)
(def :in-table-body start-tag-table-cell ()
(perror :unexpected-cell-in-table-body :name (getf token :name))
(start-tag-tr (implied-tag-token "tr" :start-tag))
token)
(def :in-table-body start-tag-table-other (inner-html)
;; XXX AT Any ideas on how to share this with endTagTable?
(cond ((or (element-in-scope "tbody" "table")
(element-in-scope "thead" "table")
(element-in-scope "tfoot" "table"))
(clear-stack-to-table-body-context)
(end-tag-table-row-group
(implied-tag-token (node-name (last-open-element))))
token)
(t
;; innerHTML case
(assert inner-html)
(perror :start-tag-table-other-in-table-body-inner-html-mode)
nil)))
(def :in-table-body start-tag-other ()
(process-start-tag token :phase :in-table))
(def :in-table-body end-tag-table-row-group (phase open-elements)
(cond ((element-in-scope (getf token :name) "table")
(clear-stack-to-table-body-context)
(pop-end open-elements)
(setf phase :in-table))
(t
(perror :unexpected-end-tag-in-table-body :name (getf token :name))))
nil)
(def :in-table-body end-tag-table (inner-html)
(cond ((or (element-in-scope "tbody" "table")
(element-in-scope "thead" "table")
(element-in-scope "tfoot" "table"))
(clear-stack-to-table-body-context)
(end-tag-table-row-group
(implied-tag-token (node-name (last-open-element))))
token)
(t
;; innerHTML case
(assert inner-html)
(perror :end-tag-table-other-in-table-body-inner-html-mode)
nil)))
(def :in-table-body end-tag-ignore ()
(perror :unexpected-end-tag-in-table-body :name (getf token :name))
nil)
(def :in-table-body end-tag-other ()
(process-end-tag token :phase :in-table)))
;; InRowPhase
;; http://www.whatwg.org/specs/web-apps/current-work/#in-row
(tagname-dispatch :in-row process-start-tag
("html" start-tag-html)
(("td" "th") start-tag-table-cell)
(("caption" "col" "colgroup" "tbody" "tfoot" "thead" "tr")
start-tag-table-other)
(default start-tag-other))
(tagname-dispatch :in-row process-end-tag
("tr" end-tag-tr)
("table" end-tag-table)
(("tbody" "tfoot" "thead") end-tag-table-row-group)
(("body" "caption" "col" "colgroup" "html" "td" "th") end-tag-ignore)
(default end-tag-other))
;; helper methods (XXX unify this with other table helper methods)
(flet ((clear-stack-to-table-row-context ()
(loop until (member (node-name (last-open-element))
'("tr" "html")
:test #'string=)
do
(perror :unexpected-implied-end-tag-in-table-row
:name (node-name (last-open-element)))
(pop-end (slot-value *parser* 'open-elements))))
(ignore-end-tag-tr ()
(not (element-in-scope "tr" "table"))))
;; the rest
(def :in-row process-eof ()
(process-eof token :phase :in-table)
nil)
(def :in-row process-space-characters ()
(process-space-characters token :phase :in-table))
(def :in-row process-characters ()
(process-characters token :phase :in-table))
(def :in-row start-tag-table-cell (phase active-formatting-elements)
(clear-stack-to-table-row-context)
(insert-element token)
(setf phase :in-cell)
(push-end :marker active-formatting-elements)
nil)
(def :in-row start-tag-table-other ()
(let ((ignore-end-tag (ignore-end-tag-tr)))
(end-tag-tr (implied-tag-token "tr"))
;; XXX how are we sure it's always ignored in the innerHTML case?
(unless ignore-end-tag
token)))
(def :in-row start-tag-other ()
(process-start-tag token :phase :in-table))
(def :in-row end-tag-tr (phase inner-html open-elements)
(cond ((not (ignore-end-tag-tr))
(clear-stack-to-table-row-context)
(pop-end open-elements)
(setf phase :in-table-body))
(t
;; innerHTML case
(assert inner-html)
(perror :end-tag-tr-inner-html-mode)))
nil)
(def :in-row end-tag-table ()
(let ((ignore-end-tag (ignore-end-tag-tr)))
(end-tag-tr (implied-tag-token "tr"))
;; Reprocess the current tag if the tr end tag was not ignored
;; XXX how are we sure it's always ignored in the innerHTML case?
(unless ignore-end-tag
token)))
(def :in-row end-tag-table-row-group ()
(cond ((element-in-scope (getf token :name) "table")
(end-tag-tr (implied-tag-token "tr"))
token)
(t
(perror :end-tag-table-row-group-something-wrong)
nil)))
(def :in-row end-tag-ignore ()
(perror :unexpected-end-tag-in-table-row (getf token :name))
nil)
(def :in-row end-tag-other ()
(process-end-tag token :phase :in-table)))
;; InCellPhase
;; http://www.whatwg.org/specs/web-apps/current-work/#in-cell
(tagname-dispatch :in-cell process-start-tag
("html" start-tag-html)
(("caption" "col" "colgroup" "tbody" "td" "tfoot" "th" "thead" "tr")
start-tag-table-other)
(default start-tag-other))
(tagname-dispatch :in-cell process-end-tag
(("td" "th") end-tag-table-cell)
(("body" "caption" "col" "colgroup" "html") end-tag-ignore)
(("table" "tbody" "tfoot" "thead" "tr") end-tag-imply)
(default end-tag-other))
(flet ((close-cell ()
(if (element-in-scope "td" "table")
(end-tag-table-cell (implied-tag-token "td"))
(if (element-in-scope "th" "table")
(end-tag-table-cell (implied-tag-token "th"))))))
(def :in-cell process-eof ()
(process-eof token :phase :in-body)
nil)
(def :in-cell process-characters ()
(process-characters token :phase :in-body))
(def :in-cell start-tag-table-other (inner-html)
(cond ((or (element-in-scope "td" "table")
(element-in-scope "th" "table"))
(close-cell)
token)
(t
;; innerHTML case
(assert inner-html)
(perror :start-tag-table-other-in-inner-html-mode)
nil)))
(def :in-cell start-tag-other ()
(process-start-tag token :phase :in-body))
(def :in-cell end-tag-table-cell (phase open-elements)
(cond ((element-in-scope (getf token :name) "table")
(generate-implied-end-tags (getf token :name))
(cond ((not (equal (node-name (last-open-element))
(getf token :name)))
(perror :unexpected-cell-end-tag :name (getf token :name))
(loop until (equal (node-name (pop-end open-elements))
(getf token :name))))
(t
(pop-end open-elements)))
(clear-active-formatting-elements)
(setf phase :in-row))
(t
(perror :unexpected-end-tag :name (getf token :name))))
nil)
(def :in-cell end-tag-ignore ()
(perror :unexpected-end-tag :name (getf token :name))
nil)
(def :in-cell end-tag-imply ()
(cond ((element-in-scope (getf token :name) "table")
(close-cell)
token)
(t
;; sometimes innerHTML case
(perror :end-tag-imply-sometimes-inner-html-case)
nil)))
(def :in-cell end-tag-other ()
(process-end-tag token :phase :in-body)))
;; InSelectPhase
(tagname-dispatch :in-select process-start-tag
("html" start-tag-html)
("option" start-tag-option)
("optgroup" start-tag-optgroup)
("select" start-tag-select)
(("input" "keygen" "textarea") start-tag-input)
("script" start-tag-script)
(default start-tag-other))
(tagname-dispatch :in-select process-end-tag
("option" end-tag-option)
("optgroup" end-tag-optgroup)
("select" end-tag-select)
(default end-tag-other))
;; http://www.whatwg.org/specs/web-apps/current-work/#in-select
(def :in-select process-eof (inner-html)
(if (not (equal (node-name (last-open-element)) "html"))
(perror :eof-in-select)
(assert inner-html))
nil)
(def :in-select process-characters ()
(unless (equal (getf token :data) (string #\u0000))
(parser-insert-text (getf token :data)))
nil)
(def :in-select start-tag-option (open-elements)
;; We need to imply </option> if <option> is the current node.
(when (equal (node-name (last-open-element)) "option")
(pop-end open-elements))
(insert-element token)
nil)
(def :in-select start-tag-optgroup (open-elements)
(when (equal (node-name (last-open-element)) "option")
(pop-end open-elements))
(when (equal (node-name (last-open-element)) "optgroup")
(pop-end open-elements))
(insert-element token)
nil)
(def :in-select start-tag-select ()
(perror :unexpected-select-in-select)
(end-tag-select (implied-tag-token "select"))
nil)
(def :in-select start-tag-input (inner-html)
(perror :unexpected-input-in-select)
(cond ((element-in-scope "select" "select")
(end-tag-select (implied-tag-token "select"))
token)
(t
(assert inner-html)
nil)))
(def :in-select start-tag-script ()
(process-start-tag token :phase :in-head))
(def :in-select start-tag-other ()
(perror :unexpected-start-tag-in-select :name (getf token :name))
nil)
(def :in-select end-tag-option (open-elements)
(if (equal (node-name (last-open-element)) "option")
(pop-end open-elements)
(perror :unexpected-end-tag-in-select :name (getf token :name)))
nil)
(def :in-select end-tag-optgroup (open-elements)
;; </optgroup> implicitly closes <option>
(when (and (equal (node-name (last-open-element)) "option")
(equal (node-name (elt open-elements
(- (length open-elements) 2)))
"optgroup"))
(pop-end open-elements))
;; It also closes </optgroup>
(if (equal (node-name (last-open-element)) "optgroup")
(pop-end open-elements)
;; But nothing else
(perror :unexpected-end-tag-in-select :name (getf token :name)))
nil)
(def :in-select end-tag-select (inner-html open-elements)
(cond ((element-in-scope "select" "select")
(loop until (equal (node-name (pop-end open-elements))
"select"))
(reset-insertion-mode))
(t
;; innerHTML case
(assert inner-html)
(perror :end-tag-select-in-inner-html-mode)))
nil)
(def :in-select end-tag-other ()
(perror :unexpected-end-tag-in-select :name (getf token :name))
nil)
;; InSelectInTablePhase
(tagname-dispatch :in-select-in-table process-start-tag
(("caption" "table" "tbody" "tfoot" "thead" "tr" "td" "th") start-tag-table)
(default start-tag-other))
(tagname-dispatch :in-select-in-table process-end-tag
(("caption" "table" "tbody" "tfoot" "thead" "tr" "td" "th") end-tag-table)
(default end-tag-other))
(def :in-select-in-table process-eof ()
(process-eof token :phase :in-select)
nil)
(def :in-select-in-table process-characters ()
(process-characters token :phase :in-select))
(def :in-select-in-table start-tag-table ()
(perror :unexpected-table-element-start-tag-in-select-in-table :name (getf token :name))
(end-tag-other (implied-tag-token "select"))
token)
(def :in-select-in-table start-tag-other ()
(process-start-tag token :phase :in-select))
(def :in-select-in-table end-tag-table ()
(perror :unexpected-table-element-end-tag-in-select-in-table :name (getf token :name))
(cond ((element-in-scope (getf token :name) "table")
(end-tag-other (implied-tag-token "select"))
token)
(t
nil)))
(def :in-select-in-table end-tag-other ()
(process-end-tag token :phase :in-select))
;; InForeignContentPhase
(defparameter +breakout-elements+
'("b" "big" "blockquote" "body" "br"
"center" "code" "dd" "div" "dl" "dt"
"em" "embed" "h1" "h2" "h3"
"h4" "h5" "h6" "head" "hr" "i" "img"
"li" "listing" "menu" "meta" "nobr"
"ol" "p" "pre" "ruby" "s" "small"
"span" "strong" "strike" "sub" "sup"
"table" "tt" "u" "ul" "var"))
(defun adjust-svg-tag-names (token)
(let ((replacement (cdr
(assoc (getf token :name)
'(("altglyph" . "altGlyph")
("altglyphdef" . "altGlyphDef")
("altglyphitem" . "altGlyphItem")
("animatecolor" . "animateColor")
("animatemotion" . "animateMotion")
("animatetransform" . "animateTransform")
("clippath" . "clipPath")
("feblend" . "feBlend")
("fecolormatrix" . "feColorMatrix")
("fecomponenttransfer" . "feComponentTransfer")
("fecomposite" . "feComposite")
("feconvolvematrix" . "feConvolveMatrix")
("fediffuselighting" . "feDiffuseLighting")
("fedisplacementmap" . "feDisplacementMap")
("fedistantlight" . "feDistantLight")
("feflood" . "feFlood")
("fefunca" . "feFuncA")
("fefuncb" . "feFuncB")
("fefuncg" . "feFuncG")
("fefuncr" . "feFuncR")
("fegaussianblur" . "feGaussianBlur")
("feimage" . "feImage")
("femerge" . "feMerge")
("femergenode" . "feMergeNode")
("femorphology" . "feMorphology")
("feoffset" . "feOffset")
("fepointlight" . "fePointLight")
("fespecularlighting" . "feSpecularLighting")
("fespotlight" . "feSpotLight")
("fetile" . "feTile")
("feturbulence" . "feTurbulence")
("foreignobject" . "foreignObject")
("glyphref" . "glyphRef")
("lineargradient" . "linearGradient")
("radialgradient" . "radialGradient")
("textpath" . "textPath"))
:test #'string=))))
(when replacement
(setf (getf token :name) replacement))))
(defparameter +only-space-characters-regexp+
(cl-ppcre:create-scanner `(:sequence :start-anchor
(:greedy-repetition
0 nil
(:alternation ,@(coerce +space-characters+ 'list)))
:end-anchor)
:multi-line-mode t))
(defun only-space-characters-p (string)
(cl-ppcre:scan +only-space-characters-regexp+ string))
(def :in-foreign-content process-characters (frameset-ok)
(cond ((equal (getf token :data) (string #\u0000))
(setf (getf token :data) (string #\uFFFD)))
((and frameset-ok
(not (only-space-characters-p (getf token :data))))
(setf frameset-ok nil)))
(process-characters token :phase nil)
nil)
(def :in-foreign-content process-start-tag (html-namespace open-elements)
(block nil
(let ((current-node (last-open-element)))
(cond ((or (member (getf token :name) +breakout-elements+ :test #'string=)
(and (string= (getf token :name) "font")
(intersection (mapcar #'car (getf token :data))
'("color" "face" "size")
:test #'string=)))
(parser-parse-error :unexpected-html-element-in-foreign-content
(getf token :name))
(loop until (or (is-html-integration-point (last-open-element))
(is-math-ml-text-integration-point (last-open-element))
(equal (node-namespace (last-open-element))
html-namespace))
do (pop-end open-elements))
(return token))
(t
(cond ((equal (node-namespace current-node) (find-namespace "mathml"))
(adjust-math-ml-attributes token))
((equal (node-namespace current-node) (find-namespace "svg"))
(adjust-svg-tag-names token)
(adjust-svg-attributes token)))
(adjust-foreign-attributes token)
(setf (getf token :namespace) (node-namespace current-node))
(insert-element token)
(when (getf token :self-closing)
(pop-end open-elements)
(setf (getf token :self-closing-acknowledged) t)))))
nil))
(def :in-foreign-content process-end-tag (phase original-phase html-namespace open-elements)
(let ((new-token)
(node-index (1- (length open-elements)))
(node (last-open-element)))
(unless (string= (node-name node) (getf token :name))
(parser-parse-error :unexpected-end-tag (getf token :name)))
(loop
(when (string= (ascii-upper-2-lower (node-name node)) (getf token :name))
;; XXX this isn't in the spec but it seems necessary
(when (eql phase :in-table-text)
(flush-characters)
(setf phase original-phase))
(loop until (eql (pop-end open-elements) node)
do (assert open-elements))
(setf new-token nil)
(return))
(decf node-index)
(setf node (elt open-elements node-index))
(when (equal (node-namespace node)
html-namespace)
(setf new-token (process-end-tag token :phase phase))
(return)))
new-token))
;; AfterBodyPhase
(tagname-dispatch :after-body process-start-tag
("html" start-tag-html)
(default start-tag-other))
(tagname-dispatch :after-body process-end-tag
("html" end-tag-html)
(default end-tag-other))
(def :after-body process-eof ()
;; Stop parsing
nil)
(def :after-body process-comment (open-elements)
;; This is needed because data is to be appended to the <html> element
;; here and not to whatever is currently open.
(insert-comment token (first open-elements))
nil)
(def :after-body process-characters (phase)
(parser-parse-error :unexpected-char-after-body)
(setf phase :in-body)
token)
(def :after-body start-tag-html ()
(process-start-tag token :phase :in-body))
(def :after-body start-tag-other (phase)
(parser-parse-error :unexpected-start-tag-after-body
`(:name ,(getf token :name)))
(setf phase :in-body)
token)
(def :after-body end-tag-html (inner-html phase)
(if inner-html
(parser-parse-error :unexpected-end-tag-after-body-innerhtml)
(setf phase :after-after-body))
nil)
(def :after-body end-tag-other (phase)
(parser-parse-error :unexpected-end-tag-after-body
`(:name ,(getf token :name)))
(setf phase :in-body)
token)
;; InFramesetPhase
(tagname-dispatch :in-frameset process-start-tag
("html" start-tag-html)
("frameset" start-tag-frameset)
("frame" start-tag-frame)
("noframes"start-tag-noframes)
(default start-tag-other))
(tagname-dispatch :in-frameset process-end-tag
("frameset" end-tag-frameset)
(default end-tag-other))
(def :in-frameset process-eof (inner-html)
(if (string/= (node-name (last-open-element)) "html")
(parser-parse-error :eof-in-frameset)
(assert inner-html))
nil)
(def :in-frameset process-characters ()
(parser-parse-error :unexpected-char-in-frameset)
nil)
(def :in-frameset start-tag-frameset ()
(insert-element token)
nil)
(def :in-frameset start-tag-frame (open-elements)
(insert-element token)
(pop-end open-elements)
nil)
(def :in-frameset start-tag-noframes ()
(process-start-tag token :phase :in-body))
(def :in-frameset start-tag-other ()
(parser-parse-error :unexpected-start-tag-in-frameset
`(:name ,(getf token :name)))
nil)
(def :in-frameset end-tag-frameset (phase inner-html open-elements)
(if (string= (node-name (last-open-element)) "html")
;; innerHTML case
(parser-parse-error :unexpected-frameset-in-frameset-innerhtml)
(pop-end open-elements))
(when (and (not inner-html)
(string/= (node-name (last-open-element)) "frameset"))
;; If we're not in innerHTML mode and the the current node is not a
;; "frameset" element (anymore) then switch.
(setf phase :after-frameset))
nil)
(def :in-frameset end-tag-other ()
(parser-parse-error :unexpected-end-tag-in-frameset
`(:name ,(getf token :name)))
nil)
;; AfterFramesetPhase
(tagname-dispatch :after-frameset process-start-tag
("html" start-tag-html)
("noframes" start-tag-noframes)
(default start-tag-other))
(tagname-dispatch :after-frameset process-end-tag
("html" end-tag-html)
(default end-tag-other))
(def :after-frameset process-eof ()
;; Stop parsing
nil)
(def :after-frameset process-characters ()
(parser-parse-error :unexpected-char-after-frameset)
nil)
(def :after-frameset start-tag-noframes ()
(process-start-tag token :phase :in-head))
(def :after-frameset start-tag-other ()
(parser-parse-error :unexpected-start-tag-after-frameset
`(:name ,(getf token :name)))
nil)
(def :after-frameset end-tag-html (phase)
(setf phase :after-after-frameset)
nil)
(def :after-frameset end-tag-other ()
(parser-parse-error :unexpected-end-tag-after-frameset
`(:name ,(getf token :name)))
nil)
;; AfterAfterBodyPhase
(tagname-dispatch :after-after-body process-start-tag
("html" start-tag-html)
(default start-tag-other))
(def :after-after-body process-eof ()
nil)
(def :after-after-body process-comment ()
(insert-comment token (document*))
nil)
(def :after-after-body process-space-characters ()
(process-space-characters token :phase :in-body))
(def :after-after-body process-characters (phase)
(parser-parse-error :expected-eof-but-got-char)
(setf phase :in-body)
token)
(def :after-after-body start-tag-html ()
(process-start-tag token :phase :in-body))
(def :after-after-body start-tag-other (phase)
(parser-parse-error :expected-eof-but-got-start-tag
`(:name (getf token :name)))
(setf phase :in-body)
token)
(def :after-after-body process-end-tag (phase)
(parser-parse-error :expected-eof-but-got-end-tag
`(:name (getf token :name)))
(setf phase :in-body)
token)
;; AfterAfterFramesetPhase
(tagname-dispatch :after-after-frameset process-start-tag
("html" start-tag-html)
("noframes" start-tag-noframes)
(default start-tag-other))
(def :after-after-frameset process-eof ()
nil)
(def :after-after-frameset process-comment ()
(insert-comment token (document*))
nil)
(def :after-after-frameset process-space-characters ()
(process-space-characters token :phase :in-body))
(def :after-after-frameset process-characters ()
(parser-parse-error :expected-eof-but-got-char)
nil)
(def :after-after-frameset start-tag-html ()
(process-start-tag token :phase :in-body))
(def :after-after-frameset start-tag-noframes ()
(process-start-tag token :phase :in-head))
(def :after-after-frameset start-tag-other ()
(parser-parse-error :expected-eof-but-got-start-tag
`(:name (getf token :name)))
nil)
(def :after-after-frameset process-end-tag ()
(parser-parse-error :expected-eof-but-got-end-tag
`(:name (getf token :name)))
nil)
| 103,109
|
Common Lisp
|
.lisp
| 2,460
| 31.982927
| 119
| 0.579752
|
rotatef/cl-html5-parser
| 55
| 14
| 11
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
70f73032563de109c359b755ae44df5690e455537182acaac911a286cd088f9a
| 3,082
|
[
-1
] |
3,083
|
simple-tree.lisp
|
rotatef_cl-html5-parser/simple-tree.lisp
|
;;;; HTML5 parser for Common Lisp
;;;;
;;;; Copyright (C) 2012 Thomas Bakketun <thomas.bakketun@copyleft.no>
;;;; Copyright (C) 2012 Asgeir Bj√∏rlykke <asgeir@copyleft.no>
;;;; Copyright (C) 2012 Mathias Hellevang
;;;; Copyright (C) 2012 Stian Sletner <stian@copyleft.no>
;;;;
;;;; This library is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Lesser General Public License as published
;;;; by the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This library 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 library. If not, see <http://www.gnu.org/licenses/>.
(in-package :html5-parser)
;; A basic implementation of a DOM-core like thing
(defclass node ()
((type :initform :node :allocation :class :reader node-type)
(name :initarg :name :initform nil :reader node-name)
(namespace :initarg :namespace :initform nil :reader node-namespace)
(parent :initform nil :reader node-parent)
(value :initform nil :initarg :value
:accessor node-value)
(child-nodes :initform nil :accessor %node-child-nodes)
(last-child :initform nil :accessor last-child)))
(defmethod (setf %node-child-nodes) :after (value (node node))
(setf (last-child node) (last value)))
(defclass document (node)
((type :initform :document :allocation :class)))
(defclass document-fragment (document)
((type :initform :document-fragment :allocation :class)))
(defclass document-type (node)
((type :initform :document-type :allocation :class)
(public-id :initarg :public-id :reader node-public-id)
(system-id :initarg :system-id :reader node-system-id)))
(defclass text-node (node)
((type :initform :text :allocation :class)))
(defclass element (node)
((type :initform :element :allocation :class)
(attributes :initform nil :accessor %node-attributes)))
(defclass comment-node (node)
((type :initform :comment :allocation :class)))
;;;
;;; Creating nodes
;;;
(defun make-document ()
(make-instance 'document))
(defun make-fragment (document)
(declare (ignore document))
(make-instance 'document-fragment))
(defun make-doctype (document name public-id system-id)
(declare (ignore document))
(make-instance 'document-type :name name :public-id public-id :system-id system-id))
(defun make-comment (document data)
(declare (ignore document))
(make-instance 'comment-node :value data))
(defun make-element (document name namespace)
(declare (ignore document))
(make-instance 'element :name name :namespace namespace))
(defun make-text-node (document data)
(declare (ignore document))
(make-instance 'text-node :value data))
;;;
;;; Node methods
;;;
(defun node-first-child (node)
(car (%node-child-nodes node)))
(defun node-last-child (node)
(car (last-child node)))
(defun node-previous-sibling (node)
(loop for (this next) on (%node-child-nodes (node-parent node))
when (eql next node) do (return this)))
(defun node-next-sibling (node)
(loop for (this next) on (%node-child-nodes (node-parent node))
when (eql this node) do (return next)))
(defun node-append-child (node child)
(when (node-parent child)
(node-remove-child (node-parent child) child))
(setf (slot-value child 'parent) node)
(if (%node-child-nodes node)
(setf (last-child node)
(push child (cdr (last-child node))))
(setf (%node-child-nodes node)
(list child)))
(%node-child-nodes node))
(defun node-remove-child (node child)
(setf (%node-child-nodes node)
(remove child (%node-child-nodes node)))
(setf (slot-value child 'parent) nil))
(defun node-insert-before (node child insert-before)
(let ((child-nodes (%node-child-nodes node)))
(setf (slot-value child 'parent) node)
(labels ((insert-before (child-nodes)
(cond ((endp child-nodes)
(cons child nil))
((eql (car child-nodes) insert-before)
(cons child child-nodes))
(t (rplacd child-nodes (insert-before (cdr child-nodes)))))))
(setf (%node-child-nodes node)
(insert-before child-nodes)))))
(defun element-attribute (node attribute &optional namespace)
(cdr (assoc (cons attribute namespace)
(%node-attributes node)
:test #'equal)))
(defun (setf element-attribute) (new-value node attribute
&optional namespace)
(check-type attribute string)
(check-type new-value string)
(let ((old-attr (assoc (cons attribute namespace)
(%node-attributes node)
:test #'equal)))
(if old-attr
(setf (cdr old-attr) new-value)
(push (cons (cons attribute namespace) new-value) (%node-attributes node)))))
;;;
;;; Traversing
;;;
(defun element-map-children (function node)
(map nil function (%node-child-nodes node)))
(defun element-map-attributes* (function node)
(loop for ((name . namespace) . value) in (%node-attributes node)
do (funcall function name namespace value)))
(defun element-map-attributes (function node)
(element-map-attributes*
(lambda (name namespace value)
(funcall function
(if namespace
(format nil "~A:~A" (html5-constants:find-prefix namespace) name)
name)
namespace
value))
node))
;;
;; Printing for the ease of debugging
;;
(defun node-count (tree)
(typecase tree
(element (1+ (apply #'+ (mapcar #'node-count (%node-child-nodes tree)))))
((or document document-fragment)
(apply #'+ (mapcar #'node-count (%node-child-nodes tree))))
(t 1)))
(defmethod print-object ((node document) stream)
(print-unreadable-object (node stream :type t :identity t)
(format stream "nodes: ~A" (node-count node))))
(defmethod print-object ((node node) stream)
(print-unreadable-object (node stream :type t :identity t)
(format stream "~A" (node-name node))))
(defmethod print-object ((node text-node) stream)
(print-unreadable-object (node stream :type t :identity t)
(write (node-value node) :stream stream :length 30)))
| 6,504
|
Common Lisp
|
.lisp
| 155
| 37.064516
| 86
| 0.677649
|
rotatef/cl-html5-parser
| 55
| 14
| 11
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
8f71c4ba5e0d51ebbb8caca35f8f1331983122825752b863663d7c9ac5851c08
| 3,083
|
[
-1
] |
3,084
|
constants.lisp
|
rotatef_cl-html5-parser/constants.lisp
|
;;;; HTML5 parser for Common Lisp
;;;;
;;;; Copyright (C) 2012 Thomas Bakketun <thomas.bakketun@copyleft.no>
;;;; Copyright (C) 2012 Asgeir Bj√∏rlykke <asgeir@copyleft.no>
;;;; Copyright (C) 2012 Mathias Hellevang
;;;; Copyright (C) 2012 Stian Sletner <stian@copyleft.no>
;;;;
;;;; This library is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Lesser General Public License as published
;;;; by the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This library 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 library. If not, see <http://www.gnu.org/licenses/>.
(in-package :html5-constants)
(defmacro defglobal (name value &optional docstring)
(let ((docstring (and docstring (list docstring))))
;; SBCL evaluates the init value of a global at compile time.
#+sbcl `(progn (sb-ext:defglobal ,name nil ,@docstring)
(setq ,name ,value)
',name)
#+ccl `(ccl:defstatic ,name ,value ,@docstring)
#-(or sbcl ccl) `(defparameter ,name ,value ,@docstring)))
(defglobal +namespaces+
'(("html" . "http://www.w3.org/1999/xhtml")
("mathml" ."http://www.w3.org/1998/Math/MathML")
("svg" . "http://www.w3.org/2000/svg")
("xlink" . "http://www.w3.org/1999/xlink")
("xml" . "http://www.w3.org/XML/1998/namespace")
("xmlns" . "http://www.w3.org/2000/xmlns/")))
(defun find-namespace (prefix)
(cdr (assoc prefix +namespaces+ :test #'string=)))
(defun find-prefix (namespace)
(car (find namespace +namespaces+ :test #'string= :key #'cdr)))
(defglobal +scoping-elements+
`((,(find-namespace "html") . "applet")
(,(find-namespace "html") . "caption")
(,(find-namespace "html") . "html")
(,(find-namespace "html") . "marquee")
(,(find-namespace "html") . "object")
(,(find-namespace "html") . "table")
(,(find-namespace "html") . "td")
(,(find-namespace "html") . "th")
(,(find-namespace "mathml") . "mi")
(,(find-namespace "mathml") . "mo")
(,(find-namespace "mathml") . "mn")
(,(find-namespace "mathml") . "ms")
(,(find-namespace "mathml") . "mtext")
(,(find-namespace "mathml") . "annotation-xml")
(,(find-namespace "svg") . "foreignObject")
(,(find-namespace "svg") . "desc")
(,(find-namespace "svg") . "title")))
(defglobal +formatting-elements+
`((,(find-namespace "html") . "a")
(,(find-namespace "html") . "b")
(,(find-namespace "html") . "big")
(,(find-namespace "html") . "code")
(,(find-namespace "html") . "em")
(,(find-namespace "html") . "font")
(,(find-namespace "html") . "i")
(,(find-namespace "html") . "nobr")
(,(find-namespace "html") . "s")
(,(find-namespace "html") . "small")
(,(find-namespace "html") . "strike")
(,(find-namespace "html") . "strong")
(,(find-namespace "html") . "tt")
(,(find-namespace "html") . "u")))
(defglobal +special-elements+
`((,(find-namespace "html") . "address")
(,(find-namespace "html") . "applet")
(,(find-namespace "html") . "area")
(,(find-namespace "html") . "article")
(,(find-namespace "html") . "aside")
(,(find-namespace "html") . "base")
(,(find-namespace "html") . "basefont")
(,(find-namespace "html") . "bgsound")
(,(find-namespace "html") . "blockquote")
(,(find-namespace "html") . "body")
(,(find-namespace "html") . "br")
(,(find-namespace "html") . "button")
(,(find-namespace "html") . "caption")
(,(find-namespace "html") . "center")
(,(find-namespace "html") . "col")
(,(find-namespace "html") . "colgroup")
(,(find-namespace "html") . "command")
(,(find-namespace "html") . "dd")
(,(find-namespace "html") . "details")
(,(find-namespace "html") . "dir")
(,(find-namespace "html") . "div")
(,(find-namespace "html") . "dl")
(,(find-namespace "html") . "dt")
(,(find-namespace "html") . "embed")
(,(find-namespace "html") . "fieldset")
(,(find-namespace "html") . "figure")
(,(find-namespace "html") . "footer")
(,(find-namespace "html") . "form")
(,(find-namespace "html") . "frame")
(,(find-namespace "html") . "frameset")
(,(find-namespace "html") . "h1")
(,(find-namespace "html") . "h2")
(,(find-namespace "html") . "h3")
(,(find-namespace "html") . "h4")
(,(find-namespace "html") . "h5")
(,(find-namespace "html") . "h6")
(,(find-namespace "html") . "head")
(,(find-namespace "html") . "header")
(,(find-namespace "html") . "hr")
(,(find-namespace "html") . "html")
(,(find-namespace "html") . "iframe")
;; Note that image is commented out in the spec as "this isn't an
;; element that can end up on the stack, so it doesn't matter,"
(,(find-namespace "html") . "image")
(,(find-namespace "html") . "img")
(,(find-namespace "html") . "input")
(,(find-namespace "html") . "isindex")
(,(find-namespace "html") . "li")
(,(find-namespace "html") . "link")
(,(find-namespace "html") . "listing")
(,(find-namespace "html") . "marquee")
(,(find-namespace "html") . "menu")
(,(find-namespace "html") . "meta")
(,(find-namespace "html") . "nav")
(,(find-namespace "html") . "noembed")
(,(find-namespace "html") . "noframes")
(,(find-namespace "html") . "noscript")
(,(find-namespace "html") . "object")
(,(find-namespace "html") . "ol")
(,(find-namespace "html") . "p")
(,(find-namespace "html") . "param")
(,(find-namespace "html") . "plaintext")
(,(find-namespace "html") . "pre")
(,(find-namespace "html") . "script")
(,(find-namespace "html") . "section")
(,(find-namespace "html") . "select")
(,(find-namespace "html") . "style")
(,(find-namespace "html") . "table")
(,(find-namespace "html") . "tbody")
(,(find-namespace "html") . "td")
(,(find-namespace "html") . "textarea")
(,(find-namespace "html") . "tfoot")
(,(find-namespace "html") . "th")
(,(find-namespace "html") . "thead")
(,(find-namespace "html") . "title")
(,(find-namespace "html") . "tr")
(,(find-namespace "html") . "ul")
(,(find-namespace "html") . "wbr")
(,(find-namespace "html") . "xmp")
(,(find-namespace "svg") . "foreignObject")))
(defglobal +html-integration-point-elements+
`((,(find-namespace "mathml") . "annotation-xml")
(,(find-namespace "svg") . "foreignObject")
(,(find-namespace "svg") . "desc")
(,(find-namespace "svg") . "title")))
(defglobal +mathml-text-integration-point-elements+
`((,(find-namespace "mathml") . "mi")
(,(find-namespace "mathml") . "mo")
(,(find-namespace "mathml") . "mn")
(,(find-namespace "mathml") . "ms")
(,(find-namespace "mathml") . "mtext")))
(defconstant +eof+ '+eof+)
(defglobal +token-types+
'(:doctype 0
:characters 1
:space-characters 2
:star-ttag 3
:end-tag 4
:empty-tag 5
:comment 6
:parse-error 7))
(defglobal +tag-token-types+
'(:start-tag :end-tag :empty-tag))
(defglobal +space-characters+
'(#\Tab
#\Newline
#\u000C
#\Space
#\Return))
(defglobal +table-insert-mode-elements+
'("table"
"tbody"
"tfoot"
"thead"
"tr"))
(defglobal +ascii-lowercase+ "abcdefghijklmnopqrstuvwxyz")
(defglobal +ascii-uppercase+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
(defglobal +ascii-letters+ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
(defglobal +digits+ "0123456789")
(defglobal +hex-digits+ "0123456789abcdefABCDEF")
(defun ascii-letter-p (c)
(when (characterp c)
(let ((code (char-code c)))
(or (<= #.(char-code #\a) code #.(char-code #\z))
(<= #.(char-code #\A) code #.(char-code #\Z))))))
(defun ascii-upper-2-lower (string)
(let ((out (copy-seq string)))
(dotimes (i (length string))
(let ((p (position (char out i) +ascii-uppercase+)))
(when p
(setf (char out i) (char +ascii-lowercase+ p)))))
out))
(defglobal +replacement-characters+
'(#x0 #\uFFFD
#x0d #\u000D
#x80 #\u20AC
#x81 #\u0081
#x81 #\u0081
#x82 #\u201A
#x83 #\u0192
#x84 #\u201E
#x85 #\u2026
#x86 #\u2020
#x87 #\u2021
#x88 #\u02C6
#x89 #\u2030
#x8A #\u0160
#x8B #\u2039
#x8C #\u0152
#x8D #\u008D
#x8E #\u017D
#x8F #\u008F
#x90 #\u0090
#x91 #\u2018
#x92 #\u2019
#x93 #\u201C
#x94 #\u201D
#x95 #\u2022
#x96 #\u2013
#x97 #\u2014
#x98 #\u02DC
#x99 #\u2122
#x9A #\u0161
#x9B #\u203A
#x9C #\u0153
#x9D #\u009D
#x9E #\u017E
#x9F #\u0178))
(defglobal +cdata-elements+
'("title"
"textarea"))
(defglobal +rcdata-elements+
'("style"
"script"
"xmp"
"iframe"
"noembed"
"noframes"
"noscript"))
(defglobal +html-integration-point-elements+
`((,(find-namespace "mathml") . "annotation-xml")
(,(find-namespace "svg") . "foreignObject")
(,(find-namespace "svg") . "desc")
(,(find-namespace "svg") . "title")))
(defglobal +mathml-text-integration-point-elements+
`((,(find-namespace "mathml") . "mi")
(,(find-namespace "mathml") . "mo")
(,(find-namespace "mathml") . "mn")
(,(find-namespace "mathml") . "ms")
(,(find-namespace "mathml") . "mtext")))
(defun make-hash-lookup (replacements)
(let ((rhash (make-hash-table :test #'equalp)))
(loop for (from to) in replacements
do (setf (gethash from rhash) to))))
(defglobal +quirks-mode-doctypes-regexp+
(cl-ppcre:create-scanner
'(:sequence :start-anchor
(:alternation
"+//silmaril//dtd html pro v0r11 19970101//"
"-//advasoft ltd//dtd html 3.0 aswedit + extensions//"
"-//as//dtd html 3.0 aswedit + extensions//"
"-//ietf//dtd html 2.0 level 1//"
"-//ietf//dtd html 2.0 level 2//"
"-//ietf//dtd html 2.0 strict level 1//"
"-//ietf//dtd html 2.0 strict level 2//"
"-//ietf//dtd html 2.0 strict//"
"-//ietf//dtd html 2.0//"
"-//ietf//dtd html 2.1e//"
"-//ietf//dtd html 3.0//"
"-//ietf//dtd html 3.2 final//"
"-//ietf//dtd html 3.2//"
"-//ietf//dtd html 3//"
"-//ietf//dtd html level 0//"
"-//ietf//dtd html level 1//"
"-//ietf//dtd html level 2//"
"-//ietf//dtd html level 3//"
"-//ietf//dtd html strict level 0//"
"-//ietf//dtd html strict level 1//"
"-//ietf//dtd html strict level 2//"
"-//ietf//dtd html strict level 3//"
"-//ietf//dtd html strict//"
"-//ietf//dtd html//"
"-//metrius//dtd metrius presentational//"
"-//microsoft//dtd internet explorer 2.0 html strict//"
"-//microsoft//dtd internet explorer 2.0 html//"
"-//microsoft//dtd internet explorer 2.0 tables//"
"-//microsoft//dtd internet explorer 3.0 html strict//"
"-//microsoft//dtd internet explorer 3.0 html//"
"-//microsoft//dtd internet explorer 3.0 tables//"
"-//netscape comm. corp.//dtd html//"
"-//netscape comm. corp.//dtd strict html//"
"-//o'reilly and associates//dtd html 2.0//"
"-//o'reilly and associates//dtd html extended 1.0//"
"-//o'reilly and associates//dtd html extended relaxed 1.0//"
"-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//"
"-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//"
"-//spyglass//dtd html 2.0 extended//"
"-//sq//dtd html 2.0 hotmetal + extensions//"
"-//sun microsystems corp.//dtd hotjava html//"
"-//sun microsystems corp.//dtd hotjava strict html//"
"-//w3c//dtd html 3 1995-03-24//"
"-//w3c//dtd html 3.2 draft//"
"-//w3c//dtd html 3.2 final//"
"-//w3c//dtd html 3.2//"
"-//w3c//dtd html 3.2s draft//"
"-//w3c//dtd html 4.0 frameset//"
"-//w3c//dtd html 4.0 transitional//"
"-//w3c//dtd html experimental 19960712//"
"-//w3c//dtd html experimental 970421//"
"-//w3c//dtd w3 html//"
"-//w3o//dtd w3 html 3.0//"
"-//webtechs//dtd mozilla html 2.0//"
"-//webtechs//dtd mozilla html//"))))
(defglobal +heading-elements+
'("h1"
"h2"
"h3"
"h4"
"h5"
"h6"))
| 12,467
|
Common Lisp
|
.lisp
| 333
| 32.585586
| 86
| 0.589557
|
rotatef/cl-html5-parser
| 55
| 14
| 11
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
c9c8a279dc922b2eef94e436d978267f66d622543cb93c286d28d31dedd53f4e
| 3,084
|
[
-1
] |
3,085
|
tree-help.lisp
|
rotatef_cl-html5-parser/tree-help.lisp
|
;;;; HTML5 parser for Common Lisp
;;;;
;;;; Copyright (C) 2012 Thomas Bakketun <thomas.bakketun@copyleft.no>
;;;; Copyright (C) 2012 Asgeir Bj√∏rlykke <asgeir@copyleft.no>
;;;; Copyright (C) 2012 Mathias Hellevang
;;;; Copyright (C) 2012 Stian Sletner <stian@copyleft.no>
;;;;
;;;; This library is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Lesser General Public License as published
;;;; by the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This library 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 library. If not, see <http://www.gnu.org/licenses/>.
(in-package :html5-parser)
(defmacro pop-end (place)
"Pop from the end of list"
(let ((old-list (gensym)))
`(let ((,old-list ,place))
(prog1 (car (last ,old-list))
(setf ,place (butlast ,old-list))))))
(defmacro push-end (object place)
"Push to the end of list"
`(progn
;(format t "~&push ~S to ~S" ',object ',place)
(setf ,place (append ,place (list ,object)))))
(defvar *parser*)
(defun document* ()
(slot-value *parser* 'document))
(defun node-clone* (node)
(ecase (node-type node)
(:document
(make-document))
(:document-fragment
(make-fragment (document*)))
(:document-type
(make-doctype (document*)
(node-name node)
(node-public-id node)
(node-system-id node)))
(:comment
(make-comment (document*) (node-value node)))
(:text
(make-text-node (document*) (node-value node)))
(:element
(let ((clone (make-element (document*) (node-name node) (node-namespace node))))
(element-map-attributes*
(lambda (name namespace value)
(setf (element-attribute clone name namespace) value))
node)
clone))))
(defun node-name-tuple (node)
(cons (or (node-namespace node)
(find-namespace "html"))
(node-name node)))
(defun node-name-tuple-values (node)
(values (or (node-namespace node)
(find-namespace "html"))
(node-name node)))
(defun node-has-content (node)
(not (null (node-first-child node))))
(defun node-attributes= (node1 node2)
(labels ((has-all-attributes-of (node1 node2)
(element-map-attributes*
(lambda (name namespace value)
(unless (equal value
(element-attribute node2 name namespace))
(return-from has-all-attributes-of nil)))
node1)
t))
(and (has-all-attributes-of node1 node2)
(has-all-attributes-of node2 node1))))
(defun node-append-child* (node child)
(let ((last-child (node-last-child node)))
(if (and (eql :text (node-type child))
last-child
(eql :text (node-type last-child)))
(nconcatf (node-value last-child)
(node-value child))
(node-append-child node child))))
(defun node-insert-before* (node child insert-before)
(when (eql :text (node-type child))
(let ((prev-child (node-previous-sibling insert-before)))
(when (and prev-child
(eql :text (node-type prev-child)))
(node-remove-child node prev-child)
(setf child (make-text-node
(document*)
(concatenate 'string
(node-value prev-child)
(node-value child)))))))
(node-insert-before node child insert-before))
(defun node-reparent-children (node new-parent)
(element-map-children (lambda (child)
(node-append-child new-parent child))
node))
(defun node-insert-text (node data &optional insert-before)
(if insert-before
(node-insert-before* node (make-text-node (document*) data) insert-before)
(node-append-child* node (make-text-node (document*) data))))
(defun last-open-element ()
(with-slots (open-elements) *parser*
(car (last open-elements))))
(defun create-element (token)
"Create an element but don't insert it anywhere"
(with-slots (html-namespace) *parser*
(let ((element (make-element (document*)
(getf token :name)
(or (getf token :namespace)
html-namespace))))
(loop for (name . value) in (getf token :data)
do (if (consp name)
(setf (element-attribute element (second name) (third name)) value)
(setf (element-attribute element name) value)))
element)))
(defun insert-root (token)
(with-slots (open-elements) *parser*
(let ((element (create-element token)))
(assert element)
(push-end element open-elements)
(node-append-child (document*) element))))
(defun insert-doctype (token)
(node-append-child (document*)
(make-doctype (document*)
(getf token :name)
(getf token :public-id)
(getf token :system-id))))
(defun insert-comment (token &optional parent)
(with-slots (open-elements) *parser*
(unless parent
(setf parent (car (last open-elements))))
(node-append-child parent (make-comment (document*) (getf token :data)))))
(defun insert-element-normal (token)
(with-slots (open-elements) *parser*
(let ((element (create-element token)))
(node-append-child (last-open-element) element)
(push-end element open-elements)
element)))
(defun insert-element-table (token)
(with-slots (open-elements) *parser*
(if (not (member (node-name (last-open-element))
+table-insert-mode-elements+ :test #'string=))
(insert-element-normal token)
(let ((element (create-element token)))
;; We should be in the InTable mode. This means we want to do
;; special magic element rearranging
(multiple-value-bind (parent insert-before)
(get-table-misnested-nodeposition)
(if (not insert-before)
(node-append-child* parent element)
(node-insert-before* parent element insert-before))
(push-end element open-elements))
element))))
(defun insert-element (token)
(with-slots (insert-from-table) *parser*
(if insert-from-table
(insert-element-table token)
(insert-element-normal token))))
(defun parser-insert-text (data &optional parent)
"Insert text data."
(with-slots (open-elements insert-from-table) *parser*
(unless parent
(setf parent (car (last open-elements))))
(cond ((or (not insert-from-table)
(and insert-from-table
(not (member (node-name (last-open-element))
+table-insert-mode-elements+ :test #'string=))))
(node-insert-text parent data))
(t
;; We should be in the InTable mode. This means we want to do
;; special magic element rearranging
(multiple-value-bind (parent insert-before)
(get-table-misnested-nodeposition)
(node-insert-text parent data insert-before))))))
(defun get-table-misnested-nodeposition ()
"Get the foster parent element, and sibling to insert before
(or None) when inserting a misnested table node"
(with-slots (open-elements) *parser*
;; The foster parent element is the one which comes before the most
;; recently opened table element
(let ((last-table (find "table" open-elements :key #'node-name :test #'string= :from-end t))
(foster-parent nil)
(insert-before nil))
(cond (last-table
;; XXX - we should really check that this parent is actually a
;; node here
(if (node-parent last-table)
(setf foster-parent (node-parent last-table)
insert-before last-table)
(setf foster-parent (elt open-elements (1- (position last-table open-elements))))))
(t
(setf foster-parent (first open-elements))))
(values foster-parent insert-before))))
(defun generate-implied-end-tags (&optional exclude)
(with-slots (open-elements) *parser*
(let ((name (node-name (last-open-element))))
;; XXX td, th and tr are not actually needed
(when (and (member name '("dd" "dt" "li" "option" "optgroup" "p" "rp" "rt") :test #'string=)
(not (equal name exclude)))
(pop-end open-elements)
;; XXX This is not entirely what the specification says. We should
;; investigate it more closely.
(generate-implied-end-tags exclude)))))
(defun reconstruct-active-formatting-elements ()
;; Within this algorithm the order of steps described in the
;; specification is not quite the same as the order of steps in the
;; code. It should still do the same though.
(with-slots (active-formatting-elements open-elements) *parser*
;; Step 1: stop the algorithm when there's nothing to do.
(unless active-formatting-elements
(return-from reconstruct-active-formatting-elements))
;; Step 2 and step 3: we start with the last element. So i is -1.
(let* ((i (1- (length active-formatting-elements)))
(entry (elt active-formatting-elements i)))
(when (or (eql entry :marker)
(member entry open-elements))
(return-from reconstruct-active-formatting-elements))
;; Step 6
(loop while (and (not (eql entry :marker))
(not (member entry open-elements))) do
(when (zerop i)
;; This will be reset to 0 below
(setf i -1)
(return))
(decf i)
;; Step 5: let entry be one earlier in the list.
(setf entry (elt active-formatting-elements i)))
(loop
;; Step 7
(incf i)
;; Step 8
(setf entry (elt active-formatting-elements i))
;; Step 9
(let* ((element (insert-element (list :type :start-tag
:name (node-name entry)
:namespace (node-namespace entry)))))
(element-map-attributes* (lambda (name namespace value)
(setf (element-attribute element name namespace) value))
entry)
;; Step 10
(setf (elt active-formatting-elements i) element)
;; Step 11
(when (eql element (car (last active-formatting-elements)))
(return)))))))
(defun clear-active-formatting-elements ()
(with-slots (active-formatting-elements) *parser*
(loop for entry = (pop-end active-formatting-elements)
while (and active-formatting-elements
(not (eql entry :marker))))))
(defun element-in-active-formatting-elements (name)
"Check if an element exists between the end of the active
formatting elements and the last marker. If it does, return it, else
return false"
(with-slots (active-formatting-elements) *parser*
(loop for item in (reverse active-formatting-elements) do
;; Check for Marker first because if it's a Marker it doesn't have a
;; name attribute.
(when (eql item :marker)
(return nil))
(when (string= (node-name item) name)
(return item)))))
(defun scope-tree ()
(load-time-value
(flet ((unflatten (alist)
"Turn an alist into a tree."
(let ((alist2
(mapcar #'list
(remove-duplicates (mapcar #'car alist)
:test #'equal))))
(loop for (key . value) in alist
do (push value (cdr (assoc key alist2
:test #'equal))))
;; Put the XHTML ns first.
(sort alist2 #'<
:key (lambda (pair)
(position (car pair)
'("http://www.w3.org/1999/xhtml"
"http://www.w3.org/2000/svg"
"http://www.w3.org/1998/Math/MathML")
:test #'string=))))))
(let ((html (find-namespace "html")))
`((nil . ,(unflatten +scoping-elements+))
("button" . ,(unflatten
`(,@+scoping-elements+
(,html . "button"))))
("list" . ,(unflatten
`(,@+scoping-elements+
(,html . "ol")
(,html . "ul"))))
("table" . ((,html "html" "table")))
("select" . ((,html "optgroup" "option"))))))))
(defun element-in-scope (target &optional variant)
(let ((list-elements
(cdr (assoc variant (scope-tree) :test #'equal)))
(invert (equal "select" variant)))
(dolist (node (reverse (slot-value *parser* 'open-elements)))
(when (or (and (stringp target)
(string= (node-name node) target))
(eql node target))
(return-from element-in-scope t))
(multiple-value-bind (ns name)
(node-name-tuple-values node)
(let ((found (member name (cdr (assoc ns list-elements :test #'string=))
:test #'string=)))
(when invert
(setf found (not found)))
(when found
(return-from element-in-scope nil)))))
(error "We should never reach this point")))
| 14,053
|
Common Lisp
|
.lisp
| 314
| 34.143312
| 101
| 0.578125
|
rotatef/cl-html5-parser
| 55
| 14
| 11
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
895c3d4e814ba2cd5d1b2a3f2041e83e8a6655708bd2631556512069eef9b612
| 3,085
|
[
-1
] |
3,086
|
packages.lisp
|
rotatef_cl-html5-parser/packages.lisp
|
;;;; HTML5 parser for Common Lisp
;;;;
;;;; Copyright (C) 2012 Thomas Bakketun <thomas.bakketun@copyleft.no>
;;;; Copyright (C) 2012 Asgeir Bj√∏rlykke <asgeir@copyleft.no>
;;;; Copyright (C) 2012 Mathias Hellevang
;;;; Copyright (C) 2012 Stian Sletner <stian@copyleft.no>
;;;;
;;;; This library is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Lesser General Public License as published
;;;; by the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This library 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 library. If not, see <http://www.gnu.org/licenses/>.
(defpackage :html5-constants
(:use
:common-lisp)
(:export
#:+namespaces+
#:find-namespace
#:find-prefix
#:+scoping-elements+
#:+formatting-elements+
#:+special-elements+
#:+html-integration-point-elements+
#:+mathml-text-integration-point-elements+
#:+eof+
#:+token-types+
#:+tag-token-types+
#:+space-characters+
#:+table-insert-mode-elements+
#:+ascii-lowercase+
#:+ascii-uppercase+
#:+ascii-letters+
#:ascii-letter-p
#:+digits+
#:+hex-digits+
#:ascii-upper-2-lower
#:+replacement-characters+
#:+cdata-elements+
#:+rcdata-elements+
#:+html-integration-point-elements+
#:+mathml-text-integration-point-elements+
#:+quirks-mode-doctypes-regexp+
#:ascii-upper-2-lower
#:+replacement-characters+
#:+heading-elements+))
(defpackage :html5-parser
(:use
:common-lisp
:html5-constants
:cl-ppcre)
(:export
#:parse-html5
#:parse-html5-fragment
#:transform-html5-dom
#:xml-escape-name
#:xml-unescape-name
;; A simple DOM
#:make-document
#:make-fragment
#:make-doctype
#:make-comment
#:make-element
#:make-text-node
#:node-type
#:node-name
#:node-namespace
#:node-value
#:node-public-id
#:node-system-id
#:element-attribute
#:node-append-child
#:node-insert-before
#:node-remove-child
#:node-parent
#:node-first-child
#:node-last-child
#:node-previous-sibling
#:node-next-sibling
#:element-map-attributes
#:element-map-attributes*
#:element-map-children))
| 2,519
|
Common Lisp
|
.lisp
| 88
| 25.306818
| 78
| 0.688119
|
rotatef/cl-html5-parser
| 55
| 14
| 11
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
53d6fce606d18ff24f5df3b40988987f894a2111ff6d46c927953e9868534d13
| 3,086
|
[
-1
] |
3,087
|
toxml.lisp
|
rotatef_cl-html5-parser/toxml.lisp
|
;;;; HTML5 parser for Common Lisp
;;;;
;;;; Copyright (C) 2017 Thomas Bakketun <thomas.bakketun@copyleft.no>
;;;;
;;;; This library is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Lesser General Public License as published
;;;; by the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This library 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 library. If not, see <http://www.gnu.org/licenses/>.
(in-package #:html5-parser)
(defun xml-escape-name (name)
"Escapes a node name (element, attribute, doctype) by replacing any
character not valid in XML name by Uxxxxxx, where x is the code point
as six hex digits. This encoding is reversable, since the HTML parser
down cases all characters in names.
See: https://www.w3.org/TR/html5/syntax.html#coercing-an-html-dom-into-an-infoset"
(if (and (xml-name-start-char-p (char name 0))
(every #'xml-name-char-p name))
name
(with-output-to-string (out)
(loop for first = t then nil
for c across name do
(if (if first
(xml-name-start-char-p c)
(xml-name-char-p c))
(princ c out)
(format out "U~:@(~6,'0X~)" (char-code c)))))))
(defun xml-unescape-name (name)
"Reverert escaping done by xml-unescape-name."
(cl-ppcre:regex-replace-all
"U[0-9A-F]{6}"
name
(lambda (u)
(string (code-char (parse-integer u :start 1 :radix 16))))
:simple-calls t))
(defun xml-name-start-char-p (c)
(or (char<= #\a c #\z)
(char= #\_ c)
(char<= #\A c #\Z)
(char<= (code-char #xC0) c (code-char #xD6))
(char<= (code-char #xD8) c (code-char #xF6))
(char<= (code-char #xF8) c (code-char #x2FF))
(char<= (code-char #x370) c (code-char #x37D))
(char<= (code-char #x37F) c (code-char #x1FFF))
(char<= (code-char #x200C) c (code-char #x200D))
(char<= (code-char #x2070) c (code-char #x218F))
(char<= (code-char #x2C00) c (code-char #x2FEF))
(char<= (code-char #x3001) c (code-char #xD7FF))
(char<= (code-char #xF900) c (code-char #xFDCF))
(char<= (code-char #xFDF0) c (code-char #xFFFD))
(char<= (code-char #x10000) c (code-char #xEFFFF))))
(defun xml-name-char-p (c)
(or (xml-name-start-char-p c)
(char= #\- c)
(char= #\. c)
(char<= #\0 c #\9)
(char= (code-char #xB7) c)
(char<= (code-char #x0300) c (code-char #x036F))
(char<= (code-char #x203F) c (code-char #x2040))))
| 2,896
|
Common Lisp
|
.lisp
| 66
| 38.212121
| 82
| 0.616667
|
rotatef/cl-html5-parser
| 55
| 14
| 11
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
1693201dab07147a481958dfba102263f97707330c2fdd619471b16a6da99ef1
| 3,087
|
[
-1
] |
3,088
|
cxml-dom.lisp
|
rotatef_cl-html5-parser/cxml/cxml-dom.lisp
|
;;;; HTML5 parser for Common Lisp
;;;;
;;;; Copyright (C) 2014 Joe Taylor <joekarma@gmail.com>
;;;; Copyright (C) 2012 Thomas Bakketun <thomas.bakketun@copyleft.no>
;;;; Copyright (C) 2012 Asgeir Bj√∏rlykke <asgeir@copyleft.no>
;;;; Copyright (C) 2012 Mathias Hellevang
;;;; Copyright (C) 2012 Stian Sletner <stian@copyleft.no>
;;;;
;;;; This library is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Lesser General Public License as published
;;;; by the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This library 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 library. If not, see <http://www.gnu.org/licenses/>.
(in-package #:html5-parser)
(defmethod transform-html5-dom ((to-type (eql :cxml)) node &key)
(let ((document-type)
(document)
(document-fragment))
(labels ((walk (node &optional parent xlink-defined)
(ecase (node-type node)
(:document-type
(setf document-type (dom:create-document-type 'rune-dom:implementation
(xml-escape-name (node-name node))
(node-public-id node)
(node-system-id node))))
(:document
(element-map-children #'walk node))
(:document-fragment
(setf document (dom:create-document 'rune-dom:implementation nil nil nil))
(setf document-fragment (dom:create-document-fragment document))
(element-map-children (lambda (c) (walk c document-fragment xlink-defined)) node))
(:element
(let ((element
(if document
(dom:create-element-ns document (node-namespace node) (xml-escape-name (node-name node)))
(dom:document-element
(setf document (dom:create-document 'rune-dom:implementation
(node-namespace node)
(xml-escape-name (node-name node))
document-type))))))
(unless (and parent
(equal (node-namespace node) (dom:namespace-uri parent)))
(dom:set-attribute-ns element (html5-constants:find-namespace "xmlns")
"xmlns" (node-namespace node)))
(element-map-attributes (lambda (name namespace value)
(when (and (not xlink-defined)
(equal namespace (html5-constants:find-namespace "xlink")))
(dom:set-attribute element "xmlns:xlink" (html5-constants:find-namespace "xlink"))
(setf xlink-defined t))
(if namespace
(dom:set-attribute-ns element namespace name value)
(dom:set-attribute element (xml-escape-name name) value)))
node)
(element-map-children (lambda (c) (walk c element xlink-defined)) node)
(dom:append-child (or parent document) element)))
(:text
(dom:append-child (or parent document)
(dom:create-text-node document (node-value node))))
(:comment
(dom:append-child (or parent document)
(dom:create-comment document (node-value node)))))))
(walk node))
(or document-fragment document)))
| 4,377
|
Common Lisp
|
.lisp
| 70
| 40.871429
| 130
| 0.5
|
rotatef/cl-html5-parser
| 55
| 14
| 11
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
a12e8405e198ad8d4549d3fa196cae3437efda66139b64a94f3caf512342477d
| 3,088
|
[
-1
] |
3,089
|
test-parser.lisp
|
rotatef_cl-html5-parser/tests/test-parser.lisp
|
;;;; HTML5 parser for Common Lisp
;;;;
;;;; Copyright (C) 2012 Thomas Bakketun <thomas.bakketun@copyleft.no>
;;;; Copyright (C) 2012 Asgeir Bj√∏rlykke <asgeir@copyleft.no>
;;;; Copyright (C) 2012 Mathias Hellevang
;;;; Copyright (C) 2012 Stian Sletner <stian@copyleft.no>
;;;;
;;;; This library is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Lesser General Public License as published
;;;; by the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This library 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 library. If not, see <http://www.gnu.org/licenses/>.
(in-package :html5-parser-tests)
;; Printing for tests
(defun print-node (node stream)
(ecase (node-type node)
(:document-type
(format stream "<!DOCTYPE ~A" (node-name node))
(when (or (node-public-id node)
(node-system-id node))
(format stream " \"~A\" \"~A\""
(or (node-public-id node) "")
(or (node-system-id node) "")))
(format stream ">"))
(:comment
(format stream "<!-- ~A -->" (node-value node)))
(:element
(if (and (node-namespace node)
(string/= (node-namespace node)
(html5-constants::find-namespace "html")))
(format stream "<~A ~A>"
(html5-constants::find-prefix (node-namespace node))
(node-name node))
(format stream "<~A>" (node-name node))))
(:text
(format stream "\"~A\"" (node-value node)))))
(defun print-tree (node &key (stream *standard-output*) (indent 0))
(ecase (node-type node)
((:document :document-fragment)
(element-map-children (lambda (child)
(print-tree child
:stream stream
:indent (+ indent 2)))
node))
(:element
(format stream "~&|~vT" indent)
(print-node node stream)
(incf indent 2)
(let ((attributes))
(element-map-attributes* (lambda (name namespace value)
(push (cons (cons name namespace) value) attributes))
node)
(when attributes
(loop for (name . value) in (sort attributes #'string<
:key (lambda (attr)
(if (consp (car attr))
(caar attr)
(car attr))))
do
(format stream "~&|~vT" indent)
(if (cdr name)
(format stream "~A ~A" (html5-constants:find-prefix (cdr name)) (car name))
(format stream "~A" (car name)))
(format stream "=\"~A\"" value)))
(element-map-children (lambda (child)
(print-tree child
:stream stream
:indent indent))
node)))
((:text :comment :document-type)
(format stream "~&|~vT" indent)
(print-node node stream)))
node)
(defparameter *parser-tests-to-skip*
())
(defun do-parser-test (&key test-name data errors document document-fragment)
(with-simple-restart (skip "Skip test ~A ~A"
test-name
data)
(format t "~&Test ~A: ~A~%" test-name data)
(setf document (string-right-trim '(#\Newline) document))
(when (member data *parser-tests-to-skip* :test #'string=)
(format t " skipped")
(return-from do-parser-test))
(multiple-value-bind (result-document got-errors)
(if document-fragment
(parse-html5-fragment data :container document-fragment)
(parse-html5 data))
(let ((result (with-output-to-string (out)
(print-tree result-document :stream out))))
(unless (string= document result)
(error "Input:~%~A~%Got:~%~A~%Expected:~%~A" data result document))
(setf errors (split-sequence:split-sequence #\Newline errors
:remove-empty-subseqs t))
(when (and errors
(/= (length errors) (length got-errors)))
(warn "Errors mismatch~&Input:~%~A~%Got:~%~{~&~A~}~%Expected:~%~{~&~A~}"
data got-errors errors)))
result-document)))
(defun test-parser ()
(let ((files (html5lib-test-files "tree-construction")))
(dolist (file files)
(let ((test-name (pathname-name file))
(tests (parse-test-data file)))
(dolist (test tests)
(apply #'do-parser-test :test-name test-name test))))))
(in-root-suite)
(defsuite parser-tests)
(in-suite parser-tests)
(deftest test-parse-content-attr ()
(is (eql nil (html5-parser::parse-content-attr "garble")))
(is (eql nil (html5-parser::parse-content-attr "charset")))
(is (string= "utf-8" (html5-parser::parse-content-attr "charset=utf-8")))
(is (string= "utf-8" (html5-parser::parse-content-attr "charset = utf-8")))
(is (string= "utf-8" (html5-parser::parse-content-attr " charset = utf-8 ")))
(is (string= " utf-8 " (html5-parser::parse-content-attr " charset =' utf-8 '")))
(is (eql nil (html5-parser::parse-content-attr " charset =\"utf-8 '")))
(is (string= "utf-8" (html5-parser::parse-content-attr " charset =\"utf-8\"")))
(is (string= "utf-8" (html5-parser::parse-content-attr " charset =\"utf-8\" "))))
| 5,944
|
Common Lisp
|
.lisp
| 126
| 36.02381
| 94
| 0.550982
|
rotatef/cl-html5-parser
| 55
| 14
| 11
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
fe5676c0fa4110b307ea65e5b2101fd1ab18a511f987fe8b8697eb08cae1e2b4
| 3,089
|
[
-1
] |
3,090
|
run-tests.lisp
|
rotatef_cl-html5-parser/tests/run-tests.lisp
|
;;;; HTML5 parser for Common Lisp
;;;;
;;;; Copyright (C) 2012 Thomas Bakketun <thomas.bakketun@copyleft.no>
;;;; Copyright (C) 2012 Asgeir Bj√∏rlykke <asgeir@copyleft.no>
;;;; Copyright (C) 2012 Mathias Hellevang
;;;; Copyright (C) 2012 Stian Sletner <stian@copyleft.no>
;;;;
;;;; This library is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Lesser General Public License as published
;;;; by the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This library 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 library. If not, see <http://www.gnu.org/licenses/>.
(in-package :html5-parser-tests)
(defun run-html5-parser-tests ()
(values (input-stream-tests)
(test-tokenizer)
(tree-builder-tests)
(test-parser)))
| 1,152
|
Common Lisp
|
.lisp
| 25
| 43.72
| 78
| 0.704889
|
rotatef/cl-html5-parser
| 55
| 14
| 11
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
cb01533b1b6818bda4b7feb7787375161829f1c1e76bc9fbe026dd0a17c4d726
| 3,090
|
[
-1
] |
3,091
|
support.lisp
|
rotatef_cl-html5-parser/tests/support.lisp
|
;;;; HTML5 parser for Common Lisp
;;;;
;;;; Copyright (C) 2017 Thomas Bakketun <thomas.bakketun@copyleft.no>
;;;; Copyright (C) 2012 Asgeir Bj√∏rlykke <asgeir@copyleft.no>
;;;; Copyright (C) 2012 Mathias Hellevang
;;;; Copyright (C) 2012 Stian Sletner <stian@copyleft.no>
;;;;
;;;; This library is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Lesser General Public License as published
;;;; by the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This library 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 library. If not, see <http://www.gnu.org/licenses/>.
(in-package :html5-parser-tests)
(defun html5lib-test-files (subdirectory &key (type "dat"))
(directory (merge-pathnames (make-pathname :directory `(:relative ,subdirectory)
:name :wild
:type type)
(asdf:system-relative-pathname :cl-html5-parser-tests "testdata/"))))
(defun parse-test-part (in)
(let ((line (read-line in nil)))
(when line
(assert (char= #\# (char line 0)))
(let ((name (intern (string-upcase (subseq line 1)) :keyword))
(value (with-output-to-string (out)
(loop for next-char = (peek-char nil in nil)
while (and next-char (char/= #\# next-char))
do (write-line (read-line in) out)))))
(list name (subseq value 0 (max 0 (1- (length value)))))))))
(defun parse-one-test (in)
(loop for part = (parse-test-part in)
while part
append part
until (eql (car part) :document)))
(defun parse-test-data (filename)
(with-open-file (in filename)
(loop for test = (parse-one-test in)
while test
collect test)))
| 2,165
|
Common Lisp
|
.lisp
| 45
| 40.866667
| 99
| 0.624231
|
rotatef/cl-html5-parser
| 55
| 14
| 11
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
af4c28911b53cb76b6fe882ca7a1e9d7df039ffcc96355ca58b034eb413a2ba9
| 3,091
|
[
-1
] |
3,092
|
test-tree-builder.lisp
|
rotatef_cl-html5-parser/tests/test-tree-builder.lisp
|
;;;; HTML5 parser for Common Lisp
;;;;
;;;; Copyright (C) 2012 Thomas Bakketun <thomas.bakketun@copyleft.no>
;;;; Copyright (C) 2012 Asgeir Bj√∏rlykke <asgeir@copyleft.no>
;;;; Copyright (C) 2012 Mathias Hellevang
;;;; Copyright (C) 2012 Stian Sletner <stian@copyleft.no>
;;;;
;;;; This library is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Lesser General Public License as published
;;;; by the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This library 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 library. If not, see <http://www.gnu.org/licenses/>.
(in-package :html5-parser-tests)
(in-root-suite)
(defsuite tree-builder-tests)
(in-suite tree-builder-tests)
(deftest test-make-document ()
(is (eq :document (node-type (make-document)))))
(deftest test-append-child ()
(let* ((doc (make-document))
(child (make-element doc "test" nil)))
(node-append-child doc child)
(element-map-children (lambda (kid)
(is (eq kid child)))
doc)))
(deftest test-reappend-child ()
(let* ((doc (make-document))
(parent1 (make-element doc "parent1" nil))
(parent2 (make-element doc "parent2" nil))
(child (make-element doc "child" nil)))
(node-append-child parent1 child)
(is (eq parent1 (node-parent child)))
(node-append-child parent2 child)
(is (eq parent2 (node-parent child)))
(element-map-children (lambda (kid)
(error "parent1 should not have children now ~S" kid))
parent1)))
(deftest test-navigate ()
(let* ((doc (make-document))
(parent (make-element doc "parent" nil))
(child1 (make-element doc "child1" nil))
(child2 (make-element doc "child2" nil))
(child3 (make-element doc "child3" nil))
(child4 (make-element doc "child4" nil)))
(node-append-child parent child1)
(node-append-child parent child2)
(node-append-child parent child3)
(node-append-child parent child4)
(is (eq child1 (node-first-child parent)))
(is (eq child4 (node-last-child parent)))
(is (eq child2 (node-next-sibling child1)))
(is (eq nil (node-next-sibling child4)))
(is (eq child1 (node-previous-sibling child2)))
(is (eq nil (node-previous-sibling child1)))))
(deftest test-remove-child ()
(let* ((doc (make-document))
(parent (make-element doc "parent" nil))
(child1 (make-element doc "child1" nil))
(child2 (make-element doc "child2" nil))
(child3 (make-element doc "child3" nil))
(child4 (make-element doc "child4" nil)))
(node-append-child parent child1)
(node-append-child parent child2)
(node-append-child parent child3)
(node-append-child parent child4)
(node-remove-child parent child2)
(is (eq child3 (node-next-sibling child1)))))
(deftest test-set-attribute ()
(let* ((doc (make-document))
(element (make-element doc "test" nil)))
(setf (element-attribute element "hello") "world")
(is (string= (element-attribute element "hello") "world"))))
(deftest test-append-text ()
(let* ((doc (make-document))
(parent (make-element doc "parent" nil)))
(html5-parser::node-append-child* parent (make-text-node doc "hello"))
(html5-parser::node-append-child* parent (make-text-node doc "world"))
(is (string= "helloworld" (node-value (node-first-child parent))))))
;; (deftest test-node-clone ()
;; (let* ((tree (make-tree))
;; (parent (tree-make-element tree "parent" nil))
;; (element (tree-make-element tree "test" nil)))
;; (node-append-child tree parent element)
;; (setf (node-attribute tree element "hello") "world")
;; (let ((clone (node-clone tree element)))
;; (is (null (node-parent tree clone)))
;; (is (string= (node-attribute tree clone "hello") "world")))))
| 4,293
|
Common Lisp
|
.lisp
| 94
| 40.510638
| 82
| 0.649475
|
rotatef/cl-html5-parser
| 55
| 14
| 11
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
67ff52f2dd39f4cf7ab5dc2c11eafbb9a81bc2bcbb0117ebcd216ac58007adaf
| 3,092
|
[
-1
] |
3,093
|
packages.lisp
|
rotatef_cl-html5-parser/tests/packages.lisp
|
;;;; HTML5 parser for Common Lisp
;;;;
;;;; Copyright (C) 2012 Thomas Bakketun <thomas.bakketun@copyleft.no>
;;;; Copyright (C) 2012 Asgeir Bj√∏rlykke <asgeir@copyleft.no>
;;;; Copyright (C) 2012 Mathias Hellevang
;;;; Copyright (C) 2012 Stian Sletner <stian@copyleft.no>
;;;;
;;;; This library is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Lesser General Public License as published
;;;; by the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This library 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 library. If not, see <http://www.gnu.org/licenses/>.
(defpackage :html5-parser-tests
(:use
:common-lisp
:html5-parser
:cl-ppcre
:stefil))
| 1,069
|
Common Lisp
|
.lisp
| 25
| 41.16
| 78
| 0.715244
|
rotatef/cl-html5-parser
| 55
| 14
| 11
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
1bdcf1d2ca7292df3dfee7fb5e25a4075dae58eac31c4004e12b02bcd3207546
| 3,093
|
[
-1
] |
3,094
|
test-inputstream.lisp
|
rotatef_cl-html5-parser/tests/test-inputstream.lisp
|
;;;; HTML5 parser for Common Lisp
;;;;
;;;; Copyright (C) 2012 Thomas Bakketun <thomas.bakketun@copyleft.no>
;;;; Copyright (C) 2012 Asgeir Bj√∏rlykke <asgeir@copyleft.no>
;;;; Copyright (C) 2012 Mathias Hellevang
;;;; Copyright (C) 2012 Stian Sletner <stian@copyleft.no>
;;;;
;;;; This library is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Lesser General Public License as published
;;;; by the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This library 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 library. If not, see <http://www.gnu.org/licenses/>.
(in-package :html5-parser-tests)
(in-root-suite)
(defsuite input-stream-tests)
(in-suite input-stream-tests)
(deftest test-read-char ()
(let ((stream (html5-parser::make-html-input-stream "hello")))
(is (eql #\h (html5-parser::html5-stream-char stream)))
(is (eql #\e (html5-parser::html5-stream-char stream)))))
(deftest test-unget ()
(let ((stream (html5-parser::make-html-input-stream "hei")))
(is (eql #\h (html5-parser::html5-stream-char stream)))
(is (eql #\e (html5-parser::html5-stream-char stream)))
(is (eql #\i (html5-parser::html5-stream-char stream)))
(is (eql html5-constants::+eof+ (html5-parser::html5-stream-char stream)))
(html5-parser::html5-stream-unget stream html5-constants::+eof+)
(html5-parser::html5-stream-unget stream #\i)
(is (eql #\i (html5-parser::html5-stream-char stream)))
(is (eql html5-constants::+eof+ (html5-parser::html5-stream-char stream)))))
(deftest test-chars-until ()
(let ((stream (html5-parser::make-html-input-stream "hello<--__-->a")))
(is (equal "hello" (html5-parser::html5-stream-chars-until stream "><")))
(is (eql #\< (html5-parser::html5-stream-char stream)))
(is (equal "--__-->" (html5-parser::html5-stream-chars-until stream "<>-_" t)))
(is (eql #\a (html5-parser::html5-stream-char stream)))))
(deftest test-chars-until-eof ()
(let ((stream (html5-parser::make-html-input-stream "hello")))
(is (equal "hello" (html5-parser::html5-stream-chars-until stream "?")))
(is (eql html5-constants::+eof+ (html5-parser::html5-stream-char stream)))))
(deftest test-line-ending-fix ()
(let ((stream (html5-parser::make-html-input-stream (coerce #(#\a #\Newline
#\b #\Return
#\c #\Return #\Newline
#\d)
'string))))
(is (eql #\a (html5-parser::html5-stream-char stream)))
(is (eql #\Newline (html5-parser::html5-stream-char stream)))
(is (eql #\b (html5-parser::html5-stream-char stream)))
(is (eql #\Newline (html5-parser::html5-stream-char stream)))
(is (eql #\c (html5-parser::html5-stream-char stream)))
(is (eql #\Newline (html5-parser::html5-stream-char stream)))
(is (eql #\d (html5-parser::html5-stream-char stream)))
(is (eql html5-constants::+eof+ (html5-parser::html5-stream-char stream)))))
(deftest test-line-ending-fix2 ()
(let ((stream (html5-parser::make-html-input-stream (coerce #(#\< #\? #\Return)
'string))))
(is (eql #\< (html5-parser::html5-stream-char stream)))
(is (eql #\? (html5-parser::html5-stream-char stream)))
(is (eql #\Newline (html5-parser::html5-stream-char stream)))
(is (eql html5-constants::+eof+ (html5-parser::html5-stream-char stream)))))
(deftest test-bom ()
(let ((stream (html5-parser::make-html-input-stream #(#xef #xbb #xbf 39))))
(is (eql (car (html5-parser::html5-stream-encoding stream))
:utf-8))
(is (eql (html5-parser::html5-stream-char stream)
#\'))))
| 4,205
|
Common Lisp
|
.lisp
| 74
| 49.243243
| 86
| 0.621845
|
rotatef/cl-html5-parser
| 55
| 14
| 11
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
fc335dfdae8ef6b493a678cb5a79dff6632a30cf0f72122dba3b10773a05995b
| 3,094
|
[
-1
] |
3,095
|
test-tokenizer.lisp
|
rotatef_cl-html5-parser/tests/test-tokenizer.lisp
|
;;;; HTML5 parser for Common Lisp
;;;;
;;;; Copyright (C) 2012 Thomas Bakketun <thomas.bakketun@copyleft.no>
;;;; Copyright (C) 2012 Asgeir Bj√∏rlykke <asgeir@copyleft.no>
;;;; Copyright (C) 2012 Mathias Hellevang
;;;; Copyright (C) 2012 Stian Sletner <stian@copyleft.no>
;;;;
;;;; This library is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Lesser General Public License as published
;;;; by the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This library 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 library. If not, see <http://www.gnu.org/licenses/>.
(in-package :html5-parser-tests)
(defun run-tokenizer-test-parser (initial-state last-start-tag source encoding)
(let ((tokenizer (html5-parser::make-html-tokenizer source :encoding encoding))
(output-tokens '()))
(setf (slot-value tokenizer 'html5-parser::state) initial-state)
(when last-start-tag
(setf (slot-value tokenizer 'html5-parser::current-token)
(list :type :start-tag
:name last-start-tag)))
(html5-parser::map-tokens
tokenizer
(lambda (token)
; (print token)
(push (ecase (getf token :type)
(:doctype
(list :type :doctype
:name (getf token :name)
:public-id (getf token :public-id)
:system-id (getf token :system-id)
:correct (getf token :correct)))
((:start-tag :empty-tag)
(list :type (getf token :type)
:name (getf token :name)
:data (remove-duplicates (getf token :data)
:key #'car
:test #'string=
:from-end t)
:self-closing (getf token :self-closing)))
(:end-tag
(list :type :end-tag
:name (getf token :name)))
(:comment
(list :type :comment
:data (getf token :data)))
((:space-characters :characters)
(list :type :characters
:data (getf token :data)))
(:parse-error
(list :type :parse-error)))
output-tokens)))
(nreverse output-tokens)))
(defun concatenate-character-tokens (tokens)
(let ((output-tokens '()))
(dolist (token tokens)
(if (and (eql :characters (getf (car output-tokens) :type))
(eql :characters (getf token :type)))
(setf (getf (car output-tokens) :data)
(concatenate 'string
(getf (car output-tokens) :data)
(getf token :data)))
(push token output-tokens)))
(nreverse output-tokens)))
(defun tokens-match (expected-tokens received-tokens ignore-error-order)
"Test whether the test has passed or failed
If the ignoreErrorOrder flag is set to true we don't test the relative
positions of parse errors and non parse errors
"
(labels ((group (tokens)
;; Sort the tokens into two groups; non-parse errors and parse errors
(cons (remove-if (lambda (x)
(eql (getf x :type) :parse-error))
tokens)
(remove-if-not (lambda (x)
(eql (getf x :type) :parse-error))
tokens))))
(when ignore-error-order
(setf expected-tokens (group expected-tokens))
(setf received-tokens (group received-tokens)))
(equal expected-tokens received-tokens)))
(defun temp-fix (data)
(flex:octets-to-string data
:external-format :utf-16le))
(defun run-tokenizer-test (test-name initial-state test)
(with-simple-restart (skip "Skip test ~A ~A: ~A"
test-name
initial-state
(getf test :description))
(let* ((expected (getf test :output))
(tokens (run-tokenizer-test-parser initial-state
(getf test :last-start-tag)
(getf test :input)
:utf-16le))
(received (concatenate-character-tokens tokens)))
(unless (tokens-match expected received (getf test :ignore-error-order))
(error "Test failed ~S ~%Expected: ~S~%Received: ~S" test expected received)))))
(defun utf16-string-to-octets (string)
(when string
(coerce (loop for i in (cdr string)
collect (ldb (byte 8 0) i)
collect (ldb (byte 8 8) i))
'(vector (unsigned-byte 8)))))
(defun double-unescape (string)
(when string
(json-streams:json-parse (format nil "\"~A\"" (from-raw-string string)) :raw-strings t)))
(defun data-to-octects (string double-escaped)
(when string
(utf16-string-to-octets (if double-escaped
(double-unescape string)
string))))
(defun fix-output (output double-escaped)
(flet ((unescape (string)
(when (consp string)
(flex:octets-to-string (data-to-octects string double-escaped)
:external-format :utf-16le))))
(loop for value in output
collect
(if (and (consp value) (eql :array (car value)))
(let ((value (cdr value)))
(flet ((is (name)
(equal (to-raw-string name) (car value))))
(cond ((is "Character")
(assert (= 2 (length value)))
(list :type :characters :data (unescape (second value))))
((is "Comment")
(assert (= 2 (length value)))
(list :type :comment :data (unescape (second value))))
((is "StartTag")
(assert (<= 3 (length value) 4))
(list :type :start-tag
:name (unescape (second value))
:data (loop for (attr . attr-value) in (cdr (third value))
collect (cons (unescape attr)
(unescape attr-value)))
:self-closing (fourth value)))
((is "EndTag")
(assert (= 2 (length value)))
(list :type :end-tag :name (unescape (second value))))
((is "DOCTYPE")
(assert (= 5 (length value)))
(list :type :doctype
:name (unescape (second value))
:public-id (unescape (third value))
:system-id (unescape (fourth value))
:correct (fifth value)))
(t (error "Unexpected token type ~S" (car value))))))
(if (equal (to-raw-string "ParseError") value)
(list :type :parse-error)
(error "Unexpected token type ~S" value))))))
(defun find-state-symbol (string)
(let ((symbol (find-symbol (substitute #\- #\Space (string-upcase string)) :keyword)))
(assert symbol () "Unkown state ~S" string)
symbol))
(defun to-raw-string (string)
(cons :string (map 'list #'char-code string)))
(defun from-raw-string (raw-string)
(when (consp raw-string)
(map 'string #'code-char (cdr raw-string))))
(defun jget (json key &rest more-keys)
"Access data from json object. Key is one of
an integer - expects an array, returns element indexed by key
a string - expectes an object, returns element matching key (using equal)
:array - expects an array, returns the items of the array
:object - expects an object, returns the items of the object, alist
Suppling more-keys will result in recursive application of jget with the result of the previous key lookup as the json object."
(when json
(let ((value (etypecase key
((member :object)
(assert (eq :object (car json)) (json) "Not a JSON object")
(cdr json))
((member :array)
(assert (eq :array (car json)) (json) "Not a JSON array")
(cdr json))
(integer
(elt (jget json :array) key))
(string
(cdr (assoc (to-raw-string key) (jget json :object) :test #'equal)))
((member :string)
(assert (eq :string (car json)) (json) "Not a JSON string")
(from-raw-string json)))))
(if more-keys
(apply #'jget value more-keys)
(if (eq :null value)
(values)
value)))))
(defun load-tests (filename)
(with-open-file (in filename)
(loop for test in (jget (json-streams:json-parse in :raw-strings t) "tests" :array)
for double-escaped = (jget test "doubleEscaped")
collect (list :description (jget test "description" :string)
:initial-states (or (loop for raw in (jget test "initialStates" :array)
collect (find-state-symbol (jget raw :string)))
'(:data-state))
:last-start-tag (jget test "lastStartTag" :string)
:input (data-to-octects (jget test "input") double-escaped)
:output (fix-output (jget test "output" :array) double-escaped)
:double-escaped double-escaped
:ignore-error-order (jget test "ignoreErrorOrder")))))
(defparameter *skip-tests*
'(("domjs"
"--!NUL in comment ") ; to many ParseErrors. Wrong test?
("unicodeCharsProblematic"
;; Hangs on the following test, due to bug in flexi-streams
"Invalid Unicode character U+DFFF with valid preceding character"
;; The valid "a" character is consumed
"Invalid Unicode character U+D800 with valid following character")))
(defun test-tokenizer ()
(loop for filename in (html5lib-test-files "tokenizer" :type "test")
for test-name = (pathname-name filename)
for tests = (load-tests filename)
for skip = (cdr (assoc test-name *skip-tests* :test #'string=))
unless (eql (first skip) :skip)
do
(dolist (test tests)
(unless (find (getf test :description) skip :test #'string=)
(dolist (initial-state (getf test :initial-states))
(run-tokenizer-test test-name initial-state test))))))
| 11,281
|
Common Lisp
|
.lisp
| 225
| 35.764444
| 127
| 0.535381
|
rotatef/cl-html5-parser
| 55
| 14
| 11
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
cbf269a0396dcf8f52efd3304d28adce3a277d2393ec4fd46d8bd104b2267c14
| 3,095
|
[
-1
] |
3,096
|
aa-lisp-tests.test
|
rotatef_cl-html5-parser/tests/testdata/tokenizer/aa-lisp-tests.test
|
{"tests": [
{"description":"Comment in script",
"initialStates":["SCRIPT DATA state"],
"lastStartTag":"plaintext",
"input":"<!--<S",
"output":[["Character", "<!--<S"]]}
]}
| 174
|
Common Lisp
|
.lisp
| 7
| 23.571429
| 38
| 0.618182
|
rotatef/cl-html5-parser
| 55
| 14
| 11
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
644ce17fb0a92ddca55fd4a82f9159d70d596e47c98ddd13047684a5eec1c794
| 3,096
|
[
-1
] |
3,097
|
cl-html5-parser.asd
|
rotatef_cl-html5-parser/cl-html5-parser.asd
|
;;;; HTML5 parser for Common Lisp
;;;;
;;;; Copyright (C) 2017 Thomas Bakketun <thomas.bakketun@copyleft.no>
;;;; Copyright (C) 2012 Asgeir Bj√∏rlykke <asgeir@copyleft.no>
;;;; Copyright (C) 2012 Mathias Hellevang
;;;; Copyright (C) 2012 Stian Sletner <stian@copyleft.no>
;;;;
;;;; This library is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Lesser General Public License as published
;;;; by the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This library 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 library. If not, see <http://www.gnu.org/licenses/>.
(defsystem #:cl-html5-parser
:name "cl-html5-parser"
:description "A HTML5 parser for Common Lisp"
:licence "GNU Lesser General Public License"
:author "Thomas Bakketun <thomas.bakketun@copyleft.no>"
:depends-on (:cl-ppcre :flexi-streams :string-case)
:serial t
:components ((:file "packages")
(:file "constants")
(:file "entities")
(:file "inputstream")
(:file "tokenizer")
(:file "simple-tree")
(:file "html5-parser-class")
(:file "tree-help")
(:file "html5-parser")
(:file "toxml")
(:file "xmls")))
(defmethod perform ((o test-op) (c (eql (find-system '#:cl-html5-parser))))
(operate 'load-op '#:cl-html5-parser-tests)
(funcall (find-symbol (string :run-html5-parser-tests)
:html5-parser-tests)))
| 1,864
|
Common Lisp
|
.asd
| 41
| 39.707317
| 78
| 0.645604
|
rotatef/cl-html5-parser
| 55
| 14
| 11
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
2e5ae0b043153c8e37f4185b239a88e408159258b0829d7373ad337add9c36b7
| 3,097
|
[
-1
] |
3,098
|
cl-html5-parser-cxml.asd
|
rotatef_cl-html5-parser/cxml/cl-html5-parser-cxml.asd
|
;;;; HTML5 parser for Common Lisp
;;;;
;;;; Copyright (C) 2017 Thomas Bakketun <thomas.bakketun@copyleft.no>
;;;; Copyright (C) 2012 Asgeir Bj√∏rlykke <asgeir@copyleft.no>
;;;; Copyright (C) 2012 Mathias Hellevang
;;;; Copyright (C) 2012 Stian Sletner <stian@copyleft.no>
;;;;
;;;; This library is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Lesser General Public License as published
;;;; by the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This library 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 library. If not, see <http://www.gnu.org/licenses/>.
(defsystem #:cl-html5-parser-cxml
:name "cl-html5-parser"
:description "CXML integration for cl-html5-parser"
:licence "GNU Lesser General Public License"
:author "Thomas Bakketun <thomas.bakketun@copyleft.no>"
:depends-on (:cl-html5-parser :cxml)
:serial t
:components ((:file "cxml-dom")))
| 1,276
|
Common Lisp
|
.asd
| 27
| 45.703704
| 78
| 0.722756
|
rotatef/cl-html5-parser
| 55
| 14
| 11
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
3ac9e8bb35025842b544e09f86cdf83b634ce2d27fdf41b0a68b14127aedc843
| 3,098
|
[
-1
] |
3,099
|
cl-html5-parser-tests.asd
|
rotatef_cl-html5-parser/tests/cl-html5-parser-tests.asd
|
;;;; HTML5 parser for Common Lisp
;;;;
;;;; Copyright (C) 2017 Thomas Bakketun <thomas.bakketun@copyleft.no>
;;;; Copyright (C) 2012 Asgeir Bj√∏rlykke <asgeir@copyleft.no>
;;;; Copyright (C) 2012 Mathias Hellevang
;;;; Copyright (C) 2012 Stian Sletner <stian@copyleft.no>
;;;;
;;;; This library is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Lesser General Public License as published
;;;; by the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This library 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 library. If not, see <http://www.gnu.org/licenses/>.
(defsystem #:cl-html5-parser-tests
:depends-on (:cl-html5-parser :stefil :json-streams :split-sequence)
:components ((:file "packages")
(:file "support")
(:file "test-inputstream")
(:file "test-tokenizer")
(:file "test-tree-builder")
(:file "test-parser")
(:file "run-tests")))
| 1,342
|
Common Lisp
|
.asd
| 28
| 43.535714
| 78
| 0.667174
|
rotatef/cl-html5-parser
| 55
| 14
| 11
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
0150e21f31f3637ffaa3997661394e7bcad9a3f808928dd46cc4f5a29df44d11
| 3,099
|
[
-1
] |
3,109
|
.travis.yml
|
rotatef_cl-html5-parser/.travis.yml
|
language: lisp
sudo: required
branches:
only:
- master
env:
matrix:
- LISP=sbcl
install:
- curl -L https://github.com/luismbo/cl-travis/raw/master/install.sh | sh
script:
- cl -e "(ql:quickload :cl-html5-parser) (ql:quickload :cl-html5-parser-tests) (html5-parser-tests::run-html5-parser-tests)"
| 316
|
Common Lisp
|
.l
| 12
| 23.666667
| 126
| 0.723333
|
rotatef/cl-html5-parser
| 55
| 14
| 11
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
01371b5316de892ea0fb24fc5a578adcad00d91726a81aea7fab707bddcc4d5c
| 3,109
|
[
-1
] |
3,125
|
pending-spec-changes-plain-text-unsafe.dat
|
rotatef_cl-html5-parser/tests/testdata/tree-construction/pending-spec-changes-plain-text-unsafe.dat
|
#data
<body><table> filler text
#errors
#document
| <html>
| <head>
| <body>
| "fillertext"
| <table>
| 115
|
Common Lisp
|
.l
| 9
| 11.777778
| 26
| 0.603774
|
rotatef/cl-html5-parser
| 55
| 14
| 11
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
b7c1b29b2b3210ef12d847aabc604c23626ac6783632560fa16ba8b90f780613
| 3,125
|
[
-1
] |
3,126
|
tables01.dat
|
rotatef_cl-html5-parser/tests/testdata/tree-construction/tables01.dat
|
#data
<table><th>
#errors
#document
| <html>
| <head>
| <body>
| <table>
| <tbody>
| <tr>
| <th>
#data
<table><td>
#errors
#document
| <html>
| <head>
| <body>
| <table>
| <tbody>
| <tr>
| <td>
#data
<table><col foo='bar'>
#errors
#document
| <html>
| <head>
| <body>
| <table>
| <colgroup>
| <col>
| foo="bar"
#data
<table><colgroup></html>foo
#errors
#document
| <html>
| <head>
| <body>
| "foo"
| <table>
| <colgroup>
#data
<table></table><p>foo
#errors
#document
| <html>
| <head>
| <body>
| <table>
| <p>
| "foo"
#data
<table></body></caption></col></colgroup></html></tbody></td></tfoot></th></thead></tr><td>
#errors
#document
| <html>
| <head>
| <body>
| <table>
| <tbody>
| <tr>
| <td>
#data
<table><select><option>3</select></table>
#errors
#document
| <html>
| <head>
| <body>
| <select>
| <option>
| "3"
| <table>
#data
<table><select><table></table></select></table>
#errors
#document
| <html>
| <head>
| <body>
| <select>
| <table>
| <table>
#data
<table><select></table>
#errors
#document
| <html>
| <head>
| <body>
| <select>
| <table>
#data
<table><select><option>A<tr><td>B</td></tr></table>
#errors
#document
| <html>
| <head>
| <body>
| <select>
| <option>
| "A"
| <table>
| <tbody>
| <tr>
| <td>
| "B"
#data
<table><td></body></caption></col></colgroup></html>foo
#errors
#document
| <html>
| <head>
| <body>
| <table>
| <tbody>
| <tr>
| <td>
| "foo"
#data
<table><td>A</table>B
#errors
#document
| <html>
| <head>
| <body>
| <table>
| <tbody>
| <tr>
| <td>
| "A"
| "B"
#data
<table><tr><caption>
#errors
#document
| <html>
| <head>
| <body>
| <table>
| <tbody>
| <tr>
| <caption>
#data
<table><tr></body></caption></col></colgroup></html></td></th><td>foo
#errors
#document
| <html>
| <head>
| <body>
| <table>
| <tbody>
| <tr>
| <td>
| "foo"
#data
<table><td><tr>
#errors
#document
| <html>
| <head>
| <body>
| <table>
| <tbody>
| <tr>
| <td>
| <tr>
#data
<table><td><button><td>
#errors
#document
| <html>
| <head>
| <body>
| <table>
| <tbody>
| <tr>
| <td>
| <button>
| <td>
#data
<table><tr><td><svg><desc><td>
#errors
#document
| <html>
| <head>
| <body>
| <table>
| <tbody>
| <tr>
| <td>
| <svg svg>
| <svg desc>
| <td>
| 2,770
|
Common Lisp
|
.l
| 196
| 13.05102
| 91
| 0.461689
|
rotatef/cl-html5-parser
| 55
| 14
| 11
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
03e5cd0f31e2974358b997f08177b281d79c0e192a0f1444aecb95a1de55cda7
| 3,126
|
[
-1
] |
3,127
|
plain-text-unsafe.dat
|
rotatef_cl-html5-parser/tests/testdata/tree-construction/plain-text-unsafe.dat
|
#data
FOO
ZOO
#errors
#document
| <html>
| <head>
| <body>
| "FOO
ZOO"
#data
<html> <frameset></frameset>
#errors
#document
| <html>
| <head>
| <frameset>
#data
<html> <frameset></frameset>
#errors
#document
| <html>
| <head>
| <frameset>
#data
<html>a a<frameset></frameset>
#errors
#document
| <html>
| <head>
| <body>
| "aa"
#data
<html> <frameset></frameset>
#errors
#document
| <html>
| <head>
| <frameset>
#data
<html>
<frameset></frameset>
#errors
#document
| <html>
| <head>
| <frameset>
#data
<html><select>
#errors
#document
| <html>
| <head>
| <body>
| <select>
#data
#errors
#document
| <html>
| <head>
| <body>
#data
<body>
#errors
#document
| <html>
| <head>
| <body>
#data
<plaintext> filler text
#errors
#document
| <html>
| <head>
| <body>
| <plaintext>
| "�filler�text�"
#data
<svg><![CDATA[ filler text ]]>
#errors
#document
| <html>
| <head>
| <body>
| <svg svg>
| "�filler�text�"
#data
<body><! >
#errors
#document
| <html>
| <head>
| <body>
| <!-- � -->
#data
<body><! filler text>
#errors
#document
| <html>
| <head>
| <body>
| <!-- �filler�text -->
#data
<body><svg><foreignObject> filler text
#errors
#document
| <html>
| <head>
| <body>
| <svg svg>
| <svg foreignObject>
| "fillertext"
#data
<svg> filler text
#errors
#document
| <html>
| <head>
| <body>
| <svg svg>
| "�filler�text"
#data
<svg> <frameset>
#errors
#document
| <html>
| <head>
| <body>
| <svg svg>
| "�"
| <svg frameset>
#data
<svg> <frameset>
#errors
#document
| <html>
| <head>
| <body>
| <svg svg>
| "� "
| <svg frameset>
#data
<svg> a<frameset>
#errors
#document
| <html>
| <head>
| <body>
| <svg svg>
| "�a"
| <svg frameset>
#data
<svg> </svg><frameset>
#errors
#document
| <html>
| <head>
| <frameset>
#data
<svg> </svg><frameset>
#errors
#document
| <html>
| <head>
| <frameset>
#data
<svg> a</svg><frameset>
#errors
#document
| <html>
| <head>
| <body>
| <svg svg>
| "�a"
#data
<svg><path></path></svg><frameset>
#errors
#document
| <html>
| <head>
| <frameset>
#data
<svg><p><frameset>
#errors
#document
| <html>
| <head>
| <frameset>
#data
<!DOCTYPE html><pre>
A</pre>
#errors
#document
| <!DOCTYPE html>
| <html>
| <head>
| <body>
| <pre>
| "
A"
#data
<!DOCTYPE html><pre>
A</pre>
#errors
#document
| <!DOCTYPE html>
| <html>
| <head>
| <body>
| <pre>
| "
A"
#data
<!DOCTYPE html><pre>
A</pre>
#errors
#document
| <!DOCTYPE html>
| <html>
| <head>
| <body>
| <pre>
| "A"
#data
<!DOCTYPE html><table><tr><td><math><mtext> a
#errors
44: Saw U+0000 in stream.
45: End of file in a foreign namespace context.
#document
| <!DOCTYPE html>
| <html>
| <head>
| <body>
| <table>
| <tbody>
| <tr>
| <td>
| <mathml math>
| <mathml mtext>
| "a"
#data
<!DOCTYPE html><table><tr><td><svg><foreignObject> a
#errors
44: Saw U+0000 in stream.
45: End of file in a foreign namespace context.
#document
| <!DOCTYPE html>
| <html>
| <head>
| <body>
| <table>
| <tbody>
| <tr>
| <td>
| <svg svg>
| <svg foreignObject>
| "a"
#data
<!DOCTYPE html><math><mi>a b
#errors
#document
| <!DOCTYPE html>
| <html>
| <head>
| <body>
| <mathml math>
| <mathml mi>
| "ab"
#data
<!DOCTYPE html><math><mo>a b
#errors
#document
| <!DOCTYPE html>
| <html>
| <head>
| <body>
| <mathml math>
| <mathml mo>
| "ab"
#data
<!DOCTYPE html><math><mn>a b
#errors
#document
| <!DOCTYPE html>
| <html>
| <head>
| <body>
| <mathml math>
| <mathml mn>
| "ab"
#data
<!DOCTYPE html><math><ms>a b
#errors
#document
| <!DOCTYPE html>
| <html>
| <head>
| <body>
| <mathml math>
| <mathml ms>
| "ab"
#data
<!DOCTYPE html><math><mtext>a b
#errors
#document
| <!DOCTYPE html>
| <html>
| <head>
| <body>
| <mathml math>
| <mathml mtext>
| "ab"
| 4,190
|
Common Lisp
|
.l
| 309
| 12.346278
| 52
| 0.563532
|
rotatef/cl-html5-parser
| 55
| 14
| 11
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
ac387fdd7b7f626b1930860a94f99f4365ceb62d62a350de2d9a62c3ab74687e
| 3,127
|
[
-1
] |
3,128
|
html5test-com.dat
|
rotatef_cl-html5-parser/tests/testdata/tree-construction/html5test-com.dat
|
#data
<div<div>
#errors
#document
| <html>
| <head>
| <body>
| <div<div>
#data
<div foo<bar=''>
#errors
#document
| <html>
| <head>
| <body>
| <div>
| foo<bar=""
#data
<div foo=`bar`>
#errors
#document
| <html>
| <head>
| <body>
| <div>
| foo="`bar`"
#data
<div \"foo=''>
#errors
#document
| <html>
| <head>
| <body>
| <div>
| \"foo=""
#data
<a href='\nbar'></a>
#errors
#document
| <html>
| <head>
| <body>
| <a>
| href="\nbar"
#data
<!DOCTYPE html>
#errors
#document
| <!DOCTYPE html>
| <html>
| <head>
| <body>
#data
⟨⟩
#errors
#document
| <html>
| <head>
| <body>
| "⟨⟩"
#data
'
#errors
#document
| <html>
| <head>
| <body>
| "'"
#data
ⅈ
#errors
#document
| <html>
| <head>
| <body>
| "‚Öà"
#data
𝕂
#errors
#document
| <html>
| <head>
| <body>
| "ùïÇ"
#data
∉
#errors
#document
| <html>
| <head>
| <body>
| "‚àâ"
#data
<?import namespace="foo" implementation="#bar">
#errors
#document
| <!-- ?import namespace="foo" implementation="#bar" -->
| <html>
| <head>
| <body>
#data
<!--foo--bar-->
#errors
#document
| <!-- foo--bar -->
| <html>
| <head>
| <body>
#data
<![CDATA[x]]>
#errors
#document
| <!-- [CDATA[x]] -->
| <html>
| <head>
| <body>
#data
<textarea><!--</textarea>--></textarea>
#errors
#document
| <html>
| <head>
| <body>
| <textarea>
| "<!--"
| "-->"
#data
<textarea><!--</textarea>-->
#errors
#document
| <html>
| <head>
| <body>
| <textarea>
| "<!--"
| "-->"
#data
<style><!--</style>--></style>
#errors
#document
| <html>
| <head>
| <style>
| "<!--"
| <body>
| "-->"
#data
<style><!--</style>-->
#errors
#document
| <html>
| <head>
| <style>
| "<!--"
| <body>
| "-->"
#data
<ul><li>A </li> <li>B</li></ul>
#errors
#document
| <html>
| <head>
| <body>
| <ul>
| <li>
| "A "
| " "
| <li>
| "B"
#data
<table><form><input type=hidden><input></form><div></div></table>
#errors
#document
| <html>
| <head>
| <body>
| <input>
| <div>
| <table>
| <form>
| <input>
| type="hidden"
#data
<i>A<b>B<p></i>C</b>D
#errors
#document
| <html>
| <head>
| <body>
| <i>
| "A"
| <b>
| "B"
| <b>
| <p>
| <b>
| <i>
| "C"
| "D"
#data
<div></div>
#errors
#document
| <html>
| <head>
| <body>
| <div>
#data
<svg></svg>
#errors
#document
| <html>
| <head>
| <body>
| <svg svg>
#data
<math></math>
#errors
#document
| <html>
| <head>
| <body>
| <mathml math>
| 2,676
|
Common Lisp
|
.l
| 223
| 10.896861
| 65
| 0.495473
|
rotatef/cl-html5-parser
| 55
| 14
| 11
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
c6a621d851468f44918b8b73120fbc980269be22cbfb54ebd57861314fce9e06
| 3,128
|
[
-1
] |
3,129
|
optionaltags.test
|
rotatef_cl-html5-parser/tests/testdata/serializer/optionaltags.test
|
{"tests": [
{"description": "html start-tag followed by text, with attributes",
"input": [["StartTag", "http://www.w3.org/1999/xhtml", "html", [{"namespace": null, "name": "lang", "value": "en"}]], ["Characters", "foo"]],
"expected": ["<html lang=en>foo"]
},
{"description": "html start-tag followed by comment",
"input": [["StartTag", "http://www.w3.org/1999/xhtml", "html", {}], ["Comment", "foo"]],
"expected": ["<html><!--foo-->"]
},
{"description": "html start-tag followed by space character",
"input": [["StartTag", "http://www.w3.org/1999/xhtml", "html", {}], ["Characters", " foo"]],
"expected": ["<html> foo"]
},
{"description": "html start-tag followed by text",
"input": [["StartTag", "http://www.w3.org/1999/xhtml", "html", {}], ["Characters", "foo"]],
"expected": ["foo"]
},
{"description": "html start-tag followed by start-tag",
"input": [["StartTag", "http://www.w3.org/1999/xhtml", "html", {}], ["StartTag", "http://www.w3.org/1999/xhtml", "foo", {}]],
"expected": ["<foo>"]
},
{"description": "html start-tag followed by end-tag",
"input": [["StartTag", "http://www.w3.org/1999/xhtml", "html", {}], ["EndTag", "http://www.w3.org/1999/xhtml", "foo"]],
"expected": ["</foo>"]
},
{"description": "html start-tag at EOF (shouldn't ever happen?!)",
"input": [["StartTag", "http://www.w3.org/1999/xhtml", "html", {}]],
"expected": [""]
},
{"description": "html end-tag followed by comment",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "html"], ["Comment", "foo"]],
"expected": ["</html><!--foo-->"]
},
{"description": "html end-tag followed by space character",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "html"], ["Characters", " foo"]],
"expected": ["</html> foo"]
},
{"description": "html end-tag followed by text",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "html"], ["Characters", "foo"]],
"expected": ["foo"]
},
{"description": "html end-tag followed by start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "html"], ["StartTag", "http://www.w3.org/1999/xhtml", "foo", {}]],
"expected": ["<foo>"]
},
{"description": "html end-tag followed by end-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "html"], ["EndTag", "http://www.w3.org/1999/xhtml", "foo"]],
"expected": ["</foo>"]
},
{"description": "html end-tag at EOF",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "html"]],
"expected": [""]
},
{"description": "head start-tag followed by comment",
"input": [["StartTag", "http://www.w3.org/1999/xhtml", "head", {}], ["Comment", "foo"]],
"expected": ["<head><!--foo-->"]
},
{"description": "head start-tag followed by space character",
"input": [["StartTag", "http://www.w3.org/1999/xhtml", "head", {}], ["Characters", " foo"]],
"expected": ["<head> foo"]
},
{"description": "head start-tag followed by text",
"input": [["StartTag", "http://www.w3.org/1999/xhtml", "head", {}], ["Characters", "foo"]],
"expected": ["<head>foo"]
},
{"description": "head start-tag followed by start-tag",
"input": [["StartTag", "http://www.w3.org/1999/xhtml", "head", {}], ["StartTag", "http://www.w3.org/1999/xhtml", "foo", {}]],
"expected": ["<foo>"]
},
{"description": "head start-tag followed by end-tag (shouldn't ever happen?!)",
"input": [["StartTag", "http://www.w3.org/1999/xhtml", "head", {}], ["EndTag", "http://www.w3.org/1999/xhtml", "foo"]],
"expected": ["<head></foo>", "</foo>"]
},
{"description": "empty head element",
"input": [["StartTag", "http://www.w3.org/1999/xhtml", "head", {}], ["EndTag", "http://www.w3.org/1999/xhtml", "head"]],
"expected": [""]
},
{"description": "head start-tag followed by empty-tag",
"input": [["StartTag", "http://www.w3.org/1999/xhtml", "head", {}], ["EmptyTag", "foo", {}]],
"expected": ["<foo>"]
},
{"description": "head start-tag at EOF (shouldn't ever happen?!)",
"input": [["StartTag", "http://www.w3.org/1999/xhtml", "head", {}]],
"expected": ["<head>", ""]
},
{"description": "head end-tag followed by comment",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "head"], ["Comment", "foo"]],
"expected": ["</head><!--foo-->"]
},
{"description": "head end-tag followed by space character",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "head"], ["Characters", " foo"]],
"expected": ["</head> foo"]
},
{"description": "head end-tag followed by text",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "head"], ["Characters", "foo"]],
"expected": ["foo"]
},
{"description": "head end-tag followed by start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "head"], ["StartTag", "http://www.w3.org/1999/xhtml", "foo", {}]],
"expected": ["<foo>"]
},
{"description": "head end-tag followed by end-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "head"], ["EndTag", "http://www.w3.org/1999/xhtml", "foo"]],
"expected": ["</foo>"]
},
{"description": "head end-tag at EOF",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "head"]],
"expected": [""]
},
{"description": "body start-tag followed by comment",
"input": [["StartTag", "http://www.w3.org/1999/xhtml", "body", {}], ["Comment", "foo"]],
"expected": ["<body><!--foo-->"]
},
{"description": "body start-tag followed by space character",
"input": [["StartTag", "http://www.w3.org/1999/xhtml", "body", {}], ["Characters", " foo"]],
"expected": ["<body> foo"]
},
{"description": "body start-tag followed by text",
"input": [["StartTag", "http://www.w3.org/1999/xhtml", "body", {}], ["Characters", "foo"]],
"expected": ["foo"]
},
{"description": "body start-tag followed by start-tag",
"input": [["StartTag", "http://www.w3.org/1999/xhtml", "body", {}], ["StartTag", "http://www.w3.org/1999/xhtml", "foo", {}]],
"expected": ["<foo>"]
},
{"description": "body start-tag followed by end-tag",
"input": [["StartTag", "http://www.w3.org/1999/xhtml", "body", {}], ["EndTag", "http://www.w3.org/1999/xhtml", "foo"]],
"expected": ["</foo>"]
},
{"description": "body start-tag at EOF (shouldn't ever happen?!)",
"input": [["StartTag", "http://www.w3.org/1999/xhtml", "body", {}]],
"expected": [""]
},
{"description": "body end-tag followed by comment",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "body"], ["Comment", "foo"]],
"expected": ["</body><!--foo-->"]
},
{"description": "body end-tag followed by space character",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "body"], ["Characters", " foo"]],
"expected": ["</body> foo"]
},
{"description": "body end-tag followed by text",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "body"], ["Characters", "foo"]],
"expected": ["foo"]
},
{"description": "body end-tag followed by start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "body"], ["StartTag", "http://www.w3.org/1999/xhtml", "foo", {}]],
"expected": ["<foo>"]
},
{"description": "body end-tag followed by end-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "body"], ["EndTag", "http://www.w3.org/1999/xhtml", "foo"]],
"expected": ["</foo>"]
},
{"description": "body end-tag at EOF",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "body"]],
"expected": [""]
},
{"description": "li end-tag followed by comment",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "li"], ["Comment", "foo"]],
"expected": ["</li><!--foo-->"]
},
{"description": "li end-tag followed by space character",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "li"], ["Characters", " foo"]],
"expected": ["</li> foo"]
},
{"description": "li end-tag followed by text",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "li"], ["Characters", "foo"]],
"expected": ["</li>foo"]
},
{"description": "li end-tag followed by start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "li"], ["StartTag", "http://www.w3.org/1999/xhtml", "foo", {}]],
"expected": ["</li><foo>"]
},
{"description": "li end-tag followed by li start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "li"], ["StartTag", "http://www.w3.org/1999/xhtml", "li", {}]],
"expected": ["<li>"]
},
{"description": "li end-tag followed by end-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "li"], ["EndTag", "http://www.w3.org/1999/xhtml", "foo"]],
"expected": ["</foo>"]
},
{"description": "li end-tag at EOF",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "li"]],
"expected": [""]
},
{"description": "dt end-tag followed by comment",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "dt"], ["Comment", "foo"]],
"expected": ["</dt><!--foo-->"]
},
{"description": "dt end-tag followed by space character",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "dt"], ["Characters", " foo"]],
"expected": ["</dt> foo"]
},
{"description": "dt end-tag followed by text",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "dt"], ["Characters", "foo"]],
"expected": ["</dt>foo"]
},
{"description": "dt end-tag followed by start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "dt"], ["StartTag", "http://www.w3.org/1999/xhtml", "foo", {}]],
"expected": ["</dt><foo>"]
},
{"description": "dt end-tag followed by dt start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "dt"], ["StartTag", "http://www.w3.org/1999/xhtml", "dt", {}]],
"expected": ["<dt>"]
},
{"description": "dt end-tag followed by dd start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "dt"], ["StartTag", "http://www.w3.org/1999/xhtml", "dd", {}]],
"expected": ["<dd>"]
},
{"description": "dt end-tag followed by end-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "dt"], ["EndTag", "http://www.w3.org/1999/xhtml", "foo"]],
"expected": ["</dt></foo>"]
},
{"description": "dt end-tag at EOF",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "dt"]],
"expected": ["</dt>"]
},
{"description": "dd end-tag followed by comment",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "dd"], ["Comment", "foo"]],
"expected": ["</dd><!--foo-->"]
},
{"description": "dd end-tag followed by space character",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "dd"], ["Characters", " foo"]],
"expected": ["</dd> foo"]
},
{"description": "dd end-tag followed by text",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "dd"], ["Characters", "foo"]],
"expected": ["</dd>foo"]
},
{"description": "dd end-tag followed by start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "dd"], ["StartTag", "http://www.w3.org/1999/xhtml", "foo", {}]],
"expected": ["</dd><foo>"]
},
{"description": "dd end-tag followed by dd start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "dd"], ["StartTag", "http://www.w3.org/1999/xhtml", "dd", {}]],
"expected": ["<dd>"]
},
{"description": "dd end-tag followed by dt start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "dd"], ["StartTag", "http://www.w3.org/1999/xhtml", "dt", {}]],
"expected": ["<dt>"]
},
{"description": "dd end-tag followed by end-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "dd"], ["EndTag", "http://www.w3.org/1999/xhtml", "foo"]],
"expected": ["</foo>"]
},
{"description": "dd end-tag at EOF",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "dd"]],
"expected": [""]
},
{"description": "p end-tag followed by comment",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "p"], ["Comment", "foo"]],
"expected": ["</p><!--foo-->"]
},
{"description": "p end-tag followed by space character",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "p"], ["Characters", " foo"]],
"expected": ["</p> foo"]
},
{"description": "p end-tag followed by text",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "p"], ["Characters", "foo"]],
"expected": ["</p>foo"]
},
{"description": "p end-tag followed by start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "p"], ["StartTag", "http://www.w3.org/1999/xhtml", "foo", {}]],
"expected": ["</p><foo>"]
},
{"description": "p end-tag followed by address start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "p"], ["StartTag", "http://www.w3.org/1999/xhtml", "address", {}]],
"expected": ["<address>"]
},
{"description": "p end-tag followed by article start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "p"], ["StartTag", "http://www.w3.org/1999/xhtml", "article", {}]],
"expected": ["<article>"]
},
{"description": "p end-tag followed by aside start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "p"], ["StartTag", "http://www.w3.org/1999/xhtml", "aside", {}]],
"expected": ["<aside>"]
},
{"description": "p end-tag followed by blockquote start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "p"], ["StartTag", "http://www.w3.org/1999/xhtml", "blockquote", {}]],
"expected": ["<blockquote>"]
},
{"description": "p end-tag followed by datagrid start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "p"], ["StartTag", "http://www.w3.org/1999/xhtml", "datagrid", {}]],
"expected": ["<datagrid>"]
},
{"description": "p end-tag followed by dialog start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "p"], ["StartTag", "http://www.w3.org/1999/xhtml", "dialog", {}]],
"expected": ["<dialog>"]
},
{"description": "p end-tag followed by dir start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "p"], ["StartTag", "http://www.w3.org/1999/xhtml", "dir", {}]],
"expected": ["<dir>"]
},
{"description": "p end-tag followed by div start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "p"], ["StartTag", "http://www.w3.org/1999/xhtml", "div", {}]],
"expected": ["<div>"]
},
{"description": "p end-tag followed by dl start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "p"], ["StartTag", "http://www.w3.org/1999/xhtml", "dl", {}]],
"expected": ["<dl>"]
},
{"description": "p end-tag followed by fieldset start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "p"], ["StartTag", "http://www.w3.org/1999/xhtml", "fieldset", {}]],
"expected": ["<fieldset>"]
},
{"description": "p end-tag followed by footer start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "p"], ["StartTag", "http://www.w3.org/1999/xhtml", "footer", {}]],
"expected": ["<footer>"]
},
{"description": "p end-tag followed by form start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "p"], ["StartTag", "http://www.w3.org/1999/xhtml", "form", {}]],
"expected": ["<form>"]
},
{"description": "p end-tag followed by h1 start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "p"], ["StartTag", "http://www.w3.org/1999/xhtml", "h1", {}]],
"expected": ["<h1>"]
},
{"description": "p end-tag followed by h2 start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "p"], ["StartTag", "http://www.w3.org/1999/xhtml", "h2", {}]],
"expected": ["<h2>"]
},
{"description": "p end-tag followed by h3 start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "p"], ["StartTag", "http://www.w3.org/1999/xhtml", "h3", {}]],
"expected": ["<h3>"]
},
{"description": "p end-tag followed by h4 start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "p"], ["StartTag", "http://www.w3.org/1999/xhtml", "h4", {}]],
"expected": ["<h4>"]
},
{"description": "p end-tag followed by h5 start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "p"], ["StartTag", "http://www.w3.org/1999/xhtml", "h5", {}]],
"expected": ["<h5>"]
},
{"description": "p end-tag followed by h6 start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "p"], ["StartTag", "http://www.w3.org/1999/xhtml", "h6", {}]],
"expected": ["<h6>"]
},
{"description": "p end-tag followed by header start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "p"], ["StartTag", "http://www.w3.org/1999/xhtml", "header", {}]],
"expected": ["<header>"]
},
{"description": "p end-tag followed by hr empty-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "p"], ["EmptyTag", "hr", {}]],
"expected": ["<hr>"]
},
{"description": "p end-tag followed by menu start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "p"], ["StartTag", "http://www.w3.org/1999/xhtml", "menu", {}]],
"expected": ["<menu>"]
},
{"description": "p end-tag followed by nav start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "p"], ["StartTag", "http://www.w3.org/1999/xhtml", "nav", {}]],
"expected": ["<nav>"]
},
{"description": "p end-tag followed by ol start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "p"], ["StartTag", "http://www.w3.org/1999/xhtml", "ol", {}]],
"expected": ["<ol>"]
},
{"description": "p end-tag followed by p start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "p"], ["StartTag", "http://www.w3.org/1999/xhtml", "p", {}]],
"expected": ["<p>"]
},
{"description": "p end-tag followed by pre start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "p"], ["StartTag", "http://www.w3.org/1999/xhtml", "pre", {}]],
"expected": ["<pre>"]
},
{"description": "p end-tag followed by section start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "p"], ["StartTag", "http://www.w3.org/1999/xhtml", "section", {}]],
"expected": ["<section>"]
},
{"description": "p end-tag followed by table start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "p"], ["StartTag", "http://www.w3.org/1999/xhtml", "table", {}]],
"expected": ["<table>"]
},
{"description": "p end-tag followed by ul start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "p"], ["StartTag", "http://www.w3.org/1999/xhtml", "ul", {}]],
"expected": ["<ul>"]
},
{"description": "p end-tag followed by end-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "p"], ["EndTag", "http://www.w3.org/1999/xhtml", "foo"]],
"expected": ["</foo>"]
},
{"description": "p end-tag at EOF",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "p"]],
"expected": [""]
},
{"description": "optgroup end-tag followed by comment",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "optgroup"], ["Comment", "foo"]],
"expected": ["</optgroup><!--foo-->"]
},
{"description": "optgroup end-tag followed by space character",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "optgroup"], ["Characters", " foo"]],
"expected": ["</optgroup> foo"]
},
{"description": "optgroup end-tag followed by text",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "optgroup"], ["Characters", "foo"]],
"expected": ["</optgroup>foo"]
},
{"description": "optgroup end-tag followed by start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "optgroup"], ["StartTag", "http://www.w3.org/1999/xhtml", "foo", {}]],
"expected": ["</optgroup><foo>"]
},
{"description": "optgroup end-tag followed by optgroup start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "optgroup"], ["StartTag", "http://www.w3.org/1999/xhtml", "optgroup", {}]],
"expected": ["<optgroup>"]
},
{"description": "optgroup end-tag followed by end-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "optgroup"], ["EndTag", "http://www.w3.org/1999/xhtml", "foo"]],
"expected": ["</foo>"]
},
{"description": "optgroup end-tag at EOF",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "optgroup"]],
"expected": [""]
},
{"description": "option end-tag followed by comment",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "option"], ["Comment", "foo"]],
"expected": ["</option><!--foo-->"]
},
{"description": "option end-tag followed by space character",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "option"], ["Characters", " foo"]],
"expected": ["</option> foo"]
},
{"description": "option end-tag followed by text",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "option"], ["Characters", "foo"]],
"expected": ["</option>foo"]
},
{"description": "option end-tag followed by optgroup start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "option"], ["StartTag", "http://www.w3.org/1999/xhtml", "optgroup", {}]],
"expected": ["<optgroup>"]
},
{"description": "option end-tag followed by start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "option"], ["StartTag", "http://www.w3.org/1999/xhtml", "foo", {}]],
"expected": ["</option><foo>"]
},
{"description": "option end-tag followed by option start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "option"], ["StartTag", "http://www.w3.org/1999/xhtml", "option", {}]],
"expected": ["<option>"]
},
{"description": "option end-tag followed by end-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "option"], ["EndTag", "http://www.w3.org/1999/xhtml", "foo"]],
"expected": ["</foo>"]
},
{"description": "option end-tag at EOF",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "option"]],
"expected": [""]
},
{"description": "colgroup start-tag followed by comment",
"input": [["StartTag", "http://www.w3.org/1999/xhtml", "colgroup", {}], ["Comment", "foo"]],
"expected": ["<colgroup><!--foo-->"]
},
{"description": "colgroup start-tag followed by space character",
"input": [["StartTag", "http://www.w3.org/1999/xhtml", "colgroup", {}], ["Characters", " foo"]],
"expected": ["<colgroup> foo"]
},
{"description": "colgroup start-tag followed by text",
"input": [["StartTag", "http://www.w3.org/1999/xhtml", "colgroup", {}], ["Characters", "foo"]],
"expected": ["<colgroup>foo"]
},
{"description": "colgroup start-tag followed by start-tag",
"input": [["StartTag", "http://www.w3.org/1999/xhtml", "colgroup", {}], ["StartTag", "http://www.w3.org/1999/xhtml", "foo", {}]],
"expected": ["<colgroup><foo>"]
},
{"description": "first colgroup in a table with a col child",
"input": [["StartTag", "http://www.w3.org/1999/xhtml", "table", {}], ["StartTag", "http://www.w3.org/1999/xhtml", "colgroup", {}], ["EmptyTag", "col", {}]],
"expected": ["<table><col>"]
},
{"description": "colgroup with a col child, following another colgroup",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "colgroup"], ["StartTag", "http://www.w3.org/1999/xhtml", "colgroup", {}], ["StartTag", "http://www.w3.org/1999/xhtml", "col", {}]],
"expected": ["</colgroup><col>", "<colgroup><col>"]
},
{"description": "colgroup start-tag followed by end-tag",
"input": [["StartTag", "http://www.w3.org/1999/xhtml", "colgroup", {}], ["EndTag", "http://www.w3.org/1999/xhtml", "foo"]],
"expected": ["<colgroup></foo>"]
},
{"description": "colgroup start-tag at EOF",
"input": [["StartTag", "http://www.w3.org/1999/xhtml", "colgroup", {}]],
"expected": ["<colgroup>"]
},
{"description": "colgroup end-tag followed by comment",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "colgroup"], ["Comment", "foo"]],
"expected": ["</colgroup><!--foo-->"]
},
{"description": "colgroup end-tag followed by space character",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "colgroup"], ["Characters", " foo"]],
"expected": ["</colgroup> foo"]
},
{"description": "colgroup end-tag followed by text",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "colgroup"], ["Characters", "foo"]],
"expected": ["foo"]
},
{"description": "colgroup end-tag followed by start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "colgroup"], ["StartTag", "http://www.w3.org/1999/xhtml", "foo", {}]],
"expected": ["<foo>"]
},
{"description": "colgroup end-tag followed by end-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "colgroup"], ["EndTag", "http://www.w3.org/1999/xhtml", "foo"]],
"expected": ["</foo>"]
},
{"description": "colgroup end-tag at EOF",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "colgroup"]],
"expected": [""]
},
{"description": "thead end-tag followed by comment",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "thead"], ["Comment", "foo"]],
"expected": ["</thead><!--foo-->"]
},
{"description": "thead end-tag followed by space character",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "thead"], ["Characters", " foo"]],
"expected": ["</thead> foo"]
},
{"description": "thead end-tag followed by text",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "thead"], ["Characters", "foo"]],
"expected": ["</thead>foo"]
},
{"description": "thead end-tag followed by start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "thead"], ["StartTag", "http://www.w3.org/1999/xhtml", "foo", {}]],
"expected": ["</thead><foo>"]
},
{"description": "thead end-tag followed by tbody start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "thead"], ["StartTag", "http://www.w3.org/1999/xhtml", "tbody", {}]],
"expected": ["<tbody>"]
},
{"description": "thead end-tag followed by tfoot start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "thead"], ["StartTag", "http://www.w3.org/1999/xhtml", "tfoot", {}]],
"expected": ["<tfoot>"]
},
{"description": "thead end-tag followed by end-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "thead"], ["EndTag", "http://www.w3.org/1999/xhtml", "foo"]],
"expected": ["</thead></foo>"]
},
{"description": "thead end-tag at EOF",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "thead"]],
"expected": ["</thead>"]
},
{"description": "tbody start-tag followed by comment",
"input": [["StartTag", "http://www.w3.org/1999/xhtml", "tbody", {}], ["Comment", "foo"]],
"expected": ["<tbody><!--foo-->"]
},
{"description": "tbody start-tag followed by space character",
"input": [["StartTag", "http://www.w3.org/1999/xhtml", "tbody", {}], ["Characters", " foo"]],
"expected": ["<tbody> foo"]
},
{"description": "tbody start-tag followed by text",
"input": [["StartTag", "http://www.w3.org/1999/xhtml", "tbody", {}], ["Characters", "foo"]],
"expected": ["<tbody>foo"]
},
{"description": "tbody start-tag followed by start-tag",
"input": [["StartTag", "http://www.w3.org/1999/xhtml", "tbody", {}], ["StartTag", "http://www.w3.org/1999/xhtml", "foo", {}]],
"expected": ["<tbody><foo>"]
},
{"description": "first tbody in a table with a tr child",
"input": [["StartTag", "http://www.w3.org/1999/xhtml", "table", {}], ["StartTag", "http://www.w3.org/1999/xhtml", "tbody", {}], ["StartTag", "http://www.w3.org/1999/xhtml", "tr", {}]],
"expected": ["<table><tr>"]
},
{"description": "tbody with a tr child, following another tbody",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "tbody"], ["StartTag", "http://www.w3.org/1999/xhtml", "tbody", {}], ["StartTag", "http://www.w3.org/1999/xhtml", "tr", {}]],
"expected": ["<tbody><tr>", "</tbody><tr>"]
},
{"description": "tbody with a tr child, following a thead",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "thead"], ["StartTag", "http://www.w3.org/1999/xhtml", "tbody", {}], ["StartTag", "http://www.w3.org/1999/xhtml", "tr", {}]],
"expected": ["<tbody><tr>", "</thead><tr>"]
},
{"description": "tbody with a tr child, following a tfoot",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "tfoot"], ["StartTag", "http://www.w3.org/1999/xhtml", "tbody", {}], ["StartTag", "http://www.w3.org/1999/xhtml", "tr", {}]],
"expected": ["<tbody><tr>", "</tfoot><tr>"]
},
{"description": "tbody start-tag followed by end-tag",
"input": [["StartTag", "http://www.w3.org/1999/xhtml", "tbody", {}], ["EndTag", "http://www.w3.org/1999/xhtml", "foo"]],
"expected": ["<tbody></foo>"]
},
{"description": "tbody start-tag at EOF",
"input": [["StartTag", "http://www.w3.org/1999/xhtml", "tbody", {}]],
"expected": ["<tbody>"]
},
{"description": "tbody end-tag followed by comment",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "tbody"], ["Comment", "foo"]],
"expected": ["</tbody><!--foo-->"]
},
{"description": "tbody end-tag followed by space character",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "tbody"], ["Characters", " foo"]],
"expected": ["</tbody> foo"]
},
{"description": "tbody end-tag followed by text",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "tbody"], ["Characters", "foo"]],
"expected": ["</tbody>foo"]
},
{"description": "tbody end-tag followed by start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "tbody"], ["StartTag", "http://www.w3.org/1999/xhtml", "foo", {}]],
"expected": ["</tbody><foo>"]
},
{"description": "tbody end-tag followed by tbody start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "tbody"], ["StartTag", "http://www.w3.org/1999/xhtml", "tbody", {}]],
"expected": ["<tbody>", "</tbody>"]
},
{"description": "tbody end-tag followed by tfoot start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "tbody"], ["StartTag", "http://www.w3.org/1999/xhtml", "tfoot", {}]],
"expected": ["<tfoot>"]
},
{"description": "tbody end-tag followed by end-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "tbody"], ["EndTag", "http://www.w3.org/1999/xhtml", "foo"]],
"expected": ["</foo>"]
},
{"description": "tbody end-tag at EOF",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "tbody"]],
"expected": [""]
},
{"description": "tfoot end-tag followed by comment",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "tfoot"], ["Comment", "foo"]],
"expected": ["</tfoot><!--foo-->"]
},
{"description": "tfoot end-tag followed by space character",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "tfoot"], ["Characters", " foo"]],
"expected": ["</tfoot> foo"]
},
{"description": "tfoot end-tag followed by text",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "tfoot"], ["Characters", "foo"]],
"expected": ["</tfoot>foo"]
},
{"description": "tfoot end-tag followed by start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "tfoot"], ["StartTag", "http://www.w3.org/1999/xhtml", "foo", {}]],
"expected": ["</tfoot><foo>"]
},
{"description": "tfoot end-tag followed by tbody start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "tfoot"], ["StartTag", "http://www.w3.org/1999/xhtml", "tbody", {}]],
"expected": ["<tbody>", "</tfoot>"]
},
{"description": "tfoot end-tag followed by end-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "tfoot"], ["EndTag", "http://www.w3.org/1999/xhtml", "foo"]],
"expected": ["</foo>"]
},
{"description": "tfoot end-tag at EOF",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "tfoot"]],
"expected": [""]
},
{"description": "tr end-tag followed by comment",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "tr"], ["Comment", "foo"]],
"expected": ["</tr><!--foo-->"]
},
{"description": "tr end-tag followed by space character",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "tr"], ["Characters", " foo"]],
"expected": ["</tr> foo"]
},
{"description": "tr end-tag followed by text",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "tr"], ["Characters", "foo"]],
"expected": ["</tr>foo"]
},
{"description": "tr end-tag followed by start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "tr"], ["StartTag", "http://www.w3.org/1999/xhtml", "foo", {}]],
"expected": ["</tr><foo>"]
},
{"description": "tr end-tag followed by tr start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "tr"], ["StartTag", "http://www.w3.org/1999/xhtml", "tr", {}]],
"expected": ["<tr>", "</tr>"]
},
{"description": "tr end-tag followed by end-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "tr"], ["EndTag", "http://www.w3.org/1999/xhtml", "foo"]],
"expected": ["</foo>"]
},
{"description": "tr end-tag at EOF",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "tr"]],
"expected": [""]
},
{"description": "td end-tag followed by comment",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "td"], ["Comment", "foo"]],
"expected": ["</td><!--foo-->"]
},
{"description": "td end-tag followed by space character",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "td"], ["Characters", " foo"]],
"expected": ["</td> foo"]
},
{"description": "td end-tag followed by text",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "td"], ["Characters", "foo"]],
"expected": ["</td>foo"]
},
{"description": "td end-tag followed by start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "td"], ["StartTag", "http://www.w3.org/1999/xhtml", "foo", {}]],
"expected": ["</td><foo>"]
},
{"description": "td end-tag followed by td start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "td"], ["StartTag", "http://www.w3.org/1999/xhtml", "td", {}]],
"expected": ["<td>", "</td>"]
},
{"description": "td end-tag followed by th start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "td"], ["StartTag", "http://www.w3.org/1999/xhtml", "th", {}]],
"expected": ["<th>", "</td>"]
},
{"description": "td end-tag followed by end-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "td"], ["EndTag", "http://www.w3.org/1999/xhtml", "foo"]],
"expected": ["</foo>"]
},
{"description": "td end-tag at EOF",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "td"]],
"expected": [""]
},
{"description": "th end-tag followed by comment",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "th"], ["Comment", "foo"]],
"expected": ["</th><!--foo-->"]
},
{"description": "th end-tag followed by space character",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "th"], ["Characters", " foo"]],
"expected": ["</th> foo"]
},
{"description": "th end-tag followed by text",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "th"], ["Characters", "foo"]],
"expected": ["</th>foo"]
},
{"description": "th end-tag followed by start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "th"], ["StartTag", "http://www.w3.org/1999/xhtml", "foo", {}]],
"expected": ["</th><foo>"]
},
{"description": "th end-tag followed by th start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "th"], ["StartTag", "http://www.w3.org/1999/xhtml", "th", {}]],
"expected": ["<th>", "</th>"]
},
{"description": "th end-tag followed by td start-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "th"], ["StartTag", "http://www.w3.org/1999/xhtml", "td", {}]],
"expected": ["<td>", "</th>"]
},
{"description": "th end-tag followed by end-tag",
"input": [["EndTag", "http://www.w3.org/1999/xhtml", "th"], ["EndTag", "http://www.w3.org/1999/xhtml", "foo"]],
"expected": ["</foo>"]
},
{"description": "th end-tag at EOF",
"input": [["EndTag", "http://www.w3.org/1999/xhtml" , "th"]],
"expected": [""]
}
]}
| 35,315
|
Common Lisp
|
.l
| 726
| 45.486226
| 187
| 0.586116
|
rotatef/cl-html5-parser
| 55
| 14
| 11
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
10681e2dc03781691c4576e8bc8dd567f2431ca3892e2ac47e6b4fd364ad01f9
| 3,129
|
[
-1
] |
3,130
|
htmlOrFeed.json
|
rotatef_cl-html5-parser/tests/testdata/sniffer/htmlOrFeed.json
|
[
{"type": "text/html", "input": ""},
{"type": "text/html", "input": "<!---->"},
{"type": "text/html", "input": "<!--asdfaslkjdf;laksjdf as;dkfjsd-->"},
{"type": "text/html", "input": "<!"},
{"type": "text/html", "input": "\t"},
{"type": "text/html", "input": "<!>"},
{"type": "text/html", "input": "<?"},
{"type": "text/html", "input": "<??>"},
{"type": "application/rss+xml", "input": "<rss"},
{"type": "application/atom+xml", "input": "<feed"},
{"type": "text/html", "input": "<html"},
{"type": "text/html", "input": "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n<html><head>\n<title>302 Found</title>\n</head><body>\n<h1>Found</h1>\n<p>The document has moved <a href=\"http://feeds.feedburner.com/gofug\">here</a>.</p>\n</body></html>\n"},
{"type": "text/html", "input": "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\r\n<HTML><HEAD>\r\n <link rel=\"stylesheet\" type=\"text/css\" href=\"http://cache.blogads.com/289619328/feed.css\" /><link rel=\"stylesheet\" type=\"text/css\" href=\"http://cache.blogads.com/431602649/feed.css\" />\r\n<link rel=\"stylesheet\" type=\"text/css\" href=\"http://cache.blogads.com/382549546/feed.css\" />\r\n<link rel=\"stylesheet\" type=\"text/css\" href=\"http://cache.blogads.com/314618017/feed.css\" /><META http-equiv=\"expires\" content="},
{"type": "text/html", "input": "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\r\n<html>\r\n<head>\r\n<title>Xiaxue - Chicken pie blogger.</title><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"><style type=\"text/css\">\r\n<style type=\"text/css\">\r\n<!--\r\nbody {\r\n background-color: #FFF2F2;\r\n}\r\n.style1 {font-family: Georgia, \"Times New Roman\", Times, serif}\r\n.style2 {\r\n color: #8a567c;\r\n font-size: 14px;\r\n font-family: Georgia, \"Times New Roman\", Times, serif;\r\n}\r"},
{"type": "text/html", "input": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\r\n<head> \r\n<title>Google Operating System</title>\r\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\r\n<meta name=\"Description\" content=\"Unofficial news and tips about Google. A blog that watches Google's latest developments and the attempts to move your operating system online.\" />\r\n<meta name=\"generator\" c"},
{"type": "text/html", "input": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\r\n<head>\r\n <title>Assimilated Press</title> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\r\n<meta name=\"MSSmartTagsPreventParsing\" content=\"true\" />\r\n<meta name=\"generator\" content=\"Blogger\" />\r\n<link rel=\"alternate\" type=\"application/atom+xml\" title=\"Assimilated Press - Atom\" href=\"http://assimila"},
{"type": "text/html", "input": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\r\n<head>\r\n <title>PostSecret</title>\r\n<META name=\"keywords\" Content=\"secrets, postcard, secret, postcards, postsecret, postsecrets,online confessional, post secret, post secrets, artomatic, post a secret\"><META name=\"discription\" Content=\"See a Secret...Share a Secret\"> <meta http-equiv=\"Content-Type\" content=\"te"},
{"type": "text/html", "input": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns='http://www.w3.org/1999/xhtml' xmlns:b='http://www.google.com/2005/gml/b' xmlns:data='http://www.google.com/2005/gml/data' xmlns:expr='http://www.google.com/2005/gml/expr'>\n <head>\n \n <meta content='text/html; charset=UTF-8' http-equiv='Content-Type'/>\n <meta content='true' name='MSSmartTagsPreventParsing'/>\n <meta content='blogger' name='generator'/>\n <link rel=\"alternate\" typ"},
{"type": "text/html", "input": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" dir=\"ltr\" lang=\"ja\">\n<head profile=\"http://gmpg.org/xfn/11\"> \n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /> \n<title> CMS Lever</title><link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"http://s.wordpress.com/wp-content/themes/pub/twenty-eight/2813.css\"/>\n<link rel=\"alternate\" type=\"application/rss+xml\" title=\"RSS 2.0\" h"},
{"type": "text/html", "input": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" dir=\"ltr\" lang=\"en\"><head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n<title> Park Avenue Peerage</title>\t<meta name=\"generator\" content=\"WordPress.com\" />\t<!-- feeds -->\n\t<link rel=\"alternate\" type=\"application/rss+xml\" title=\"RSS 2.0\" href=\"http://parkavenuepeerage.wordpress.com/feed/\" />\t<link rel=\"pingback\" href="},
{"type": "text/html", "input": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" dir=\"ltr\" lang=\"ja\"><head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n<title> \u884c\u96f2\u6d41\u6c34 -like a floating clouds and running water-</title>\t<meta name=\"generator\" content=\"WordPress.com\" />\t<!-- feeds -->\n\t<link rel=\"alternate\" type=\"application/rss+xml\" title=\"RSS 2.0\" href=\"http://shw4.wordpress.com/feed/\" />\t<li"},
{"type": "text/html", "input": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n<meta name=\"generator\" content=\"http://www.typepad.com/\" />\n<title>Go Fug Yourself</title><link rel=\"stylesheet\" href=\"http://gofugyourself.typepad.com/go_fug_yourself/styles.css\" type=\"text/css\" />\n<link rel=\"alternate\" type=\"application/atom+xml\" title=\"Atom\" "},
{"type": "text/html", "input": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" dir=\"ltr\" lang=\"en\"><head profile=\"http://gmpg.org/xfn/11\">\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /><title> Ladies…</title><meta name=\"generator\" content=\"WordPress.com\" /> <!-- leave this for stats --><link rel=\"stylesheet\" href=\"http://s.wordpress.com/wp-content/themes/default/style.css?1\" type=\"tex"},
{"type": "text/html", "input": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n<head>\r\n <title>The Sartorialist</title> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\r\n<meta name=\"MSSmartTagsPreventParsing\" content=\"true\" />\r\n<meta name=\"generator\" content=\"Blogger\" />\r\n<link rel=\"alternate\" type=\"application/atom+xml\" title=\"The Sartorialist - Atom\" href=\"http://thesartorialist.blogspot"},
{"type": "text/html", "input": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\">\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\" />\n<meta name=\"generator\" content=\"http://www.typepad.com/\" />\n<title>Creating Passionate Users</title><link rel=\"stylesheet\" href=\"http://headrush.typepad.com/creating_passionate_users/styles.css\" type=\"text/css\" />\n<link rel=\"alternate\" type"},
{"type": "text/html", "input": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" id=\"sixapart-standard\">\n<head>\n\t<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n\t<meta name=\"generator\" content=\"http://www.typepad.com/\" />\n\t\n\t\n <meta name=\"keywords\" content=\"marketing, blog, seth, ideas, respect, permission\" />\n <meta name=\"description\" content=\"Seth Godin's riffs on marketing, respect, and the "},
{"type": "text/html", "input": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" id=\"sixapart-standard\">\n<head>\n\t<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n\t<meta name=\"generator\" content=\"http://www.typepad.com/\" />\n\t\n\t\n \n <meta name=\"description\" content=\" Western Civilization hangs in the balance. This blog is part of the solution,the cure. Get your heads out of the sand and Fight the G"},
{"type": "text/html", "input": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" dir=\"ltr\" lang=\"en\">\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=pahrefhttpwwwfeedburnercomtarget_blankimgsrchttpwwwfeedburnercomfbimagespubpowered_by_fbgifaltPoweredbyFeedBurnerstyleborder0ap\" />\n<title> From Under the Rotunda</title>\n<link rel=\"stylesheet\" href=\"http://s.wordpress.com/wp-content/themes/pub/andreas04/style.css\" type=\"text/css\""},
{"type": "application/atom+xml", "input": "<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href=\"http://www.blogger.com/styles/atom.css\" type=\"text/css\"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'><id>tag:blogger.com,1999:blog-10861780</id><updated>2007-07-27T12:38:50.888-07:00</updated><title type='text'>Official Google Blog</title><link rel='alternate' type='text/html' href='http://googleblog.blogspot.com/'/><link rel='next' type='application/atom+xml' href='http://googleblog.blogs"},
{"type": "application/rss+xml", "input": "<?xml version='1.0' encoding='UTF-8'?><rss xmlns:atom='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' version='2.0'><channel><atom:id>tag:blogger.com,1999:blog-10861780</atom:id><lastBuildDate>Fri, 27 Jul 2007 19:38:50 +0000</lastBuildDate><title>Official Google Blog</title><description/><link>http://googleblog.blogspot.com/</link><managingEditor>Eric Case</managingEditor><generator>Blogger</generator><openSearch:totalResults>729</openSearch:totalResults><openSearc"},
{"type": "application/rss+xml", "input": "<?xml version=\"1.0\" encoding=\"pahrefhttpwwwfeedburnercomtarget_blankimgsrchttpwwwfeedburnercomfbimagespubpowered_by_fbgifaltPoweredbyFeedBurnerstyleborder0ap\"?>\n<!-- generator=\"wordpress/MU\" -->\n<rss version=\"2.0\"\n\txmlns:content=\"http://purl.org/rss/1.0/modules/content/\"\n\txmlns:wfw=\"http://wellformedweb.org/CommentAPI/\"\n\txmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n\t><channel>\n\t<title>From Under the Rotunda</title>\n\t<link>http://dannybernardi.wordpress.com</link>\n\t<description>The Monographs of Danny Ber"},
{"type": "application/rss+xml", "input": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!-- generator=\"wordpress/MU\" -->\n<rss version=\"2.0\"\n\txmlns:content=\"http://purl.org/rss/1.0/modules/content/\"\n\txmlns:wfw=\"http://wellformedweb.org/CommentAPI/\"\n\txmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n\t><channel>\n\t<title>CMS Lever</title>\n\t<link>http://kanaguri.wordpress.com</link>\n\t<description>CMS\u306e\u6c17\u306b\u306a\u3063\u305f\u3053\u3068</description>\n\t<pubDate>Wed, 18 Jul 2007 21:26:22 +0000</pubDate>\n\t<generator>http://wordpress.org/?v=MU</generator>\n\t<language>ja</languag"},
{"type": "application/atom+xml", "input": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<feed xmlns=\"http://www.w3.org/2005/Atom\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:thr=\"http://purl.org/syndication/thread/1.0\">\n <title>Atlas Shrugs</title>\n <link rel=\"self\" type=\"application/atom+xml\" href=\"http://atlasshrugs2000.typepad.com/atlas_shrugs/atom.xml\" />\n <link rel=\"alternate\" type=\"text/html\" href=\"http://atlasshrugs2000.typepad.com/atlas_shrugs/\" />\n <id>tag:typepad.com,2003:weblog-132946</id>\n <updated>2007-08-15T16:07:34-04"},
{"type": "application/atom+xml", "input": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<?xml-stylesheet href=\"http://feeds.feedburner.com/~d/styles/atom10full.xsl\" type=\"text/xsl\" media=\"screen\"?><?xml-stylesheet href=\"http://feeds.feedburner.com/~d/styles/itemcontent.css\" type=\"text/css\" media=\"screen\"?><feed xmlns=\"http://www.w3.org/2005/Atom\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:thr=\"http://purl.org/syndication/thread/1.0\" xmlns:feedburner=\"http://rssnamespace.org/feedburner/ext/1.0\">\r\n <title>Creating Passionate Users</title>\r\n "},
{"type": "application/atom+xml", "input": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<?xml-stylesheet href=\"http://feeds.feedburner.com/~d/styles/atom10full.xsl\" type=\"text/xsl\" media=\"screen\"?><?xml-stylesheet href=\"http://feeds.feedburner.com/~d/styles/itemcontent.css\" type=\"text/css\" media=\"screen\"?><feed xmlns=\"http://www.w3.org/2005/Atom\" xmlns:feedburner=\"http://rssnamespace.org/feedburner/ext/1.0\">\r\n <title>Seth's Blog</title>\r\n <link rel=\"alternate\" type=\"text/html\" href=\"http://sethgodin.typepad.com/seths_blog/\" />\r\n <link rel=\"s"},
{"type": "application/atom+xml", "input": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<?xml-stylesheet href=\"http://feeds.feedburner.com/~d/styles/atom10full.xsl\" type=\"text/xsl\" media=\"screen\"?><?xml-stylesheet href=\"http://feeds.feedburner.com/~d/styles/itemcontent.css\" type=\"text/css\" media=\"screen\"?><feed xmlns=\"http://www.w3.org/2005/Atom\" xmlns:openSearch=\"http://a9.com/-/spec/opensearchrss/1.0/\" xmlns:feedburner=\"http://rssnamespace.org/feedburner/ext/1.0\"><id>tag:blogger.com,1999:blog-32454861</id><updated>2007-07-31T21:44:09.867+02:00</upd"},
{"type": "application/atom+xml", "input": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<?xml-stylesheet href=\"http://feeds.feedburner.com/~d/styles/atomfull.xsl\" type=\"text/xsl\" media=\"screen\"?><?xml-stylesheet href=\"http://feeds.feedburner.com/~d/styles/itemcontent.css\" type=\"text/css\" media=\"screen\"?><feed xmlns=\"http://purl.org/atom/ns#\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:feedburner=\"http://rssnamespace.org/feedburner/ext/1.0\" version=\"0.3\">\r\n <title>Go Fug Yourself</title>\r\n <link rel=\"alternate\" type=\"text/html\" href=\"http://go"},
{"type": "application/rss+xml", "input": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<?xml-stylesheet href=\"http://feeds.feedburner.com/~d/styles/rss2full.xsl\" type=\"text/xsl\" media=\"screen\"?><?xml-stylesheet href=\"http://feeds.feedburner.com/~d/styles/itemcontent.css\" type=\"text/css\" media=\"screen\"?><rss xmlns:creativeCommons=\"http://backend.userland.com/creativeCommonsRssModule\" xmlns:feedburner=\"http://rssnamespace.org/feedburner/ext/1.0\" version=\"2.0\"><channel><title>Google Operating System</title><link>http://googlesystem.blogspot.com/</link>"},
{"type": "application/rss+xml", "input": "<?xml version=\"1.0\" encoding=\"\"?>\n<!-- generator=\"wordpress/MU\" -->\n<rss version=\"2.0\"\n\txmlns:content=\"http://purl.org/rss/1.0/modules/content/\"\n\txmlns:wfw=\"http://wellformedweb.org/CommentAPI/\"\n\txmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n\t><channel>\n\t<title>Nunublog</title>\n\t<link>http://nunubh.wordpress.com</link>\n\t<description>Just Newbie Blog!</description>\n\t<pubDate>Mon, 09 Jul 2007 18:54:09 +0000</pubDate>\n\t<generator>http://wordpress.org/?v=MU</generator>\n\t<language>id</language>\n\t\t\t<item>\n\t\t<ti"},
{"type": "text/html", "input": "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\r\n<HEAD>\r\n<TITLE>Design*Sponge</TITLE><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\r\n<meta name=\"MSSmartTagsPreventParsing\" content=\"true\" />\r\n<meta name=\"generator\" content=\"Blogger\" />\r\n<link rel=\"alternate\" type=\"application/atom+xml\" title=\"Design*Sponge - Atom\" href=\"http://designsponge.blogspot.com/feeds/posts/default\" />\r\n<link rel=\"alternate\" type=\"application/rss+xml\" title=\"Design*Sponge - RSS\" href="},
{"type": "text/html", "input": "<HTML>\n<HEAD>\n<TITLE>Moved Temporarily</TITLE>\n</HEAD>\n<BODY BGCOLOR=\"#FFFFFF\" TEXT=\"#000000\">\n<H1>Moved Temporarily</H1>\nThe document has moved <A HREF=\"http://feeds.feedburner.com/thesecretdiaryofstevejobs\">here</A>.\n</BODY>\n</HTML>\n"}
]
| 17,365
|
Common Lisp
|
.l
| 43
| 399.046512
| 617
| 0.671535
|
rotatef/cl-html5-parser
| 55
| 14
| 11
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
ce18c4642cead03ab881cf6686502b0d746361b3e95e831c48eebf547b8ee3d6
| 3,130
|
[
-1
] |
3,131
|
unicodeCharsProblematic.test
|
rotatef_cl-html5-parser/tests/testdata/tokenizer/unicodeCharsProblematic.test
|
{"tests" : [
{"description": "Invalid Unicode character U+DFFF",
"doubleEscaped":true,
"input": "\\uDFFF",
"output":["ParseError", ["Character", "\\uFFFD"]]},
{"description": "Invalid Unicode character U+D800",
"doubleEscaped":true,
"input": "\\uD800",
"output":["ParseError", ["Character", "\\uFFFD"]]},
{"description": "Invalid Unicode character U+DFFF with valid preceding character",
"doubleEscaped":true,
"input": "a\\uDFFF",
"output":["ParseError", ["Character", "a\\uFFFD"]]},
{"description": "Invalid Unicode character U+D800 with valid following character",
"doubleEscaped":true,
"input": "\\uD800a",
"output":["ParseError", ["Character", "\\uFFFDa"]]},
{"description":"CR followed by U+0000",
"input":"\r\u0000",
"output":[["Character", "\n"], "ParseError", ["Character", "\u0000"]],
"ignoreErrorOrder":true}
]
}
| 826
|
Common Lisp
|
.l
| 23
| 34.782609
| 82
| 0.6825
|
rotatef/cl-html5-parser
| 55
| 14
| 11
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
5c0922edb0af851130ad50b67a1174e4f673c1b730ec29dd5617885ae4c77d6a
| 3,131
|
[
-1
] |
3,132
|
contentModelFlags.test
|
rotatef_cl-html5-parser/tests/testdata/tokenizer/contentModelFlags.test
|
{"tests": [
{"description":"PLAINTEXT content model flag",
"initialStates":["PLAINTEXT state"],
"lastStartTag":"plaintext",
"input":"<head>&body;",
"output":[["Character", "<head>&body;"]]},
{"description":"End tag closing RCDATA or RAWTEXT",
"initialStates":["RCDATA state", "RAWTEXT state"],
"lastStartTag":"xmp",
"input":"foo</xmp>",
"output":[["Character", "foo"], ["EndTag", "xmp"]]},
{"description":"End tag closing RCDATA or RAWTEXT (case-insensitivity)",
"initialStates":["RCDATA state", "RAWTEXT state"],
"lastStartTag":"xmp",
"input":"foo</xMp>",
"output":[["Character", "foo"], ["EndTag", "xmp"]]},
{"description":"End tag closing RCDATA or RAWTEXT (ending with space)",
"initialStates":["RCDATA state", "RAWTEXT state"],
"lastStartTag":"xmp",
"input":"foo</xmp ",
"output":[["Character", "foo"], "ParseError"]},
{"description":"End tag closing RCDATA or RAWTEXT (ending with EOF)",
"initialStates":["RCDATA state", "RAWTEXT state"],
"lastStartTag":"xmp",
"input":"foo</xmp",
"output":[["Character", "foo</xmp"]]},
{"description":"End tag closing RCDATA or RAWTEXT (ending with slash)",
"initialStates":["RCDATA state", "RAWTEXT state"],
"lastStartTag":"xmp",
"input":"foo</xmp/",
"output":[["Character", "foo"], "ParseError"]},
{"description":"End tag not closing RCDATA or RAWTEXT (ending with left-angle-bracket)",
"initialStates":["RCDATA state", "RAWTEXT state"],
"lastStartTag":"xmp",
"input":"foo</xmp<",
"output":[["Character", "foo</xmp<"]]},
{"description":"End tag with incorrect name in RCDATA or RAWTEXT",
"initialStates":["RCDATA state", "RAWTEXT state"],
"lastStartTag":"xmp",
"input":"</foo>bar</xmp>",
"output":[["Character", "</foo>bar"], ["EndTag", "xmp"]]},
{"description":"End tag with incorrect name in RCDATA or RAWTEXT (starting like correct name)",
"initialStates":["RCDATA state", "RAWTEXT state"],
"lastStartTag":"xmp",
"input":"</foo>bar</xmpaar>",
"output":[["Character", "</foo>bar</xmpaar>"]]},
{"description":"End tag closing RCDATA or RAWTEXT, switching back to PCDATA",
"initialStates":["RCDATA state", "RAWTEXT state"],
"lastStartTag":"xmp",
"input":"foo</xmp></baz>",
"output":[["Character", "foo"], ["EndTag", "xmp"], ["EndTag", "baz"]]},
{"description":"RAWTEXT w/ something looking like an entity",
"initialStates":["RAWTEXT state"],
"lastStartTag":"xmp",
"input":"&foo;",
"output":[["Character", "&foo;"]]},
{"description":"RCDATA w/ an entity",
"initialStates":["RCDATA state"],
"lastStartTag":"textarea",
"input":"<",
"output":[["Character", "<"]]}
]}
| 2,521
|
Common Lisp
|
.l
| 62
| 39.451613
| 95
| 0.675797
|
rotatef/cl-html5-parser
| 55
| 14
| 11
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
00414eb1e7c0ab21ef6ef853e113100acdb676c91b90b98d97d009fc32db5306
| 3,132
|
[
-1
] |
3,133
|
escapeFlag.test
|
rotatef_cl-html5-parser/tests/testdata/tokenizer/escapeFlag.test
|
{"tests": [
{"description":"Commented close tag in RCDATA or RAWTEXT",
"initialStates":["RCDATA state", "RAWTEXT state"],
"lastStartTag":"xmp",
"input":"foo<!--</xmp>--></xmp>",
"output":[["Character", "foo<!--"], ["EndTag", "xmp"], ["Character", "-->"], ["EndTag", "xmp"]]},
{"description":"Bogus comment in RCDATA or RAWTEXT",
"initialStates":["RCDATA state", "RAWTEXT state"],
"lastStartTag":"xmp",
"input":"foo<!-->baz</xmp>",
"output":[["Character", "foo<!-->baz"], ["EndTag", "xmp"]]},
{"description":"End tag surrounded by bogus comment in RCDATA or RAWTEXT",
"initialStates":["RCDATA state", "RAWTEXT state"],
"lastStartTag":"xmp",
"input":"foo<!--></xmp><!-->baz</xmp>",
"output":[["Character", "foo<!-->"], ["EndTag", "xmp"], "ParseError", ["Comment", ""], ["Character", "baz"], ["EndTag", "xmp"]]},
{"description":"Commented entities in RCDATA",
"initialStates":["RCDATA state"],
"lastStartTag":"xmp",
"input":" & <!-- & --> & </xmp>",
"output":[["Character", " & <!-- & --> & "], ["EndTag", "xmp"]]},
{"description":"Incorrect comment ending sequences in RCDATA or RAWTEXT",
"initialStates":["RCDATA state", "RAWTEXT state"],
"lastStartTag":"xmp",
"input":"foo<!-- x --x>x-- >x--!>x--<></xmp>",
"output":[["Character", "foo<!-- x --x>x-- >x--!>x--<>"], ["EndTag", "xmp"]]}
]}
| 1,306
|
Common Lisp
|
.l
| 27
| 47.148148
| 129
| 0.597015
|
rotatef/cl-html5-parser
| 55
| 14
| 11
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
1fac5089737b5aa2d2461ee7c26807553c43b9d0d16b2e985f099b43a8a6cc69
| 3,133
|
[
-1
] |
3,134
|
xmlViolation.test
|
rotatef_cl-html5-parser/tests/testdata/tokenizer/xmlViolation.test
|
{"xmlViolationTests": [
{"description":"Non-XML character",
"input":"a\uFFFFb",
"ignoreErrorOrder":true,
"output":["ParseError",["Character","a\uFFFDb"]]},
{"description":"Non-XML space",
"input":"a\u000Cb",
"ignoreErrorOrder":true,
"output":[["Character","a b"]]},
{"description":"Double hyphen in comment",
"input":"<!-- foo -- bar -->",
"output":["ParseError",["Comment"," foo - - bar "]]},
{"description":"FF between attributes",
"input":"<a b=''\u000Cc=''>",
"output":[["StartTag","a",{"b":"","c":""}]]}
]}
| 518
|
Common Lisp
|
.l
| 16
| 31
| 53
| 0.625
|
rotatef/cl-html5-parser
| 55
| 14
| 11
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
3ac617dab355d2d0b0f2dfac86e4698a098f8ba1d42bd6b32a27a6a827233d55
| 3,134
|
[
-1
] |
3,150
|
package.lisp
|
chunsj_TH/package.lisp
|
(defpackage :th
(:use #:common-lisp
#:mu)
(:import-from #:cffi)
(:export #:generator
#:storage.byte
#:storage.char
#:storage.short
#:storage.int
#:storage.long
#:storage.float
#:storage.double
#:tensor.byte
#:tensor.char
#:tensor.short
#:tensor.int
#:tensor.long
#:tensor.float
#:tensor.double
#:tensor
#:eye
#:linspace
#:logspace
#:zeros
#:ones
#:filled
#:range
#:arange
#:rnd
#:rndn
#:rndperm
#:$seed
#:$random
#:$uniform
#:$discrete-uniform
#:$normal
#:$exponential
#:$poisson
#:$cauchy
#:$lognormal
#:$geometric
#:$hypergeometric
#:$bernoulli
#:$binomial
#:$beta
#:$gamma
#:$chisq
#:$fdist
#:random/random
#:random/uniform
#:random/discrete-uniform
#:random/normal
#:random/exponential
#:random/poisson
#:random/cauchy
#:random/lognormal
#:random/geometric
#:random/hypergeometric
#:random/bernoulli
#:random/binomial
#:random/beta
#:random/gamma
#:random/chisq
#:random/fdist
#:$storagep
#:$tensorp
#:$empty
#:$list
#:$handle
#:$pointer
#:$type
#:$storage
#:$offset
#:$ndim
#:$size
#:$stride
#:$coerce
#:$acoerce
#:$contiguous!
#:$contiguousp
#:$resize!
#:$copy!
#:$swap!
#:$expand
#:$expand!
#:$fill
#:$fill!
#:$zero
#:$zero!
#:$one
#:$one!
#:$clone
#:$sizep
#:$set!
#:$setp
#:$transpose
#:$transpose!
#:$view
#:$subview
#:$select
#:$select!
#:$narrow
#:$narrow!
#:$unfold
#:$unfold!
#:$index
#:$gather
#:$scatter!
#:$masked
#:$squeeze
#:$squeeze!
#:$unsqueeze
#:$unsqueeze!
#:$permute
#:$split
#:$chunk
#:$cat
#:$catn
#:$repeat
#:$reshape
#:$reshape!
#:$diag
#:$diag!
#:$eye
#:$eye!
#:$tril
#:$tril!
#:$triu
#:$triu!
#:$compare
#:$lt
#:$le
#:$gt
#:$ge
#:$eq
#:$ne
#:$nonzero
#:$fmap
#:$fmap!
#:$abs
#:$abs!
#:$sign
#:$sign!
#:$acos
#:$acos!
#:$asin
#:$asin!
#:$atan
#:$atan!
#:$atan2
#:$atan2!
#:$ceil
#:$ceil!
#:$cos
#:$cos!
#:$cosh
#:$cosh!
#:$exp
#:$exp!
#:$floor
#:$floor!
#:$log
#:$log!
#:$logit
#:$invlogit
#:$log1p
#:$log1p!
#:$lgammaf
#:$lgammaf!
#:$gammaf
#:$gammaf!
#:$betaf
#:$betaf!
#:$erf
#:$erf!
#:$erfc
#:$erfc!
#:$lbetaf
#:$lbetaf!
#:$polygamma
#:$polygamma!
#:$neg
#:$neg!
#:$cinv
#:$cinv!
#:$expt
#:$expt!
#:$round
#:$round!
#:$sin
#:$sin!
#:$sinh
#:$sinh!
#:$sqrt
#:$sqrt!
#:$rsqrt
#:$rsqrt!
#:$tan
#:$tan!
#:$tanh
#:$tanh!
#:$sigmoid
#:$sigmoid!
#:$trunc
#:$trunc!
#:$frac
#:$frac!
#:$equal
#:$clamp
#:$clamp!
#:$fmod
#:$fmod!
#:$rem
#:$rem!
#:$dot
#:$axpy
#:$axpy!
#:$gemv
#:$gemv!
#:$ger
#:$ger!
#:$gemm
#:$gemm!
#:$add
#:$add!
#:$sub
#:$sub!
#:$mul
#:$mul!
#:$div
#:$div!
#:$addmul
#:$addmul!
#:$adddiv
#:$adddiv!
#:$addmv
#:$addmv!
#:$addr
#:$addr!
#:$addmm
#:$addmm!
#:$addbmm
#:$addbmm!
#:$baddbmm
#:$baddbamm!
#:$vv
#:$vv!
#:$xx
#:$xx!
#:$mv
#:$mv!
#:$mm
#:$mm!
#:$bmm
#:$bmm!
#:$+
#:$-
#:$*
#:$@
#:$/
#:$cumprd
#:$cumprd!
#:$cumsum
#:$cumsum!
#:$max*
#:$max
#:$max!
#:$min*
#:$min
#:$min!
#:$cmax
#:$cmax!
#:$cmin
#:$cmin!
#:$mean
#:$mean!
#:$median
#:$median!
#:$mode
#:$mode!
#:$kth
#:$kth!
#:$topk
#:$topk!
#:$sort
#:$sort!
#:$prd
#:$prd!
#:$sum
#:$sum!
#:$sd
#:$sd!
#:$var
#:$var!
#:$uniform!
#:$discrete-uniform!
#:$normal!
#:$exponential!
#:$poisson!
#:$bernoulli!
#:$binomial!
#:$beta!
#:$gamma!
#:$geometric!
#:$hypergeometric!
#:$chisq!
#:$fdist!
#:$norm
#:$norm!
#:$renorm
#:$renorm!
#:$dist
#:$trace
#:$conv2
#:$conv2!
#:$xcorr2
#:$xcorr2!
#:$conv3
#:$conv3!
#:$xcorr3
#:$xcorr3!
#:$gesv
#:$gesv!
#:$trtrs
#:$trtrs!
#:$potrf
#:$potrf!
#:$cholesky
#:$cholesky!
#:$pstrf
#:$pstrf!
#:$potrs
#:$potrs!
#:$potri
#:$potri!
#:$gels
#:$gels!
#:$syev
#:$syev!
#:$ev
#:$ev!
#:$svd
#:$svd!
#:$rsvd
#:$inverse
#:$inverse!
#:$qr
#:$qr!
#:$multinomial
#:file.disk
#:file.pipe
#:file.memory
#:$fopenedp
#:$fquietp
#:$fpedanticp
#:$freadablep
#:$fwritablep
#:$fbinaryp
#:$fasciip
#:$fautospacingp
#:$fnoautospacingp
#:$ferrorp
#:$freadbyte
#:$freadchar
#:$freadshort
#:$freadint
#:$freadlong
#:$freadfloat
#:$freaddouble
#:$fread
#:$fwritebyte
#:$fwritechar
#:$fwriteshort
#:$fwriteint
#:$fwritelong
#:$fwritefloat
#:$fwritedouble
#:$fwrite
#:$fsync
#:$feek
#:$fseekend
#:$ftell
#:$fclose
#:$fname
#:$percentile
#:$cv
#:$se
#:node
#:parameters
#:$push
#:$parameter
#:$parameters
#:$data
#:$gradient
#:$parameterp
#:$append
#:$broadcast
#:$clear
#:$krows
#:$kcols
#:$gs!
#:$cg!
#:$reset!
#:$gd!
#:$mgd!
#:$agd!
#:$amgd!
#:$rmgd!
#:$adgd!
#:$rpgd!
#:$bce
#:$bce*
#:$cee
#:$mse
#:$cnll
#:$cec
#:$square
#:$relu
#:$lrelu
#:$elu
#:$selu
#:$softmax
#:$logsoftmax
#:$softplus
#:$mish
#:$swish
#:$gelu
#:$celu
#:$bnorm
#:$bn
#:$dropout
#:$conv1d
#:$maxpool1d
#:$rowconv1d
#:$conv2d
#:$maxpool2d
#:$avgpool2d
#:$dlconv2d
#:$dlmaxpool2d
#:$dconv2d
#:$affine
#:$affine2
#:$addm2
#:$xwpb
#:$choice
#:$wimb
#:$wemb
#:$embedding
#:$emb
#:$array
#:$argmax
#:$argmin
#:$scalar
#:$diagflat
#:$incf
#:$decf
#:$acv
#:$acr
#:$slice
#:random-normals
#:$rnn
#:$lstm
#:$rn!
#:$ru!
#:$rnt!
#:$xavieru!
#:$xaviern!
#:$heu!
#:$hen!
#:$lecunu!
#:$lecunn!
#:vrn
#:vru
#:vrnt
#:vxavier
#:vhe
#:vlecun
#:vselu
#:score/bernoulli
#:score/binomial
#:score/categorical
#:score/discrete-uniform
#:score/poisson
#:score/beta
#:score/cauchy
#:score/exponential
#:score/gaussian
#:score/normal
#:score/uniform
#:sample/bernoulli
#:sample/binomial
#:sample/categorical
#:sample/discrete-uniform
#:sample/poisson
#:sample/beta
#:sample/cauchy
#:sample/exponential
#:sample/gaussian
#:sample/normal
#:sample/uniform
#:with-max-heap))
| 10,693
|
Common Lisp
|
.lisp
| 501
| 9.42515
| 36
| 0.301217
|
chunsj/TH
| 59
| 8
| 0
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
8ec869b4acc2e680897224793fcf75848bad652732616eabbeef53cfe239cd42
| 3,150
|
[
-1
] |
3,151
|
gaussian.lisp
|
chunsj_TH/pd/gaussian.lisp
|
(in-package :th)
(defgeneric score/gaussian (data mean sd))
(defgeneric sample/gaussian (mean sd &optional n))
(defun score/normal (data mean sd) (score/gaussian data mean sd))
(defun sample/normal (mean sd &optional (n 1)) (sample/gaussian mean sd n))
(defun of-gaussian-p (sd) (of-plusp sd))
(defun log-gaussian (data mean sd)
(when (of-gaussian-p sd)
(let ((z (if ($tensorp data) ($sub data mean) (- data mean)))
(n (* (if ($tensorp data) ($count data) 1) (log (* 2 pi))))
(s ($square sd)))
(if ($tensorp data)
(list (* -0.5 (+ n ($sum ($add ($log s) ($div ($square z) s)))))
z)
(list (* -0.5 (+ n (+ (log s) (/ ($square z) s))))
z)))))
(defun dlog-gaussian/dmean (z sd)
(if ($tensorp z)
(* (/ 1 (* sd sd)) ($sum z))
(* (/ 1 (* sd sd)) z)))
(defun dlog-gaussian/ddata (z sd)
(if ($tensorp z)
(* (/ -1 (* sd sd)) ($sum z))
(* (/ -1 (* sd sd)) z)))
(defun dlog-gaussian/dsd (z sd)
(if ($tensorp z)
(* (- (/ 1 sd)) (- ($count z) (/ ($sum ($square z)) (* sd sd))))
(* (- (/ 1 sd)) (- 1 (/ ($square z) (* sd sd))))))
(defmethod score/gaussian ((data number) (mean number) (sd number))
(car (log-gaussian data mean sd)))
(defmethod score/gaussian ((data number) (mean node) (sd number))
(let ((res (log-gaussian data ($data mean) sd)))
(when res
(node (car res)
:name :gaussian
:link (link (to mean ($mul (dlog-gaussian/dmean (cadr res) sd) gv)))))))
(defmethod score/gaussian ((data number) (mean number) (sd node))
(let ((res (log-gaussian data mean ($data sd))))
(when res
(node (car res)
:name :gaussian
:link (link (to sd ($mul (dlog-gaussian/dsd (cadr res) ($data sd)) gv)))))))
(defmethod score/gaussian ((data number) (mean node) (sd node))
(let ((res (log-gaussian data ($data mean) ($data sd))))
(when res
(node (car res)
:name :gaussian
:link (link
(to mean ($mul (dlog-gaussian/dmean (cadr res) ($data sd)) gv))
(to sd ($mul (dlog-gaussian/dsd (cadr res) ($data sd)) gv)))))))
(defmethod score/gaussian ((data tensor) (mean number) (sd number))
(car (log-gaussian data mean sd)))
(defmethod score/gaussian ((data tensor) (mean tensor) (sd number))
(car (log-gaussian data mean sd)))
(defmethod score/gaussian ((data tensor) (mean tensor) (sd tensor))
(car (log-gaussian data mean sd)))
(defmethod score/gaussian ((data tensor) (mean node) (sd number))
(let ((res (log-gaussian data ($data mean) sd)))
(when res
(node (car res)
:name :gaussian
:link (link (to mean ($mul (dlog-gaussian/dmean (cadr res) sd) gv)))))))
(defmethod score/gaussian ((data tensor) (mean number) (sd node))
(let ((res (log-gaussian data mean ($data sd))))
(when res
(node (car res)
:name :gaussian
:link (link (to sd ($mul (dlog-gaussian/dsd (cadr res) ($data sd)) gv)))))))
(defmethod score/gaussian ((data tensor) (mean node) (sd node))
(let ((res (log-gaussian data ($data mean) ($data sd))))
(when res
(node (car res)
:name :gaussian
:link (link
(to mean ($mul (dlog-gaussian/dmean (cadr res) ($data sd)) gv))
(to sd ($mul (dlog-gaussian/dsd (cadr res) ($data sd)) gv)))))))
(defmethod score/gaussian ((data node) (mean number) (sd number))
(let ((res (log-gaussian ($data data) mean sd)))
(when res
(node (car res)
:name :gaussian
:link (link (to data ($mul (dlog-gaussian/ddata (cadr res) sd) gv)))))))
(defmethod score/gaussian ((data node) (mean node) (sd number))
(let ((res (log-gaussian ($data data) ($data mean) sd)))
(when res
(node (car res)
:name :gaussian
:link (link
(to data ($mul (dlog-gaussian/ddata (cadr res) sd) gv))
(to mean ($mul (dlog-gaussian/dmean (cadr res) sd) gv)))))))
(defmethod score/gaussian ((data node) (mean number) (sd node))
(let ((res (log-gaussian ($data data) mean ($data sd))))
(when res
(node (car res)
:name :gaussian
:link (link
(to data ($mul (dlog-gaussian/ddata (cadr res) ($data sd)) gv))
(to sd ($mul (dlog-gaussian/dsd (cadr res) ($data sd)) gv)))))))
(defmethod score/gaussian ((data node) (mean node) (sd node))
(let ((res (log-gaussian ($data data) ($data mean) ($data sd))))
(when res
(node (car res)
:name :gaussian
:link (link
(to data ($mul (dlog-gaussian/ddata (cadr res) ($data sd)) gv))
(to mean ($mul (dlog-gaussian/dmean (cadr res) ($data sd)) gv))
(to sd ($mul (dlog-gaussian/dsd (cadr res) ($data sd)) gv)))))))
(defmethod sample/gaussian ((mean number) (sd number) &optional (n 1))
(cond ((= n 1) (random/normal mean sd))
((> n 1) ($normal! (tensor n) mean sd))))
(defmethod sample/gaussian ((mean node) (sd number) &optional (n 1))
(cond ((= n 1) (random/normal ($data mean) sd))
((> n 1) ($normal! (tensor n) ($data mean) sd))))
(defmethod sample/gaussian ((mean number) (sd node) &optional (n 1))
(cond ((= n 1) (random/normal mean ($data sd)))
((> n 1) ($normal! (tensor n) mean ($data sd)))))
(defmethod sample/gaussian ((mean node) (sd node) &optional (n 1))
(cond ((= n 1) (random/normal ($data mean) ($data sd)))
((> n 1) ($normal! (tensor n) ($data mean) ($data sd)))))
| 5,610
|
Common Lisp
|
.lisp
| 119
| 39.596639
| 88
| 0.558361
|
chunsj/TH
| 59
| 8
| 0
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
c7d8beecd492f1c455d0b95186d36bb6b74c2e2a52fd388250e03ec0ba367890
| 3,151
|
[
-1
] |
3,152
|
beta.lisp
|
chunsj_TH/pd/beta.lisp
|
(in-package :th)
(defgeneric score/beta (data alpha beta))
(defgeneric sample/beta (alpha beta &optional n))
(defun of-beta-p (data alpha beta)
(and (of-unit-interval-p data) (of-plusp alpha) (of-plusp beta)))
(defun beta/clamp (data) ($clamp data 1E-7 (- 1 1E-7)))
(defmethod score/beta ((data number) (alpha number) (beta number))
(when (of-beta-p data alpha beta)
(let ((data (beta/clamp data)))
(+ (* (- alpha 1) (log data))
(* (- beta 1) (log (- 1 data)))
(- ($lbetaf alpha beta))))))
(defmethod score/beta ((data number) (alpha node) (beta number))
(when (of-beta-p data ($data alpha) beta)
(let ((data (beta/clamp data)))
($sub ($add ($mul ($sub alpha 1) (log data))
(* (- beta 1) (log (- 1 data))))
($lbetaf alpha beta)))))
(defmethod score/beta ((data number) (alpha number) (beta node))
(when (of-beta-p data alpha ($data beta))
(let ((data (beta/clamp data)))
($sub ($add (* (- alpha 1) (log data))
($mul ($sub beta 1) (log (- 1 data))))
($lbetaf alpha beta)))))
(defmethod score/beta ((data number) (alpha node) (beta node))
(when (of-beta-p data ($data alpha) ($data beta))
(let ((data (beta/clamp data)))
($sub ($add ($mul ($sub alpha 1) (log data))
($mul ($sub beta 1) (log (- 1 data))))
($lbetaf alpha beta)))))
(defmethod score/beta ((data tensor) (alpha number) (beta number))
(when (of-beta-p data alpha beta)
($sum ($sub ($add ($mul (- alpha 1) ($log data))
($mul (- beta 1) ($log ($sub 1 data))))
($lbetaf alpha beta)))))
(defmethod score/beta ((data tensor) (alpha node) (beta number))
(when (of-beta-p data ($data alpha) beta)
($sum ($sub ($add ($mul ($sub alpha 1) ($log data))
($mul (- beta 1) ($log ($sub 1 data))))
($lbetaf alpha beta)))))
(defmethod score/beta ((data tensor) (alpha number) (beta node))
(when (of-beta-p data alpha ($data beta))
($sum ($sub ($add ($mul (- alpha 1) ($log data))
($mul ($sub beta 1) ($log ($sub 1 data))))
($lbetaf alpha beta)))))
(defmethod score/beta ((data tensor) (alpha node) (beta node))
(when (of-beta-p data ($data alpha) ($data beta))
($sum ($sub ($add ($mul ($sub alpha 1) ($log data))
($mul ($sub beta 1) ($log ($sub 1 data))))
($lbetaf alpha beta)))))
(defmethod score/beta ((data node) (alpha number) (beta number))
(when (of-beta-p ($data data) alpha beta)
($sum ($sub ($add ($mul (- alpha 1) ($log data))
($mul (- beta 1) ($log ($sub 1 data))))
($lbetaf alpha beta)))))
(defmethod score/beta ((data node) (alpha node) (beta number))
(when (of-beta-p ($data data) ($data alpha) beta)
($sum ($sub ($add ($mul ($sub alpha 1) ($log data))
($mul (- beta 1) ($log ($sub 1 data))))
($lbetaf alpha beta)))))
(defmethod score/beta ((data node) (alpha number) (beta node))
(when (of-beta-p ($data data) alpha ($data beta))
($sum ($sub ($add ($mul (- alpha 1) ($log data))
($mul ($sub beta 1) ($log ($sub 1 data))))
($lbetaf alpha beta)))))
(defmethod score/beta ((data node) (alpha node) (beta node))
(when (of-beta-p ($data data) ($data alpha) ($data beta))
($sum ($sub ($add ($mul ($sub alpha 1) ($log data))
($mul ($sub beta 1) ($log ($sub 1 data))))
($lbetaf alpha beta)))))
(defmethod sample/beta ((alpha number) (beta number) &optional (n 1))
(cond ((= n 1) (random/beta alpha beta))
((> n 1) ($beta! (tensor n) alpha beta))))
(defmethod sample/beta ((alpha node) (beta number) &optional (n 1))
(cond ((= n 1) (random/beta ($data alpha) beta))
((> n 1) ($beta! (tensor n) ($data alpha) beta))))
(defmethod sample/beta ((alpha number) (beta node) &optional (n 1))
(cond ((= n 1) (random/beta alpha ($data beta)))
((> n 1) ($beta! (tensor n) alpha ($data beta)))))
(defmethod sample/beta ((alpha node) (beta node) &optional (n 1))
(cond ((= n 1) (random/beta ($data alpha) ($data beta)))
((> n 1) ($beta! (tensor n) ($data alpha) ($data beta)))))
| 4,285
|
Common Lisp
|
.lisp
| 82
| 44.317073
| 69
| 0.546606
|
chunsj/TH
| 59
| 8
| 0
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
1ee4932d9b8edad726b98e0cf72b1d3648c53047e55361e182e6397259c0a270
| 3,152
|
[
-1
] |
3,153
|
poisson.lisp
|
chunsj_TH/pd/poisson.lisp
|
(in-package :th)
(defgeneric score/poisson (data rate))
(defgeneric sample/poisson (rate &optional n))
(defun of-poisson-p (data rate) (and (of-plusp rate) (of-ge data 0)))
(defmethod score/poisson ((data number) (rate number))
(when (of-poisson-p data rate)
(let ((lfac ($lgammaf (+ 1 data))))
(- (* data (log rate)) (+ rate lfac)))))
(defmethod score/poisson ((data number) (rate node))
(when (of-poisson-p data ($data rate))
(let ((lfac ($lgammaf (+ 1 data))))
($sub ($mul data ($log rate)) ($add rate lfac)))))
(defmethod score/poisson ((data tensor) (rate number))
(when (of-poisson-p data rate)
(let ((lfac ($lgammaf ($add 1 data))))
($sum ($sub ($mul data (log rate)) ($add rate lfac))))))
(defmethod score/poisson ((data tensor) (rate tensor))
(when (of-poisson-p data rate)
(let ((lfac ($lgammaf ($add 1 data))))
($sum ($sub ($mul data ($log rate)) ($add rate lfac))))))
(defmethod score/poisson ((data tensor) (rate node))
(when (of-poisson-p data ($data rate))
(let ((lfac ($lgammaf ($add 1 data))))
($sum ($sub ($mul data ($log rate)) ($add rate lfac))))))
(defmethod score/poisson ((data node) (rate number))
(when (of-poisson-p ($data data) rate)
(let ((lfac ($lgammaf ($add 1 data))))
($sum ($sub ($mul data (log rate)) ($add rate lfac))))))
(defmethod score/poisson ((data node) (rate node))
(when (of-poisson-p ($data data) ($data rate))
(let ((lfac ($lgammaf ($add 1 data))))
($sum ($sub ($mul data ($log rate)) ($add rate lfac))))))
(defmethod sample/poisson ((rate number) &optional (n 1))
(cond ((= n 1) (random/poisson rate))
((> n 1) ($poisson! (tensor n) rate))))
(defmethod sample/poisson ((rate node) &optional (n 1))
(cond ((= n 1) (random/poisson ($data rate)))
((> n 1) ($poisson! (tensor n) ($data rate)))))
| 1,853
|
Common Lisp
|
.lisp
| 38
| 44.736842
| 69
| 0.609756
|
chunsj/TH
| 59
| 8
| 0
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
0eccc4c463aa1266feeea05016df6c9cb8057b40ba61827901e477823a9a8e09
| 3,153
|
[
-1
] |
3,154
|
categorical.lisp
|
chunsj_TH/pd/categorical.lisp
|
(in-package :th)
(defgeneric score/categorical (data probs))
(defgeneric sample/categorical (probs &optional n))
(defun of-categorical-p (data probs)
(let ((n ($count probs)))
(and (of-ie data 0 (- n 1)) (of-ie probs 0 1))))
(defmethod score/categorical ((data number) (probs tensor))
(when (of-categorical-p data probs)
($sum ($gather ($log probs) 0 (tensor.long (list data))))))
(defmethod score/categorical ((data number) (probs node))
(when (of-categorical-p data ($data probs))
($sum ($gather ($log probs) 0 (tensor.long (list data))))))
(defmethod score/categorical ((data tensor) (probs tensor))
(when (of-categorical-p data probs)
($sum ($gather ($log probs) 0 (tensor.long data)))))
(defmethod score/categorical ((data tensor) (probs node))
(when (of-categorical-p data ($data probs))
($sum ($gather ($log probs) 0 (tensor.long data)))))
(defmethod score/categorical ((data node) (probs tensor))
(when (of-categorical-p ($data data) probs)
($sum ($gather ($log probs) 0 (tensor.long data)))))
(defmethod score/categorical ((data node) (probs node))
(when (of-categorical-p ($data data) ($data probs))
($sum ($gather ($log probs) 0 (tensor.long data)))))
(defmethod sample/categorical ((probs tensor) &optional (n 1))
(let ((s ($multinomial probs n)))
(cond ((= n 1) ($0 s))
((> n 1) s))))
(defmethod sample/categorical ((probs node) &optional (n 1))
(let ((s ($multinomial ($data probs) n)))
(cond ((= n 1) ($0 s))
((> n 1) s))))
| 1,523
|
Common Lisp
|
.lisp
| 32
| 43.96875
| 63
| 0.649561
|
chunsj/TH
| 59
| 8
| 0
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
71ed248b4f38591de34559cf8e979c306f62e665ec73b0e98f5417ea562074a0
| 3,154
|
[
-1
] |
3,155
|
uniform.lisp
|
chunsj_TH/pd/uniform.lisp
|
(in-package :th)
(defgeneric score/uniform (data lower upper))
(defgeneric sample/uniform (lower upper &optional n))
(defun of-uniform-p (data lower upper) (and (> upper lower) (of-ie data lower upper)))
(defmethod score/uniform ((data number) (lower number) (upper number))
(when (of-uniform-p data lower upper)
(- (log (- upper lower)))))
(defmethod score/uniform ((data number) (lower node) (upper number))
(when (of-uniform-p data ($data lower) upper)
($neg ($log ($sub upper lower)))))
(defmethod score/uniform ((data number) (lower number) (upper node))
(when (of-uniform-p data lower ($data upper))
($neg ($log ($sub upper lower)))))
(defmethod score/uniform ((data number) (lower node) (upper node))
(when (of-uniform-p data ($data lower) ($data upper))
($neg ($log ($sub upper lower)))))
(defmethod score/uniform ((data tensor) (lower number) (upper number))
(when (of-uniform-p data lower upper)
(let ((n ($count data)))
($mul (- n) ($log ($sub upper lower))))))
(defmethod score/uniform ((data tensor) (lower node) (upper number))
(when (of-uniform-p data ($data lower) upper)
(let ((n ($count data)))
($mul (- n) ($log ($sub upper lower))))))
(defmethod score/uniform ((data tensor) (lower number) (upper node))
(when (of-uniform-p data lower ($data upper))
(let ((n ($count data)))
($mul (- n) ($log ($sub upper lower))))))
(defmethod score/uniform ((data tensor) (lower node) (upper node))
(when (of-uniform-p data ($data lower) ($data upper))
(let ((n ($count data)))
($mul (- n) ($log ($sub upper lower))))))
(defmethod score/uniform ((data node) (lower number) (upper number))
(when (of-uniform-p ($data data) lower upper)
(let ((n (if ($tensorp data) ($count data) 1)))
($mul (- n) ($log ($sub upper lower))))))
(defmethod score/uniform ((data node) (lower node) (upper number))
(when (of-uniform-p data ($data lower) upper)
(let ((n (if ($tensorp data) ($count data) 1)))
($mul (- n) ($log ($sub upper lower))))))
(defmethod score/uniform ((data node) (lower number) (upper node))
(when (of-uniform-p ($data data) lower ($data upper))
(let ((n (if ($tensorp data) ($count data) 1)))
($mul (- n) ($log ($sub upper lower))))))
(defmethod score/uniform ((data node) (lower node) (upper node))
(when (of-uniform-p ($data data) ($data lower) ($data upper))
(let ((n (if ($tensorp data) ($count data) 1)))
($mul (- n) ($log ($sub upper lower))))))
(defmethod sample/uniform ((lower number) (upper number) &optional (n 1))
(cond ((= n 1) (random/uniform lower upper))
((> n 1) ($uniform! (tensor n) lower upper))))
(defmethod sample/uniform ((lower node) (upper number) &optional (n 1))
(cond ((= n 1) (random/uniform ($data lower) upper))
((> n 1) ($uniform! (tensor n) ($data lower) upper))))
(defmethod sample/uniform ((lower number) (upper node) &optional (n 1))
(cond ((= n 1) (random/uniform lower ($data upper)))
((> n 1) ($uniform! (tensor n) lower ($data upper)))))
(defmethod sample/uniform ((lower node) (upper node) &optional (n 1))
(cond ((= n 1) (random/uniform ($data lower) ($data upper)))
((> n 1) ($uniform! (tensor n) ($data lower) ($data upper)))))
| 3,259
|
Common Lisp
|
.lisp
| 60
| 50.35
| 86
| 0.628419
|
chunsj/TH
| 59
| 8
| 0
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
9fe8be025ed352175358d9014a2fda3af5fade90027b77af866f4c7d4c3cf386
| 3,155
|
[
-1
] |
3,156
|
cauchy.lisp
|
chunsj_TH/pd/cauchy.lisp
|
(in-package :th)
(defgeneric score/cauchy (data location scale))
(defgeneric sample/cauchy (location scale &optional n))
(defun of-cauchy-p (scale) (of-plusp scale))
(defmethod score/cauchy ((data number) (location number) (scale number))
(when (of-cauchy-p scale)
(let ((lpi (log pi))
(ls (log scale))
(z (/ (- data location) scale)))
(- lpi (+ ls (log (+ 1 ($square z))))))))
(defmethod score/cauchy ((data number) (location node) (scale number))
(when (of-cauchy-p scale)
(let ((lpi (log pi))
(ls (log scale))
(z ($div ($sub data location) scale)))
($sub lpi ($add ls ($log1p ($square z)))))))
(defmethod score/cauchy ((data number) (location number) (scale node))
(when (of-cauchy-p ($data scale))
(let ((lpi (log pi))
(ls ($log scale))
(z ($div (- data location) scale)))
($sub lpi ($add ls ($log1p ($square z)))))))
(defmethod score/cauchy ((data number) (location node) (scale node))
(when (of-cauchy-p ($data scale))
(let ((lpi (log pi))
(ls ($log scale))
(z ($div ($sub data location) scale)))
($sub lpi ($add ls ($log1p ($square z)))))))
(defmethod score/cauchy ((data tensor) (location number) (scale number))
(when (of-cauchy-p scale)
(let ((lpi (log pi))
(ls (log scale))
(z ($div ($sub data location) scale)))
($sum ($sub lpi ($add ls ($log1p ($square z))))))))
(defmethod score/cauchy ((data tensor) (location node) (scale number))
(when (of-cauchy-p scale)
(let ((lpi (log pi))
(ls (log scale))
(z ($div ($sub data location) scale)))
($sum ($sub lpi ($add ls ($log1p ($square z))))))))
(defmethod score/cauchy ((data tensor) (location number) (scale node))
(when (of-cauchy-p ($data scale))
(let ((lpi (log pi))
(ls (log scale))
(z ($div ($sub data location) scale)))
($sum ($sub lpi ($add ls ($log1p ($square z))))))))
(defmethod score/cauchy ((data tensor) (location node) (scale node))
(when (of-cauchy-p ($data scale))
(let ((lpi (log pi))
(ls (log scale))
(z ($div ($sub data location) scale)))
($sum ($sub lpi ($add ls ($log1p ($square z))))))))
(defmethod score/cauchy ((data node) (location number) (scale number))
(when (of-cauchy-p scale)
(let ((lpi (log pi))
(ls (log scale))
(z ($div ($sub data location) scale)))
($sum ($sub lpi ($add ls ($log1p ($square z))))))))
(defmethod score/cauchy ((data node) (location node) (scale number))
(when (of-cauchy-p scale)
(let ((lpi (log pi))
(ls (log scale))
(z ($div ($sub data location) scale)))
($sum ($sub lpi ($add ls ($log1p ($square z))))))))
(defmethod score/cauchy ((data node) (location number) (scale node))
(when (of-cauchy-p ($data scale))
(let ((lpi (log pi))
(ls (log scale))
(z ($div ($sub data location) scale)))
($sum ($sub lpi ($add ls ($log1p ($square z))))))))
(defmethod score/cauchy ((data node) (location node) (scale node))
(when (of-cauchy-p ($data scale))
(let ((lpi (log pi))
(ls (log scale))
(z ($div ($sub data location) scale)))
($sum ($sub lpi ($add ls ($log1p ($square z))))))))
(defmethod sample/cauchy ((location number) (scale number) &optional (n 1))
(cond ((= n 1) (+ location
(* scale (tan (* pi (- (random 1D0) 0.5D0))))))
((> n 1) (tensor (loop :repeat n
:for u = (tan (* pi (- (random 1D0) 0.5D0)))
:collect (+ location (* scale u)))))))
(defmethod sample/cauchy ((location node) (scale number) &optional (n 1))
(cond ((= n 1) (+ ($data location)
(* scale (tan (* pi (- (random 1D0) 0.5D0))))))
((> n 1) (tensor (loop :repeat n
:for u = (tan (* pi (- (random 1D0) 0.5D0)))
:collect (+ ($data location) (* scale u)))))))
(defmethod sample/cauchy ((location number) (scale node) &optional (n 1))
(cond ((= n 1) (+ location
(* ($data scale) (tan (* pi (- (random 1D0) 0.5D0))))))
((> n 1) (tensor (loop :repeat n
:for u = (tan (* pi (- (random 1D0) 0.5D0)))
:collect (+ location (* ($data scale) u)))))))
(defmethod sample/cauchy ((location node) (scale node) &optional (n 1))
(cond ((= n 1) (+ ($data location)
(* ($data scale) (tan (* pi (- (random 1D0) 0.5D0))))))
((> n 1) (tensor (loop :repeat n
:for u = (tan (* pi (- (random 1D0) 0.5D0)))
:collect (+ ($data location) (* ($data scale) u)))))))
| 4,778
|
Common Lisp
|
.lisp
| 100
| 39.08
| 85
| 0.527897
|
chunsj/TH
| 59
| 8
| 0
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
20124f0f09aa0805c15cf99d7451500ba4fa10becc56e62d5937bf2f2f36e820
| 3,156
|
[
-1
] |
3,157
|
exponential.lisp
|
chunsj_TH/pd/exponential.lisp
|
(in-package :th)
(defgeneric score/exponential (data rate))
(defgeneric sample/exponential (rate &optional n))
(defun of-exponential-p (data rate) (and (of-ge data 0) (of-plusp rate)))
(defmethod score/exponential ((data number) (rate number))
(when (of-exponential-p data rate)
(- (log rate) (* rate data))))
(defmethod score/exponential ((data number) (rate node))
(when (of-exponential-p data ($data rate))
($sub ($log rate) ($mul rate data))))
(defmethod score/exponential ((data tensor) (rate number))
(when (of-exponential-p data rate)
($sum ($sub ($log rate) ($mul rate data)))))
(defmethod score/exponential ((data tensor) (rate node))
(when (of-exponential-p data ($data rate))
($sum ($sub ($log rate) ($mul rate data)))))
(defmethod score/exponential ((data node) (rate number))
(when (of-exponential-p ($data data) rate)
($sum ($sub ($log rate) ($mul rate data)))))
(defmethod score/exponential ((data node) (rate node))
(when (of-exponential-p ($data data) ($data rate))
($sum ($sub ($log rate) ($mul rate data)))))
(defmethod sample/exponential ((rate number) &optional (n 1))
(cond ((= n 1) (random/exponential rate))
((> n 1) ($exponential! (tensor n) rate))))
(defmethod sample/exponential ((rate node) &optional (n 1))
(cond ((= n 1) (random/exponential ($data rate)))
((> n 1) ($exponential! (tensor n) ($data rate)))))
| 1,404
|
Common Lisp
|
.lisp
| 28
| 46.785714
| 73
| 0.661054
|
chunsj/TH
| 59
| 8
| 0
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
d0db9d86b0063ebe7081612183d55b7141d23d9ca3cf48b4d753a142ea3a81a7
| 3,157
|
[
-1
] |
3,158
|
discrete-uniform.lisp
|
chunsj_TH/pd/discrete-uniform.lisp
|
(in-package :th)
(defgeneric score/discrete-uniform (data lower upper))
(defgeneric sample/discrete-uniform (lower upper &optional n))
(defun of-uniform-p (data lower upper) (and (> upper lower) (of-ie data lower upper)))
(defmethod score/discrete-uniform ((data number) (lower number) (upper number))
(when (of-uniform-p data lower upper)
(- (log (+ 1 (- upper lower))))))
(defmethod score/discrete-uniform ((data number) (lower node) (upper number))
(when (of-uniform-p data ($data lower) upper)
($neg ($log ($add 1 ($sub upper lower))))))
(defmethod score/discrete-uniform ((data number) (lower number) (upper node))
(when (of-uniform-p data lower ($data upper))
($neg ($log ($add 1($sub upper lower))))))
(defmethod score/discrete-uniform ((data number) (lower node) (upper node))
(when (of-uniform-p data ($data lower) ($data upper))
($neg ($log ($add 1 ($sub upper lower))))))
(defmethod score/discrete-uniform ((data tensor) (lower number) (upper number))
(when (of-uniform-p data lower upper)
(let ((n ($count data)))
($mul (- n) ($log ($add 1 ($sub upper lower)))))))
(defmethod score/discrete-uniform ((data tensor) (lower node) (upper number))
(when (of-uniform-p data ($data lower) upper)
(let ((n ($count data)))
($mul (- n) ($log ($add 1 ($sub upper lower)))))))
(defmethod score/discrete-uniform ((data tensor) (lower number) (upper node))
(when (of-uniform-p data lower ($data upper))
(let ((n ($count data)))
($mul (- n) ($log ($add 1 ($sub upper lower)))))))
(defmethod score/discrete-uniform ((data tensor) (lower node) (upper node))
(when (of-uniform-p data ($data lower) ($data upper))
(let ((n ($count data)))
($mul (- n) ($log ($add 1 ($sub upper lower)))))))
(defmethod score/discrete-uniform ((data node) (lower number) (upper number))
(when (of-uniform-p ($data data) lower upper)
(let ((n (if ($tensorp data) ($count data) 1)))
($mul (- n) ($log ($add 1 ($sub upper lower)))))))
(defmethod score/discrete-uniform ((data node) (lower node) (upper number))
(when (of-uniform-p ($data data) ($data lower) upper)
(let ((n (if ($tensorp data) ($count data) 1)))
($mul (- n) ($log ($add 1 ($sub upper lower)))))))
(defmethod score/discrete-uniform ((data node) (lower number) (upper node))
(when (of-uniform-p ($data data) lower ($data upper))
(let ((n (if ($tensorp data) ($count data) 1)))
($mul (- n) ($log ($add 1 ($sub upper lower)))))))
(defmethod score/discrete-uniform ((data node) (lower node) (upper node))
(when (of-uniform-p ($data data) ($data lower) ($data upper))
(let ((n (if ($tensorp data) ($count data) 1)))
($mul (- n) ($log ($add 1 ($sub upper lower)))))))
(defmethod sample/discrete-uniform ((lower number) (upper number) &optional (n 1))
(cond ((= n 1) (random/discrete-uniform lower upper))
((> n 1) ($discrete-uniform! (tensor n) lower upper))))
(defmethod sample/discrete-uniform ((lower node) (upper number) &optional (n 1))
(cond ((= n 1) (random/discrete-uniform ($data lower) upper))
((> n 1) ($discrete-uniform! (tensor n) ($data lower) upper))))
(defmethod sample/discrete-uniform ((lower number) (upper node) &optional (n 1))
(cond ((= n 1) (random/discrete-uniform lower ($data upper)))
((> n 1) ($discrete-uniform! (tensor n) lower ($data upper)))))
(defmethod sample/discrete-uniform ((lower node) (upper node) &optional (n 1))
(cond ((= n 1) (random/discrete-uniform ($data lower) ($data upper)))
((> n 1) ($discrete-uniform! (tensor n) ($data lower) ($data upper)))))
| 3,605
|
Common Lisp
|
.lisp
| 60
| 56.116667
| 86
| 0.639637
|
chunsj/TH
| 59
| 8
| 0
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
89d4a247fde7c685ac55b49588eba5fba9203249e2175dd9ed3f65c449ad1c9e
| 3,158
|
[
-1
] |
3,159
|
binomial.lisp
|
chunsj_TH/pd/binomial.lisp
|
(in-package :th)
(defgeneric score/binomial (data p n))
(defgeneric sample/binomial (p nt &optional n))
(defun of-binomial-p (data p n) (and (of-ie data 0 n) (of-it p 0 1) (> n 0)))
(defun lbc (n k)
(let ((n1 ($add n 1))
(k1 ($add k 1))
(nk1 ($add ($sub n k) 1)))
($sub ($lgammaf n1)
($add ($lgammaf k1) ($lgammaf nk1)))))
(defmethod score/binomial ((data number) (p number) (n number))
(when (of-binomial-p data p n)
(let ((lbc (lbc n data))
(lp (log p))
(lq (log (- 1 p))))
(+ lbc (+ (* data lp) (* (- n data) lq))))))
(defmethod score/binomial ((data number) (p node) (n number))
(when (of-binomial-p data ($data p) n)
(let ((lbc (lbc n data))
(lp ($log p))
(lq ($log ($sub 1 p))))
($add lbc ($add ($mul data lp) ($mul (- n data) lq))))))
(defmethod score/binomial ((data tensor) (p number) (n number))
(when (of-binomial-p data p n)
(let ((lbc (lbc n data))
(lp (log p))
(lq (log (- 1 p))))
($sum ($add lbc ($add ($mul data lp) ($mul ($sub n data) lq)))))))
(defmethod score/binomial ((data tensor) (p node) (n number))
(when (of-binomial-p data ($data p) n)
(let ((lbc (lbc n data))
(lp ($log p))
(lq ($log ($sub 1 p))))
($sum ($add lbc ($add ($mul data lp) ($mul ($sub n data) lq)))))))
(defmethod score/binomial ((data node) (p number) (n number))
(when (of-binomial-p ($data data) p n)
(let ((lbc (lbc n data))
(lp (log p))
(lq (log (- 1 p))))
($sum ($add lbc ($add ($mul data lp) ($mul ($sub n data) lq)))))))
(defmethod score/binomial ((data node) (p node) (n number))
(when (of-binomial-p ($data data) ($data p) n)
(let ((lbc (lbc n data))
(lp ($log p))
(lq ($log ($sub 1 p))))
($sum ($add lbc ($add ($mul data lp) ($mul ($sub n data) lq)))))))
(defmethod sample/binomial ((p number) (nt number) &optional (n 1))
(cond ((= n 1) (random/binomial nt p))
((> n 1) ($binomial! (tensor n) nt p))))
(defmethod sample/binomial ((p node) (nt number) &optional (n 1))
(cond ((= n 1) (random/binomial nt ($data p)))
((> n 1) ($binomial! (tensor n) nt ($data p)))))
| 2,221
|
Common Lisp
|
.lisp
| 52
| 36.807692
| 77
| 0.53012
|
chunsj/TH
| 59
| 8
| 0
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
09998beac736294a82cf742a9706e9948670c59560f30a872e8c078789552054
| 3,159
|
[
-1
] |
3,160
|
cs.lisp
|
chunsj_TH/pd/cs.lisp
|
(in-package :th)
(defgeneric of-lt (n v))
(defgeneric of-le (n v))
(defgeneric of-gt (n v))
(defgeneric of-ge (n v))
(defgeneric of-it (n min max))
(defgeneric of-ie (n min max))
(defgeneric of-ot (n min max))
(defgeneric of-oe (n min max))
(defmethod of-lt ((n number) v) (< n v))
(defmethod of-le ((n number) v) (<= n v))
(defmethod of-gt ((n number) v) (> n v))
(defmethod of-ge ((n number) v) (>= n v))
(defmethod of-it ((n number) min max) (and (> n min) (< n max)))
(defmethod of-ie ((n number) min max) (and (>= n min) (<= n max)))
(defmethod of-ot ((n number) min max) (or (< n min) (> n max)))
(defmethod of-oe ((n number) min max) (or (<= n min) (>= n max)))
(defmethod of-lt ((n tensor) v) (zerop ($sum ($ge n v))))
(defmethod of-le ((n tensor) v) (zerop ($sum ($gt n v))))
(defmethod of-gt ((n tensor) v) (zerop ($sum ($le n v))))
(defmethod of-ge ((n tensor) v) (zerop ($sum ($lt n v))))
(defmethod of-it ((n tensor) min max) (and (of-gt n min) (of-lt n max)))
(defmethod of-ie ((n tensor) min max) (and (of-ge n min) (of-le n max)))
(defmethod of-ot ((n tensor) min max) (or (of-lt n min) (of-gt n max)))
(defmethod of-oe ((n tensor) min max) (or (of-le n min) (of-ge n max)))
(defun of-plusp (n) (of-gt n 0))
(defun of-minusp (n) (of-lt n 0))
(defun of-unit-interval-p (n) (of-ie n 0 1))
| 1,307
|
Common Lisp
|
.lisp
| 28
| 45.535714
| 72
| 0.607059
|
chunsj/TH
| 59
| 8
| 0
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
390c380519af03f0abe2e086901a2373d29b43b5fd14c232090f87bb02efb5a5
| 3,160
|
[
-1
] |
3,161
|
bernoulli.lisp
|
chunsj_TH/pd/bernoulli.lisp
|
(in-package :th)
(defgeneric score/bernoulli (data p))
(defgeneric sample/bernoulli (p &optional n))
(defun of-bernoulli-p (data p)
(if ($tensorp data)
(and (= ($count data) ($+ ($sum ($eq data 0)) ($sum ($eq data 1))))
(of-it p 0 1))
(and (or (= data 0) (= data 1)) (of-it p 0 1))))
(defmethod score/bernoulli ((data number) (p number))
(when (of-bernoulli-p data p)
(+ (* data (log p)) (* (- 1 data) (log (- 1 p))))))
(defmethod score/bernoulli ((data number) (p node))
(when (of-bernoulli-p data ($data p))
($add ($mul data ($log p)) ($mul (- 1 data) ($log ($sub 1 p))))))
(defmethod score/bernoulli ((data tensor) (p number))
(when (of-bernoulli-p data p)
($sum ($add ($mul data (log p)) ($mul ($sub 1 data) (log (- 1 p)))))))
(defmethod score/bernoulli ((data tensor) (p tensor))
(when (of-bernoulli-p data p)
($sum ($add ($mul data ($log p)) ($mul ($sub 1 data) ($log ($sub 1 p)))))))
(defmethod score/bernoulli ((data tensor) (p node))
(when (of-bernoulli-p data ($data p))
($sum ($add ($mul data ($log p)) ($mul ($sub 1 data) ($log ($sub 1 p)))))))
(defmethod score/bernoulli ((data node) (p number))
(when (of-bernoulli-p ($data data) p)
($sum ($add ($mul data (log p)) ($mul ($sub 1 data) (log (- 1 p)))))))
(defmethod score/bernoulli ((data node) (p node))
(when (of-bernoulli-p ($data data) ($data p))
($sum ($add ($mul data ($log p)) ($mul ($sub 1 data) ($log ($sub 1 p)))))))
(defmethod sample/bernoulli ((p number) &optional (n 1))
(cond ((= n 1) (random/bernoulli p))
((> n 1) ($bernoulli! (tensor n) p))))
(defmethod sample/bernoulli ((p node) &optional (n 1))
(cond ((= n 1) (random/bernoulli ($data p)))
((> n 1) ($bernoulli! (tensor n) ($data p)))))
| 1,768
|
Common Lisp
|
.lisp
| 35
| 46.714286
| 79
| 0.58072
|
chunsj/TH
| 59
| 8
| 0
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
ae973f57f688fcbe2183a12d0a9184b4e8414cd323b301b52e2c3628044b3a20
| 3,161
|
[
-1
] |
3,162
|
implementation.lisp
|
chunsj_TH/private/implementation.lisp
|
(declaim (optimize (speed 3) (debug 1) (safety 0)))
(in-package :th)
(defmethod tensor-with-storage ((storage null) &optional (storage-offset 0) size stride)
(cond ((eq *default-tensor-class* 'tensor.float)
(let* ((tr (make-instance 'tensor.float))
(size (if (listp size) (storage.long size) size))
(stride (if (listp stride) (storage.long stride) stride))
(rh (th-float-tensor-new-with-storage ($handle storage)
storage-offset
(if (null size)
+nil+
($handle size))
(if (null stride)
+nil+
($handle stride)))))
(setf ($handle tr) rh)
#+sbcl (sb-ext:finalize tr (lambda () (th-float-tensor-free rh)))
#+ccl (ccl:terminate-when-unreachable tr)
tr))
((eq *default-tensor-class* 'tensor.double)
(let* ((tr (make-instance 'tensor.double))
(size (if (listp size) (storage.long size) size))
(stride (if (listp stride) (storage.long stride) stride))
(rh (th-double-tensor-new-with-storage ($handle storage)
storage-offset
(if (null size)
+nil+
($handle size))
(if (null stride)
+nil+
($handle stride)))))
(setf ($handle tr) rh)
#+sbcl (sb-ext:finalize tr (lambda () (th-double-tensor-free rh)))
#+ccl (ccl:terminate-when-unreachable tr)
tr))
(T nil)))
(defmethod $count ((tensor tensor)) (tensor-n-element tensor))
(defmethod tensor-coerce ((tensor tensor.byte) value) (coerce value 'unsigned-byte))
(defmethod tensor-coerce ((tensor tensor.char) value) (coerce value 'signed-byte))
(defmethod tensor-coerce ((tensor tensor.short) value) (coerce value 'integer))
(defmethod tensor-coerce ((tensor tensor.int) value) (coerce value 'integer))
(defmethod tensor-coerce ((tensor tensor.long) value) (coerce value 'integer))
(defmethod tensor-coerce ((tensor tensor.float) value) (coerce value 'single-float))
(defmethod tensor-coerce ((tensor tensor.double) value) (coerce value 'double-float))
(defmethod tensor-acoerce ((tensor tensor.byte) value) (coerce value 'integer))
(defmethod tensor-acoerce ((tensor tensor.char) value) (coerce value 'integer))
(defmethod tensor-acoerce ((tensor tensor.short) value) (coerce value 'integer))
(defmethod tensor-acoerce ((tensor tensor.int) value) (coerce value 'integer))
(defmethod tensor-acoerce ((tensor tensor.long) value) (coerce value 'integer))
(defmethod tensor-acoerce ((tensor tensor.float) value) (coerce value 'double-float))
(defmethod tensor-acoerce ((tensor tensor.double) value) (coerce value 'double-float))
(defmethod tensor-type ((tensor tensor.byte)) :byte)
(defmethod tensor-type ((tensor tensor.char)) :char)
(defmethod tensor-type ((tensor tensor.short)) :short)
(defmethod tensor-type ((tensor tensor.int)) :int)
(defmethod tensor-type ((tensor tensor.long)) :long)
(defmethod tensor-type ((tensor tensor.float)) :float)
(defmethod tensor-type ((tensor tensor.double)) :double)
(defun tensor.byte-random (&rest sizes)
(let ((x (apply #'tensor.byte sizes)))
(tensor-random x)))
(defun tensor.char-random (&rest sizes)
(let ((x (apply #'tensor.char sizes)))
(tensor-random x)))
(defun tensor.short-random (&rest sizes)
(let ((x (apply #'tensor.short sizes)))
(tensor-random x)))
(defun tensor.int-random (&rest sizes)
(let ((x (apply #'tensor.int sizes)))
(tensor-random x)))
(defun tensor.long-random (&rest sizes)
(let ((x (apply #'tensor.long sizes)))
(tensor-random x)))
(defun tensor.float-random (&rest sizes)
(let ((x (apply #'tensor.float sizes)))
(tensor-random x)))
(defun tensor.double-random (&rest sizes)
(let ((x (apply #'tensor.double sizes)))
(tensor-random x)))
(defun coerce-to-long (v) (coerce v 'integer))
(defun coerce-to-prob (p) (coerce p 'double-float))
(defun byte-eye (nrow ncol) (tensor-eye (tensor.byte) nrow ncol))
(defun char-eye (nrow ncol) (tensor-eye (tensor.char) nrow ncol))
(defun short-eye (nrow ncol) (tensor-eye (tensor.short) nrow ncol))
(defun int-eye (nrow ncol) (tensor-eye (tensor.int) nrow ncol))
(defun long-eye (nrow ncol) (tensor-eye (tensor.long) nrow ncol))
(defun float-eye (nrow ncol) (tensor-eye (tensor.float) nrow ncol))
(defun double-eye (nrow ncol) (tensor-eye (tensor.double) nrow ncol))
(defun tensor.byte-arange (xmin xmax &optional (step 1))
(tensor-arange (tensor.byte) xmin xmax step))
(defun tensor.char-arange (xmin xmax &optional (step 1))
(tensor-arange (tensor.char) xmin xmax step))
(defun tensor.short-arange (xmin xmax &optional (step 1))
(tensor-arange (tensor.short) xmin xmax step))
(defun tensor.int-arange (xmin xmax &optional (step 1))
(tensor-arange (tensor.int) xmin xmax step))
(defun tensor.long-arange (xmin xmax &optional (step 1))
(tensor-arange (tensor.long) xmin xmax step))
(defun tensor.float-arange (xmin xmax &optional (step 1))
(tensor-arange (tensor.float) xmin xmax step))
(defun tensor.double-arange (xmin xmax &optional (step 1))
(tensor-arange (tensor.double) xmin xmax step))
(defun tensor.byte-range (xmin xmax &optional (step 1))
(tensor-range (tensor.byte) xmin xmax step))
(defun tensor.char-range (xmin xmax &optional (step 1))
(tensor-range (tensor.char) xmin xmax step))
(defun tensor.short-range (xmin xmax &optional (step 1))
(tensor-range (tensor.short) xmin xmax step))
(defun tensor.int-range (xmin xmax &optional (step 1))
(tensor-range (tensor.int) xmin xmax step))
(defun tensor.long-range (xmin xmax &optional (step 1))
(tensor-range (tensor.long) xmin xmax step))
(defun tensor.float-range (xmin xmax &optional (step 1))
(tensor-range (tensor.float) xmin xmax step))
(defun tensor.double-range (xmin xmax &optional (step 1))
(tensor-range (tensor.double) xmin xmax step))
(defun tensor.byte-rand-perm (n &optional generator)
(tensor-rand-perm (tensor.byte) n generator))
(defun tensor.char-rand-perm (n &optional generator)
(tensor-rand-perm (tensor.char) n generator))
(defun tensor.short-rand-perm (n &optional generator)
(tensor-rand-perm (tensor.short) n generator))
(defun tensor.int-rand-perm (n &optional generator)
(tensor-rand-perm (tensor.int) n generator))
(defun tensor.long-rand-perm (n &optional generator)
(tensor-rand-perm (tensor.long) n generator))
(defun tensor.float-rand-perm (n &optional generator)
(tensor-rand-perm (tensor.float) n generator))
(defun tensor.double-rand-perm (n &optional generator)
(tensor-rand-perm (tensor.double) n generator))
(defmethod tensor-abs ((tensor tensor.short) (src tensor.short))
(th-short-tensor-abs ($handle tensor) ($handle src))
tensor)
(defmethod tensor-abs ((tensor tensor.int) (src tensor.int))
(th-int-tensor-abs ($handle tensor) ($handle src))
tensor)
(defmethod tensor-abs ((tensor tensor.long) (src tensor.long))
(th-long-tensor-abs ($handle tensor) ($handle src))
tensor)
(defmethod tensor-logical-all ((tensor tensor.byte))
(eq 1 (th-byte-tensor-logical-all ($handle tensor))))
(defmethod tensor-logical-any ((tensor tensor.byte))
(eq 1 (th-byte-tensor-logical-any ($handle tensor))))
(defun %%match-fn-p (leaf)
(and (symbolp leaf)
(let ((name (string leaf)))
(and (> (length name) 3) (string-equal "ft-" (subseq name 0 3))))))
(defun %%gen-fn (leaf type)
(let ((fbody (subseq (string leaf) 3)))
(intern (string-upcase (strcat "th-" type "-" fbody)))))
(defun %%gen-tensor-type (type) (intern (string-upcase (strcat "tensor." type))))
(defun %%gen-storage-type (type) (intern (string-upcase (strcat "storage." type))))
(defun %%gen-pointer-type (type) (intern (string-upcase (strcat "pointer." type))))
(defun %%gen-impl (fimpl type)
(-> fimpl
(tree-leaves (eq 'tensor.type x) (%%gen-tensor-type type))
(tree-leaves (eq 'storage.type x) (%%gen-storage-type type))
(tree-leaves (eq 'pointer.type x) (%%gen-pointer-type type))
(tree-leaves (%%match-fn-p x) (%%gen-fn x type))))
(defparameter *tensor-generic-interface-implementations*
'((defmethod tensor-with-tensor ((tensor tensor.type))
(let ((tr (make-instance 'tensor.type))
(rh (ft-tensor-new-with-tensor ($handle tensor))))
(setf ($handle tr) rh)
#+sbcl (sb-ext:finalize tr (lambda () (ft-tensor-free rh)))
#+ccl (ccl:terminate-when-unreachable tr)
tr))
(defmethod tensor-with-storage ((storage storage.type) &optional (storage-offset 0) size stride)
(let* ((tr (make-instance 'tensor.type))
(size (if (listp size) (storage.long size) size))
(stride (if (listp stride) (storage.long stride) stride))
(rh (ft-tensor-new-with-storage ($handle storage)
storage-offset
(if (null size)
+nil+
($handle size))
(if (null stride)
+nil+
($handle stride)))))
(setf ($handle tr) rh)
#+sbcl (sb-ext:finalize tr (lambda () (ft-tensor-free rh)))
#+ccl (ccl:terminate-when-unreachable tr)
tr))
(defmethod tensor-at ((tensor tensor.type) location &rest others-and-default)
(if (null others-and-default)
(ft-tensor-get-1d ($handle tensor) location)
(cond ((eq 1 ($count others-and-default))
(ft-tensor-get-2d ($handle tensor) location ($0 others-and-default)))
((eq 2 ($count others-and-default))
(ft-tensor-get-3d ($handle tensor) location
($0 others-and-default)
($1 others-and-default)))
((eq 3 ($count others-and-default))
(ft-tensor-get-4d ($handle tensor) location
($0 others-and-default)
($1 others-and-default)
($2 others-and-default))))))
(defmethod (setf tensor-at) (value (tensor tensor.type) location &rest others)
(let ((v (tensor-coerce tensor value)))
(if (null others)
(ft-tensor-set-1d ($handle tensor) location v)
(cond ((eq 1 ($count others))
(ft-tensor-set-2d ($handle tensor) location ($0 others)
v))
((eq 2 ($count others))
(ft-tensor-set-3d ($handle tensor) location
($0 others)
($1 others)
v))
((eq 3 ($count others))
(ft-tensor-set-4d ($handle tensor) location
($0 others)
($1 others)
($2 others)
v))))
v))
(defmethod tensor-storage ((tensor tensor.type))
(let ((h (ft-tensor-storage ($handle tensor))))
(when (and h (not (cffi:null-pointer-p h)))
(let ((storage (make-instance 'storage.type)))
(setf ($handle storage) h)
storage))))
(defmethod tensor-storage-offset ((tensor tensor.type))
(ft-tensor-storage-offset ($handle tensor)))
(defmethod tensor-n-dimension ((tensor tensor.type))
(ft-tensor-n-dimension ($handle tensor)))
(defmethod tensor-size ((tensor tensor.type) dimension)
(ft-tensor-size ($handle tensor) dimension))
(defmethod tensor-stride ((tensor tensor.type) dimension)
(ft-tensor-stride ($handle tensor) dimension))
(defmethod tensor-data ((tensor tensor.type))
(let ((ptr (make-instance 'pointer.type)))
(setf ($handle ptr) (ft-tensor-data ($handle tensor)))
ptr))
(defmethod tensor-clone ((tensor tensor.type))
(let ((clone (make-instance 'tensor.type))
(handle (ft-tensor-new-clone ($handle tensor))))
(setf ($handle clone) handle)
#+sbcl (sb-ext:finalize clone (lambda () (ft-tensor-free handle)))
#+ccl (ccl:terminate-when-unreachable clone)
clone))
(defmethod tensor-contiguous ((tensor tensor.type))
(let ((tr (make-instance 'tensor.type))
(rh (ft-tensor-new-contiguous ($handle tensor))))
(setf ($handle tr) rh)
#+sbcl (sb-ext:finalize tr (lambda () (ft-tensor-free rh)))
#+ccl (ccl:terminate-when-unreachable tr)
tr))
(defmethod tensor-new-select ((tensor tensor.type) dimension slice-index)
(let ((tr (make-instance 'tensor.type))
(h (ft-tensor-new-select ($handle tensor) dimension slice-index)))
(setf ($handle tr) h)
#+sbcl (sb-ext:finalize tr (lambda () (ft-tensor-free h)))
#+ccl (ccl:terminate-when-unreachable tr)
tr))
(defmethod tensor-new-narrow ((tensor tensor.type) dimension first-index size)
(let ((r (make-instance 'tensor.type))
(h (ft-tensor-new-narrow ($handle tensor) dimension first-index size)))
(setf ($handle r) h)
#+sbcl (sb-ext:finalize r (lambda () (ft-tensor-free h)))
#+ccl (ccl:terminate-when-unreachable r)
r))
(defmethod tensor-new-transpose ((tensor tensor.type))
(let ((r (make-instance 'tensor.type))
(h (ft-tensor-new-transpose ($handle tensor) 0 1)))
(setf ($handle r) h)
#+sbcl (sb-ext:finalize r (lambda () (ft-tensor-free h)))
#+ccl (ccl:terminate-when-unreachable r)
r))
(defmethod tensor-new-unfold ((tensor tensor.type) dimension size step)
(let ((r (make-instance 'tensor.type))
(h (ft-tensor-new-unfold ($handle tensor) dimension size step)))
(setf ($handle r) h)
#+sbcl (sb-ext:finalize r (lambda () (ft-tensor-free h)))
#+ccl (ccl:terminate-when-unreachable r)
r))
(defmethod tensor-new-view ((tensor tensor.type) (size list))
(let* ((r (make-instance 'tensor.type))
(s (let ((s (storage.long ($count size))))
(loop :for i :from 0 :below ($count size)
:do (setf ($ s i) ($ size i)))
s))
(h (ft-tensor-new-view ($handle tensor) ($handle s))))
(setf ($handle r) h)
#+sbcl (sb-ext:finalize r (lambda () (ft-tensor-free h)))
#+ccl (ccl:terminate-when-unreachable r)
r))
(defmethod tensor-new-view ((tensor tensor.type) (size storage.long))
(let ((r (make-instance 'tensor.type))
(h (ft-tensor-new-view ($handle tensor) ($handle size))))
(setf ($handle r) h)
#+sbcl (sb-ext:finalize r (lambda () (ft-tensor-free h)))
#+ccl (ccl:terminate-when-unreachable r)
r))
(defmethod tensor-expand ((tensor tensor.type) (src tensor.type) (size list))
(when (> ($count size) 0)
(let ((storage (storage.long ($count size)))
(tensor (or tensor (tensor.type))))
(loop :for i :from 0 :below ($count size)
:do (setf ($ storage i) ($ size i)))
(ft-tensor-expand ($handle tensor) ($handle src)
($handle storage))
tensor)))
(defmethod tensor-resize-as ((tensor tensor.type) src)
(ft-tensor-resize-as ($handle tensor) ($handle src))
tensor)
(defmethod tensor-resize ((tensor tensor.type) (size list) &optional stride)
(let ((size (storage.long size))
(stride (when stride (storage.long stride))))
(ft-tensor-resize-nd ($handle tensor)
($size size)
($handle ($pointer size))
(if stride
($handle ($pointer stride))
+nil+))
tensor))
(defmethod tensor-set ((tensor tensor.type) (src tensor))
(ft-tensor-set ($handle tensor) ($handle src))
tensor)
(defmethod tensor-set-storage ((tensor tensor.type) (storage storage.type) offset
(size list) (stride list))
(let ((size (storage.long size))
(stride (storage.long stride)))
(ft-tensor-set-storage ($handle tensor) ($handle storage) offset
($handle size) ($handle stride))))
(defmethod tensor-set-storage ((tensor tensor.type) (storage storage.type) offset
(size storage.long) (stride storage.long))
(ft-tensor-set-storage ($handle tensor) ($handle storage) offset
($handle size) ($handle stride)))
(defmethod tensor-set-storage ((tensor tensor.type) (storage storage.type) offset
(size list) (stride null))
(let ((size (storage.long size)))
(ft-tensor-set-storage ($handle tensor) ($handle storage) offset
($handle size) +nil+)))
(defmethod tensor-set-storage ((tensor tensor.type) (storage storage.type) offset
(size storage.long) (stride null))
(ft-tensor-set-storage ($handle tensor) ($handle storage) offset
($handle size) +nil+))
(defmethod tensor-narrow ((tensor tensor.type) (src tensor.type) dimension first-idx size)
(ft-tensor-narrow ($handle tensor) ($handle src) dimension first-idx size)
tensor)
(defmethod tensor-select ((tensor tensor.type) (src tensor.type) dimension slice-index)
(ft-tensor-select ($handle tensor) ($handle src) dimension slice-index)
tensor)
(defmethod tensor-transpose ((tensor tensor.type) (src tensor.type) dimension0 dimension1)
(ft-tensor-transpose ($handle tensor) ($handle src) dimension0 dimension1)
tensor)
(defmethod tensor-unfold ((tensor tensor.type) (src tensor.type) dimension size step)
(ft-tensor-unfold ($handle tensor) ($handle src) dimension size step)
tensor)
(defmethod tensor-unfold ((tensor tensor.type) (src null) dimension size step)
(ft-tensor-unfold ($handle tensor) +nil+ dimension size step)
tensor)
(defmethod tensor-squeeze ((tensor tensor.type) (src tensor.type) &optional dimension)
(cond ((null dimension) (ft-tensor-squeeze ($handle tensor) ($handle src)))
(t (ft-tensor-squeeze-1d ($handle tensor) ($handle src) dimension)))
tensor)
(defmethod tensor-squeeze ((tensor tensor.type) (src null) &optional dimension)
(cond ((null dimension) (ft-tensor-squeeze ($handle tensor) +nil+))
(t (ft-tensor-squeeze-1d ($handle tensor) +nil+ dimension)))
tensor)
(defmethod tensor-unsqueeze ((tensor tensor.type) (src tensor.type) dimension)
(ft-tensor-unsqueeze-1d ($handle tensor) ($handle src) dimension)
tensor)
(defmethod tensor-unsqueeze ((tensor tensor.type) (src null) dimension)
(ft-tensor-unsqueeze-1d ($handle tensor) +nil+ dimension)
tensor)
(defmethod tensor-contiguous-p ((tensor tensor.type))
(eq 1 (ft-tensor-is-contiguous ($handle tensor))))
(defmethod tensor-same-size-p ((tensor tensor.type) (src tensor.type))
(eq 1 (ft-tensor-is-same-size-as ($handle tensor) ($handle src))))
(defmethod tensor-set-to-p ((tensor tensor.type) (src tensor.type))
(eq 1 (ft-tensor-is-set-to ($handle tensor) ($handle src))))
(defmethod tensor-size-p ((tensor tensor.type) (size list))
(let ((s (storage.long ($count size))))
(loop :for i :from 0 :below ($count size) :do (setf ($ s i) ($ size i)))
(eq 1 (ft-tensor-is-size ($handle tensor) ($handle s)))))
(defmethod tensor-size-p ((tensor tensor.type) (size storage.long))
(eq 1 (ft-tensor-is-size ($handle tensor) ($handle size))))
(defmethod tensor-n-element ((tensor tensor.type)) (ft-tensor-n-element ($handle tensor)))
(defmethod tensor-copy ((tensor tensor.type) (src tensor.byte))
(ft-tensor-copy-byte ($handle tensor) ($handle src))
tensor)
(defmethod tensor-copy ((tensor tensor.type) (src tensor.char))
(ft-tensor-copy-char ($handle tensor) ($handle src))
tensor)
(defmethod tensor-copy ((tensor tensor.type) (src tensor.short))
(ft-tensor-copy-short ($handle tensor) ($handle src))
tensor)
(defmethod tensor-copy ((tensor tensor.type) (src tensor.int))
(ft-tensor-copy-int ($handle tensor) ($handle src))
tensor)
(defmethod tensor-copy ((tensor tensor.type) (src tensor.long))
(ft-tensor-copy-long ($handle tensor) ($handle src))
tensor)
(defmethod tensor-copy ((tensor tensor.type) (src tensor.float))
(ft-tensor-copy-float ($handle tensor) ($handle src))
tensor)
(defmethod tensor-copy ((tensor tensor.type) (src tensor.double))
(ft-tensor-copy-double ($handle tensor) ($handle src))
tensor)
(defmethod tensor-random ((tensor tensor.type) &optional generator)
(ft-tensor-random ($handle tensor) ($handle (or generator *generator*)))
tensor)
(defmethod tensor-geometric ((tensor tensor.type) p &optional generator)
(ft-tensor-geometric ($handle tensor) ($handle (or generator *generator*))
(coerce-to-prob p))
tensor)
(defmethod tensor-binomial ((tensor tensor.type) n p &optional generator)
(ft-tensor-binomial ($handle tensor) ($handle (or generator *generator*))
(coerce n 'integer)
(coerce-to-prob p))
tensor)
(defmethod tensor-bernoulli ((tensor tensor.type) (p number) &optional generator)
(if (zerop (tensor-n-element tensor)) (tensor-resize tensor '(1)))
(ft-tensor-bernoulli ($handle tensor) ($handle (or generator *generator*))
(coerce-to-prob p))
tensor)
(defmethod tensor-bernoulli ((tensor tensor.type) (p tensor.float) &optional generator)
(tensor-resize-as tensor p)
(ft-tensor-bernoulli-float-tensor ($handle tensor)
($handle (or generator *generator*))
($handle p))
tensor)
(defmethod tensor-bernoulli ((tensor tensor.type) (p tensor.double) &optional generator)
(tensor-resize-as tensor p)
(ft-tensor-bernoulli-double-tensor ($handle tensor)
($handle (or generator *generator*))
($handle p))
tensor)
(defmethod tensor-hypergeometric ((tensor tensor.type) (nr number) (nb number) (k number)
&optional generator)
(if (zerop (tensor-n-element tensor)) (tensor-resize tensor '(1)))
(ft-tensor-hypergeometric ($handle tensor)
($handle (or generator *generator*))
(coerce (round nr) 'integer)
(coerce (round nb) 'integer)
(coerce (round k) 'integer))
tensor)
(defmethod tensor-poisson ((tensor tensor.type) (mu number) &optional generator)
(if (zerop (tensor-n-element tensor)) (tensor-resize tensor '(1)))
(ft-tensor-poisson ($handle tensor)
($handle (or generator *generator*))
(coerce mu 'double-float)))
(defmethod tensor-fill ((tensor tensor.type) value)
(ft-tensor-fill ($handle tensor) (tensor-coerce tensor value))
tensor)
(defmethod tensor-zero ((tensor tensor.type)) (ft-tensor-zero ($handle tensor)) tensor)
(defmethod tensor-masked-fill ((tensor tensor.type) (mask tensor.byte) value)
(ft-tensor-masked-fill ($handle tensor)
($handle mask)
(tensor-coerce tensor value))
tensor)
(defmethod tensor-masked-copy ((tensor tensor.type) (mask tensor.byte) (src tensor.type))
(ft-tensor-masked-copy ($handle tensor)
($handle mask)
($handle src))
tensor)
(defmethod tensor-masked-select ((tensor tensor.type) (mask tensor.byte) (src tensor.type))
(ft-tensor-masked-select ($handle tensor)
($handle src)
($handle mask))
tensor)
(defmethod tensor-non-zero ((tensor tensor.type) &optional indices)
(let ((indices (or indices (tensor.long))))
(ft-tensor-nonzero ($handle indices)
($handle tensor))
indices))
(defmethod tensor-index-select ((tensor tensor.type) (src tensor.type) dim (index tensor.long))
(ft-tensor-index-select ($handle tensor)
($handle src)
dim
($handle index))
tensor)
(defmethod tensor-index-copy ((tensor tensor.type) (src tensor.type) dim (index tensor.long))
(ft-tensor-index-copy ($handle tensor)
dim
($handle index)
($handle src))
tensor)
(defmethod tensor-index-add ((tensor tensor.type) (src tensor.type) dim (index tensor.long))
(ft-tensor-index-add ($handle tensor)
dim
($handle index)
($handle src))
tensor)
(defmethod tensor-index-fill ((tensor tensor.type) value dim (index tensor.long))
(ft-tensor-index-fill ($handle tensor)
dim
($handle index)
(tensor-coerce tensor value))
tensor)
(defmethod tensor-gather ((tensor tensor.type) (src tensor.type) dim (index tensor.long))
(ft-tensor-gather ($handle tensor)
($handle src)
dim
($handle index))
tensor)
(defmethod tensor-scatter ((tensor tensor.type) (src tensor.type) dim (index tensor.long))
(ft-tensor-scatter ($handle tensor)
dim
($handle index)
($handle src))
tensor)
(defmethod tensor-scatter-add ((tensor tensor.type) (src tensor.type) dim (index tensor.long))
(ft-tensor-scatter-add ($handle tensor)
dim
($handle index)
($handle src))
tensor)
(defmethod tensor-scatter-fill ((tensor tensor.type) value dim (index tensor.long))
(ft-tensor-scatter-fill ($handle tensor)
dim
($handle index)
(tensor-coerce tensor value))
tensor)
(defmethod tensor-dot ((tensor1 tensor.type) (tensor2 tensor.type))
(ft-tensor-dot ($handle tensor1) ($handle tensor2)))
(defmethod tensor-min-all ((tensor tensor.type)) (ft-tensor-min-all ($handle tensor)))
(defmethod tensor-max-all ((tensor tensor.type)) (ft-tensor-max-all ($handle tensor)))
(defmethod tensor-median-all ((tensor tensor.type)) (ft-tensor-median-all ($handle tensor)))
(defmethod tensor-sum-all ((tensor tensor.type)) (ft-tensor-sum-all ($handle tensor)))
(defmethod tensor-prd-all ((tensor tensor.type)) (ft-tensor-prod-all ($handle tensor)))
(defmethod tensor-neg ((tensor tensor.type) (src tensor.type))
(ft-tensor-neg ($handle tensor) ($handle src))
tensor)
(defmethod tensor-add ((tensor tensor.type) (src tensor.type) (value number))
(ft-tensor-add ($handle tensor)
($handle src)
(tensor-coerce src value))
tensor)
(defmethod tensor-sub ((tensor tensor.type) (src tensor.type) (value number))
(ft-tensor-sub ($handle tensor)
($handle src)
(tensor-coerce src value))
tensor)
(defmethod tensor-mul ((tensor tensor.type) (src tensor.type) (value number))
(ft-tensor-mul ($handle tensor)
($handle src)
(tensor-coerce src value))
tensor)
(defmethod tensor-div ((tensor tensor.type) (src tensor.type) (value number))
(ft-tensor-div ($handle tensor)
($handle src)
(tensor-coerce src value))
tensor)
(defmethod tensor-mod ((tensor tensor.type) (src tensor.type) (value number))
(ft-tensor-remainder ($handle tensor)
($handle src)
(tensor-coerce src value))
tensor)
(defmethod tensor-fmod ((tensor tensor.type) (src tensor.type) (value number))
(ft-tensor-fmod ($handle tensor)
($handle src)
(tensor-coerce src value))
tensor)
(defmethod tensor-clamp ((tensor tensor.type) (src tensor.type) (min number) (max number))
(ft-tensor-clamp ($handle tensor)
($handle src)
(tensor-coerce src min)
(tensor-coerce src max))
tensor)
(defmethod tensor-lshift ((tensor tensor.type) (src tensor.type) (value number))
(ft-tensor-lshift ($handle tensor)
($handle src)
(tensor-coerce src value))
tensor)
(defmethod tensor-rshift ((tensor tensor.type) (src tensor.type) (value number))
(ft-tensor-rshift ($handle tensor)
($handle src)
(tensor-coerce src value))
tensor)
(defmethod tensor-bitand ((tensor tensor.type) (src tensor.type) (value number))
(ft-tensor-bitand ($handle tensor)
($handle src)
(tensor-coerce src value))
tensor)
(defmethod tensor-bitor ((tensor tensor.type) (src tensor.type) (value number))
(ft-tensor-bitor ($handle tensor)
($handle src)
(tensor-coerce src value))
tensor)
(defmethod tensor-bitxor ((tensor tensor.type) (src tensor.type) (value number))
(ft-tensor-bitxor ($handle tensor)
($handle src)
(tensor-coerce src value))
tensor)
(defmethod tensor-cadd ((tensor tensor.type) (src1 tensor.type)
(value number) (src2 tensor.type))
(ft-tensor-cadd ($handle tensor) ($handle src1)
(tensor-coerce tensor value) ($handle src2))
tensor)
(defmethod tensor-csub ((tensor tensor.type) (src1 tensor.type)
(value number) (src2 tensor.type))
(ft-tensor-csub ($handle tensor) ($handle src1)
(tensor-coerce tensor value) ($handle src2))
tensor)
(defmethod tensor-cmul ((tensor tensor.type) (src1 tensor.type) (src2 tensor.type))
(ft-tensor-cmul ($handle tensor) ($handle src1) ($handle src2))
tensor)
(defmethod tensor-cpow ((tensor tensor.type) (src1 tensor.type) (src2 tensor.type))
(ft-tensor-cpow ($handle tensor) ($handle src1) ($handle src2))
tensor)
(defmethod tensor-cdiv ((tensor tensor.type) (src1 tensor.type) (src2 tensor.type))
(ft-tensor-cdiv ($handle tensor) ($handle src1) ($handle src2))
tensor)
(defmethod tensor-clshift ((tensor tensor.type) (src1 tensor.type) (src2 tensor.type))
(ft-tensor-clshift ($handle tensor) ($handle src1) ($handle src2))
tensor)
(defmethod tensor-crshift ((tensor tensor.type) (src1 tensor.type) (src2 tensor.type))
(ft-tensor-crshift ($handle tensor) ($handle src1) ($handle src2))
tensor)
(defmethod tensor-cmod ((tensor tensor.type) (src1 tensor.type) (src2 tensor.type))
(ft-tensor-cremainder ($handle tensor) ($handle src1) ($handle src2))
tensor)
(defmethod tensor-cfmod ((tensor tensor.type) (src1 tensor.type) (src2 tensor.type))
(ft-tensor-cfmod ($handle tensor) ($handle src1) ($handle src2))
tensor)
(defmethod tensor-cbitand ((tensor tensor.type) (src1 tensor.type) (src2 tensor.type))
(ft-tensor-cbitand ($handle tensor) ($handle src1) ($handle src2))
tensor)
(defmethod tensor-cbitor ((tensor tensor.type) (src1 tensor.type) (src2 tensor.type))
(ft-tensor-cbitor ($handle tensor) ($handle src1) ($handle src2))
tensor)
(defmethod tensor-cbitxor ((tensor tensor.type) (src1 tensor.type) (src2 tensor.type))
(ft-tensor-cbitxor ($handle tensor) ($handle src1) ($handle src2))
tensor)
(defmethod tensor-add-cmul ((tensor tensor.type) (src1 tensor.type) (value number)
(src2 tensor.type) (src3 tensor.type))
(ft-tensor-add-cmul ($handle tensor)
($handle src1)
(tensor-coerce src1 value)
($handle src2)
($handle src3))
tensor)
(defmethod tensor-add-cdiv ((tensor tensor.type) (src1 tensor.type) (value number)
(src2 tensor.type) (src3 tensor.type))
(ft-tensor-add-cdiv ($handle tensor)
($handle src1)
(tensor-coerce src1 value)
($handle src2)
($handle src3))
tensor)
(defmethod tensor-add-mv ((tensor tensor.type) (beta number) (y tensor.type)
(alpha number) (A tensor.type) (x tensor.type))
(ft-tensor-add-mv ($handle tensor)
(tensor-coerce y beta)
($handle y)
(tensor-coerce y alpha)
($handle A)
($handle x))
tensor)
(defmethod tensor-add-mm ((tensor tensor.type) (beta number) (C tensor.type)
(alpha number) (A tensor.type) (B tensor.type))
(ft-tensor-add-mm ($handle tensor)
(tensor-coerce C beta)
($handle C)
(tensor-coerce C alpha)
($handle A)
($handle B))
tensor)
(defmethod tensor-add-r ((tensor tensor.type) (beta number) (A tensor.type)
(alpha number) (x tensor.type) (y tensor.type))
(ft-tensor-add-r ($handle tensor)
(tensor-coerce A beta)
($handle A)
(tensor-coerce A alpha)
($handle x)
($handle y))
tensor)
(defmethod tensor-add-bmm ((tensor tensor.type) (beta number) (C tensor.type)
(alpha number) (A tensor.type) (B tensor.type))
(ft-tensor-add-bmm ($handle tensor)
(tensor-coerce C beta)
($handle C)
(tensor-coerce C alpha)
($handle A)
($handle B))
tensor)
(defmethod tensor-badd-bmm ((tensor tensor.type) (beta number) (C tensor.type)
(alpha number) (A tensor.type) (B tensor.type))
(ft-tensor-badd-bmm ($handle tensor)
(tensor-coerce C beta)
($handle C)
(tensor-coerce C alpha)
($handle A)
($handle B))
tensor)
(defmethod tensor-match ((tensor tensor.type) (m1 tensor.type) (m2 tensor.type) gain)
(ft-tensor-match ($handle tensor)
($handle m1) ($handle m2)
(tensor-coerce tensor gain))
tensor)
(defmethod tensor-max ((vals tensor.type) (indices tensor.long) (src tensor.type) dimension kd)
(ft-tensor-max ($handle vals)
($handle indices)
($handle src)
dimension
(if kd 1 0))
vals)
(defmethod tensor-min ((vals tensor.type) (indices tensor.long) (src tensor.type) dimension kd)
(ft-tensor-min ($handle vals)
($handle indices)
($handle src)
dimension
(if kd 1 0))
vals)
(defmethod tensor-kth-value ((vals tensor.type) (indices tensor.long) (src tensor.type)
k dimension keepdim)
(ft-tensor-kth-value ($handle vals)
($handle indices)
($handle src)
k dimension (if keepdim 1 0))
vals)
(defmethod tensor-kth-value ((vals tensor.type) (indices list) (src tensor.type)
k dimension keepdim)
(let ((idx (tensor.long indices)))
(ft-tensor-kth-value ($handle vals)
($handle idx)
($handle src)
k dimension (if keepdim 1 0)))
vals)
(defmethod tensor-mode ((vals tensor.type) (indices tensor.long) (src tensor.type)
dimension keepdim)
(ft-tensor-mode ($handle vals)
($handle indices)
($handle src)
dimension (if keepdim 1 0))
vals)
(defmethod tensor-mode ((vals tensor.type) (indices list) (src tensor.type)
dimension keepdim)
(let ((idx (tensor.long indices)))
(ft-tensor-mode ($handle vals)
($handle idx)
($handle src)
dimension (if keepdim 1 0)))
vals)
(defmethod tensor-median ((vals tensor.type) (indices tensor.long) (src tensor.type)
dimension keepdim)
(ft-tensor-median ($handle vals)
($handle indices)
($handle src)
dimension (if keepdim 1 0))
vals)
(defmethod tensor-median ((vals tensor.type) (indices list) (src tensor.type)
dimension keepdim)
(let ((idx (tensor.long indices)))
(ft-tensor-median ($handle vals)
($handle idx)
($handle src)
dimension (if keepdim 1 0)))
vals)
(defmethod tensor-sum ((tensor tensor.type) (src tensor.type) dimension keepdim)
(ft-tensor-sum ($handle tensor)
($handle src)
dimension (if keepdim 1 0))
tensor)
(defmethod tensor-prd ((tensor tensor.type) (src tensor.type) dimension keepdim)
(ft-tensor-prod ($handle tensor)
($handle src)
dimension (if keepdim 1 0))
tensor)
(defmethod tensor-cum-sum ((tensor tensor.type) (src tensor.type) dimension)
(ft-tensor-cum-sum ($handle tensor)
($handle src)
dimension)
tensor)
(defmethod tensor-cum-prd ((tensor tensor.type) (src tensor.type) dimension)
(ft-tensor-cum-prod ($handle tensor)
($handle src)
dimension)
tensor)
(defmethod tensor-sign ((tensor tensor.type) (src tensor.type))
(ft-tensor-sign ($handle tensor) ($handle src))
tensor)
(defmethod tensor-trace ((tensor tensor.type)) (ft-tensor-trace ($handle tensor)))
(defmethod tensor-cross ((tensor tensor.type) (A tensor.type) (B tensor.type) dimension)
(ft-tensor-cross ($handle tensor)
($handle A)
($handle B)
dimension)
tensor)
(defmethod tensor-cmax ((tensor tensor.type) (src1 tensor.type) (src2 tensor.type))
(ft-tensor-cmax ($handle tensor) ($handle src1) ($handle src2))
tensor)
(defmethod tensor-cmax ((tensor tensor.type) (src1 tensor.type) (src2 number))
(ft-tensor-cmax-value ($handle tensor) ($handle src1)
(tensor-coerce tensor src2))
tensor)
(defmethod tensor-cmin ((tensor tensor.type) (src1 tensor.type) (src2 tensor.type))
(ft-tensor-cmin ($handle tensor) ($handle src1) ($handle src2))
tensor)
(defmethod tensor-cmin ((tensor tensor.type) (src1 tensor.type) (src2 number))
(ft-tensor-cmin-value ($handle tensor) ($handle src1)
(tensor-coerce tensor src2))
tensor)
(defmethod tensor-zeros ((tensor tensor.type) (size storage.long))
(ft-tensor-zeros ($handle tensor) ($handle size))
tensor)
(defmethod tensor-zeros ((tensor tensor.type) (size list))
(when size
(let ((s (storage.long size)))
(ft-tensor-zeros ($handle tensor) ($handle s))
tensor)))
(defmethod tensor-zeros ((tensor tensor.type) (src tensor.type))
(ft-tensor-zeros ($handle tensor) ($size src))
tensor)
(defmethod tensor-ones ((tensor tensor.type) (size storage.long))
(ft-tensor-ones ($handle tensor) ($handle size))
tensor)
(defmethod tensor-ones ((tensor tensor.type) (size list))
(when size
(let ((s (storage.long size)))
(ft-tensor-ones ($handle tensor) ($handle s))
tensor)))
(defmethod tensor-ones ((tensor tensor.type) (src tensor.type))
(ft-tensor-ones ($handle tensor) ($size src))
tensor)
(defmethod tensor-diag ((tensor tensor.type) (src tensor.type) k)
(ft-tensor-diag ($handle tensor) ($handle src) k)
tensor)
(defmethod tensor-eye ((tensor tensor.type) nrow ncol)
(ft-tensor-eye ($handle tensor) nrow ncol)
tensor)
(defmethod tensor-arange ((tensor tensor.type) xmin xmax step)
(ft-tensor-arange ($handle tensor)
(tensor-acoerce tensor xmin)
(tensor-acoerce tensor xmax)
(tensor-acoerce tensor step))
tensor)
(defmethod tensor-range ((tensor tensor.type) xmin xmax step)
(ft-tensor-range ($handle tensor)
(tensor-acoerce tensor xmin)
(tensor-acoerce tensor xmax)
(tensor-acoerce tensor step))
tensor)
(defmethod tensor-rand-perm ((tensor tensor.type) n &optional generator)
(ft-tensor-rand-perm ($handle tensor) ($handle (or generator *generator*)) n)
tensor)
(defmethod tensor-reshape ((tensor tensor.type) (src tensor.type) (size storage.long))
(ft-tensor-reshape ($handle tensor) ($handle src) ($handle size))
tensor)
(defmethod tensor-reshape ((tensor tensor.type) (src tensor.type) (size list))
(when size
(let ((s (storage.long size)))
(ft-tensor-reshape ($handle tensor) ($handle src) ($handle s))))
tensor)
(defmethod tensor-sort ((tensor tensor.type) (indices tensor.long) (src tensor.type)
dimension descending)
(ft-tensor-sort ($handle tensor)
($handle indices)
($handle src)
dimension
(if descending 1 0))
tensor)
(defmethod tensor-sort ((tensor tensor.type) (indices list) (src tensor.type)
dimension descending)
(when indices
(let ((idx (tensor.long indices)))
(ft-tensor-sort ($handle tensor)
($handle idx)
($handle src)
dimension
(if descending 1 0))))
tensor)
(defmethod tensor-top-k ((tensor tensor.type) (indices tensor.long) (src tensor.type)
k dim descending sorted)
(ft-tensor-topk ($handle tensor) ($handle indices)
($handle src)
k dim (if descending 1 0) (if sorted 1 0))
tensor)
(defmethod tensor-tri-l ((tensor tensor.type) (src tensor.type) k)
(ft-tensor-tril ($handle tensor) ($handle src) k)
tensor)
(defmethod tensor-tri-u ((tensor tensor.type) (src tensor.type) k)
(ft-tensor-triu ($handle tensor) ($handle src) k)
tensor)
(defmethod tensor-catn ((tensor tensor.type) dimension srcs)
(let ((n ($count srcs)))
(cffi:with-foreign-object (inputs :pointer n)
(loop :for s :in srcs
:for i :from 0
:do (setf (cffi:mem-aref inputs :pointer i) ($handle s)))
(ft-tensor-cat-array ($handle tensor) inputs n dimension))
tensor))
(defmethod tensor-cat ((tensor tensor.type) dimension &rest srcs)
(cond ((null srcs) tensor)
((eq 1 ($count srcs)) (tensor-set tensor (tensor-clone ($0 srcs))))
((eq 2 ($count srcs)) (progn
(ft-tensor-cat ($handle tensor)
($handle ($0 srcs))
($handle ($1 srcs))
dimension)
tensor))
(t (progn
(tensor-catn tensor dimension srcs)
tensor))))
(defmethod tensor-cat2 ((tensor tensor.type) dimension (src1 tensor.type) (src2 tensor.type))
(ft-tensor-cat ($handle tensor) ($handle src1) ($handle src2) dimension)
tensor)
(defmethod tensor-equal ((tensora tensor.type) (tensorb tensor.type))
(eq 1 (ft-tensor-equal ($handle tensora) ($handle tensorb))))
(defmethod tensor-compare (operation (tensor tensor.type) (src1 tensor.type) (src2 number))
(cond ((eq operation :lt) (progn (ft-tensor-lt-value-t ($handle tensor)
($handle src1)
(tensor-coerce src1 src2))
tensor))
((eq operation :le) (progn (ft-tensor-le-value-t ($handle tensor)
($handle src1)
(tensor-coerce src1 src2))
tensor))
((eq operation :gt) (progn (ft-tensor-gt-value-t ($handle tensor)
($handle src1)
(tensor-coerce src1 src2))
tensor))
((eq operation :ge) (progn (ft-tensor-ge-value-t ($handle tensor)
($handle src1)
(tensor-coerce src1 src2))
tensor))
((eq operation :ne) (progn (ft-tensor-ne-value-t ($handle tensor)
($handle src1)
(tensor-coerce src1 src2))
tensor))
((eq operation :eq) (progn (ft-tensor-eq-value-t ($handle tensor)
($handle src1)
(tensor-coerce src1 src2))
tensor))))
(defmethod tensor-compare (operation (tensor tensor.type) (src1 tensor.type) (src2 tensor.type))
(cond ((eq operation :lt) (progn (ft-tensor-lt-tensor-t ($handle tensor)
($handle src1)
($handle src2))
tensor))
((eq operation :le) (progn (ft-tensor-le-tensor-t ($handle tensor)
($handle src1)
($handle src2))
tensor))
((eq operation :gt) (progn (ft-tensor-gt-tensor-t ($handle tensor)
($handle src1)
($handle src2))
tensor))
((eq operation :ge) (progn (ft-tensor-ge-tensor-t ($handle tensor)
($handle src1)
($handle src2))
tensor))
((eq operation :ne) (progn (ft-tensor-ne-tensor-t ($handle tensor)
($handle src1)
($handle src2))
tensor))
((eq operation :eq) (progn (ft-tensor-eq-tensor-t ($handle tensor)
($handle src1)
($handle src2))
tensor))))
(defmethod tensor-compare (operation (tensor tensor.byte) (src1 tensor.type) (src2 number))
(cond ((eq operation :lt) (progn (ft-tensor-lt-value ($handle tensor)
($handle src1)
(tensor-coerce src1 src2))
tensor))
((eq operation :le) (progn (ft-tensor-le-value ($handle tensor)
($handle src1)
(tensor-coerce src1 src2))
tensor))
((eq operation :gt) (progn (ft-tensor-gt-value ($handle tensor)
($handle src1)
(tensor-coerce src1 src2))
tensor))
((eq operation :ge) (progn (ft-tensor-ge-value ($handle tensor)
($handle src1)
(tensor-coerce src1 src2))
tensor))
((eq operation :ne) (progn (ft-tensor-ne-value ($handle tensor)
($handle src1)
(tensor-coerce src1 src2))
tensor))
((eq operation :eq) (progn (ft-tensor-eq-value ($handle tensor)
($handle src1)
(tensor-coerce src1 src2))
tensor))))
(defmethod tensor-compare (operation (tensor tensor.byte) (src1 tensor.type) (src2 tensor.type))
(cond ((eq operation :lt) (progn (ft-tensor-lt-tensor ($handle tensor)
($handle src1)
($handle src2))
tensor))
((eq operation :le) (progn (ft-tensor-le-tensor ($handle tensor)
($handle src1)
($handle src2))
tensor))
((eq operation :gt) (progn (ft-tensor-gt-tensor ($handle tensor)
($handle src1)
($handle src2))
tensor))
((eq operation :ge) (progn (ft-tensor-ge-tensor ($handle tensor)
($handle src1)
($handle src2))
tensor))
((eq operation :ne) (progn (ft-tensor-ne-tensor ($handle tensor)
($handle src1)
($handle src2))
tensor))
((eq operation :eq) (progn (ft-tensor-eq-tensor ($handle tensor)
($handle src1)
($handle src2))
tensor))))
(defmethod tensor-conv-2d-rev-ger ((result tensor.type) beta alpha (tensor tensor.type)
(k tensor.type) srow scol)
(ft-tensor-conv-2d-rev-ger ($handle result)
(tensor-coerce tensor beta)
(tensor-coerce tensor alpha)
($handle tensor)
($handle k)
srow scol))
(defmethod tensor-conv-2d-rev-germ ((result tensor.type) beta alpha (tensor tensor.type)
(k tensor.type) srow scol)
(ft-tensor-conv-2d-rev-germ ($handle result)
(tensor-coerce tensor beta)
(tensor-coerce tensor alpha)
($handle tensor)
($handle k)
srow scol))
(defmethod tensor-conv-2d-ger ((result tensor.type) beta alpha (tensor tensor.type)
(k tensor.type) srow scol vf xc)
(ft-tensor-conv-2d-ger ($handle result)
(tensor-coerce tensor beta)
(tensor-coerce tensor alpha)
($handle tensor)
($handle k)
srow scol vf xc))
(defmethod tensor-conv-2d-mv ((result tensor.type) beta alpha (tensor tensor.type)
(k tensor.type) srow scol vf xc)
(ft-tensor-conv-2d-mv ($handle result)
(tensor-coerce tensor beta)
(tensor-coerce tensor alpha)
($handle tensor)
($handle k)
srow scol vf xc))
(defmethod tensor-conv-2d-mm ((result tensor.type) beta alpha (tensor tensor.type)
(k tensor.type) srow scol vf xc)
(ft-tensor-conv-2d-mm ($handle result)
(tensor-coerce tensor beta)
(tensor-coerce tensor alpha)
($handle tensor)
($handle k)
srow scol vf xc))
(defmethod tensor-conv-2d-mul ((result tensor.type) beta alpha (tensor tensor.type)
(k tensor.type) srow scol vf xc)
(ft-tensor-conv-2d-mul ($handle result)
(tensor-coerce tensor beta)
(tensor-coerce tensor alpha)
($handle tensor)
($handle k)
srow scol vf xc))
(defmethod tensor-conv-2d-cmul ((result tensor.type) beta alpha (tensor tensor.type)
(k tensor.type) srow scol vf xc)
(ft-tensor-conv-2d-cmul ($handle result)
(tensor-coerce tensor beta)
(tensor-coerce tensor alpha)
($handle tensor)
($handle k)
srow scol vf xc))
(defmethod tensor-conv-3d-rev-ger ((result tensor.type) beta alpha (tensor tensor.type)
(k tensor.type) sdepth srow scol)
(ft-tensor-conv-3d-rev-ger ($handle result)
(tensor-coerce tensor beta)
(tensor-coerce tensor alpha)
($handle tensor)
($handle k)
sdepth srow scol))
(defmethod tensor-conv-3d-ger ((result tensor.type) beta alpha (tensor tensor.type)
(k tensor.type) sdepth srow scol vf xc)
(ft-tensor-conv-3d-ger ($handle result)
(tensor-coerce tensor beta)
(tensor-coerce tensor alpha)
($handle tensor)
($handle k)
sdepth srow scol vf xc))
(defmethod tensor-conv-3d-mv ((result tensor.type) beta alpha (tensor tensor.type)
(k tensor.type) sdepth srow scol vf xc)
(ft-tensor-conv-3d-mv ($handle result)
(tensor-coerce tensor beta)
(tensor-coerce tensor alpha)
($handle tensor)
($handle k)
sdepth srow scol vf xc))
(defmethod tensor-conv-3d-mul ((result tensor.type) beta alpha (tensor tensor.type)
(k tensor.type) sdepth srow scol vf xc)
(ft-tensor-conv-3d-mul ($handle result)
(tensor-coerce tensor beta)
(tensor-coerce tensor alpha)
($handle tensor)
($handle k)
sdepth srow scol vf xc))
(defmethod tensor-conv-3d-cmul ((result tensor.type) beta alpha (tensor tensor.type)
(k tensor.type) sdepth srow scol vf xc)
(ft-tensor-conv-3d-cmul ($handle result)
(tensor-coerce tensor beta)
(tensor-coerce tensor alpha)
($handle tensor)
($handle k)
sdepth srow scol vf xc))))
(loop :for ti :in *th-type-infos*
:for type = (car ti)
:do (loop :for fimpl :in *tensor-generic-interface-implementations*
:do (eval (%%gen-impl fimpl type))))
(defparameter *tensor-generic-interface-fractional-implementations*
'((defmethod tensor-uniform ((tensor tensor.type) a b &optional generator)
(ft-tensor-uniform ($handle tensor) ($handle (or generator *generator*))
(tensor-acoerce tensor a)
(tensor-acoerce tensor b))
tensor)
(defmethod tensor-normal ((tensor tensor.type) (mean number) (stdev number) &optional generator)
(ft-tensor-normal ($handle tensor) ($handle (or generator *generator*))
(tensor-acoerce tensor mean)
(tensor-acoerce tensor stdev))
tensor)
(defmethod tensor-exponential ((tensor tensor.type) lam &optional generator)
(ft-tensor-exponential ($handle tensor) ($handle (or generator *generator*))
(tensor-acoerce tensor lam))
tensor)
(defmethod tensor-cauchy ((tensor tensor.type) median sigma &optional generator)
(ft-tensor-cauchy ($handle tensor) ($handle (or generator *generator*))
(tensor-acoerce tensor median)
(tensor-acoerce tensor sigma))
tensor)
(defmethod tensor-log-normal ((tensor tensor.type) mean stdev &optional generator)
(ft-tensor-log-normal ($handle tensor) ($handle (or generator *generator*))
(tensor-acoerce tensor mean)
(tensor-acoerce tensor stdev))
tensor)
(defmethod tensor-multinomial ((tensor tensor.long) (pdist tensor.type) nsample replacement
&optional generator)
(ft-tensor-multinomial ($handle tensor)
($handle (or generator *generator*))
($handle pdist)
nsample
(if replacement 1 0))
tensor)
(defmethod tensor-rbeta ((tensor tensor.type) a b &optional generator)
(ft-tensor-rbeta ($handle tensor) ($handle (or generator *generator*))
(tensor-acoerce tensor a)
(tensor-acoerce tensor b))
tensor)
(defmethod tensor-rgamma ((tensor tensor.type) shape scale &optional generator)
(ft-tensor-rgamma ($handle tensor) ($handle (or generator *generator*))
(tensor-acoerce tensor shape)
(tensor-acoerce tensor scale))
tensor)
(defmethod tensor-multinomial-alias-setup ((pdist tensor.type) (J tensor.long) (q tensor.type))
(ft-tensor-multinomial-alias-setup ($handle pdist)
($handle J)
($handle q))
pdist)
(defmethod tensor-multinomial-alias-draw ((tensor tensor.type) (J tensor.long) (q tensor.type)
&optional generator)
(ft-tensor-multinomial-alias-draw ($handle tensor)
($handle (or generator *generator*))
($handle J)
($handle q))
tensor)
(defmethod tensor-cinv ((tensor tensor.type) (src tensor.type))
(ft-tensor-cinv ($handle tensor) ($handle src))
tensor)
(defmethod tensor-sigmoid ((tensor tensor.type) (src tensor.type))
(ft-tensor-sigmoid ($handle tensor) ($handle src))
tensor)
(defmethod tensor-log ((tensor tensor.type) (src tensor.type))
(ft-tensor-log ($handle tensor) ($handle src))
tensor)
(defmethod tensor-gamma ((tensor tensor.type) (src tensor.type))
(ft-tensor-gamma ($handle tensor) ($handle src))
tensor)
(defmethod tensor-lgamma ((tensor tensor.type) (src tensor.type))
(ft-tensor-lgamma ($handle tensor) ($handle src))
tensor)
(defmethod tensor-erf ((tensor tensor.type) (src tensor.type))
(ft-tensor-erf ($handle tensor) ($handle src))
tensor)
(defmethod tensor-erfc ((tensor tensor.type) (src tensor.type))
(ft-tensor-erfc ($handle tensor) ($handle src))
tensor)
(defmethod tensor-polygamma ((tensor tensor.type) (src tensor.type) n)
(ft-tensor-polygamma n ($handle src) ($handle tensor))
tensor)
(defmethod tensor-lbeta ((tensor tensor.type) (a tensor.type) (b tensor.type))
(ft-tensor-lbeta ($handle a) ($handle b) ($handle tensor))
tensor)
(defmethod tensor-log1p ((tensor tensor.type) (src tensor.type))
(ft-tensor-log1p ($handle tensor) ($handle src))
tensor)
(defmethod tensor-exp ((tensor tensor.type) (src tensor.type))
(ft-tensor-exp ($handle tensor) ($handle src))
tensor)
(defmethod tensor-cos ((tensor tensor.type) (src tensor.type))
(ft-tensor-cos ($handle tensor) ($handle src))
tensor)
(defmethod tensor-acos ((tensor tensor.type) (src tensor.type))
(ft-tensor-acos ($handle tensor) ($handle src))
tensor)
(defmethod tensor-cosh ((tensor tensor.type) (src tensor.type))
(ft-tensor-cosh ($handle tensor) ($handle src))
tensor)
(defmethod tensor-sin ((tensor tensor.type) (src tensor.type))
(ft-tensor-sin ($handle tensor) ($handle src))
tensor)
(defmethod tensor-asin ((tensor tensor.type) (src tensor.type))
(ft-tensor-asin ($handle tensor) ($handle src))
tensor)
(defmethod tensor-sinh ((tensor tensor.type) (src tensor.type))
(ft-tensor-sinh ($handle tensor) ($handle src))
tensor)
(defmethod tensor-tan ((tensor tensor.type) (src tensor.type))
(ft-tensor-tan ($handle tensor) ($handle src))
tensor)
(defmethod tensor-atan ((tensor tensor.type) (src tensor.type))
(ft-tensor-atan ($handle tensor) ($handle src))
tensor)
(defmethod tensor-atan2 ((tensor tensor.type) (tensorx tensor.type) (tensory tensor.type))
(ft-tensor-atan2 ($handle tensor) ($handle tensorx) ($handle tensory))
tensor)
(defmethod tensor-tanh ((tensor tensor.type) (src tensor.type))
(ft-tensor-tanh ($handle tensor) ($handle src))
tensor)
(defmethod tensor-pow ((tensor tensor.type) (src tensor.type) (exponent number))
(ft-tensor-pow ($handle tensor) ($handle src) (tensor-coerce tensor exponent))
tensor)
(defmethod tensor-pow ((tensor tensor.type) (src number) (exponent tensor.type))
(ft-tensor-tpow ($handle tensor)
(tensor-coerce tensor src) ($handle exponent))
tensor)
(defmethod tensor-sqrt ((tensor tensor.type) (src tensor.type))
(ft-tensor-sqrt ($handle tensor) ($handle src))
tensor)
(defmethod tensor-rsqrt ((tensor tensor.type) (src tensor.type))
(ft-tensor-rsqrt ($handle tensor) ($handle src))
tensor)
(defmethod tensor-ceil ((tensor tensor.type) (src tensor.type))
(ft-tensor-ceil ($handle tensor) ($handle src))
tensor)
(defmethod tensor-floor ((tensor tensor.type) (src tensor.type))
(ft-tensor-floor ($handle tensor) ($handle src))
tensor)
(defmethod tensor-round ((tensor tensor.type) (src tensor.type))
(ft-tensor-round ($handle tensor) ($handle src))
tensor)
(defmethod tensor-abs ((tensor tensor.type) (src tensor.type))
(ft-tensor-abs ($handle tensor) ($handle src))
tensor)
(defmethod tensor-trunc ((tensor tensor.type) (src tensor.type))
(ft-tensor-trunc ($handle tensor) ($handle src))
tensor)
(defmethod tensor-frac ((tensor tensor.type) (src tensor.type))
(ft-tensor-frac ($handle tensor) ($handle src))
tensor)
(defmethod tensor-lerp ((tensor tensor.type) (a tensor.type) (b tensor.type) weight)
(ft-tensor-lerp ($handle tensor)
($handle a)
($handle b)
(tensor-coerce a weight))
tensor)
(defmethod tensor-mean ((tensor tensor.type) (src tensor.type) dimension keepdim)
(ft-tensor-mean ($handle tensor) ($handle src)
dimension (if keepdim 1 0))
tensor)
(defmethod tensor-sd ((tensor tensor.type) (src tensor.type) dimension keepdim
&optional biased)
(ft-tensor-std ($handle tensor) ($handle src)
dimension (if biased 1 0) (if keepdim 1 0))
tensor)
(defmethod tensor-var ((tensor tensor.type) (src tensor.type) dimension keepdim
&optional biased)
(ft-tensor-var ($handle tensor) ($handle src)
dimension (if biased 1 0) (if keepdim 1 0))
tensor)
(defmethod tensor-norm ((tensor tensor.type) (src tensor.type) value dimension keep-dim)
(ft-tensor-norm ($handle tensor)
($handle src)
(tensor-coerce tensor value)
dimension
(if keep-dim 1 0))
tensor)
(defmethod tensor-renorm ((tensor tensor.type) (src tensor.type) value dimension maxnorm)
(ft-tensor-renorm ($handle tensor)
($handle src)
(tensor-coerce tensor value)
dimension
(tensor-coerce tensor maxnorm))
tensor)
(defmethod tensor-dist ((tensora tensor.type) (tensorb tensor.type) value)
(ft-tensor-dist ($handle tensora) ($handle tensorb) (tensor-coerce tensora value)))
(defmethod tensor-histc ((hist tensor.type) (src tensor.type) nbins minvalue maxvalue)
(ft-tensor-histc ($handle hist)
($handle src)
nbins
(tensor-coerce hist minvalue)
(tensor-coerce hist maxvalue))
hist)
(defmethod tensor-bhistc ((hist tensor.type) (src tensor.type) nbins minvalue maxvalue)
(ft-tensor-bhistc ($handle hist)
($handle src)
nbins
(tensor-coerce hist minvalue)
(tensor-coerce hist maxvalue))
hist)
(defmethod tensor-mean-all ((tensor tensor.type)) (ft-tensor-mean-all ($handle tensor)))
(defmethod tensor-var-all ((tensor tensor.type) &optional biased)
(ft-tensor-varall ($handle tensor) (if biased 1 0)))
(defmethod tensor-sd-all ((tensor tensor.type) &optional biased)
(ft-tensor-std-all ($handle tensor) (if biased 1 0)))
(defmethod tensor-norm-all ((tensor tensor.type) value)
(ft-tensor-norm-all ($handle tensor) (tensor-coerce tensor value)))
(defmethod tensor-linspace ((tensor tensor.type) a b n)
(ft-tensor-linspace ($handle tensor) (tensor-coerce tensor a) (tensor-coerce tensor b) n)
tensor)
(defmethod tensor-logspace ((tensor tensor.type) a b n)
(ft-tensor-logspace ($handle tensor) (tensor-coerce tensor a) (tensor-coerce tensor b) n)
tensor)
(defmethod tensor-rand ((tensor tensor.type) (size storage.long) &optional generator)
(ft-tensor-rand ($handle tensor) ($handle (or generator *generator*)) ($handle size))
tensor)
(defmethod tensor-rand ((tensor tensor.type) (size list) &optional generator)
(when size
(let ((s (storage.long size)))
(ft-tensor-rand ($handle tensor) ($handle (or generator *generator*)) ($handle s))))
tensor)
(defmethod tensor-randn ((tensor tensor.type) (size storage.long) &optional generator)
(ft-tensor-randn ($handle tensor) ($handle (or generator *generator*)) ($handle size))
tensor)
(defmethod tensor-randn ((tensor tensor.type) (size list) &optional generator)
(when size
(let ((s (storage.long size)))
(ft-tensor-randn ($handle tensor) ($handle (or generator *generator*)) ($handle s))))
tensor)
(defmethod tensor-gesv ((rb tensor.type) (ra tensor.type) (b tensor.type) (a tensor.type))
(ft-tensor-gesv ($handle rb)
($handle ra)
($handle b)
($handle a)))
(defmethod tensor-trtrs ((rb tensor.type) (ra tensor.type) (b tensor.type) (a tensor.type)
uplo trans diag)
(ft-tensor-trtrs ($handle rb)
($handle ra)
($handle b)
($handle a)
(if uplo "U" "L")
(if trans "T" "N")
(if diag "U" "N")))
(defmethod tensor-gels ((rb tensor.type) (ra tensor.type) (b tensor.type) (a tensor.type))
(ft-tensor-gels ($handle rb)
($handle ra)
($handle b)
($handle a)))
(defmethod tensor-syev ((re tensor.type) (rv tensor.type) (a tensor.type) jobz uplo)
(ft-tensor-syev ($handle re)
($handle rv)
($handle a)
(if jobz "V" "N")
(if uplo "U" "L")))
(defmethod tensor-geev ((re tensor.type) (rv tensor.type) (a tensor.type) jobvr)
(ft-tensor-geev ($handle re)
($handle rv)
($handle a)
(if jobvr "V" "N")))
(defmethod tensor-gesvd ((ru tensor.type) (rs tensor.type) (rv tensor.type)
(a tensor.type) jobu)
(ft-tensor-gesvd ($handle ru)
($handle rs)
($handle rv)
($handle a)
(if jobu "A" "S")))
(defmethod tensor-gesvd2 ((ru tensor.type) (rs tensor.type) (rv tensor.type)
(ra tensor.type) (a tensor.type) jobu)
(ft-tensor-gesvd2 ($handle ru)
($handle rs)
($handle rv)
($handle ra)
($handle a)
(if jobu "A" "S")))
(defmethod tensor-getri ((ra tensor.type) (a tensor.type))
(ft-tensor-getri ($handle ra) ($handle a)))
(defmethod tensor-potrf ((ra tensor.type) (a tensor.type) uplo)
(ft-tensor-potrf ($handle ra)
($handle a)
(if uplo "U" "L")))
(defmethod tensor-potrs ((rb tensor.type) (b tensor.type) (a tensor.type) uplo)
(ft-tensor-potrs ($handle rb)
($handle b)
($handle a)
(if uplo "U" "L")))
(defmethod tensor-potri ((ra tensor.type) (a tensor.type) uplo)
(ft-tensor-potri ($handle ra)
($handle a)
(if uplo "U" "L")))
(defmethod tensor-qr ((rq tensor.type) (rr tensor.type) (a tensor.type))
(ft-tensor-qr ($handle rq) ($handle rr) ($handle a)))
(defmethod tensor-geqrf ((ra tensor.type) (rtau tensor.type) (a tensor.type))
(ft-tensor-geqrf ($handle ra) ($handle rtau) ($handle a)))
(defmethod tensor-orgqr ((ra tensor.type) (a tensor.type) (tau tensor.type))
(ft-tensor-orgqr ($handle ra) ($handle a) ($handle tau)))
(defmethod tensor-ormqr ((ra tensor.type) (a tensor.type) (tau tensor.type)
(c tensor.type) left trans)
(ft-tensor-ormqr ($handle ra)
($handle a)
($handle tau)
($handle c)
(if left "L" "R")
(if trans "T" "N")))
(defmethod tensor-pstrf ((ra tensor.type) (rpiv tensor.int) (a tensor.type) uplo tol)
(ft-tensor-pstrf ($handle ra)
($handle rpiv)
($handle a)
(if uplo "U" "L")
(tensor-coerce ra tol)))
(defmethod tensor-btrifact ((ra tensor.type) (rpivots tensor.int) (rinfo tensor.int)
(a tensor.type) pivot)
(ft-tensor-btrifact ($handle ra)
($handle rpivots)
($handle rinfo)
(if pivot 1 0)
($handle a)))
(defmethod tensor-btrisolve ((rb tensor.type) (b tensor.type) (atf tensor.type)
(pivots tensor.int))
(ft-tensor-btrisolve ($handle rb)
($handle b)
($handle atf)
($handle pivots)))))
(loop :for ti :in (last *th-type-infos* 2)
:for type = (car ti)
:do (loop :for fimpl :in *tensor-generic-interface-fractional-implementations*
:do (eval (%%gen-impl fimpl type))))
| 75,625
|
Common Lisp
|
.lisp
| 1,427
| 37.238262
| 100
| 0.531338
|
chunsj/TH
| 59
| 8
| 0
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
270b955bab75a3a0ae73ae594569eb89b1e65bfa440ccf902a149cbbc672c809
| 3,162
|
[
-1
] |
3,163
|
interface.lisp
|
chunsj_TH/private/interface.lisp
|
(declaim (optimize (speed 3) (debug 1) (safety 0)))
(in-package :th)
(defgeneric tensor-coerce (tensor value)
(:documentation "returns coerced value for given tensor"))
(defgeneric tensor-acoerce (tensor value)
(:documentation "returns coerced value for given tensor for accumulated type"))
(defgeneric tensor-type (tensor)
(:documentation "returns type of elements of the tensor"))
(defgeneric tensor-at (tensor location &rest others)
(:documentation "accessing tensor elements"))
(defgeneric (setf tensor-at) (value tensor location &rest others)
(:documentation "setf for tensor-at method"))
(defgeneric tensor-storage (tensor)
(:documentation "returns storage of the tensor"))
(defgeneric tensor-storage-offset (tensor)
(:documentation "returns the 1st index used in tensor's storage"))
(defgeneric tensor-n-dimension (tensor)
(:documentation "returns the number of dimensions of given tensor"))
(defgeneric tensor-size (tensor dimension)
(:documentation "returns dimensions of the tensor"))
(defgeneric tensor-stride (tensor dimension)
(:documentation "returns the jumps to go from one to next element in tensor"))
(defgeneric tensor-data (tensor)
(:documentation "returns pointer for tensor data"))
(defgeneric tensor-with-tensor (tensor)
(:documentation "returns a new tensor which shared the same storage of the given tensor"))
(defgeneric tensor-clone (tensor)
(:documentation "returns a new cloned tensor"))
(defgeneric tensor-contiguous (tensor)
(:documentation "returns a new contiguously allocated layout tensor if it's not"))
(defgeneric tensor-with-storage (storage &optional storage-offset size stride)
(:documentation "returns a new tensor with given storage"))
(defgeneric tensor-new-select (tensor dimension slice-index)
(:documentation "returns a new tensor slice at the slice-index in the given dimension"))
(defgeneric tensor-new-narrow (tensor dimension first-index size)
(:documentation "returns a new tensor that is a narrowed version of src tensor"))
(defgeneric tensor-new-transpose (tensor)
(:documentation "returns a new tensor that is the transposed view of the tensor"))
(defgeneric tensor-new-unfold (tensor dimension size step)
(:documentation "returns a new tensor which contains all slice of the given size by step"))
(defgeneric tensor-new-view (tensor size)
(:documentation "returns a new tensor which different dimensions of the same storage"))
(defgeneric tensor-expand (tensor src size)
(:documentation "returns a new view of the src with singleton dimension expanded"))
(defgeneric tensor-resize-as (tensor src))
(defgeneric tensor-resize (tensor size &optional stride))
(defgeneric tensor-set (tensor src))
(defgeneric tensor-set-storage (tensor storage offset size stride))
(defgeneric tensor-narrow (tensor src dimension first-idx size)
(:documentation "returns a tensor that is a narrowed version of src tensor"))
(defgeneric tensor-select (tensor src dimension slice-index)
(:documentation "returns a tensor which is a slice at the given index in the dim"))
(defgeneric tensor-transpose (tensor src dimension0 dimension1)
(:documentation "returns a transposed tensor between dimensions"))
(defgeneric tensor-unfold (tensor src dimension size step))
(defgeneric tensor-squeeze (tensor src &optional dimension)
(:documentation "removes all the dimensions with size 1"))
(defgeneric tensor-unsqueeze (tensor src dimension))
(defgeneric tensor-contiguous-p (tensor)
(:documentation "check whether tensor is contiguous in memory in C order"))
(defgeneric tensor-same-size-p (tensor src))
(defgeneric tensor-set-to-p (tensor src))
(defgeneric tensor-size-p (tensor dims))
(defgeneric tensor-n-element (tensor))
(defgeneric tensor-copy (tensor src)
(:documentation "returns the already same sized element-wise copied tensor from the source"))
(defgeneric tensor-random (tensor &optional generator))
(defgeneric tensor-geometric (tensor p &optional generator)
(:documentation "returns geometric(p) element-wise"))
(defgeneric tensor-bernoulli (tensor p &optional generator)
(:documentation "returns bernoulli(p) element-wise"))
(defgeneric tensor-binomial (tensor n p &optional generaor)
(:documentation "returns binomial(n,p) element-wise"))
(defgeneric tensor-hypergeometric (tensor nr nb k &optional generator)
(:documentation "returns hypergeometric(nr, nb, k) element-wise"))
(defgeneric tensor-poisson (tensor mu &optional generator)
(:documentation "returns poisson(mu) element-wise" ))
(defgeneric tensor-uniform (tensor a b &optional generator)
(:documentation "returns tensor filled with number drawn from uniform distribution"))
(defgeneric tensor-normal (tensor mean stdev &optional generator)
(:documentation "returns tensor filled with numbers drawn from normal distribution"))
(defgeneric tensor-exponential (tensor lam &optional generator)
(:documentation "returns tensor filled with numbers drawn from exponential distribution"))
(defgeneric tensor-cauchy (tensor median sigma &optional generator)
(:documentation "returns tensor filled with numbers drawn from cauchy distribution"))
(defgeneric tensor-log-normal (tensor mean stdev &optional generator)
(:documentation "returns tensor filled with numbers drawn from log normal distribution"))
(defgeneric tensor-rbeta (tensor a b &optional generator)
(:documentation "returns tensor filled with numbers drawn from beta distribution"))
(defgeneric tensor-rgamma (tensor shape scale &optional generator)
(:documentation "returns tensor filled with numbers drawn from gamma distribution"))
(defgeneric tensor-multinomial (tensor pdist nsample replacement &optional generator)
(:documentation "returns tensor filled with numbers drawn from multinomial distribution"))
(defgeneric tensor-multinomial-alias-setup (pdist J q))
(defgeneric tensor-multinomial-alias-draw (tensor J q &optional generator))
(defgeneric tensor-fill (tensor value)
(:documentation "fills element of the tensor with value"))
(defgeneric tensor-zero (tensor)
(:documentation "fills element of the tensor with zero"))
(defgeneric tensor-masked-fill (tensor mask value)
(:documentation "fills element of tensor at the location of one in byte tensor mask"))
(defgeneric tensor-masked-copy (tensor mask src))
(defgeneric tensor-masked-select (tensor mask src)
(:documentation "returns a vector from elements of src masked by byte mask"))
(defgeneric tensor-non-zero (tensor &optional indices)
(:documentation "returns indices of non zero elements in tnsor"))
(defgeneric tensor-index-select (tensor src dim index))
(defgeneric tensor-index-copy (tensor src dim index))
(defgeneric tensor-index-add (tensor src dim index))
(defgeneric tensor-index-fill (tensor value dim index))
(defgeneric tensor-gather (tensor src dim index))
(defgeneric tensor-scatter (tensor src dim index))
(defgeneric tensor-scatter-add (tensor src dim index))
(defgeneric tensor-scatter-fill (tensor value dim index))
(defgeneric tensor-dot (tensor1 tensor2)
(:documentation "returns dot product of two tensors"))
(defgeneric tensor-min-all (tensor))
(defgeneric tensor-max-all (tensor))
(defgeneric tensor-median-all (tensor))
(defgeneric tensor-sum-all (tensor))
(defgeneric tensor-prd-all (tensor))
(defgeneric tensor-neg (tensor src))
(defgeneric tensor-cinv (tensor src))
(defgeneric tensor-add (tensor src value)
(:documentation "returns element-wise addition of scalar value"))
(defgeneric tensor-sub (tensor src value))
(defgeneric tensor-mul (tensor src value))
(defgeneric tensor-div (tensor src value)
(:documentation "returns element-wise division of scalar value"))
(defgeneric tensor-mod (tensor src value))
(defgeneric tensor-fmod (tensor src value)
(:documentation "returns element-wise remainders"))
(defgeneric tensor-clamp (tensor src min max)
(:documentation "returns tensor with its elements clamped between min and max"))
(defgeneric tensor-lshift (tensor src value))
(defgeneric tensor-rshift (tensor src value))
(defgeneric tensor-bitand (tensor src value))
(defgeneric tensor-bitor (tensor src value))
(defgeneric tensor-bitxor (tensor src value))
(defgeneric tensor-cadd (tensor src1 value src2))
(defgeneric tensor-csub (tensor src1 value src2))
(defgeneric tensor-cmul (tensor src1 src2))
(defgeneric tensor-cpow (tensor src1 src2))
(defgeneric tensor-cdiv (tensor src1 src2))
(defgeneric tensor-clshift (tensor src1 src2))
(defgeneric tensor-crshift (tensor src1 src2))
(defgeneric tensor-cmod (tensor src1 src2))
(defgeneric tensor-cfmod (tensor src1 src2))
(defgeneric tensor-cbitand (tensor src1 src2))
(defgeneric tensor-cbitor (tensor src1 src2))
(defgeneric tensor-cbitxor (tensor src1 src2))
(defgeneric tensor-add-cmul (tensor src1 value src2 src3)
(:documentation "returns src1 + value * src2 * src3, element-wise"))
(defgeneric tensor-add-cdiv (tensor src1 value src2 src3)
(:documentation "returns src1 + value * (src2 / src3), element-wise"))
(defgeneric tensor-add-mv (tensor beta y alpha A x)
(:documentation "returns beta * y + alpha * A @ x"))
(defgeneric tensor-add-mm (tensor beta C alpha A B)
(:documentation "returns beta * C + alpha * A @ B"))
(defgeneric tensor-add-r (tensor beta A alpha x y)
(:documentation "returns beta * A + alpha * (x cross y)"))
(defgeneric tensor-add-bmm (tensor beta C alpha batchA batchB)
(:documentation "returns beta * C + alpha * [sum of batchA @ batch B]"))
(defgeneric tensor-badd-bmm (tensor beta batchC alpha batchA batchB)
(:documentation "returns beta * batchC(i) + alpha * (batchA(i) @ batchB(i))"))
(defgeneric tensor-match (tensor m1 m2 gain))
(defgeneric tensor-max (vals indices tensor dimension keep-dim)
(:documentation "returns max values and indices with given dimension axis"))
(defgeneric tensor-min (vals indices tensor dimension keep-dim)
(:documentation "returns min values and indices with given dimension axis"))
(defgeneric tensor-kth-value (vals indices tensor k dimension keep-dim)
(:documentation "returns kth smallest element of the given tensor along given dimension"))
(defgeneric tensor-mode (vals indices tensor dimension keep-dim)
(:documentation "returns the mode value of each row specified by dimension (-1 as default)"))
(defgeneric tensor-median (vals indices tensor dimension keep-dim))
(defgeneric tensor-sum (tensor src dimension keep-dim))
(defgeneric tensor-prd (tensor src dimension keep-dim))
(defgeneric tensor-cum-sum (tensor src dimension)
(:documentation "returns cumulative sum value along dimension axis"))
(defgeneric tensor-cum-prd (tensor src dimension)
(:documentation "returns cumulative product value along dimension axis"))
(defgeneric tensor-sign (tensor src))
(defgeneric tensor-trace (tensor))
(defgeneric tensor-cross (tensor A B dimension))
(defgeneric tensor-cmax (tensor src1 src2))
(defgeneric tensor-cmin (tensor src1 src2))
(defgeneric tensor-zeros (tensor size))
(defgeneric tensor-ones (tensor size))
(defgeneric tensor-diag (tensor src k))
(defgeneric tensor-eye (tensor nrow ncol))
(defgeneric tensor-arange (tensor xmin xmax step))
(defgeneric tensor-range (tensor xmin xmax step))
(defgeneric tensor-rand-perm (tensor n &optional generator)
(:documentation "returns random permutation of integers from 0 to n - 1"))
(defgeneric tensor-reshape (tensor src size)
(:documentation "reshapes size of the given tensor src"))
(defgeneric tensor-sort (tensor indices src dimension descending))
(defgeneric tensor-top-k (tensor indices src k dim dir sorted)
(:documentation "returns k smallest/largest(dir) values sorted or not"))
(defgeneric tensor-tri-l (tensor src k))
(defgeneric tensor-tri-u (tensor src k))
(defgeneric tensor-cat (tensor dimension &rest srcs))
(defgeneric tensor-cat2 (tensor dimension src1 src2))
(defgeneric tensor-catn (tensor dimension srcs))
(defgeneric tensor-equal (tensor-a tensor-b)
(:documentation "check equality of element in tensors"))
(defgeneric tensor-compare (operation tensor src1 src2)) ;; :lt :le :gt :ge :ne :eq
(defgeneric tensor-sigmoid (tensor src)
(:documentation "returns element-wise sigmoid values"))
(defgeneric tensor-log (tensor src)
(:documentation "returns element-wise log values"))
(defgeneric tensor-gamma (tensor src))
(defgeneric tensor-lgamma (tensor src))
(defgeneric tensor-erf (tensor src))
(defgeneric tensor-erfc (tensor src))
(defgeneric tensor-polygamma (tensor src n))
(defgeneric tensor-lbeta (tensor a b))
(defgeneric tensor-log1p (tensor src))
(defgeneric tensor-exp (tensor src)
(:documentation "returns element-wise exponential values"))
(defgeneric tensor-cos (tensor src)
(:documentation "returns element-wise cos values"))
(defgeneric tensor-acos (tensor src)
(:documentation "returns element-wise acos values"))
(defgeneric tensor-cosh (tensor src)
(:documentation "returns element-wise cosh values"))
(defgeneric tensor-sin (tensor src)
(:documentation "returns element-wise sin values"))
(defgeneric tensor-asin (tensor src)
(:documentation "returns element-wise asin values"))
(defgeneric tensor-sinh (tensor src)
(:documentation "returns element-wise sinh values"))
(defgeneric tensor-tan (tensor src)
(:documentation "returns element-wise tan values"))
(defgeneric tensor-atan (tensor src)
(:documentation "returns element-wise atan values"))
(defgeneric tensor-atan2 (tensor srcx srcy)
(:documentation "returns element-wise atan(x/y)"))
(defgeneric tensor-tanh (tensor src)
(:documentation "returns element-wise tanh values"))
(defgeneric tensor-pow (tensor src exponent)
(:documentation "returns element-wise pow values"))
(defgeneric tensor-sqrt (tensor src)
(:documentation "returns element-wise sqrt values"))
(defgeneric tensor-rsqrt (tensor src))
(defgeneric tensor-ceil (tensor src)
(:documentation "returns ceil of the elements"))
(defgeneric tensor-floor (tensor src)
(:documentation "returns element-wise floor values"))
(defgeneric tensor-round (tensor src)
(:documentation "returns element-wise rounded values"))
(defgeneric tensor-abs (tensor src)
(:documentation "returns element-wise abs values"))
(defgeneric tensor-trunc (tensor src))
(defgeneric tensor-frac (tensor src)
(:documentation "returns element-wise fractional values"))
(defgeneric tensor-lerp (tensor tensor-a tensor-b weight)
(:documentation "performs linear interpolation of tensor a and b; a + weight * (b - a)"))
(defgeneric tensor-mean (tensor src dimension keep-dim))
(defgeneric tensor-sd (tensor src dimension keep-dim &optional biased))
(defgeneric tensor-var (tensor src dimension keep-dim &optional biased))
(defgeneric tensor-norm (tensor src value dimension keep-dim))
(defgeneric tensor-renorm (tensor src value dimension maxnorm)
(:documentation "returns a tensor whose subtensors along dimension is normalized (lower maxnorm)"))
(defgeneric tensor-dist (tensor-a tensor-b value))
(defgeneric tensor-histc (hist tensor nbins min-value max-value))
(defgeneric tensor-bhistc (hist tensor nbins min-value max-value))
(defgeneric tensor-mean-all (tensor))
(defgeneric tensor-var-all (tensor &optional biased))
(defgeneric tensor-sd-all (tensor &optional biased))
(defgeneric tensor-norm-all (tensor value))
(defgeneric tensor-linspace (tensor a b n))
(defgeneric tensor-logspace (tensor a b n))
(defgeneric tensor-rand (tensor size &optional generator))
(defgeneric tensor-randn (tensor size &optional generator))
(defgeneric tensor-conv-2d-rev-ger (result beta alpha tensor k srow scol))
(defgeneric tensor-conv-2d-rev-germ (result beta alpha tensor k srow scol))
(defgeneric tensor-conv-2d-ger (result beta alpha tensor k srow scol vf xc))
(defgeneric tensor-conv-2d-mv (result beta alpha tensor k srow scol vf xc))
(defgeneric tensor-conv-2d-mm (result beta alpha tensor k srow scol vf xc))
(defgeneric tensor-conv-2d-mul (result beta alpha tensor k srow scol vf xc))
(defgeneric tensor-conv-2d-cmul (result beta alpha tensor k srow scol vf xc))
(defgeneric tensor-conv-3d-rev-ger (result beta alpha tensor k sdepth srow scol))
(defgeneric tensor-conv-3d-ger (result beta alpha tensor k sdepth srow scol vf xc))
(defgeneric tensor-conv-3d-mv (result beta alpha tensor k sdepth srow scol vf xc))
(defgeneric tensor-conv-3d-mul (result beta alpha tensor k sdepth srow scol vf xc))
(defgeneric tensor-conv-3d-cmul (result beta alpha tensor k sdepth srow scol vf xc))
(defun make-tensor-rand (tensor sizes)
(let ((sz (if (typep ($last sizes) 'generator)
(butlast sizes)
sizes))
(g (if (typep ($last sizes) 'generator)
($last sizes)
*generator*)))
(tensor-rand tensor sz g)))
(defun tensor.float-rand (&rest sizes) (make-tensor-rand (tensor.float) sizes))
(defun tensor.double-rand (&rest sizes) (make-tensor-rand (tensor.double) sizes))
(defun make-tensor-randn (tensor sizes)
(let ((sz (if (typep ($last sizes) 'generator)
(butlast sizes)
sizes))
(g (if (typep ($last sizes) 'generator)
($last sizes)
*generator*)))
(tensor-randn tensor sz g)))
(defun tensor.float-randn (&rest sizes) (make-tensor-randn (tensor.float) sizes))
(defun tensor.double-randn (&rest sizes) (make-tensor-randn (tensor.double) sizes))
(defun byte-zeros (&rest sizes) (-> (apply #'tensor.byte sizes) (tensor-zero)))
(defun char-zeros (&rest sizes) (-> (apply #'tensor.char sizes) (tensor-zero)))
(defun short-zeros (&rest sizes) (-> (apply #'tensor.short sizes) (tensor-zero)))
(defun int-zeros (&rest sizes) (-> (apply #'tensor.int sizes) (tensor-zero)))
(defun long-zeros (&rest sizes) (-> (apply #'tensor.long sizes) (tensor-zero)))
(defun float-zeros (&rest sizes) (-> (apply #'tensor.float sizes) (tensor-zero)))
(defun double-zeros (&rest sizes) (-> (apply #'tensor.double sizes) (tensor-zero)))
(defgeneric tensor-logical-all (tensor))
(defgeneric tensor-logical-any (tensor))
(defgeneric tensor-gesv (rb ra b a))
(defgeneric tensor-trtrs (rb ra b a uplo trans diag))
(defgeneric tensor-gels (rb ra b a))
(defgeneric tensor-syev (re rv a jobz uplo)
(:documentation "computes eigenvalues and eigenvectors"))
(defgeneric tensor-geev (re rv a jobvr))
(defgeneric tensor-gesvd (ru rs rv a jobu))
(defgeneric tensor-gesvd2 (ru rs rv ra a jobu))
(defgeneric tensor-getri (ra a))
(defgeneric tensor-potrf (ra a uplo)
(:documentation "computes the cholesky decomposition of symmetric positive-definite matrix a"))
(defgeneric tensor-potrs (rb b a uplo)
(:documentation "solves a linear system of equations with its cholesky factor u"))
(defgeneric tensor-potri (ra a uplo)
(:documentation "inverses a positive semidefinite matrix given its cholesky factor u"))
(defgeneric tensor-qr (rq rr a))
(defgeneric tensor-geqrf (ra rtau a))
(defgeneric tensor-orgqr (ra a tau))
(defgeneric tensor-ormqr (ra a tau c side trans))
(defgeneric tensor-pstrf (ra rpiv a uplo tol)
(:documentation "computes the pivoted cholesky decomposition"))
(defgeneric tensor-btrifact (ra rpivots rinfo a pivot)
(:documentation "performs batch LU factorization"))
(defgeneric tensor-btrisolve (rb b atf pivots)
(:documentation "performs batch LU solve; uses LU factorization results"))
| 19,185
|
Common Lisp
|
.lisp
| 341
| 54.117302
| 101
| 0.772157
|
chunsj/TH
| 59
| 8
| 0
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
dccdcb86599d0972a2b21b69aa9181f7434d2ba2a425717059966839d675b021
| 3,163
|
[
-1
] |
3,164
|
cifar.lisp
|
chunsj_TH/db/cifar.lisp
|
(declaim (optimize (speed 3) (debug 0) (safety 0)))
(defpackage :th.db.cifar
(:use #:common-lisp
#:mu
#:th)
(:export #:read-cifar-10-data
#:read-cifar-100-data))
(in-package :th.db.cifar)
(defparameter +cifar-location+ ($concat (namestring (user-homedir-pathname)) ".th/datasets/cifar"))
(defparameter +record-length+ (+ 1 3072))
(defun read-nbyte (n str)
(let ((ret 0))
(loop :repeat n :do (setf ret (logior (ash ret 8) (read-byte str))))
ret))
(defun read-single-image-into (m l idx s &optional (normalize nil))
(let ((label (read-byte s)))
(setf ($ l idx) label)
(dotimes (i (1- +record-length+))
(let* ((v (read-byte s))
(rv (if normalize (/ v 255.0) (* 1.0 v))))
(setf ($ m idx i) rv)))))
(defun original-read-cifar-10-train-images (&key (normalize nil))
(let* ((n 10000)
(l (zeros (* 5 n)))
(m (zeros (* 5 n) (* 3 1024))))
(with-open-file (str (strcat +cifar-location+ "/10/data_batch_1.bin")
:element-type '(unsigned-byte 8))
(dotimes (i n)
(read-single-image-into m l i str normalize)))
(with-open-file (str (strcat +cifar-location+ "/10/data_batch_2.bin")
:element-type '(unsigned-byte 8))
(dotimes (i n)
(read-single-image-into m l (+ i n) str normalize)))
(with-open-file (str (strcat +cifar-location+ "/10/data_batch_3.bin")
:element-type '(unsigned-byte 8))
(dotimes (i n)
(read-single-image-into m l (+ i (* 2 n)) str normalize)))
(with-open-file (str (strcat +cifar-location+ "/10/data_batch_4.bin")
:element-type '(unsigned-byte 8))
(dotimes (i n)
(read-single-image-into m l (+ i (* 3 n) i) str normalize)))
(with-open-file (str (strcat +cifar-location+ "/10/data_batch_5.bin")
:element-type '(unsigned-byte 8))
(dotimes (i n)
(read-single-image-into m l (+ i (* 4 n)) str normalize)))
(list l m)))
(defun original-read-cifar-10-test-images (&key (normalize nil))
(let* ((n 10000)
(l1 (zeros n))
(l2 (zeros n))
(m (zeros n (* 3 1024))))
(with-open-file (str (strcat +cifar-location+ "/10/test_batch.bin")
:element-type '(unsigned-byte 8))
(dotimes (i n)
(read-single-image-into m l i str normalize)))
(list l m)))
(defun generate-cifar-10-data (&key (loc +cifar-location+))
(let ((train (original-read-cifar-10-train-images))
(test (original-read-cifar-10-test-images)))
(let ((f (file.disk (strcat loc "/10/cifar-10-train-images.tensor") "w")))
(setf ($fbinaryp f) t)
($fwrite (tensor.byte (cadr train)) f)
($fclose f))
(let ((f (file.disk (strcat loc "/10/cifar-10-train-labels.tensor") "w")))
(setf ($fbinaryp f) t)
($fwrite (tensor.byte (car train)) f)
($fclose f))
(let ((f (file.disk (strcat loc "/10/cifar-10-test-images.tensor") "w")))
(setf ($fbinaryp f) t)
($fwrite (tensor.byte (cadr test)) f)
($fclose f))
(let ((f (file.disk (strcat loc "/10/cifar-10-test-labels.tensor") "w")))
(setf ($fbinaryp f) t)
($fwrite (tensor.byte (car test)) f)
($fclose f))))
(defun read-single-image-into2 (m l1 l2 idx s &optional (normalize nil))
(let ((label1 (read-byte s))
(label2 (read-byte s)))
(setf ($ l1 idx) label1)
(setf ($ l2 idx) label2)
(dotimes (i (1- +record-length+))
(let* ((v (read-byte s))
(rv (if normalize (/ v 255.0) (* 1.0 v))))
(setf ($ m idx i) rv)))))
(defun original-read-cifar-100-train-images (&key (normalize nil))
(let* ((n 50000)
(l1 (zeros n))
(l2 (zeros n))
(m (zeros n (* 3 1024))))
(with-open-file (str (strcat +cifar-location+ "/100/train.bin")
:element-type '(unsigned-byte 8))
(dotimes (i n)
(read-single-image-into2 m l1 l2 i str normalize)))
(list l1 l2 m)))
(defun original-read-cifar-100-test-images (&key (normalize nil))
(let* ((n 10000)
(l1 (zeros n))
(l2 (zeros n))
(m (zeros n (* 3 1024))))
(with-open-file (str (strcat +cifar-location+ "/100/test.bin")
:element-type '(unsigned-byte 8))
(dotimes (i n)
(read-single-image-into2 m l1 l2 i str normalize)))
(list l1 l2 m)))
(defun generate-cifar-100-data (&key (loc +cifar-location+))
(let ((train (original-read-cifar-100-train-images))
(test (original-read-cifar-100-test-images)))
(let ((f (file.disk (strcat loc "/100/cifar-100-train-images.tensor") "w")))
(setf ($fbinaryp f) t)
($fwrite (tensor.byte (caddr train)) f)
($fclose f))
(let ((f (file.disk (strcat loc "/100/cifar-100-train-fine-labels.tensor") "w")))
(setf ($fbinaryp f) t)
($fwrite (tensor.byte (cadr train)) f)
($fclose f))
(let ((f (file.disk (strcat loc "/100/cifar-100-train-coarse-labels.tensor") "w")))
(setf ($fbinaryp f) t)
($fwrite (tensor.byte (car train)) f)
($fclose f))
(let ((f (file.disk (strcat loc "/100/cifar-100-test-images.tensor") "w")))
(setf ($fbinaryp f) t)
($fwrite (tensor.byte (caddr test)) f)
($fclose f))
(let ((f (file.disk (strcat loc "/100/cifar-100-test-fine-labels.tensor") "w")))
(setf ($fbinaryp f) t)
($fwrite (tensor.byte (cadr test)) f)
($fclose f))
(let ((f (file.disk (strcat loc "/100/cifar-100-test-coarse-labels.tensor") "w")))
(setf ($fbinaryp f) t)
($fwrite (tensor.byte (car test)) f)
($fclose f))))
(defun read-cifar-10-train-images-tensor (&key (loc +cifar-location+) (normalize T))
(let ((f (file.disk (strcat loc "/10/cifar-10-train-images.tensor") "r"))
(m (tensor.byte)))
(setf ($fbinaryp f) t)
($fread m f)
($fclose f)
(if normalize
($div! (tensor.float m) 255)
(tensor.float m))))
(defun read-cifar-10-train-labels-tensor (&key (loc +cifar-location+) (onehot T))
(let ((f (file.disk (strcat loc "/10/cifar-10-train-labels.tensor") "r"))
(m (tensor.byte)))
(setf ($fbinaryp f) t)
($fread m f)
($fclose f)
(if onehot
(let ((z (zeros ($size m 0) 10)))
(loop :for i :from 0 :below ($size m 0)
:do (setf ($ z i ($ m i)) 1))
z)
(tensor.float m))))
(defun read-cifar-10-test-images-tensor (&key (loc +cifar-location+) (normalize T))
(let ((f (file.disk (strcat loc "/10/cifar-10-test-images.tensor") "r"))
(m (tensor.byte)))
(setf ($fbinaryp f) t)
($fread m f)
($fclose f)
(if normalize
($div! (tensor.float m) 255)
(tensor.float m))))
(defun read-cifar-10-test-labels-tensor (&key (loc +cifar-location+) (onehot T))
(let ((f (file.disk (strcat loc "/10/cifar-10-test-labels.tensor") "r"))
(m (tensor.byte)))
(setf ($fbinaryp f) t)
($fread m f)
($fclose f)
(if onehot
(let ((z (zeros ($size m 0) 10)))
(loop :for i :from 0 :below ($size m 0)
:do (setf ($ z i ($ m i)) 1))
z)
(tensor.float m))))
(defun read-cifar-10-label-descriptions (&key (loc +cifar-location+))
(coerce (->> (slurp (strcat loc "/10/batches.meta.txt"))
(mapcar (lambda (s) (strim s)))
(remove-if-not (lambda (s) (> ($count s) 0))))
'vector))
(defun read-cifar-10-data (&key (path +cifar-location+) (normalize T) (onehot T))
#{:train-images (read-cifar-10-train-images-tensor :loc path :normalize normalize)
:train-labels (read-cifar-10-train-labels-tensor :loc path :onehot onehot)
:test-images (read-cifar-10-test-images-tensor :loc path :normalize normalize)
:test-labels (read-cifar-10-test-labels-tensor :loc path :onehot onehot)
:label-descriptions (read-cifar-10-label-descriptions :loc path)})
(defun read-cifar-100-train-images-tensor (&key (loc +cifar-location+) (normalize T))
(let ((f (file.disk (strcat loc "/100/cifar-100-train-images.tensor") "r"))
(m (tensor.byte)))
(setf ($fbinaryp f) t)
($fread m f)
($fclose f)
(if normalize
($div! (tensor.float m) 255)
(tensor.float m))))
(defun read-cifar-100-train-fine-labels-tensor (&key (loc +cifar-location+) (onehot T))
(let ((f (file.disk (strcat loc "/100/cifar-100-train-fine-labels.tensor") "r"))
(m (tensor.byte)))
(setf ($fbinaryp f) t)
($fread m f)
($fclose f)
(if onehot
(let ((z (zeros ($size m 0) 100)))
(loop :for i :from 0 :below ($size m 0)
:do (setf ($ z i ($ m i)) 1))
z)
(tensor.float m))))
(defun read-cifar-100-train-coarse-labels-tensor (&key (loc +cifar-location+) (onehot T))
(let ((f (file.disk (strcat loc "/100/cifar-100-train-coarse-labels.tensor") "r"))
(m (tensor.byte)))
(setf ($fbinaryp f) t)
($fread m f)
($fclose f)
(if onehot
(let ((z (zeros ($size m 0) 10)))
(loop :for i :from 0 :below ($size m 0)
:do (setf ($ z i ($ m i)) 1))
z)
(tensor.float m))))
(defun read-cifar-100-test-images-tensor (&key (loc +cifar-location+) (normalize T))
(let ((f (file.disk (strcat loc "/100/cifar-100-test-images.tensor") "r"))
(m (tensor.byte)))
(setf ($fbinaryp f) t)
($fread m f)
($fclose f)
(if normalize
($div! (tensor.float m) 255)
(tensor.float m))))
(defun read-cifar-100-test-fine-labels-tensor (&key (loc +cifar-location+) (onehot T))
(let ((f (file.disk (strcat loc "/100/cifar-100-test-fine-labels.tensor") "r"))
(m (tensor.byte)))
(setf ($fbinaryp f) t)
($fread m f)
($fclose f)
(if onehot
(let ((z (zeros ($size m 0) 100)))
(loop :for i :from 0 :below ($size m 0)
:do (setf ($ z i ($ m i)) 1))
z)
(tensor.float m))))
(defun read-cifar-100-test-coarse-labels-tensor (&key (loc +cifar-location+) (onehot T))
(let ((f (file.disk (strcat loc "/100/cifar-100-test-coarse-labels.tensor") "r"))
(m (tensor.byte)))
(setf ($fbinaryp f) t)
($fread m f)
($fclose f)
(if onehot
(let ((z (zeros ($size m 0) 10)))
(loop :for i :from 0 :below ($size m 0)
:do (setf ($ z i ($ m i)) 1))
z)
(tensor.float m))))
(defun read-cifar-100-fine-label-descriptions (&key (loc +cifar-location+))
(coerce (->> (slurp (strcat loc "/100/fine_label_names.txt"))
(mapcar (lambda (s) (strim s)))
(remove-if-not (lambda (s) (> ($count s) 0))))
'vector))
(defun read-cifar-100-coarse-label-descriptions (&key (loc +cifar-location+))
(coerce (->> (slurp (strcat loc "/100/coarse_label_names.txt"))
(mapcar (lambda (s) (strim s)))
(remove-if-not (lambda (s) (> ($count s) 0))))
'vector))
(defun read-cifar-100-data (&key (path +cifar-location+) (normalize T) (onehot T))
#{:train-images (read-cifar-100-train-images-tensor :loc path :normalize normalize)
:train-fine-labels (read-cifar-100-train-fine-labels-tensor :loc path :onehot onehot)
:train-coarse-labels (read-cifar-100-train-coarse-labels-tensor :loc path :onehot onehot)
:test-images (read-cifar-100-test-images-tensor :loc path :normalize normalize)
:test-fine-labels (read-cifar-100-test-fine-labels-tensor :loc path :onehot onehot)
:test-coarse-labels (read-cifar-100-test-coarse-labels-tensor :loc path :onehot onehot)
:fine-label-descriptions (read-cifar-100-fine-label-descriptions)
:coarse-label-descriptions (read-cifar-100-coarse-label-descriptions)})
| 11,739
|
Common Lisp
|
.lisp
| 269
| 36.427509
| 99
| 0.578083
|
chunsj/TH
| 59
| 8
| 0
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
21bdac4ac48aee70b3b04e6428c9e566e5d7cf1690f1a6f693b88e06f88b51de
| 3,164
|
[
-1
] |
3,165
|
mnist.lisp
|
chunsj_TH/db/mnist.lisp
|
(declaim (optimize (speed 3) (debug 1) (safety 0)))
(defpackage :th.db.mnist
(:use #:common-lisp
#:mu
#:th)
(:export #:read-mnist-data))
(in-package :th.db.mnist)
(defparameter +mnist-location+ ($concat (namestring (user-homedir-pathname)) ".th/datasets/mnist"))
(defun mfn (n &key (loc +mnist-location+)) (strcat loc "/" n))
;; (defun generate-mnist-data (&key (loc +mnist-location+))
;; (let ((orig-mnist (th.db.mnist-original::read-mnist-data :normalize nil :onehot nil)))
;; (let ((train-images ($ orig-mnist :train-images))
;; (train-labels ($ orig-mnist :train-labels))
;; (test-images ($ orig-mnist :test-images))
;; (test-labels ($ orig-mnist :test-labels)))
;; (let ((f (file.disk (mfn "mnist-train-images.tensor" :loc loc) "w")))
;; (setf ($fbinaryp f) t)
;; ($fwrite (tensor.byte train-images) f)
;; ($fclose f))
;; (let ((f (file.disk (mfn "mnist-train-labels.tensor" :loc loc) "w")))
;; (setf ($fbinaryp f) t)
;; ($fwrite (tensor.byte train-labels) f)
;; ($fclose f))
;; (let ((f (file.disk (mfn "mnist-test-images.tensor" :loc loc) "w")))
;; (setf ($fbinaryp f) t)
;; ($fwrite (tensor.byte test-images) f)
;; ($fclose f))
;; (let ((f (file.disk (mfn "mnist-test-labels.tensor" :loc loc) "w")))
;; (setf ($fbinaryp f) t)
;; ($fwrite (tensor.byte test-labels) f)
;; ($fclose f)))))
(defun read-mnist-images-tensor (n &key (loc +mnist-location+) (normalize T))
(let ((f (file.disk (mfn n :loc loc) "r"))
(m (tensor.byte)))
(setf ($fbinaryp f) t)
($fread m f)
($fclose f)
(if normalize
($div! (tensor.float m) 255)
(tensor.float m))))
(defun read-mnist-labels-tensor (n &key (loc +mnist-location+) (onehot T))
(let ((f (file.disk (mfn n :loc loc) "r"))
(m (tensor.byte)))
(setf ($fbinaryp f) t)
($fread m f)
($fclose f)
(if onehot
(let ((z (zeros ($size m 0) 10)))
(loop :for i :from 0 :below ($size m 0)
:do (setf ($ z i ($ m i 0)) 1))
z)
(tensor.float m))))
(defun read-mnist-data (&key (path +mnist-location+) (normalize T) (onehot T))
#{:train-images (read-mnist-images-tensor "mnist-train-images.tensor"
:loc path :normalize normalize)
:train-labels (read-mnist-labels-tensor "mnist-train-labels.tensor"
:loc path :onehot onehot)
:test-images (read-mnist-images-tensor "mnist-test-images.tensor"
:loc path :normalize normalize)
:test-labels (read-mnist-labels-tensor "mnist-test-labels.tensor"
:loc path :onehot onehot)})
| 2,729
|
Common Lisp
|
.lisp
| 61
| 39.868852
| 99
| 0.570677
|
chunsj/TH
| 59
| 8
| 0
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
0dec4dd4ea8ed3ff4b046b03288275ff86cd25c9b73864151165123c2ca5bc4a
| 3,165
|
[
-1
] |
3,166
|
imdb.lisp
|
chunsj_TH/db/imdb.lisp
|
(declaim (optimize (speed 3) (debug 0) (safety 0)))
(defpackage :th.db.imdb
(:use #:common-lisp
#:mu
#:th)
(:export #:read-imdb-data
#:read-imdb-data2))
(in-package :th.db.imdb)
(defparameter +imdb-location+ ($concat (namestring (user-homedir-pathname)) ".th/datasets/imdb"))
(defun imdb-reviews (path)
(let ((filename ($concat path "/reviews-small.txt")))
(read-lines-from filename)))
(defun imdb-labels (path)
(let ((filename ($concat path "/labels-small.txt")))
(read-lines-from filename)))
(defun imdb-reviews-test (path)
(let ((filename ($concat path "/reviews-small-test.txt")))
(read-lines-from filename)))
(defun imdb-labels-test (path)
(let ((filename ($concat path "/labels-small-test.txt")))
(read-lines-from filename)))
(defun read-imdb-data (&key (path +imdb-location+))
#{:train-reviews (imdb-reviews path)
:train-labels (imdb-labels path)
:test-reviews (imdb-reviews-test path)
:test-labels (imdb-labels-test path)})
(defun imdb-reviews2 (path)
(let ((filename ($concat path "/greviews.txt")))
(read-lines-from filename)))
(defun imdb-labels2 (path)
(let ((filename ($concat path "/glabels.txt")))
(read-lines-from filename)))
(defun read-imdb-data2 (&key (path +imdb-location+))
#{:reviews (imdb-reviews2 path)
:labels (imdb-labels2 path)})
| 1,355
|
Common Lisp
|
.lisp
| 35
| 34.914286
| 97
| 0.674561
|
chunsj/TH
| 59
| 8
| 0
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
4a6ad18b5e0e1e80ca34e8dce65cbc313b038cdd8b82875e576b1d031bb86ed6
| 3,166
|
[
-1
] |
3,167
|
fashion.lisp
|
chunsj_TH/db/fashion.lisp
|
(declaim (optimize (speed 3) (debug 1) (safety 0)))
(defpackage :th.db.fashion
(:use #:common-lisp
#:mu
#:th)
(:export #:read-fashion-data))
(in-package :th.db.fashion)
(defparameter +fashion-location+ ($concat (namestring (user-homedir-pathname))
".th/datasets/fashion-mnist"))
(defun mfn (n &key (loc +fashion-location+)) (strcat loc "/" n))
;; (defun generate-fashion-data (&key (loc +fashion-location+))
;; (let ((orig-fashion (th.db.fashion-original::read-fashion-data :normalize nil :onehot nil)))
;; (let ((train-images ($ orig-fashion :train-images))
;; (train-labels ($ orig-fashion :train-labels))
;; (test-images ($ orig-fashion :test-images))
;; (test-labels ($ orig-fashion :test-labels)))
;; (let ((f (file.disk (mfn "fashion-train-images.tensor" :loc loc) "w")))
;; (setf ($fbinaryp f) t)
;; ($fwrite (tensor.byte train-images) f)
;; ($fclose f))
;; (let ((f (file.disk (mfn "fashion-train-labels.tensor" :loc loc) "w")))
;; (setf ($fbinaryp f) t)
;; ($fwrite (tensor.byte train-labels) f)
;; ($fclose f))
;; (let ((f (file.disk (mfn "fashion-test-images.tensor" :loc loc) "w")))
;; (setf ($fbinaryp f) t)
;; ($fwrite (tensor.byte test-images) f)
;; ($fclose f))
;; (let ((f (file.disk (mfn "fashion-test-labels.tensor" :loc loc) "w")))
;; (setf ($fbinaryp f) t)
;; ($fwrite (tensor.byte test-labels) f)
;; ($fclose f)))))
(defun read-fashion-images-tensor (n &key (loc +fashion-location+) (normalize T))
(let ((f (file.disk (mfn n :loc loc) "r"))
(m (tensor.byte)))
(setf ($fbinaryp f) t)
($fread m f)
($fclose f)
(if normalize
($div! (tensor.float m) 255)
(tensor.float m))))
(defun read-fashion-labels-tensor (n &key (loc +fashion-location+) (onehot T))
(let ((f (file.disk (mfn n :loc loc) "r"))
(m (tensor.byte)))
(setf ($fbinaryp f) t)
($fread m f)
($fclose f)
(if onehot
(let ((z (zeros ($size m 0) 10)))
(loop :for i :from 0 :below ($size m 0)
:do (setf ($ z i ($ m i 0)) 1))
z)
(tensor.float m))))
(defun read-fashion-data (&key (path +fashion-location+) (normalize T) (onehot T))
#{:train-images (read-fashion-images-tensor "fashion-train-images.tensor"
:loc path :normalize normalize)
:train-labels (read-fashion-labels-tensor "fashion-train-labels.tensor"
:loc path :onehot onehot)
:test-images (read-fashion-images-tensor "fashion-test-images.tensor"
:loc path :normalize normalize)
:test-labels (read-fashion-labels-tensor "fashion-test-labels.tensor"
:loc path :onehot onehot)})
| 2,843
|
Common Lisp
|
.lisp
| 62
| 40.370968
| 97
| 0.573026
|
chunsj/TH
| 59
| 8
| 0
|
GPL-3.0
|
9/19/2024, 11:26:04 AM (Europe/Amsterdam)
|
02bf8b28dc8c420ab3036fd5c0861c86ecbaf163acb41490d9f4f5a88f4cdd26
| 3,167
|
[
-1
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.