(import
  (howl *)
  (howl/forge ()))

(const gravity 9.81)

(inputs platformer
        (axis1 move
               ((key (KeyA)) -1.0)
               ((key (KeyD)) 1.0))
        (button jump (key (KeySpace))))

(type Ball < DeformableModel
  ((grounded bool nil)
   (airborne f32 0.0)
   (charge f32 0.0)
   (stretch f32 0.0)
   (impact-speed f32 0.0)
   (rolling f32 0.0)))

(var landing-dust
     (EmitterConfig :texture (load "textures/landing-dust.png")
                    :atlas (Atlas :cols 6)
                    :max-particles 12
                    :shape (EmitDisc 0.65)
                    :lifetime (Interval 0.4 0.6)
                    :start-size (Interval 0.45 0.75)
                    :start-speed (Interval 0.9 1.6)
                    :start-rotation (Interval 0.0 360.0)
                    :angular-velocity (Interval -100.0 100.0)
                    :acceleration (Vec3 0.0 0.5 0.0)
                    :drag 5.5
                    :size-over-life (curve (CurveKey 0.0 0.7) (CurveKey 0.6 1.3))
                    :color-over-life (gradient (GradientKey 0.0 (Color 210 178 140 100))
                                               (GradientKey 0.15 (Color 210 178 140 205))
                                               (GradientKey 0.85 (Color 210 178 140 0)))))

(pub fn setup () -> void
  (scene:load "scenes/ball.scene")
  (spawn (Camera :position (Vec3 0.0 4.0 18.0)
                 :target (Vec3 0.0 1.6 0.0)
                 :fov-y 22.0))
  (spawn (DirectionalLight :direction (Vec3 0.35 -1.0 -0.25)
                           :color (Color 255 228 183)
                           :intensity 1.0
                           :ambient 0.3))
  (spawn (Ball :position (Vec3 -2.4 0.65 0.0)
               :mesh (sphere-mesh 0.55 32 20)
               :settings (PhysicsMeshSettings :surface-sim true
                                              :material (PhysicsMaterial :density 10.0
                                                                         :pressure 35.0
                                                                         :compliance 0.0004
                                                                         :bend-compliance (Some 0.02)
                                                                         :damping 0.08
                                                                         :iterations 16))
               :body-settings (SoftBodySettings :vertex-radius 0.025 :friction 0.65)
               :material (Material :base (Color 166 222 179)
                                   :albedo (load "textures/slime.jpg")
                                   :highlight-intensity 0.45
                                   :highlight-exponent 16.0))))

(fn jump ((velocity !&Vec3)) -> void
  (let ((height 0.6))
    (set [velocity y] (sqrt (* 2.0 gravity height)))))

(fn on-update ((ball !&Ball) (dt f32)) -> void
  (let ((bounds (bounds ball))
        (center (center bounds))
        (velocity (velocity ball))
        (ground (raycast (Vec3 [center x] (+ [bounds min y] 0.12) [center z])
                         (Vec3 0.0 -0.24 0.0)
                         (ignoring ball)))
        (on-ground (when-let ((hit ground))
                     (and (> [hit normal y] 0.6)
                          (< [velocity y] 0.8)
                          (< (- [bounds min y] [hit point y]) 0.045))))
        (direction (axis1 (input platformer move)))
        (wall (raycast center
                       (Vec3 (* direction (+ [(half bounds) x] 0.08)) 0.0 0.0)
                       (ignoring ball)))
        (target velocity))
    (when (and on-ground (not [ball grounded]) (> [ball airborne] 0.15))
      (when-let ((hit ground))
        (burst landing-dust (+ [hit point] (Vec3 0.0 0.04 0.0))
               (i32 (clamp (* [ball impact-speed] 2.0) 5.0 12.0)))))

    (set [ball impact-speed] (if on-ground 0.0 (max [ball impact-speed] (- 0.0 [velocity y])))
         [ball airborne] (if on-ground 0.0 (+ [ball airborne] dt))
         [ball grounded] on-ground
         [ball stretch] (max 0.0 (- [ball stretch] dt))
         [target x] (lerp [velocity x] (if (some? wall) 0.0 (* direction 3.6))
                          (- 1.0 (exp (* -12.0 dt))))
         [target z] (* [center z] -8.0))

    (when on-ground
      (set [ball rolling] (lerp [ball rolling] (/ (- 0.0 [target x]) 0.55)
                                (- 1.0 (exp (* -14.0 dt))))))

    (when (and [ball grounded] (= [ball charge] 0.0) (pressed? (input platformer jump)))
      (set [ball charge] 0.12))
    (when (> [ball charge] 0.0)
      (set [ball charge] (max 0.0 (- [ball charge] dt)))
      (when (= [ball charge] 0.0)
        (jump target)
        (set [ball grounded] nil [ball stretch] 0.09)))

    (deform ball center velocity target dt)))

(fn deform ((ball !&Ball) (center Vec3) (velocity Vec3) (target Vec3) (dt f32)) -> void
  (let ((strain (cond
                  ((> [ball charge] 0.0) -5.0)
                  ((> [ball stretch] 0.0) 4.0)
                  (else 0.0)))
        (vertices (edit-vertices ball)))
    (for (i (count vertices))
      (let ((offset (- (position vertices i) center))
            (relative (- (velocity vertices i) velocity))
            (spin (cross (Vec3 0.0 0.0 [ball rolling]) offset)))
        ;; Preserve rolling while damping deformation around it
        (set relative
             (if (/= strain 0.0)
               (lerp relative (+ spin (Vec3 (* [offset x] strain -0.5)
                                            (* [offset y] strain)
                                            (* [offset z] strain -0.5)))
                     (- 1.0 (exp (* -12.0 dt))))
               (+ spin (* (- relative spin) (exp (* -10.0 dt))))))
        (set-velocity vertices i (+ target relative))))))

(pub fn main () -> (Result void string)
  (run (App :title "Ball Platformer"
            :width 640
            :height 480)
       :setup setup))
