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

--GAME VARS
fDefaultFOV = 80
fAdditionalFOV = 0
fAdditionalCinematicsFOV = 0
fAspectRatio = DisplayInfo:GetWidth() / DisplayInfo:GetHeight()
fGameAspect = fAspectRatio
fAspectRatio169 = 1.777778

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

--PROCESS VARS
Process_FriendlyName = Module:GetFriendlyName()
Process_WindowName = "*"
Process_ClassName = "*"
Process_EXEName = "Bloom&Rage.exe"

--INJECTION BEHAVIOUR
InjectDelay = 100
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","In game FOV fine adjustment",15,70,210,17)	
	DefaultControls.AddFixedFOVSlider("FOVSlider","FOVSlider_Changed",55,100,125,35,0,90,0,1)
	FOVSlider:SetTickFrequency(10)

	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("CKDOFFix_Enable","Depth of field fix","CKDOFFix_Changed",255,141,180,14)
	DefaultControls.AddFixToggle("CKFRINGEFix_Enable","Chromatic aberrations fix","CKFRINGEFix_Changed",255,161,180,14)

end

function Configure_SignatureScan() 
	
	local tAddress = HackTool:AddAddress("FOV")
	
	if HackTool:SignatureScan("77 ?? 48 8B ?? FF 90 ?? ?? ?? ?? F3 0F ?? ?? ??",tAddress,PAGE_EXECUTE_READ,0x0b,Process_EXEName) == 0 then	
		return ErrorOccurred(string.format(SigScanError,tAddress:GetName()))
	else	
		print( tAddress:GetInfo(TYPE_ADDRESS) )
		--Bloom&Rage.exe+4ED9CB4 - 48 8B 01              - mov rax,[rcx]
		--Bloom&Rage.exe+4ED9CB7 - FF 90 30 07 00 00     - call qword ptr [rax+00000730]
		--Bloom&Rage.exe+4ED9CBD - F3 0F 10 40 30        - movss xmm0,[rax+30]
		--Bloom&Rage.exe+4ED9CC2 - 48 83 C4 28           - add rsp,28
		--Bloom&Rage.exe+4ED9CC6 - C3                    - ret 
	end
	
	local tAddress = HackTool:AddAddress("CINEMATICSFOV")
	
	--if HackTool:SignatureScan("F3 0F ?? ?? ?? 0F ?? ?? 8B 83 ?? ?? ?? ?? 89 ?? ?? 0F B6",tAddress,PAGE_EXECUTE_READ,0x0,Process_EXEName) == 0 then	
	if HackTool:SignatureScan("F3 0F ?? ?? ?? ?? ?? ?? 0F ?? ?? F3 0F ?? ?? ?? ?? ?? ?? 0F ?? ?? 76 ?? F3 0F ?? ?? ?? ?? ?? ?? F3 0F ?? ?? EB",tAddress,PAGE_EXECUTE_READ,0x0,Process_EXEName) == 0 then	
		return ErrorOccurred(string.format(SigScanError,tAddress:GetName()))
	else	
		print( tAddress:GetInfo(TYPE_ADDRESS) )
		--Bloom&Rage.exe+495D6C4 - EB 08                 	- jmp Bloom&Rage.exe+495D6CE
		--Bloom&Rage.exe+495D6C6 - F3 0F 10 83 A8 02 00 00  - movss xmm0,[rbx+000002A8]
		--Bloom&Rage.exe+495D6CE - F3 0F 11 47 30         	- movss [rdi+30],xmm0
		--Bloom&Rage.exe+495D6D3 - 0F 57 C0               	- xorps xmm0,xmm0
		--Bloom&Rage.exe+495D6D6 - 8B 83 B8 02 00 00        - mov eax,[rbx+000002B8]
	end
	
	local tAddress = HackTool:AddAddress("ASPECT_1")
	
	--if HackTool:SignatureScan("F3 0F ?? ?? ?? ?? ?? ?? F3 0F ?? ?? 0F 54 ?? ?? ?? ?? ?? 0F 2F ?? ?? ?? ?? ?? 76 ?? 48 8D",tAddress,PAGE_EXECUTE_READ,0x0,Process_EXEName) == 0 then	
	if HackTool:SignatureScan("E9 ?? ?? ?? ?? 41 ?? ?? ?? 41 ?? ?? F3 0F ?? ?? ?? ?? ?? ?? 44 0F 29",tAddress,PAGE_EXECUTE_READ,0x0,Process_EXEName) == 0 then
		return ErrorOccurred(string.format(SigScanError,tAddress:GetName()))
	else	
		print( tAddress:GetInfo(TYPE_ADDRESS) )
		local Aspect_2 = HackTool:AddAddress("ASPECT_2", tAddress)
		Aspect_2:OffsetAddress(0x3F)
		--Bloom&Rage.exe+494BC30 - 0F 5B C9               	- cvtdq2ps xmm1,xmm1
		--Bloom&Rage.exe+494BC33 - 66 0F 6E C0            	- movd xmm0,eax
		--Bloom&Rage.exe+494BC37 - 0F 5B C0               	- cvtdq2ps xmm0,xmm0
		--Bloom&Rage.exe+494BC3A - F3 0F 5E C8            	- divss xmm1,xmm0
		--Bloom&Rage.exe+494BC3E - 0F 2F CA               	- comiss xmm1,xmm2
		--Bloom&Rage.exe+494BC41 - 72 0B                 	- jb Bloom&Rage.exe+494BC4E
		--Bloom&Rage.exe+494BC43 - 0F 28 D1               	- movaps xmm2,xmm1
		--Bloom&Rage.exe+494BC46 - F3 0F 5D 15 4A BA A7 01  - minss xmm2,[Bloom&Rage.exe+63C7698]
		--Bloom&Rage.exe+494BC4E - F3 0F 5C CA            	- subss xmm1,xmm2
		--Bloom&Rage.exe+494BC52 - 0F 54 0D 77 EA 79 01     - andps xmm1,[Bloom&Rage.exe+60EA6D0]
		--Bloom&Rage.exe+494BC59 - 0F 2F 0D C0 E9 79 01     - comiss xmm1,[Bloom&Rage.exe+60EA620]
		--Bloom&Rage.exe+494BC60 - 76 35                 	- jna Bloom&Rage.exe+494BC97
		--Bloom&Rage.exe+494BC62 - 48 8D 54 24 20        	- lea rdx,[rsp+20]
		--Bloom&Rage.exe+494BC67 - 49 8B C8              	- mov rcx,r8
		--Bloom&Rage.exe+494BC6A - E8 B1 B3 7E 00           - call Bloom&Rage.exe+5137020
	end
	
	local tResultCount = HackTool:SignatureScanMulti("F2 0F ?? ?? ?? 8B ?? ?? 89 ?? ?? 41 8B ?? ?? 89 ?? ?? 41 8B","ASPECTS",PAGE_EXECUTE_READ,0x32,Process_EXEName)
	
	if tResultCount ~= 2 then	
		return ErrorOccurred("Could not find ASPECTS 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("CINEMATICSASPECT", HackTool:GetAddress( string.format("ASPECTS%d",2) ))
		print( tAddress:GetInfo(TYPE_ADDRESS) )	
		--Bloom&Rage.exe+4CFFAB7 - 89 47 44              - mov [rdi+44],eax
		--Bloom&Rage.exe+4CFFABA - 41 8B 46 48           - mov eax,[r14+48]
		--Bloom&Rage.exe+4CFFABE - 89 47 48              - mov [rdi+48],eax
		--Bloom&Rage.exe+4CFFAC1 - 41 33 4E 4C           - xor ecx,[r14+4C]
		--Bloom&Rage.exe+4CFFAC5 - 83 E1 01              - and ecx,01
	end
	
	local tAddress = HackTool:AddAddress("DOF") -- r.DepthOfFieldQuality
	
	if HackTool:SignatureScan("8B ?? ?? 48 ?? ?? E8 ?? ?? ?? ?? 0F ?? ?? 48 6B",tAddress,PAGE_EXECUTE_READ,0x0,Process_EXEName) == 0 then
		return ErrorOccurred(string.format(SigScanError,tAddress:GetName()))
	else	
		print( tAddress:GetInfo(TYPE_ADDRESS) )
		--Bloom&Rage.exe+368A723 - 75 05                 - jne Bloom&Rage.exe+368A72A
		--Bloom&Rage.exe+368A725 - BF 04 00 00 00        - mov edi,00000004
		--Bloom&Rage.exe+368A72A - 8B 3C 37              - mov edi,[rdi+rsi]
		--Bloom&Rage.exe+368A72D - 48 8B CB              - mov rcx,rbx
		--Bloom&Rage.exe+368A730 - E8 FB 1E 93 01        - call Bloom&Rage.exe+4FBC630
	end
	
	local tAddress = HackTool:AddAddress("FRINGE") -- r.SceneColorFringeQuality
	
	if HackTool:SignatureScan("7F ?? 89 B3 ?? ?? ?? ?? 8B ?? ?? 39 05 ?? ?? ?? ?? 0F 8F",tAddress,PAGE_EXECUTE_READ,0x0,Process_EXEName) == 0 then	
		return ErrorOccurred(string.format(SigScanError,tAddress:GetName()))
	else	
		print( tAddress:GetInfo(TYPE_ADDRESS) )
		--Bloom&Rage.exe+4FB8D45 - 48 8B 05 4C 24 B8 03  - mov rax,[Bloom&Rage.exe+8B3B198]
		--Bloom&Rage.exe+4FB8D4C - 39 30                 - cmp [rax],esi
		--Bloom&Rage.exe+4FB8D4E - 7F 06                 - jg Bloom&Rage.exe+4FB8D56
		--Bloom&Rage.exe+4FB8D50 - 89 B3 EC 1D 00 00     - mov [rbx+00001DEC],esi
		--Bloom&Rage.exe+4FB8D56 - 8B 04 2F              - mov eax,[rdi+rbp]
	end
	
	return true
	
end

function Enable_Inject()
	local Variables = HackTool:AllocateMemory("Variables", 0)
	Variables:PushFloat("FOVIn")
	Variables:PushFloat("FOVOut")
	Variables:PushFloat("CINEMATICSFOVIn")
	Variables:PushFloat("CINEMATICSFOVOut")
	Variables:PushFloat("CompensatedFOV")
	Variables:PushFloat("AdditionalFOV")
	Variables:PushFloat("ScreenRatio")
	Variables:PushFloat("GameAspect")
	Variables:PushByte("ASPECTCHECKED")
	
	Variables:Allocate()
	Variables["FOVIn"]:WriteFloat(fDefaultFOV)
	Variables["FOVOut"]:WriteFloat(fDefaultFOV)
	Variables["AdditionalFOV"]:WriteFloat(fAdditionalFOV)
	Variables["ScreenRatio"]:WriteFloat(fAspectRatio)
	Variables["GameAspect"]:WriteFloat(fAspectRatio)
	
	FOVCalculator = HackTool:InjectFOVCalculator("FOVCalculator")
	
	ResolutionChanged()	

	local asm = [[		

		(codecave:jmp)FOV,FOV_cc:		
			%originalcode%
			$$0 [(allocation)Variables->FOVIn],$$1						$ctx=1
			cmp byte ptr [(allocation)Variables->ASPECTCHECKED],1
			jne normalFOV
			fld dword ptr [(allocation)Variables->FOVIn]
			call (allocation)FOVCalculator
			fstp dword ptr [(allocation)Variables->CompensatedFOV]
			$$0 $$1,[(allocation)Variables->CompensatedFOV]				$ctx=1
		normalFOV:
			addss $$1,[(allocation)Variables->AdditionalFOV]			$ctx=1
			$$0 [(allocation)Variables->FOVOut],$$1						$ctx=1			
			jmp %returnaddress%
			%end%
					
		(codecave:jmp)CINEMATICSASPECT,CINEMATICSASPECT_cc:
			cmp eax,0x3FAAAAA8
			je next
			$$0 $$2,[(allocation)Variables->ScreenRatio]				$ctx=1
			next:
			%originalcode%
			jmp %returnaddress%
			%end%			
			
		(codecave:jmp)ASPECT_1,ASPECT_1_cc:
			fld dword ptr [defaultaspect]
			fstp dword ptr [(allocation)Variables->GameAspect]			; Only injected to set general aspect ratio 1.777778
			%originalcode%			
			%end%
			
		defaultaspect: (float)1.777778
			
		(codecave:jmp)ASPECT_2,ASPECT_2_cc:
			movss $$1,[(allocation)Variables->ScreenRatio]				$ctx=1
			movss [(allocation)Variables->GameAspect],$$1				$ctx=1
			jmp %returnaddress%
			%end%
								
		(codecave)DOF,DOF_cc:
			xor $$1,$$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
		if Variables and Variables["ASPECTCHECKED"] and bAspect then
			Variables["ASPECTCHECKED"]:WriteByte(1)
		end
		Toggle_CodeCave("FOV_cc",(bFOV or bAspect))
		Toggle_CodeCave("ASPECT_1_cc",bAspect)
		Toggle_CodeCave("ASPECT_2_cc",bAspect)
		Toggle_CodeCave("CINEMATICSASPECT_cc",bAspect)
		Toggle_CodeCave("DOF_cc",bDOF)
		Toggle_CodeCave("FRINGE_cc",bFringe)
	end	
			
	Write_FOV()
	
end

function Periodic()

	local Variables = HackTool:GetAllocation("Variables")
	
	if Variables and Variables["FOVIn"] and Variables["AdditionalFOV"] then
	
		local fFOVIn = Variables["FOVIn"]:ReadFloat()
		local fFOVOut = Variables["FOVOut"]:ReadFloat()
		local fFOVCompensated = Variables["CompensatedFOV"]:ReadFloat()
		
		PluginViewport:AppendStatusMessage( string.format("\r\n===== Fix informations =====\r\nFOV In: %.2f, Compensated: %.2f, Out: %.2f", fFOVIn, fFOVCompensated, fFOVOut))
	end
	
	if Variables and Variables["GameAspect"] then
	
		local CurrentAspectRatio = DisplayInfo:GetAspectRatio()
		local gameAspect = Variables["GameAspect"]:ReadFloat()
		local AspectDevisional = CurrentAspectRatio / gameAspect
		if CurrentAspectRatio < 1.78 then
			AspectDevisional = 1.0
		end
	
		UpdateFOVCalculator("FOVCalculator",AspectDevisional,0.0)
	end
	
end

function FOVSlider_Changed(Sender)

	fAdditionalFOV = Sender:GetPosition() - 20
	lblFOVSlider.Caption:SetCaption( string.format("World FOV: %.0f",fAdditionalFOV) )
		
	Write_FOV()	
	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 CKFOVFix_Changed(Sender)

	bFOV = Toggle_CheckFix(Sender)
	local fFOV = (bFOV or bAspect)
	Write_FOV()
	Toggle_CodeCave("FOV_cc",fFOV)
	ForceUpdate()
	
end

function CKARFix_Changed(Sender)

	bAspect = Toggle_CheckFix(Sender)
	local Variables = HackTool:GetAllocation("Variables")
	Toggle_CodeCave("ASPECT_1_cc",bAspect)
	Toggle_CodeCave("ASPECT_2_cc",bAspect)
	Toggle_CodeCave("CINEMATICSASPECT_cc",bAspect)
	
	local Variables = HackTool:GetAllocation("Variables")
	if Variables and Variables["ASPECTCHECKED"] then
		if bAspect then
			Variables["ASPECTCHECKED"]:WriteByte(1)
		else
			Variables["ASPECTCHECKED"]:WriteByte(0)
		end
	end
	ForceUpdate()
	
end

function CKDOFFix_Changed(Sender)

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

function CKFRINGEFix_Changed(Sender)

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

end

function Disable_Inject()
	
	CleanUp()
	
end

function ResolutionChanged() 

	SyncDisplayDetection()
	
end

function Init()

	Init_BaseControls()
	Init_Controls()

end

function DeInit()

	DisableFix()

end
