package xaero.rotatenjump.game.graphics.model;

/**
 * Created by xaero on 26/01/2018.
 */

public class Sphere extends Model {

    public Sphere(int n, int m){
        float[] vertices = new float[VERTEX_SIZE * (n + 1) * m];
        short[] indices = new short[(n - 1) * 2 * m * 3];
        int currentIndexOffset = 0;
        double verticalSector = Math.PI / n;
        double horizontalSector = 2 * Math.PI / m;
        for(int i = 0; i < m; i++){
            double horAngle = horizontalSector * i;
            float circleX = (float)Math.cos(horAngle);
            float circleZ = (float)Math.sin(horAngle);
            int previousHor = i == 0 ? m - 1 : i - 1;
            for(int j = 0; j <= n; j++){
                double vertAngle = -Math.PI / 2 + j * verticalSector;
                double vertAngleCos = Math.cos(vertAngle);
                int currentVertex = i * (n + 1) + j;
                int previousVertexHorizontally = previousHor * (n + 1) + j;
                vertices[VERTEX_SIZE * currentVertex] = vertices[VERTEX_SIZE * currentVertex + 5] = (float) (circleX * vertAngleCos);//coord and normal are the same
                vertices[VERTEX_SIZE * currentVertex + 1] = vertices[VERTEX_SIZE * currentVertex + 6] = (float) Math.sin(vertAngle);
                vertices[VERTEX_SIZE * currentVertex + 2] = vertices[VERTEX_SIZE * currentVertex + 7] = (float) (circleZ * vertAngleCos);
                vertices[VERTEX_SIZE * currentVertex + 8] = vertices[VERTEX_SIZE * currentVertex + 9] = vertices[VERTEX_SIZE * currentVertex + 10] = vertices[VERTEX_SIZE * currentVertex + 11] = 1;//white colour
                if(j == n){
                    indices[currentIndexOffset] = (short)(currentVertex - 1);//current 1 below
                    indices[currentIndexOffset + 1] = (short)(previousVertexHorizontally - 1);//previous 1 below
                    indices[currentIndexOffset + 2] = (short)currentVertex;//current
                    currentIndexOffset += 3;
                } else if(j != 0) {
                    indices[currentIndexOffset] = (short)(currentVertex - 1);//bottom center or current 1 below
                    indices[currentIndexOffset + 1] = (short)previousVertexHorizontally;//previous
                    indices[currentIndexOffset + 2] = (short)currentVertex;//current
                    currentIndexOffset += 3;
                    if(j != 1){
                        indices[currentIndexOffset] = (short)(previousVertexHorizontally - 1);//previous 1 below
                        indices[currentIndexOffset + 1] = (short)previousVertexHorizontally;//previous
                        indices[currentIndexOffset + 2] = (short)(currentVertex - 1);//current 1 below
                        currentIndexOffset += 3;
                    }
                }
            }
        }
        //System.out.println(Arrays.toString(vertices));
        create(vertices, indices);
    }

}
