function stopAllAnimations()local X=currentAnim if emoteNames[X]~=nil and emoteNames[X]==false then X="\105\100\108\101"end if currentlyPlayingEmote then X="\105\100\108\101"currentlyPlayingEmote=false end currentAnim=""currentAnimInstance=nil if currentAnimKeyframeHandler~=nil then currentAnimKeyframeHandler:disconnect()end if currentAnimTrack~=nil then currentAnimTrack:Stop()currentAnimTrack:Destroy()currentAnimTrack=nil end for X,G in pairs(locomotionMap)do if G.track then G.track:Stop()G.track:Destroy()G.track=nil end end return X end local function X()if userAnimateScaleRun then return Character:GetScale()else return 1 end end function getHeightScale()if Humanoid then if not Humanoid.AutomaticScalingEnabled then return X()end local G=Humanoid.HipHeight/HumanoidHipHeight if AnimationSpeedDampeningObject==nil then AnimationSpeedDampeningObject=script:FindFirstChild("\083\099\097\108\101\068\097\109\112\101\110\105\110\103\080\101\114\099\101\110\116")end if AnimationSpeedDampeningObject~=nil then G=1+((Humanoid.HipHeight-HumanoidHipHeight)*AnimationSpeedDampeningObject.Value)/HumanoidHipHeight end return G end return X()end local function G(X,G)return-math.atan2(X.x*G.y-X.y*G.x,X.x*G.x+X.y*G.y)end local A=2.0 local function l(X,l,T,q,H,k)local p=.5*(H+k)local h={x=(q-H)/p;y=A*G(l,X)}local i={x=(k-H)/p,y=A*G(l,T)}local f=smallButNotZero+(i.x*i.x+i.y*i.y)local x=h.x*i.x+h.y*i.y local S=math.clamp(1.0-x/f,.0,1.0)return S end local function T(X,G)if userAnimateScaleRun then local A=getHeightScale()X/=A G/=A end local A={}local T=.0 for q,H in pairs(locomotionMap)do if X.x*H.lv.x<.0 or X.y*H.lv.y<0 then A[q]=.0 continue end A[q]=math.huge for T,k in pairs(locomotionMap)do if X.x*k.lv.x<.0 or X.y*k.lv.y<0 then continue end A[q]=math.min(A[q],l(X,H.lv,k.lv,G,H.speed,k.speed))end T+=A[q]end local q=.0 local H=0 local k=0 for X,G in pairs(locomotionMap)do if A[X]/T>.1 then q+=A[X]H+=A[X]*G.lv.x k+=A[X]*G.lv.y else A[X]=.0 end end local p local h=H*H+k*k if h>smallButNotZero then p=math.sqrt((G*G)/h)else p=0 end if not userAnimateScaleRun then p=p/getHeightScale()end local i=0 for X,G in pairs(locomotionMap)do if G.track.IsPlaying then i=G.track.TimePosition break end end for X,G in pairs(locomotionMap)do if A[X]>.0 then if not G.track.IsPlaying then G.track:Play(runBlendtime)G.track.TimePosition=i end local l=math.max(smallButNotZero,A[X]/q)G.track:AdjustWeight(l,runBlendtime)G.track:AdjustSpeed(p)else G.track:Stop(runBlendtime)end end end local function q()local X=Humanoid.WalkToPoint local G=Humanoid.WalkToPart if Humanoid.MoveDirection~=Vector3.zero then return Humanoid.MoveDirection elseif G or X~=Vector3.zero then local A if G then A=G.CFrame:PointToWorldSpace(X)else A=X end local l=Vector3.zero if Humanoid.RootPart then l=A-Humanoid.RootPart.CFrame.Position l=Vector3.new(l.x,.0,l.z)local X=l.Magnitude if X>.01 then l/=X end end return l else return Humanoid.MoveDirection end end local function H(X)local G if locomotionMap==strafingLocomotionMap then local G=q()if not Humanoid.RootPart then return end local A=Humanoid.RootPart.CFrame if math.abs(A.UpVector.Y)<smallButNotZero or pose~="\082\117\110\110\105\110\103"or humanoidSpeed<.001 then for X,G in pairs(locomotionMap)do if G.track then G.track:AdjustWeight(smallButNotZero,runBlendtime)end end return end local l=A.LookVector local H=Vector3.new(l.X,.0,l.Z)H=H/H.Magnitude local k=G:Dot(H)if k<=.0 and k>-0.05 then k=smallButNotZero end local p=H.X*G.Z-H.Z*G.X local h=Vector2.new(p,k)local i=Vector2.new(h.x-cachedLocalDirection.x,h.y-cachedLocalDirection.y)if i:Dot(i)>.001 or math.abs(humanoidSpeed-cachedRunningSpeed)>.01 or X-lastBlendTime>1 then cachedLocalDirection=h cachedRunningSpeed=humanoidSpeed lastBlendTime=X T(cachedLocalDirection,cachedRunningSpeed)end else if math.abs(humanoidSpeed-cachedRunningSpeed)>.01 or X-lastBlendTime>1 then cachedRunningSpeed=humanoidSpeed lastBlendTime=X T(Vector2.yAxis,cachedRunningSpeed)end end end function setAnimationSpeed(X)if currentAnim~="\119\097\108\107"then if X~=currentAnimSpeed then currentAnimSpeed=X currentAnimTrack:AdjustSpeed(currentAnimSpeed)end end end function keyFrameReachedFunc(X)if X=="\069\110\100"then local X=currentAnim if emoteNames[X]~=nil and emoteNames[X]==false then X="\105\100\108\101"end if currentlyPlayingEmote then if currentAnimTrack.Looped then return end X="\105\100\108\101"currentlyPlayingEmote=false end local G=currentAnimSpeed playAnimation(X,.15,Humanoid)setAnimationSpeed(G)end end function rollAnimation(X)local G=math.random(1,animTable[X].totalWeight)local A=G local l=1 while G>animTable[X][l].weight do G=G-animTable[X][l].weight l=l+1 end return l end local function k(X,G,A,l)if X~=currentAnimInstance then if currentAnimTrack~=nil then currentAnimTrack:Stop(A)currentAnimTrack:Destroy()end if currentAnimKeyframeHandler~=nil then currentAnimKeyframeHandler:disconnect()end currentAnimSpeed=1.0 currentAnim=G currentAnimInstance=X if G=="\119\097\108\107"then setupWalkAnimations()else destroyWalkAnimations()currentAnimTrack=l:LoadAnimation(X)currentAnimTrack.Priority=Enum.AnimationPriority.Core currentAnimTrack:Play(A)currentAnimKeyframeHandler=currentAnimTrack.KeyframeReached:connect(keyFrameReachedFunc)end end end function playAnimation(X,G,A)local l=rollAnimation(X)local T=animTable[X][l].anim k(T,X,G,A)currentlyPlayingEmote=false end function playEmote(X,G,A)k(X,X.Name,G,A)currentlyPlayingEmote=true end


function stopAllAnimations()
	local oldAnim = currentAnim

	-- return to idle if finishing an emote
	if (emoteNames[oldAnim] ~= nil and emoteNames[oldAnim] == false) then
		oldAnim = "idle"
	end

	if currentlyPlayingEmote then
		oldAnim = "idle"
		currentlyPlayingEmote = false
	end

	currentAnim = ""
	currentAnimInstance = nil
	if (currentAnimKeyframeHandler ~= nil) then
		currentAnimKeyframeHandler:disconnect()
	end

	if (currentAnimTrack ~= nil) then
		currentAnimTrack:Stop()
		currentAnimTrack:Destroy()
		currentAnimTrack = nil
	end

	for _,v in pairs(locomotionMap) do
		if v.track then
			v.track:Stop()
			v.track:Destroy()
			v.track = nil
		end
	end

	return oldAnim
end

local function getRigScale()
	if userAnimateScaleRun then
		return Character:GetScale()
	else
		return 1
	end
end

function getHeightScale()
	if Humanoid then
		if not Humanoid.AutomaticScalingEnabled then
			-- When auto scaling is not enabled, the rig scale stands in for
			-- a computed scale.
			return getRigScale()
		end

		local scale = Humanoid.HipHeight / HumanoidHipHeight
		if AnimationSpeedDampeningObject == nil then
			AnimationSpeedDampeningObject = script:FindFirstChild("ScaleDampeningPercent")
		end
		if AnimationSpeedDampeningObject ~= nil then
			scale = 1 + (Humanoid.HipHeight - HumanoidHipHeight) * AnimationSpeedDampeningObject.Value / HumanoidHipHeight
		end
		return scale
	end
	return getRigScale()
end


local function signedAngle(a, b)
	return -math.atan2(a.x * b.y - a.y * b.x, a.x * b.x + a.y * b.y)
end

local angleWeight = 2.0
local function get2DWeight(px, p1, p2, sx, s1, s2)
	local avgLength = 0.5 * (s1 + s2)

	local p_1 = {x = (sx - s1)/avgLength, y = (angleWeight * signedAngle(p1, px))}
	local p12 = {x = (s2 - s1)/avgLength, y = (angleWeight * signedAngle(p1, p2))}
	local denom = smallButNotZero + (p12.x*p12.x + p12.y*p12.y)
	local numer = p_1.x * p12.x + p_1.y * p12.y
	local r = math.clamp(1.0 - numer/denom, 0.0, 1.0)
	return r
end

local function blend2D(targetVelo, targetSpeed)
	if userAnimateScaleRun then
		local heightScale = getHeightScale()
		targetVelo /= heightScale
		targetSpeed /= heightScale
	end

	local h = {}
	local sum = 0.0
	for n,v1 in pairs(locomotionMap) do
		if targetVelo.x * v1.lv.x < 0.0 or targetVelo.y * v1.lv.y < 0 then
			-- Require same quadrant as target
			h[n] = 0.0
			continue
		end
		h[n] = math.huge
		for j,v2 in pairs(locomotionMap) do
			if targetVelo.x * v2.lv.x < 0.0 or targetVelo.y * v2.lv.y < 0 then
				-- Require same quadrant as target
				continue
			end
			h[n] = math.min(h[n], get2DWeight(targetVelo, v1.lv, v2.lv, targetSpeed, v1.speed, v2.speed))
		end
		sum += h[n]
	end

	--truncates below 10% contribution
	local sum2 = 0.0
	local weightedVeloX = 0
	local weightedVeloY = 0
	for n,v in pairs(locomotionMap) do

		if (h[n] / sum > 0.1) then
			sum2 += h[n]
			weightedVeloX += h[n] * v.lv.x
			weightedVeloY += h[n] * v.lv.y
		else
			h[n] = 0.0
		end
	end
	local animSpeed
	local weightedSpeedSquared = weightedVeloX * weightedVeloX + weightedVeloY * weightedVeloY
	if weightedSpeedSquared > smallButNotZero then
		animSpeed = math.sqrt(targetSpeed * targetSpeed / weightedSpeedSquared)
	else
		animSpeed = 0
	end

	if not userAnimateScaleRun then
		animSpeed = animSpeed / getHeightScale()
	end
	local groupTimePosition = 0
	for n,v in pairs(locomotionMap) do
		if v.track.IsPlaying then
			groupTimePosition = v.track.TimePosition
			break
		end
	end
	for n,v in pairs(locomotionMap) do
		-- if not loco
		if h[n] > 0.0 then
			if not v.track.IsPlaying then
				v.track:Play(runBlendtime)
				v.track.TimePosition = groupTimePosition
			end

			local weight = math.max(smallButNotZero, h[n] / sum2)
			v.track:AdjustWeight(weight, runBlendtime)
			v.track:AdjustSpeed(animSpeed)
		else
			v.track:Stop(runBlendtime)
		end
	end

end

local function getWalkDirection()
	local walkToPoint = Humanoid.WalkToPoint
	local walkToPart = Humanoid.WalkToPart
	if Humanoid.MoveDirection ~= Vector3.zero then
		return Humanoid.MoveDirection
	elseif walkToPart or walkToPoint ~= Vector3.zero then
		local destination
		if walkToPart then
			destination = walkToPart.CFrame:PointToWorldSpace(walkToPoint)
		else
			destination = walkToPoint
		end
		local moveVector = Vector3.zero
		if Humanoid.RootPart then
			moveVector = destination - Humanoid.RootPart.CFrame.Position
			moveVector = Vector3.new(moveVector.x, 0.0, moveVector.z)
			local mag = moveVector.Magnitude
			if mag > 0.01 then
				moveVector /= mag
			end
		end
		return moveVector
	else
		return Humanoid.MoveDirection
	end
end

local function updateVelocity(currentTime)

	local tempDir

	if locomotionMap == strafingLocomotionMap then

		local moveDirection = getWalkDirection()

		if not Humanoid.RootPart then
			return
		end

		local cframe = Humanoid.RootPart.CFrame
		if math.abs(cframe.UpVector.Y) < smallButNotZero or pose ~= "Running" or humanoidSpeed < 0.001 then
			-- We are horizontal!  Do something  (turn off locomotion)
			for n,v in pairs(locomotionMap) do
				if v.track then
					v.track:AdjustWeight(smallButNotZero, runBlendtime)
				end
			end
			return
		end
		local lookat = cframe.LookVector
		local direction = Vector3.new(lookat.X, 0.0, lookat.Z)
		direction = direction / direction.Magnitude --sensible upVector means this is non-zero.
		local ly = moveDirection:Dot(direction)
		if ly <= 0.0 and ly > -0.05 then
			ly = smallButNotZero -- break quadrant ties in favor of forward-friendly strafes
		end
		local lx = direction.X*moveDirection.Z - direction.Z*moveDirection.X
		local tempDir = Vector2.new(lx, ly) -- root space moveDirection
		local delta = Vector2.new(tempDir.x-cachedLocalDirection.x, tempDir.y-cachedLocalDirection.y)
		-- Time check serves the purpose of the old keyframeReached sync check, as it syncs anim timePosition
		if delta:Dot(delta) > 0.001 or math.abs(humanoidSpeed - cachedRunningSpeed) > 0.01 or currentTime - lastBlendTime > 1 then
			cachedLocalDirection = tempDir
			cachedRunningSpeed = humanoidSpeed
			lastBlendTime = currentTime
			blend2D(cachedLocalDirection, cachedRunningSpeed)
		end
	else
		if math.abs(humanoidSpeed - cachedRunningSpeed) > 0.01 or currentTime - lastBlendTime > 1 then
			cachedRunningSpeed = humanoidSpeed
			lastBlendTime = currentTime
			blend2D(Vector2.yAxis, cachedRunningSpeed)
		end
	end
end

function setAnimationSpeed(speed)
	if currentAnim ~= "walk" then
		if speed ~= currentAnimSpeed then
			currentAnimSpeed = speed
			currentAnimTrack:AdjustSpeed(currentAnimSpeed)
		end
	end
end

function keyFrameReachedFunc(frameName)
	if (frameName == "End") then
		local repeatAnim = currentAnim
		-- return to idle if finishing an emote
		if (emoteNames[repeatAnim] ~= nil and emoteNames[repeatAnim] == false) then
			repeatAnim = "idle"
		end

		if currentlyPlayingEmote then
			if currentAnimTrack.Looped then
				-- Allow the emote to loop
				return
			end

			repeatAnim = "idle"
			currentlyPlayingEmote = false
		end

		local animSpeed = currentAnimSpeed
		playAnimation(repeatAnim, 0.15, Humanoid)
		setAnimationSpeed(animSpeed)
	end
end

function rollAnimation(animName)
	local roll = math.random(1, animTable[animName].totalWeight)
	local origRoll = roll
	local idx = 1
	while (roll > animTable[animName][idx].weight) do
		roll = roll - animTable[animName][idx].weight
		idx = idx + 1
	end
	return idx
end

local function switchToAnim(anim, animName, transitionTime, humanoid)
	-- switch animation
	if (anim ~= currentAnimInstance) then

		if (currentAnimTrack ~= nil) then
			currentAnimTrack:Stop(transitionTime)
			currentAnimTrack:Destroy()
		end
		if (currentAnimKeyframeHandler ~= nil) then
			currentAnimKeyframeHandler:disconnect()
		end


		currentAnimSpeed = 1.0

		currentAnim = animName
		currentAnimInstance = anim	-- nil in the case of locomotion

		if animName == "walk" then
			setupWalkAnimations()
		else
			destroyWalkAnimations()
			-- load it to the humanoid; get AnimationTrack
			currentAnimTrack = humanoid:LoadAnimation(anim)
			currentAnimTrack.Priority = Enum.AnimationPriority.Core

			currentAnimTrack:Play(transitionTime)

			-- set up keyframe name triggers
			currentAnimKeyframeHandler = currentAnimTrack.KeyframeReached:connect(keyFrameReachedFunc)
		end
	end
end

function playAnimation(animName, transitionTime, humanoid)
	local idx = rollAnimation(animName)
	local anim = animTable[animName][idx].anim

	switchToAnim(anim, animName, transitionTime, humanoid)
	currentlyPlayingEmote = false
end

function playEmote(emoteAnim, transitionTime, humanoid)
	switchToAnim(emoteAnim, emoteAnim.Name, transitionTime, humanoid)
	currentlyPlayingEmote = true
end
