extends GridMap

@export var ChunkWidth: int = 0
@export var ChunkHeight: int = 0

var heightMapTexture = NoiseTexture2D.new()

@onready var player = $Player

const DEEPWATER = 0
const WATER = 1
const SAND = 2
const GRASS = 3
const STONE = 4
const SNOW = 5

func _ready():
	randomize()
	heightMapTexture.width = 2048
	heightMapTexture.height = 2048
	heightMapTexture.noise = FastNoiseLite.new()
	heightMapTexture.noise.fractal_lacunarity = 0.1

	heightMapTexture.noise.seed = randi()
	
	print("Seed: " + str(heightMapTexture.noise.seed))
	
	setGridChunk(0, ChunkWidth, 0, ChunkHeight)
	
func generateGridChunk(playerPos: Vector3) -> void:
	clear()
	var chunkCenter = local_to_map(playerPos)
	var rowStart: float = chunkCenter.z - (ChunkHeight / 2)
	var rowEnd: float = chunkCenter.z + (ChunkHeight / 2)
	var columnStart: float = chunkCenter.x - (ChunkWidth / 2)
	var columnEnd: float = chunkCenter.x + (ChunkWidth / 2)
	setGridChunk(columnStart, columnEnd, rowStart, rowEnd)

func setGridChunk(columnStart: float, columnEnd: float, rowStart: float, rowEnd: float) -> void:
	if columnStart < 0 : 
		columnStart = 0
	if rowStart < 0 : 
		rowStart = 0
	if columnEnd > heightMapTexture.width : 
		columnEnd = heightMapTexture.width - 1
	if rowEnd > heightMapTexture.height : 
		rowEnd = heightMapTexture.height - 1
		
	for mz in range(rowStart, rowEnd):
		for mx in range(columnStart, columnEnd):
			var noiseValue: float = heightMapTexture.noise.get_noise_2d(mx, mz)
			var my: int = floor(noiseValue * 10)
			var meshID = SNOW
			if my < 8:
				meshID = STONE
			if my < 5:
				meshID = GRASS
			if my < 2:
				meshID = SAND
			if my < 1:
				meshID = WATER
			if my < -5:
				meshID = DEEPWATER
			
			set_cell_item( Vector3(mx,max(my, 0),mz) , meshID,0)
#			var weight: float = (noiseValue + 1) / 2
#			var height: float = floor(lerp(0, 8, weight)) * 2
#			for my in range(0, height):
#				var meshID = floor(my / 2)
#				set_cell_item( Vector3(mx,my*2,mz) ,meshID,0)



func _on_MapUpdateTimer_timeout():
	generateGridChunk(player.global_transform.origin)
