﻿-- *** Example on/off light of car ***
-- Since: v0.4.1
-- Press game key "SPECIAL KEY 2" for enabled/disabled light and press PageUp (numpad) for call DebugCarLights

local gamestate = 0
local ped = 0
local car = 0
local player = 0

function DebugCarLights(car)
	WriteInLog(string.format("DebugCarLights(): car 8,9,10,11: %d %d %d %d\n", ReadProcessMemory(car + 8, 1), ReadProcessMemory(car + 9, 1), ReadProcessMemory(car + 10, 1), ReadProcessMemory(car + 11, 1) ))
end

function ToggleCarLights(car)
	-- WriteInLog(string.format("car 8,9,10,11: %d %d %d %d", ReadProcessMemory(car + 8, 1), ReadProcessMemory(car + 9, 1), ReadProcessMemory(car + 10, 1), ReadProcessMemory(car + 11, 1) ))
	-- To improve the example, a comparison of the bit values
	-- the one who works well with them will be able to improve the example
	-- you need to check the broken headlights so that they do not turn on
	-- 4 addresses are represented by 1 byte values
	-- they are responsible for the decals included on the car (lights, broken parts, open/closed doors)
	-- car struct + 0x8 0x9 0xA 0xB:
	-- 64 0 128 0 light on
	--  0 0   0 0 light off
	-- +4 0   0 0 front left light crashed
	-- +8 0   0 0 front right light crashed
	-- 12 0   0 0 front left and right light crashed	
	if (ReadProcessMemory(car + 8, 1) == 64) then -- front left light
		WriteProcessMemory(car + 8, 0, 1)
	else
		if (ReadProcessMemory(car + 8, 1) == 0) then
			WriteProcessMemory(car + 8, 64, 1)
		end
	end	
	if (ReadProcessMemory(car + 10, 1) == 128) then -- front right light
		WriteProcessMemory(car + 10, 0, 1)
	else
		if (ReadProcessMemory(car + 10, 1) == 0) then
			WriteProcessMemory(car + 10, 128, 1)
		end
	end
end

while(true) do
	wait(0)
	if (GetGameFrame() > 0) then
		if (gamestate == 0) then -- If start new game
			ped = GetPedStruct(1)
			player = GetPedPlayer(ped)
			gamestate = 1
		end
		if (ped ~= 0) then		
			car = GetPedCar(ped)
			if (car ~= 0) then -- If ped in car
				if (IsGameKeyPress(player, 0x82)) then
					ToggleCarLights(car)
				end
				if (IsGameKeyPress(player, 0x77)) then
					DebugCarLights(car)
				end
			end
		end
	else
		wait(100)
		gamestate = 0 -- If not frame to game restart or game not loaded
	end
end