Advertisement
nezvers

Godot background load

Dec 13th, 2019
522
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.42 KB | None | 0 0
  1. extends Node
  2.  
  3. signal scene_loaded
  4.  
  5. var file
  6. var thread
  7. var mutex
  8. var semaphore
  9. var resource
  10. var exit_thread = false
  11. var props = {} #Extra info passed along loading request
  12.  
  13. func _ready():
  14.     file = File.new()
  15.     thread = Thread.new()
  16.     mutex = Mutex.new()
  17.     semaphore = Semaphore.new()
  18.     thread.start(self, "thread_func")
  19.  
  20. func load_scene(path, instruction):
  21.     mutex.lock()
  22.     if !file_check(path):
  23.         print("File does not exist: " + path)
  24.         return
  25.     mutex.unlock()
  26.    
  27.     mutex.lock()
  28.     props[path] = instruction
  29.     resource = path
  30.     mutex.unlock()
  31.    
  32.     semaphore.post()
  33.  
  34. func file_check(path)->bool:
  35.     var result = false
  36.     mutex.lock()
  37.     result = file.file_exists(path)
  38.     mutex.unlock()
  39.     return result
  40.  
  41. func thread_func(null):
  42.     while true: #Trap the function
  43.         semaphore.wait()    #start the work when semaphote.post()
  44.        
  45.         mutex.lock()
  46.         var should_exit = exit_thread # Protect with Mutex.
  47.         mutex.unlock()
  48.  
  49.         if should_exit:
  50.             break
  51.            
  52.         mutex.lock() #didn't feel like to do separate lock
  53.         var scene = load(resource)
  54.         call_deferred("emit_signal", "scene_loaded", {resource=scene, instructions = props[resource]})
  55.         mutex.unlock()
  56.  
  57. func _exit_tree(): #even autoloaded script needs to do this or bricks on quiting
  58.     mutex.lock()
  59.     exit_thread = true #this is checked in thread
  60.     mutex.unlock()
  61.    
  62.     semaphore.post()    #give last resume to the function to see it neads to break
  63.     thread.wait_to_finish() #sync the threads
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement