Как поделиться текстовыми сообщениями в OpenGL ES 2.0 на AndroidStudio - PullRequest
0 голосов
/ 30 июня 2019

Finally, I solved my problem thanks to Columbo.

Я делаю игру-симулятор стратегии с использованием AndroidStudio с OpenGL ES 2.0 и испытываю проблему с эффективной загрузкой изображений. Игра была разработана для загрузки всех изображений с самого начала и работала хорошо. Тем не менее, я пытался загрузить только те изображения, которые нужны на каждом экране, потому что в игре много изображений. Но я получил сообщение об ошибке E/libEGL: call to OpenGL ES API with no current context (logged once per thread) с пустым (черным) пробелом на экране, когда я попытался внести некоторые изменения.

Через Google я нашел некоторую информацию об активности, виде поверхности, рендеринге, потоке, обмене текстурами и т. Д. И устал от них. Тем не менее, любые ответы не сработали в моем приложении в AndroidStudio, и я не знаю, в чем причина. Основная проблема заключается в том, что, когда я пытался применить ответы, я не знаю, куда мне точно поместить код и пример кода, в основном относящиеся к «egl», которые выражены красным цветом, означающим ошибку в моем AndroidStudio. Ниже приведены некоторые примеры.

1. eglGetCurrentContext()
2. eglCreateContext(mEglDisplay, mEglConfig, sharedContext, contextAttribs);

Я бы хотел, чтобы мое приложение работало более эффективно. Я думаю, что совместное использование текстуры другим потоком - лучшее решение, но любое другое решение хорошо, если оно загружает изображения отдельно на каждом экране. Пожалуйста, помогите мне с реальным кодом, который может быть применен к моему приложению.

[Пояснения по поводу моего кода]

initResourceMap () выполняется, когда экран изменяется с Intro на Map, и появляется сообщение об ошибке (E/libEGL: call to OpenGL ES API with no current context (logged once per thread)).

// 1. Main Activity
public class MainActivity extends Activity {
//GLSurfaceView
private GLSurfaceView mGLSurfaceView;

//Create Activity
@Override
protected void onCreate(Bundle savedInstanceState) {
    //Matrix to create surfaceview    
    DisplayMetrics displaymetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    int height = displaymetrics.heightPixels;
    int width = displaymetrics.widthPixels;
    mGLSurfaceView = new MainGLSurfaceView(this, width, height, 1, 1);
    setContentView(mGLSurfaceView);
}
}


// 2. SurfaceView class
class MainGLSurfaceView extends GLSurfaceView {
//Renderer
private MainGLRenderer mGLRendererMain;

//Creator
public MainGLSurfaceView(MainActivity activity, int width, int height, int stage, int subStage){
    super(activity.getApplicationContext());
    //Create OpenGL ES 2.0 context
    setEGLContextClientVersion(2);
    //Create renderer by using Context to use GLSurfaceView
    mGLRendererMain = new MainGLRenderer(activity, this, width, height);
    setRenderer(mGLRendererMain);
    //Draw if changed RenderMode
    setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
}
}



// 3. Renderer
public class MainGLRenderer implements GLSurfaceView.Renderer {
// Matrix
private final float[] mMtrxProjection = new float[16];
private final float[] mMtrxView = new float[16];
private final float[] mMtrxProjectionAndView = new float[16];
// Program color, image
private static int mProgramSolidColor;
private static int mProgramImage;
long mLastTime;
// Device's width, height
public static int mDeviceWidth = 0;
public static int mDeviceHeight = 0;
// Main activity
MainActivity mActivity;
Context mContextMain;
Context mContextStory;
// Set screen
ScreenConfig mScreenConfig;

// Creator
public MainGLRenderer(MainActivity activity, MainGLSurfaceView surfaceView, int width, int height){
    mSurfaceView = surfaceView;
    mActivity = activity;
    mContextMain = activity.getApplicationContext();
    mLastTime = System.currentTimeMillis() + 100;
    mDeviceWidth = width;
    mDeviceHeight = height;
}

// Create surface view
@Override
public void onSurfaceCreated(GL10 gl, javax.microedition.khronos.egl.EGLConfig eglConfig){
    mScreenConfig = new ScreenConfig(mDeviceWidth, mDeviceHeight);
    mScreenConfig.setSize(2000, 1200);
    GLES20.glClearColor(0.0f, 0.5f, 0.0f, 1);
    int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vs_Image);
    int fragmentShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fs_Image);
    mProgramImage = GLES20.glCreateProgram();
    GLES20.glAttachShader(mProgramImage, vertexShader);
    GLES20.glAttachShader(mProgramImage, fragmentShader);
    GLES20.glLinkProgram(mProgramImage);
    GLES20.glUseProgram(mProgramImage);

    if(mIsFirstCalled){
        init();
    }
    else {
        initResourceIntro();
        mResourceLoadingMain.setResourceIntro(mSubject, mRyubiIntro, mGwanuIntro,
                mJangbiIntro, mBtnEnter);
        mResourceLoadingMain.setResourceMap(mPanelMap, mCity, mCityName, mRyubiMap, mGwanuMap,
                mJangbiMap, mChochoMap, mHahudonMap, mJanghabMap, mBtnExit);
        mResourceLoadingMain.setResourceGame(mOurForce, mOurForceEnergy, mOurForceWord,
                mEnemyForce, mEnemyForceEnergy, mEnemyForceWord, Map.mLand);
    }
    mIsFirstCalled = false;

    mMoveInputX = 1000;
    mMoveInputY = 600;
}

private void init(){
    initResourceIntro();
    initObject();
    initIntro();
}

private void initResourceIntro(){
    float scale = mContextMain.getResources().getDisplayMetrics().density;
    mResourceLoadingMain = new ResourceLoading(mActivity, mContextMain, scale);
    mResourceLoadingMain.initResource();
}

private void initResourceMap(MainActivity activity){
    mSurfaceView.restartRenderer(activity, mDeviceWidth, mDeviceHeight);
    mContextStory = activity.getApplicationContext();
    float scale = mContextStory.getResources().getDisplayMetrics().density;
    mResourceLoadingStory = new ResourceLoading(mActivity, mContextStory, scale);
    mResourceLoadingStory.initResource();
}
}
...