
vec2 line_intersection(vec2 a1, vec2 a2,
                       vec2 b1, vec2 b2)
{
  float x1 = a1.x;
  float y1 = a1.y;
  float x2 = a2.x;
  float y2 = a2.y;

  float x3 = b1.x;
  float y3 = b1.y;
  float x4 = b2.x;
  float y4 = b2.y;

  float x1x2 = x1 - x2;
  float x1x3 = x1 - x3;
  float x3x4 = x3 - x4;
  float y1y2 = y1 - y2;
  float y1y3 = y1 - y3;
  float y3y4 = y3 - y4;

  float div = 1.0f / (x1x2 * y3y4 - y1y2 * x3x4);

  float t = (x1x3 * y3y4 - y1y3 * x3x4) * div;
  float u = -(x1x2 * y1y3 - y1y2 * x1x3) * div;

  return {t, u};
}

bool collided[256] = {};

bool line_has_collision(vec3 a1, vec3 a2, const mat4x4& model_trans, const mat4x4& screen)
{
  mat4x4 trans = screen * model_trans;

  const struct model * model = &haunted_mansion_collision_model;
  const struct object * object = model->object[0];

  for (int i = 0; i < object->line_count; i++) {

    const union line * line = &object->line[i];

    vec3 b1 = trans * model->position[line->a];
    vec3 b2 = trans * model->position[line->b];

    vec2 tu = line_intersection({a1.x, a1.z},
                                {a2.x, a2.z},
                                {b1.x, b1.z},
                                {b2.x, b2.z});

    if (tu.x >= 0.0f && tu.x <= 1.0f && tu.y >= 0.0f && tu.y <= 1.0f) {
      collided[i] = true;
      return true;
    }
  }
  return false;
}

float last_dx = 0;
float last_dy = 0;

void render_collision(ta_parameter_writer& writer, const mat4x4& model_trans, const mat4x4& screen)
{
  mat4x4 trans = screen * model_trans;

  const uint32_t base_color = 0xffffffff;

  const struct model * model = &haunted_mansion_collision_model;
  const struct object * object = model->object[0];

  int line_count = object->line_count;
  for (int i = 0; i < line_count; i++) {

    const union line * line = &object->line[i];

    vec3 a = trans * model->position[line->a];
    vec3 b = trans * model->position[line->b];

    render_line(writer,
                screen_transform((vec3){a.x, -a.z, 4.f}),
                screen_transform((vec3){b.x, -b.z, 4.f}),
                collided[i] ? 0xffff0000 : base_color);
  }

  vec3 a = {last_dx * -4,  -last_dy * -4, 4};
  vec3 b = {last_dx * 0.5f, -last_dy * 0.5f, 4};
  //if (a.z > 0) {
    render_line(writer,
                screen_transform(a),
                screen_transform(b),
                0xff00ff00);
    //}
}
