local LD = require("design.LevelDesignLibrary")
local DL = require("design.DesignerLibrary")
local monitors = require("level.MonitorLibrary")
local timer = require("level.timer")
local uiCalls = require("ui.uicalls")
local BossEncounter = require("boss.statemachine")
local color = require("core.color")
local TUT = require("game.GlobalTutorials")
local checkpoint = require("level.checkpoint")
local actorlib = require("narrative.actor")
local gVFSEnableAlternateAfterFightCamera = engine.VFSBool.New("Enable Alternate After Fight Camera")
gVFSEnableAlternateAfterFightCamera.value = false
local toggleDebug = monitors.CreateDownButtonMonitor()
local frame_RoofMMA_1 = 0
local frame_RoofMMA_2 = 55
local frame_RoofMMA_3 = 464
local frame_RoofMMA_4 = 606
local frame_KratosCave_1 = 0
local frame_KratosCave_2 = 968
local frame_KratosCave_3 = 1674
local frame_GroundRip_1 = 0
local frame_GroundRip_2 = 300
local frame_GroundRip_3 = 1274
local frame_GroundRip_4 = 1501
local baldur_health_max = 600
local baldur_health_p1_wound1 = 525
local baldur_health_p1_wound2 = 450
local baldur_health_p1_wound3 = 375
local baldur_health_threshold_mma_start = 300
local baldur_health_threshold_mma_mid = 200
local baldur_health_threshold_mma_end = 150
local baldur_health_threshold_treebat = 200
local baldur_health_threshold_treebat_hit = 100
local baldur_health_threshold_statue_start = 600
local baldur_health_threshold_statue_rage_drains = 350
local baldur_health_threshold_statue_rage_resist = 350
local baldur_health_threshold_statue_end = 50
local baldur_health_threshold_throw_statue = 100
local baldur_health_threshold_final_start = 600
local baldur_health_threshold_final_end = 50
local btrFirstRage_2 = "400_BaldurBuriedTaunt_BAL"
local btrBaldurCrushed = "420_BaldurCrushed"
local btrFirstCrackClimb = "440_FirstCrackClimb"
local boolFirstCrackClimbBant = false
local BossStage_0_1 = BossEncounter:AddStage("stage0_1")
local BossStage_1_1 = BossEncounter:AddStage("stage1_1", true)
local BossStage_1_2 = BossEncounter:AddStage("stage1_2")
local BossStage_1_3 = BossEncounter:AddStage("stage1_3")
local BossStage_1_5 = BossEncounter:AddStage("stage1_5")
local BossStage_1_5b = BossEncounter:AddStage("stage1_5b", true)
local BossStage_1_5c = BossEncounter:AddStage("stage1_5c")
local BossStage_1_6 = BossEncounter:AddStage("stage1_6")
local BossStage_1_7 = BossEncounter:AddStage("stage1_7")
local BossStage_1_9 = BossEncounter:AddStage("stage1_9")
local BossStage_1_10 = BossEncounter:AddStage("stage1_10")
local BossStage_2_1 = BossEncounter:AddStage("stage2_1", true)
local BossStage_2_2 = BossEncounter:AddStage("stage2_2")
local BossStage_2_2b = BossEncounter:AddStage("stage2_2b")
local BossStage_2_3 = BossEncounter:AddStage("stage2_3")
local BossStage_2_4 = BossEncounter:AddStage("stage2_4", true)
local BossStage_2_5p = BossEncounter:AddStage("stage2_5p")
local BossStage_2_5 = BossEncounter:AddStage("stage2_5")
local BossStage_2_6 = BossEncounter:AddStage("stage2_6")
local BossStage_2_7 = BossEncounter:AddStage("stage2_7")
local BossStage_2_7b = BossEncounter:AddStage("stage2_7b")
local BossStage_2_8 = BossEncounter:AddStage("stage2_8")
local BossStage_2_9 = BossEncounter:AddStage("stage2_9")
local BossStage_3_1 = BossEncounter:AddStage("stage3_1", true)
local BossStage_3_2 = BossEncounter:AddStage("stage3_2")
local BossStage_3_2b = BossEncounter:AddStage("stage3_2b")
local BossStage_3_3 = BossEncounter:AddStage("stage3_3")
local BossStage_3_4 = BossEncounter:AddStage("stage3_4", true)
local BossStage_3_5 = BossEncounter:AddStage("stage3_5")
local BossStage_3_6 = BossEncounter:AddStage("stage3_6")
local thisLevel, player, houseLevel, assetLevel, pad, baldur
local descString = ""
local doTeleport = false
local using_TB_Baldur = false
local currentStepAnimPlayed = false
local currentStepAnimPlayed2 = false
local currentStepAnimPlayed3 = false
local doorReEnabled = false
local groundSplitTimer
local phaseHealthDDA = 0
local debugPopups = 0
local mmaTutorialPhase = 0
local rageModeTutorialPhase = 0
local instantSetup = false
local forceIdleBeforeTransition = true
local kratosPup, switchParams
local bBaldurBuriedCineEnter = false
local goBaldurBuriedCineEnterModule
local camera_InWoundWalk = false
local debugSkip = false
local treeRipState = 1
local BloodDecayForStatueSmash = function()
  game.Combat.SetBloodDecayMultiplier(0)
end
local TurnOffIntroBreakable = function()
  if houseLevel ~= nil then
    houseLevel:CallScript("CallScriptVisibility", "for200_house_firsthit_landing", false)
  end
end
local BloodDecayReset = function()
  game.Combat.SetBloodDecayMultiplier(0.5)
end
local SonDisable = function()
  local availabilityState = {
    AvailableForSync = false,
    AvailableForBanter = false,
    AvailableInLevel = false,
    AvailableForCombat = false
  }
  game.AI.FindSon():SetNewAvailabilityRequest("SonUnavailable", availabilityState)
  game.Combat.ForceBloodDecayInCombat(true)
  BloodDecayReset()
end
local SonEnable = function()
  game.AI.FindSon():RemoveAvailabilityRequest("SonUnavailable")
  game.Combat.ForceBloodDecayInCombat(false)
  game.Combat.SetBloodDecayMultiplier(1)
end
function Boss_ShowHealth()
  baldur:CallScript("LuaHook_ShowHealth", baldur)
end
function Boss_HideHealth()
  baldur:CallScript("LuaHook_HideHealth", baldur)
end
function AllowOffscreenIndicators()
  if baldur:HasMarker("nooffscreen") then
    baldur:RemoveMarker("nooffscreen")
  end
end
local baldurWoundLevel = 0
local BaldurSetWoundLevel = function(newWoundLevel)
  if newWoundLevel == 0 then
    baldur:HideJoint(baldur:GetJointIndex("Baldur_Wounds_1"))
    baldur:HideJoint(baldur:GetJointIndex("Baldur_Wounds_2"))
    baldur:HideJoint(baldur:GetJointIndex("Baldur_Wounds_3"))
  elseif newWoundLevel == 1 then
    baldur:ShowJoint(baldur:GetJointIndex("Baldur_Wounds_1"))
    baldur:HideJoint(baldur:GetJointIndex("Baldur_Wounds_2"))
    baldur:HideJoint(baldur:GetJointIndex("Baldur_Wounds_3"))
  elseif newWoundLevel == 2 then
    baldur:ShowJoint(baldur:GetJointIndex("Baldur_Wounds_1"))
    baldur:ShowJoint(baldur:GetJointIndex("Baldur_Wounds_2"))
    baldur:HideJoint(baldur:GetJointIndex("Baldur_Wounds_3"))
  elseif newWoundLevel == 3 then
    baldur:ShowJoint(baldur:GetJointIndex("Baldur_Wounds_1"))
    baldur:ShowJoint(baldur:GetJointIndex("Baldur_Wounds_2"))
    baldur:ShowJoint(baldur:GetJointIndex("Baldur_Wounds_3"))
  end
  baldurWoundLevel = newWoundLevel
end
local CheckAdvanceStageMove = function()
  if player:IsPlayingMove("MOV_TriggerNextMove") or baldur:IsPlayingMove("MOV_TriggerNextMove") then
    player:TriggerMoveEvent("kLETransitionExecuted")
    baldur:TriggerMoveEvent("kLETransitionExecuted")
    doTeleport = false
    return true
  elseif player:IsPlayingMove("MOV_TriggerNextMoveInstant") or baldur:IsPlayingMove("MOV_TriggerNextMoveInstant") then
    instantSetup = true
    player:TriggerMoveEvent("kLETransitionExecuted")
    baldur:TriggerMoveEvent("kLETransitionExecuted")
    doTeleport = false
    return true
  end
  return false
end
local StageSetup = function(curStage, newDescString)
  assetLevel = game.FindLevel("For310_BossAssets")
  descString = newDescString
  if curStage ~= 0 then
    BossEncounter:SetDebugInput(true)
  end
  if baldur == nil then
    return
  end
  if baldur:PickupIsAcquired("Baldur_FightTimer") then
    baldur:PickupRelinquish("Baldur_FightTimer")
  end
  baldur:PickupAcquire("Baldur_FightTimer")
  baldur:RemoveMarker("Stage1")
  baldur:RemoveMarker("Stage2")
  baldur:RemoveMarker("Stage3")
  if curStage == 1 then
    baldur:AddMarker("Stage1")
  elseif curStage == 2 then
    baldur:AddMarker("Stage2")
  elseif curStage == 3 then
    baldur:AddMarker("Stage3")
  end
  if 0 < curStage then
    TurnOffIntroBreakable()
  end
  if baldur:HasMarker("nooffscreen") == false then
    baldur:AddMarker("nooffscreen")
  end
  BloodDecayReset()
  if forceIdleBeforeTransition then
    player:TriggerMoveEvent("LE_ForceIdle")
    baldur:TriggerMoveEvent("LE_ForceIdle")
  else
    forceIdleBeforeTransition = true
  end
  doTeleport = false
  currentStepAnimPlayed = false
  currentStepAnimPlayed2 = false
  currentStepAnimPlayed3 = false
  if assetLevel ~= nil then
    assetLevel:CallScript("CallScriptVisibility", "BaldurTreeBat", false)
    assetLevel:CallScript("CallScriptVisibility", "SCRIPTED_Landmark_Prop", false)
    assetLevel:CallScript("CallScriptVisibility", "BREAK_Landmark_Throw", false)
    houseLevel:CallScript("CallScriptVisibility", "BREAK_TreePlow_Pristine", false)
    houseLevel:CallScript("CallScriptVisibility", "BREAK_TreePlow_Stump", false)
    assetLevel:CallScript("CallScriptVisibility", "BREAK_TreePlow_Ripout", false)
    assetLevel:CallScript("CallScriptVisibility", "BREAK_PlowThrough", false)
    if treeRipState == 1 then
      houseLevel:CallScript("CallScriptVisibility", "BREAK_TreePlow_Pristine", true)
    end
    if treeRipState == 2 then
      assetLevel:CallScript("CallScriptVisibility", "BREAK_TreePlow_Ripout", true)
    end
    if treeRipState == 3 then
      houseLevel:CallScript("CallScriptVisibility", "BREAK_TreePlow_Stump", true)
    end
    if curStage == 0 then
      DL.HideLevelObject(thisLevel, "SCRIPTED_CollisionBeforeCollapse")
      DL.HideLevelObject(thisLevel, "SCRIPTED_CollisionAfterCollapse")
      DL.HideLevelObject(thisLevel, "Phase1Collision")
      houseLevel:CallScript("CallScriptVisibility", "SCRIPTED_Mountains", true)
    elseif curStage == 1 then
      DL.HideLevelObject(thisLevel, "SCRIPTED_CollisionBeforeCollapse")
      DL.HideLevelObject(thisLevel, "SCRIPTED_CollisionAfterCollapse")
      houseLevel:CallScript("CallScriptVisibility", "SCRIPTED_Mountains", true)
    elseif curStage == 2 then
      DL.HideLevelObject(thisLevel, "SCRIPTED_CollisionAfterCollapse")
      DL.ShowLevelObject(thisLevel, "SCRIPTED_CollisionBeforeCollapse")
      houseLevel:CallScript("CallScriptVisibility", "SCRIPTED_Mountains", false)
    elseif curStage == 3 then
      DL.HideLevelObject(thisLevel, "SCRIPTED_CollisionBeforeCollapse")
      DL.ShowLevelObject(thisLevel, "SCRIPTED_CollisionAfterCollapse")
      houseLevel:CallScript("CallScriptVisibility", "SCRIPTED_Mountains", false)
      assetLevel:CallScript("CallScriptVisibility", "BREAK_KratosCave", false)
    end
  end
  baldur:CallScript("SetStage", curStage)
end
local PostStageSetup = function()
  if instantSetup == false then
    doTeleport = true
  else
    instantSetup = false
  end
end
local UpdateMMA = function()
  if mmaTutorialPhase == 1 then
    TUT.For300_BaldurBlock_Tutorial()
    mmaTutorialPhase = mmaTutorialPhase + 1
  elseif mmaTutorialPhase == 2 then
    if DL.CheckCreatureContext(player:GetContext(), "DEFENDING") then
      baldur:TriggerMoveEvent("LE_MMABlockTutorialDone")
      if thisLevel:FindSingleGameObject("Breakable_RockBug2") ~= nil then
        DL.HideLevelObject(thisLevel, "Breakable_RockBug2")
      end
      if thisLevel:FindSingleGameObject("Breakable_RockBug1") ~= nil then
        DL.HideLevelObject(thisLevel, "Breakable_RockBug1")
      end
    end
    if baldur:IsPlayingMove("MOV_MMA_Defense_DodgeTutorial") then
      TUT.For300_BaldurDodge_Tutorial()
      mmaTutorialPhase = mmaTutorialPhase + 1
    end
  elseif mmaTutorialPhase == 3 then
    if baldur:IsPlayingMove("MOV_MMA_Defense_DodgeTutorial2") then
      TUT.For300_BaldurDodge_Tutorial2()
      mmaTutorialPhase = mmaTutorialPhase + 1
    end
  elseif mmaTutorialPhase == 4 and baldur:IsPlayingMove("MOV_MMA_Defense_AttackTutorial") then
    TUT.For300_BaldirDodgeAttacl_Tutorial()
    mmaTutorialPhase = mmaTutorialPhase + 1
  end
  if baldur:HasMarker("React") then
    mmaTutorialPhase = 99
    uiCalls.UI_Event_TurnOffDesignerMessage()
  end
end
local BaldurStunnedTransitionCheck = function()
  baldur:MeterSetValue("Health", 800)
  if CheckAdvanceStageMove() or baldur:HasMarker("PhaseTransition") == false then
    doTeleport = false
    BossEncounter:ForwardState()
    return
  end
end
function BossStage_0_1:OnEnter(level)
  forceIdleBeforeTransition = false
  StageSetup(0, "InitialSetup")
  BaldurSetWoundLevel(0)
  baldur:CallScript("SetStage", 0)
  baldur:CallScript("SetNonhostile")
end
local cinePlayedOnce = false
local initedFightFromCine = false
function BossStage_0_1:OnUpdate(level)
  if baldur:IsPlayingMove("MOV_BaldurIntro") and baldur:GetActiveMovePercent() > 0.965 and currentStepAnimPlayed == false then
    TurnOffIntroBreakable()
    currentStepAnimPlayed = true
  end
  if baldur:IsPlayingMove("MOV_BaldurIntro") or using_TB_Baldur then
    BossEncounter:SetDebugInput(true)
    if initedFightFromCine == false then
      DL.ShowLevelObject(level, "Phase1Collision")
      assetLevel = game.FindLevel("For310_BossAssets")
      if assetLevel ~= nil then
        assetLevel:CallScript("CallScriptAnim", "BREAK_Baldur_RoofBugSplat", "reset")
        assetLevel:CallScript("CallScriptVisibility", "BaldurTreeBat", false)
        assetLevel:CallScript("CallScriptVisibility", "BREAK_PlowThrough", false)
      end
      initedFightFromCine = true
    end
  end
  if game.Level.GetVariable("CompletedCineNumber") >= 80 and baldur:IsPlayingMove("MOV_BaldurIntro") == false and cinePlayedOnce == false then
    debugSkip = false
    forceIdleBeforeTransition = false
    BossEncounter:ForwardState()
    return
  end
end
local blockBanterHintString = "356_BlockingHints"
local blockBanterTimePlayed = 0
local blockBanterHealthThreshold = 0
function BlockHintBanterCheck()
  if 5 < blockBanterHealthThreshold and blockBanterTimePlayed < game.GetGameTime() then
    if game.Audio.CanBanterConversationPlay(blockBanterHintString) and player:MeterGetValue("Health") < blockBanterHealthThreshold then
      game.Audio.PlayBanter(blockBanterHintString)
      blockBanterTimePlayed = game.GetGameTime() + 15
      blockBanterHealthThreshold = blockBanterHealthThreshold - 25
    else
      blockBanterTimePlayed = game.GetGameTime() + 3
    end
  end
end
function BossStage_1_1:OnEnter(level)
  StageSetup(1, "Kratos and Baldur fight in the backyard.")
  houseLevel:CallScript("RemoveBurnableCollision")
  SonDisable()
  Boss_ShowHealth()
  AllowOffscreenIndicators()
  blockBanterHealthThreshold = 50
  if assetLevel ~= nil then
    assetLevel:CallScript("CallScriptAnim", "BREAK_Baldur_RoofBugSplat", "reset")
  end
  assetLevel:CallScript("CallScriptVisibility", "BREAK_GroundRip", false)
  SetBaldurPhaseHealth(1, baldur_health_max)
  if cinePlayedOnce == false then
    cinePlayedOnce = true
  end
  if debugSkip then
    TeleportKratosBaldur("Warp_Stage1", "Warp_Stage1b", false)
  end
  game.Level.SetVariable("CompletedCineNumber", 80)
  BaldurSetWoundLevel(0)
  DL.ShowLevelObject(level, "Phase1Collision")
  baldur:CallScript("SetHostile")
  phaseHealthDDA = 60
  player:MeterSetValue("Health", 999)
  baldur:TriggerMoveEvent("LE_TauntInviteL")
end
function BossStage_1_1:OnUpdate(level)
  if currentStepAnimPlayed == false and player:MeterGetValue("Health") < blockBanterHealthThreshold then
    TUT.For300_BaldurBlock_Tutorial()
    currentStepAnimPlayed = true
  end
  BlockHintBanterCheck()
  if baldur:GetHitPoints() <= baldur_health_p1_wound1 and baldurWoundLevel < 1 then
    BaldurSetWoundLevel(1)
  elseif baldur:GetHitPoints() <= baldur_health_p1_wound2 and baldurWoundLevel < 2 then
    BaldurSetWoundLevel(2)
  elseif baldur:GetHitPoints() <= baldur_health_p1_wound3 and baldurWoundLevel < 3 then
    BaldurSetWoundLevel(3)
  end
  if GetBaldurHealthThreshold(1, 1) > 0 and baldur:GetHitPoints() <= GetBaldurHealthThreshold(1, 1) and CheckValidBaldurState() then
    forceIdleBeforeTransition = false
    BossEncounter:ForwardState()
    return
  end
end
function BossStage_1_1:OnExit(level)
  uiCalls.UI_Event_TurnOffDesignerMessage()
end
function BossStage_1_2:OnEnter(level)
  forceIdleBeforeTransition = false
  if BossEncounter:IsDebugSkip() then
    forceIdleBeforeTransition = true
  end
  BaldurSetWoundLevel(3)
  StageSetup(1, "Baldur does transition attack.")
  TeleportKratosBaldur(nil, nil, false)
  if BossEncounter:IsDebugSkip() then
    baldur:TriggerMoveEvent("LE_EvadeB")
  end
  baldur:CallScript("SetHostile")
  if baldur:HasMarker("StageTransition") == false then
    baldur:AddMarker("StageTransition")
  end
end
function SetRoofSlamUppercutDrivers()
end
function BaldurRoofUppercutMotionWarpSetup(debugSkipped)
  local warpRot = player:GetAnimDriver("RoofSlamUppercutRotation")
  warpRot.ValueVec = player:GetWorldPosition() - thisLevel:FindSingleGameObject("Warp_Stage1_OrientToHouse"):GetWorldPosition()
end
function BossStage_1_2:OnUpdate(level)
  BaldurRoofUppercutMotionWarpSetup(false)
  if CheckAdvanceStageMove() or player:IsPlayingMove("MOV_Phase1_RoofSlamUppercut") or player:IsPlayingMove("MOV_Phase1_RoofSlamUppercut02") or player:IsPlayingMove("MOV_Phase1_RoofSlamUppercut03") then
    forceIdleBeforeTransition = false
    BossEncounter:ForwardState()
  end
end
function BossStage_1_2:OnExit(level)
  if baldur:HasMarker("StageTransition") then
    baldur:RemoveMarker("StageTransition")
  end
end
local roofBreakableCounter
function BossStage_1_3:OnEnter(level)
  StageSetup(1, "Baldur grabs Kratos and launches him high into the air.")
  Boss_HideHealth()
  SetBaldurPhaseHealth(1, baldur_health_threshold_mma_start)
  assetLevel:CallScript("CallScriptAnimFrames", "BREAK_Baldur_RoofMMA", frame_RoofMMA_1, 0)
  roofBreakableCounter = 0
  TeleportKratosBaldur("Warp_Stage1_RoofSlamStart", "Warp_Stage1_RoofSlamStart", false)
  if BossEncounter:IsDebugSkip() then
    BaldurRoofUppercutMotionWarpSetup(true)
    if player.Pad.L1Down == true and player.Pad.L2Down == false then
      player:TriggerMoveEvent("LE_Phase1_RoofSlam02")
    else
      player:TriggerMoveEvent("LE_Phase1_RoofSlam03")
    end
  end
  baldur:CallScript("SetNonhostile")
  uiCalls.UI_Event_TurnOffDesignerMessage()
  baldur:AddMarker("MMA_Tutorial")
end
function BossStage_1_3:OnUpdate(level)
  BaldurRoofUppercutMotionWarpSetup(false)
  if CheckAdvanceStageMove() or player:IsPlayingMove("MOV_MMA_Defense_Enter") or player:IsPlayingMove("MOV_Phase1_RoofBeatdownEnter") then
    forceIdleBeforeTransition = false
    BossEncounter:ForwardState()
    return
  end
  if baldur:IsPlayingMove("MOV_Phase1_RoofSlamUppercut02") and player:IsPlayingMove("MOV_Phase1_RoofSlamUppercut02") == false or baldur:IsPlayingMove("MOV_Phase1_RoofSlamUppercut03") and player:IsPlayingMove("MOV_Phase1_RoofSlamUppercut03") == false or baldur:IsPlayingMove("MOV_Phase1_RoofSlamUppercut") and player:IsPlayingMove("MOV_Phase1_RoofSlamUppercut") == false then
    BossEncounter:BackwardState()
  end
  if baldur:IsPlayingMove("MOV_Phase1_RoofSlamLand02") and roofBreakableCounter == 0 then
    assetLevel:CallScript("CallScriptAnimFrames", "BREAK_Baldur_RoofMMA", frame_RoofMMA_1, frame_RoofMMA_2)
    roofBreakableCounter = 1
  end
end
local roofHole = false
function BossStage_1_5:OnEnter(level)
  StageSetup(1, "MMA moment")
  SetBaldurPhaseHealth(1, baldur_health_threshold_mma_mid)
  DL.HideLevelObject(thisLevel, "Phase1Collision")
  assetLevel:CallScript("CallScriptAnimFrames", "BREAK_Baldur_RoofMMA", frame_RoofMMA_2, 0)
  baldur:CallScript("SetNonhostile")
  uiCalls.UI_Event_TurnOffDesignerMessage()
  TeleportKratosBaldur("Warp_Stage1_RoofSlamPunchHole", nil, true)
  if player:IsPlayingMove("MOV_Phase1_RoofBeatdownEnter") == false then
    player:TriggerMoveEvent("LE_Phase1_BeatdownEnter")
  end
  roofBreakableCounter = 0
end
function BossStage_1_5:OnUpdate(level)
  if baldur:IsPlayingMove("MOV_Phase1_RoofBeatdownEnter") and baldur:GetActiveMovePercent() < 0.1 then
    if roofHole == false then
      roofHole = true
      assetLevel:CallScript("CallScriptAnimFrames", "BREAK_Baldur_RoofMMA", frame_RoofMMA_2 + 1, frame_RoofMMA_3)
    end
  elseif roofHole == true then
    roofHole = false
  end
  if player:IsPlayingMove("MOV_MMA_Offense_Enter") then
    forceIdleBeforeTransition = false
    BossEncounter:ForwardState()
    return
  end
end
function BossStage_1_5:OnExit(level)
  roofHole = false
end
function BossStage_1_5b:OnEnter(level)
  StageSetup(1, "MMA moment")
  local fromCheckpoint = debugSkip
  TUT.Peak800_BaldurMMAOffense_Tutorial()
  Boss_ShowHealth()
  if player:HasMarker("MMA_ReadyTransition") == true then
    player:RemoveMarker("MMA_ReadyTransition")
  end
  if player:HasMarker("MMA_Roof") == false then
    player:AddMarker("MMA_Roof")
  end
  assetLevel:CallScript("CallScriptVisibility", "BREAK_GroundRip", false)
  baldur:MeterSetValue("MMA_Counter", 0)
  baldur:MeterSetValue("MMA_Choke", 0)
  SetBaldurPhaseHealth(1, baldur_health_threshold_mma_mid)
  baldur:CallScript("SetHostile")
  TeleportKratosBaldur("Warp_Stage1_RoofSlamOffense", nil, false)
  if BossEncounter:IsDebugSkip() or fromCheckpoint then
    player:TriggerMoveEvent("LE_MMAOffense")
  end
  roofBreakableCounter = 0
  assetLevel:CallScript("CallScriptAnimFrames", "BREAK_Baldur_RoofMMA", frame_RoofMMA_3, 0)
end
function BossStage_1_5b:OnUpdate(level)
  baldur:MeterSetValue("MMA_Counter", 0)
  if player:MeterGetValue("Health") < 30 then
    player:MeterSetValue("Health", player:MeterGetValue("Health") + thisLevel:GetUnitTime() * 2)
    baldur:MeterSetValue("MMA_Choke", 0)
  end
  if 0 < GetBaldurHealthThreshold(1, 5) and baldur:GetHitPoints() <= GetBaldurHealthThreshold(1, 5) and player:HasMarker("MMA_ReadyTransition") == false then
    player:AddMarker("MMA_ReadyTransition")
  end
  if player:IsPlayingMove("MOV_Phase1_RoofBeatdownExit") then
    forceIdleBeforeTransition = false
    BossEncounter:ForwardState()
  end
  game.Camera.SubmitCameraByName("PLYR_For200_MMA_020")
  if player:HasMarker("CAMERAPUSH") then
    game.Camera.SubmitCameraByName("PLYR_For200_MMA_020_Zoom")
  end
end
function BossStage_1_5b:OnExit(level)
  if player:HasMarker("MMA_ReadyTransition") == true then
    player:RemoveMarker("MMA_ReadyTransition")
  end
  if player:HasMarker("MMA_Roof") == true then
    player:RemoveMarker("MMA_Roof")
  end
end
function BossStage_1_5c:OnEnter(level)
  StageSetup(1, "MMA moment")
  uiCalls.UI_Event_TurnOffDesignerMessage()
  Boss_HideHealth()
  SetBaldurPhaseHealth(1, baldur_health_threshold_mma_end)
  uiCalls.UI_Event_TurnOffDesignerMessage()
  assetLevel:CallScript("CallScriptAnimFrames", "BREAK_Baldur_RoofMMA", frame_RoofMMA_3, 0)
  assetLevel:CallScript("CallScriptAnim", "BaldurTreeBat", "reset")
  assetLevel:CallScript("CallScriptWarp", "BaldurTreeBat", "Warp_Prop_TreeBat")
  baldur:CallScript("SetNonhostile")
  TeleportKratosBaldur("Warp_Stage1_RoofSlamOffense", nil, true)
  if BossEncounter:IsDebugSkip() then
    player:TriggerMoveEvent("LE_Phase1_BeatdownExit")
  end
  if player:HasMarker("TreeBatWait") == false then
    player:AddMarker("TreeBatWait")
  end
  roofBreakableCounter = 0
end
function BossStage_1_5c:OnUpdate(level)
  if player:IsPlayingMove("MOV_Phase1_RoofBeatdownExit") and currentStepAnimPlayed == false then
    assetLevel:CallScript("CallScriptAnimFrames", "BREAK_Baldur_RoofMMA", frame_RoofMMA_3 + 1, frame_RoofMMA_4)
    currentStepAnimPlayed = true
  end
  if player:IsPlayingMove("MOV_Phase1_RoofBeatdownExit") and player:GetActiveMovePercent() > 0.5 and currentStepAnimPlayed2 == false then
    assetLevel:CallScript("CallScriptVisibility", "BREAK_PlowThrough", true)
    currentStepAnimPlayed2 = true
  end
  if CheckAdvanceStageMove() or player:IsPlayingMove("MOV_Phase1_TreeBatLoop") then
    forceIdleBeforeTransition = false
    BossEncounter:ForwardState()
    return
  end
end
local tutTimer = 0
function BossStage_1_6:OnEnter(level)
  StageSetup(1, "Baldur gets ready to charge Kratos. Kratos can bat him away with a tree.")
  tutTimer = 0
  SetBaldurPhaseHealth(1, baldur_health_threshold_mma_end)
  assetLevel:CallScript("CallScriptVisibility", "BREAK_PlowThrough", true)
  baldur:RemoveMarker("MMA_Tutorial")
  assetLevel:CallScript("CallScriptAnim", "BREAK_Baldur_RoofBugSplat", "reset")
  assetLevel:CallScript("CallScriptAnim", "BREAK_PlowThrough", "reset")
  assetLevel:CallScript("CallScriptAnim", "BaldurTreeBat", "reset")
  assetLevel:CallScript("CallScriptWarp", "BaldurTreeBat", "Warp_Prop_TreeBat")
  TeleportKratosBaldur("Warp_Stage1_Bat", "Warp_Stage1b_Bat", true)
  baldur:CallScript("SetNonhostile")
  if BossEncounter:IsDebugSkip() then
    player:TriggerMoveEvent("LE_Phase1_TreeBatLoop")
    baldur:TriggerMoveEvent("LE_Phase1_TreeBatLoop")
  end
end
function BossStage_1_6:OnUpdate(level)
  SetBaldurPhaseHealth(1, baldur_health_threshold_treebat)
  assetLevel:CallScript("CallScriptAnimFrames", "BREAK_KratosCave", frame_KratosCave_1, 0)
  if CheckAdvanceStageMove() or player:IsPlayingMove("MOV_Phase1_BaldurBuried") or player:IsPlayingMove("MOV_Phase1_PlowThroughExit") then
    forceIdleBeforeTransition = false
    BossEncounter:ForwardState()
    return
  end
  if currentStepAnimPlayed == false and player:HasMarker("TreeBatWait") == true then
    player:RemoveMarker("TreeBatWait")
  end
  if player:IsPlayingMove("MOV_Phase1_TreeBatSwing") and currentStepAnimPlayed == false then
    currentStepAnimPlayed = true
    assetLevel:CallScript("CallScriptAnim", "BaldurTreeBat", "play")
    uiCalls.UI_Event_TurnOffDesignerMessage()
  elseif 0 <= tutTimer and currentStepAnimPlayed == false then
    tutTimer = tutTimer + baldur:GetFrameTime()
    if 2 < tutTimer then
      tutTimer = -1
      TUT.For300_BaldurTreeBat()
    end
  end
  if player:IsPlayingMove("MOV_Phase1_PlowThroughEnter") and currentStepAnimPlayed2 == false then
    currentStepAnimPlayed2 = true
    SetBaldurPhaseHealth(1, baldur_health_threshold_treebat_hit)
    baldur:StartMaterialAnim("baldur00_Damage01")
    assetLevel:CallScript("CallScriptAnim", "BREAK_Baldur_RoofBugSplat", "play")
    assetLevel:CallScript("CallScriptAnim", "BREAK_PlowThrough", "play")
  end
end
local healStarted = false
function BossStage_1_7:OnEnter(level)
  StageSetup(1, "First Heal")
  if player:HasMarker("TreeBatWait") == true then
    player:RemoveMarker("TreeBatWait")
  end
  pad:ClearAllDisabledGameButtons()
  uiCalls.UI_Event_TurnOffDesignerMessage()
  assetLevel:CallScript("CallScriptAnimFrames", "BREAK_KratosCave", frame_KratosCave_1, frame_KratosCave_2)
  SetBaldurPhaseHealth(1, baldur_health_threshold_treebat_hit)
  TeleportKratosBaldur("Warp_Stage1_FirstHeal", nil, true)
  if BossEncounter:IsDebugSkip() then
    player:TriggerMoveEvent("LE_PlowThroughExit")
  end
  healStarted = false
  DL.HideLevelObject(thisLevel, "Phase1Collision")
  baldur:StartMaterialAnim("baldur00_Damage01")
end
function BossStage_1_7:OnUpdate(level)
  if healStarted == false and baldur:IsPlayingMove("MOV_Phase1_PlowThroughExit") and baldur:GetActiveMovePercent() > 0.3 then
    Boss_ShowHealth()
    baldur:StartMaterialAnim("baldur00_Healing01")
    healStarted = true
  end
  if healStarted and baldur:GetActiveMovePercent() > 0.35 and baldur:MeterGetValue("Health") < baldur:MeterGetMax("Health") then
    baldur:MeterSetValue("Health", baldur:MeterGetValue("Health") + thisLevel:GetUnitTime() * 100)
  end
  if baldur:IsPlayingMove("MOV_Phase1_PlowThroughExit") and baldur:GetActiveMovePercent() > 0.65 then
    Boss_HideHealth()
  end
  if CheckAdvanceStageMove() or player:IsPlayingMove("MOV_Phase1_BaldurBuried") then
    forceIdleBeforeTransition = false
    BossEncounter:ForwardState()
    return
  end
end
function BossStage_1_7:OnExit(level)
end
local rageAvailableTicker = 0
local rageAvailableTickerSwitch = false
function BossStage_1_9:OnEnter(level)
  StageSetup(1, "Kratos buried")
  BaldurSetWoundLevel(0)
  if player:PickupIsAcquired("ForceRageModeDisabled") then
    player:PickupRelinquish("ForceRageModeDisabled")
  end
  SetBaldurPhaseHealth(1, baldur_health_threshold_statue_start)
  if BossEncounter:IsDebugSkip() then
    assetLevel:CallScript("CallScriptAnimFrames", "BREAK_KratosCave", frame_KratosCave_2, 0)
  end
  player:MeterSetValue("Blood", 0)
  TeleportKratosBaldur("Warp_Stage1_RageActivate", "Warp_Stage1_RageTutorialBaldurLoc", true)
  baldur:TriggerMoveEvent("LE_Phase1_RageLoop")
  player:TriggerMoveEvent("LE_Phase1_RageLoop")
  rageAvailableTicker = 0
  rageAvailableTickerSwitch = false
  game.Audio.PlayBanter(btrFirstRage_2)
end
function BossStage_1_9:OnUpdate(level)
  if player:IsPlayingMove("MOV_Phase1_BaldurBuried") and rageModeTutorialPhase == 0 then
    rageModeTutorialPhase = 1
  end
  if player:IsPlayingMove("MOV_Phase1_BaldurBuried") and player:GetActiveMovePercent() >= 0.6 and rageAvailableTickerSwitch == false then
    rageAvailableTicker = rageAvailableTicker + 1
    rageAvailableTickerSwitch = true
  elseif rageAvailableTickerSwitch == true and player:GetActiveMovePercent() <= 0.25 and rageAvailableTicker < 10 then
    rageAvailableTickerSwitch = false
  end
  uiCalls.UI_Event_Force_Combat_HUD_On()
  uiCalls.UI_Event_Turn_Rage_Meter_On()
  if 2 <= rageAvailableTicker then
    if player:MeterGetValue("Blood") < 99 then
      player:MeterSetValue("Blood", player:MeterGetValue("Blood") + thisLevel:GetUnitTime() * 50)
    else
      uiCalls.EnableMechanicRage()
      player:MeterSetValue("Blood", 100)
    end
    if player:MeterGetValue("Blood") >= 100 then
      if game.GetEnterRageModeOptionNumber ~= nil and game.GetEnterRageModeOptionNumber() == 1 then
        if player.Pad.CrossDown and player.Pad.CircleDown then
          forceIdleBeforeTransition = false
          uiCalls.DisableMechanicRage()
          uiCalls.UI_Event_Force_Combat_HUD_Clear()
          BossEncounter:ForwardState()
        end
      elseif player.Pad.L3Down and player.Pad.R3Down then
        forceIdleBeforeTransition = false
        uiCalls.DisableMechanicRage()
        uiCalls.UI_Event_Force_Combat_HUD_Clear()
        BossEncounter:ForwardState()
      end
    end
  elseif player:MeterGetValue("Blood") < 95 then
    player:MeterSetValue("Blood", player:MeterGetValue("Blood") + thisLevel:GetUnitTime() * 12)
  end
end
function BossStage_1_10:OnEnter(level)
  treeRipState = 2
  StageSetup(1, "-----")
  assetLevel:CallScript("CallScriptVisibility", "BREAK_GroundRip", true)
  assetLevel:CallScript("CallScriptAnimFrames", "BREAK_GroundRip", frame_GroundRip_1, 0)
  assetLevel:CallScript("CallScriptAnimFrames", "BREAK_KratosCave", frame_KratosCave_2, frame_KratosCave_3)
  baldur:CallScript("SetNonhostile")
  if BossEncounter:IsDebugSkip() == false then
    player:CallScript("LuaHook_BaldurRageEnter")
  end
  player:TriggerMoveEvent("LE_Phase1_RageActivate")
  TeleportKratosBaldur("Warp_Stage1_RageActivate", nil, true)
  assetLevel:CallScript("CallScriptAnim", "BREAK_TreePlow_Ripout", "reset")
  assetLevel:CallScript("CallScriptAnim", "BREAK_TreePlow_Ripout", "play")
  uiCalls.UI_Event_TurnOffDesignerMessage()
end
function BossStage_1_10:OnUpdate(level)
  if baldur:IsPlayingMove("MOV_Phase1_RageActivate") and baldur:GetActiveMovePercent() >= 0 and currentStepAnimPlayed == false then
    currentStepAnimPlayed = true
  end
  if baldur:IsPlayingMove("MOV_Phase1_RageActivate") and baldur:GetActiveMovePercent() >= 0.95 and currentStepAnimPlayed3 == false then
    assetLevel:CallScript("CallScriptVisibility", "BREAK_TreePlow_Ripout", false)
    currentStepAnimPlayed3 = true
  end
  if baldur:IsPlayingMove("MOV_Phase1_RageActivate") and baldur:GetActiveMovePercent() >= 0.77 and baldur:GetActiveMovePercent() <= 84 then
    SetBaldurPhaseHealth(2, baldur_health_threshold_statue_start)
  end
  if CheckAdvanceStageMove() or baldur:IsPlayingMove("MOV_Phase1_RageActivate") == false and currentStepAnimPlayed == true then
    forceIdleBeforeTransition = false
    BossEncounter:ForwardState()
    return
  end
end
function BossStage_1_10:OnExit(level)
end
local rageThrowString, rageModeString, rageTutorialMessageType
local rageTutorialOn = false
function BossStage_2_1:OnEnter(level)
  treeRipState = 3
  StageSetup(2, "Base of the cliff")
  Boss_ShowHealth()
  AllowOffscreenIndicators()
  SetBaldurPhaseHealth(2, baldur_health_threshold_statue_start)
  DL.ShowLevelObject(thisLevel, "BossExitCollision")
  assetLevel:CallScript("CallScriptAnimFrames", "BREAK_GroundRip", frame_GroundRip_1, 0)
  player:MeterSetValue("Blood", 100)
  player:CallScript("LuaHook_BaldurRageEnter")
  if player.SetWeaponMode ~= nil then
    player:SetWeaponMode("Bare", true)
  end
  if baldur:PickupIsAcquired("Baldur_RageTutorial") == false then
    baldur:PickupAcquire("Baldur_RageTutorial")
  end
  if debugSkip then
    TeleportKratosBaldur("Warp_Stage2", "Warp_Stage2b", false)
    baldur:TriggerMoveEvent("LE_TauntInviteL")
  end
  baldur:CallScript("SetHostile")
  phaseHealthDDA = 50
  if player:MeterGetValue("Health") < 70 then
    player:MeterSetValue("Health", 70)
  end
  rageTutorialMessageType = nil
  rageThrowString = "Hold [CircleButton] to perform a RAGE THROW. (Costs 1 meter)"
  rageModeString = "Press [L3] + [XButton] to activate RAGE MODE. (Costs 2 meters)"
  if rageTutorialOn == true then
    TUT.For300_BuildRage_Tutorial()
  end
end
function BossStage_2_1:OnUpdate(level)
  if currentStepAnimPlayed == false and baldur:GetHitPoints() <= baldur_health_threshold_statue_rage_drains then
    player:CallScript("LuaHook_BaldurRageExit")
    currentStepAnimPlayed = true
  elseif currentStepAnimPlayed2 == false and baldur:GetHitPoints() <= baldur_health_threshold_statue_rage_resist then
    if baldur:PickupIsAcquired("Baldur_RageTutorial") == true then
      baldur:PickupRelinquish("Baldur_RageTutorial")
    end
    currentStepAnimPlayed2 = true
  end
  if GetBaldurHealthThreshold(2, 1) > 0 and baldur:GetHitPoints() <= GetBaldurHealthThreshold(2, 1) and CheckValidBaldurState() then
    forceIdleBeforeTransition = false
    BossEncounter:ForwardState()
    return
  end
  if rageTutorialOn then
    local curRage = player:MeterGetValue("Blood")
    if 100 <= curRage and rageModeString ~= nil and rageTutorialMessageType ~= "RageMode" then
      if rageThrowString ~= nil then
        TUT.For300_RageThrowAndActivate_Tutorial()
      else
        TUT.For300_ActivateRageMode_Tutorial()
      end
      rageTutorialMessageType = "RageMode"
    elseif 50 <= curRage and rageThrowString ~= nil and (curRage < 100 or rageModeString == nil) and (player:PickupIsAcquired("RageMode") == false or 0 >= player:PickupGetStage("RageMode")) then
      if rageTutorialMessageType ~= "RageThrow" then
        TUT.For300_RageThrow_Tutorial()
        rageTutorialMessageType = "RageThrow"
      end
    elseif curRage < 50 and (rageTutorialMessageType == "RageThrow" or rageTutorialMessageType == "RageMode") then
      uiCalls.UI_Event_TurnOffDesignerMessage()
    end
  end
  if player:IsPlayingMove("MOV_CSSuperUppercutLaunch") and rageThrowString ~= nil then
    rageThrowString = nil
    rageTutorialMessageType = nil
    uiCalls.UI_Event_TurnOffDesignerMessage()
  elseif player:IsPlayingMove("MOV_RageCombatEnter") and rageModeString ~= nil then
    rageModeString = nil
    rageTutorialMessageType = nil
    uiCalls.UI_Event_TurnOffDesignerMessage()
  end
end
function BossStage_2_2:OnEnter(level)
  StageSetup(2, "Baldur Stunned")
  assetLevel:CallScript("CallScriptVisibility", "BREAK_KratosCave", true)
  player:CallScript("LuaHook_BaldurRageExit")
  baldur:CallScript("SetHostile")
  if baldur:HasMarker("StageTransition") == false then
    baldur:AddMarker("StageTransition")
  end
  if BossEncounter:IsDebugSkip() then
    baldur:TriggerMoveEvent("LE_EvadeB")
    player:CallScript("LuaHook_BaldurRageForceExit")
  end
  uiCalls.UI_Event_TurnOffDesignerMessage()
end
function SetHereToThereDrivers_First()
  local desiredPos = baldur:GetWorldPosition()
  if desiredPos.z > -647 then
    desiredPos = engine.Vector.New(-318.116, 42.237, -647.176)
  end
  local warpPos = baldur:GetAnimDriver("HereToThereEnterTranslation")
  warpPos.ValueVec = desiredPos
  local warpRot = baldur:GetAnimDriver("HereToThereEnterRotation")
  warpRot.ValueVec = desiredPos - thisLevel:FindSingleGameObject("Warp_Stage2_BaldurAgainstStatue"):GetWorldPosition()
end
function SetHereToThereDrivers_Kill()
  local desiredPos = baldur:GetWorldPosition()
  if desiredPos.x > -325 and desiredPos.z > -669 and desiredPos.z < -656 then
    desiredPos = engine.Vector.New(-325.097, 41.976, -663.043)
  end
  local warpPos = baldur:GetAnimDriver("HereToThereEnterTransKill")
  warpPos.ValueVec = desiredPos
  local warpRot = baldur:GetAnimDriver("HereToThereEnterRotation")
  warpRot.ValueVec = desiredPos - thisLevel:FindSingleGameObject("Warp_Stage3_KillLocation"):GetWorldPosition()
end
function BossStage_2_2:OnUpdate(level)
  SetHereToThereDrivers_First()
  if CheckAdvanceStageMove() or player:IsPlayingMove("MOV_HereToThereEnter") or player:IsPlayingMove("MOV_HereToThereEnter2") or player:IsPlayingMove("MOV_HereToThereEnter3") then
    forceIdleBeforeTransition = false
    BossEncounter:ForwardState()
  end
end
function BossStage_2_2:OnExit(level)
  if baldur:HasMarker("StageTransition") then
    baldur:RemoveMarker("StageTransition")
  end
end
function BossStage_2_2b:OnEnter(level)
  StageSetup(2, "Baldur Stunned")
  Boss_HideHealth()
  SetBaldurPhaseHealth(2, baldur_health_threshold_statue_end)
  if BossEncounter:IsDebugSkip() then
    TeleportKratosBaldur("Warp_Stage2", "Warp_Stage2_BaldurDebug", false)
    player:TriggerMoveEvent("LE_HereToThere2")
  end
  player:CallScript("LuaHook_ForceCineRageModeExit")
  assetLevel:CallScript("CallScriptAnim", "BREAK_Landmark_Pull", "reset")
  assetLevel:CallScript("CallScriptAnimFrames", "BREAK_GroundRip", frame_GroundRip_1, 0)
end
function BossStage_2_2b:OnUpdate(level)
  SetHereToThereDrivers_First()
  DL.SetMotionWarpDrivers(thisLevel, baldur, "HereToThereTranslation", "HereToThereRotation", "Warp_Stage2_BaldurAgainstStatue")
  if CheckAdvanceStageMove() or baldur:IsPlayingMove("MOV_HereToThereHitWall") and baldur:GetActiveMovePercent() > 0.9 then
    forceIdleBeforeTransition = false
    BossEncounter:ForwardState()
  end
  if baldur:IsPlayingMove("MOV_HereToThereHitWall") then
    DL.WarpCreature(baldur, thisLevel, "Warp_Stage2_BaldurAgainstStatue")
  end
  if baldur:IsPlayingMove("MOV_HereToThereHitWall") and currentStepAnimPlayed == false then
    assetLevel:CallScript("CallScriptAnim", "BREAK_Landmark_Pull", "play")
    currentStepAnimPlayed = true
  end
end
local kratosActor = actorlib.Actor.New("Kratos", game.Player.FindPlayer)
local baldurActor = actorlib.Actor.New("Baldur", function()
  return baldur
end)
function BossStage_2_3:OnEnter(level)
  StageSetup(2, "Slam down")
  BloodDecayForStatueSmash()
  SetBaldurPhaseHealth(2, baldur_health_threshold_statue_end)
  DL.HideLevelObject(thisLevel, "SCRIPTED_Trees_HidePostGroundRip")
  if BossEncounter:IsDebugSkip() then
    TeleportKratosBaldur("Warp_Stage2_BaldurAgainstStatue", "Warp_Stage2_BaldurAgainstStatue", true)
  else
    TeleportKratosBaldur(nil, nil, true)
  end
  assetLevel:CallScript("CallScriptVisibility", "BREAK_KratosCave", false)
  assetLevel:CallScript("CallScriptAnimFrames", "BREAK_Landmark_Pull", 50, -1)
  baldur:CallScript("SetNonhostile")
  local sequence = LD.CreateCineSequence(thisLevel, GameObjects.BaldurStatueSmashSync, "BaldurStatueSmash")
  sequence:ActorSync(kratosActor, {
    Slaves = {
      {Actor = baldurActor}
    },
    Branch = "BRA_BaldurStatueSmashEnter",
    ReferenceJoint = "csBaldurStatueSmashJoint"
  })
  sequence:WaitForFunctionTrue(function()
    return not player:IsPlayingMove("MOV_StatueSmashEnter") and not player:IsPlayingMove("MOV_HereToThereHitWall")
  end)
  sequence:StopPuppetingActor(kratosActor)
  sequence:StopPuppetingActor(baldurActor)
  sequence:StartSequence()
end
function BossStage_2_3:OnUpdate(level)
  if player:IsPlayingMove("MOV_StatueSmashEnter") and player:GetActiveMovePercent() > 0.882 and currentStepAnimPlayed == false then
    currentStepAnimPlayed = true
    baldur:MeterSetValue("Health", 2)
    assetLevel:CallScript("CallScriptAnimFrames", "BREAK_GroundRip", frame_GroundRip_1, frame_GroundRip_2)
  end
  if baldur:IsPlayingMove("MOV_StatueSmashEnter") and baldur:GetActiveMovePercent() >= 0.417 and currentStepAnimPlayed2 == false then
    SetBaldurPhaseHealth(2, 25)
    currentStepAnimPlayed2 = true
  end
  if CheckAdvanceStageMove() or player:IsPlayingMove("MOV_BaldurWound_2_Idle") or player:IsPlayingMove("MOV_BaldurWound_2_Start") then
    forceIdleBeforeTransition = false
    BossEncounter:ForwardState()
    return
  end
end
function BossStage_2_4:OnEnter(level)
  goBaldurBuriedCineEnterModule.LuaObjectScript.Reset()
  bBaldurBuriedCineEnter = false
  local fromCheckpoint = debugSkip
  StageSetup(2, "Crush")
  DL.HideLevelObject(thisLevel, "SCRIPTED_Trees_HidePostGroundRip")
  assetLevel:CallScript("CallScriptVisibility", "BREAK_KratosCave", false)
  assetLevel:CallScript("CallScriptVisibility", "BREAK_Landmark_Pull", true)
  assetLevel:CallScript("CallScriptAnim", "BREAK_Landmark_Pull", "finish")
  if BossEncounter:IsDebugSkip() or fromCheckpoint then
    TeleportKratosBaldur("Warp_Stage2_AfterBaldurBuried", nil, true)
    assetLevel:CallScript("CallScriptAnimFrames", "BREAK_GroundRip", frame_GroundRip_2, 0)
    player:TriggerMoveEvent("LE_BaldurWoundWalk2")
  else
    TeleportKratosBaldur(nil, nil, true)
  end
  TeleportKratosBaldur(nil, "Warp_Stage1b", true)
  baldur:CallScript("SetNonhostile")
end
function BossStage_2_4:OnUpdate(level)
  if player:IsInsideEntityZone("Zone_StatueLift") then
    forceIdleBeforeTransition = false
    BossEncounter:ForwardState()
    return
  end
end
function BossStage_2_5p:OnEnter(level)
  BloodDecayReset()
  SetBaldurBuriedTrue()
  if BossEncounter:IsDebugSkip() then
    TeleportKratosBaldur("Warp_Stage2_StatueThrow", "Warp_Stage2b_Crushed", true)
  end
  TeleportKratosBaldur(nil, "Warp_Stage2b_Crushed", true)
  local puppetMarker = thisLevel:FindSingleGameObject("Warp_Stage2_StatueThrow")
  switchParams = {
    pos = puppetMarker:GetWorldPosition(),
    dir = puppetMarker:GetWorldForward(),
    speed = 2,
    stop = false,
    complete_radius = 1.5,
    strafe_distance = 1,
    focus_end_direction = true
  }
  kratosPup = game.Puppeteer.NewForce(thisLevel:FindSingleGameObject("Warp_Stage2_StatueThrow"), "Go to baldur buried stagger spot", player)
  kratosPup:Approach(switchParams)
  kratosPup:OnComplete(BaldurBuriedStagger)
end
function BaldurBuriedStagger()
  FreeKratos()
  DL.SetMotionWarpDrivers(thisLevel, player, "BuriedStaggerTranslation", "BuriedStaggerRotation", "Warp_Stage2_StatueThrow")
  player:TriggerMoveEvent("LE_Phase2_BaldurBuriedStagger")
  game.Audio.PlayBanter(btrBaldurCrushed)
end
function FreeKratos()
  if kratosPup ~= nil then
    kratosPup:Clear()
    kratosPup:DetachPuppet()
    kratosPup = nil
  end
end
function BossStage_2_5p:OnUpdate(level)
  if CheckAdvanceStageMove() or player:IsPlayingMove("MOV_Phase2_BaldurBuriedExit") then
    forceIdleBeforeTransition = false
    BossEncounter:ForwardState()
    return
  end
end
function BossStage_2_5p:OnExit(level)
  FreeKratos()
end
function BossStage_2_5:OnEnter(level)
  timer.StartLevelTimer(2, goBaldurBuriedCineEnterModule.LuaObjectScript.Reset)
  bBaldurBuriedCineEnter = false
  StageSetup(2, "Get up")
  SetBaldurPhaseHealth(2, baldur_health_threshold_throw_statue)
  if BossEncounter:IsDebugSkip() then
    TeleportKratosBaldur("Warp_Stage2_StatueThrow", "Warp_Stage2b_Crushed", true)
  else
    TeleportKratosBaldur(nil, "Warp_Stage2b_Crushed", true)
  end
  player:TriggerMoveEvent("LE_Phase2_BaldurBuriedExit")
  assetLevel:CallScript("CallScriptVisibility", "BREAK_Landmark_Pull", false)
  assetLevel:CallScript("CallScriptVisibility", "BREAK_Landmark_Throw", true)
  assetLevel:CallScript("CallScriptAnim", "BREAK_Landmark_Throw", "play")
  GameObjects.NavCol_After1:JumpAnimToFrame(0)
  GameObjects.NavCol_Before1:JumpAnimToFrame(0)
  GameObjects.NavCol_After1:PauseAnim()
  GameObjects.NavCol_Before1:PauseAnim()
  assetLevel:CallScript("CallScriptAnimFrames", "BREAK_GroundRip", frame_GroundRip_2, frame_GroundRip_3)
end
function BossStage_2_5:OnUpdate(level)
  if CheckAdvanceStageMove() or baldur:IsPlayingMove("MOV_Phase2_BaldurGroundSplitLoop") then
    forceIdleBeforeTransition = false
    BossEncounter:ForwardState()
    return
  end
end
function BossStage_2_6:OnEnter(level)
  StageSetup(2, "Split")
  TeleportKratosBaldur("Warp_Stage2_GroundRip", nil, false)
  GameObjects.NavCol_After1:PlayAnimToEnd()
  GameObjects.NavCol_Before1:PlayAnimToEnd()
  if BossEncounter:IsDebugSkip() then
    player:TriggerMoveEvent("LE_Phase2_BaldurGroundSplitEnter")
  end
  if groundSplitTimer ~= nil then
    groundSplitTimer = nil
  end
end
function BossStage_2_6:OnUpdate(level)
  DL.SetMotionWarpDrivers(thisLevel, player, "BirdseyeLaunchTranslation", "BirdseyeLaunchRotation", "Warp_Stage2_BirdseyeDestination")
  if CheckAdvanceStageMove() or baldur:IsPlayingMove("MOV_Phase2_BaldurBirdseyeLaunch") then
    forceIdleBeforeTransition = false
    BossEncounter:ForwardState()
    return
  end
end
function BossStage_2_7:OnEnter(level)
  StageSetup(2, "Birdseye Launch")
  assetLevel:CallScript("CallScriptAnimFrames", "BREAK_GroundRip", frame_GroundRip_3, frame_GroundRip_4)
  DL.SetMotionWarpDrivers(thisLevel, player, "BirdseyeLaunchTranslation", "BirdseyeLaunchRotation", "Warp_Stage2_BirdseyeDestination")
  if BossEncounter:IsDebugSkip() then
    player:TriggerMoveEvent("LE_Phase2_BaldurBirdseyeLaunch")
  end
  assetLevel:CallScript("CallScriptAnim", "BREAK_CrackClimbScrape", "reset")
end
function BossStage_2_7:OnUpdate(level)
  if baldur:IsPlayingMove("MOV_Phase2_BaldurBirdseyeLaunch") and baldur:GetActiveMovePercent() > 0.5 and currentStepAnimPlayed == false then
    currentStepAnimPlayed = true
  end
  if CheckAdvanceStageMove() or player:IsPlayingMove("MOV_Phase2_BaldurCrackClimbEnter") then
    forceIdleBeforeTransition = false
    BossEncounter:ForwardState()
    return
  end
end
function BossStage_2_7b:OnEnter(level)
  StageSetup(2, "Wall Scrape")
  assetLevel:CallScript("CallScriptAnimFrames", "BREAK_GroundRip", frame_GroundRip_4, 0)
  assetLevel:CallScript("CallScriptAnim", "BREAK_CrackClimbScrape", "play")
  if BossEncounter:IsDebugSkip() then
    TeleportKratosBaldur("Warp_Stage2_BirdseyeDestination", nil, true)
    player:TriggerMoveEvent("LE_Phase2_CrackClimbEnter")
  end
end
function BossStage_2_7b:OnUpdate(level)
  if CheckAdvanceStageMove() or player:IsPlayingMove("MOV_Cinematic_Enter_To_Idle") then
    forceIdleBeforeTransition = false
    BossEncounter:ForwardState()
    return
  end
end
function BossStage_2_8:OnEnter(level)
  StageSetup(3, "Inside Chasm")
  baldur:CallScript("SetNonhostile")
  TeleportKratosBaldur(nil, "Warp_Stage2_StaredownBaldur", true)
  LD.CallFunctionAfterDelay(function()
    game.Audio.PlayBanter("440_FirstCrackClimb")
  end, 3)
  baldur:TriggerMoveEvent("LE_FloatIdle")
  if BossEncounter:IsDebugSkip() then
    TeleportKratosBaldur("Warp_Stage2_ScrapeLanding", nil, true)
  end
  assetLevel:CallScript("CallScriptAnimFrames", "BREAK_GroundRip", frame_GroundRip_4, 0)
  assetLevel:CallScript("CallScriptAnim", "BREAK_CrackClimbKick", "reset")
  if debugPopups < 1 then
    debugPopups = 1
  end
  boolFirstCrackClimbBant = false
end
function BossStage_2_8:OnUpdate(level)
  if player:IsInsideEntityZone("Zone_ClimbOut") and (player:IsPlayingMove("MOV_Crack_Climb_HOD_Up_Stop") or player:IsPlayingMove("MOV_Crack_Climb_Idle") or player:IsPlayingMove("MOV_Crack_Climb_Up_Stop")) then
    forceIdleBeforeTransition = false
    player:TriggerMoveEvent("LE_StaredownPrep")
    BossEncounter:ForwardState()
    return
  end
  local playerPos = player:GetWorldPosition()
  if game.World.IsInsideCameraZone(playerPos, "CamZone_BaldurFightClimb_010") == true or game.World.IsInsideCameraZone(playerPos, "CamZone_BaldurFightClimb_020") == true or game.World.IsInsideCameraZone(playerPos, "CamZone_BaldurFightClimb_025") == true then
    game.Camera.SubmitCameraByName("PLYR_BaldurFight_Climb_010")
  end
  if player:IsPlayingMove("MOV_Crack_Climb_Up_Enter") and player:GetActiveMovePercent() > 0.01 and player:GetActiveMovePercent() < 0.05 and boolFirstCrackClimbBant == false then
    game.Audio.PlayBanter(btrFirstCrackClimb)
    boolFirstCrackClimbBant = true
  end
end
function BossStage_2_9:OnEnter(level)
  StageSetup(3, "Staredown")
  baldur:CallScript("SetNonhostile")
  TeleportKratosBaldur("Warp_Stage2_Staredown", nil, true)
  SetBaldurPhaseHealth(2, baldur_health_threshold_throw_statue)
  assetLevel:CallScript("CallScriptVisibility", "BREAK_CrackClimbScrape", false)
  assetLevel:CallScript("CallScriptAnim", "BREAK_CrackClimbKick", "play")
  player:TriggerMoveEvent("LE_Phase2_BaldurStaredown")
  local levelRiv200 = game.FindLevel("For200_House")
  if levelRiv200 ~= nil then
    levelRiv200:CallScript("BulderTerrainSwitch")
  end
end
function BossStage_2_9:OnUpdate(level)
  if player:IsPlayingMove("MOV_Phase2_Staredown") and player:GetActiveMovePercent() > 0.5 and player:MeterGetValue("Health") < player:MeterGetMax("Health") then
    player:MeterSetValue("Health", player:MeterGetValue("Health") + thisLevel:GetUnitTime() * 100)
  end
  if player:IsPlayingMove("MOV_Phase2_Staredown") then
    currentStepAnimPlayed = true
  end
  if player:IsPlayingMove("MOV_Phase2_Staredown") == false and currentStepAnimPlayed == true then
    BossEncounter:ForwardState()
    return
  end
end
function BossStage_3_1:OnEnter(level)
  StageSetup(3, "Fight")
  Boss_ShowHealth()
  AllowOffscreenIndicators()
  TeleportKratosBaldur("Warp_Stage3", "Warp_Stage3b", false)
  baldur:CallScript("SetHostile")
  baldur:TriggerMoveEvent("LE_TauntInviteL")
  DL.ShowLevelObject(thisLevel, "BossExitCollision")
  SetBaldurPhaseHealth(3, baldur_health_threshold_final_start)
  DL.HideLevelObject(thisLevel, "SCRIPTED_Trees_HidePostGroundRip")
  if player:MeterGetValue("Health") < 55 then
    player:MeterSetValue("Health", 55)
  end
  phaseHealthDDA = 50
end
function BossStage_3_1:OnUpdate(level)
  if currentStepAnimPlayed == false and player:MeterGetValue("Health") < 30 and baldur:PickupIsAcquired("Baldur_FightTimer") and baldur:PickupGetStage("Baldur_FightTimer") <= 2 then
    baldur:PickupSetStage("Baldur_FightTimer", 3)
    currentStepAnimPlayed = true
  end
  if GetBaldurHealthThreshold(3, 1) > 0 and baldur:GetHitPoints() <= GetBaldurHealthThreshold(3, 1) and CheckValidBaldurState() then
    forceIdleBeforeTransition = false
    BossEncounter:ForwardState()
    return
  end
  if baldur:GetWorldPosition().y <= 35 then
    DL.WarpCreature(baldur, thisLevel, "Warp_Stage3b")
  end
end
function BossStage_3_2:OnEnter(level)
  StageSetup(3, "Baldur Stunned")
  baldur:CallScript("SetHostile")
  if baldur:HasMarker("StageTransition") == false then
    baldur:AddMarker("StageTransition")
  end
  if BossEncounter:IsDebugSkip() then
    baldur:TriggerMoveEvent("LE_EvadeB")
  end
end
function BossStage_3_2:OnUpdate(level)
  SetHereToThereDrivers_Kill()
  if CheckAdvanceStageMove() or player:IsPlayingMove("MOV_HereToThereEnter") or player:IsPlayingMove("MOV_HereToThereEnter2") or player:IsPlayingMove("MOV_HereToThereEnter3") then
    forceIdleBeforeTransition = false
    BossEncounter:ForwardState()
  end
end
function BossStage_3_2:OnExit(level)
  if baldur:HasMarker("StageTransition") then
    baldur:RemoveMarker("StageTransition")
  end
end
function BossStage_3_2b:OnEnter(level)
  StageSetup(3, "Kill Transition")
  Boss_HideHealth()
  player:CallScript("LuaHook_ForceCineRageModeExit")
  if BossEncounter:IsDebugSkip() then
    TeleportKratosBaldur("Warp_Stage2", "Warp_Stage2", false)
    player:TriggerMoveEvent("LE_HereToThere3")
  end
end
function BossStage_3_2b:OnUpdate(level)
  DL.SetMotionWarpDrivers(thisLevel, baldur, "HereToThereTranslation", "HereToThereRotation", "Warp_Stage3_KillLocation")
  if CheckAdvanceStageMove() or baldur:IsPlayingMove("MOV_Phase3_BaldurKill") then
    forceIdleBeforeTransition = false
    BossEncounter:ForwardState()
  end
end
function BossStage_3_3:OnEnter(level)
  StageSetup(3, "Kill")
  baldur:CallScript("SetNonhostile")
  camera_InWoundWalk = false
  TeleportKratosBaldur("Warp_Stage3_KillLocation2", nil, true)
  if BossEncounter:IsDebugSkip() then
    player:TriggerMoveEvent("LE_Phase3_BaldurKill")
  end
  uiCalls.UI_Event_TurnOffDesignerMessage()
end
function BossStage_3_3:OnUpdate(level)
  if player:IsPlayingMove("MOV_Phase3_BaldurKillLoop") and player:GetActiveMovePercent() > 0.8 and currentStepAnimPlayed == false then
    uiCalls.EnableMechanicNonRage()
    currentStepAnimPlayed = true
  end
  if player:IsPlayingMove("MOV_Phase3_BaldurKillLoop") then
    if game.GetEnterRageModeOptionNumber ~= nil and game.GetEnterRageModeOptionNumber() == 1 then
      if player.Pad.CrossDown and player.Pad.CircleDown then
        player:TriggerMoveEvent("LE_SnapNeck")
      end
    elseif player.Pad.R3Down and player.Pad.L3Down then
      player:TriggerMoveEvent("LE_SnapNeck")
    end
  end
  if player:IsPlayingMove("MOV_Phase3_BaldurKillExit") and currentStepAnimPlayed2 == false then
    uiCalls.DisableMechanicNonRage()
    currentStepAnimPlayed2 = true
  end
  if player:IsPlayingMove("MOV_Phase3_BaldurKillExit") and player:GetActiveMovePercent() > 0.65 and currentStepAnimPlayed3 == false then
    currentStepAnimPlayed3 = true
    ShowForcedWoundedCamera()
  end
  if CheckAdvanceStageMove() or player:IsPlayingMove("MOV_BaldurWound_0_Idle") then
    forceIdleBeforeTransition = false
    BossEncounter:ForwardState()
    return
  end
end
function BossStage_3_4:OnEnter(level)
  GameObjects.woundWalkNavCurve.Child.LuaObjectScript.Enable()
  camera_InWoundWalk = true
  StageSetup(3, "Fight Complete")
  DL.HideLevelObject(thisLevel, "SCRIPTED_Trees_HidePostGroundRip")
  timer.StartLevelTimer(2, function()
    game.Audio.PlayBanter("455_FayeTellInTraction_00")
  end)
  if BossEncounter:IsDebugSkip() or debugSkip then
    ShowForcedWoundedCamera()
    player:TriggerMoveEvent("LE_BaldurWoundWalkDropAxe")
    TeleportKratosBaldur("Warp_Stage3_FightComplete", nil, true)
  end
  TeleportKratosBaldur(nil, "Son_Cage", true)
  DL.HideLevelObject(thisLevel, "BossExitCollision")
  DL.HideLevelObject(thisLevel, "Phase1Collision")
  baldur:CallScript("SetNonhostile")
  if debugPopups < 2 then
    debugPopups = 2
  end
end
function BossStage_3_4:OnUpdate(level)
  if player:GetWorldPosition().z < -686.5 and currentStepAnimPlayed3 == false then
    game.Audio.PlayBanter("455_FayeTellInTraction_01")
    currentStepAnimPlayed3 = true
  end
  if player:GetWorldPosition().z < -688 and currentStepAnimPlayed == false then
    player:TriggerMoveEvent("LE_BaldurWoundWalk0_Transition")
    currentStepAnimPlayed = true
  end
  if player:GetWorldPosition().z < -700 and currentStepAnimPlayed2 == false then
    player:TriggerMoveEvent("LE_BaldurWoundWalk1_Transition")
    currentStepAnimPlayed2 = true
  end
  if player:IsPlayingMove("MOV_BaldurWound_2_Idle") or player:IsPlayingMove("MOV_BaldurWound_2_Start") or player:IsPlayingMove("MOV_BaldurWound_2_Loop") then
    forceIdleBeforeTransition = false
    BossEncounter:ForwardState()
    HideForcedWoundedCamera()
    return
  end
end
function BossStage_3_5:OnEnter(level)
  HideForcedWoundedCamera()
  StageSetup(3, "Fight Complete")
  game.Audio.PlayBanter("455_FayeTellInTraction_02")
  camera_InWoundWalk = true
  if BossEncounter:IsDebugSkip() then
    TeleportKratosBaldur("Warp_Stage3_WoundWalkMid", "Son_Cage", true)
    player:TriggerMoveEvent("LE_BaldurWoundWalk2")
  end
  if not player:HasMarker("ReadyForTimeToGo") then
    player:AddMarker("ReadyForTimeToGo")
  end
end
function BossStage_3_5:OnUpdate(level)
  DL.SetMotionWarpDrivers(thisLevel, player, "WallLeanTranslation", "WallLeanRotation", "Warp_Stage3_HouseLean")
  if player:IsInsideEntityZone("Zone_WoundWalkDone") and currentStepAnimPlayed == false then
    player:TriggerMoveEvent("LE_BaldurWoundWalk2_Transition")
    currentStepAnimPlayed = true
    GameObjects.woundWalkNavCurve.Child.LuaObjectScript.Disable()
    camera_InWoundWalk = false
  end
  if player:IsPlayingMove("MOV_BaldurWound_2_Transition") and player:GetActiveMovePercent() >= 0 and currentStepAnimPlayed2 == false then
    game.Audio.PlayBanter("455_FayeTellInTraction_03")
    currentStepAnimPlayed2 = true
  end
  if player:IsPlayingMove("MOV_BaldurWound_ReadyForCine") and player:GetActiveMovePercent() >= 0 and doorReEnabled == false then
    houseLevel:CallScript("EnableDoorCineInteract")
    doorReEnabled = true
  end
  if player:IsPlayingMove("MOV_TimeToGo") then
    forceIdleBeforeTransition = false
    BossEncounter:ForwardState()
    return
  end
end
function BossStage_3_6:OnEnter(level)
  forceIdleBeforeTransition = false
  StageSetup(3, "Fight Complete")
  SonEnable()
  houseLevel:CallScript("RestoreBurnableCollision")
  GameObjects.woundWalkNavCurve.Child.LuaObjectScript.Disable()
  DL.HideLevelObject(thisLevel, "SCRIPTED_Trees_HidePostGroundRip")
  camera_InWoundWalk = false
  SonEnable()
  game.Level.SetVariable("FOR_BaldurBossDone", true)
  CompleteDefeatBaldurQuest()
  if baldur ~= nil then
    baldur:Destroy()
    baldur = nil
  end
end
function BossStage_3_6:OnUpdate(level)
end
function BossStage_3_6:OnExit(level)
  if baldur == nil then
    InitializeBossFight(false)
  end
end
function OnScriptLoaded(level)
  thisLevel = level
  player = game.Player.FindPlayer()
  pad = player.Pad
  houseLevel = game.FindLevel("For200_House")
  if houseLevel == nil then
    houseLevel = thisLevel
    using_TB_Baldur = true
  end
  toggleDebug:OnButtonDown(ToggleDebug)
  goBaldurBuriedCineEnterModule = level:FindGameObject("FireAndForget_CineEnterBaldurBuried")
  DL.HideLevelObject(thisLevel, "Phase1Collision")
  DL.HideLevelObject(thisLevel, "BossExitCollision")
  timer.StartLevelTimer(1, CheckGroundCollision)
end
function CheckGroundCollision()
  if game.Level.GetVariable("FOR_BaldurBossDone") == true then
    GameObjects.SCRIPTED_CollisionAfterCollapse:ShowCollision()
    GameObjects.SCRIPTED_CollisionBeforeCollapse:HideCollision()
  end
end
function OnSaveCheckpoint(level)
  return {
    levelstate = checkpoint.Save()
  }
end
function OnRestoreCheckpoint(level, savedInfo)
  print("restore")
  debugSkip = true
  checkpoint.Restore(savedInfo.levelstate)
end
function OnStart(level)
  print("start")
  doTeleport = true
  if game.Level.GetVariable("CompletedCineNumber") >= 100 then
    GameObjects.SCRIPTED_Trees_HidePostGroundRip:Hide()
  end
  local stage = BossEncounter:GetActiveIndex()
  if 2 < stage then
    BossEncounter:AddCreature("BaldurSpawner")
  end
  if baldur == nil then
    BossEncounter:SpawnBoss()
    baldur = BossEncounter:GetBoss()
  end
end
function OnFirstStart(level)
  print("first start")
end
function BossEncounter:OnEnter(level)
end
function BossEncounter:OnExit(level)
  PostStageSetup()
end
function BossEncounter:OnDebugBack()
  debugSkip = true
end
function BossEncounter:OnDebugForward()
  debugSkip = true
end
function BossEncounter:OnDebugRestart()
  debugSkip = true
end
function ToggleDebug()
end
function TeleportKratosBaldur(playerPos, baldurPos, forceTeleport)
  if doTeleport == true or forceTeleport or debugSkip then
    local currentState = BossEncounter:GetActiveStateName()
    if currentState == "stage3_4" then
      ShowForcedWoundedCamera()
    else
      HideForcedWoundedCamera()
    end
    if playerPos ~= nil then
      DL.WarpPlayer(thisLevel, playerPos)
    end
    if baldurPos ~= nil then
      DL.WarpCreature(baldur, thisLevel, baldurPos)
    end
    debugSkip = false
  end
end
function CallScriptVisibility(level, objectName, isVisible)
  if isVisible then
    DL.ShowLevelObject(thisLevel, objectName)
  else
    pcall(function()
      DL.HideLevelObject(thisLevel, objectName)
    end)
  end
end
function CallScriptGetBaldur(level)
  return baldur
end
local UpdateMotionDrivers = function()
  DL.SetMotionWarpDrivers(thisLevel, player, "RoofSlamTranslation", "RoofSlamRotation", "Warp_Stage1_RoofSlamDestination")
  DL.SetMotionWarpDrivers(thisLevel, player, "RoofSlamLandTranslation", "RoofSlamLandRotation", "Warp_Stage1_MMA")
  DL.SetMotionWarpDrivers(thisLevel, player, "TreeBatTranslation", "TreeBatRotation", "Warp_Stage1_BatReposition")
  DL.SetMotionWarpDrivers(thisLevel, baldur, "PlowExitTranslation", "PlowExitRotation", "Warp_Stage1b_Boulder")
  DL.SetMotionWarpDrivers(thisLevel, baldur, "BoulderFallTranslation", "BoulderFallRotation", "Warp_Stage1b_Boulder_Stunned")
  DL.SetMotionWarpDrivers(thisLevel, player, "BuriedStaggerTranslation", "BuriedStaggerRotation", "Warp_Stage2_StatueThrow")
  if player:IsPlayingMove("MOV_Phase1_RoofSlamUppercut") then
    DL.SetMotionWarpDrivers(thisLevel, player, "RoofSlamTranslation", "RoofSlamRotation", "Warp_Stage1_RoofSlamDestination")
  end
end
local rageMeterPrev = 0
local debugText
function DoDebug()
end
function IsBossFightActive()
  return game.Level.GetVariable("FOR_BaldurBossDone") == false and baldur ~= nil
end
function OnUpdate(level)
  if IsBossFightActive() then
    DoDebug()
    DoDDA()
    UpdateMotionDrivers()
    local stageString = "Baldur " .. BossEncounter:GetActiveStateName() .. "\n"
    stageString = stageString .. descString
    engine.DrawText2D(stageString, 200, 100, color.yellow)
    local debugTable = {}
    table.insert(debugTable, {
      "Add custom data here ",
      0
    })
    BossEncounter:UpdateCustomTable(debugTable)
    if baldur ~= nil and baldur:PickupIsAcquired("Debuff_Slow") then
      baldur:PickupRelinquish("Debuff_Slow")
    end
    baldur:CallScript("DrawBaldurDebug")
    if camera_InWoundWalk == true then
      UpdateCamera()
    end
  elseif (game.Level.GetVariable("CompletedCineNumber") == 78 or using_TB_Baldur == true) and baldur == nil and game.Level.GetVariable("FOR_BaldurBossDone") == false then
    InitializeBossFight(true)
  end
end
function InitializeBossFight(firstInit)
  if firstInit then
    BossEncounter:AddCreature("BaldurSpawner")
  end
  if baldur == nil then
    BossEncounter:SpawnBoss()
    baldur = BossEncounter:GetBoss()
  end
  if firstInit then
    BossEncounter:SetActiveState("stage0_1")
  end
end
function CheckValidBaldurState()
  local retVal = false
  if baldur:HasMarker("React") and baldur:HasMarker("MMA") == false then
    retVal = true
  end
  return retVal
end
function DoDDA()
  if baldur:HasMarker("React") == false and 0 < phaseHealthDDA then
    phaseHealthDDA = phaseHealthDDA - thisLevel:GetUnitTime()
    if phaseHealthDDA < 0 then
      phaseHealthDDA = 0
    end
  end
  engine.DrawText2D([[





DDA: ]] .. string.format("%.0f", phaseHealthDDA), 200, 100, color.yellow)
end
function SetBaldurPhaseHealth(phaseNum, curHealthNum)
  if baldur:PickupIsAcquired("Baldur_Phase") == false then
    baldur:PickupAcquire("Baldur_Phase")
  end
  baldur:PickupSetStage("Baldur_Phase", phaseNum)
  baldur:MeterSetValue("Health", curHealthNum)
  timer.StartLevelTimer(0.05, function()
    baldur:MeterSetValue("Health", curHealthNum)
  end)
end
function GetBaldurHealthThreshold(currentStage, currentStep)
  local retVal = -1
  local ddaMultipier = 0
  if currentStage == 1 and currentStep == 1 then
    retVal = baldur_health_threshold_mma_start
    ddaMultipier = 0
  elseif currentStage == 1 and currentStep == 4 then
    retVal = baldur_health_threshold_mma_mid
    ddaMultipier = 0
  elseif currentStage == 1 and currentStep == 5 then
    retVal = baldur_health_threshold_mma_end
    ddaMultipier = 0
  elseif currentStage == 2 and currentStep == 1 then
    retVal = baldur_health_threshold_statue_end
    ddaMultipier = 0
  elseif currentStage == 3 and currentStep == 1 then
    retVal = baldur_health_threshold_final_end
    ddaMultipier = 0
  end
  local ddaChange = 0
  if 0 < retVal and 0 < phaseHealthDDA then
    ddaChange = phaseHealthDDA * ddaMultipier
    if 150 < ddaChange then
      ddaChange = 150
    end
  end
  retVal = retVal - ddaChange
  return retVal
end
function GetBool_bBaldurBuriedCineEnter()
  return bBaldurBuriedCineEnter
end
function SetBaldurBuriedTrue()
  bBaldurBuriedCineEnter = true
end
function UpdateCamera()
  if player:HasMarker("WOUNDED0") then
    game.Camera.SubmitCameraByName("PLYR_WoundedWalk_000")
  end
  if player:HasMarker("WOUNDED1") then
    game.Camera.SubmitCameraByName("PLYR_WoundedWalk_010")
    if game.World.IsInsideCameraZone(player.WorldPosition, "cameraZone_peak") then
      game.Camera.SubmitCameraByName("PLYR_WoundedWalk_010")
      if gVFSEnableAlternateAfterFightCamera.value == true then
        game.Camera.SubmitCameraByName("PLYR_WoundedWalk_010_CLOSER_WIDE")
      else
        game.Camera.SubmitCameraByName("PLYR_WoundedWalk_010_CLOSER")
      end
    end
  end
  if player:HasMarker("WOUNDED0_TRANSITION") then
    game.Camera.SubmitCameraByName("PLYR_WoundedWalk_000")
  end
  if player:HasMarker("WOUNDED1_TRANSITION") then
    if gVFSEnableAlternateAfterFightCamera.value == true then
      game.Camera.SubmitCameraByName("PLYR_WoundedWalk_010_CLOSER_WIDE")
    else
      game.Camera.SubmitCameraByName("PLYR_WoundedWalk_010_CLOSER")
    end
  end
  if player:HasMarker("WOUNDED2") then
    game.Camera.SubmitCameraByName("PLYR_WoundedWalk_020")
  end
end
function ShowForcedWoundedCamera()
  local forcedcamera = thisLevel:GetGameObject("CamZone_ForcedCamera_Wounded_000")
  assert(forcedcamera)
  forcedcamera:ShowCameraVolume()
end
function HideForcedWoundedCamera()
  local forcedcamera = thisLevel:GetGameObject("CamZone_ForcedCamera_Wounded_000")
  assert(forcedcamera)
  forcedcamera:HideCameraVolume()
end
function UpdateLoadGroup_TimeToGo()
end
function CompleteDefeatBaldurQuest()
  LD.CompleteQuest("Quest_Forest_Objective900")
end
function AwardTrophy()
  print("Award Trophy: This is MY House")
  game.UnlockTrophy(1)
end
