/*
 * This file is part of Afterwarp Framework (http://afterwarp.io).
 * Copyright (c) 2015 - 2025 Dr. Yuriy Kotsarenko. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and limitations under the License.
 */

// This example illustrates the following features:
//  * Drawing with 2D canvas to a "drawable" texture. By drawing to another texture, which retains its
//    contents between the frames, it is possible to produce a "motion blur" looking effect.

#ifdef _WIN32
  #include "Resource.h"
  #include <SDKDDKVer.h>

  #define WIN32_LEAN_AND_MEAN
  #include <windows.h>
  // Remove conflicting Windows macros.
  #undef KEY_EXECUTE
#endif

#include <stdio.h>

#include "Afterwarp.h"
#include "Afterwarp.Vectors.h"

#define AFTERWARP_VECTORS_IMPLEMENTATION
#include "Afterwarp.Vectors.h"

// Global variables.

// Display characteristics.
static Point displaySize = {800, 600};
static float displayScale = 1.0f;

// Base Afterwarp interfaces.
static Application* application = NULL;
static Device* device = NULL;
static SwapChain* swapChain = NULL;
static Canvas* canvas = NULL;
static TextRenderer* textRenderer = NULL;
static Timer* timer = NULL;

static Texture* textureCanvasMSAA = NULL;
static Texture* textureCanvas = NULL;
static Texture* textureMotion = NULL;
static Texture* textureMotionCopy = NULL;

// Forward declarations.

static bool createTextures(void);
static void destroyTextures(void);
static void outputError(char const* message);

// Implementation.

LibraryBool applicationCreate(Application* application, void* user)
{
  device = DeviceCreate(application, DEVICE_TECHNOLOGY_UNKNOWN, 0);
  if (!device)
  {
    outputError("Could not create graphics device.");
    return false;
  }
  swapChain = SwapChainCreate(device, ApplicationGetWindowHandle(application), &displaySize,
    PIXEL_FORMAT_RGBA8, PIXEL_FORMAT_UNKNOWN, 0, false);
  if (!swapChain)
  {
    outputError("Could not create rendering swap-chain.");
    return false;
  }
#ifndef _WIN32
  {
    char const* fileNames[] = {"../../../../Media/afterwarp.ico"};

    if (!ApplicationSetIconsFromFiles(application, fileNames, sizeof(fileNames) / sizeof(fileNames[0])))
    {
      outputError("Could not load application icon.");
      return false;
    }
  }
  #endif
  canvas = CanvasCreate(device);
  if (!canvas)
  {
    outputError("Could not create rendering canvas.");
    return false;
  }
  textRenderer = TextRendererCreate(canvas, &(Point){512, 512}, PIXEL_FORMAT_LA8, false);
  if (!textRenderer)
  {
    outputError("Could not create text rendering module.");
    return false;
  }
  timer = TimerCreate();
  if (!timer)
  {
    outputError("Could not create timer module.");
    return false;
  }
  if (!createTextures())
  {
    outputError("Could not create rendering textures.");
    return false;
  }
  return true;
}

void applicationDestroy(Application* application, void* user)
{
  destroyTextures();
  TimerDestroy(timer);
  TextRendererDestroy(textRenderer);
  CanvasDestroy(canvas);
  SwapChainDestroy(swapChain);
  DeviceDestroy(device);
}

void applicationResize(Application* application, void* user)
{
  Rect clientRect = {0};
  ApplicationGetClientRect(application, &clientRect);

  displaySize = rectGetSize(clientRect);

  SwapChainResize(swapChain, &displaySize);

  destroyTextures();
  if (!createTextures())
  {
    outputError("Could not create rendering textures.");
    ApplicationTerminate(application);
  }
}

void applicationRender(Application* application, void* user)
{
  displayScale = ApplicationGetWindowScale(application);
  double const ticks = GetSystemTicks() * 60.0 / 1000000.0;

  Quad const fullQuad = makeQuad(0.0f, 0.0f, (float)displaySize.x, (float)displaySize.y);
  DeviceTechnology const technology = DeviceGetTechnology(device);

  bool const flipped = technology == DEVICE_TECHNOLOGY_OPENGL || technology == DEVICE_TECHNOLOGY_OPENGL_ES;
  Quad const texCoords = flipped ? quadFlip(quadUnity) : quadUnity;

  PointF const targetSize = pointF(displaySize);
  PointF const halfTargetSize = pointRescaleF(targetSize, 0.5f);

  if (textureCanvasMSAA)
  {
    TextureClear(textureCanvasMSAA);

    if (TextureBegin(textureCanvasMSAA, 0, 0))
    {
      if (CanvasBegin(canvas))
      {
        CanvasSetContextState(canvas, CANVAS_CONTEXT_STATE_FLAT_SCENE);

        float kappa = (float)(ticks * 0.0274);
        float const size = MIN((float)displaySize.x, (float)displaySize.y);

        CanvasTapeGrad(canvas, &halfTargetSize, &(PointF){size * 0.25f, size * 0.2f},
          &(PointF){size * 0.3f, size * 0.4f}, kappa, kappa +
          (float)(1.25 * M_PI + sin(ticks * 0.024751) * 0.5 * M_PI), 128,
          &(ColorRect){0xFFFF0000u, 0xFF00FF00u, 0xFF0000FFu, 0xFFFFFFFFu}, BLENDING_EFFECT_COPY);

        kappa = -(float)(ticks * 0.0132);

        CanvasTapeGrad(canvas, &halfTargetSize, &(PointF){size * 0.02f, size * 0.01f},
          &(PointF){size * 0.12f, size * 0.1f}, kappa, kappa +
          (float)(1.5 * M_PI + cos(ticks * 0.024751) * 0.5 * M_PI), 64,
          &(ColorRect){0xFFFF00FF, 0xFF00FFFF, 0xFFFFFF00, 0xFFFFFFFF}, BLENDING_EFFECT_COPY);

        CanvasEnd(canvas);
      }
      TextureEnd(textureCanvasMSAA);
    }
  }
  // Resolve MSAA texture.
  TextureCopy(textureCanvas, textureCanvasMSAA, 0, NULL, 0, NULL, 0, 0);

  if (textureMotion && TextureBegin(textureMotion, 0, 0))
  {
    if (CanvasBegin(canvas))
    {
      CanvasSetContextState(canvas, CANVAS_CONTEXT_STATE_FLAT_SCENE);
      CanvasSetSamplerState(canvas, &(CanvasSamplerState){TEXTURE_FILTER_LINEAR, TEXTURE_FILTER_LINEAR});

      // Copy previous scene, englarged and slightly rotated.
      CanvasSetAttributes(canvas, CANVAS_ATTRIBUTE_COLOR_ADJUST | CANVAS_ATTRIBUTE_CUBIC);

      Quad const vertices = makeQuadRotated(halfTargetSize, targetSize, -0.01f, 1.02f);

      CanvasTexturedQuad(canvas, textureMotionCopy, &vertices, &texCoords, &COLOR_RECT(0xFE80807Eu),
        BLENDING_EFFECT_COPY);

      // Add the "motion scene" on our working surface.
      CanvasSetAttributes(canvas, 0);
      CanvasTexturedQuad(canvas, textureCanvas, &fullQuad, &texCoords, &COLOR_RECT(MakeColorAlphaF(0.875f)),
        BLENDING_EFFECT_NORMAL);

      CanvasEnd(canvas);
    }
    TextureEnd(textureMotion);
  }
  TextureCopy(textureMotionCopy, textureMotion, 0, NULL, 0, NULL, 0, 0);

  if (SwapChainBegin(swapChain))
  {
    FloatColor const clearColor = floatColor(0xFFE1E2E6u);
    DeviceClear(device, DEVICE_CLEAR_LAYER_COLOR, &clearColor, 1.0f, 0);

    if (CanvasBegin(canvas))
    {
      // Blend motion texture with background.
      CanvasSetContextState(canvas, CANVAS_CONTEXT_STATE_FLAT_SCENE);
      CanvasTexturedQuad(canvas, textureMotion, &fullQuad, &texCoords, &COLOR_RECT(0xFFFFFFFFu),
        BLENDING_EFFECT_NORMAL);

      // Prepare canvas for text output.
      CanvasSetContextState(canvas, CANVAS_CONTEXT_STATE_FLAT_TEXT);
      CanvasSetSamplerState(canvas, &(CanvasSamplerState){TEXTURE_FILTER_NEAREST, TEXTURE_FILTER_NEAREST});

      { // Draw technology string.
        FontParameters parameters = {
          .family = "Segoe UI", .size = 16.0f * displayScale, .weight = FONT_WEIGHT_SEMI_BOLD,
          .stretch = FONT_STRETCH_NORMAL, .slant = FONT_SLANT_NONE, .effect = fontEffectDefault};
        parameters.effect.borderType = FONT_BORDER_SEMI_HEAVY;
        parameters.effect.borderBrightness = 1.0f;
        parameters.effect.fillBrightness = 0.0f;
        parameters.effect.shadowBrightness = 0.75f;
        parameters.effect.shadowOpacity = 1.0f;
        TextRendererSetFontParameters(textRenderer, &parameters);

        char const* const textDirect3D = "Direct3D (%d.%d), features: %d.%d";
        char const* const textOpenGL = "OpenGL (%d.%d+), features: %d.%d";

        char const* const formatText = DeviceGetTechnology(device) == DEVICE_TECHNOLOGY_DIRECT3D ?
          textDirect3D : textOpenGL;

        char text[128];

        snprintf(text, sizeof(text), "Frame Rate: %1.0f", TimerGetFrameRate(timer));

        TextRendererDrawAligned(textRenderer, &(PointF){12.0f * displayScale, 4.0f * displayScale}, text,
          &COLOR_PAIR(0xA0FFFFFFu), TEXT_ALIGNMENT_START, TEXT_ALIGNMENT_START, 1.0f, true, NULL);

        snprintf(text, sizeof(text), formatText,
          DeviceGetTechVersion(device) >> 8, (DeviceGetTechVersion(device) >> 4) & 0xF,
          DeviceGetTechFeatureVersion(device) >> 8, (DeviceGetTechFeatureVersion(device) >> 4) & 0xF);

        TextRendererDrawAligned(textRenderer, &(PointF){displaySize.x - 12.0f * displayScale,
          displaySize.y - 4.0f * displayScale}, text, &COLOR_PAIR(0xA0FFFFFFu), TEXT_ALIGNMENT_END,
          TEXT_ALIGNMENT_END, 1.0f, true, NULL);
      }
      CanvasEnd(canvas);
    }
    SwapChainEnd(swapChain);
  }
  TimerUpdate(timer);
}

LibraryBool applicationIdle(Application* application, void* user)
{
  ApplicationInvalidate(application);
  return false;
}

bool createTextures(void)
{
  TextureParameters parameters = {0};
  parameters.width = displaySize.x;
  parameters.height = displaySize.y;
  parameters.attributes = TEXTURE_ATTRIBUTE_DRAWABLE | TEXTURE_ATTRIBUTE_PREMULTIPLIED_ALPHA;
  parameters.format = PIXEL_FORMAT_RGBA16;
  parameters.multisamples = 8;

  textureCanvasMSAA = TextureCreate(device, &parameters);

  parameters.multisamples = 0;

  textureCanvas = TextureCreate(device, &parameters);
  textureMotion = TextureCreate(device, &parameters);
  textureMotionCopy = TextureCreate(device, &parameters);

  return textureCanvasMSAA && textureCanvas && textureMotion && textureMotionCopy;
}

void destroyTextures(void)
{
  TextureDestroy(textureMotionCopy);
  TextureDestroy(textureMotion);
  TextureDestroy(textureCanvas);
  TextureDestroy(textureCanvasMSAA);
}

void outputError(char const* message)
{
#ifdef _WIN32
  static char const* initErrorTitle = "Initialization Error";
  MessageBoxA(NULL, message, initErrorTitle, MB_ICONERROR | MB_OK | MB_DEFAULT_DESKTOP_ONLY);
#else
  printf("%s\n", message);
#endif
}

// Main application entry.

#ifdef _WIN32

int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prevInstance, _In_ LPWSTR cmdLine,
  _In_ int showCmd)
{
  UNREFERENCED_PARAMETER(prevInstance);
  UNREFERENCED_PARAMETER(cmdLine);
  UNREFERENCED_PARAMETER(showCmd);

  char const* windowClassName = "AfterwarpColorTunnelDemo";

#else

int main(int argc, char **argv)
{

#endif

  ApplicationConfiguration configuration = {0};
  configuration.size = displaySize;
  configuration.position = (Point){.x = INT32_MAX, .y = INT32_MAX}; // default position
#ifdef _WIN32
  configuration.startup.win.handleInstance = instance;
  configuration.startup.win.handleIconSmall = LoadIcon(instance, MAKEINTRESOURCE(IDI_AFTERWARP));
  configuration.startup.win.handleIconBig = LoadIcon(instance, MAKEINTRESOURCE(IDI_AFTERWARP));

  strncpy(configuration.startup.win.windowClassName, windowClassName,
    sizeof(configuration.startup.win.windowClassName));
#else
  configuration.startup.nx.parameterCount = argc;
  configuration.startup.nx.parameterStrings = argv;
#endif

  application = ApplicationCreate(&configuration);
  if (!application)
  {
    outputError("Could not create Application object.");
    return -1;
  }

  ApplicationEvents events = {0};
  events.eventCreate = applicationCreate;
  events.eventDestroy = applicationDestroy;
  events.eventResize = applicationResize;
  events.eventRender = applicationRender;
  events.eventIdle = applicationIdle;
  ApplicationSetEvents(application, &events, NULL);

  displayScale = ApplicationGetWindowScale(application);
  ApplicationSetTitle(application, "Afterwarp: ColorTunnel example");

  { // Retrieve client size back in case it has changed since startup.
    Rect clientRect = {0};
    ApplicationGetClientRect(application, &clientRect);
    displaySize = rectGetSize(clientRect);
  }

  bool const executed = ApplicationExecute(application);
  ApplicationDestroy(application);

  return executed ? 0 : -1;
}