准备给游戏加入一个Loading画面,采用多线程,前面很顺利,但是就是载入后精灵无法正常显示,看不见纹理,开始以为是使用DevIL库出问题,单步调试发现DevIL载入图片正常,而opengl的glGenTextures出错了,返回的索引总是0。
后来google在gamedev上找到答案,原来opengl不是线程安全的(不知道正确不?),找到了关键方向:wglCreateContext.
后来在msdn上找到API解释,以及代码实例:
HDC hdc;
HGLRC hglrc;
// create a rendering context
hglrc = wglCreateContext (hdc);
// make it the calling thread's current rendering context
wglMakeCurrent (hdc, hglrc);
// call OpenGL APIs as desired ...
// when the rendering context is no longer needed ...
// make the rendering context not current
wglMakeCurrent (NULL, NULL) ;
// delete the rendering context
wglDeleteContext (hglrc);
只要hdc一样,创建的context都会渲染到相同的设备上面
但是实验很久,都没成功,最后发现是少了一个函数:wglShareLists(HGLRC hglrc1, HGLRC hglrc2)
注:hglrc1分享hglrc2的资源
// 创建多线程
// 获取当前hdc
HDC hDC = GetDC(hWnd);
// 创建渲染context
HGLRC hrc1 = wglCreateContext(hDC);
// 分享资源
wglShareLists(wglGetCurrentContext(), hrc1);
...
...
// 载入资源的时候
wglMakeCurrent(hDC, hrc1);
...
...
// 使用后
wglMakeCurrent(NULL, NULL);
wglDeleteContext(hrc1);