/**
 * Copyright (c) 2021 Dominic Masters
 * 
 * This software is released under the MIT License.
 * https://opensource.org/licenses/MIT
 */

#include "skywall.h"

void skywallInit(primitive_t *primitive) {
  primitiveInit(primitive, SKYWALL_VERTICE_COUNT, SKYWALL_INDICE_COUNT);
  
  vertice_t vertices[SKYWALL_VERTICE_COUNT];
  indice_t indices[SKYWALL_INDICE_COUNT];
  int32_t n, i, j;
  float x, z, p, r;

  // For each slice. We iterate slices+1 to do the wrapping mentioned below.
  for(i = 0; i < SKYWALL_SLICE_COUNT+1; i++) {
    // Get the "percentage" of the current slice, slice 0 is 0, slice n is 1
    p = (float)i/(float)SKYWALL_SLICE_COUNT;

    // Because we we are to "seal the cylinder" we wrap around back to 0 on the
    // last slice to have the last vertice meet the first.
    if(SKYWALL_SLICE_COUNT == i) {
      r = 0;
    } else {
      r = p * MATH_PI * 2.0f;// Convert % to radians
    }

    // Determine the X/Z for the given radian
    x = SKYWALL_SIZE * (float)cos(r);
    z = SKYWALL_SIZE * (float)sin(r);

    // Get the start index for the ertices
    n = i * SKYWALL_VERTICES_PER_SLICE;
    vertices[n].x = x, vertices[n].y = -SKYWALL_SIZE, vertices[n].z = z;
    vertices[n].u = p, vertices[n].v = 1;
    vertices[n+1].x = x, vertices[n+1].y = SKYWALL_SIZE, vertices[n+1].z = z;
    vertices[n+1].u = p, vertices[n+1].v = 0;

    if(i == SKYWALL_SLICE_COUNT) continue;
    j = i * SKYWALL_INDICES_PER_SLICE;
    indices[j] = (indice_t)n;
    indices[j+1] = (indice_t)n+1;
    indices[j+2] = (indice_t)n+2;

    indices[j+3] = (indice_t)n+3;
    indices[j+4] = (indice_t)n+2;
    indices[j+5] = (indice_t)n+1;
  }

  primitiveBufferVertices(primitive, 0, SKYWALL_VERTICE_COUNT, vertices);
  primitiveBufferIndices(primitive, 0, SKYWALL_INDICE_COUNT, indices);
}