require(GlobalDependencys:GetDependency("StandardBase"):GetPackageName())

--GAME VARS
fDefaultFOV = 0
fAdditionalFOV = 0
fFOV = 0
fCameraDistance = 1
fSharpness = 0

--ControlVars
bFixEnabled = true
bFOV = true
bCamera = true
bSharpness = true

--PROCESS VARS
Process_FriendlyName = Module:GetFriendlyName()
Process_WindowName = "*"
Process_ClassName = "*"
Process_EXEName = "tlou-ii.exe;tlou-ii-l.exe"

--INJECTION BEHAVIOUR
InjectDelay = 100
WriteInterval = 500
SearchInterval = 500
SuspendThread = true

--Name                         Manual/Auto/Hybrid  		Steam/Origin/Any                IncludeFile:Configure;Enable;Periodic;Disable;
SupportedVersions = { 		
{"Automatically Detect",       "Hybrid",  			"Any",	                         "Configure_SignatureScan;Enable_Inject;Periodic;Disable_Inject;"},
}

function Init_Controls()

	DefaultControls.AddHeader("Header_FixesEnableDisable","Individual Fixes",245,70,210,17)
	
	DefaultControls.AddHeader("Header_FOV","FOV fine adjustment",15,70,210,17)	
	DefaultControls.AddFixedFOVSlider("FOVSlider","FOVSlider_Changed",55,100,125,35,0,70,0,1)
	FOVSlider:SetTickFrequency(7)
	FOVSlider:SetLabel1Text("-20")
	FOVSlider:SetLabel2Text("+50")

	DefaultControls.AddHeader("Header_CAMERADISTANCE","Camera distance adjustment",15,165,210,17)	
	DefaultControls.AddFixedFOVSlider("CAMERADISSTANCESlider","CAMERADISTANCESlider_Changed",55,195,125,35,0,30,0,1)
	CAMERADISSTANCESlider:SetTickFrequency(5)
	CAMERADISSTANCESlider:SetLabel1Text("0")
	CAMERADISSTANCESlider:SetLabel2Text("3")
	
	DefaultControls.AddHeader("Header_SHARPNESS","Sharpness fine adjustment",15,260,210,17)	
	DefaultControls.AddFixedFOVSlider("SHARPNESSSlider","SHARPNESSSlider_Changed",55,290,125,35,0,30,0,1)
	SHARPNESSSlider:SetTickFrequency(5)
	SHARPNESSSlider:SetLabel1Text("0")
	SHARPNESSSlider:SetLabel2Text("3")
	
	DefaultControls.AddFixToggle("CKFOVFix_Enable","FOV fix","CKFOVFix_Changed",255,101,180,14)
	DefaultControls.AddFixToggle("CKCAMERADISTANCEFix_Enable","Camera fix","CKCAMERADISTANCEFix_Changed",255,121,180,14)
	DefaultControls.AddFixToggle("CKSHARPNESSFix_Enable","Sharpness fix","CKSHARPNESSFix_Changed",255,141,180,14)

end

function Configure_SignatureScan() 
	
	local tAddress = HackTool:AddAddress("FOV")
	
	if HackTool:SignatureScan("E8 ?? ?? ?? ?? C5 FA ?? ?? ?? ?? ?? ?? C5 F8 ?? ?? E8 ?? ?? ?? ?? C5 7A",tAddress,PAGE_EXECUTE_READ,0x0,Process_EXEName) == 0 then	
		return ErrorOccurred(string.format(SigScanError,tAddress:GetName()))
	else	
		--tlou-ii.exe+1473C35 - C5 F8 11 41 10          - vmovups [rcx+10],xmm0
		--tlou-ii.exe+1473C3A - 48 8B CA              	- mov rcx,rdx
		--tlou-ii.exe+1473C3D - E8 3E AF 21 00          - call "tlou-ii.exe"+168EB80
		--tlou-ii.exe+1473C42 - C5 FA 10 35 E6 11 6A 01 - vmovss xmm6,["tlou-ii.exe"+2B14E30]
		--tlou-ii.exe+1473C4A - C5 F8 28 CE             - vmovaps xmm1,xmm6
		print( tAddress:GetInfo(TYPE_ADDRESS) )
	end
	
	local tAddress = HackTool:AddAddress("CAMERADISTANCE")
	
	if HackTool:SignatureScan("C5 FA ?? ?? ?? ?? ?? ?? C5 FA ?? ?? ?? C5 22 ?? ?? ?? C4 C1 ?? ?? ?? C5 FA ?? ?? ?? C5 7A",tAddress,PAGE_EXECUTE_READ,0x0,Process_EXEName) == 0 then	
		return ErrorOccurred(string.format(SigScanError,tAddress:GetName()))
	else	
		--tlou-ii.exe+1ED0467 - C5 FA 11 56 0C           - vmovss [rsi+0C],xmm2
		--tlou-ii.exe+1ED046C - 48 8B 07              	 - mov rax,[rdi]
		--tlou-ii.exe+1ED046F - C5 FA 10 05 21 52 95 01  - vmovss xmm0,["tlou-ii.exe"+3825698]
		--tlou-ii.exe+1ED0477 - C5 FA 59 48 20           - vmulss xmm1,xmm0,[rax+20]
		--tlou-ii.exe+1ED047C - C5 22 59 48 24           - vmulss xmm9,xmm11,[rax+24]
		print( tAddress:GetInfo(TYPE_ADDRESS) )
	end

	local tAddress = HackTool:AddAddress("SHARPNESS")
	
	if HackTool:SignatureScan("C5 FA ?? ?? ?? ?? ?? ?? 8B 86 ?? ?? ?? ?? 89 87 ?? ?? ?? ?? 0F B6 ?? ?? ?? ?? ?? 89",tAddress,PAGE_EXECUTE_READ,0x0,Process_EXEName) == 0 then	
		return ErrorOccurred(string.format(SigScanError,tAddress:GetName()))
	else	
		--tlou-ii.exe+147163A - C5 F9 76 D1              - vpcmpeqd xmm2,xmm0,xmm1
		--tlou-ii.exe+147163E - C4 C3 51 4A C5 20        - vblendvps xmm0,xmm5,xmm13,xmm2
		--tlou-ii.exe+1471644 - C5 FA 11 87 C4 02 00 00  - vmovss [rdi+000002C4],xmm0
		--tlou-ii.exe+147164C - 8B 86 18 1B 00 00        - mov eax,[rsi+00001B18]
		--tlou-ii.exe+1471652 - 89 87 C8 02 00 00        - mov [rdi+000002C8],eax
		print( tAddress:GetInfo(TYPE_ADDRESS) )
	end

		
	return true
end


function Enable_Inject()

	local Variables = HackTool:AllocateMemory("Variables",0)
	Variables:PushFloat("FOVIn")
	Variables:PushFloat("FOVOut")
	Variables:PushFloat("AdditionalFOV")
	Variables:PushFloat("CameraDistance")
	Variables:PushFloat("Sharpness")
	Variables:Allocate()
	Variables["FOVIn"]:WriteFloat(fDefaultFOV)
	Variables["AdditionalFOV"]:WriteFloat(fAdditionalFOV)
	Variables["CameraDistance"]:WriteFloat(fCameraDistance)
	Variables["Sharpness"]:WriteFloat(fSharpness)
	
	ResolutionChanged()	
	
	local asm = [[	

		(codecave:jmp)FOV,FOV_cc:
			%originalcode%
			comiss xmm0,xmm15
			jne exit
			vmovss [(allocation)Variables->FOVIn],xmm0
			vaddss xmm0,xmm0,[(allocation)Variables->AdditionalFOV]
			vmovss [(allocation)Variables->FOVOut],xmm0
		exit:
			jmp %returnaddress%
			%end%
						
		(codecave:jmp)CAMERADISTANCE,CAMERADISTANCE_cc:
			$$0 $$1,[(allocation)Variables->CameraDistance]				$ctx=1
			jmp %returnaddress%
			%end%
			
		(codecave:jmp)SHARPNESS,SHARPNESS_cc:
			$$0 $$2,[(allocation)Variables->Sharpness]					$ctx=1
			%originalcode%
			jmp %returnaddress%
			%end%

	]]

	RemoveAVXInstructions()

	if HackTool:CompileAssembly(asm,"Fixes") == nil then
		RestoreAVXInstructions()
		return ErrorOccurred("Assembly compilation failed...")
	else
		RestoreAVXInstructions()
		Toggle_CodeCave("FOV_cc",bFOV)
		Toggle_CodeCave("CAMERADISTANCE_cc",bCamera)
		Toggle_CodeCave("SHARPNESS_cc",bSharpness)
	end	
			
	Write_FOV()
	
end

function Periodic()
	local Variables = HackTool:GetAllocation("Variables")
	
	if Variables and Variables["FOVIn"] and Variables["AdditionalFOV"] then
		fFOVIn = Variables["FOVIn"]:ReadFloat()
		fFOVOut = Variables["FOVOut"]:ReadFloat()
		if fFOVIn < 160 then
			PluginViewport:AppendStatusMessage( string.format("\r\n===== Fix informations =====\r\nFOV In: %.2f, FOV Out : %.2f", fFOVIn, fFOVOut))
		else
			PluginViewport:AppendStatusMessage( string.format("\r\n===== Fix informations =====\r\nFOV In: 0, FOV Out : 0", fFOVIn, fFOVOut))
		end
	end
end

function FOVSlider_Changed(Sender)

	fFOV = Sender:GetPosition() - 20
	if fFOV > 0 then
		lblFOVSlider.Caption:SetCaption( string.format("Additional FOV: +%.2f",fFOV) )
	else
		lblFOVSlider.Caption:SetCaption( string.format("Additional FOV: %.2f",fFOV) )	
	end
	Write_FOV()
	ForceUpdate()
	
end

function CAMERADISTANCESlider_Changed(Sender)

	fCameraDistance = (Sender:GetPosition() / 10)
	lblCAMERADISSTANCESlider.Caption:SetCaption( string.format("Camera scale: %.2f",fCameraDistance) )
	Write_CAMERADISTANCE()
	ForceUpdate()
	
end

function SHARPNESSSlider_Changed(Sender)

	fSharpness = Sender:GetPosition() / 10
	lblSHARPNESSSlider.Caption:SetCaption( string.format("Sharpness: %.2f",fSharpness) )
	Write_SHARPNESS()
	ForceUpdate()

end

function Write_FOV()

	local Variables = HackTool:GetAllocation("Variables")
	if Variables and Variables["AdditionalFOV"] then
		Variables["AdditionalFOV"]:WriteFloat(fFOV)
	end

end

function Write_CAMERADISTANCE()

	local Variables = HackTool:GetAllocation("Variables")
	if Variables and Variables["CameraDistance"] then
		Variables["CameraDistance"]:WriteFloat(fCameraDistance)
	end

end

function Write_SHARPNESS()

	local Variables = HackTool:GetAllocation("Variables")
	if Variables and Variables["Sharpness"] then
		Variables["Sharpness"]:WriteFloat(fSharpness)
	end
	
end

function Disable_Inject()
	
	CleanUp()
	
end

function CKFOVFix_Changed(Sender)

	bFOV = Toggle_CheckFix(Sender)
	Toggle_CodeCave("FOV_cc",bFOV)
	ForceUpdate()
	
end

function CKCAMERADISTANCEFix_Changed(Sender)

	bCamera = Toggle_CheckFix(Sender)
	Toggle_CodeCave("CAMERADISTANCE_cc",bCamera)
	ForceUpdate()

end

function CKSHARPNESSFix_Changed(Sender)

	bSharpness = Toggle_CheckFix(Sender)
	Toggle_CodeCave("SHARPNESS_cc",bSharpness)
	ForceUpdate()
	
end

function RemoveAVXInstructions()

	local tSuspendedThreadID = HackTool:SuspendAttachedThread() 						
	
	local tAddress = HackTool:GetAddress("SHARPNESS")
	tAddress:WriteByte(0xF3,0)
	tAddress:WriteByte(0x0F,1)

	local tAddress = HackTool:GetAddress("CAMERADISTANCE")
	tAddress:WriteByte(0xF3,0)
	tAddress:WriteByte(0x0F,1)
	
	HackTool:ResumeThread(tSuspendedThreadID)

end

function RestoreAVXInstructions()

	local tSuspendedThreadID = HackTool:SuspendAttachedThread()
	
	local tAddress = HackTool:GetAddress("SHARPNESS")
	tAddress:WriteByte(0xC5,0)
	tAddress:WriteByte(0xFA,1)
		
	local tAddress = HackTool:GetAddress("CAMERADISTANCE")
	tAddress:WriteByte(0xC5,0)
	tAddress:WriteByte(0xFA,1)
	
	HackTool:ResumeThread(tSuspendedThreadID)

end


function ResolutionChanged() 

	SyncDisplayDetection()
	
end

function Init()	
	Init_BaseControls()
	Init_Controls()
end

function DeInit()
	DisableFix()
end
