class_name M2MeshResourceExtractor
extends RefCounted

## Selects the first Mesh from loaded M2 Resources or existing Node subtrees.
## The caller owns ResourceLoader I/O, cache adoption and material preparation.


## Returns the direct Mesh Resource or the first Mesh in a temporary PackedScene
## instance. The temporary instance is freed before this method returns.
func extract_first_mesh(resource: Resource) -> Mesh:
	if resource is Mesh:
		return resource as Mesh
	if not (resource is PackedScene):
		return null
	var temporary_root := (resource as PackedScene).instantiate()
	if temporary_root == null:
		return null
	var mesh := find_first_mesh_in_subtree(temporary_root)
	temporary_root.free()
	return mesh


## Returns the first MeshInstance3D Mesh in depth-first preorder. The subtree
## and Mesh ownership remain unchanged.
func find_first_mesh_in_subtree(root: Node) -> Mesh:
	if root == null:
		return null
	if root is MeshInstance3D:
		return (root as MeshInstance3D).mesh
	for child in root.get_children():
		var mesh := find_first_mesh_in_subtree(child)
		if mesh != null:
			return mesh
	return null
