tool
extends Spatial

var map = Image.new()
var rng = RandomNumberGenerator.new()
const N: int = 512

func set_points(n: int) -> void:
	map.lock()
	for i in range(0, n):
		map.set_pixel(rng.randi_range(0, N), rng.randi_range(0, N), Color("#000000"))
	map.unlock()


func rule(rule, p, c, n) -> bool:
	# Rule 30
	if (p && c && !n) || (p && !c && !n) || (!p && c && n) || (!p && !c && n):
	# Rule 184
	# if (p && c && n) || (p && !c && n) || (p && !c && !n) || (!p && c && n):
		return true
	return false

func set_ca_texture(rule: int) -> void:
	map.lock()

	var prev_row = []
	var next_row = []
	
	prev_row.resize(N+1)
	for i in range(0, N):
		if rng.randf() > 0.5:
			prev_row[i] = true
	#map.set_pixel(0, 256, Color("#000000"))
	for i in range(0, N):
		next_row.clear()
		next_row.resize(N+1)
		for j in range(0, N):
			var p
			var n
			var c
			c = prev_row[j]
			if j >= 1 && j < N:
				p = prev_row[j-1]
				n = prev_row[j+1]
			if j == 0:
				p = prev_row[N]
			if j == N:
				n = prev_row[0]
			if self.rule(rule, p, c, n):
				next_row[j] = true;
				map.set_pixel(j, i, Color("#000000"))
		prev_row = next_row.duplicate()
	map.unlock()

func _ready() -> void:
	rng.randomize()
	map.create(N, N, false, Image.FORMAT_RGB8)
	map.fill(Color("#ffffff"))
	self.set_ca_texture(100)
	var text = ImageTexture.new()
	text.create_from_image(map)
	var mat = get_node("Thing").get_surface_material(0)
	mat.set_texture(0, text)
