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

--GAME VARS
fDefaultFOV = 85
fAdditionalFOV = 0
fAspectRatio = DisplayInfo:GetWidth() / DisplayInfo:GetHeight()
fAspectRatio169 = 1.77775
fFactor = 0.00872665
fHUDSafeZOneLeft = 0
fHUDSafeZoneRight = 0

--ControlVars
bFixEnabled = true
bFOV = true
bAspect = true
bHUDSafeZone = true
bFPSLimit = true
bFringe = true
bDOF = true

--PROCESS VARS
Process_FriendlyName = Module:GetFriendlyName()
Process_WindowName = "*"
Process_ClassName = "UnrealWindow"
Process_EXEName = "TheBeastInside-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,60,0,1)
	FOVSlider:SetTickFrequency(5)
	FOVSlider:SetLabel1Text("-20")
	FOVSlider:SetLabel2Text("+40")
	
	DefaultControls.AddHeader("HeaderHUDSZ","HUD safe zone",15,160,210,17)	
	DefaultControls.AddFixedFOVSlider("HUD","HUDSZSlider_Changed",55,190,125,35,0,40,0,1)
	HUD:SetTickFrequency(5)
	HUD:SetLabel1Text("0")
	HUD:SetLabel2Text("40")
	
	DefaultControls.AddFixToggle("CKFOVFix_Enable","FOV fix","CKFOVFix_Changed",255,101,180,14)
	DefaultControls.AddFixToggle("CKARFix_Enable","Aspect ratio fix","CKARFix_Changed",255,121,180,14)
	DefaultControls.AddFixToggle("CKHUDFix_Enable","HUD safe zone fix","CKHUDFix_Changed",255,141,180,14)
	DefaultControls.AddFixToggle("CKFPSFix_Enable","FPS limit fix (uncapped)","CKFPSLimitFix_Changed",255,161,180,14)
	DefaultControls.AddFixToggle("CKFRINGEFix_Enable","Chromatic aberration fix","CKFRINGEFix_Changed",255,181,180,14)
	DefaultControls.AddFixToggle("CKDOFFix_Enable","Depth of field fix","CKDOFFix_Changed",255,201,180,14)
	
end

function Configure_SignatureScan() 
	
	local tResultCount = HackTool:SignatureScanMulti("F3 0F 10 ?? ?? ?? ?? ?? 0F ?? ?? 0F ?? ?? 77 ?? F3 0F 10 ?? ?? ?? ?? ?? C3","FOVS",PAGE_EXECUTE_READ,0x10,Process_EXEName)
	
	if tResultCount ~= 3 then	
		return ErrorOccurred("Could not find FOVS injection point, " .. Process_FriendlyName .. 
							 " may have updated to a version that is no longer supported.\r\n\r\n" .. 
							 "Try selecting a different version and re-enable the fix."	)
	else
	
		local tAddress = HackTool:AddAddress("FOV", HackTool:GetAddress( string.format("FOVS%d",1) ))
		print( tAddress:GetInfo(TYPE_ADDRESS) )	
		--TheBeastInside-Win64-Shipping.exe+82C0CB - 0F 2F C1               	- comiss xmm0,xmm1
		--TheBeastInside-Win64-Shipping.exe+82C0CE - 77 08                 		- ja TheBeastInside-Win64-Shipping.exe+82C0D8
		--TheBeastInside-Win64-Shipping.exe+82C0D0 - F3 0F 10 81 B8 03 00 00   	- movss xmm0,[rcx+000003B8]
		--TheBeastInside-Win64-Shipping.exe+82C0D8 - C3                    		- ret 		
	end	

	local tAddress = HackTool:AddAddress("ASPECT")
	
	if HackTool:SignatureScan("F3 0F ?? ?? ?? ?? ?? ?? F3 0F ?? ?? ?? ?? 88 87 ?? ?? ?? ?? F3 0F",tAddress,PAGE_EXECUTE_READ,0x0,Process_EXEName) == 0 then
		return ErrorOccurred(string.format(SigScanError,tAddress:GetName()))
	else	
		print( tAddress:GetInfo(TYPE_ADDRESS) )
		--TheBeastInside-Win64-Shipping.exe+827DD2 - 09 87 CC 03 00 00        	- or [rdi+000003CC],eax
		--TheBeastInside-Win64-Shipping.exe+827DD8 - 0F B6 44 24 60         	- movzx eax,byte ptr [rsp+60]
		--TheBeastInside-Win64-Shipping.exe+827DDD - F3 0F 11 87 C8 03 00 00   	- movss [rdi+000003C8],xmm0
		--TheBeastInside-Win64-Shipping.exe+827DE5 - F3 0F 10 44 24 64      	- movss xmm0,[rsp+64]
		--TheBeastInside-Win64-Shipping.exe+827DEB - 88 87 D0 03 00 00        	- mov [rdi+000003D0],al
	end
	
	local tAddress = HackTool:AddAddress("HUDSAFEZONE")
	
	if HackTool:SignatureScan("48 8B ?? ?? ?? 0F ?? ?? 48 ?? ?? 0F ?? ?? 48 83 ?? ?? 5F C3 48",tAddress,PAGE_EXECUTE_READ,0x05,Process_EXEName) == 0 then
		return ErrorOccurred(string.format(SigScanError,tAddress:GetName()))
	else	
		print( tAddress:GetInfo(TYPE_ADDRESS) )
		--TheBeastInside-Win64-Shipping.exe+11DF6EA - FF D0                 - call rax
		--TheBeastInside-Win64-Shipping.exe+11DF6EC - 48 8B 5C 24 40        - mov rbx,[rsp+40]
		--TheBeastInside-Win64-Shipping.exe+11DF6F1 - 0F 10 00              - movups xmm0,[rax]
		--TheBeastInside-Win64-Shipping.exe+11DF6F4 - 48 8B C7              - mov rax,rdi
		--TheBeastInside-Win64-Shipping.exe+11DF6F7 - 0F 11 07              - movups [rdi],xmm0
	end
	
	local tAddress = HackTool:AddAddress("FPSLIMIT")
	
	if HackTool:SignatureScan("F3 0F ?? ?? 41 0F ?? ?? 77 ?? 0F ?? ?? 0F 28",tAddress,PAGE_EXECUTE_READ,0x04,Process_EXEName) == 0 then
		return ErrorOccurred(string.format(SigScanError,tAddress:GetName()))
	else	
		print( tAddress:GetInfo(TYPE_ADDRESS) )
		--TheBeastInside-Win64-Shipping.exe+5E8A18 - EB 14                 - jmp TheBeastInside-Win64-Shipping.exe+5E8A2E
		--TheBeastInside-Win64-Shipping.exe+5E8A1A - 48 8B 05 DF C3 5F 02  - mov rax,[TheBeastInside-Win64-Shipping.exe+2BE4E00]
		--TheBeastInside-Win64-Shipping.exe+5E8A21 - F3 0F 10 00           - movss xmm0,[rax]
		--TheBeastInside-Win64-Shipping.exe+5E8A25 - 41 0F 2F C0           - comiss xmm0,xmm8
		--TheBeastInside-Win64-Shipping.exe+5E8A29 - 77 03                 - ja TheBeastInside-Win64-Shipping.exe+5E8A2E
	end
	
	local tAddress = HackTool:AddAddress("FRINGE")
	
	if HackTool:SignatureScan("7F ?? 89 B3 ?? ?? ?? ?? 8B ?? ?? 39 05",tAddress,PAGE_EXECUTE_READ,0x0,Process_EXEName) == 0 then
		return ErrorOccurred(string.format(SigScanError,tAddress:GetName()))
	else	
		print( tAddress:GetInfo(TYPE_ADDRESS) )
		--TheBeastInside-Win64-Shipping.exe+6CFEDA - 48 8B 05 1F 83 51 02  - mov rax,[TheBeastInside-Win64-Shipping.exe+2BE8200]
		--TheBeastInside-Win64-Shipping.exe+6CFEE1 - 39 30                 - cmp [rax],esi
		--TheBeastInside-Win64-Shipping.exe+6CFEE3 - 7F 06                 - jg TheBeastInside-Win64-Shipping.exe+6CFEEB
		--TheBeastInside-Win64-Shipping.exe+6CFEE5 - 89 B3 8C 0D 00 00     - mov [rbx+00000D8C],esi
		--TheBeastInside-Win64-Shipping.exe+6CFEEB - 8B 04 2F              - mov eax,[rdi+rbp]
	end
	
	local tAddress = HackTool:AddAddress("DOF")
	
	if HackTool:SignatureScan("0F 8E ?? ?? ?? ?? 80 BF ?? ?? ?? ?? ?? 0F 85 ?? ?? ?? ?? F3 0F ?? ?? ?? ?? ?? ?? F3 0F",tAddress,PAGE_EXECUTE_READ,0x0,Process_EXEName) == 0 then
		return ErrorOccurred(string.format(SigScanError,tAddress:GetName()))
	else	
		print( tAddress:GetInfo(TYPE_ADDRESS) )
		--TheBeastInside-Win64-Shipping.exe+11052C1 - 83 78 04 00           	- cmp dword ptr [rax+04],00
		--TheBeastInside-Win64-Shipping.exe+11052C5 - 48 C7 43 04 00 00 80 3F  	- mov qword ptr [rbx+04],3F800000
		--TheBeastInside-Win64-Shipping.exe+11052CD - 0F 8E DE 00 00 00         - jng TheBeastInside-Win64-Shipping.exe+11053B1
		--TheBeastInside-Win64-Shipping.exe+11052D3 - 80 BF C8 0F 00 00 02     	- cmp byte ptr [rdi+00000FC8],02
		--TheBeastInside-Win64-Shipping.exe+11052DA - 0F 85 D1 00 00 00         - jne TheBeastInside-Win64-Shipping.exe+11053B1
	end
	
	return true
end

function Enable_Inject()

	local Variables = HackTool:AllocateMemory("Variables",0)
	Variables:PushFloat("CompensatedFOV")
	Variables:PushFloat("FOVIn")
	Variables:PushFloat("FOVOut")
	Variables:PushFloat("AdditionalFOV")
	Variables:PushFloat("AspectRatio")
	Variables:PushFloat("ScreenRatio")
	Variables:PushFloat("factor")
	Variables:PushFloat("HUDSafeZoneLeft")
	Variables:PushFloat("HUDSafeZoneTop")
	Variables:PushFloat("HUDSafeZoneRight")
	Variables:PushFloat("HUDSafeZoneBottom")
	Variables:PushFloat("HUDSafeZoneDefRight")
	Variables:PushFloat("HUDSafeZoneDefBottom")
	Variables:Allocate()
	Variables["FOVIn"]:WriteFloat(fDefaultFOV)
	Variables["FOVOut"]:WriteFloat(fDefaultFOV)
	Variables["AdditionalFOV"]:WriteFloat(fAdditionalFOV)
	Variables["AspectRatio"]:WriteFloat(fAspectRatio169)
	Variables["ScreenRatio"]:WriteFloat(fAspectRatio)
	Variables["factor"]:WriteFloat(fFactor)
	Variables["HUDSafeZoneLeft"]:WriteFloat(0)
	Variables["HUDSafeZoneTop"]:WriteFloat(0)
	Variables["HUDSafeZoneRight"]:WriteFloat(1)
	Variables["HUDSafeZoneBottom"]:WriteFloat(1)
	Variables["HUDSafeZoneDefRight"]:WriteFloat(1)
	Variables["HUDSafeZoneDefBottom"]:WriteFloat(1)
	
	ResolutionChanged()	
	
	local asm = [[	

		(codecave:jmp)FOV,FOV_cc:
			%originalcode%
			movss [(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->ScreenRatio]
			fdiv dword ptr [(allocation)Variables->AspectRatio]
			fmulp st1,st0
		    fld1
		    fpatan
			fdiv dword ptr [(allocation)Variables->factor]						; calculate compensated FOV
			fstp dword ptr [(allocation)Variables->CompensatedFOV]				; and retrieve it			
			movss $$1,[(allocation)Variables->CompensatedFOV]				$ctx=1
			addss $$1,[(allocation)Variables->AdditionalFOV]				$ctx=1
			movss [(allocation)Variables->FOVOut],$$1						$ctx=1
			jmp %returnaddress%
			%end%

		(codecave:jmp)ASPECT,ASPECT_cc:
			$$0 $$2,[(allocation)Variables->ScreenRatio]					$ctx=1
			%originalcode%
			jmp %returnaddress%
			%end%
									
		(codecave:jmp)HUDSAFEZONE,HUDSAFEZONE_cc:
			movsd xmm14,[$$2+8]												$ctx=1
			ucomisd xmm14,[(allocation)Variables->HUDSafeZoneDefRight]
			jne next			
			$$0 xmm14,[(allocation)Variables->HUDSafeZoneLeft]				$ctx=1
			$$0 [$$2],xmm14													$ctx=1
			
			next:
			%originalcode%			
			jmp %returnaddress%
			%end%
			
		(codecave:jmp)FPSLIMIT,FPSLIMIT_cc:
			movss $$1,[FPSLimit]											$ctx=1
			%originalcode%			
			jmp %returnaddress%
			%end%
			
			FPSLimit: (float)0f
			
		(codecave)DOF,DOF_cc:
			jmp $$1															$ctx=1
			nop
			%end%
			
		(codecave)FRINGE,FRINGE_cc:
			nop
			nop
			%end%
			
	]]

	if HackTool:CompileAssembly(asm,"Fixes") == nil then
		return ErrorOccurred("Assembly compilation failed...")
	else
		Toggle_CodeCave("FOV_cc",bFOV)
		Toggle_CodeCave("ASPECT_cc",bAspect)
		Toggle_CodeCave("HUDSAFEZONE_cc",bHUDSafeZone)
		Toggle_CodeCave("FPSLIMIT_cc",bFPSLimit)
		Toggle_CodeCave("FRINGE_cc",bFringe)
		Toggle_CodeCave("DOF_cc",bDOF)
	end	
			
	Write_FOV()
	Write_AR()
	Write_HUD_Safe_Zone()
	
end

function Periodic()

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

function FOVSlider_Changed(Sender)

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

end

function HUDSZSlider_Changed(Sender)

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

function Write_FOV()

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

end

function Write_AR()

	local Variables = HackTool:GetAllocation("Variables")
	if Variables and Variables["AspectRatio"] then
		if bAspect == true then
			Variables["AspectRatio"]:WriteFloat(fAspectRatio169)
		else
			Variables["AspectRatio"]:WriteFloat(fAspectRatio)
		end
	end

end

function Write_HUD_Safe_Zone()

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

function Disable_Inject()
	
	CleanUp()
	
end

function CKFOVFix_Changed(Sender)

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

function CKARFix_Changed(Sender)

	bAspect = Toggle_CheckFix(Sender)
	Toggle_CodeCave("ASPECT_cc",bAspect)
	Write_AR()
	ForceUpdate()
	
end

function CKHUDFix_Changed(Sender)

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

end

function CKFPSLimitFix_Changed(Sender)

	bFPSLimit = Toggle_CheckFix(Sender)
	Toggle_CodeCave("FPSLIMIT_cc",bFPSLimit)
	ForceUpdate()

end

function CKFRINGEFix_Changed(Sender)

	bFringe = Toggle_CheckFix(Sender)
	Toggle_CodeCave("FRINGE_cc",bFringe)
	ForceUpdate()

end

function CKDOFFix_Changed(Sender)

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

end

function ResolutionChanged() 

	SyncDisplayDetection()
	
end

function Init()

	Init_BaseControls()
	Init_Controls()

end

function DeInit()

	DisableFix()

end
