if acrobatics --c'mon
	print("Acrobatics is already loaded - don't load both of these files at once!")
	return
end

--freeslots
freeslot("sfx_tric", "sfx_trice") 

for tsnd = 0, 5 --trick confirms
	freeslot("sfx_acgr".. tsnd)
end

for tsnd = 0, 5 --trick dashes
	freeslot("sfx_acgd".. tsnd)
end

--CVARS--

local as_active = CV_RegisterVar({
	name = "as_active",
	defaultvalue = "On",
	flags = CV_NETVAR,
	possiblevalue = CV_OnOff
})

local as_trickreminder = CV_RegisterVar({
	name = "as_trickreminder",
	defaultvalue = "On",
	flags = CV_NETVAR,
	possiblevalue = CV_OnOff
})

local as_trickyield = CV_RegisterVar({
	name = "as_trickyield",
	defaultvalue = "combo",
	flags = CV_NETVAR,
	possiblevalue = {combo = 0, sneaker = 1}
})

rawset(_G, "as_textdebug", CV_RegisterVar({ --touch this if you don't wanna see the side of your screen
  name = "as_textdebug",
  defaultvalue = "Off",
  flags = CV_SHOWMODIF,
  PossibleValue = CV_OnOff,
}))


addHook("ThinkFrame", function()
	if (CV_FindVar("hm_scoreboard")) and as_hmload == false --check for hostmod
		HM_Scoreboard_AddMod({disp = "Acrobatics(L)", var = "as_active"})
		as_hmload = true
	end
end)


local function print_to_player(p, message)
    CONS_Printf(p, message)
    S_StartSound(nil, sfx_beep, p) 
end 

local function is_string(x)
	return type(x) == 'string'
end

local function trickchangebutton(p, arg)
	arg = tostring(arg):lower()
	if(arg == "brake" or (arg == "custom" or arg=="custom1")) then 
		if(arg == "brake") then 
			p.trick_prefbutton = BT_BRAKE
		elseif(arg == "custom" or arg == "custom1") then 
			p.trick_prefbutton = BT_CUSTOM1
			arg = "custom1"
		end 
		if tsrb2kr --TEAM SONIC RACING: Uses all the Customs, so you shouldn't change this, probably.
			print_to_player(p, "\133*WARNING:\131 TSRB2KR is active, CUSTOM1 cannot be used!")
			print_to_player(p, "\131* Trick button force changed to \130BRAKE\131.")
			p.trick_prefbutton = BT_BRAKE
			p.trick_button = p.trick_prefbutton
		else
			p.trick_button = p.trick_prefbutton
			print_to_player(p, "\131* Trick button changed to \130" .. arg:upper() .. "\131.")
		end
	else 
		print_to_player(p, "\135* Please choose between \130BRAKE \135or \130CUSTOM.")
	end 
end
COM_AddCommand("as_trickbtn", trickchangebutton, 0)

--MATH and OTHER STUFF--

--rescale from ashnal- saved a braincell
local function rescale(value, oldmin, oldmax, newmin, newmax)
    return newmin +  FixedMul(FixedDiv( value-oldmin , oldmax-oldmin), newmax-newmin)
end

--TIME FOR TRICKS--
local function setplayertrickvars(p)
--Visuals
    p.sparkle = nil -- The sparkle... thingies.
    p.hastricked = false  --self explanatory
    p.spintimer = 0 -- How long the 'spin' animation will play when you've done a trick.
	p.spinning = (p.mo.state == S_KART_SPIN or p.mo.state == S_KART_PAIN) --If you're already spinning, there's no reason to force things.
--Pretricks
	p.lastz = p.mo.z -- Race tricks only work ascending.
    p.trickready = 1 -- In case a player joins in the MIDDLE of a netgame and these variables haven't been set. 
	p.trick_button = (p.trick_prefbutton ~= nil) and p.trick_prefbutton or BT_BRAKE -- Gotta call it somewhere.
	p.trick_button_trigger = nil -- Did he do it?
---COMBO TRICKS
	p.trickchaintimer = 0  -- Counts down every tic, for combo tricks
	p.inchain = false -- Eligibility for chaining combo
	p.chaincount = 0 -- Count your combos!
---AFTEREFFECTS
	p.trickboost = 0 -- Time-based [Low speed, max length] - integers
	p.trickbooststr = 0 --Strength based [Low weight, max strength] - fixed point
	p.trickboostdust = 0 --Timer for dust
	p.trickoffroad = 0 --Needs its own timer so great tricks don't over frontrun
--TRICKSNEAKER
	p.tricksneakerlastframe = 0 --Post storage checks
	p.tricklastframebtn = 0 --Post storage checks
	p.tricksneaker = false --flag for sneaker vs trick boosts	
	p.tricksneakerbuffer = 0 --a more specific sneaker check
	p.tricksneakerprevboost = 0 --fixed point, for value smoothing between sneakers and tricks
	p.finaltrickboost = 0 --fixed point for value smoothing
---HUD STUFF
	p.sincelasttrick = 0 --Timer for style messages.
	p.trickgrade = 0 --Usually syncs up to chargecheck, for style messages
end 

--TRICK FUNCTIONS

local function confirmtrickpress(p) 
	if(p.trick_button == BT_BRAKE)
		p.trick_button_trigger = p.cmd.buttons & BT_BRAKE
	else
		p.trick_button_trigger = p.cmd.buttons & BT_CUSTOM1
	end 	
end

local function tricksparkle(p, potential) --The sparkle function. potential [boolean] denotes intensity: possible chain/charging.
	if(not p.kartstuff[k_invincibilitytimer]) and not(p.powers[pw_nocontrol])
		if potential == true
			K_SpawnSparkleTrail(p.mo) --maybe i'll write a real one later that's not this
		else
			p.sparkle = P_SpawnMobj(p.mo.x+P_RandomRange(-30, 30)*p.mo.scale, p.mo.y+P_RandomRange(-30, 30)*p.mo.scale, p.mo.z+P_RandomRange(-15, 0)*p.mo.scale, MT_SPARKLETRAIL) 
			p.sparkle.destscale = p.mo.destscale
			p.sparkle.target = p.mo 
			p.sparkle.color = p.mo.color
		end
		if leveltime%4 > 2 
			p.mo.colorized = true
		else
			p.mo.colorized = false
		end 
	end
end

---TRICKBOOST FUNCTIONS 
--DUST AND EFFECTS

local trvangle, newx, newy, dust, flash 

local function K_TrickDustRelease(p, intensity) --since i can't get into spawn dust funcss on lua
	
	if intensity == nil then intensity = 1 end --dummy check
	
	--3 Checks -- Ground Check, Way Too Slow, or you're already kicking up sliptide dust.
	if not(P_IsObjectOnGround(p.mo)) or FixedDiv(p.speed, mapobjectscale)/FRACUNIT <= 25 or p.kartstuff[k_aizdriftstrat] 
		return --yeah
	end
	
	if leveltime%2 == 1 or intensity == 3--Kick up some dust every other frame, like the game
		for i = 0,1 do
			trvangle = p.mo.angle - (ANGLE_45/5)*p.kartstuff[k_drift]
			newx = p.mo.x + P_ReturnThrustX(p.mo, trvangle + ((i == 0) and -1 or 1)*ANGLE_90, FixedMul(24*FRACUNIT, p.mo.scale))			
			newy = p.mo.y + P_ReturnThrustY(p.mo, trvangle + ((i == 0) and -1 or 1)*ANGLE_90, FixedMul(24*FRACUNIT, p.mo.scale))
			dust = P_SpawnMobj(newx, newy, (verticalflip and (p.mo.ceilingz or -1) or p.mo.floorz), MT_AIZDRIFTSTRAT)
			dust.target = p.mo
			dust.angle = trvangle - ((i == 0) and -1 or 1)*ANGLE_67h
			dust.scale = p.mo.scale/(5-intensity)
			dust.destscale = 2*p.mo.scale/(6-intensity)
			dust.scalespeed = p.mo.scale/6
			dust.momx = 3*p.mo.momx/5
			dust.momy = 3*p.mo.momy/5				
			//dust.fuse = 25 -- dunno if this actually does shit
		end
	end
end


--TRICKCALCS
local um
local function calctrickboostlength(p, debug) --use debug to force values
	um = rescale(p.kartspeed<<FRACBITS, 9<<FRACBITS, 1<<FRACBITS, 5<<FRACBITS, 15<<FRACBITS) 
	um = $>>FRACBITS
	return (um*p.chaincount)+10 --Capping a trickboost	
end


local function tricksneakerCheck(p)

	--A trick JUST landed and we suddenly have trickboost, and we're not midsneaker buffer.
	if p.trickboost > 0 and not(p.tricksneakerbuffer)
		p.tricksneaker = true
	end
	--The following blocks try to prove otherwise.
	

	if (p.kartstuff[k_rocketsneakertimer] and p.tricklastframebtn == 0 and (p.cmd.buttons & BT_ATTACK)) and p.tricklastitem ~= KITEM_ROCKETSNEAKER
		p.tricksneakerbuffer = p.kartstuff[k_sneakertimer] --A buffer that means "we're in a sneaker now don't disturb" -number from sourcecode
		p.tricksneaker = false	--It was PRESSED, - we want the real sneakerboost.
	end

	
	if p.kartstuff[k_floorboost] --Sneaker panel?
		p.tricksneakerbuffer = p.kartstuff[k_sneakertimer] 
		p.tricksneaker = false
	end
	
	--Check for a sneakertimer change of ANYTHING.
	if not(p.kartstuff[k_sneakertimer] == p.tricksneakerlastframe)

		--First - item use
		if p.tricklastitem ~= nil --Was there an item last frame?
			if (p.tricklastitem == KITEM_SNEAKER and p.kartstuff[k_itemtype] ~= KITEM_SNEAKER) or --Sneaker
			(p.kartstuff[k_itemtype] == KITEM_SNEAKER and p.kartstuff[k_itemamount] < p.trickprevitemcount) then --Multisneaker
				p.tricksneakerbuffer = p.kartstuff[k_sneakertimer]
				p.tricksneaker = false	
			end
		end
		
		if (p.kartstuff[k_sneakertimer] > p.tricksneakerlastframe) --Something else is making us sneaker and we need to not worry about it
			p.tricksneakerbuffer = p.kartstuff[k_sneakertimer]
			p.tricksneaker = false	
		end
		
	end
	
end


--K_DoTrickBoost(p)
local function applytrickboost(p) 

	if p.trickboost > 0 
		if p.tricksneaker then p.kartstuff[k_sneakertimer] = max($, p.trickboost) end --Sometimes trickboosts are longer than sneakers, so let's just give 'em the whole thing.
		--Calculating trick strength via kartspeed.
		p.trickbooststr = rescale(p.kartspeed*FRACUNIT, 9*FRACUNIT, FRACUNIT, 3*FRACUNIT/20, 3*FRACUNIT/8) --Min 15%[9], Max 37.5%[1]
		p.trickbooststr = $*(min(p.chaincount, 4)) --It can get out of control!

		--Offroad penalty after leniency is over -- bonus TANKS if you're still offroad to prevent accels from taking shortcuts
		if p.trickoffroad == 0 and p.kartstuff[k_offroad] > FRACUNIT and not(p.tricksneakerbuffer)
			p.trickbooststr = 0 --nope
			p.kartstuff[k_sneakertimer] = 0 --Reapply offroad pain if no true sneaker
		end	
		
		p.finaltrickboost = p.trickbooststr --let's set this aside for now.
		
		--Applying the boost is way less straightforward because a trickboost is less then a sneaker boost [which is being applied by sneakertimer] - so we have to undo sneakerboost beforehand carefully.
		if p.tricksneaker and not(p.tricksneakerbuffer) then  --we're in puretrick boost!
		
			if not(tsrb2kr and p.mo.tsr_ultimateon)
				p.kartstuff[k_accelboost] = $ - 8*FRACUNIT -- Nuke accel.
			end
			
			if p.tricksneakerprevboost > p.trickbooststr -- ...but readd a little of it, if we're transitioning. value smoothing from the other way.
				p.finaltrickboost = p.tricksneakerprevboost + (p.trickbooststr - p.tricksneakerprevboost)/(TICRATE/2);
			else --Or not, then we're here 
				p.finaltrickboost = p.trickbooststr
			end
	
		end	
		
		if not(p.tricksneakerbuffer)
			if tsrb2kr and p.mo.tsr_ultimateon 
				p.kartstuff[k_speedboost] = $ + (p.trickbooststr/10) --What, is wipezones level speed not enough for you?
			else
				p.kartstuff[k_speedboost] = p.finaltrickboost --forced here deliberately.
			end
		end
		p.kartstuff[k_accelboost] = max($, 4*FRACUNIT) --400% accel increase for nonsneaker boosts.
		if p.trickboostdust >= 24
			K_TrickDustRelease(p, 1)
		elseif p.trickboostdust >= 10
			K_TrickDustRelease(p, 0)
		else
			--lmao
		end
		tricksparkle(p, false) --kirakira
		p.trickboostdust = max($ - 1, 0) 
		p.trickboost = max($ - 1,0) 
		p.trickoffroad = max($ - 1,0) 
	end
	
	p.tricksneakerprevboost = p.finaltrickboost --stored for next tic because sneakertimer's gonna overwrite it :deadinside:
	p.tricksneakerbuffer = max($ - 1, 0) --This needs to be run outside the trickboost check so we can have overlaps of trick vs sneaker.
	
end

local function canplayertrick(p) --CAN THEY? Check for air, and not spinning out, and not deading out.
    return (not P_IsObjectOnGround(p.mo) and not p.kartstuff[k_respawn] and p.kartstuff[k_spinouttimer] == 0 and p.playerstate ~= PST_DEAD and not p.mo.drifthold and not(p.powers[pw_nocontrol]))
end 

local function trickspinanimate(p) --The actual spinning.
	local spinfactor = p.chaincount
	local spindiff = ( ANGLE_11hh * leveltime * ((spinfactor == 0 and 6) or spinfactor) ) --TODO
    p.spintimer = max($ - 1, 0)
	p.frameangle = $ + spindiff
end 


--HUD Animation Functions

local flavorframeinfo = {
		[-1] = 8,
		[0] = 8,
		[1] = 10,
		[2] = 16,
		[3] = 8,
		[4] = 8,
		[5] = 8,
		}
local curframe, maxframes	
local function flavoranimation(p) --TODO: Sometimes the animation bugs the fuck out on longer anims
	curframe = 0 
	maxframes = flavorframeinfo[p.trickgrade] --The max amount of frames for each status
	curframe = (leveltime)%maxframes
	return curframe	+ 1 --[tl note: i am too lazy to rename my exports from aseprite]
end


addHook("MapLoad", do
    for p in players.iterate do 
		p.trickready = nil
		if p.mo and not p.spectator
			setplayertrickvars(p) --Reset it all
		end
    end 
end)

local starttime = 6*TICRATE + (3*TICRATE/4) --Everyone's doing it

--The ThinkFrame

addHook("ThinkFrame", do 
    for p in players.iterate do	
        if not p.mo or not p.mo.valid continue end 

        // Initialization etc etc durr hurr
		if leveltime == 0 or not (p.trickready) then setplayertrickvars(p) end
		
		if(leveltime == 2*TICRATE and as_trickreminder.value ==1)
			local pref_btn_str = (p.trick_button == BT_BRAKE) and "BRAKE" or (p.trick_button == BT_CUSTOM1) and "CUSTOM1"
			if not G_BattleGametype()
				chatprintf(p, "\131*Press \130" .. pref_btn_str .. "\131 in midair to perform a \130trick! \130 Chain multiple tricks for \131speed!", true)
			else
				chatprintf(p, "\131*Tricks are \133disabled\131 in battle mode.", true)
			end
		end 
		
		if leveltime <= starttime continue end --moved here because otherwise we can't initialize hurrr
		if G_BattleGametype() return end -- nah.
		
		-- Kill trick states if you die, dingus
		if (p.health < 1 or p.playerstate == PST_DEAD)
			if p.chargeactive or (p.trickchaintimer > 0)
				p.trickgrade = 0 -- Let's rub salt in that wound
				p.sincelasttrick = 8
			end
			p.hastricked = false 
			p.trickchaintimer = 0
			p.inchain = false
			p.trickboost = 0
			p.trickbooststr = 0
			continue --the difference between continue and break could save someone's life
		end 
		
		-- Ground checks: Tick down the timer for combo tricks, reset spin timers.
		if P_IsObjectOnGround(p.mo)
			p.spintimer = 0
			if p.trickchaintimer > 0
				p.trickchaintimer = $ - 1
				p.inchain = true
			else
				p.inchain = false
			end
		end		
		
-- Pre Trick Block in Airtime
		if(canplayertrick(p))	
			confirmtrickpress(p) 
			if(not p.hastricked)
				if(p.trick_button_trigger)
					if (p.mo.z > (p.lastz + 1)) or (p.mo.z < (p.lastz - 1) and p.mo.eflags & MFE_VERTICALFLIP)-- shoutouts to simpleflipgoop
						p.hastricked = true 
						if p.trickchaintimer > 0 --We're mid-combo
							p.inchain = true
							S_StopSoundByID(p.mo, sfx_tric)
							S_StopSoundByID(p.mo, sfx_trice) --:oh:
							S_StartSound(p.mo, sfx_trice)
							p.trickchaintimer = min($ + 18, 52)
							p.chaincount = $ + 1
						else --We need to start the combo.
							S_StartSound(p.mo, sfx_tric)
							p.inchain = true
							p.trickgrade = 1 
							p.chaincount = 1
						end	
						if(p.kartstuff[k_pogospring] == 0 and not p.spinning)
							p.spintimer = 30 --vinny.mp3
						end
					end
				else
					p.hastricked = false --I don't know if this is necessary
				end 
				
			else -- Post-press block
				--Revert if you happen to get shot down midair.
				if p.kartstuff[k_spinouttimer] > 0 
					p.trickchaintimer = 0
					p.inchain = false
				end
				
                if(p.spintimer > 0) 
                    trickspinanimate(p)
					tricksparkle(p, true)
                elseif (p.kartstuff[k_pogospring] == 0 and not p.spinning)
                    p.frameangle = p.mo.angle
                end 
            end 
        end
		

--Visuals and Sparkles --Combo
		if p.trickchaintimer > 0 or p.hastricked and not(p.spintimer) and not(p.trickboost)
			tricksparkle(p, false) 
		end 
		
--Trick Landing Block.
        if(P_IsObjectOnGround(p.mo) and p.hastricked)	
			if as_trickyield.value == 0
				p.trickboost = calctrickboostlength(p)  
				p.trickoffroad = min(p.trickboost, 6+(2*p.chaincount)) 
				p.trickboostdust = max(p.trickboost - 10, 10)
				p.kartstuff[k_speedboost] = max($, ((3+p.chaincount)*FRACUNIT)/10)
				if p.trickchaintimer > 0 and p.inchain == true --Midcombo?
					S_StartSound(p.mo, _G["sfx_acgr" .. min(p.chaincount,4)+1], p)
					S_StartSound(p.mo, sfx_s23c)
					K_TrickDustRelease(p, 3) 
					p.trickchaintimer = min($ + 18, 70) 
					p.trickgrade = min($ + 1, 4) 
					if p.chaincount > 4
						K_PlayPowerGloatSound(p.mo)
					else
						if P_RandomChance((p.chaincount*FRACUNIT)/7) then K_PlayBoostTaunt(p.mo) end 
					end
				else --Let's start a combo, then
					S_StartSound(p.mo, sfx_s23c)
					p.trickchaintimer = 70
				end

			else
				K_DoSneaker(p, 1) -- kind of funny how small this is
			end
			p.sincelasttrick = p.trickchaintimer 
			p.hastricked = false 
			p.frameangle = p.mo.angle 
			p.mo.color = p.skincolor
		end
		
		tricksneakerCheck(p) 
		applytrickboost(p) 
        p.lastz = p.mo.z --For trick 
		p.tricklastitem = p.kartstuff[k_itemtype]
		p.trickprevitemcount = p.kartstuff[k_itemamount]
		p.tricksneakerlastframe = p.kartstuff[k_sneakertimer]
		p.tricklastframebtn = (p.cmd.buttons & BT_ATTACK) and ($+1) or 0
		p.sincelasttrick = max($ - 1, 0)  
		
    end
end)



local meterx, metery, trickflags, flavoralignment, xspscr, yspscr

hud.add(function(v, p, c)

	if p.trickready == nil or p.exiting then return end --let's not get hasty here
	meterx = 190 --for real screens
	metery = 48
	trickflags = V_10TRANS
	flavoralignment = 100*0
	local splitflavorinfo = {
		[0] = "MISS...",
		[1] = "OK...",
		[2] = "NICE!",
		[3] = "RADICAL!", 
		[4] = "WILD!",
		}
	local splitcolorinfo = {
		[0] = V_GRAYMAP,
		[1] = V_ORANGEMAP,
		[2] = V_YELLOWMAP,
		[3] = V_GREENMAP, 
		[4] = V_SKYMAP,
	}
	
	--Welcome to Flavorblock
    if (p.trickchaintimer > 0) then
        --I think a fadeout would be better - Latius
		trickflags = V_10TRANS
        local fademod = 11 - min((p.sincelasttrick * 16) / max(p.trickchaintimer, 1), 9)
        trickflags = $ * fademod
	end
	
	if not(splitscreen)
		if p.sincelasttrick > 0 
			v.draw(160+flavoralignment, 40, v.cachePatch("TS" .. p.trickgrade .. "FLAV" .. flavoranimation(p)), trickflags) --my god
		end
	else
		--ss indexer by callmore
		local ssindex = nil
			for i = 0, splitscreen do
				if p == displayplayers[i] then
					ssindex = i
					break
				end
			end
		if ssindex == nil then return end --you're not visible and you need to go
		
		local sox = 0 --splitoffsetx, not clothes
		local soy = 0 --splitoffsety, not tofu
		local flavorx = 4 --flavor text in splitscreen needs to be simple text... real estate is scarce!
		local flavory = 50
		trickflags = splitcolorinfo[p.trickgrade] 
		if splitscreen == 1 --2p mode, big split
			flavorx = 6 --bothered me a little
			if ssindex == 1 --bottom
				soy = 100 --shifts to lower scr
			else --topscreen
				soy = 0 
			end

		else --3/4p
		
			flavory = 30 --because the item boxes are smaller
			if ssindex%2 == 1
				sox = 160 --shift right!
			end
			if ssindex > 1
				soy = 100
			end
			
		end
		
		if p.sincelasttrick > 0 
			v.drawString(flavorx+sox, flavory+soy, splitflavorinfo[p.trickgrade],trickflags) --a simpler time
		end

	end

end)


rawset(_G, "acrobasics", true) --Someone's gonna want it.
print("\131* Acrobasics v1, by Angular. Load successful! Please spin responsibly. *")
