#include <stdint.h>
#include <bit>

#include "holly/background.hpp"
#include "holly/core.hpp"
#include "holly/core_bits.hpp"
#include "holly/holly.hpp"
#include "holly/isp_tsp.hpp"
#include "holly/region_array.hpp"
#include "holly/ta_bits.hpp"
#include "holly/ta_fifo_polygon_converter.hpp"
#include "holly/ta_global_parameter.hpp"
#include "holly/ta_parameter.hpp"
#include "holly/ta_vertex_parameter.hpp"
#include "holly/texture_memory_alloc5.hpp"
#include "holly/video_output.hpp"

#include "sh7091/sh7091.hpp"
#include "sh7091/sh7091_bits.hpp"
#include "sh7091/serial.hpp"
#include "sh7091/vbr.hpp"

#include "systembus.hpp"
#include "systembus_bits.hpp"

#include "maple/maple.hpp"
#include "maple/maple_host_command_writer.hpp"
#include "maple/maple_bus_bits.hpp"
#include "maple/maple_bus_commands.hpp"
#include "maple/maple_bus_ft0.hpp"

#include "memorymap.hpp"
#include "interrupt.hpp"

#include "math/vec2.hpp"
#include "math/vec3.hpp"
#include "math/vec4.hpp"
#include "math/mat4x4.hpp"
#include "math/geometry.hpp"
#include "math/transform.hpp"

using vec2 = vec<2, float>;
using vec3 = vec<3, float>;
using vec4 = vec<4, float>;
using mat4x4 = mat<4, 4, float>;

#include "textures/brick_floor_diff_1k.vq.h"
#include "textures/brick_wall_10_diff_512p.vq.h"
#include "textures/rebar_reinforced_concrete_diff_512.vq.h"
#include "textures/red_plaster_weathered_diff_512p.vq.h"
#include "textures/weathered_planks_diff_1k.vq.h"
#include "textures/white_plaster_rough_02_diff_512p.vq.h"
#include "textures/wooden_gate_diff_1k.vq.h"
#include "textures/yellow_plaster_02_diff_512p.vq.h"
#include "textures/yellow_plaster_diff_512p.vq.h"
#include "textures/generic.vq.h"

#include "model/blender_export.h"
//#include "model/model.h"
//#include "model/cone/model.h"
//#include "model/cube/model.h"
//#include "model/haunted_mansion/model.h"
//#include "model/haunted_mansion/collision.h"
#include "model/haunted_mansion/scene.h"

#include "src/ta.hpp"
#include "src/transform.hpp"

void vbr100()
{
  serial::string("vbr100\n");
  interrupt_exception();
}

void vbr400()
{
  serial::string("vbr400\n");
  interrupt_exception();
}

const int framebuffer_width = 640;
const int framebuffer_height = 480;
const int tile_width = framebuffer_width / 32;
const int tile_height = framebuffer_height / 32;

constexpr uint32_t ta_alloc = 0
                            | ta_alloc_ctrl::pt_opb::no_list
                            | ta_alloc_ctrl::tm_opb::no_list
                            | ta_alloc_ctrl::t_opb::no_list
                            | ta_alloc_ctrl::om_opb::no_list
                            | ta_alloc_ctrl::o_opb::_32x4byte;

constexpr int ta_cont_count = 1;
constexpr struct opb_size opb_size[ta_cont_count] = {
  {
    .opaque = 32 * 4,
    .opaque_modifier = 0,
    .translucent = 0,
    .translucent_modifier = 0,
    .punch_through = 0
  }
};

static volatile int ta_in_use = 0;
static volatile int core_in_use = 0;
static volatile int next_frame = 0;
static volatile int framebuffer_ix = 0;
static volatile int next_frame_ix = 0;

static inline void pump_events(uint32_t istnrm)
{
  if (istnrm & istnrm::v_blank_in) {
    system.ISTNRM = istnrm::v_blank_in;
    next_frame = 1;
    holly.FB_R_SOF1 = texture_memory_alloc.framebuffer[next_frame_ix].start;
  }

  if (istnrm & istnrm::end_of_render_tsp) {
    system.ISTNRM = istnrm::end_of_render_tsp
                  | istnrm::end_of_render_isp
                  | istnrm::end_of_render_video;

    next_frame_ix = framebuffer_ix;
    framebuffer_ix += 1;
    if (framebuffer_ix >= 3) framebuffer_ix = 0;

    core_in_use = 0;
  }

  if (istnrm & istnrm::end_of_transferring_opaque_list) {
    system.ISTNRM = istnrm::end_of_transferring_opaque_list;

    core_in_use = 1;
    core_start_render2(texture_memory_alloc.region_array.start,
                       texture_memory_alloc.isp_tsp_parameters.start,
                       texture_memory_alloc.background[0].start,
                       texture_memory_alloc.framebuffer[framebuffer_ix].start,
                       framebuffer_width);

    ta_in_use = 0;
  }
}

void vbr600()
{
  uint32_t sr;
  asm volatile ("stc sr,%0" : "=r" (sr));
  sr |= sh::sr::imask(15);
  asm volatile ("ldc %0,sr" : : "r" (sr));
  //serial::string("imask\n");

  //check_pipeline();

  if (sh7091.CCN.EXPEVT == 0 && sh7091.CCN.INTEVT == 0x320) {
    uint32_t istnrm = system.ISTNRM;
    uint32_t isterr = system.ISTERR;

    if (isterr) {
      serial::string("isterr: ");
      serial::integer<uint32_t>(system.ISTERR);
    }

    pump_events(istnrm);

    sr &= ~sh::sr::imask(15);
    asm volatile ("ldc %0,sr" : : "r" (sr));

    return;
  }

  serial::string("vbr600\n");
  interrupt_exception();
}

static ft0::data_transfer::data_format data[4];

uint8_t send_buf[1024] __attribute__((aligned(32)));
uint8_t recv_buf[1024] __attribute__((aligned(32)));

void do_get_condition()
{
  auto writer = maple::host_command_writer(send_buf, recv_buf);

  using command_type = maple::get_condition;
  using response_type = maple::data_transfer<ft0::data_transfer::data_format>;

  auto [host_command, host_response]
    = writer.append_command_all_ports<command_type, response_type>();

  for (int port = 0; port < 4; port++) {
    auto& data_fields = host_command[port].bus_data.data_fields;
    data_fields.function_type = std::byteswap(function_type::controller);
  }
  maple::dma_start(send_buf, writer.send_offset,
                   recv_buf, writer.recv_offset);

  for (uint8_t port = 0; port < 4; port++) {
    auto& bus_data = host_response[port].bus_data;
    if (bus_data.command_code != response_type::command_code) {
      return;
    }
    auto& data_fields = bus_data.data_fields;
    if ((std::byteswap(data_fields.function_type) & function_type::controller) == 0) {
      return;
    }

    data[port].digital_button = data_fields.data.digital_button;
    for (int i = 0; i < 6; i++) {
      data[port].analog_coordinate_axis[i]
        = data_fields.data.analog_coordinate_axis[i];
    }
  }
}

constexpr inline mat4x4 screen_rotation()
{
  mat4x4 t = {
    1, 0,  0, 0.0f,
    0, 0, -1, 1,
    0, 1,  0, 1.2f,
    0, 0,  0, 1,
  };

  return t;
}

const vec3 light_vec = {20, 1, -20};

struct mesh_material generic_material = {
  512, 512, 933888 + (1024 * 1024 / 4) + (256 * 4 * 2),
};

vec3 position[1024];
vec3 polygon_normal[1024];

void render_blender_object(ta_parameter_writer& writer,
                           const mat4x4& screen_trans,
                           const object * object)
{
  const mat4x4 trans = screen_trans
    * translate(object->location)
    * scale(object->scale)
    * rotate_quaternion(object->rotation);

  const mesh * mesh = object->mesh;
  assert(mesh->normal_length == mesh->position_length);
  //assert(mesh->polygon_normal_length == mesh->polygons_length);
  assert(mesh->uv_layers_length == 1);
  assert(mesh->position_length < (int)((sizeof (position)) / (sizeof (position[0]))));

  for (int i = 0; i < mesh->position_length; i++) {
    position[i] = trans * mesh->position[i];
  }
  for (int i = 0; i < mesh->polygon_normal_length; i++) {
    polygon_normal[i] = normal_multiply(trans, mesh->polygon_normal[i]);
  }

  const vec2 * uvmap = mesh->uv_layers[0];

  int last_material = -2;

  for (int i = 0; i < mesh->polygons_length; i++) {
    const polygon * polygon = &mesh->polygons[i];

    if (polygon->material_index < 0 || polygon->material_index >= mesh->materials_length) {
      if (last_material != -1) {
        global_polygon_textured(writer,
                                para_control::list_type::opaque,
                                &generic_material);
        last_material = -1;
      }
    } else if (last_material != polygon->material_index) {
      global_polygon_textured(writer,
                              para_control::list_type::opaque,
                              &mesh->materials[polygon->material_index]);
      last_material = polygon->material_index;
    }

    render_polygon(writer,
                   light_vec,
                   i,
                   polygon,
                   position,
                   polygon_normal,
                   uvmap);
  }
}

void transfer_scene(ta_parameter_writer& writer, const mat4x4& screen_trans)
{
  // modifier volume
  if (0) {
    //render_inclusion_cube(writer);
    //render_cone(writer, cone_model);

    // end of modifier volume list
    writer.append<ta_global_parameter::end_of_list>() =
      ta_global_parameter::end_of_list(para_control::para_type::end_of_list);
  }

  // opaque
  {
    for (uint32_t i = 0; i < (sizeof (objects)) / (sizeof (objects[0])); i++) {
      render_blender_object(writer, screen_trans, &objects[i]);
    }

    //global_polygon_type_0(writer);
    //render_collision(writer, mansion_model_trans, screen);

    // end of opaque list
    writer.append<ta_global_parameter::end_of_list>() =
      ta_global_parameter::end_of_list(para_control::para_type::end_of_list);
  }
}

void transfer_ta_fifo_texture_memory_32byte(void * dst, void * src, int length)
{
  uint32_t out_addr = (uint32_t)dst;
  sh7091.CCN.QACR0 = ((reinterpret_cast<uint32_t>(out_addr) >> 24) & 0b11100);
  sh7091.CCN.QACR1 = ((reinterpret_cast<uint32_t>(out_addr) >> 24) & 0b11100);

  volatile uint32_t * base = &store_queue[(out_addr & 0x03ffffc0) / 4];
  uint32_t * src32 = reinterpret_cast<uint32_t *>(src);

  length = (length + 31) & ~31; // round up to nearest multiple of 32
  while (length > 0) {
    base[0] = src32[0];
    base[1] = src32[1];
    base[2] = src32[2];
    base[3] = src32[3];
    base[4] = src32[4];
    base[5] = src32[5];
    base[6] = src32[6];
    base[7] = src32[7];
    asm volatile ("pref @%0"
                  :                // output
                  : "r" (&base[0]) // input
                  : "memory");
    length -= 32;
    base += 8;
    src32 += 8;
  }
}

void transfer_textures()
{
  system.LMMODE0 = 0; // 64-bit address space
  system.LMMODE1 = 0; // 64-bit address space

  for (uint32_t i = 0; i < (sizeof (materials)) / (sizeof (materials[0])); i++) {
    int offset = texture_memory_alloc.texture.start + materials[i].offset;
    void * dst = reinterpret_cast<void *>(&ta_fifo_texture_memory[offset / 4]);
    transfer_ta_fifo_texture_memory_32byte(dst,
                                           materials[i].start,
                                           materials[i].size);
  }
}

constexpr inline mat4x4 update_cone()
{
  static float rx = 0;
  static float ry = 0;

  float tx = 0;
  float ty = 0;
  if (ft0::data_transfer::digital_button::ua(data[0].digital_button) == 0) {
    tx =  0.5;
  } else if (ft0::data_transfer::digital_button::da(data[0].digital_button) == 0) {
    tx = -0.5;
  }

  if (ft0::data_transfer::digital_button::la(data[0].digital_button) == 0) {
    ty = -0.5;
  } else if (ft0::data_transfer::digital_button::ra(data[0].digital_button) == 0) {
    ty =  0.5;
  }

  /*
    rx = 0, tx = 1, dx = 1;
    rx = 1, tx = 1, dx = 0;
    rx = -1, tx = 1, dx = 2;
   */

  float dx = tx - rx;
  float dy = ty - ry;

  rx += dx * 0.05;
  ry += dy * 0.05;

  mat4x4 mrx = {
    1, 0, 0, 0,
    0, cos(rx), -sin(rx), 0,
    0, sin(rx),  cos(rx), 0,
    0, 0, 0, 1,
  };

  mat4x4 mry = {
     cos(ry), 0, sin(ry), 0,
    0, 1, 0, 0,
    -sin(ry), 0, cos(ry), 0,
    0, 0, 0, 1,
  };

  return mry * mrx;
}

constexpr inline mat4x4 update_analog(const mat4x4& screen_trans)
{
  const float l_ = static_cast<float>(data[0].analog_coordinate_axis[0]) * (1.f / 255.f);
  const float r_ = static_cast<float>(data[0].analog_coordinate_axis[1]) * (1.f / 255.f);

  const float x_ = static_cast<float>(data[0].analog_coordinate_axis[2] - 0x80) / 127.f;
  const float y_ = static_cast<float>(data[0].analog_coordinate_axis[3] - 0x80) / 127.f;
  float x = 0.05f * -x_;
  float y = 0.05f * y_;

  mat4x4 t = {
    1, 0, 0, x,
    0, 1, 0, 0,
    0, 0, 1, y,
    0, 0, 0, 1,
  };

  float theta = 0;
  if (l_ > 0.1f) {
    theta = -0.05f * l_;
  } else if (r_ > 0.1f) {
    theta = 0.05f * r_;
  }

  mat4x4 ry = {
     cos(theta), 0, sin(theta), 0,
    0, 1, 0, 0,
    -sin(theta), 0, cos(theta), 0,
    0, 0, 0, 1,
  };

  return t * ry * screen_trans;
}

uint8_t __attribute__((aligned(32))) ta_parameter_buf[1024 * 1024];

void main()
{
  serial::init(0);

  interrupt_init();
  serial::string("interrupt_init\n");

  holly.SOFTRESET = softreset::pipeline_soft_reset
		  | softreset::ta_soft_reset;
  holly.SOFTRESET = 0;

  core_init();

  holly.FPU_SHAD_SCALE = fpu_shad_scale::simple_shadow_enable::intensity_volume_mode
                       | fpu_shad_scale::scale_factor_for_shadows(128);

  system.ISTNRM = 0xffffffff;
  system.ISTERR = 0xffffffff;
  system.IML6NRM = istnrm::end_of_render_tsp
                 | istnrm::v_blank_in
                 | istnrm::end_of_transferring_opaque_list;

  region_array_multipass(tile_width,
                         tile_height,
                         opb_size,
                         ta_cont_count,
                         texture_memory_alloc.region_array.start,
                         texture_memory_alloc.object_list.start);

  background_parameter2(texture_memory_alloc.background[0].start,
                        0xff202040);

  ta_parameter_writer writer = ta_parameter_writer(ta_parameter_buf, (sizeof (ta_parameter_buf)));

  transfer_textures();
  video_output::set_mode_vga();
  do_get_condition();

  mat4x4 screen_trans = screen_rotation();

  while (1) {
    maple::dma_wait_complete();
    do_get_condition();
    screen_trans = update_analog(screen_trans);
    //mat4x4 cone_model = update_cone();

    writer.offset = 0;
    transfer_scene(writer, screen_trans);
    while (ta_in_use);
    while (core_in_use);
    ta_in_use = 1;
    ta_polygon_converter_init2(texture_memory_alloc.isp_tsp_parameters.start,
                               texture_memory_alloc.isp_tsp_parameters.end,
                               texture_memory_alloc.object_list.start,
                               texture_memory_alloc.object_list.end,
                               opb_size[0].total(),
                               ta_alloc,
                               tile_width,
                               tile_height);
    ta_polygon_converter_writeback(writer.buf, writer.offset);
    ta_polygon_converter_transfer(writer.buf, writer.offset);
    while (next_frame == 0);
    next_frame = 0;
  }
}
