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

--GAME VARS
fDefaultFOV = 0
fDefaultAspectRatio = 1.777777791
fAdditionalFOV = 0
fAspectRatio = fDefaultAspectRatio
fFactor = 0.00872665
fHUDSafeZOneLeft = 0
fHUDSafeZoneRight = 100

--ControlVars
bFixEnabled = true
bFOV = true
bPillarBoxing = true
bAspect = true
bDOF = true
bHUDSafeZone = true

--PROCESS VARS
Process_FriendlyName = Module:GetFriendlyName()
Process_WindowName = "*"
Process_ClassName = "*"
Process_EXEName = "Stray-Win64-Shipping.exe"

--INJECTION BEHAVIOUR
InjectDelay = 500
WriteInterval = 100
SearchInterval = 100
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,80,0,1)
	
	FOVSlider:SetTickFrequency(5)
	FOVSlider:SetLabel1Text("-20")
	FOVSlider:SetLabel2Text("+60")

	DefaultControls.AddHeader("Header_HUD_SZ_LEFT","HUD safe zone left",15,190,210,17)	
	DefaultControls.AddFixedFOVSlider("HUD_SZ_LEFT","HUDSZLSlider_Changed",55,220,125,35,0,40,0,1)
	HUD_SZ_LEFT:SetTickFrequency(5)
	HUD_SZ_LEFT:SetLabel1Text("0")
	HUD_SZ_LEFT:SetLabel2Text("40")
	DefaultControls.AddHeader("Header_HUDSZRIGHT","HUD safe zone right",245,190,210,17)	
	DefaultControls.AddFixedFOVSlider("HUD_SZ_RIGHT","HUDSZRSlider_Changed",285,220,125,35,0,40,0,1)
	HUD_SZ_RIGHT:SetTickFrequency(5)
	HUD_SZ_RIGHT:SetLabel1Text("0")
	HUD_SZ_RIGHT:SetLabel2Text("40")

	DefaultControls.AddFixToggle("CKFOVFix_Enable","FOV fix","CKFOVFix_Changed",255,101,180,14)
	DefaultControls.AddFixToggle("CKARFix_Enable","Cutscenes letterbox fix","CKARFix_Changed",255,121,180,14)
	DefaultControls.AddFixToggle("CKDOFFix_Enable","Depth of field fix","CKDOFFix_Changed",255,141,180,14)
	DefaultControls.AddFixToggle("CKHUDFix_Enable","HUD safe zone fix","CKHUDFix_Changed",255,161,180,14)

end

function Configure_SignatureScan() 
	
	local tAddress = HackTool:AddAddress("FOV")
	
	if HackTool:SignatureScan("77 ?? 48 ?? ?? 48 ?? ?? ?? ?? FF 90 ?? ?? ?? ?? F3 0F ?? ?? ?? B8 ?? ?? ?? ??",tAddress,PAGE_EXECUTE_READ,0x10,Process_EXEName) == 0 then	
		return ErrorOccurred(string.format(SigScanError,tAddress:GetName()))
	else	
		print( tAddress:GetInfo(TYPE_ADDRESS) )
		--Stray-Win64-Shipping.exe+2D90AFA - 48 8D 54 24 30        - lea rdx,[rsp+30]
		--Stray-Win64-Shipping.exe+2D90AFF - FF 90 70 06 00 00     - call qword ptr [rax+00000670]
		--Stray-Win64-Shipping.exe+2D90B05 - F3 0F 10 70 18        - movss xmm6,[rax+18]
		--Stray-Win64-Shipping.exe+2D90B0A - B8 01 00 00 00        - mov eax,00000001
		--Stray-Win64-Shipping.exe+2D90B0F - A8 01                 - test al,01
	end
	
	
	--local tAddress = HackTool:AddAddress("Aspect")	
	--if HackTool:SignatureScan("C3 CC 48 89 ?? ?? ?? 57 48 83 ?? ?? F2 0F ?? ?? 48 8B ?? F2 0F ?? ?? 48 ?? ?? 8B ?? ?? 89 ?? ?? F2 0F ?? ?? ?? F2 0F ?? ?? ?? 8B",tAddress,PAGE_EXECUTE_READ,0x4e,Process_EXEName) == 0 then	
	--	return ErrorOccurred(string.format(SigScanError,tAddress:GetName()))
	--else	
	--	print( tAddress:GetInfo(TYPE_ADDRESS) )
	--end

	local tAddress = HackTool:AddAddress("Aspect2")	
	if HackTool:SignatureScan("CC CC 48 ?? ?? ?? ?? 57 48 ?? ?? ?? F2 ?? ?? ?? 48 ?? ?? F2 ?? ?? ?? 48 ?? ?? 8B ?? ?? 89 ?? ?? F2 ?? ?? ?? ?? F2 ?? ?? ?? ?? 8B ?? ?? 89 ?? ?? 8B ?? ?? 89 ?? ?? 8B ?? ?? 89 ?? ??",tAddress,PAGE_EXECUTE_READ,0x51,Process_EXEName) == 0 then	
		return ErrorOccurred(string.format(SigScanError,tAddress:GetName()))
	else	
		print( tAddress:GetInfo(TYPE_ADDRESS) )
	end

	
	-- Reference search for DOF F7 ?? ?? ?? ?? ?? ?? 74 ?? 48 8B ?? ?? ?? ?? ?? 83 78 04 00
	local tAddress = HackTool:AddAddress("DOF")
	
	if HackTool:SignatureScan("48 8B ?? ?? ?? ?? ?? 48 ?? ?? 8B ?? ?? E8 ?? ?? ?? ?? 8B",tAddress,PAGE_EXECUTE_READ,0x07,Process_EXEName) == 0 then	
		return ErrorOccurred(string.format(SigScanError,tAddress:GetName()))
	else	
		print( tAddress:GetInfo(TYPE_ADDRESS) )		
	end
	
	local tAddress = HackTool:AddAddress("HUDSAFEZONE")
	if HackTool:SignatureScan("48 ?? ?? 48 ?? ?? 66 48 ?? ?? ?? FF ?? 48 8B ?? ?? ?? 0F ?? ??",tAddress,PAGE_EXECUTE_READ,0x18,Process_EXEName) == 0 then	
		return ErrorOccurred(string.format(SigScanError,tAddress:GetName()))
	else
		print( tAddress:GetInfo(TYPE_ADDRESS) )
		--Stray-Win64-Shipping.exe+27357E1 - 0F 10 00              - movups xmm0,[rax]
		--Stray-Win64-Shipping.exe+27357E4 - 48 8B C7              - mov rax,rdi
		--Stray-Win64-Shipping.exe+27357E7 - 0F 11 07              - movups [rdi],xmm0
		--Stray-Win64-Shipping.exe+27357EA - 48 83 C4 30           - add rsp,30
		--Stray-Win64-Shipping.exe+27357EE - 5F                    - pop rdi
	end
	
	return true

end


function Enable_Inject()

	if bAspect == true then
		fAspectRatio = DisplayInfo:GetWidth() / DisplayInfo:GetHeight()
	end

	local Variables = HackTool:AllocateMemory("Variables",0)
	Variables:PushFloat("FOVIn")
	Variables:PushFloat("FOVOut")
	Variables:PushFloat("CompensatedFOV")
	Variables:PushFloat("AdditionalFOV")
	Variables:PushFloat("DefaultAspectRatio")
	Variables:PushFloat("ScreenAspect")
	Variables:PushFloat("AspectRatio")
	Variables:PushFloat("factor")
	Variables:PushFloat("HUDSafeZoneLeft")
	Variables:PushFloat("HUDSafeZoneTop")
	Variables:PushFloat("HUDSafeZoneRight")
	Variables:PushFloat("HUDSafeZoneBottom")
	
	Variables:Allocate()
	Variables["FOVIn"]:WriteFloat(fDefaultFOV)
	Variables["AdditionalFOV"]:WriteFloat(fAdditionalFOV)
	Variables["DefaultAspectRatio"]:WriteFloat(fDefaultAspectRatio)
	Variables["AspectRatio"]:WriteFloat(fAspectRatio)
	Variables["ScreenAspect"]:WriteFloat(DisplayInfo:GetWidth() / DisplayInfo:GetHeight())
	Variables["factor"]:WriteFloat(fFactor)
	Variables["HUDSafeZoneLeft"]:WriteFloat(0)
	Variables["HUDSafeZoneTop"]:WriteFloat(0)
	Variables["HUDSafeZoneRight"]:WriteFloat(1)
	Variables["HUDSafeZoneBottom"]:WriteFloat(1)
	
	ResolutionChanged()	
	local asm = [[	

		(codecave:jmp)FOV,FOV_cc:
			%originalcode%
			$$0 [(allocation)Variables->FOVIn],$$1						$ctx=1
			fld dword ptr [(allocation)Variables->FOVIn]
			fmul dword ptr [(allocation)Variables->factor]
			fptan
			fstp st0
			fld dword ptr [(allocation)Variables->AspectRatio]
			fdiv dword ptr [(allocation)Variables->DefaultAspectRatio]
			fmulp st1,st0
		    fld1
		    fpatan
			fdiv dword ptr [(allocation)Variables->factor]						; calculate compensated FOV
			fstp dword ptr [(allocation)Variables->CompensatedFOV]				; and retrieve it			
			$$0 $$1,[(allocation)Variables->CompensatedFOV]				$ctx=1					
			addss $$1,[(allocation)Variables->AdditionalFOV]			$ctx=1
			$$0 [(allocation)Variables->FOVOut],$$1						$ctx=1
			jmp %returnaddress%
			%end%
			
		(codecave:jmp)Aspect2,Aspect2_cc:
		    $$0 $$2,[(allocation)Variables->ScreenAspect]				$ctx=1
			%originalcode%
			jmp %returnaddress%
			%end%
			
		(codecave:jmp)DOF,DOF_cc:
			%originalcode%
			$$0 edi,0													$ctx=1
			jmp %returnaddress%
			%end%
			
		(codecave:jmp)HUDSAFEZONE,HUDSAFEZONE_cc:
			%originalcode%
			$$0 $$2,[(allocation)Variables->HUDSafeZoneLeft]		$ctx=1 ; Will copy all safe zone offsets
			$$0 [$$1],$$2											$ctx=1
			jmp %returnaddress%			
			%end%
			
	]]

	if HackTool:CompileAssembly(asm,"Fixes") == nil then
		return ErrorOccurred("Assembly compilation failed...")
	else
		Toggle_CodeCave("FOV_cc",bFOV)
		Toggle_CodeCave("Aspect2_cc",bAspect)
		Toggle_CodeCave("DOF_cc",bDOF)
		Toggle_CodeCave("HUDSAFEZONE_cc",bHUDSafeZone)
	end	
			
	Write_FOV()
	Write_HUD_Safe_Zone_Left()
	Write_HUD_Safe_Zone_Right()
	
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()
		fCompensatedFOV = Variables["CompensatedFOV"]:ReadFloat()
		PluginViewport:AppendStatusMessage( string.format("\r\n===== Fix informations =====\r\nFOV In: %0.2f, FOV Compensated: %0.2f, FOV Out : %.02f", fFOVIn, fCompensatedFOV, fFOVOut))
	end
end

function FOVSlider_Changed(Sender)

	fAdditionalFOV = Sender:GetPosition() - 20
	lblFOVSlider.Caption:SetCaption( string.format("Value: +%.0f",fAdditionalFOV) )
		
	if bFOV == true then
		Write_FOV()
	end
	
	ForceUpdate()

end

function Write_FOV()

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

end

function Disable_Inject()
	
	CleanUp()
	
end

function CKFOVFix_Changed(Sender)

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

function CKARFix_Changed(Sender)

	bAspect = Toggle_CheckFix(Sender)
	Toggle_CodeCave("Aspect2_cc",bAspect)
	fAspectRatio = DisplayInfo:GetWidth() / DisplayInfo:GetHeight()
	
	if bAspect == false then
		fAspectRatio = fDefaultAspectRatio
	end
	
	local Variables = HackTool:GetAllocation("Variables")
	
	if Variables and Variables["AspectRatio"] then
		Variables["AspectRatio"]:WriteFloat(fAspectRatio)
	end
	
	ForceUpdate()

end

function CKDOFFix_Changed(Sender)

	bDOF = Toggle_CheckFix(Sender)
	Toggle_CodeCave("DOF_cc",bDOF)
	ForceUpdate()
	
end

function CKHUDFix_Changed(Sender)

	bHUDSafeZone = Toggle_CheckFix(Sender)
	Toggle_CodeCave("HUDSAFEZONE_cc",bHUDSafeZone)
	ForceUpdate()

end

function HUDSZLSlider_Changed(Sender)
	
	fHUDSafeZOneLeft = Sender:GetPosition()
	lblHUD_SZ_LEFT.Caption:SetCaption( string.format("+ %.0f %%",fHUDSafeZOneLeft) )
	Write_HUD_Safe_Zone_Left()
	ForceUpdate()
	
end

function HUDSZRSlider_Changed(Sender)

	fHUDSafeZoneRight = Sender:GetPosition()
	lblHUD_SZ_RIGHT.Caption:SetCaption( string.format("+ %.0f %%",fHUDSafeZoneRight) )
	Write_HUD_Safe_Zone_Right()
	ForceUpdate()
	
end

function Write_HUD_Safe_Zone_Left()
	
	local Variables = HackTool:GetAllocation("Variables")
	
	if Variables and Variables["HUDSafeZoneLeft"] then
		Variables["HUDSafeZoneLeft"]:WriteFloat(fHUDSafeZOneLeft / 100)
	end
	
end

function Write_HUD_Safe_Zone_Right()
	
	local Variables = HackTool:GetAllocation("Variables")
	
	if Variables and Variables["HUDSafeZoneRight"] then
		Variables["HUDSafeZoneRight"]:WriteFloat(1 - (fHUDSafeZoneRight / 100))
	end
	
end

function ResolutionChanged() 

	SyncDisplayDetection()
	
end

function Init()

	Init_BaseControls()
	Init_Controls()

end

function DeInit()

	DisableFix()

end
