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

--GAME VARS
fScaleFOV = 0

--ControlVars
bFixEnabled = true
bLetterbox = true
bFOV = true
bHUD = true
bPSN = true

--PROCESS VARS
Process_FriendlyName = Module:GetFriendlyName()
Process_WindowName = "*"
Process_ClassName = "*"
Process_EXEName = "GhostOfTsushima.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 scaling",15,70,210,17)		
	DefaultControls.AddFixedFOVSlider("FOVSlider","FOVSlider_Changed",55,100,125,35,50,200,0,1)
	FOVSlider:SetTickFrequency(10)
	FOVSlider:SetLabel1Text("0.5")
	FOVSlider:SetLabel2Text("2.0")
		
	DefaultControls.AddHeader("Header_HUD_Scaling","HUD scaling fine adjustment",15,165,210,17)
	DefaultControls.AddFixedFOVSlider("HUDScalingSlider","HUDScalingSlider_Changed",55,195,125,35,0,40,0,1)
	HUDScalingSlider:SetTickFrequency(5)
	HUDScalingSlider:SetLabel1Text("0%")
	HUDScalingSlider:SetLabel2Text("40%")
	
	DefaultControls.AddFixToggle("CKFOVFix_Enable","FOV fix","CKFOVFix_Changed",255,101,180,14)
	DefaultControls.AddFixToggle("CKHUDFix_Enable","HUD Scaling fine fix","CKHUDFix_Changed",255,121,180,14)
	DefaultControls.AddFixToggle("CKLETTERBOXFix_Enable","Letterbox fix","CKLETTERBOXFix_Changed",255,141,180,14)
	DefaultControls.AddFixToggle("CKPSNFix_Enable","PSN check fix","CKPSNFix_Changed",255,161,180,14)
	
end

function Configure_SignatureScan() 


	local tAddress = HackTool:AddAddress("FOV")
	
	if HackTool:SignatureScan("F3 0F ?? ?? ?? ?? ?? ?? C3 CC CC CC CC CC CC CC 48 63 ?? ?? ?? ?? ?? 48 6B",tAddress,PAGE_EXECUTE_READ,0x0,Process_EXEName) == 0 then
		if HackTool:SignatureScan("F3 0F 10 ?? ?? ?? ?? ?? F3 0F 11 ?? ?? ?? ?? ?? F3 0F 59 ?? C3",tAddress,PAGE_EXECUTE_READ,0x0,Process_EXEName) == 0 then	
			return ErrorOccurred(string.format(SigScanError,tAddress:GetName()))
		else	
		print( tAddress:GetInfo(TYPE_ADDRESS) )
		--GhostOfTsushima.exe+4CDE4E - CC                    	- int 3 
		--GhostOfTsushima.exe+4CDE4F - CC                    	- int 3 
		--GhostOfTsushima.exe+4CDE50 - F3 0F 10 81 C4 01 00 00  - movss xmm0,[rcx+000001C4]
		--GhostOfTsushima.exe+4CDE58 - C3                    	- ret 
		--GhostOfTsushima.exe+4CDE59 - CC                    	- int 3 
	end
	else	
		print( tAddress:GetInfo(TYPE_ADDRESS) )
	end
 
	local tAddress = HackTool:AddAddress("HUD")
	
	if HackTool:SignatureScan("F3 0F ?? ?? ?? ?? ?? ?? BE ?? ?? ?? ?? E8",tAddress,PAGE_EXECUTE_READ,0x0d,Process_EXEName) == 0 then
		return ErrorOccurred(string.format(SigScanError,tAddress:GetName()))
	else	
		print( tAddress:GetInfo(TYPE_ADDRESS) )
		--GhostOfTsushima.exe+6CF13A - F3 0F 10 35 C2 F2 A1 00  - movss xmm6,[GhostOfTsushima.D3D12SDKVersion+38D4]
		--GhostOfTsushima.exe+6CF142 - BE 80 07 00 00           - mov esi,00000780
		--GhostOfTsushima.exe+6CF147 - E8 44 A2 D3 FF           - call GhostOfTsushima.AK::MemoryMgr::StopProfileThreadUsage+C780
		--GhostOfTsushima.exe+6CF14C - 48 8B C8              	- mov rcx,rax
		--GhostOfTsushima.exe+6CF14F - 48 8B D8              	- mov rbx,rax
	end
 
	local tAddress = HackTool:AddAddress("LETTERBOX")
	
	if HackTool:SignatureScan("FF 90 ?? ?? ?? ?? 84 ?? 74 ?? 45 8B",tAddress,PAGE_EXECUTE_READ,0x0,Process_EXEName) == 0 then
		return ErrorOccurred(string.format(SigScanError,tAddress:GetName()))
	else	
		print( tAddress:GetInfo(TYPE_ADDRESS) )
		--GhostOfTsushima.exe+6D3C5E - 48 8B 07              - mov rax,[rdi]
		--GhostOfTsushima.exe+6D3C61 - 48 8B CF              - mov rcx,rdi
		--GhostOfTsushima.exe+6D3C64 - FF 90 10 02 00 00     - call qword ptr [rax+00000210]
		--GhostOfTsushima.exe+6D3C6A - 84 C0                 - test al,al
		--GhostOfTsushima.exe+6D3C6C - 74 30                 - je GhostOfTsushima.exe+6D3C9E
	end
  
	local tAddress = HackTool:AddAddress("LETTERBOX_CONTROLLER")
	
	if HackTool:SignatureScan("74 ?? 38 87 ?? ?? ?? ?? 0F 84 ?? ?? ?? ?? 80 3D",tAddress,PAGE_EXECUTE_READ,0x02,Process_EXEName) == 0 then
		return ErrorOccurred(string.format(SigScanError,tAddress:GetName()))
	else	
		print( tAddress:GetInfo(TYPE_ADDRESS) )
		--GhostOfTsushima.exe+6D34FA - 38 05 C8 31 6E 01     - cmp [GhostOfTsushima.exe+1DB66C8],al
		--GhostOfTsushima.exe+6D3500 - 74 0C                 - je GhostOfTsushima.exe+6D350E
		--GhostOfTsushima.exe+6D3502 - 38 87 5A 07 00 00     - cmp [rdi+0000075A],al
		--GhostOfTsushima.exe+6D3508 - 0F 84 49 03 00 00     - je GhostOfTsushima.exe+6D3857
		--GhostOfTsushima.exe+6D350E - 80 3D C7 AB DA 00 00  - cmp byte ptr [GhostOfTsushima.AmdPowerXpressRequestHighPerformance+3F38],00
	end

	local tAddress = HackTool:AddAddress("LETTERBOX_KEYBOARD")
	
	if HackTool:SignatureScan("74 ?? 80 BF ?? ?? ?? ?? ?? 0F 84 ?? ?? ?? ?? 80 BF",tAddress,PAGE_EXECUTE_READ,0x02,Process_EXEName) == 0 then
		return ErrorOccurred(string.format(SigScanError,tAddress:GetName()))
	else	
		print( tAddress:GetInfo(TYPE_ADDRESS) )
		--GhostOfTsushima.exe+6D350E - 80 3D C7 AB DA 00 00  - cmp byte ptr [GhostOfTsushima.AmdPowerXpressRequestHighPerformance+3F38],00
		--GhostOfTsushima.exe+6D3515 - 74 0D                 - je GhostOfTsushima.exe+6D3524
		--GhostOfTsushima.exe+6D3517 - 80 BF 5B 07 00 00 00  - cmp byte ptr [rdi+0000075B],00
		--GhostOfTsushima.exe+6D351E - 0F 84 33 03 00 00     - je GhostOfTsushima.exe+6D3857
		--GhostOfTsushima.exe+6D3524 - 80 BF 61070000 00     - cmp byte ptr [rdi+00000761],00
	end
	
	local tAddress = HackTool:AddAddress("PSN_CHECK_1")
	
	if HackTool:SignatureScan("FF ?? ?? 48 8B ?? ?? ?? ?? ?? 4C 8B ?? ?? ?? ?? ?? 4D",tAddress,PAGE_EXECUTE_READ,0x0,Process_EXEName) == 0 then
		return ErrorOccurred(string.format(SigScanError,tAddress:GetName()))
	else	
		print( tAddress:GetInfo(TYPE_ADDRESS) )
		--GhostOfTsushima.AK::MemoryMgr::StopProfileThreadUsage+C145 - 48 8B 08              - mov rcx,[rax]
		--GhostOfTsushima.AK::MemoryMgr::StopProfileThreadUsage+C148 - 48 8B 01              - mov rax,[rcx]
		--GhostOfTsushima.AK::MemoryMgr::StopProfileThreadUsage+C14B - FF 50 60              - call qword ptr [rax+60]
		--GhostOfTsushima.AK::MemoryMgr::StopProfileThreadUsage+C14E - 48 8B 0D 6B 64 58 01  - mov rcx,[GhostOfTsushima.g_pAssertHook+D658]
		--GhostOfTsushima.AK::MemoryMgr::StopProfileThreadUsage+C155 - 4C 8B 81 E0 00 00 00  - mov r8,[rcx+000000E0]
	end

	local tAddress = HackTool:AddAddress("PSN_CHECK_2")
	
	if HackTool:SignatureScan("40 ?? 48 ?? ?? ?? 80 79 ?? ?? 48 ?? ?? 75 ?? E8 ?? ?? ?? ?? 48 8D ?? ?? ?? ?? ?? B9",tAddress,PAGE_EXECUTE_READ,0x0,Process_EXEName) == 0 then
		return ErrorOccurred(string.format(SigScanError,tAddress:GetName()))
	else	
		print( tAddress:GetInfo(TYPE_ADDRESS) )
	end
	
	local tResultCount = HackTool:SignatureScanMulti("48 83 ?? ?? 48 8D ?? ?? ?? ?? ?? E8 ?? ?? ?? ?? 48 8D ?? ?? ?? ?? ?? E8 ?? ?? ?? ?? 48 8D ?? ?? ?? ?? ?? E8 ?? ?? ?? ?? 48 8D ?? ?? ?? ?? ?? E8 ?? ?? ?? ?? 48 8D ?? ?? ?? ?? ?? E8","PSN_CHECK",PAGE_EXECUTE_READ,0x3B,Process_EXEName)
	
	if tResultCount ~= 4 then	
		return ErrorOccurred("Could not find PSN_CHECK 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("PSN_CHECK_3", HackTool:GetAddress( string.format("PSN_CHECK%d",1) ))
		print( tAddress:GetInfo(TYPE_ADDRESS) )	
		--GhostOfTsushima.AK::WriteBytesCount::SetCount+536F - E8 1C 19 30 00        - call GhostOfTsushima.exe+7BEC70
		--GhostOfTsushima.AK::WriteBytesCount::SetCount+5374 - 48 8D 0D 9D 92 91 01  - lea rcx,[GhostOfTsushima.exe+1DD65F8]
		--GhostOfTsushima.AK::WriteBytesCount::SetCount+537B - E8 20 29 08 00        - call GhostOfTsushima.exe+53FC80
		--GhostOfTsushima.AK::WriteBytesCount::SetCount+5380 - 48 8D 0D 19 60 FE 02  - lea rcx,[GhostOfTsushima.exe+34A3380]
		--GhostOfTsushima.AK::WriteBytesCount::SetCount+5387 - E8 D4 EF 2D 00        - call GhostOfTsushima.exe+79C340
	end

	return true
	
end

function Enable_Inject()

	local Variables = HackTool:AllocateMemory("Variables",0)
	Variables:PushFloat("ScaleFOV")
	Variables:PushFloat("HUDAspectRatio")
	Variables:PushDouble("RDI")
	Variables:PushInt("HUDWidth")
	Variables:Allocate()
	Variables["ScaleFOV"]:WriteFloat(fScaleFOV)
	
	ResolutionChanged()	
	
	local asm = [[	

		(codecave:jmp)HUD,HUD_cc:
			movss xmm6,[(allocation)Variables->HUDAspectRatio]
			mov esi,[(allocation)Variables->HUDWidth]
			%originalcode%
			jmp %returnaddress%
			%end%
			
		(codecave:jmp)LETTERBOX,LETTERBOX_cc:
			mov [(allocation)Variables->RDI],rdi
			%originalcode%
			jmp %returnaddress%
			%end%
		
		(codecave:jmp)LETTERBOX_CONTROLLER,LETTERBOX_CONTROLLER_cc:
			call isLetterbox								; Determine if letterboxing is involved
			jne originalController							; Shortcut original test if so
			jmp %returnaddress%
		originalController:
			%originalcode%
			jmp %returnaddress%
			%end%
			
		(codecave:jmp)LETTERBOX_KEYBOARD,LETTERBOX_KEYBOARD_cc:
			call isLetterbox
			jne originalKeyboard
			jmp %returnaddress%
		originalKeyboard:
			%originalcode%
			jmp %returnaddress%
			%end%

		isLetterbox:
			push rax
			mov rax,[(allocation)Variables->RDI]
			cmp rax,rdi
			pop rax
			ret
			
		(codecave)FOV,FOV_cc:
			$$0 $$1,[(allocation)Variables->ScaleFOV]				$ctx=1
			%end%
			
		(codecave)PSN_CHECK_1,PSN_CHECK_1_cc:
			nop
			nop
			nop
			%end%
			
		(codecave)PSN_CHECK_2,PSN_CHECK_2_cc:
			nop
			nop
			%end%
			
		(codecave)PSN_CHECK_3,PSN_CHECK_3_cc:
			nop
			nop
			nop
			nop
			nop
			%end%
			
	]]

	if HackTool:CompileAssembly(asm,"Fixes") == nil then
		return ErrorOccurred("Assembly compilation failed...")
	else
		Toggle_CodeCave("FOV_cc",bFOV)
		Toggle_CodeCave("HUD_cc",bHUD)
		Toggle_CodeCave("LETTERBOX_cc",bLetterbox)
		Toggle_CodeCave("LETTERBOX_CONTROLLER_cc",bLetterbox)
		Toggle_CodeCave("LETTERBOX_KEYBOARD_cc",bLetterbox)
		Toggle_CodeCave("PSN_CHECK_1_cc",bPSN)
		Toggle_CodeCave("PSN_CHECK_2_cc",bPSN)
		Toggle_CodeCave("PSN_CHECK_3_cc",bPSN)
	end	
			
	Write_FOV()
	Write_HUD_Scaling()
	
end

function Periodic()
	
	local Variables = HackTool:GetAllocation("Variables")
	
	if Variables and Variables["HUDAspectRatio"] and Variables["HUDWidth"] then
		local fHUDScalingAspect = Variables["HUDAspectRatio"]:ReadFloat()
		local fHUDWidth = Variables["HUDWidth"]:ReadInt()
		PluginViewport:AppendStatusMessage( string.format("===== Fix informations =====\r\nHUD scaling aspect : %.2f, HUD computed width : %.0f", fHUDScalingAspect, fHUDWidth))
	end
	
end

function FOVSlider_Changed(Sender)

	fScaleFOV = Sender:GetPosition() / 100
	lblFOVSlider.Caption:SetCaption( string.format("Factor: x%.2f",fScaleFOV) )
	Write_FOV()
	ForceUpdate()
	
end

function HUDScalingSlider_Changed(Sender)

	fHUDScaling = Sender:GetPosition()
	lblHUDScalingSlider.Caption:SetCaption( string.format("Value: %.0f%%",fHUDScaling) )
	Write_HUD_Scaling()
	ForceUpdate()

end

function Write_FOV()

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

end

function Write_HUD_Scaling()

	local width = DisplayInfo:GetWidth()
	local height = DisplayInfo:GetHeight()
	local HUDLeft = width * (fHUDScaling / 100)
	local HUDRight = width * (1 - (fHUDScaling / 100))
	local HUDWidth = HUDRight - HUDLeft
	local HUDAspectRatio = HUDWidth / height
	local Variables = HackTool:GetAllocation("Variables")
	
	if Variables and Variables["HUDAspectRatio"] and Variables["HUDWidth"] then
		Variables["HUDAspectRatio"]:WriteFloat(HUDAspectRatio)
		Variables["HUDWidth"]:WriteInt(HUDWidth)
	end
	
end

function Disable_Inject()
	
	CleanUp()
	
end

function CKFOVFix_Changed(Sender)

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

function CKHUDFix_Changed(Sender)

	bHUD = Toggle_CheckFix(Sender)
	Write_HUD_Scaling()
	Toggle_CodeCave("HUD_cc",bHUD)
	ForceUpdate()

end

function CKLETTERBOXFix_Changed(Sender)

	bLetterbox = Toggle_CheckFix(Sender)
	Toggle_CodeCave("LETTERBOX_cc",bLetterbox)
	Toggle_CodeCave("LETTERBOX_CONTROLLER_cc",bLetterbox)
	Toggle_CodeCave("LETTERBOX_KEYBOARD_cc",bLetterbox)
	ForceUpdate()

end

function CKPSNFix_Changed(Sender)

	bPSN = Toggle_CheckFix(Sender)
	Toggle_CodeCave("PSN_CHECK_1_cc",bPSN)
	Toggle_CodeCave("PSN_CHECK_2_cc",bPSN)
	Toggle_CodeCave("PSN_CHECK_3_cc",bPSN)
	ForceUpdate()
	
end

function ResolutionChanged() 

	SyncDisplayDetection()
	
end

function Init()

	Init_BaseControls()
	Init_Controls()

end

function DeInit()

	DisableFix()

end
