extends MeshInstance

const chunk_dimensions = Vector3(16, 16, 16);

var chunk_data = PoolIntArray()
var voxel_name_index = PoolStringArray()
var voxels = {}

func _ready():
	add_voxel("default:air", false, null)
	add_voxel("default:dirt", true, preload("res://packages/voxel_mesher/materials/dirt.material"))
	add_voxel("default:grass", true, preload("res://packages/voxel_mesher/materials/grass.material"))
	add_voxel("default:glass", true, preload("res://packages/voxel_mesher/materials/glass.material"))
	add_voxel("default:lamp", true, preload("res://packages/voxel_mesher/materials/lamp.material"))

func add_voxel(name, opaque, material):
	voxels[name] = {
		"name": name,
		"opaque": opaque,
		"material": material
	}
	voxel_name_index.append(name)

func generate_data():
	var rng = RandomNumberGenerator.new()
	var length = chunk_dimensions.x*chunk_dimensions.y*chunk_dimensions.z
	chunk_data.resize(length)
	for i in range(0, length):
		chunk_data.set(i, rng.randi_range(0, voxel_name_index.size() - 1))

func mesh(mesher):
	var start_time = OS.get_ticks_msec()
	var surface_data = mesher.mesh(voxel_name_index, chunk_dimensions, chunk_data)
	var end_time = OS.get_ticks_msec()
	print("Elapsed: ", end_time - start_time)
	# Initialize the ArrayMesh.
	var arr_mesh = ArrayMesh.new()
	
	for i in range(1, surface_data.size()):
		var voxel = voxels[voxel_name_index[i]]
		var mesh_data = surface_data[i]
		var arrays = []
		arrays.resize(ArrayMesh.ARRAY_MAX)
		arrays[ArrayMesh.ARRAY_VERTEX] = mesh_data.vertices
		arrays[ArrayMesh.ARRAY_NORMAL] = mesh_data.normals
		arrays[ArrayMesh.ARRAY_TEX_UV] = mesh_data.uvs
		arrays[ArrayMesh.ARRAY_TEX_UV2] = mesh_data.uvs
		# Create the Mesh.
		arr_mesh.add_surface_from_arrays(Mesh.PRIMITIVE_TRIANGLES, arrays)
		arr_mesh.surface_set_material(i - 1, voxel.material)

	self.mesh = arr_mesh
	generate_data()

