/*
===========================================================================
Copyright (C) 2024 Gian 'myT' Schellenbaum

This file is part of Challenge Quake 3 (CNQ3).

Challenge Quake 3 is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.

Challenge Quake 3 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Challenge Quake 3. If not, see <https://www.gnu.org/licenses/>.
===========================================================================
*/
// Cinematic Rendering Pipeline - magnifier tool for pixel peeping


#include "crp_local.h"
#include "../client/cl_imgui.h"
#include "compshaders/crp/fullscreen.h"
#include "compshaders/crp/magnifier.h"


#pragma pack(push, 4)
struct MagnifierRC
{
	uint32_t colorTextureIndex;
	uint32_t cursorIndexX;
	uint32_t cursorIndexY;
	uint32_t magnifierWidth;
	uint32_t magnifierScale;
	uint32_t edgeWidth;
	uint32_t edgeColor;
};
#pragma pack(pop)


void Magnifier::Init()
{
	GraphicsPipelineDesc desc("Magnifier");
	MakeFullScreenPipeline(desc, ShaderByteCode(g_magnifier_ps));
	desc.AddRenderTarget(0, crp.renderTargetFormat);
	pipeline = CreateGraphicsPipeline(desc);
}

void Magnifier::Draw()
{
	if(r_debugUI->integer == 0 || !magnifierActive)
	{
		return;
	}

	srp.renderMode = RenderMode::None;

	SCOPED_RENDER_PASS("Magnifier", 1.0f, 1.0f, 1.0f);

	CmdSetViewportAndScissor(0, 0, glConfig.vidWidth, glConfig.vidHeight);

	crp.SwapRenderTargets();

	CmdBeginBarrier();
	CmdTextureBarrier(crp.GetReadRenderTarget(), ResourceStates::PixelShaderAccessBit);
	CmdTextureBarrier(crp.GetWriteRenderTarget(), ResourceStates::RenderTargetBit);
	CmdEndBarrier();

	MagnifierRC rc = {};
	rc.colorTextureIndex = GetTextureIndexSRV(crp.GetReadRenderTarget());
	rc.cursorIndexX = ImGui::GetIO().MousePos.x;
	rc.cursorIndexY = ImGui::GetIO().MousePos.y;
	rc.magnifierWidth = 256;
	rc.magnifierScale = 4;
	rc.edgeWidth = 2;
	rc.edgeColor = 0xFF00FFFF;

	CmdBindRenderTargets(1, &crp.renderTarget, NULL);
	CmdBindPipeline(pipeline);
	CmdSetGraphicsRootConstants(0, sizeof(rc), &rc);
	CmdDraw(3, 0);
}

void Magnifier::DrawGUI()
{
	ToggleBooleanWithShortcut(magnifierActive, ImGuiKey_M);
	GUI_AddMainMenuItem(GUI_MainMenu::Tools, "Magnifier", "Ctrl+M", &magnifierActive);
}
