You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
108 lines
2.2 KiB
108 lines
2.2 KiB
package mightypork.gamecore.loading;
|
|
|
|
|
|
import java.util.concurrent.ExecutorService;
|
|
import java.util.concurrent.Executors;
|
|
import java.util.concurrent.LinkedBlockingQueue;
|
|
|
|
import mightypork.gamecore.control.bus.BusAccess;
|
|
import mightypork.gamecore.control.bus.events.MainLoopTaskRequest;
|
|
import mightypork.gamecore.control.bus.events.ResourceLoadRequest;
|
|
import mightypork.gamecore.control.interf.Destroyable;
|
|
import mightypork.utils.logging.Log;
|
|
|
|
|
|
/**
|
|
* Asynchronous resource loading thread.
|
|
*
|
|
* @author MightyPork
|
|
*/
|
|
public class AsyncResourceLoader extends Thread implements ResourceLoadRequest.Listener, Destroyable {
|
|
|
|
public static void launch(BusAccess app)
|
|
{
|
|
(new AsyncResourceLoader(app)).start();
|
|
}
|
|
|
|
private final ExecutorService exs = Executors.newCachedThreadPool();
|
|
|
|
private final LinkedBlockingQueue<DeferredResource> toLoad = new LinkedBlockingQueue<>();
|
|
private boolean stopped;
|
|
private final BusAccess app;
|
|
|
|
|
|
public AsyncResourceLoader(BusAccess app) {
|
|
super("Deferred loader");
|
|
this.app = app;
|
|
app.getEventBus().subscribe(this);
|
|
}
|
|
|
|
|
|
@Override
|
|
public void loadResource(DeferredResource resource)
|
|
{
|
|
toLoad.add(resource);
|
|
}
|
|
|
|
|
|
@Override
|
|
public void run()
|
|
{
|
|
Log.f3("Asynchronous resource loader started.");
|
|
|
|
while (!stopped) {
|
|
|
|
try {
|
|
final DeferredResource def = toLoad.take();
|
|
if (def == null) continue;
|
|
|
|
if (!def.isLoaded()) {
|
|
|
|
// skip nulls
|
|
if (def instanceof NullResource) continue;
|
|
|
|
// textures & fonts needs to be loaded in main thread
|
|
if (def.getClass().isAnnotationPresent(MustLoadInMainThread.class)) {
|
|
|
|
Log.f3("<LOADER> Delegating to main thread:\n " + Log.str(def));
|
|
|
|
app.getEventBus().send(new MainLoopTaskRequest(new Runnable() {
|
|
|
|
@Override
|
|
public void run()
|
|
{
|
|
def.load();
|
|
}
|
|
}));
|
|
|
|
continue;
|
|
}
|
|
|
|
Log.f3("<LOADER> Loading async:\n " + Log.str(def));
|
|
|
|
exs.submit(new Runnable() {
|
|
|
|
@Override
|
|
public void run()
|
|
{
|
|
def.load();
|
|
}
|
|
});
|
|
}
|
|
|
|
} catch (final InterruptedException ignored) {
|
|
//
|
|
}
|
|
|
|
}
|
|
}
|
|
|
|
|
|
@Override
|
|
public void destroy()
|
|
{
|
|
stopped = true;
|
|
exs.shutdownNow();
|
|
}
|
|
|
|
}
|
|
|