(ns games.crow.flight)

(def flight-settings
  {:hover  {:speed 0  :amplitude 0.1 :frequency 9}
   :slow   {:speed 2  :amplitude 0.3 :frequency 5}
   :normal {:speed 9  :amplitude 0.3 :frequency 5}
   :fast   {:speed 24 :amplitude 0.6 :frequency 8}
   :vertical {:amplitude 0.6 :frequency 9}})

(def tour-route
  [[50 24 -30] [55 16 -12] [38 9 2] [28 8 13]
   [23 10 29] [7 15 32] [-13 10 29] [-29 8 19]
   [-28 10 1] [-18 10 -20] [-3 19 -29] [18 20 -29]
   [36 24 -34]])

(defn tour-position [time]
  (let [n (count tour-route)
        segment (mod (/ time 4) n)
        i (js/Math.floor segment)
        t (- segment i)
        p0 (nth tour-route (mod (dec i) n))
        p1 (nth tour-route i)
        p2 (nth tour-route (mod (inc i) n))
        p3 (nth tour-route (mod (+ i 2) n))]
    (mapv (fn [a b c d]
            (* 0.5 (+ (* 2 b)
                      (* (- c a) t)
                      (* (+ (* 2 a) (* -5 b) (* 4 c) (- d)) t t)
                      (* (+ (- a) (* 3 b) (* -3 c) d) t t t))))
          p0 p1 p2 p3)))

(defn clamp [x low high]
  (max low (min high x)))

(def max-bank (* 80 (/ js/Math.PI 180)))

(defn approach-bank [bank target dt]
  (let [banking-in (and (>= (* bank target) 0)
                        (> (js/Math.abs target) (js/Math.abs bank)))]
    (+ bank (* (- target bank) (min 1 (* (if banking-in 4 2) dt))))))

(defn advance-wings [{:keys [wing-frequency wing-amplitude wing-phase]}
                     {target-frequency :frequency target-amplitude :amplitude}
                     dt]
  (let [blend (min 1 (* 4 dt))
        frequency (+ wing-frequency (* (- target-frequency wing-frequency) blend))
        amplitude (+ wing-amplitude (* (- target-amplitude wing-amplitude) blend))
        phase (+ wing-phase (* dt frequency))]
    {:wing-frequency frequency
     :wing-amplitude amplitude
     :wing-phase phase
     :bob (* amplitude (js/Math.sin phase))}))

(defn look-direction [yaw pitch]
  (let [horizontal (js/Math.cos pitch)]
    [(* (js/Math.sin yaw) horizontal)
     (js/Math.sin pitch)
     (* (js/Math.cos yaw) horizontal)]))

(defn take-control [{:keys [mode] :as state}]
  (if (= :tour mode)
    (assoc state :mode :flight)
    state))

(defn start-flight [{:keys [braking] :as state} control]
  (if braking
    state
    (assoc (take-control state) :stopped false control true)))

(defn editable-target? [target]
  (or (.-isContentEditable target)
      (#{"INPUT" "TEXTAREA" "SELECT"} (.-tagName target))))

(defn start! [canvas scene engine]
  (let [camera (js/BABYLON.FreeCamera.
                 "camera" (js/BABYLON.Vector3. 50 24 -30) scene)
        state (atom {:mode :tour
                     :time 0
                     :x 50 :y 24 :z -30
                     :yaw 0 :pitch 0.18
                     :view-yaw 0 :view-pitch 0.18
                     :tour-look-yaw 0 :tour-look-pitch 0
                     :accelerating false :slowing false :braking false :stopped false
                     :left false :right false :up false :down false
                     :turn-left false :turn-right false
                     :speed 9 :bank 0 :wing-phase 0
                     :wing-amplitude (get-in flight-settings [:normal :amplitude])
                     :wing-frequency (get-in flight-settings [:normal :frequency])
                     :bob 0 :turn-delta 0})
        locked (atom false)
        end-drag! (fn []
                    (swap! state dissoc :pointer-id :pointer-x :pointer-y)
                    (when (= canvas (.-pointerLockElement js/document))
                      (.exitPointerLock js/document)))
        drag! (fn [event locked?]
                (swap! state
                       (fn [{:keys [mode pointer-id pointer-x pointer-y
                                    tour-look-yaw tour-look-pitch view-yaw view-pitch
                                    turn-delta]
                             :as s}]
                         (if (and (some? pointer-id)
                                  (or locked? (= pointer-id (.-pointerId event))))
                           (let [x (.-clientX event)
                                 y (.-clientY event)
                                 dx (if locked? (.-movementX event) (- x pointer-x))
                                 dy (if locked? (.-movementY event) (- y pointer-y))
                                 s (assoc s :pointer-x x :pointer-y y)]
                             (if (and (= :tour mode) (.-shiftKey event))
                               (assoc s
                                      :tour-look-yaw (+ tour-look-yaw (* 0.005 dx))
                                      :tour-look-pitch (clamp (- tour-look-pitch (* 0.005 dy)) -1.2 1.2))
                               (let [yaw (+ view-yaw (* 0.005 dx))
                                     pitch (clamp (- view-pitch (* 0.005 dy)) -1.2 1.2)
                                     s (assoc s :view-yaw yaw :view-pitch pitch)]
                                 (if (or (.-shiftKey event) (and (zero? dx) (zero? dy)))
                                   s
                                   (assoc (take-control s) :yaw yaw :pitch pitch
                                          :turn-delta (+ turn-delta (* 0.005 dx)))))))
                           s))))]
    (.addEventListener canvas "pointerdown"
                       (fn [event]
                         (when (zero? (.-button event))
                           (when (not= "mouse" (.-pointerType event))
                             (.preventDefault event))
                           (.setPointerCapture canvas (.-pointerId event))
                           (swap! state assoc
                                  :pointer-id (.-pointerId event)
                                  :pointer-x (.-clientX event)
                                  :pointer-y (.-clientY event))
                           (when (= "mouse" (.-pointerType event))
                             (if (.-requestPointerLock canvas)
                               (when-let [request (.requestPointerLock canvas)]
                                 (.catch request (fn [error]
                                                   (.error js/console "Could not lock pointer:" error))))
                               (.warn js/console "Pointer lock is not supported; drag-look remains bounded by the screen."))))))
    (.addEventListener canvas "pointermove"
                       (fn [event]
                         (when-not (= canvas (.-pointerLockElement js/document))
                           (drag! event false))))
    (.addEventListener canvas "mousemove"
                       (fn [event]
                         (when (= canvas (.-pointerLockElement js/document))
                           (drag! event true))))
    (.addEventListener js/document "pointerup"
                       (fn [event]
                         (when (= (:pointer-id @state) (.-pointerId event))
                           (end-drag!))))
    (.addEventListener js/document "pointercancel"
                       (fn [event]
                         (when (and (= (:pointer-id @state) (.-pointerId event))
                                    (not= canvas (.-pointerLockElement js/document)))
                           (end-drag!))))
    (.addEventListener canvas "mouseup"
                       (fn [event]
                         (when (and (zero? (.-button event))
                                    (= canvas (.-pointerLockElement js/document)))
                           (end-drag!))))
    (.addEventListener js/document "pointerlockchange"
                       (fn []
                         (if (= canvas (.-pointerLockElement js/document))
                           (if (:pointer-id @state)
                             (reset! locked true)
                             (.exitPointerLock js/document))
                           (when @locked
                             (reset! locked false)
                             (end-drag!)))))
    (.addEventListener js/document "pointerlockerror"
                       (fn [event] (.error js/console "Could not lock pointer:" event)))
    (.addEventListener canvas "lostpointercapture"
                       (fn [event]
                         (when (and (= (:pointer-id @state) (.-pointerId event))
                                    (not= canvas (.-pointerLockElement js/document)))
                           (end-drag!))))
    (.addEventListener js/window "keydown"
                       (fn [event]
                         (when (and (not (editable-target? (.-target event)))
                                    (not (.-ctrlKey event))
                                    (not (.-metaKey event))
                                    (not (.-altKey event)))
                           (when (= "Space" (.-code event))
                             (.preventDefault event))
                           (when-not (.-repeat event)
                             (case (.-code event)
                               "KeyW" (swap! state (fn [{:keys [braking] :as s}]
                                                    (if braking s
                                                        (assoc (start-flight s :accelerating) :slowing false))))
                               "KeyS" (swap! state (fn [{:keys [accelerating] :as s}]
                                                    (if accelerating s
                                                        (start-flight s :slowing))))
                               "KeyA" (swap! state start-flight :left)
                               "KeyD" (swap! state start-flight :right)
                               "KeyZ" (swap! state #(assoc (take-control %) :turn-left true))
                               "KeyC" (swap! state #(assoc (take-control %) :turn-right true))
                               "KeyE" (swap! state #(assoc (take-control %) :up true))
                               "KeyQ" (swap! state #(assoc (take-control %) :down true))
                               "Space" (swap! state #(assoc (take-control %) :braking true :stopped true
                                                            :accelerating false :speed 0 :turn-delta 0))
                               "KeyR" (do
                                        (end-drag!)
                                        (swap! state (fn [{:keys [x y z view-yaw view-pitch] :as s}]
                                                       (assoc s :mode :tour :time 0
                                                              :accelerating false :slowing false :braking false
                                                              :stopped false :left false :right false :up false :down false
                                                              :turn-left false :turn-right false
                                                              :turn-delta 0
                                                              :tour-look-yaw 0 :tour-look-pitch 0
                                                              :tour-camera-yaw view-yaw :tour-camera-pitch view-pitch
                                                              :tour-start [x y z]))))
                               nil))))
                       true)
    (.addEventListener js/window "keyup"
                       (fn [event]
                         (when (and (= "KeyS" (.-code event))
                                    (not (editable-target? (.-target event)))
                                    (not (.-ctrlKey event))
                                    (not (.-metaKey event))
                                    (not (.-altKey event)))
                           (.preventDefault event)
                           (.stopPropagation event))
                         (case (.-code event)
                           "KeyW" (swap! state assoc :accelerating false)
                           "KeyA" (swap! state assoc :left false)
                           "KeyD" (swap! state assoc :right false)
                           "KeyZ" (swap! state assoc :turn-left false)
                           "KeyC" (swap! state assoc :turn-right false)
                           "KeyE" (swap! state assoc :up false)
                           "KeyQ" (swap! state assoc :down false)
                           "Space" (swap! state assoc :braking false)
                           nil))
                       true)
    (.addEventListener js/window "blur"
                       (fn [_]
                         (end-drag!)
                         (swap! state assoc :accelerating false :braking false
                                :left false :right false :up false :down false
                                :turn-left false :turn-right false :turn-delta 0)))
    (.add (.-onBeforeRenderObservable scene)
          (fn [& _]
            (let [dt (min 0.05 (/ (.getDeltaTime engine) 1000))
                  {:keys [mode] :as s} @state
                  time (+ (:time s) dt)]
              (if (= :tour mode)
                (let [{:keys [tour-start tour-look-yaw tour-look-pitch
                              tour-camera-yaw tour-camera-pitch]
                       current-bank :bank} s
                      [tx ty tz] (tour-position time)
                      [nx ny nz] (tour-position (+ time 0.05))
                      progress (if tour-start (min 1 (/ time 2)) 1)
                      blend (* progress progress (- 3 (* 2 progress)))
                      [sx sy sz] (or tour-start [tx ty tz])
                      x (+ sx (* blend (- tx sx)))
                      y (+ sy (* blend (- ty sy)))
                      z (+ sz (* blend (- tz sz)))
                      blend-speed (if (and tour-start (< time 2)) (* 3 progress (- 1 progress)) 0)
                      dx (+ (* blend-speed (- tx sx)) (* blend (/ (- nx tx) 0.05)))
                      dy (+ (* blend-speed (- ty sy)) (* blend (/ (- ny ty) 0.05)))
                      dz (+ (* blend-speed (- tz sz)) (* blend (/ (- nz tz) 0.05)))
                      heading-yaw (js/Math.atan2 dx dz)
                      heading-pitch (js/Math.atan2 dy (js/Math.sqrt (+ (* dx dx) (* dz dz))))
                      previous-yaw (or tour-camera-yaw heading-yaw)
                      yaw-difference (- heading-yaw previous-yaw)
                      turn-angle (js/Math.atan2 (js/Math.sin yaw-difference) (js/Math.cos yaw-difference))
                      camera-yaw (+ previous-yaw (* turn-angle (min 1 (* 2 dt))))
                      previous-pitch (or tour-camera-pitch -0.22)
                      camera-pitch (+ previous-pitch (* (- -0.22 previous-pitch) (min 1 (* 2 dt))))
                      yaw (+ camera-yaw tour-look-yaw)
                      pitch (clamp (+ camera-pitch tour-look-pitch) -1.2 1.2)
                      target-bank (clamp (* -0.8 (/ (- camera-yaw previous-yaw) (max dt 0.001)))
                                         (- max-bank) max-bank)
                      bank (approach-bank current-bank target-bank dt)
                      {:keys [bob] :as wings} (advance-wings s (:normal flight-settings) dt)]
                  (set! (.-position camera) (js/BABYLON.Vector3. x (+ y bob) z))
                  (set! (.. camera -rotation -x) (- pitch))
                  (set! (.. camera -rotation -y) yaw)
                  (set! (.. camera -rotation -z) bank)
                  (swap! state #(merge % wings {:time time :x x :y y :z z
                                               :yaw heading-yaw :pitch heading-pitch
                                               :tour-camera-yaw camera-yaw :tour-camera-pitch camera-pitch
                                               :view-yaw yaw :view-pitch pitch :bank bank})))
                (let [{:keys [stopped slowing accelerating up down left right
                              turn-left turn-right view-pitch turn-delta]
                       current-view-yaw :view-yaw
                       current-speed :speed current-yaw :yaw current-pitch :pitch
                       current-bank :bank current-x :x current-y :y current-z :z} s
                      flight-mode (cond stopped :hover accelerating :fast
                                        slowing :slow :else :normal)
                      settings (flight-settings flight-mode)
                      vertical-active (or up down)
                      wing-settings (if vertical-active (:vertical flight-settings) settings)
                      target-speed (:speed settings)
                      speed (if stopped 0
                                (+ current-speed
                                   (* (- target-speed current-speed) (min 1 (* 2 dt)))))
                      strafe (if stopped 0 (- (if right 1 0) (if left 1 0)))
                      turn-rate (* 1.6 (- (if turn-right 1 0) (if turn-left 1 0)))
                      view-yaw (+ current-view-yaw (* turn-rate dt))
                      yaw (+ current-yaw (* turn-rate dt))
                      pitch current-pitch
                      mouse-turn (/ turn-delta (max dt 0.001))
                      turn-bank (clamp (* -0.28 (+ turn-rate mouse-turn)) (- max-bank) max-bank)
                      target-bank (clamp (+ (* -0.25 strafe) turn-bank) (- max-bank) max-bank)
                      bank (approach-bank current-bank target-bank dt)
                      [fx fy fz] (look-direction yaw pitch)
                      vertical (- (if up 1 0) (if down 1 0))
                      x (+ current-x (* fx speed dt) (* strafe 12 (js/Math.cos yaw) dt))
                      y (max 2 (+ current-y (* fy speed dt) (* vertical 8 dt)))
                      z (- (+ current-z (* fz speed dt)) (* strafe 12 (js/Math.sin yaw) dt))
                      {:keys [bob] :as wings} (advance-wings s wing-settings dt)]
                  (set! (.-position camera) (js/BABYLON.Vector3. x (+ y bob) z))
                  (set! (.. camera -rotation -x) (- view-pitch))
                  (set! (.. camera -rotation -y) view-yaw)
                  (set! (.. camera -rotation -z) bank)
                  (swap! state #(merge % wings {:time time :speed speed :x x :y y :z z
                                               :yaw yaw :pitch pitch :view-yaw view-yaw
                                               :bank bank :turn-delta 0})))))))
    camera))
