/*
PolyGun

Copyright (c) 2023 kacperks https://kacperks.cubesoftware.xyz
Copyright (c) 2023 Looki2000 https://looki2000.cubesoftware.xyz

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#include "greedy_meshing.hpp"
#include "game/world/chunk.hpp"

namespace polygun::engine {

	cuboid_list greedy_meshing::merge(world::Chunk& chunk) {
		// create copy of chunk
		world::Chunk chunk_copy = chunk;

		cuboid_list cuboids;
		cuboid cuboid_to_append;

		for (unsigned int m_y = 0; m_y < m_voxel_count; m_y++) {
			for (unsigned int m_z = 0; m_z < m_voxel_count; m_z++) {
				m_last_material = 0;

				for (unsigned int m_x = 0; m_x < m_voxel_count; m_x++) {
					m_cuboid_ended = false;

					// if material changed
					if (chunk_copy.get_node(glm::vec3(m_x, m_y, m_z)) != m_last_material) {
						// if cuboid ended
						// material switch NOT from air
						if (m_last_material != 0) {
							m_cuboid_end_x = m_x;
							m_cuboid_ended = true;
						}

						// if new cuboid just started AND NOT cuboid ended while new one starting
						if (chunk_copy.get_node(glm::vec3(m_x, m_y, m_z)) != 0 && !m_cuboid_ended) {
							m_cuboid_start_x = m_x;
						}
					}

					// if cuboid ended
					// end of map row on NOT air
					if (m_x == m_voxel_max_idx && chunk_copy.get_node(glm::vec3(m_x, m_y, m_z)) != 0) {
						m_cuboid_end_x = m_x + 1;
						m_cuboid_ended = true;
						m_last_material = chunk_copy.get_node(glm::vec3(m_x, m_y, m_z));
					}

					if (m_cuboid_ended) {
						// scanning for other rows under existing row that can be included in the cuboid
						m_cuboid_end_z = m_z;
						m_invalid_row = false;
						while (true) {
							m_cuboid_end_z++;

							// if the end of the map is reached, break the loop
							if (m_cuboid_end_z == m_voxel_count) {
								break;
							}

							// check if all materials in row are the same as the cuboid's material
							for (unsigned int m_x_s = m_cuboid_start_x; m_x_s < m_cuboid_end_x; m_x_s++) {
								if (chunk_copy.get_node(glm::vec3(m_x_s, m_y, m_cuboid_end_z)) != m_last_material) {
									m_invalid_row = true;
									break;
								}
							}

							if (m_invalid_row) {
								break;
							}

							// set all values of next row that will be added to the cuboid to 0 to prevent them from being treated as a new cuboid in the next z loop iteration
							for (unsigned int m_x_s = m_cuboid_start_x; m_x_s < m_cuboid_end_x; m_x_s++) {
								chunk_copy.add_node(0, glm::vec3(m_x_s, m_y, m_cuboid_end_z));
							}
						}

						// x, z sizes have been found. now check the size of the y axis
						m_cuboid_end_y = m_y;
						m_invalid_plane = false;
						while (true) {
							m_cuboid_end_y++;

							// if the end of the map is reached, break the loop
							if (m_cuboid_end_y == m_voxel_count) {
								break;
							}

							// check if all materials in a "plane" under the current cuboid are the same as the cuboid's material
							for (unsigned int m_z_s = m_z; m_z_s < m_cuboid_end_z; m_z_s++) {
								for (unsigned int m_x_s = m_cuboid_start_x; m_x_s < m_cuboid_end_x; m_x_s++) {
									if (chunk_copy.get_node(glm::vec3(m_x_s, m_cuboid_end_y, m_z_s)) != m_last_material) {
										m_invalid_plane = true;
										break;
									}
								}
							}

							if (m_invalid_plane) {
								break;
							}

							// set all values of next plane that will be added to the cuboid to 0 to prevent them from being treated as a new cuboid in the next y loop iteration
							for (unsigned int m_z_s = m_z; m_z_s < m_cuboid_end_z; m_z_s++) {
								for (unsigned int m_x_s = m_cuboid_start_x; m_x_s < m_cuboid_end_x; m_x_s++) {
									chunk_copy.add_node(0, glm::vec3(m_x_s, m_cuboid_end_y, m_z_s));
								}
							}
						}

						// add cuboid to cuboids
						cuboid_to_append = {{
							m_cuboid_start_x, m_y, m_z,
							m_cuboid_end_x, m_cuboid_end_y, m_cuboid_end_z,
							},
							static_cast<unsigned>(m_last_material)
						};
						cuboids.push_back(cuboid_to_append);


						// if last cuboid is touching current cuboid, use current position as current cuboid's start position
						if (chunk_copy.get_node(glm::vec3(m_x, m_y, m_z)) != 0) {
							m_cuboid_start_x = m_x;
						}

					}

					m_last_material = chunk_copy.get_node(glm::vec3(m_x, m_y, m_z));
					
				}
			}
		}

		return cuboids;
	}


	static bool is_face_covered(world::Chunk& chunk, unsigned int slice_axis_A_start, unsigned int slice_axis_A_end, unsigned int slice_axis_B_start, unsigned int slice_axis_B_end, unsigned int slice_axis_C,  unsigned int face_axis_idx) {
		// check if face is fully covered with voxels

		// bottom/top face check (y axis)
		if (face_axis_idx == 0) {
			for (unsigned int z = slice_axis_B_start; z < slice_axis_B_end; z++) {
				for (unsigned int x = slice_axis_A_start; x < slice_axis_A_end; x++) {
					if (chunk.get_node(glm::vec3(z, slice_axis_C, x)) == 0) { // if air, face is not fully covered, stop checking
						return false;
					}
				}
			}
		}


		// left/right face check (x axis)
		else if (face_axis_idx == 1) {
			for (unsigned int z = slice_axis_B_start; z < slice_axis_B_end; z++) {
				for (unsigned int y = slice_axis_A_start; y < slice_axis_A_end; y++) {
					if (chunk.get_node(glm::vec3(z, y, slice_axis_C)) == 0) {
						return false;
					}
				}
			}
		}


		// back/front face check (z axis
		else {
			for (unsigned int y = slice_axis_B_start; y < slice_axis_B_end; y++) {
				for (unsigned int x = slice_axis_A_start; x < slice_axis_A_end; x++) {
					if (chunk.get_node(glm::vec3(slice_axis_C, y, x)) == 0) {
						return false;
					}
				}
			}
		}

		// none of returns were called, face is fully covered and NOT visible
		return true;
	}


	static unsigned int faces_indices[6][6] = {
		{0, 1, 3, 0, 3, 2}, // bottom
		{0, 2, 6, 0, 6, 4}, // left
		{0, 4, 5, 0, 5, 1}, // back
		{4, 7, 5, 4, 6, 7}, // top
		{1, 5, 7, 1, 7, 3}, // right
		{2, 7, 6, 2, 3, 7}, // front
	};
	
	static unsigned int slice_axises_indices[3][6] {
		{0, 3, 2, 5, 1, 4}, //  bottom/top face check
		{1, 4, 2, 5, 0, 3}, //  left/right face check
		{0, 3, 1, 4, 2, 5}, //  back/front face check
	};


	vertices_indices greedy_meshing::generate_mesh(cuboid_list cuboids, world::Chunk& chunk) {

		std::vector<glm::vec3> m_vertices;
		std::vector<unsigned int> m_indices;
		std::vector<unsigned int> m_cuboid_vertices_indices;

		for(const cuboid& cur_cuboid : cuboids) {

			// calculate vertices

			// positions of every vertex of the cuboid (each corner)
			unsigned int m_cuboid_vertices[8][3] = {
				{cur_cuboid.coords[0], cur_cuboid.coords[1], cur_cuboid.coords[2]},
				{cur_cuboid.coords[3], cur_cuboid.coords[1], cur_cuboid.coords[2]},
				{cur_cuboid.coords[0], cur_cuboid.coords[1], cur_cuboid.coords[5]},
				{cur_cuboid.coords[3], cur_cuboid.coords[1], cur_cuboid.coords[5]},
				{cur_cuboid.coords[0], cur_cuboid.coords[4], cur_cuboid.coords[2]},
				{cur_cuboid.coords[3], cur_cuboid.coords[4], cur_cuboid.coords[2]},
				{cur_cuboid.coords[0], cur_cuboid.coords[4], cur_cuboid.coords[5]},
				{cur_cuboid.coords[3], cur_cuboid.coords[4], cur_cuboid.coords[5]},
			};

			m_cuboid_vertices_indices.clear();

			// iterate over cuboid vertices
			for (const auto& m_vertex : m_cuboid_vertices) {

				int m_vertex_idx = -1;

				// check if vertex is already in vertices list
				for (unsigned int i = 0; i < m_vertices.size(); i++) {
					if (m_vertices[i] == glm::vec3(m_vertex[0], m_vertex[1], m_vertex[2])) {
						m_vertex_idx = i;
						break;
					}
				}

				// if so, add found index to m_cuboid_vertices_indices
				if (m_vertex_idx != -1) {
					m_cuboid_vertices_indices.push_back(m_vertex_idx);

				// if not, add it (vertex) and add its index to m_cuboid_vertices_indices
				} else {
					m_cuboid_vertices_indices.push_back(m_vertices.size());
					m_vertices.push_back(glm::vec3(m_vertex[0], m_vertex[1], m_vertex[2]));
				}
			}

			// calculate faces

			for (unsigned int face_idx = 0; face_idx < 6; ++face_idx) {
				// do not add faces that are not visible. check what sides of cuboid are occupied by voxels completely
				// if a side is not occupied, add the corresponding faces to the mesh

				unsigned int face_dir = face_idx / 3;
				unsigned int face_axis_idx = face_idx % 3;
				// face_dir: 0 - negative, 1 - positive

				int slice_axis_C = cur_cuboid.coords[slice_axises_indices[face_axis_idx][4 + face_dir]] - (1 - face_dir);

				// if face is NOT touching chunk border
				if (slice_axis_C != -1 && static_cast<unsigned>(slice_axis_C) != m_voxel_count) {
					// start and end of axises for scan of slice of voxels next to the face
					unsigned int slice_axis_A_start = cur_cuboid.coords[slice_axises_indices[face_axis_idx][0]];
					unsigned int slice_axis_A_end = cur_cuboid.coords[slice_axises_indices[face_axis_idx][1]];
					unsigned int slice_axis_B_start = cur_cuboid.coords[slice_axises_indices[face_axis_idx][2]];
					unsigned int slice_axis_B_end = cur_cuboid.coords[slice_axises_indices[face_axis_idx][3]];

					// check if face is obstructed by any voxels
					if (is_face_covered(chunk, slice_axis_A_start, slice_axis_A_end, slice_axis_B_start, slice_axis_B_end, slice_axis_C, face_axis_idx)) {
						continue;
					}

				}

				for (unsigned int i = 0; i < 6; ++i) {
					m_indices.push_back(m_cuboid_vertices_indices[faces_indices[face_idx][i]]);
				}

			}
		
		}
		
		return {m_vertices, m_indices};
	}
}
