LibGDX - 异步加载和处理纹理

时间:2015-06-10 06:40:34

标签: java android opengl-es libgdx

关于使用LibGDX中的Assets异步加载纹理,有一些讨论。据我所知,LibGDX使用2种方法(异步和同步)来加载数据。如果它依赖于使用OpenGL函数,它使用带有GL上下文的主线程并同步执行,否则异步。

我需要异步加载和处理纹理。加载很快完成。不幸的是,我不能对流程说同样的话。这个过程是纹理的一些变形,需要很多时间。出于这个原因,我试图分开如下的线程:

 public void load(final String filename){
    if(callback!=null && !isLoading){   
    //WE NEED TO USE THIS FUNC AS DESCRIBED IN LIBGDX MANUAL        
        Gdx.app.postRunnable(new Runnable() {               
            @Override
            public void run() {                 
                //SIMULATE HEAVY PROCESS                                                
                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {                      
                        e.printStackTrace();
                    }

                    if(callback!=null){
                        callback.onComplete(filename);                          
                    }                       
            }
        });
 }

//JAVA CLASS HAS THE SAME BEHAVIOUR
 new Thread(new Runnable() {                
            @Override
            public void run() {
                //SIMULATE HEAVY PROCESS                                                
                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {                      
                        e.printStackTrace();
                    }

                    if(callback!=null){
                        callback.onComplete(filename);                          
                    }                   
            }
        }).run();

此线程停止主线程10秒。为什么?所以,我可以假设这个线程在主线程内部执行。重点是什么?可以在LibGDX中分离线程吗?如何在2个线程之间共享GL上下文? 顺便说一下,我找到了example,但它不适合LibGDX。

还有一个有趣的课程here,上面写着:

/*
To handle an event you will typically subclass GLSurfaceView and override the
appropriate method, just as you would with any other View. However, when handling
the event, you may need to communicate with the Renderer object
that's running in the rendering thread. You can do this using any
standard Java cross-thread communication mechanism. In addition,
one relatively easy way to communicate with your renderer is
to call
For example:
*/
class MyGLSurfaceView extends GLSurfaceView {
private MyRenderer mMyRenderer;

public void start() {
  mMyRenderer = ...;
  setRenderer(mMyRenderer);
}

public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
queueEvent(new Runnable() {
// This method will be called on the rendering
// thread:
public void run() {
  mMyRenderer.handleDpadCenter();
}});
return true;
}
 return super.onKeyDown(keyCode, event);
}
}

1 个答案:

答案 0 :(得分:4)

  1. 您无法在线程之间共享GL上下文。

  2. Gdx.app.postRunnable()没有启动新线程,它只是将Runnable添加到主线程,然后在下一帧中处理。这就是你的主线程停止的原因。

  3. 更多:https://github.com/libgdx/libgdx/wiki/Threading