/*
 * 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 images and portions of thereof with 2D canvas, using multiple techniques, interpolation
//    filters and effects.

#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 = {1280, 720};
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 Texture* sampleImage = NULL;

// Forward declarations.

static void outputError(char const* message);

// Implementation.

LibraryBool applicationCreate(Application_t* 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, 4, 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;
  }
  sampleImage = TextureCreateFromFile(device, "../../../../Media/ForkLift.png", PIXEL_FORMAT_RGBA8, 0);
  if (!sampleImage)
  {
    outputError("Could not load sample image from disk.");
    return false;
  }
  return true;
}

void applicationDestroy(Application_t* application, void* user)
{
  TextureDestroy(sampleImage);
  TextRendererDestroy(textRenderer);
  CanvasDestroy(canvas);
  SwapChainDestroy(swapChain);
  DeviceDestroy(device);
}

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

  displaySize = rectGetSize(clientRect);

  SwapChainResize(swapChain, &displaySize);
}

void applicationRender(Application_t* application, void* user)
{
  displayScale = ApplicationGetWindowScale(application);
  float const scale = displaySize.y / 720.0f;

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

    if (CanvasBegin(canvas))
    {
      CanvasSetContextState(canvas, CANVAS_CONTEXT_STATE_FLAT_SCENE);

      // Enable cubic interpolation for drawing image at its full size.
      CanvasSetAttributes(canvas, CANVAS_ATTRIBUTE_CUBIC);
      CanvasSetSamplerState(canvas, &(CanvasSamplerState){
        .filterMin = TEXTURE_FILTER_LINEAR, .filterMag = TEXTURE_FILTER_LINEAR,
        .addressU = TEXTURE_ADDRESS_CLAMP, .addressV = TEXTURE_ADDRESS_CLAMP});

      PointF imageSize, position;
      Quad quad;

      { // Draw image at its full size.
        TextureParameters parameters;
        TextureGetParameters(sampleImage, &parameters);

        imageSize = (PointF){parameters.width * scale, parameters.height * scale};
        position = pointRescaleF(pointSubtractF(pointF(displaySize), imageSize), 0.5f);

        quad = makeQuad(position.x, position.y, imageSize.x, imageSize.y);
        CanvasTexturedQuad(canvas, sampleImage, &quad, &quadUnity, &colorRectWhite, BLENDING_EFFECT_COPY);
      }
      CanvasSetAttributes(canvas, 0); // Disable cubic interpolation.
      { // Magnification samples.
        RectF const subRect = makeBoundsF(201.0f, 184.0f, 235.0f, 210.0f);
        float const magnification = 8.0f * scale;
        float const angle = (float)M_PI * -0.15f;
        Quad const texCoords = quadFromRectF(subRect);

        // Draw rectangle to show which portion of parrot is going to be magnified.
        CanvasFrameRect(canvas, &(RectF){position.x + (subRect.left - 1.0f) * scale,
          position.y + (subRect.top - 1.0f) * scale, (subRect.width + 2.0f) * scale,
          (subRect.height + 2.0f) * scale}, &COLOR_RECT(0xFF000000u), 2.0f * scale, BLENDING_EFFECT_COPY);

        CanvasFrameRect(canvas, &(RectF){position.x + subRect.left * scale, position.y + subRect.top * scale,
          subRect.width * scale, subRect.height * scale}, &COLOR_RECT(0xFFFFFFFFu), 2.0f * scale,
          BLENDING_EFFECT_COPY);

        // Nearest filtering...
        CanvasSetSamplerState(canvas, &(CanvasSamplerState){TEXTURE_FILTER_NEAREST, TEXTURE_FILTER_NEAREST});

        position = (PointF){displaySize.x * 0.85f, displaySize.y * 0.2f};
        quad = makeQuadRotated(position, rectGetSizeF(subRect), angle, magnification);

        CanvasTexturedQuadRegion(canvas, sampleImage, &quad, &texCoords, &colorRectWhite,
          BLENDING_EFFECT_COPY);

        // Linear filtering...
        CanvasSetSamplerState(canvas, &(CanvasSamplerState){TEXTURE_FILTER_LINEAR, TEXTURE_FILTER_LINEAR});

        position = (PointF){displaySize.x * 0.85f, displaySize.y * 0.5f};
        quad = makeQuadRotated(position, rectGetSizeF(subRect), angle, magnification);

        CanvasTexturedQuadRegion(canvas, sampleImage, &quad, &texCoords, &colorRectWhite,
          BLENDING_EFFECT_COPY);

        // Linear + cubic filtering...
        CanvasSetAttributes(canvas, CANVAS_ATTRIBUTE_CUBIC);

        position = (PointF){displaySize.x * 0.85f, displaySize.y * 0.8f};
        quad = makeQuadRotated(position, rectGetSizeF(subRect), angle, magnification);

        CanvasTexturedQuadRegion(canvas, sampleImage, &quad, &texCoords, &colorRectWhite,
          BLENDING_EFFECT_COPY);
      }
      CanvasSetAttributes(canvas, CANVAS_ATTRIBUTE_COLOR_ADJUST);
      CanvasSetSamplerState(canvas, &(CanvasSamplerState){TEXTURE_FILTER_LINEAR, TEXTURE_FILTER_LINEAR});
      { // Color manipulation samples.
        RectF const subRect = makeBoundsF(71.0f, 49.0f, 265.0f, 275.0f);
        float const magnification = 1.4f * scale;
        float const angle = (float)M_PI * 0.1f;
        Quad const texCoords = quadFromRectF(subRect);

        position = (PointF){displaySize.x * 0.15f, displaySize.y * 0.17f};
        quad = makeQuadRotated(position, rectGetSizeF(subRect), angle, magnification);

        CanvasTexturedQuadRegion(canvas, sampleImage, &quad, &texCoords, &COLOR_RECT(0xFFAF7F7Fu),
          BLENDING_EFFECT_COPY);

        position = (PointF){displaySize.x * 0.15f, displaySize.y * 0.5f};
        quad = makeQuadRotated(position, rectGetSizeF(subRect), angle, magnification);

        CanvasTexturedQuadRegion(canvas, sampleImage, &quad, &texCoords, &COLOR_RECT(0xFF7F107Fu),
          BLENDING_EFFECT_COPY);

        position = (PointF){displaySize.x * 0.15f, displaySize.y * 0.83f};
        quad = makeQuadRotated(position, rectGetSizeF(subRect), angle, magnification);

        CanvasTexturedQuadRegion(canvas, sampleImage, &quad, &texCoords, &COLOR_RECT(0xFF3F7F7Fu),
          BLENDING_EFFECT_COPY);
      }
      CanvasSetAttributes(canvas, 0);
      CanvasSetContextState(canvas, CANVAS_CONTEXT_STATE_FLAT_TEXT);
      CanvasSetSamplerState(canvas, &(CanvasSamplerState){TEXTURE_FILTER_NEAREST, TEXTURE_FILTER_NEAREST});
      {
        FontParameters parameters = {
          .family = "Segoe UI", .size = 16.0f * displayScale, .weight = FONT_WEIGHT_BOLD,
          .stretch = FONT_STRETCH_NORMAL, .slant = FONT_SLANT_NONE, .effect = fontEffectDefault};
        parameters.effect.borderType = FONT_BORDER_SEMI_HEAVY;
        parameters.effect.shadowOpacity = 1.0f;
        TextRendererSetFontParameters(textRenderer, &parameters);

        PointF offset = pointRescaleF(makePointF(-50.0f, -90.0f), scale);

        position = pointAddF(makePointF(displaySize.x * 0.93f, displaySize.y * 0.2f), offset);

        TextRendererDrawAligned(textRenderer, &position, "Nearest", &(ColorPair){0xFF325DFFu, 0xFFC5DCFFu},
          TEXT_ALIGNMENT_MIDDLE, TEXT_ALIGNMENT_MIDDLE, 1.0f, true, NULL);

        position = pointAddF(makePointF(displaySize.x * 0.93f, displaySize.y * 0.5f), offset);

        TextRendererDrawAligned(textRenderer, &position, "Linear", &(ColorPair){0xFF51F700u, 0xFFA7FFC5u},
          TEXT_ALIGNMENT_MIDDLE, TEXT_ALIGNMENT_MIDDLE, 1.0f, true, NULL);

        position = pointAddF(makePointF(displaySize.x * 0.93f, displaySize.y * 0.8f), offset);

        TextRendererDrawAligned(textRenderer, &position, "Cubic", &(ColorPair){0xFF34B9FFu, 0xFF93FFF6u},
          TEXT_ALIGNMENT_MIDDLE, TEXT_ALIGNMENT_MIDDLE, 1.0f, true, NULL);

        offset = pointRescaleF(makePointF(70.0f, -110.0f), scale);
        position = pointAddF(makePointF(displaySize.x * 0.1f, displaySize.y * 0.17f), offset);

        TextRendererDrawAligned(textRenderer, &position, "Positive hue shift",
          &(ColorPair){0xFF75C916u, 0xFF9CFADCu}, TEXT_ALIGNMENT_MIDDLE, TEXT_ALIGNMENT_MIDDLE,
          1.0f, true, NULL);

        position = pointAddF(makePointF(displaySize.x * 0.1f, displaySize.y * 0.5f), offset);

        TextRendererDrawAligned(textRenderer, &position, "Chroma reduction",
          &(ColorPair){0xFF26A1FFu, 0xFF62EAFFu}, TEXT_ALIGNMENT_MIDDLE, TEXT_ALIGNMENT_MIDDLE,
          1.0f, true, NULL);

        position = pointAddF(makePointF(displaySize.x * 0.1f, displaySize.y * 0.83f), offset);

        TextRendererDrawAligned(textRenderer, &position, "Negative hue shift",
          &(ColorPair){0xFF3318D6u, 0xFFFDC3E7u}, TEXT_ALIGNMENT_MIDDLE, TEXT_ALIGNMENT_MIDDLE,
          1.0f, true, NULL);
      }

      { // Draw technology string.
        FontParameters parameters = {
          .family = "Segoe UI", .size = 14.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), formatText,
          DeviceGetTechVersion(device) >> 8, (DeviceGetTechVersion(device) >> 4) & 0xF,
          DeviceGetTechFeatureVersion(device) >> 8, (DeviceGetTechFeatureVersion(device) >> 4) & 0xF);

        TextRendererDrawAligned(textRenderer, &(PointF){truncf(displaySize.x * 0.5f), displaySize.y -
          2.0f * scale}, text, &COLOR_PAIR(0xA0FFFFFFu), TEXT_ALIGNMENT_MIDDLE, TEXT_ALIGNMENT_END,
          1.0f, true, NULL);
      }
      CanvasEnd(canvas);
    }
    SwapChainEnd(swapChain);
  }
}

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 = "AfterwarpImageBasicsDemo";

#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;
  ApplicationSetEvents(application, &events, NULL);

  displayScale = ApplicationGetWindowScale(application);
  ApplicationSetTitle(application, "Afterwarp: ImageBasics 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;
}