class_name MaterialManagerClass
extends Node

var material_application_queue: Array = []
var max_materials_per_frame: int = 20 # Adjust based on performance

func _process(_delta):
	# Process material applications gradually over multiple frames
	process_material_queue()

func process_material_queue():
	var processed = 0
	while material_application_queue.size() > 0 and processed < max_materials_per_frame:
		var task = material_application_queue.pop_front()

		if is_instance_valid(task.mesh_instance) and task.mesh_instance != null:
			apply_material_immediately(task.mesh_instance, task.surface_index, task.material)
		
		processed += 1

func queue_material_application(mesh_instance: MeshInstance3D, surface_index: int, material: StandardMaterial3D):
	material_application_queue.append({
		"mesh_instance": mesh_instance,
		"surface_index": surface_index,
		"material": material
	})

func apply_material_immediately(mesh_instance: MeshInstance3D, surface_index: int, material: StandardMaterial3D):
	if is_instance_valid(mesh_instance):
		mesh_instance.set_surface_override_material(surface_index, material)
