/*
 * This file is part of Afterwarp Framework (http://afterwarp.io).
 * Copyright (c) 2015 - 2025 Dr. Yuriy Kotsarenko. All rights reserved.
 *
 * This example source code is 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:
//  * Accurate Order-Independent Transparency (OIT) with Frosted Glass effect.
//  * Color dithering to reduce quantization errors when converting from 64-bits per pixel to 32-bit and
//    remove visible banding effects.
//  * Object layers, which define what objects are currently visible. This enables quick switching between
//    different views and/or floors.
//  * Optional orthographic projection, where all objects appear in their original sizes.
//  * Third-person view camera with location-based zoom (zooms in or out where the mouse is pointing at).

namespace Architecture
{
  using System.Numerics;
  using System.Windows.Forms;
  using Afterwarp;
  using TextRenderer = Afterwarp.TextRenderer;
  using Application = System.Windows.Forms.Application;

  public partial class MainForm : Form
  {
    private Device device;
    private SwapChain swapChain;
    private Canvas canvas;
    private TextRenderer textRenderer;

    private SceneMeshes meshes;
    private ObjectModels objects;
    private SceneLights lights;
    private ObjectMaterials materials;

    private TextureCabinet textureCabinet;
    private ColorDithering colorDithering;

    private Scene sceneDepthNormals;
    private Scene sceneModeling;

    private ActorCamera camera;
    private ObjectModelView viewport;
    private Matrix4x4 projection;

    private Vector2 displaySize;
    private Vector2 mousePos;
    private ulong layers = 1;
    private float cameraZoom = 400.0f;
    private bool orthographic = false;

    private static readonly VertexElement[] vertexElements = [
      new VertexElement("vertexPosition", ElementFormat.Float, 3),
      new VertexElement("vertexNormal", ElementFormat.Float, 3),
      new VertexElement("vertexColor", ElementFormat.UnsignedByte, 4, VertexElement.ChannelNormalized)
    ];

    private static readonly Vector3 lightPosition = new(300.0f, 800.0f, -300.0f);

    public MainForm()
    {
      InitializeComponent();
    }

    private void MainForm_Load(object sender, EventArgs e)
    {
      displaySize = new Vector2(ClientSize.Width, ClientSize.Height);
      try
      {
        device = new Device(DeviceTechnology.Direct3D);
        swapChain = new SwapChain(device, Handle);
        canvas = new Canvas(device);
        textRenderer = new TextRenderer(canvas, new Point(512, 512));

        meshes = new SceneMeshes(device);
        objects = new ObjectModels(meshes);
        lights = new SceneLights(device);
        materials = new ObjectMaterials();

        textureCabinet = new TextureCabinet(device, new Point(displaySize), TextureFidelity.High, 8);
        { // Configure Ambient Occlusion parameters.
          AmbientOcclusionParameters parameters = textureCabinet.AmbientOcclusionParameters;
          parameters.Radius = 32.0f;
          parameters.KernelBias = 0.05f;
          parameters.Strength = 1.0f;
          textureCabinet.AmbientOcclusionParameters = parameters;
        }

        sceneDepthNormals = Scene.CreateDepthNormals(device);
        sceneDepthNormals.SetVertexElements(0, vertexElements);

        sceneModeling = Scene.CreateModeling(device);
        sceneModeling.SetVertexElements(0, vertexElements);

        colorDithering = new ColorDithering(device);
        viewport = objects.CreateView();

        camera = new ActorCamera(position: new Vector3(0.0f, 0.0f, 0.0f),
          rotation: new Vector3(MathF.PI * 0.25f, MathF.PI * -0.25f, 0.0f), distance: 400.0f)
        {
          Constraints = new CameraConstraints(
            positionMin: new Vector4(-300.0f, -150.0f, -300.0f, 200.0f),
            positionMax: new Vector4(300.0f, 150.0f, 300.0f, 1500.0f),
            rotationMin: new Vector4(MathF.PI * 0.01f, 0.0f, 0.0f, 0.0f),
            rotationMax: new Vector4(MathF.PI * 0.49f, 0.0f, 0.0f, 0.0f))
        };

        CreateAndLoadMeshes(meshes);
        CreateLightsAndMaterials(lights, materials);
        CreateObjects();

        MouseWheel += new MouseEventHandler(MainForm_MouseWheel);
      }
      catch (Exception ex)
      {
        MessageBox.Show(ex.Message, "Initialization failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
        Application.Exit();
      }
    }

    private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
    {
      camera?.Dispose();
      objects?.Dispose();
      meshes?.Dispose();
      materials?.Dispose();
      colorDithering?.Dispose();

      sceneModeling?.Dispose();
      sceneDepthNormals?.Dispose();
      textureCabinet?.Dispose();
      lights?.Dispose();

      textRenderer?.Dispose();
      canvas?.Dispose();
      swapChain?.Dispose();
      device?.Dispose();
    }

    private void MainForm_Resize(object sender, EventArgs e)
    {
      if (WindowState != FormWindowState.Minimized && device is not null)
      {
        displaySize = new Vector2(ClientSize.Width, ClientSize.Height);
        swapChain.Resize(new Point(displaySize));
        textureCabinet.Size = new Point(displaySize);
        Invalidate();
      }
    }

    private void MainForm_Paint(object sender, PaintEventArgs e)
    {
      float scale = DeviceDpi / 96.0f;

      Matrix4x4 view = camera.View;

      if (orthographic)
        projection = Utility.MatrixOrthographic4x4(cameraZoom, cameraZoom * displaySize.Y / displaySize.X,
          10.0f, 1800.0f);
      else
        projection = Utility.MatrixPerspective4x4(MathF.PI * 0.25f, displaySize.X / displaySize.Y,
          10.0f, 1800.0f);

      viewport.View = view;
      viewport.Projection = projection;
      viewport.Layers = layers;
      viewport.Update();

      { // Update texture cabinet's attributes.
        uint attributes = 0
          | TextureCabinet.Attribute.Bloom
          | TextureCabinet.Attribute.BloomCubic
          | TextureCabinet.Attribute.AmbientOcclusion
          | TextureCabinet.Attribute.Glassy
          | TextureCabinet.Attribute.GlassyFrosted;

        if (scale >= 2.0f)
          attributes |= TextureCabinet.Attribute.BloomDownscale |
            TextureCabinet.Attribute.AmbientOcclusionDownscale;

        textureCabinet.Attributes = attributes;
      }

      // Perform light assignment for 3D scene.
      lights.Size = new Point(displaySize);

      // Only one light is used for the entire scene, so only minimal light culling is required.
      lights.CullingMode = ClustersCullingMode.Performance;
      lights.ClusterSize = 512;
      lights.DepthSlices = 1;

      lights.Execute(view, projection);

      // Prepare scene's attributes.
      uint sceneAttributes = 0
    // Note: "normals" attribute is not enabled because objects have flat normals anyway.
    //  | Scene.Attribute.Normals
        | Scene.Attribute.Coloring
        | Scene.Attribute.DepthPrePass;

      // Render depth pre-pass.
      textureCabinet.Clear(TextureCabinetPass.Depth);
      textureCabinet.Begin(TextureCabinetPass.Depth);
      try
      {
        sceneDepthNormals.Attributes = sceneAttributes;
        sceneDepthNormals.View = view;
        sceneDepthNormals.Projection = projection;

        sceneDepthNormals.Begin();
        try
        {
          RenderObjects(sceneDepthNormals, viewport);
        }
        finally
        {
          sceneDepthNormals.End();
        }
      }
      finally
      {
        textureCabinet.End();
      }
      textureCabinet.Filter(TextureCabinetFilterType.Occlusion, projection);

      // Render main scene.
      textureCabinet.Clear(TextureCabinetPass.Color, new FloatColor(0xFF303030u));
      textureCabinet.Begin(TextureCabinetPass.Color);
      try
      {
        sceneModeling.Lights = lights;
        sceneModeling.TextureCabinet = textureCabinet;

        sceneModeling.Attributes = sceneAttributes;
        sceneModeling.View = viewport.View;
        sceneModeling.Projection = viewport.Projection;

        sceneModeling.Prepare();
        sceneModeling.Begin();
        try
        {
          RenderObjects(sceneModeling, viewport, materials);
        }
        finally
        {
          sceneModeling.End();
        }
      }
      finally
      {
        textureCabinet.End();
      }
      textureCabinet.Filter(TextureCabinetFilterType.Bloom);

      // Render semi-transparent objects.
      textureCabinet.Clear(TextureCabinetPass.Glassy);
      textureCabinet.Begin(TextureCabinetPass.Glassy);
      try
      {
        sceneModeling.Attributes = sceneAttributes | Scene.Attribute.Glassy;

        sceneModeling.Begin();
        try
        {
          RenderObjectsGlassy(sceneModeling, viewport, materials);
        }
        finally
        {
          sceneModeling.End();
        }
      }
      finally
      {
        textureCabinet.End();
      }
      textureCabinet.Filter(TextureCabinetFilterType.Glassy);

      // Render on the form.
      swapChain.Begin();
      try
      {
        // Clear the screen to discard previous swap-chain contents, which may improve performance.
        device.Clear(DeviceClear.Color, new FloatColor(0xFF404040u));

        // Note: on lower quality panels, using ColorDitheringFormat.RGB6 would lead to better results.
        colorDithering.Format = ColorDitheringFormat.RGB8;
        colorDithering.Execute(textureCabinet.Texture);

        // Comment above two lines and uncomment the following to render without dithering:
        // textureCabinet.Present();

        // Draw 2D text on top of 3D scene.
        canvas.Begin();
        try
        {
          canvas.SamplerState = CanvasSamplerState.Default;
          canvas.ContextState = CanvasContextState.FlatText;
          { // Draw text hints.
            FontParameters parameters = new("Segoe UI", 14.0f * scale, FontWeight.SemiBold);
            parameters.Effect.FillBrightness = 0.0f;
            parameters.Effect.BorderBrightness = 1.0f;
            parameters.Effect.BorderOpacity = 0.75f;
            parameters.Effect.BorderType = FontBorder.SemiHeavy;
            parameters.Effect.ShadowBrightness = 0.85f;
            parameters.Effect.ShadowOpacity = 0.4f;
            textRenderer.Parameters = parameters;

            textRenderer.DrawAligned(new Vector2(displaySize.X - 8.0f * scale, 4.0f * scale),
              "Space - switch layers, Enter - orthographic, Up/Down - adjust 'frosted glass' effect.",
              new ColorPair(0xFFA5E7B8u, 0xFF77FFCEu), TextAlignment.End, TextAlignment.Start);

            textRenderer.DrawAligned(new Vector2(displaySize.X * 0.5f, displaySize.Y - 4.0f * scale),
              "Left mouse button: rotate scene, right button: move scene, wheel: zoom.",
              new ColorPair(0xFFA5E7B8u, 0xFF77FFCEu), TextAlignment.Middle, TextAlignment.End);
          }
          { // Draw technology string.
            FontParameters parameters = new("Segoe UI", 16.0f * scale, FontWeight.SemiBold);
            parameters.Effect.FillBrightness = 0.0f;
            parameters.Effect.BorderBrightness = 1.0f;
            parameters.Effect.BorderType = FontBorder.SemiHeavy;
            parameters.Effect.ShadowBrightness = 0.75f;
            parameters.Effect.ShadowOpacity = 1.0f;

            textRenderer.Parameters = parameters;
            textRenderer.Draw(new Vector2(8.0f * scale, 4.0f * scale),
              string.Format("Direct3D ({0}.{1}), features: {2}.{3}",
              device.TechVersion >> 8, (device.TechVersion >> 4) & 0xF,
              device.TechFeatureVersion >> 8, (device.TechFeatureVersion >> 4) & 0xF),
              new ColorPair(0xA0FFFFFFu), 1.0f);
          }
        }
        finally
        {
          canvas.End();
        }
      }
      finally
      {
        swapChain.End();
      }
    }

    private void MainForm_MouseDown(object sender, MouseEventArgs e)
    {
      mousePos = new Vector2(e.X, e.Y);

      if (e.Button == MouseButtons.Left)
        camera.Command(CameraCommand.Rotation, new Vector3(mousePos, 0.0f), displaySize);
      else if (e.Button == MouseButtons.Right)
        camera.Command(CameraCommand.Dragging, new Vector3(mousePos, 0.0f), displaySize);
    }

    private void MainForm_MouseMove(object sender, MouseEventArgs e)
    {
      Vector2 prevMousePos = mousePos;
      mousePos = new Vector2(e.X, e.Y);

      if (camera.Command(CameraCommand.Update, new Vector3(mousePos, 0.0f), displaySize))
        Invalidate();

      if (prevMousePos != mousePos)
        Invalidate();
    }

    private void MainForm_MouseUp(object sender, MouseEventArgs e)
    {
      mousePos = new Vector2(e.X, e.Y);
      camera.Command(CameraCommand.Stop, new Vector3(mousePos, 0.0f), displaySize);
    }

    private void MainForm_MouseWheel(object sender, MouseEventArgs e)
    {
      if (orthographic)
      {
        float adjustedZoom = MathF.Min(MathF.Max(cameraZoom - e.Delta * 0.25f, 100.0f), 1500.0f);
        if (MathF.Abs(cameraZoom - adjustedZoom) > 1e-6f)
        {
          Matrix4x4 adjustedProjection = Utility.MatrixOrthographic4x4(adjustedZoom, adjustedZoom *
            displaySize.Y / displaySize.X, 10.0f, 1800.0f);

          camera.ZoomOrtho(mousePos, displaySize, cameraZoom, adjustedZoom, projection, adjustedProjection);
          cameraZoom = adjustedZoom;
          Invalidate();
        }
      }
      else
      {
        camera.Zoom(mousePos, displaySize, projection, -e.Delta * 0.25f);
        cameraZoom = camera.Distance;
        Invalidate();
      }
    }

    private void MainForm_KeyDown(object sender, KeyEventArgs e)
    {
      if (e.KeyCode == Keys.Space)
      {
        if (layers == 0x01)
        {
          ObjectModel obj = objects.Object("GroundFloorWalls");
          obj.Attributes &= ~ObjectModel.Attribute.Transparent;

          layers = 0x03;
        }
        else if (layers == 0x03)
          layers = 0x07;
        else if (layers == 0x07)
        {
          ObjectModel obj = objects.Object("GroundFloorWalls");
          obj.Attributes |= ObjectModel.Attribute.Transparent;

          layers = 0x01;
        }
        Invalidate();
      }
      else if (e.KeyCode == Keys.Up)
      {
        ObjectMaterial material = materials.GetMaterial(2);
        material.FrostedGlass = MathF.Min(material.FrostedGlass + 0.5f, 12.0f);
        materials.SetMaterial(2, material);
        Invalidate();
      }
      else if (e.KeyCode == Keys.Down)
      {
        ObjectMaterial material = materials.GetMaterial(2);
        material.FrostedGlass = MathF.Max(material.FrostedGlass - 0.5f, 0.0f);
        materials.SetMaterial(2, material);
        Invalidate();
      }
      else if (e.KeyCode == Keys.Return && e.Alt)
      {
        if (WindowState == FormWindowState.Maximized)
        {
          FormBorderStyle = FormBorderStyle.Sizable;
          WindowState = FormWindowState.Normal;
        }
        else
        {
          WindowState = FormWindowState.Normal;
          FormBorderStyle = FormBorderStyle.None;
          WindowState = FormWindowState.Maximized;
        }
      }
      else if (e.KeyCode == Keys.Return)
      {
        orthographic = !orthographic;

        if (orthographic)
          camera.Distance = 400.0f;
        else
          camera.Distance = cameraZoom;

        // Reset camera position and rotation.
        camera.SetPosition(Vector3.Zero);
        camera.SetRotation(new Vector4(MathF.PI * 0.25f, MathF.PI * -0.25f, 0.0f, 0.0f));

        Invalidate();
      }
      else if (e.KeyCode == Keys.Escape)
        Close();
    }

    private static void RenderObjects(Scene scene, ObjectModelView view, ObjectMaterials materials = null)
    {
      for (int i = 0; i < view.ObjectCount; ++i)
      {
        ObjectModel obj = view.Object(i);
        if ((obj.Attributes & ObjectModel.Attribute.Transparent) != 0u)
          continue; // Skip transparent objects.

        scene.World = obj.GetTransform(ModelTransform.GlobalModel);

        if (materials is not null)
          scene.Material = materials.GetMaterial(obj.Material);

        obj.Mesh.Model.Draw(scene.Program);
      }
    }

    private static void RenderObjectsGlassy(Scene scene, ObjectModelView view, ObjectMaterials materials)
    {
      for (int i = 0; i < view.ObjectCount; ++i)
      {
        ObjectModel obj = view.Object(i);
        if ((obj.Attributes & ObjectModel.Attribute.Transparent) == 0u)
          continue; // Skip non-transparent objects.

        scene.World = obj.GetTransform(ModelTransform.GlobalModel);

        FloatColor color = obj.Color;
        color.Alpha = 0.4f;

        ObjectMaterial material = materials.GetMaterial(obj.Material);
        material.AmbientColor *= color.RGB;
        material.AlbedoColor *= color;
        scene.Material = material;

        obj.Mesh.Model.Draw(scene.Program);
      }
    }

    private void CreateObjects()
    {
      {
        ObjectModel obj = objects.Add("HouseFloor");
        obj.MeshName = "HouseFloor";
        obj.Material = 0;
        obj.Attributes = ObjectModel.Attribute.Visible | ObjectModel.Attribute.Selectable |
          ObjectModel.Attribute.Hierarchyless;
        obj.Layers = 0x01;
      }
      {
        ObjectModel obj = objects.Add("GroundFloor");
        obj.MeshName = "GroundFloorNoWalls";
        obj.Material = 1;
        obj.Attributes = ObjectModel.Attribute.Visible | ObjectModel.Attribute.Selectable;
        obj.Layers = 0x01;
      }
      {
        ObjectModel obj = objects.Add("GroundFloorWalls");
        obj.MeshName = "GroundFloorWalls";
        obj.Material = 2;
        obj.Attributes = ObjectModel.Attribute.Visible | ObjectModel.Attribute.Selectable |
          ObjectModel.Attribute.Transparent;
        obj.Layers = 0x01;
        obj.SetTransform(ModelTransform.Local, Matrix4x4.CreateTranslation(0.55f, 0.0f, -71.6f));
      }
      {
        ObjectModel obj = objects.Add("TopFloor");
        obj.MeshName = "TopFloorNoWalls";
        obj.Material = 1;
        obj.Attributes = ObjectModel.Attribute.Visible | ObjectModel.Attribute.Selectable;
        obj.Layers = 0x02;
        obj.SetTransform(ModelTransform.Local, Matrix4x4.CreateTranslation(0.0f, 15.5f, -280.0f));
      }
      {
        ObjectModel obj = objects.Add("TopFloorDivision");
        obj.MeshName = "TopFloorDivision";
        obj.Material = 0;
        obj.Attributes = ObjectModel.Attribute.Visible | ObjectModel.Attribute.Selectable;
        obj.Layers = 0x02;
        obj.SetTransform(ModelTransform.Local, Matrix4x4.CreateTranslation(0.0f, 15.5f, -280.0f));
      }
      {
        ObjectModel obj = objects.Add("TopFloorWalls");
        obj.MeshName = "TopFloorWalls";
        obj.Material = 2;
        obj.Attributes = ObjectModel.Attribute.Visible | ObjectModel.Attribute.Selectable |
          ObjectModel.Attribute.Transparent;
        obj.Layers = 0x02;
        obj.SetTransform(ModelTransform.Local, Matrix4x4.CreateTranslation(0.0f, 96.0f, -280.0f));
      }
      {
        ObjectModel obj = objects.Add("HouseWalls");
        obj.MeshName = "HouseWalls";
        obj.Material = 1;
        obj.Attributes = ObjectModel.Attribute.Visible | ObjectModel.Attribute.Selectable;
        obj.Layers = 0x04;
      }
    }

    private static void CreateLightsAndMaterials(SceneLights lights, ObjectMaterials materials)
    {
      { // Create default light.
        SceneLight light = SceneLight.Default;
        light.AmbientColor = new FloatColorRGB(0x00FFFFFFu);
        light.AlbedoColor = new FloatColorRGB(0x00FFFFFFu);
        light.SpecularColor = new FloatColorRGB(0x00FFFFFFu);
        light.SpecularExponent = 1.0f;
        light.Position = lightPosition;
        light.ShadowCaster = 0;

        lights.Add(light);
      }
      { // (0) Floor
        ObjectMaterial material = ObjectMaterial.Default;
        material.AmbientColor = new FloatColorRGB(1.0f, 1.0f, 1.0f);
        material.AlbedoColor = new FloatColor(0.0f, 0.0f, 0.0f, 0.0f);
        material.SpecularColor = new FloatColorRGB(0.0f, 0.0f, 0.0f);
        material.Occlusion = 1.0f;

        materials.Add(material);
      }
      { // (1) Non-transparent objects
        ObjectMaterial material = ObjectMaterial.Default;
        material.AmbientColor = new FloatColorRGB(0.25f, 0.25f, 0.25f);
        material.AlbedoColor = new FloatColor(1.0f, 1.0f, 1.0f, 0.5f);
        material.SpecularColor = new FloatColorRGB(1.0f, 1.0f, 1.0f);
        material.SpecularExponent = 4.0f;
        material.Occlusion = 1.0f;

        materials.Add(material);
      }
      { // (2) Plastic looking semi-transparent walls
        ObjectMaterial material = ObjectMaterial.Default;
        material.AmbientColor = new FloatColorRGB(0.25f, 0.25f, 0.25f);
        material.AlbedoColor = new FloatColor(0.5f, 0.5f, 0.5f, 1.0f);
        material.SpecularColor = new FloatColorRGB(0.25f, 0.25f, 0.25f);
        material.SpecularExponent = 16.0f;
        material.Roughness = new Vector3(0.3f, 1.2f, 0.4f);
        material.Technique = TechniqueLighting.Minnaert;
        material.FrostedGlass = 4.0f;

        materials.Add(material);
      }
    }

    private static void CreateAndLoadMeshes(SceneMeshes meshes)
    {
      string basePath = "../../../../Media/House/";
      string[] meshNames = ["GroundFloorNoWalls", "GroundFloorWalls", "TopFloorNoWalls", "TopFloorWalls",
        "TopFloorDivision", "HouseWalls", "HouseFloor"];

      foreach (string meshName in meshNames)
      {
        uint options = MeshLoadingOption.MaterialVertexColor;
        meshes.AddFromFile(meshName, basePath + meshName + ".obj", vertexElements, ref options, null,
          0, 0, 20.0f);
      }
    }
  }
}