Multithreaded resource loading is still laggy

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By creativeape

I turned my non-threaded terrain mesh loading into a multi-threaded version after reading up on godot Threads, but I seem to be doing something wrong because the game still locks up for a few hundred milliseconds when loading.

I’ll simply post the code here:

	class_name TerrainZone
extends Spatial

var zone_index:int
var zone_scene_file:String

var is_loaded:bool = false

var thread:Thread

var mutex:Mutex
var load_finished:bool = false

var is_loading:bool = false


func _ready():
	thread = Thread.new()
	mutex = Mutex.new()


func load_in():
	if not is_loaded():
		if not ResourceLoader.exists(zone_scene_file):
			push_error("The zone scene does not exist at " + zone_scene_file + "!")
			return
		
		if thread.is_active():
			thread.wait_to_finish()
		
		thread.start(self, "_load_scene_file", zone_scene_file, Thread.PRIORITY_LOW)


func _load_scene_file(scene_file):
	var mesh = load(scene_file).instance() as TerrainMesh
	mesh.create_trimesh_collision()
	call_deferred("add_child", mesh)
	
	mutex.lock()
	load_finished = true
	mutex.unlock()


func is_loaded() -> bool:
	return get_child_count() > 0


func unload():
	if is_loaded():
		get_child(0).queue_free()
		is_loaded = false
	#hide()

func _exit_tree():
	thread.wait_to_finish()

Anything I’m doing that is obviously wrong? :\

thanks in advance.

You could run a debug build using a C++ profiler to determine where the bottleneck is. It’s possible that uploading the mesh through the engine (and to the GPU) is the bottleneck itself, in which case there is no way to solve this but to use smaller chunks that can be loaded more often.

Calinou | 2021-07-04 21:27