Night rider script

Lua / Roblox script by trx

Hack for night rider on roblox

--!nonstrict
--[[
  Night Rider farm: kinematic traffic-car drive on the road spline + stunt spam.
  Run again to stop.
]]

local getgenvFn: () -> { [string]: any } = (getgenv or rawget(_G, "getgenv") or function()
	return _G
end) :: () -> { [string]: any }

local function getgenv(): { [string]: any }
	return getgenvFn()
end

local MinimUI
do
	local ok, lib = pcall(function()
		return loadstring(game:HttpGet("https://raw.githubusercontent.com/Hosvile/MinimUI/refs/heads/main/init.lua"))()
	end)
	if ok and lib then
		MinimUI = lib
	else
		warn("[NightRiderFarm] MinimUI download failed, using local copy if present")
		local localPath = "UserInterface/MinimUI.luau"
		if isfile and isfile(localPath) and readfile then
			MinimUI = loadstring(readfile(localPath))()
		end
	end
end

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService")
local Players = game:GetService("Players")

local Previous = getgenv().NightRiderFarm
if Previous then
	if type(Previous.Stop) == "function" then
		pcall(Previous.Stop)
	elseif type(Previous.Connections) == "table" then
		for i = 1, #Previous.Connections do
			local conn = Previous.Connections[i]
			if conn then
				conn:Disconnect()
			end
		end
		table.clear(Previous.Connections)
	end
end

local LocalPlayer = Players.LocalPlayer
local Generation = (Previous and Previous.Generation or 0) + 1
local Active = true

local Motorcycle = ReplicatedStorage:WaitForChild("Motorcycle")
local Road = require(Motorcycle.Shared:WaitForChild("Road"))
local TrafficNet = require(Motorcycle.Shared:WaitForChild("TrafficNet"))
local TrafficClient = require(Motorcycle.Client:WaitForChild("TrafficClient"))
local BikeClient = require(Motorcycle.Client:WaitForChild("BikeClient"))
local Chase = require(Motorcycle.Client:WaitForChild("Chase"))
local Cops = require(Motorcycle.Client:WaitForChild("Cops"))

local Config = require(Motorcycle:WaitForChild("Config"))
local GameConfig = require(ReplicatedStorage.GameShared:WaitForChild("GameConfig"))
local LaneCount = Config.Highway.Lanes
local LaneWidth = Config.Highway.LaneWidth
local MiddleLane = math.ceil(LaneCount / 2)
local StuntRemote = ReplicatedStorage:WaitForChild("GameShared")
	:WaitForChild("Remotes")
	:WaitForChild("Stunt") :: RemoteEvent

local OrigContact = Chase.contact
local OrigTouchable = Chase.touchable
local OrigTrafficHit = Chase.onTrafficHit
local OrigCopsFeature = Config.Features.Cops
local OrigCopsBust = Cops.bust
local SavedPoliceOn = LocalPlayer:GetAttribute("PoliceOn")

local FarmSettings = {
	AutoDrive = true,
	AutoFarm = true,
	PerformStunts = true,
	NoCollision = true,
	NoPoliceBust = true,
	DebugStunts = false,
}

local UiWindow = nil
local LastPoliceCancel = 0

local function ApplyNoCollision()
	if FarmSettings.NoCollision then
		Chase.contact = function()
			return nil
		end
		Chase.touchable = function()
			return {}
		end
		Chase.onTrafficHit = nil
		return
	end

	if OrigContact then
		Chase.contact = OrigContact
	end
	if OrigTouchable then
		Chase.touchable = OrigTouchable
	end
	Chase.onTrafficHit = OrigTrafficHit
end

local function ApplyNoPoliceBust()
	if FarmSettings.NoPoliceBust then
		Config.Features.Cops = false
		Cops.bust = function() end
		return
	end

	Config.Features.Cops = OrigCopsFeature
	Cops.bust = OrigCopsBust
end

local function ApplyProtections()
	ApplyNoCollision()
	ApplyNoPoliceBust()
end

local Random = Random.new()

local CloseCfg = GameConfig.CloseCall
local StuntCfg = GameConfig.Stunts
local RunIdle = GameConfig.Run and GameConfig.Run.Idle or { LaneMove = 7, LeanMin = 0.12, SteerRecent = 4 }
local MphToSpeed = 1 / GameConfig.MPH

local OutskirtsInterval = 8
local MinimumLaneInterval = 2.4
local MaximumLaneInterval = 5.2
local LaneGoalMinSep = RunIdle.LaneMove + 2
local LanePilotW = 4.25
local GapPickChance = 0.22
local DefaultLatW = 8
local DriveSpeed = 400
local RideLift = 0.95

local RoadS = 0
local TravelDir = 1
local PilotLong: PilotLongState? = nil
local PilotLat: PilotLatState? = nil
local TargetD = Road.laneD(1, MiddleLane)

local LastLanePick = 0
local LastOutskirts = os.clock()
local NextLaneAt = 0
local LastGoalLane = MiddleLane
local LastGoalD = 0
local RecentLaneHistory: { number } = {}
local TeleportDone = false
local WasAutoDriving = false
local WarnedNoBike = false

local EndlessMinX = (Config.Highway and Config.Highway.CenterX or 68) + 3
local EndlessMaxX = EndlessMinX + 88
local EndlessNormalY = (Config.Highway and Config.Highway.Top) or 21
local EndlessOutskirtsY = EndlessNormalY - 16.7
local EndlessDurationMin = 0.6
local EndlessDurationMax = 2.5
local EndlessDurationPerStud = 0.035
local EndlessMaxLean = math.rad(30)
local EndlessX = EndlessMinX
local EndlessStartX = EndlessMinX
local EndlessTargetX = EndlessMaxX
local EndlessStartTime = os.clock()
local EndlessDuration = EndlessDurationMax
local EndlessLean = 0

local Connections: { RBXScriptConnection } = {}

type PilotLongState = {
	t0: number,
	s0: number,
	v0: number,
	v1: number,
	a: number,
	dir: number,
}

type PilotLatState = {
	t0: number,
	d0: number,
	vd0: number,
	goal: number,
	w: number,
}

local function ServerNow()
	return workspace:GetServerTimeNow()
end

local function SideFromD(d)
	local side = Road.side(d)
	if side == 0 then
		side = d >= 0 and 1 or -1
	end
	return side
end

local function SampleTrafficLatW()
	return DefaultLatW
end

local function ResetPilotLat(d, vd, goal)
	TargetD = goal
	LastGoalD = goal
	PilotLat = {
		t0 = ServerNow(),
		d0 = d,
		vd0 = vd,
		goal = goal,
		w = math.min(SampleTrafficLatW(), LanePilotW),
	}
end

local function RememberLane(lane)
	table.insert(RecentLaneHistory, 1, lane)
	if #RecentLaneHistory > 6 then
		table.remove(RecentLaneHistory, 7)
	end
end

local function LaneUsedRecently(lane)
	for i = 1, #RecentLaneHistory do
		if RecentLaneHistory[i] == lane then
			return true
		end
	end
	return false
end

local function LaneBand()
	local outer = math.abs(Road.laneD(1, LaneCount)) + LaneWidth * 0.4
	local inner = math.abs(Road.laneD(1, 1)) - LaneWidth * 0.4
	if inner < 0 then
		inner = 0
	end
	if Road.endless or Road.oneWay then
		return inner, outer
	end
	return -outer, outer
end

local function ClampLaneD(d)
	local lo, hi = LaneBand()
	return math.clamp(d, lo, hi)
end

local function LeftTheLane(d)
	return math.abs(d - ClampLaneD(d)) > LaneWidth
end

local function GoalTooSimilar(goalD, currentD)
	if math.abs(goalD - LastGoalD) < LaneGoalMinSep then
		return true
	end
	if math.abs(goalD - currentD) < RunIdle.LaneMove then
		return true
	end
	return false
end

local function GoalDForLane(side, lane, currentD)
	local base = Road.laneD(side, lane)
	local jitter = Random:NextNumber(-LaneWidth * 0.2, LaneWidth * 0.2)
	local goal = base + jitter

	if GoalTooSimilar(goal, currentD) then
		local push = (goal >= currentD and 1 or -1) * LaneGoalMinSep
		goal = currentD + push
	end

	return goal
end

local function CurrentLaneIndex(d)
	return Road.laneOf(d)
end

local function FindGapD(s, myD)
	local when = ServerNow()
	local nearby = {}
	local myLane = CurrentLaneIndex(myD)

	local cars = TrafficClient.cars
	if type(TrafficClient.where) == "function" and type(cars) == "table" then
		for slot = 1, 2048 do
			local car = rawget(cars, slot)
			if type(car) == "table" and car.long and car.lat then
				local carS, _, carD = TrafficClient.where(car, when)
				if math.abs(Road.delta(carS, s)) < 55 then
					nearby[#nearby + 1] = carD
				end
			end
		end
	end

	local bestGap = 0
	local bestMid = nil

	for i = 1, #nearby do
		for j = i + 1, #nearby do
			local gap = math.abs(nearby[i] - nearby[j])
			if gap > LaneWidth * 0.75 and gap < LaneWidth * 2.8 and gap > bestGap then
				local mid = (nearby[i] + nearby[j]) * 0.5
				if CurrentLaneIndex(mid) ~= myLane or math.abs(mid - myD) > GameConfig.Run.Idle.LaneMove then
					bestGap = gap
					bestMid = mid
				end
			end
		end
	end

	return bestMid
end

local function ChooseLaneIndex(current)
	if current < 1 or current > LaneCount then
		current = MiddleLane
	end

	local choices = table.create(LaneCount - 1)
	local n = 0
	for i = 1, LaneCount do
		if i ~= current and not LaneUsedRecently(i) then
			n += 1
			choices[n] = i
		end
	end

	if n == 0 then
		for i = 1, LaneCount do
			if i ~= current then
				n += 1
				choices[n] = i
			end
		end
	end

	if n < 1 then
		return MiddleLane
	end

	local lane = choices[Random:NextInteger(1, n)]

	if math.abs(lane - current) < 2 and Random:NextNumber() < 0.55 then
		local far = Random:NextInteger(0, 1) == 0 and 1 or LaneCount
		if far ~= current then
			lane = far
		end
	end

	return lane
end

local function SetLaneGoalD(goalD, laneIndex, scheduleNext)
	goalD = ClampLaneD(goalD)
	local when = ServerNow()
	local d, vd = 0, 0
	if PilotLat then
		d, vd = TrafficNet.lat(PilotLat, when)
	end
	ResetPilotLat(d, vd, goalD)
	if laneIndex then
		LastGoalLane = laneIndex
	end
	if scheduleNext ~= false then
		LastLanePick = os.clock()
		NextLaneAt = LastLanePick + Random:NextNumber(MinimumLaneInterval, MaximumLaneInterval)
	end
end

local function SetLaneGoal(side, lane, currentD)
	local goalD = GoalDForLane(side, lane, currentD)
	RememberLane(lane)
	SetLaneGoalD(goalD, lane)
	LastGoalLane = lane
end

local function PickVariedLane(side, s, myD)
	local current = CurrentLaneIndex(myD)
	local lane = ChooseLaneIndex(current)

	if Random:NextNumber() < GapPickChance then
		local gapD = FindGapD(s, myD)
		if gapD and not GoalTooSimilar(gapD, myD) then
			SetLaneGoalD(gapD, CurrentLaneIndex(gapD))
			RememberLane(CurrentLaneIndex(gapD))
			return
		end
	end

	SetLaneGoal(side, lane, myD)
end

local function RefreshPilotLong(s, speed)
	PilotLong = {
		t0 = ServerNow(),
		s0 = Road.wrap(s),
		v0 = speed,
		v1 = speed,
		a = 0,
		dir = TravelDir,
	}
end

local function ClampForwardRoadS(candidateS)
	if not TeleportDone then
		return candidateS
	end

	local delta = Road.delta(RoadS, candidateS)
	if TravelDir < 0 and delta > 0 then
		return RoadS
	end
	if TravelDir > 0 and delta < 0 then
		return RoadS
	end

	return candidateS
end

local function LaneSideForTravel(dir)
	if Road.oneWay or Road.endless then
		return 1
	end
	return dir > 0 and 1 or -1
end

local function PickTravelAndLane(s, chassis)
	local when = ServerNow()
	local votes = { [-1] = 0, [1] = 0 }
	local laneSum = { [-1] = 0, [1] = 0 }
	local laneCount = { [-1] = 0, [1] = 0 }
	local cars = TrafficClient.cars

	if type(cars) == "table" then
		for slot = 1, 2048 do
			local car = rawget(cars, slot)
			if type(car) == "table" and type(car.dir) == "number" then
				local carS, _, carD = TrafficClient.where(car, when)
				if math.abs(Road.delta(carS, s)) < 600 then
					votes[car.dir] += 1
					laneSum[car.dir] += carD
					laneCount[car.dir] += 1
				end
			end
		end
	end

	local dir = 1
	if votes[-1] > votes[1] then
		dir = -1
	elseif votes[1] == 0 and votes[-1] == 0 and (Road.oneWay or Road.endless) then
		dir = 1
	elseif votes[1] == 0 and votes[-1] == 0 then
		dir = SideFromD(select(2, Road.project(chassis.Position))) > 0 and 1 or -1
	end

	local laneD = Road.laneD(LaneSideForTravel(dir), MiddleLane)
	if laneCount[dir] > 0 then
		laneD = laneSum[dir] / laneCount[dir]
	end
	laneD = ClampLaneD(laneD)

	local _, forward = Road.frame(s)
	local bestCarDot = -2
	for slot = 1, 2048 do
		local car = rawget(cars, slot)
		if type(car) == "table" and type(car.dir) == "number" and car.entry and car.entry.root then
			local carS = TrafficClient.where(car, when)
			if math.abs(Road.delta(carS, s)) < 220 then
				local carAlong = forward * car.dir
				if carAlong.Magnitude > 0.01 then
					local dot = car.entry.root.CFrame.LookVector:Dot(carAlong.Unit)
					if dot > bestCarDot then
						bestCarDot = dot
						dir = car.dir
						if laneCount[dir] > 0 then
							laneD = ClampLaneD(laneSum[dir] / laneCount[dir])
						end
					end
				end
			end
		end
	end

	return dir, laneD
end

local function RoadSurfaceAt(s, d)
	local center, _, right = Road.frame(s)
	return center + right * d
end

local StreamingTuned = false

local function SnapToLane(chassis)
	local s = Road.wrap(RoadS)
	local midD = ClampLaneD(Road.laneD(LaneSideForTravel(TravelDir), MiddleLane))

	CalibrateRideLift(chassis, s, midD)
	RefreshPilotLong(s, DriveSpeed)
	ResetPilotLat(midD, 0, midD)

	local cf, vel = CarKinematic(PilotLong, TravelDir, PilotLat)
	chassis.CFrame = cf
	chassis.AssemblyLinearVelocity = vel
	chassis.AssemblyAngularVelocity = Vector3.zero
	SyncPilotInputs(0, true)
	LastGoalLane = MiddleLane
end

local function KeepWorldLive()
	pcall(function()
		if LocalPlayer.GameplayPaused then
			LocalPlayer.GameplayPaused = false
		end
	end)
	if sethiddenproperty then
		pcall(sethiddenproperty, LocalPlayer, "GameplayPaused", false)
	end
	if StreamingTuned then
		return
	end
	StreamingTuned = true
	pcall(function()
		if workspace.StreamingEnabled then
			workspace.StreamingMinRadius = 2048
			workspace.StreamingTargetRadius = 4096
		end
	end)
end

local function CalibrateRideLift(chassis, s, d)
	local surfaceY = RoadSurfaceAt(s, d).Y
	local measured = chassis.Position.Y - surfaceY
	if measured > 0.25 and measured < 8 then
		RideLift = math.clamp(measured + 0.15, 0.65, 2.35)
	end
end

local function CarKinematic(long: PilotLongState?, dir: number, lat: PilotLatState?)
	if not long or not lat then
		return CFrame.identity, Vector3.zero, 0, 0, 0, 0, Vector3.zAxis, Vector3.zAxis
	end

	local when = ServerNow()
	local s, speed = TrafficNet.long(long, when)
	local d, dSpeed = TrafficNet.lat(lat, when)
	d = ClampLaneD(d)

	local center, forward, right = Road.frame(s)
	local at = center + right * d + Vector3.yAxis * RideLift
	local along = forward * dir
	local heading = (along + Vector3.yAxis * (Road.grade(s) * dir)).Unit
	local cf = CFrame.lookAt(at, at + heading)
	local vel = along * speed + right * dSpeed

	return cf, vel, s, d, dSpeed, speed, heading, forward
end

local function SyncPilotInputs(steer, throttle, lean)
	steer = type(steer) == "number" and steer or 0
	lean = type(lean) == "number" and lean or steer

	BikeClient.touchSteer(steer, steer)
	BikeClient.touchInput("throttle", throttle == true)
	BikeClient.touchInput("brake", false)
	BikeClient.touchInput("rear", false)

	local ctx = BikeClient.current()
	if not ctx or not ctx.input then
		return
	end

	ctx.input.steer = steer
	ctx.input.lean = lean
	if type(ctx.input.throttle) ~= "number" then
		ctx.input.throttle = 0
	end
	if type(ctx.input.brake) ~= "number" then
		ctx.input.brake = 0
	end
	if type(ctx.input.rear) ~= "number" then
		ctx.input.rear = 0
	end
end

local function ReleaseFarmDrive(ctx, chassis)
	-- touchSteer(0, 0) still locks virtual stick steer at 0 and blocks keyboard/mouse.
	BikeClient.touchSteer()
	BikeClient.touchInput("throttle", false)
	BikeClient.touchInput("brake", false)
	BikeClient.touchInput("rear", false)

	if ctx and ctx.input then
		if type(ctx.input.throttle) == "number" then
			ctx.input.throttle = 0
		end
	end

	if ctx and ctx.state then
		ctx.state.neutral = false
	end

	if chassis then
		chassis.AssemblyLinearVelocity = Vector3.zero
		chassis.AssemblyAngularVelocity = Vector3.zero
	end
end

local function ApplyRunSpeed(ctx, speed)
	if not ctx or not ctx.state then
		return
	end

	local state = ctx.state
	local tripSpeed = TravelDir * speed
	local chassis = ctx.bike and ctx.bike.chassis

	if chassis then
		local roadS = Road.project(chassis.Position)
		local _, forward = Road.frame(roadS)
		local along = chassis.AssemblyLinearVelocity:Dot(forward) * TravelDir
		if math.abs(along) >= speed * 0.35 then
			tripSpeed = along
		end
	end

	state.speed = tripSpeed
	state.neutral = false
end

local function EndlessDriveStep(chassis, clockNow)
	local pos = chassis.Position

	if clockNow - LastOutskirts >= OutskirtsInterval then
		EndlessTargetX = Random:NextInteger(0, 1) == 0 and EndlessMinX or EndlessMaxX
		chassis.CFrame = CFrame.new(EndlessTargetX, EndlessOutskirtsY, pos.Z)
		EndlessX = EndlessTargetX
		EndlessStartX = EndlessTargetX
		LastOutskirts = clockNow
		EndlessStartTime = clockNow
	else
		local alpha = math.clamp((clockNow - EndlessStartTime) / EndlessDuration, 0, 1)
		local eased = if alpha < 0.5
			then 4 * alpha ^ 3
			else 1 - ((-2 * alpha + 2) ^ 3) / 2

		EndlessX = EndlessStartX + (EndlessTargetX - EndlessStartX) * eased

		if alpha >= 1 then
			EndlessStartX = EndlessTargetX
			EndlessTargetX = Random:NextNumber(EndlessMinX, EndlessMaxX)
			EndlessStartTime = clockNow
			local distance = math.abs(EndlessTargetX - EndlessStartX)
			EndlessDuration = math.clamp(
				distance * EndlessDurationPerStud,
				EndlessDurationMin,
				EndlessDurationMax
			)
		end

		local leanDir = math.sign(EndlessTargetX - EndlessX)
		local leanTarget = -leanDir * EndlessMaxLean
		EndlessLean += (leanTarget - EndlessLean) * 0.12

		chassis.CFrame = CFrame.new(EndlessX, EndlessNormalY, pos.Z) * CFrame.Angles(0, 0, EndlessLean)
	end

	chassis.AssemblyLinearVelocity = Vector3.new(0, 0, -DriveSpeed)
	chassis.AssemblyAngularVelocity = Vector3.zero
end

local function SyncMotionState(ctx, dir, speed, vel, forward, steer)
	if not ctx or not ctx.state then
		return
	end

	local state = ctx.state
	local fwdSpeed = vel:Dot(forward) * dir
	if math.abs(fwdSpeed) < math.abs(speed) * 0.85 then
		fwdSpeed = dir * speed
	end

	local leanCmd = math.clamp(steer, -1, 1)
	if math.abs(leanCmd) < RunIdle.LeanMin then
		leanCmd = RunIdle.LeanMin * (leanCmd >= 0 and 1 or -1)
	end

	state.speed = fwdSpeed
	state.lean = leanCmd * 0.38
	state.leanCmd = leanCmd * 0.52
	state.leanRate = leanCmd * 0.18
	state.riderX = leanCmd * 0.08
	state.neutral = false
	state.preV = vel

	if ctx.input then
		ctx.input.steer = steer
		ctx.input.lean = leanCmd
	end
end

local function ShieldPolice()
	if not FarmSettings.NoPoliceBust then
		return
	end

	pcall(function()
		LocalPlayer:SetAttribute("PoliceOn", false)
		if LocalPlayer:GetAttribute("EarnPaused") == true then
			LocalPlayer:SetAttribute("EarnPaused", nil)
		end
	end)

	local pursuitActive = LocalPlayer:GetAttribute("PursuitActive") == true
	local pursuitPhase = LocalPlayer:GetAttribute("PursuitPhase")
	local copKneel = LocalPlayer:GetAttribute("CopKneel")

	if pursuitActive or copKneel or pursuitPhase == "chase" or pursuitPhase == "busted" then
		local clockNow = os.clock()
		if clockNow - LastPoliceCancel > 0.25 then
			LastPoliceCancel = clockNow
			pcall(Cops.cancel, "farm")
		end
	end

	local ctx = BikeClient.current()
	if ctx and ctx.forced then
		ctx.forced = nil
	end
end

local function ShieldBike()
	ShieldPolice()

	local ctx = BikeClient.current()
	if not ctx then
		return
	end

	if ctx.state then
		ctx.state.crash = nil
		ctx.state.pickup = nil
		ctx.state.knockFlat = nil
		ctx.state.knockN = nil
		ctx.state.neutral = false
	end

	ctx.knockV = nil
	ctx.downFor = 0
	ctx.wedgedFor = 0
end

local function TeleportToHighway(chassis)
	KeepWorldLive()
	local s, d = Road.project(chassis.Position)
	local midD = ClampLaneD(Road.laneD(LaneSideForTravel(TravelDir), MiddleLane))

	if Road.endless then
		TravelDir = 1
		EndlessX = math.clamp(chassis.Position.X, EndlessMinX, EndlessMaxX)
		EndlessStartX = EndlessX
		EndlessTargetX = Random:NextNumber(EndlessMinX, EndlessMaxX)
		EndlessStartTime = os.clock()
		EndlessDuration = EndlessDurationMax
		chassis.AssemblyLinearVelocity = Vector3.new(0, 0, -DriveSpeed)
		SyncPilotInputs(0, true)
		TeleportDone = true
		return
	end

	if not TeleportDone then
		TravelDir, midD = PickTravelAndLane(s, chassis)
	end

	s = ClampForwardRoadS(s)
	TargetD = midD
	local speed = DriveSpeed

	CalibrateRideLift(chassis, s, midD)

	RoadS = s
	RefreshPilotLong(RoadS, speed)
	ResetPilotLat(midD, 0, midD)
	LastLanePick = os.clock()
	NextLaneAt = LastLanePick + Random:NextNumber(MinimumLaneInterval, MaximumLaneInterval)

	local _, vel, _, d = CarKinematic(PilotLong, TravelDir, PilotLat)
	chassis.AssemblyLinearVelocity = vel
	chassis.AssemblyAngularVelocity = Vector3.zero
	SyncPilotInputs(0, true)
	TeleportDone = true
	LastGoalLane = CurrentLaneIndex(d)
end

local function CarStep(dt)
	if not Active or getgenv().NightRiderFarm and getgenv().NightRiderFarm.Generation ~= Generation then
		return
	end

	if not FarmSettings.AutoDrive then
		if WasAutoDriving then
			WasAutoDriving = false
			local offCtx = BikeClient.current()
			local offChassis = offCtx and offCtx.bike and offCtx.bike.chassis
			ReleaseFarmDrive(offCtx, offChassis)
		end
		return
	end

	WasAutoDriving = true

	KeepWorldLive()
	ApplyNoCollision()
	ShieldPolice()
	ShieldBike()

	local ctx = BikeClient.current()
	local chassis = ctx and ctx.bike and ctx.bike.chassis
	if not chassis then
		TeleportDone = false
		if not WarnedNoBike then
			WarnedNoBike = true
			warn("[NightRiderFarm] Mount a bike, then run this script.")
		end
		return
	end

	WarnedNoBike = false

	if not TeleportDone then
		TeleportToHighway(chassis)
		return
	end

	KeepWorldLive()

	dt = math.clamp(dt, 1 / 240, 0.05)
	local speed = DriveSpeed
	local clockNow = os.clock()

	if Road.endless then
		EndlessDriveStep(chassis, clockNow)
		SyncPilotInputs(0, true, EndlessLean / EndlessMaxLean * RunIdle.LeanMin)
		return
	end

	local roadS = Road.project(chassis.Position)
	RoadS = Road.wrap(roadS + TravelDir * speed * dt)
	RefreshPilotLong(RoadS, speed)

	local _, roadD = Road.project(chassis.Position)
	local side = LaneSideForTravel(TravelDir)

	local when = ServerNow()
	local latD = TargetD
	local latDSpeed = 0
	if PilotLat then
		latD, latDSpeed = TrafficNet.lat(PilotLat, when)
	end

	if LeftTheLane(latD) then
		warn("[NightRiderFarm] left the lane at d", string.format("%.1f", latD), "- snapping to mid lane")
		SnapToLane(chassis)
		return
	end

	if clockNow >= NextLaneAt then
		PickVariedLane(side, RoadS, latD)
	end

	if clockNow - LastOutskirts >= OutskirtsInterval then
		LastOutskirts = clockNow
		local current = CurrentLaneIndex(latD)
		local edge = Random:NextInteger(0, 1) == 0 and 1 or LaneCount
		if edge == current then
			edge = edge == 1 and LaneCount or 1
		end
		SetLaneGoal(side, edge, latD)
	end

	local _, vel, _, d, dSpeed, longSpeed, _, forward = CarKinematic(PilotLong, TravelDir, PilotLat)
	chassis.AssemblyLinearVelocity = vel
	chassis.AssemblyAngularVelocity = Vector3.zero

	local laneErr = TargetD - d
	local steerRaw = math.clamp(laneErr / (LaneWidth * 0.85), -1, 1)
	local steerWobble = math.sin(clockNow * 1.85) * RunIdle.LeanMin * 1.15
	local laneBusy = math.abs(laneErr) > 2 or math.abs(dSpeed) > 0.75
	local steer = math.clamp((laneBusy and steerRaw or steerRaw * 0.5) + steerWobble, -1, 1)
	local lean = steer
	if math.abs(lean) < RunIdle.LeanMin then
		lean = RunIdle.LeanMin * (lean >= 0 and 1 or -1)
	end

	SyncPilotInputs(steer, true, lean)
	SyncMotionState(ctx, TravelDir, longSpeed, vel, forward, steer)
end

local function FarmAlive()
	return Active and (not getgenv().NightRiderFarm or getgenv().NightRiderFarm.Generation == Generation)
end

local function Stop()
	Active = false

	if UiWindow then
		pcall(function()
			UiWindow:Destroy()
		end)
		UiWindow = nil
	end

	if Connections then
		for i = 1, #Connections do
			local conn = Connections[i]
			if conn then
				conn:Disconnect()
			end
		end
		table.clear(Connections)
	end

	BikeClient.touchSteer()
	BikeClient.touchInput("throttle", false)
	BikeClient.touchInput("brake", false)

	Config.Features.Cops = OrigCopsFeature
	Cops.bust = OrigCopsBust

	pcall(function()
		if SavedPoliceOn == true then
			LocalPlayer:SetAttribute("PoliceOn", true)
		end
	end)

	if OrigContact then
		Chase.contact = OrigContact
	end
	if OrigTouchable then
		Chase.touchable = OrigTouchable
	end
	Chase.onTrafficHit = OrigTrafficHit
end

getgenv().NightRiderFarm = {
	Generation = Generation,
	Stop = Stop,
	Connections = Connections,
	DriveSpeed = DriveSpeed,
	Settings = FarmSettings,
	IsActive = function()
		return Active
	end,
}

local function Connect(signal: RBXScriptSignal, fn: (...any) -> ())
	local conn = signal:Connect(fn)
	Connections[#Connections + 1] = conn
	return conn
end

Connect(RunService.PreSimulation, CarStep)
Connect(RunService.PostSimulation, function()
	if not Active or not TeleportDone or not FarmSettings.AutoDrive then
		return
	end
	local ctx = BikeClient.current()
	if ctx then
		ApplyRunSpeed(ctx, DriveSpeed)
	end
end)
Connect(RunService.Heartbeat, function()
	KeepWorldLive()
	ShieldBike()
end)

Connect(LocalPlayer.CharacterAdded, function()
	TeleportDone = false
	RideLift = 1.05
	PilotLat = nil
	PilotLong = nil
	LastLanePick = 0
	LastOutskirts = os.clock()
	NextLaneAt = 0
	LastGoalLane = MiddleLane
	LastGoalD = 0
	table.clear(RecentLaneHistory)
	WarnedNoBike = false
end)

local RunStartSpeed = (GameConfig.Run and GameConfig.Run.StartMph or 60) * MphToSpeed

local SplitPairDelay = 0.5
local StuntPhase = "boot"
local StuntCycles = 0
local StuntSweepSent = 0
local StuntSweepCount = 0
local StuntClosecalls = 0
local StuntTricks = 0
local StuntSkips = 0
local LastTrickFire = 0
local LastStuntBlock = ""

local function PrepareStuntClient(): boolean
	local ctx = BikeClient.current()
	if not ctx or not ctx.state then
		LastStuntBlock = if not ctx then "no-ctx" else "no-state"
		return false
	end

	LastStuntBlock = ""

	ctx.state.neutral = false
	ctx.state.crash = nil
	ctx.state.pickup = nil

	local minSpeed = math.max(RunStartSpeed, CloseCfg.MinMph * MphToSpeed)
	if FarmSettings.AutoDrive and math.abs(ctx.state.speed or 0) < minSpeed then
		ctx.state.speed = TravelDir * DriveSpeed
	end

	if type(ctx.lean) == "number" and math.abs(ctx.lean) < RunIdle.LeanMin then
		ctx.lean = RunIdle.LeanMin * (ctx.lean >= 0 and 1 or -1)
	end

	return true
end

local function FireClosecallId(trafficId: number?)
	if not trafficId or not FarmAlive() then
		StuntSkips += 1
		return
	end

	if not PrepareStuntClient() then
		StuntSkips += 1
		return
	end

	StuntRemote:FireServer("closecall", trafficId, true, "split")
	StuntClosecalls += 1
end

local TrickList = { "stand", "kneeL", "kneeR", "spread", "flamingo", "sideL", "sideR", "layback" }

local function FireTrick(trickId: string, duration: number)
	local ctx = BikeClient.current()
	if ctx then
		ctx.trick = trickId
	end

	StuntRemote:FireServer("trick", duration, trickId, true)
end

local function FireTrickBatch()
	if not PrepareStuntClient() then
		StuntSkips += 1
		StuntPhase = "trick-skip"
		return
	end

	local ctx = BikeClient.current()
	if ctx and ctx.state then
		ctx.state.wheelie = StuntCfg.WheelieMin
	end

	local wheelieDur = Random:NextNumber(StuntCfg.WheelieMin, math.min(8, StuntCfg.MaxSeconds))
	StuntRemote:FireServer("wheelie", wheelieDur)

	for i = 1, #TrickList do
		FireTrick(TrickList[i], Random:NextNumber(StuntCfg.TrickMin, math.min(5, StuntCfg.MaxSeconds)))
	end

	StuntTricks += 1
	LastTrickFire = os.clock()
	StuntPhase = "tricks"
end

local function CollectTrafficIds(): { number }
	local ids = {}
	local folder = workspace:FindFirstChild("MotorcycleTrafficLocal")
	if not folder then
		return ids
	end
	local children = folder:GetChildren()
	for index = 1, #children do
		local trafficId = children[index]:GetAttribute("TrafficId")
		if type(trafficId) == "number" then
			ids[#ids + 1] = trafficId
		end
	end
	return ids
end

local function FireSplitPass(ids: { number })
	for index = 1, #ids do
		if not FarmAlive() then
			return
		end

		FireClosecallId(ids[index])
		StuntSweepSent = index
	end
end

local StuntThread = task.spawn(function()
	print("[NightRiderFarm] stunt loop start gen", Generation)
	StuntPhase = "pace"

	while FarmAlive() do
		if not FarmSettings.AutoFarm then
			StuntPhase = "farm-off"
			task.wait(0.25)
			continue
		end

		StuntCycles += 1

		if not PrepareStuntClient() then
			StuntSkips += 1
			StuntPhase = "no-bike"
			task.wait(0.2)
			continue
		end

		local ids = CollectTrafficIds()
		local count = #ids
		StuntSweepCount = count
		StuntSweepSent = 0

		StuntPhase = "split-1"
		FireSplitPass(ids)

		if count > 0 and FarmAlive() then
			StuntPhase = "split-wait"
			task.wait(SplitPairDelay)
			if FarmAlive() then
				StuntPhase = "split-2"
				StuntSweepSent = 0
				FireSplitPass(ids)
			end
		end

		if FarmSettings.PerformStunts then
			StuntPhase = "tricks"
			FireTrickBatch()
		else
			StuntPhase = "splits-only"
		end

		if StuntPhase ~= "trick-skip" then
			StuntPhase = if count == 0 then "idle" else "pace"
		end
		if count == 0 then
			task.wait(0.35)
		else
			task.wait(0.05)
		end
	end

	StuntPhase = "stopped"
	print("[NightRiderFarm] stunt loop exit gen", Generation)
end)

task.spawn(function()
	while FarmAlive() do
		task.wait(2)
		if not FarmAlive() then
			break
		end
		if not FarmSettings.DebugStunts then
			continue
		end

		local status = coroutine.status(StuntThread)
		local alive = status ~= "dead"
		local trickAgo = if LastTrickFire > 0 then string.format("%.1fs", os.clock() - LastTrickFire) else "never"
		local block = if LastStuntBlock ~= "" then LastStuntBlock else "-"

		print(string.format(
			"[NightRiderFarm] stunt loop %s phase=%s cycles=%d sweep=%d/%d closecalls=%d tricks=%d skips=%d lastTrick=%s block=%s",
			if alive then "alive" else "DEAD",
			StuntPhase,
			StuntCycles,
			StuntSweepSent,
			StuntSweepCount,
			StuntClosecalls,
			StuntTricks,
			StuntSkips,
			trickAgo,
			block
		))

		if not alive then
			warn("[NightRiderFarm] stunt loop died while the farm is still on. Last phase:", StuntPhase)
			break
		end
	end
end)

local function BuildUi()
	if not MinimUI or not MinimUI.Window then
		warn("[NightRiderFarm] MinimUI unavailable")
		return
	end

	UiWindow = MinimUI:Window({
		Title = "Night Rider Farm",
		File = "night_rider_farm",
	})
	if not UiWindow then
		return
	end

	UiWindow:Toggle({
		Text = "Auto drive",
		Flag = "auto_drive",
		Default = FarmSettings.AutoDrive,
		Callback = function(value)
			FarmSettings.AutoDrive = value == true
			if value ~= true then
				WasAutoDriving = false
				local ctx = BikeClient.current()
				local chassis = ctx and ctx.bike and ctx.bike.chassis
				ReleaseFarmDrive(ctx, chassis)
			end
		end,
	})

	UiWindow:Toggle({
		Text = "Auto farm (splits)",
		Flag = "auto_farm",
		Default = FarmSettings.AutoFarm,
		Callback = function(value)
			FarmSettings.AutoFarm = value == true
		end,
	})

	UiWindow:Toggle({
		Text = "Perform stunts",
		Flag = "perform_stunts",
		Default = FarmSettings.PerformStunts,
		Callback = function(value)
			FarmSettings.PerformStunts = value == true
		end,
	})

	UiWindow:Toggle({
		Text = "No collision",
		Flag = "no_collision",
		Default = FarmSettings.NoCollision,
		Callback = function(value)
			FarmSettings.NoCollision = value == true
			ApplyNoCollision()
		end,
	})

	UiWindow:Toggle({
		Text = "No police bust",
		Flag = "no_police",
		Default = FarmSettings.NoPoliceBust,
		Callback = function(value)
			FarmSettings.NoPoliceBust = value == true
			ApplyNoPoliceBust()
		end,
	})

	UiWindow:Toggle({
		Text = "Stunt debug log",
		Flag = "stunt_debug",
		Default = FarmSettings.DebugStunts,
		Callback = function(value)
			FarmSettings.DebugStunts = value == true
		end,
	})

	UiWindow:Slider({
		Text = "Drive speed",
		Flag = "drive_speed",
		Min = 120,
		Max = 500,
		Default = DriveSpeed,
		Step = 5,
		Callback = function(value)
			DriveSpeed = value
			getgenv().NightRiderFarm.DriveSpeed = value
		end,
	})

	UiWindow:Slider({
		Text = "Split delay",
		Flag = "split_delay",
		Min = 0.1,
		Max = 1.5,
		Default = SplitPairDelay,
		Step = 0.05,
		Callback = function(value)
			SplitPairDelay = value
		end,
	})

	UiWindow:Button({
		Text = "Stop farm",
		Callback = function()
			Stop()
		end,
	})

	ApplyProtections()
end

ApplyProtections()
task.defer(BuildUi)

print("[NightRiderFarm] ON gen", Generation, "- MinimUI open, run again to stop")