2 * WINED3D draw functions
4 * Copyright 2002-2004 Jason Edmeades
5 * Copyright 2002-2004 Raphael Junqueira
6 * Copyright 2004 Christian Costa
7 * Copyright 2005 Oliver Stieber
8 * Copyright 2006 Henri Verbeet
9 * Copyright 2007 Stefan Dösinger for CodeWeavers
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation; either
14 * version 2.1 of the License, or (at your option) any later version.
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with this library; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
27 #include "wined3d_private.h"
29 WINE_DEFAULT_DEBUG_CHANNEL(d3d_draw);
30 #define GLINFO_LOCATION This->adapter->gl_info
35 extern IWineD3DVertexShaderImpl* VertexShaders[64];
36 extern IWineD3DVertexDeclarationImpl* VertexShaderDeclarations[64];
37 extern IWineD3DPixelShaderImpl* PixelShaders[64];
39 #undef GL_VERSION_1_4 /* To be fixed, caused by mesa headers */
42 /* Issues the glBegin call for gl given the primitive type and count */
43 static DWORD primitiveToGl(WINED3DPRIMITIVETYPE PrimitiveType,
47 DWORD NumVertexes = NumPrimitives;
49 switch (PrimitiveType) {
50 case WINED3DPT_POINTLIST:
52 *primType = GL_POINTS;
53 NumVertexes = NumPrimitives;
56 case WINED3DPT_LINELIST:
59 NumVertexes = NumPrimitives * 2;
62 case WINED3DPT_LINESTRIP:
63 TRACE("LINE_STRIP\n");
64 *primType = GL_LINE_STRIP;
65 NumVertexes = NumPrimitives + 1;
68 case WINED3DPT_TRIANGLELIST:
70 *primType = GL_TRIANGLES;
71 NumVertexes = NumPrimitives * 3;
74 case WINED3DPT_TRIANGLESTRIP:
75 TRACE("TRIANGLE_STRIP\n");
76 *primType = GL_TRIANGLE_STRIP;
77 NumVertexes = NumPrimitives + 2;
80 case WINED3DPT_TRIANGLEFAN:
81 TRACE("TRIANGLE_FAN\n");
82 *primType = GL_TRIANGLE_FAN;
83 NumVertexes = NumPrimitives + 2;
87 FIXME("Unhandled primitive\n");
88 *primType = GL_POINTS;
94 static BOOL fixed_get_input(
95 BYTE usage, BYTE usage_idx,
96 unsigned int* regnum) {
100 /* Those positions must have the order in the
101 * named part of the strided data */
103 if ((usage == WINED3DDECLUSAGE_POSITION || usage == WINED3DDECLUSAGE_POSITIONT) && usage_idx == 0)
105 else if (usage == WINED3DDECLUSAGE_BLENDWEIGHT && usage_idx == 0)
107 else if (usage == WINED3DDECLUSAGE_BLENDINDICES && usage_idx == 0)
109 else if (usage == WINED3DDECLUSAGE_NORMAL && usage_idx == 0)
111 else if (usage == WINED3DDECLUSAGE_PSIZE && usage_idx == 0)
113 else if (usage == WINED3DDECLUSAGE_COLOR && usage_idx == 0)
115 else if (usage == WINED3DDECLUSAGE_COLOR && usage_idx == 1)
117 else if (usage == WINED3DDECLUSAGE_TEXCOORD && usage_idx < WINED3DDP_MAXTEXCOORD)
118 *regnum = 7 + usage_idx;
119 else if ((usage == WINED3DDECLUSAGE_POSITION || usage == WINED3DDECLUSAGE_POSITIONT) && usage_idx == 1)
120 *regnum = 7 + WINED3DDP_MAXTEXCOORD;
121 else if (usage == WINED3DDECLUSAGE_NORMAL && usage_idx == 1)
122 *regnum = 8 + WINED3DDP_MAXTEXCOORD;
123 else if (usage == WINED3DDECLUSAGE_TANGENT && usage_idx == 0)
124 *regnum = 9 + WINED3DDP_MAXTEXCOORD;
125 else if (usage == WINED3DDECLUSAGE_BINORMAL && usage_idx == 0)
126 *regnum = 10 + WINED3DDP_MAXTEXCOORD;
127 else if (usage == WINED3DDECLUSAGE_TESSFACTOR && usage_idx == 0)
128 *regnum = 11 + WINED3DDP_MAXTEXCOORD;
129 else if (usage == WINED3DDECLUSAGE_FOG && usage_idx == 0)
130 *regnum = 12 + WINED3DDP_MAXTEXCOORD;
131 else if (usage == WINED3DDECLUSAGE_DEPTH && usage_idx == 0)
132 *regnum = 13 + WINED3DDP_MAXTEXCOORD;
133 else if (usage == WINED3DDECLUSAGE_SAMPLE && usage_idx == 0)
134 *regnum = 14 + WINED3DDP_MAXTEXCOORD;
137 FIXME("Unsupported input stream [usage=%s, usage_idx=%u]\n",
138 debug_d3ddeclusage(usage), usage_idx);
144 void primitiveDeclarationConvertToStridedData(
145 IWineD3DDevice *iface,
146 BOOL useVertexShaderFunction,
147 WineDirect3DVertexStridedData *strided,
150 /* We need to deal with frequency data!*/
153 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
154 IWineD3DVertexDeclarationImpl* vertexDeclaration = (IWineD3DVertexDeclarationImpl *)This->stateBlock->vertexDecl;
156 WINED3DVERTEXELEMENT *element;
159 DWORD numPreloadStreams = This->stateBlock->streamIsUP ? 0 : vertexDeclaration->num_streams;
160 DWORD *streams = vertexDeclaration->streams;
162 /* Check for transformed vertices, disable vertex shader if present */
163 strided->u.s.position_transformed = vertexDeclaration->position_transformed;
164 if(vertexDeclaration->position_transformed) {
165 useVertexShaderFunction = FALSE;
168 /* Translate the declaration into strided data */
169 for (i = 0 ; i < vertexDeclaration->declarationWNumElements - 1; ++i) {
174 element = vertexDeclaration->pDeclarationWine + i;
175 TRACE("%p Element %p (%d of %d)\n", vertexDeclaration->pDeclarationWine,
176 element, i + 1, vertexDeclaration->declarationWNumElements - 1);
178 if (This->stateBlock->streamSource[element->Stream] == NULL)
181 stride = This->stateBlock->streamStride[element->Stream];
182 if (This->stateBlock->streamIsUP) {
183 TRACE("Stream is up %d, %p\n", element->Stream, This->stateBlock->streamSource[element->Stream]);
185 data = (BYTE *)This->stateBlock->streamSource[element->Stream];
187 TRACE("Stream isn't up %d, %p\n", element->Stream, This->stateBlock->streamSource[element->Stream]);
188 data = IWineD3DVertexBufferImpl_GetMemory(This->stateBlock->streamSource[element->Stream], 0, &streamVBO);
190 /* Can't use vbo's if the base vertex index is negative. OpenGL doesn't accept negative offsets
191 * (or rather offsets bigger than the vbo, because the pointer is unsigned), so use system memory
192 * sources. In most sane cases the pointer - offset will still be > 0, otherwise it will wrap
193 * around to some big value. Hope that with the indices, the driver wraps it back internally. If
194 * not, drawStridedSlow is needed, including a vertex buffer path.
196 if(This->stateBlock->loadBaseVertexIndex < 0) {
197 WARN("loadBaseVertexIndex is < 0 (%d), not using vbos\n", This->stateBlock->loadBaseVertexIndex);
199 data = ((IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[element->Stream])->resource.allocatedMemory;
200 if(data + This->stateBlock->loadBaseVertexIndex * stride < 0) {
201 FIXME("System memory vertex data load offset is negative!\n");
206 if( streamVBO != 0) *fixup = TRUE;
207 else if(*fixup && !useVertexShaderFunction &&
208 (element->Usage == WINED3DDECLUSAGE_COLOR ||
209 element->Usage == WINED3DDECLUSAGE_POSITIONT)) {
210 /* This may be bad with the fixed function pipeline */
211 FIXME("Missing vbo streams with unfixed colors or transformed position, expect problems\n");
215 data += element->Offset;
218 TRACE("Offset %d Stream %d UsageIndex %d\n", element->Offset, element->Stream, element->UsageIndex);
220 if (useVertexShaderFunction)
221 stride_used = vshader_get_input(This->stateBlock->vertexShader,
222 element->Usage, element->UsageIndex, &idx);
224 stride_used = fixed_get_input(element->Usage, element->UsageIndex, &idx);
227 TRACE("Loaded %s array %u [usage=%s, usage_idx=%u, "
228 "stream=%u, offset=%u, stride=%u, type=%s, VBO=%u]\n",
229 useVertexShaderFunction? "shader": "fixed function", idx,
230 debug_d3ddeclusage(element->Usage), element->UsageIndex,
231 element->Stream, element->Offset, stride, debug_d3ddecltype(element->Type), streamVBO);
233 strided->u.input[idx].lpData = data;
234 strided->u.input[idx].dwType = element->Type;
235 strided->u.input[idx].dwStride = stride;
236 strided->u.input[idx].VBO = streamVBO;
237 strided->u.input[idx].streamNo = element->Stream;
240 /* Now call PreLoad on all the vertex buffers. In the very rare case
241 * that the buffers stopps converting PreLoad will dirtify the VDECL again.
242 * The vertex buffer can now use the strided structure in the device instead of finding its
245 * NULL streams won't be recorded in the array, UP streams won't be either. A stream is only
248 for(i=0; i < numPreloadStreams; i++) {
249 IWineD3DVertexBuffer_PreLoad(This->stateBlock->streamSource[streams[i]]);
253 static void drawStridedFast(IWineD3DDevice *iface,UINT numberOfVertices, GLenum glPrimitiveType,
254 const void *idxData, short idxSize, ULONG minIndex, ULONG startIdx, ULONG startVertex) {
255 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
257 if (idxSize != 0 /* This crashes sometimes!*/) {
258 TRACE("(%p) : glElements(%x, %d, %d, ...)\n", This, glPrimitiveType, numberOfVertices, minIndex);
259 idxData = idxData == (void *)-1 ? NULL : idxData;
261 glDrawElements(glPrimitiveType, numberOfVertices, idxSize == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT,
262 (const char *)idxData+(idxSize * startIdx));
263 checkGLcall("glDrawElements");
264 #else /* using drawRangeElements may be faster */
266 glDrawRangeElements(glPrimitiveType, minIndex, minIndex + numberOfVertices - 1, numberOfVertices,
267 idxSize == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT,
268 (const char *)idxData+(idxSize * startIdx));
269 checkGLcall("glDrawRangeElements");
274 /* Note first is now zero as we shuffled along earlier */
275 TRACE("(%p) : glDrawArrays(%x, 0, %d)\n", This, glPrimitiveType, numberOfVertices);
276 glDrawArrays(glPrimitiveType, startVertex, numberOfVertices);
277 checkGLcall("glDrawArrays");
285 * Actually draw using the supplied information.
286 * Slower GL version which extracts info about each vertex in turn
289 static void drawStridedSlow(IWineD3DDevice *iface, WineDirect3DVertexStridedData *sd,
290 UINT NumVertexes, GLenum glPrimType,
291 const void *idxData, short idxSize, ULONG minIndex, ULONG startIdx, ULONG startVertex) {
293 unsigned int textureNo = 0;
294 const WORD *pIdxBufS = NULL;
295 const DWORD *pIdxBufL = NULL;
297 float x = 0.0f, y = 0.0f, z = 0.0f; /* x,y,z coordinates */
298 float rhw = 0.0f; /* rhw */
299 DWORD diffuseColor = 0xFFFFFFFF; /* Diffuse Color */
300 DWORD specularColor = 0; /* Specular Color */
301 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
302 UINT *streamOffset = This->stateBlock->streamOffset;
303 long SkipnStrides = startVertex + This->stateBlock->loadBaseVertexIndex;
305 BYTE *texCoords[WINED3DDP_MAXTEXCOORD];
306 BYTE *diffuse = NULL, *specular = NULL, *normal = NULL, *position = NULL;
308 TRACE("Using slow vertex array code\n");
310 /* Variable Initialization */
312 /* Immediate mode drawing can't make use of indices in a vbo - get the data from the index buffer.
313 * If the index buffer has no vbo(not supported or other reason), or with user pointer drawing
314 * idxData will be != NULL
316 if(idxData == NULL) {
317 idxData = ((IWineD3DIndexBufferImpl *) This->stateBlock->pIndexData)->resource.allocatedMemory;
320 if (idxSize == 2) pIdxBufS = (const WORD *) idxData;
321 else pIdxBufL = (const DWORD *) idxData;
324 /* Adding the stream offset once is cheaper than doing it every iteration. Do not modify the strided data, it is a pointer
325 * to the strided Data in the device and might be needed intact on the next draw
327 for (textureNo = 0; textureNo < GL_LIMITS(texture_stages); ++textureNo) {
328 if(sd->u.s.texCoords[textureNo].lpData) {
329 texCoords[textureNo] = sd->u.s.texCoords[textureNo].lpData + streamOffset[sd->u.s.texCoords[textureNo].streamNo];
331 texCoords[textureNo] = NULL;
334 if(sd->u.s.diffuse.lpData) {
335 diffuse = sd->u.s.diffuse.lpData + streamOffset[sd->u.s.diffuse.streamNo];
337 if(sd->u.s.specular.lpData) {
338 specular = sd->u.s.specular.lpData + streamOffset[sd->u.s.specular.streamNo];
340 if(sd->u.s.normal.lpData) {
341 normal = sd->u.s.normal.lpData + streamOffset[sd->u.s.normal.streamNo];
343 if(sd->u.s.position.lpData) {
344 position = sd->u.s.position.lpData + streamOffset[sd->u.s.position.streamNo];
347 /* Start drawing in GL */
348 VTRACE(("glBegin(%x)\n", glPrimType));
351 /* Default settings for data that is not passed */
352 if (sd->u.s.normal.lpData == NULL) {
355 if(sd->u.s.diffuse.lpData == NULL) {
356 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
358 if(sd->u.s.specular.lpData == NULL) {
359 if (GL_SUPPORT(EXT_SECONDARY_COLOR)) {
360 GL_EXTCALL(glSecondaryColor3fEXT)(0, 0, 0);
364 /* We shouldn't start this function if any VBO is involved. Should I put a safety check here?
365 * Guess it's not necessary(we crash then anyway) and would only eat CPU time
368 /* For each primitive */
369 for (vx_index = 0; vx_index < NumVertexes; ++vx_index) {
371 /* Initialize diffuse color */
372 diffuseColor = 0xFFFFFFFF;
374 /* Blending data and Point sizes are not supported by this function. They are not supported by the fixed
375 * function pipeline at all. A Fixme for them is printed after decoding the vertex declaration
378 /* For indexed data, we need to go a few more strides in */
379 if (idxData != NULL) {
381 /* Indexed so work out the number of strides to skip */
383 VTRACE(("Idx for vertex %d = %d\n", vx_index, pIdxBufS[startIdx+vx_index]));
384 SkipnStrides = pIdxBufS[startIdx + vx_index] + This->stateBlock->loadBaseVertexIndex;
386 VTRACE(("Idx for vertex %d = %d\n", vx_index, pIdxBufL[startIdx+vx_index]));
387 SkipnStrides = pIdxBufL[startIdx + vx_index] + This->stateBlock->loadBaseVertexIndex;
391 /* Texture coords --------------------------- */
392 for (textureNo = 0; textureNo < GL_LIMITS(texture_stages); ++textureNo) {
394 if (!GL_SUPPORT(ARB_MULTITEXTURE) && textureNo > 0) {
395 FIXME("Program using multiple concurrent textures which this opengl implementation doesn't support\n");
399 /* Query tex coords */
400 if (This->stateBlock->textures[textureNo] != NULL) {
402 int coordIdx = This->stateBlock->textureState[textureNo][WINED3DTSS_TEXCOORDINDEX];
403 float *ptrToCoords = NULL;
404 float s = 0.0, t = 0.0, r = 0.0, q = 0.0;
407 VTRACE(("tex: %d - Skip tex coords, as being system generated\n", textureNo));
409 } else if (coordIdx < 0) {
410 FIXME("tex: %d - Coord index %d is less than zero, expect a crash.\n", textureNo, coordIdx);
414 ptrToCoords = (float *)(texCoords[coordIdx] + (SkipnStrides * sd->u.s.texCoords[coordIdx].dwStride));
415 if (texCoords[coordIdx] == NULL) {
416 TRACE("tex: %d - Skipping tex coords, as no data supplied\n", textureNo);
417 glTexCoord4f(0, 0, 0, 1);
420 int texture_idx = This->texUnitMap[textureNo];
421 int coordsToUse = sd->u.s.texCoords[coordIdx].dwType + 1; /* 0 == WINED3DDECLTYPE_FLOAT1 etc */
423 if (texture_idx == -1) continue;
425 /* The coords to supply depend completely on the fvf / vertex shader */
426 switch (coordsToUse) {
427 case 4: q = ptrToCoords[3]; /* drop through */
428 case 3: r = ptrToCoords[2]; /* drop through */
429 case 2: t = ptrToCoords[1]; /* drop through */
430 case 1: s = ptrToCoords[0];
433 switch (coordsToUse) { /* Supply the provided texture coords */
434 case WINED3DTTFF_COUNT1:
435 VTRACE(("tex:%d, s=%f\n", textureNo, s));
436 if (GL_SUPPORT(ARB_MULTITEXTURE)) {
437 GL_EXTCALL(glMultiTexCoord1fARB(GL_TEXTURE0_ARB + texture_idx, s));
442 case WINED3DTTFF_COUNT2:
443 VTRACE(("tex:%d, s=%f, t=%f\n", textureNo, s, t));
444 if (GL_SUPPORT(ARB_MULTITEXTURE)) {
445 GL_EXTCALL(glMultiTexCoord2fARB(GL_TEXTURE0_ARB + texture_idx, s, t));
450 case WINED3DTTFF_COUNT3:
451 VTRACE(("tex:%d, s=%f, t=%f, r=%f\n", textureNo, s, t, r));
452 if (GL_SUPPORT(ARB_MULTITEXTURE)) {
453 GL_EXTCALL(glMultiTexCoord3fARB(GL_TEXTURE0_ARB + texture_idx, s, t, r));
455 glTexCoord3f(s, t, r);
458 case WINED3DTTFF_COUNT4:
459 VTRACE(("tex:%d, s=%f, t=%f, r=%f, q=%f\n", textureNo, s, t, r, q));
460 if (GL_SUPPORT(ARB_MULTITEXTURE)) {
461 GL_EXTCALL(glMultiTexCoord4fARB(GL_TEXTURE0_ARB + texture_idx, s, t, r, q));
463 glTexCoord4f(s, t, r, q);
467 FIXME("Should not get here as coordsToUse is two bits only (%x)!\n", coordsToUse);
471 } /* End of textures */
473 /* Diffuse -------------------------------- */
475 DWORD *ptrToCoords = (DWORD *)(diffuse + (SkipnStrides * sd->u.s.diffuse.dwStride));
476 diffuseColor = ptrToCoords[0];
477 VTRACE(("diffuseColor=%lx\n", diffuseColor));
479 glColor4ub(D3DCOLOR_B_R(diffuseColor),
480 D3DCOLOR_B_G(diffuseColor),
481 D3DCOLOR_B_B(diffuseColor),
482 D3DCOLOR_B_A(diffuseColor));
483 VTRACE(("glColor4ub: r,g,b,a=%lu,%lu,%lu,%lu\n",
484 D3DCOLOR_B_R(diffuseColor),
485 D3DCOLOR_B_G(diffuseColor),
486 D3DCOLOR_B_B(diffuseColor),
487 D3DCOLOR_B_A(diffuseColor)));
489 if(This->activeContext->num_untracked_materials) {
492 color[0] = D3DCOLOR_B_R(diffuseColor) / 255.0;
493 color[1] = D3DCOLOR_B_G(diffuseColor) / 255.0;
494 color[2] = D3DCOLOR_B_B(diffuseColor) / 255.0;
495 color[3] = D3DCOLOR_B_A(diffuseColor) / 255.0;
497 for(i = 0; i < This->activeContext->num_untracked_materials; i++) {
498 glMaterialfv(GL_FRONT_AND_BACK, This->activeContext->untracked_materials[i], color);
503 /* Specular ------------------------------- */
505 DWORD *ptrToCoords = (DWORD *)(specular + (SkipnStrides * sd->u.s.specular.dwStride));
506 specularColor = ptrToCoords[0];
507 VTRACE(("specularColor=%lx\n", specularColor));
509 /* special case where the fog density is stored in the specular alpha channel */
510 if(This->stateBlock->renderState[WINED3DRS_FOGENABLE] &&
511 (This->stateBlock->renderState[WINED3DRS_FOGVERTEXMODE] == WINED3DFOG_NONE || sd->u.s.position.dwType == WINED3DDECLTYPE_FLOAT4 )&&
512 This->stateBlock->renderState[WINED3DRS_FOGTABLEMODE] == WINED3DFOG_NONE) {
513 if(GL_SUPPORT(EXT_FOG_COORD)) {
514 GL_EXTCALL(glFogCoordfEXT(specularColor >> 24));
516 static BOOL warned = FALSE;
518 /* TODO: Use the fog table code from old ddraw */
519 FIXME("Implement fog for transformed vertices in software\n");
525 VTRACE(("glSecondaryColor4ub: r,g,b=%lu,%lu,%lu\n",
526 D3DCOLOR_B_R(specularColor),
527 D3DCOLOR_B_G(specularColor),
528 D3DCOLOR_B_B(specularColor)));
529 if (GL_SUPPORT(EXT_SECONDARY_COLOR)) {
530 GL_EXTCALL(glSecondaryColor3ubEXT)(
531 D3DCOLOR_B_R(specularColor),
532 D3DCOLOR_B_G(specularColor),
533 D3DCOLOR_B_B(specularColor));
535 /* Do not worry if specular colour missing and disable request */
536 VTRACE(("Specular color extensions not supplied\n"));
540 /* Normal -------------------------------- */
541 if (normal != NULL) {
542 float *ptrToCoords = (float *)(normal + (SkipnStrides * sd->u.s.normal.dwStride));
544 VTRACE(("glNormal:nx,ny,nz=%f,%f,%f\n", ptrToCoords[0], ptrToCoords[1], ptrToCoords[2]));
545 glNormal3f(ptrToCoords[0], ptrToCoords[1], ptrToCoords[2]);
548 /* Position -------------------------------- */
550 float *ptrToCoords = (float *)(position + (SkipnStrides * sd->u.s.position.dwStride));
555 VTRACE(("x,y,z=%f,%f,%f\n", x,y,z));
557 /* RHW follows, only if transformed, ie 4 floats were provided */
558 if (sd->u.s.position_transformed) {
559 rhw = ptrToCoords[3];
560 VTRACE(("rhw=%f\n", rhw));
563 if (1.0f == rhw || ((rhw < eps) && (rhw > -eps))) {
564 VTRACE(("Vertex: glVertex:x,y,z=%f,%f,%f\n", x,y,z));
567 GLfloat w = 1.0 / rhw;
568 VTRACE(("Vertex: glVertex:x,y,z=%f,%f,%f / rhw=%f\n", x,y,z,rhw));
569 glVertex4f(x*w, y*w, z*w, w);
573 /* For non indexed mode, step onto next parts */
574 if (idxData == NULL) {
580 checkGLcall("glEnd and previous calls");
583 static void depth_blt(IWineD3DDevice *iface, GLuint texture) {
584 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
585 GLint old_binding = 0;
587 glPushAttrib(GL_ENABLE_BIT | GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
589 glDisable(GL_CULL_FACE);
591 glDisable(GL_ALPHA_TEST);
592 glDisable(GL_SCISSOR_TEST);
593 glDisable(GL_STENCIL_TEST);
594 glEnable(GL_DEPTH_TEST);
595 glDepthFunc(GL_ALWAYS);
596 glBlendFunc(GL_ZERO, GL_ONE);
598 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
599 glGetIntegerv(GL_TEXTURE_BINDING_2D, &old_binding);
600 glBindTexture(GL_TEXTURE_2D, texture);
601 glEnable(GL_TEXTURE_2D);
603 This->shader_backend->shader_select_depth_blt(iface);
605 glBegin(GL_TRIANGLE_STRIP);
606 glVertex2f(-1.0f, -1.0f);
607 glVertex2f(1.0f, -1.0f);
608 glVertex2f(-1.0f, 1.0f);
609 glVertex2f(1.0f, 1.0f);
612 glBindTexture(GL_TEXTURE_2D, old_binding);
616 /* Reselect the old shaders. There doesn't seem to be any glPushAttrib bit for arb shaders,
617 * and this seems easier and more efficient than providing the shader backend with a private
618 * storage to read and restore the old shader settings
620 This->shader_backend->shader_select(iface, use_ps(This), use_vs(This));
623 static void depth_copy(IWineD3DDevice *iface) {
624 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
625 IWineD3DSurfaceImpl *depth_stencil = (IWineD3DSurfaceImpl *)This->depthStencilBuffer;
627 /* Only copy the depth buffer if there is one. */
628 if (!depth_stencil) return;
630 /* TODO: Make this work for modes other than FBO */
631 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) return;
633 if (depth_stencil->current_renderbuffer) {
634 FIXME("Not supported with fixed up depth stencil\n");
638 if (This->render_offscreen) {
639 static GLuint tmp_texture = 0;
640 GLint old_binding = 0;
642 TRACE("Copying onscreen depth buffer to offscreen surface\n");
645 glGenTextures(1, &tmp_texture);
648 /* Note that we use depth_blt here as well, rather than glCopyTexImage2D
649 * directly on the FBO texture. That's because we need to flip. */
650 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
651 glGetIntegerv(GL_TEXTURE_BINDING_2D, &old_binding);
652 glBindTexture(GL_TEXTURE_2D, tmp_texture);
653 glCopyTexImage2D(depth_stencil->glDescription.target,
654 depth_stencil->glDescription.level,
655 depth_stencil->glDescription.glFormatInternal,
658 depth_stencil->currentDesc.Width,
659 depth_stencil->currentDesc.Height,
661 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
662 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
663 glTexParameteri(GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE_ARB, GL_LUMINANCE);
664 glBindTexture(GL_TEXTURE_2D, old_binding);
666 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, This->fbo));
667 checkGLcall("glBindFramebuffer()");
668 depth_blt(iface, tmp_texture);
669 checkGLcall("depth_blt");
671 TRACE("Copying offscreen surface to onscreen depth buffer\n");
673 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
674 checkGLcall("glBindFramebuffer()");
675 depth_blt(iface, depth_stencil->glDescription.textureName);
676 checkGLcall("depth_blt");
680 static inline void drawStridedInstanced(IWineD3DDevice *iface, WineDirect3DVertexStridedData *sd, UINT numberOfVertices,
681 GLenum glPrimitiveType, const void *idxData, short idxSize, ULONG minIndex,
682 ULONG startIdx, ULONG startVertex) {
683 UINT numInstances = 0;
684 int numInstancedAttribs = 0, i, j;
685 UINT instancedData[sizeof(sd->u.input) / sizeof(sd->u.input[0]) /* 16 */];
686 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
687 IWineD3DStateBlockImpl *stateblock = This->stateBlock;
690 /* This is a nasty thing. MSDN says no hardware supports that and apps have to use software vertex processing.
691 * We don't support this for now
693 * Shouldn't be too hard to support with opengl, in theory just call glDrawArrays instead of drawElements.
694 * But the StreamSourceFreq value has a different meaning in that situation.
696 FIXME("Non-indexed instanced drawing is not supported\n");
700 TRACE("(%p) : glElements(%x, %d, %d, ...)\n", This, glPrimitiveType, numberOfVertices, minIndex);
701 idxData = idxData == (void *)-1 ? NULL : idxData;
703 /* First, figure out how many instances we have to draw */
704 for(i = 0; i < MAX_STREAMS; i++) {
705 /* Look at all non-instanced streams */
706 if(!(stateblock->streamFlags[i] & WINED3DSTREAMSOURCE_INSTANCEDATA) &&
707 stateblock->streamSource[i]) {
708 int inst = stateblock->streamFreq[i];
710 if(numInstances && inst != numInstances) {
711 ERR("Two streams specify a different number of instances. Got %d, new is %d\n", numInstances, inst);
717 for(i = 0; i < sizeof(sd->u.input) / sizeof(sd->u.input[0]); i++) {
718 if(stateblock->streamFlags[sd->u.input[i].streamNo] & WINED3DSTREAMSOURCE_INSTANCEDATA) {
719 instancedData[numInstancedAttribs] = i;
720 numInstancedAttribs++;
724 /* now draw numInstances instances :-) */
725 for(i = 0; i < numInstances; i++) {
726 /* Specify the instanced attributes using immediate mode calls */
727 for(j = 0; j < numInstancedAttribs; j++) {
728 BYTE *ptr = sd->u.input[instancedData[j]].lpData +
729 sd->u.input[instancedData[j]].dwStride * i +
730 stateblock->streamOffset[sd->u.input[instancedData[j]].streamNo];
731 if(sd->u.input[instancedData[j]].VBO) {
732 IWineD3DVertexBufferImpl *vb = (IWineD3DVertexBufferImpl *) stateblock->streamSource[sd->u.input[instancedData[j]].streamNo];
733 ptr += (long) vb->resource.allocatedMemory;
736 switch(sd->u.input[instancedData[j]].dwType) {
737 case WINED3DDECLTYPE_FLOAT1:
738 GL_EXTCALL(glVertexAttrib1fvARB(instancedData[j], (float *) ptr));
740 case WINED3DDECLTYPE_FLOAT2:
741 GL_EXTCALL(glVertexAttrib2fvARB(instancedData[j], (float *) ptr));
743 case WINED3DDECLTYPE_FLOAT3:
744 GL_EXTCALL(glVertexAttrib3fvARB(instancedData[j], (float *) ptr));
746 case WINED3DDECLTYPE_FLOAT4:
747 GL_EXTCALL(glVertexAttrib4fvARB(instancedData[j], (float *) ptr));
750 case WINED3DDECLTYPE_UBYTE4:
751 GL_EXTCALL(glVertexAttrib4ubvARB(instancedData[j], ptr));
753 case WINED3DDECLTYPE_UBYTE4N:
754 case WINED3DDECLTYPE_D3DCOLOR:
755 GL_EXTCALL(glVertexAttrib4NubvARB(instancedData[j], ptr));
758 case WINED3DDECLTYPE_SHORT2:
759 GL_EXTCALL(glVertexAttrib4svARB(instancedData[j], (GLshort *) ptr));
761 case WINED3DDECLTYPE_SHORT4:
762 GL_EXTCALL(glVertexAttrib4svARB(instancedData[j], (GLshort *) ptr));
765 case WINED3DDECLTYPE_SHORT2N:
767 GLshort s[4] = {((short *) ptr)[0], ((short *) ptr)[1], 0, 1};
768 GL_EXTCALL(glVertexAttrib4NsvARB(instancedData[j], s));
771 case WINED3DDECLTYPE_USHORT2N:
773 GLushort s[4] = {((unsigned short *) ptr)[0], ((unsigned short *) ptr)[1], 0, 1};
774 GL_EXTCALL(glVertexAttrib4NusvARB(instancedData[j], s));
777 case WINED3DDECLTYPE_SHORT4N:
778 GL_EXTCALL(glVertexAttrib4NsvARB(instancedData[j], (GLshort *) ptr));
780 case WINED3DDECLTYPE_USHORT4N:
781 GL_EXTCALL(glVertexAttrib4NusvARB(instancedData[j], (GLushort *) ptr));
784 case WINED3DDECLTYPE_UDEC3:
785 FIXME("Unsure about WINED3DDECLTYPE_UDEC3\n");
786 /*glVertexAttrib3usvARB(instancedData[j], (GLushort *) ptr); Does not exist */
788 case WINED3DDECLTYPE_DEC3N:
789 FIXME("Unsure about WINED3DDECLTYPE_DEC3N\n");
790 /*glVertexAttrib3NusvARB(instancedData[j], (GLushort *) ptr); Does not exist */
793 case WINED3DDECLTYPE_FLOAT16_2:
794 /* Are those 16 bit floats. C doesn't have a 16 bit float type. I could read the single bits and calculate a 4
795 * byte float according to the IEEE standard
797 if (GL_SUPPORT(NV_HALF_FLOAT)) {
798 GL_EXTCALL(glVertexAttrib2hvNV(instancedData[j], (GLhalfNV *)ptr));
800 FIXME("Unsupported WINED3DDECLTYPE_FLOAT16_2\n");
803 case WINED3DDECLTYPE_FLOAT16_4:
804 if (GL_SUPPORT(NV_HALF_FLOAT)) {
805 GL_EXTCALL(glVertexAttrib4hvNV(instancedData[j], (GLhalfNV *)ptr));
807 FIXME("Unsupported WINED3DDECLTYPE_FLOAT16_4\n");
811 case WINED3DDECLTYPE_UNUSED:
813 ERR("Unexpected declaration in instanced attributes\n");
818 glDrawElements(glPrimitiveType, numberOfVertices, idxSize == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT,
819 (const char *)idxData+(idxSize * startIdx));
820 checkGLcall("glDrawElements");
828 void blt_to_drawable(IWineD3DDeviceImpl *This, IWineD3DSurfaceImpl *surface) {
829 struct coords coords[4];
832 /* TODO: This could be supported for lazy unlocking */
833 if(!(surface->Flags & SFLAG_INTEXTURE)) {
834 /* It is ok at init to be nowhere */
835 if(!(surface->Flags & SFLAG_INSYSMEM)) {
836 ERR("Blitting surfaces from sysmem not supported yet\n");
841 ActivateContext(This, This->render_targets[0], CTXUSAGE_BLIT);
844 if(surface->glDescription.target == GL_TEXTURE_2D) {
845 glBindTexture(GL_TEXTURE_2D, surface->glDescription.textureName);
846 checkGLcall("GL_TEXTURE_2D, This->glDescription.textureName)");
848 coords[0].x = 0; coords[0].y = 0; coords[0].z = 0;
849 coords[1].x = 0; coords[1].y = 1; coords[1].z = 0;
850 coords[2].x = 1; coords[2].y = 1; coords[2].z = 0;
851 coords[3].x = 1; coords[3].y = 0; coords[3].z = 0;
855 /* Must be a cube map */
856 glDisable(GL_TEXTURE_2D);
857 checkGLcall("glDisable(GL_TEXTURE_2D)");
858 glEnable(GL_TEXTURE_CUBE_MAP_ARB);
859 checkGLcall("glEnable(surface->glDescription.target)");
860 glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, surface->glDescription.textureName);
861 checkGLcall("GL_TEXTURE_CUBE_MAP_ARB, This->glDescription.textureName)");
863 switch(surface->glDescription.target) {
864 case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
865 coords[0].x = 1; coords[0].y = -1; coords[0].z = 1;
866 coords[1].x = 1; coords[1].y = 1; coords[1].z = 1;
867 coords[2].x = 1; coords[2].y = 1; coords[2].z = -1;
868 coords[3].x = 1; coords[3].y = -1; coords[3].z = -1;
871 case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
872 coords[0].x = -1; coords[0].y = -1; coords[0].z = 1;
873 coords[1].x = -1; coords[1].y = 1; coords[1].z = 1;
874 coords[2].x = -1; coords[2].y = 1; coords[2].z = -1;
875 coords[3].x = -1; coords[3].y = -1; coords[3].z = -1;
878 case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
879 coords[0].x = -1; coords[0].y = 1; coords[0].z = 1;
880 coords[1].x = 1; coords[1].y = 1; coords[1].z = 1;
881 coords[2].x = 1; coords[2].y = 1; coords[2].z = -1;
882 coords[3].x = -1; coords[3].y = 1; coords[3].z = -1;
885 case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
886 coords[0].x = -1; coords[0].y = -1; coords[0].z = 1;
887 coords[1].x = 1; coords[1].y = -1; coords[1].z = 1;
888 coords[2].x = 1; coords[2].y = -1; coords[2].z = -1;
889 coords[3].x = -1; coords[3].y = -1; coords[3].z = -1;
892 case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
893 coords[0].x = -1; coords[0].y = -1; coords[0].z = 1;
894 coords[1].x = 1; coords[1].y = -1; coords[1].z = 1;
895 coords[2].x = 1; coords[2].y = -1; coords[2].z = 1;
896 coords[3].x = -1; coords[3].y = -1; coords[3].z = 1;
899 case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
900 coords[0].x = -1; coords[0].y = -1; coords[0].z = -1;
901 coords[1].x = 1; coords[1].y = -1; coords[1].z = -1;
902 coords[2].x = 1; coords[2].y = -1; coords[2].z = -1;
903 coords[3].x = -1; coords[3].y = -1; coords[3].z = -1;
906 ERR("Unexpected texture target\n");
914 if(This->render_offscreen) {
915 coords[0].y = coords[0].y == 1 ? low_coord : 1;
916 coords[1].y = coords[1].y == 1 ? low_coord : 1;
917 coords[2].y = coords[2].y == 1 ? low_coord : 1;
918 coords[3].y = coords[3].y == 1 ? low_coord : 1;
922 glTexCoord3iv((GLint *) &coords[0]);
925 glTexCoord3iv((GLint *) &coords[1]);
926 glVertex2i(0, surface->pow2Height);
928 glTexCoord3iv((GLint *) &coords[2]);
929 glVertex2i(surface->pow2Width, surface->pow2Height);
931 glTexCoord3iv((GLint *) &coords[3]);
932 glVertex2i(surface->pow2Width, 0);
934 checkGLcall("glEnd");
936 if(surface->glDescription.target != GL_TEXTURE_2D) {
937 glEnable(GL_TEXTURE_2D);
938 checkGLcall("glEnable(GL_TEXTURE_2D)");
939 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
940 checkGLcall("glDisable(GL_TEXTURE_CUBE_MAP_ARB)");
945 /* Routine common to the draw primitive and draw indexed primitive routines */
946 void drawPrimitive(IWineD3DDevice *iface,
950 long StartVertexIndex,
951 UINT numberOfVertices,
957 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
958 IWineD3DSwapChain *swapchain;
959 IWineD3DBaseTexture *texture = NULL;
960 IWineD3DSurfaceImpl *target;
963 /* Signals other modules that a drawing is in progress and the stateblock finalized */
964 This->isInDraw = TRUE;
966 /* Invalidate the back buffer memory so LockRect will read it the next time */
967 for(i = 0; i < GL_LIMITS(buffers); i++) {
968 target = (IWineD3DSurfaceImpl *) This->render_targets[i];
970 /* TODO: Only do all that if we're going to change anything
971 * Texture container dirtification does not work quite right yet
973 if(target /*&& target->Flags & (SFLAG_INTEXTURE | SFLAG_INSYSMEM)*/) {
978 IWineD3DSurface_GetContainer((IWineD3DSurface *) target, &IID_IWineD3DSwapChain, (void **)&swapchain);
980 /* Need the surface in the drawable! */
981 if(!(target->Flags & SFLAG_INDRAWABLE) && (swapchain || wined3d_settings.offscreen_rendering_mode != ORM_FBO)) {
982 blt_to_drawable(This, target);
986 /* Onscreen target. Invalidate system memory copy and texture copy */
987 target->Flags &= ~(SFLAG_INSYSMEM | SFLAG_INTEXTURE);
988 target->Flags |= SFLAG_INDRAWABLE;
989 IWineD3DSwapChain_Release(swapchain);
990 } else if(wined3d_settings.offscreen_rendering_mode != ORM_FBO) {
991 /* Non-FBO target: Invalidate system copy, texture copy and dirtify the container */
992 IWineD3DSurface_GetContainer((IWineD3DSurface *) target, &IID_IWineD3DBaseTexture, (void **)&texture);
995 IWineD3DBaseTexture_SetDirty(texture, TRUE);
996 IWineD3DTexture_Release(texture);
999 target->Flags &= ~(SFLAG_INSYSMEM | SFLAG_INTEXTURE);
1000 target->Flags |= SFLAG_INDRAWABLE;
1002 /* FBO offscreen target. Invalidate system memory copy */
1003 target->Flags &= ~SFLAG_INSYSMEM;
1006 /* Must be an fbo render target */
1007 target->Flags &= ~SFLAG_INSYSMEM;
1008 target->Flags |= SFLAG_INTEXTURE;
1013 /* Ok, we will be updating the screen from here onwards so grab the lock */
1015 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
1017 apply_fbo_state(iface);
1021 ActivateContext(This, This->render_targets[0], CTXUSAGE_DRAWPRIM);
1024 if (This->depth_copy_state == WINED3D_DCS_COPY) {
1027 This->depth_copy_state = WINED3D_DCS_INITIAL;
1031 BOOL emulation = FALSE;
1032 WineDirect3DVertexStridedData *strided = &This->strided_streams;
1033 WineDirect3DVertexStridedData stridedlcl;
1034 /* Ok, Work out which primitive is requested and how many vertexes that
1036 UINT calculatedNumberOfindices = primitiveToGl(PrimitiveType, NumPrimitives, &glPrimType);
1037 if (numberOfVertices == 0 )
1038 numberOfVertices = calculatedNumberOfindices;
1041 if(!This->strided_streams.u.s.position_transformed && This->activeContext->num_untracked_materials &&
1042 This->stateBlock->renderState[WINED3DRS_LIGHTING]) {
1043 FIXME("Using software emulation because not all material properties could be tracked\n");
1046 else if(This->activeContext->fog_coord && This->stateBlock->renderState[WINED3DRS_FOGENABLE]) {
1047 /* Either write a pipeline replacement shader or convert the specular alpha from unsigned byte
1048 * to a float in the vertex buffer
1050 FIXME("Using software emulation because manual fog coordinates are provided\n");
1055 IWineD3DVertexBufferImpl *vb;
1057 strided = &stridedlcl;
1058 memcpy(&stridedlcl, &This->strided_streams, sizeof(stridedlcl));
1060 #define FIXVBO(type) \
1061 if(stridedlcl.u.s.type.VBO) { \
1062 vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[stridedlcl.u.s.type.streamNo]; \
1063 stridedlcl.u.s.type.VBO = 0; \
1064 stridedlcl.u.s.type.lpData = (BYTE *) ((unsigned long) stridedlcl.u.s.type.lpData + (unsigned long) vb->resource.allocatedMemory); \
1067 FIXVBO(blendWeights);
1068 FIXVBO(blendMatrixIndices);
1073 for(i = 0; i < WINED3DDP_MAXTEXCOORD; i++) FIXVBO(texCoords[i]);
1086 if (This->useDrawStridedSlow || emulation) {
1087 /* Immediate mode drawing */
1088 drawStridedSlow(iface, strided, calculatedNumberOfindices,
1089 glPrimType, idxData, idxSize, minIndex, StartIdx, StartVertexIndex);
1090 } else if(This->instancedDraw) {
1091 /* Instancing emulation with mixing immediate mode and arrays */
1092 drawStridedInstanced(iface, &This->strided_streams, calculatedNumberOfindices, glPrimType,
1093 idxData, idxSize, minIndex, StartIdx, StartVertexIndex);
1095 /* Simple array draw call */
1096 drawStridedFast(iface, calculatedNumberOfindices, glPrimType,
1097 idxData, idxSize, minIndex, StartIdx, StartVertexIndex);
1101 /* Finshed updating the screen, restore lock */
1103 TRACE("Done all gl drawing\n");
1106 #ifdef SHOW_FRAME_MAKEUP
1108 static long int primCounter = 0;
1109 /* NOTE: set primCounter to the value reported by drawprim
1110 before you want to to write frame makeup to /tmp */
1111 if (primCounter >= 0) {
1112 WINED3DLOCKED_RECT r;
1114 IWineD3DSurface_LockRect(This->renderTarget, &r, NULL, WINED3DLOCK_READONLY);
1115 sprintf(buffer, "/tmp/backbuffer_%d.tga", primCounter);
1116 TRACE("Saving screenshot %s\n", buffer);
1117 IWineD3DSurface_SaveSnapshot(This->renderTarget, buffer);
1118 IWineD3DSurface_UnlockRect(This->renderTarget);
1120 #ifdef SHOW_TEXTURE_MAKEUP
1122 IWineD3DSurface *pSur;
1124 for (textureNo = 0; textureNo < MAX_COMBINED_SAMPLERS; ++textureNo) {
1125 if (This->stateBlock->textures[textureNo] != NULL) {
1126 sprintf(buffer, "/tmp/texture_%p_%d_%d.tga", This->stateBlock->textures[textureNo], primCounter, textureNo);
1127 TRACE("Saving texture %s\n", buffer);
1128 if (IWineD3DBaseTexture_GetType(This->stateBlock->textures[textureNo]) == WINED3DRTYPE_TEXTURE) {
1129 IWineD3DTexture_GetSurfaceLevel((IWineD3DTexture *)This->stateBlock->textures[textureNo], 0, &pSur);
1130 IWineD3DSurface_SaveSnapshot(pSur, buffer);
1131 IWineD3DSurface_Release(pSur);
1133 FIXME("base Texture isn't of type texture %d\n", IWineD3DBaseTexture_GetType(This->stateBlock->textures[textureNo]));
1140 TRACE("drawprim #%d\n", primCounter);
1145 /* Control goes back to the device, stateblock values may change again */
1146 This->isInDraw = FALSE;
1149 static void normalize_normal(float *n) {
1150 float length = n[0] * n[0] + n[1] * n[1] + n[2] * n[2];
1151 if(length == 0.0) return;
1152 length = sqrt(length);
1153 n[0] = n[0] / length;
1154 n[1] = n[1] / length;
1155 n[2] = n[2] / length;
1158 /* Tesselates a high order rectangular patch into single triangles using gl evaluators
1160 * The problem is that OpenGL does not offer a direct way to return the tesselated primitives,
1161 * and they can't be sent off for rendering directly either. Tesselating is slow, so we want
1162 * to chache the patches in a vertex buffer. But more importantly, gl can't bind generated
1163 * attributes to numbered shader attributes, so we have to store them and rebind them as needed
1166 * To read back, the opengl feedback mode is used. This creates a proplem because we want
1167 * untransformed, unlit vertices, but feedback runs everything through transform and lighting.
1168 * Thus disable lighting and set identity matrices to get unmodified colors and positions.
1169 * To overcome clipping find the biggest x, y and z values of the vertices in the patch and scale
1170 * them to [-1.0;+1.0] and set the viewport up to scale them back.
1172 * Normals are more tricky: Draw white vertices with 3 directional lights, and calculate the
1173 * resulting colors back to the normals.
1175 * NOTE: This function activates a context for blitting, modifies matrices & viewport, but
1176 * does not restore it because normally a draw follows immediately afterwards. The caller is
1177 * responsible of taking care that either the gl states are restored, or the context activated
1178 * for drawing to reset the lastWasBlit flag.
1180 HRESULT tesselate_rectpatch(IWineD3DDeviceImpl *This,
1181 struct WineD3DRectPatch *patch) {
1182 unsigned int i, j, num_quads, out_vertex_size, buffer_size, d3d_out_vertex_size;
1183 float max_x = 0.0, max_y = 0.0, max_z = 0.0, neg_z = 0.0;
1184 WineDirect3DVertexStridedData strided;
1186 WINED3DRECTPATCH_INFO *info = &patch->RectPatchInfo;
1188 GLenum feedback_type;
1189 GLfloat *feedbuffer;
1191 /* First, locate the position data. This is provided in a vertex buffer in the stateblock.
1194 memset(&strided, 0, sizeof(strided));
1195 primitiveDeclarationConvertToStridedData((IWineD3DDevice *) This, FALSE, &strided, NULL);
1196 if(strided.u.s.position.VBO) {
1197 IWineD3DVertexBufferImpl *vb;
1198 vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[strided.u.s.position.streamNo];
1199 strided.u.s.position.lpData = (BYTE *) ((unsigned long) strided.u.s.position.lpData +
1200 (unsigned long) vb->resource.allocatedMemory);
1202 vtxStride = strided.u.s.position.dwStride;
1203 data = strided.u.s.position.lpData +
1204 vtxStride * info->Stride * info->StartVertexOffsetHeight +
1205 vtxStride * info->StartVertexOffsetWidth;
1207 /* Not entirely sure about what happens with transformed vertices */
1208 if(strided.u.s.position_transformed) {
1209 FIXME("Transformed position in rectpatch generation\n");
1211 if(vtxStride % sizeof(GLfloat)) {
1212 /* glMap2f reads vertex sizes in GLfloats, the d3d stride is in bytes.
1213 * I don't see how the stride could not be a multiple of 4, but make sure
1216 ERR("Vertex stride is not a multiple of sizeof(GLfloat)\n");
1218 if(info->Basis != WINED3DBASIS_BEZIER) {
1219 FIXME("Basis is %s, how to handle this?\n", debug_d3dbasis(info->Basis));
1221 if(info->Degree != WINED3DDEGREE_CUBIC) {
1222 FIXME("Degree is %s, how to handle this?\n", debug_d3ddegree(info->Degree));
1225 /* First, get the boundary cube of the input data */
1226 for(j = 0; j < info->Height; j++) {
1227 for(i = 0; i < info->Width; i++) {
1228 float *v = (float *) (data + vtxStride * i + vtxStride * info->Stride * j);
1229 if(fabs(v[0]) > max_x) max_x = fabs(v[0]);
1230 if(fabs(v[1]) > max_y) max_y = fabs(v[1]);
1231 if(fabs(v[2]) > max_z) max_z = fabs(v[2]);
1232 if(v[2] < neg_z) neg_z = v[2];
1236 /* This needs some improvements in the vertex decl code */
1237 FIXME("Cannot find data to generate. Only generating position and normals\n");
1238 patch->has_normals = TRUE;
1239 patch->has_texcoords = FALSE;
1241 /* Simply activate the context for blitting. This disables all the things we don't want and
1242 * takes care of dirtifying. Dirtifying is preferred over pushing / popping, since drawing the
1243 * patch (as opposed to normal draws) will most likely need different changes anyway
1245 ActivateContext(This, This->lastActiveRenderTarget, CTXUSAGE_BLIT);
1248 glMatrixMode(GL_PROJECTION);
1249 checkGLcall("glMatrixMode(GL_PROJECTION)");
1251 checkGLcall("glLoadIndentity()");
1252 glScalef(1 / (max_x) , 1 / (max_y), max_z == 0 ? 1 : 1 / ( 2 * max_z));
1253 glTranslatef(0, 0, 0.5);
1254 checkGLcall("glScalef");
1255 glViewport(-max_x, -max_y, 2 * (max_x), 2 * (max_y));
1256 checkGLcall("glViewport");
1258 /* Some states to take care of. If we're in wireframe opengl will produce lines, and confuse
1259 * our feedback buffer parser
1261 glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
1262 checkGLcall("glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)");
1263 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_FILLMODE));
1264 if(patch->has_normals) {
1265 float black[4] = {0, 0, 0, 0};
1266 float red[4] = {1, 0, 0, 0};
1267 float green[4] = {0, 1, 0, 0};
1268 float blue[4] = {0, 0, 1, 0};
1269 float white[4] = {1, 1, 1, 1};
1270 glEnable(GL_LIGHTING);
1271 checkGLcall("glEnable(GL_LIGHTING)");
1272 glLightModelfv(GL_LIGHT_MODEL_AMBIENT, black);
1273 checkGLcall("glLightModel for MODEL_AMBIENT");
1274 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_AMBIENT));
1276 for(i = 3; i < GL_LIMITS(lights); i++) {
1277 glDisable(GL_LIGHT0 + i);
1278 checkGLcall("glDisable(GL_LIGHT0 + i)");
1279 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_ACTIVELIGHT(i));
1282 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_ACTIVELIGHT(0));
1283 glLightfv(GL_LIGHT0, GL_DIFFUSE, red);
1284 glLightfv(GL_LIGHT0, GL_SPECULAR, black);
1285 glLightfv(GL_LIGHT0, GL_AMBIENT, black);
1286 glLightfv(GL_LIGHT0, GL_POSITION, red);
1287 glEnable(GL_LIGHT0);
1288 checkGLcall("Setting up light 1\n");
1289 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_ACTIVELIGHT(1));
1290 glLightfv(GL_LIGHT1, GL_DIFFUSE, green);
1291 glLightfv(GL_LIGHT1, GL_SPECULAR, black);
1292 glLightfv(GL_LIGHT1, GL_AMBIENT, black);
1293 glLightfv(GL_LIGHT1, GL_POSITION, green);
1294 glEnable(GL_LIGHT1);
1295 checkGLcall("Setting up light 2\n");
1296 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_ACTIVELIGHT(2));
1297 glLightfv(GL_LIGHT2, GL_DIFFUSE, blue);
1298 glLightfv(GL_LIGHT2, GL_SPECULAR, black);
1299 glLightfv(GL_LIGHT2, GL_AMBIENT, black);
1300 glLightfv(GL_LIGHT2, GL_POSITION, blue);
1301 glEnable(GL_LIGHT2);
1302 checkGLcall("Setting up light 3\n");
1304 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_MATERIAL);
1305 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_COLORVERTEX));
1306 glDisable(GL_COLOR_MATERIAL);
1307 glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, black);
1308 glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, black);
1309 glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, white);
1310 checkGLcall("Setting up materials\n");
1313 /* Enable the needed maps.
1314 * GL_MAP2_VERTEX_3 is needed for positional data.
1315 * GL_AUTO_NORMAL to generate normals from the position. Do not use GL_MAP2_NORMAL.
1316 * GL_MAP2_TEXTURE_COORD_4 for texture coords
1318 num_quads = ceilf(patch->numSegs[0]) * ceilf(patch->numSegs[1]);
1319 out_vertex_size = 3 /* position */;
1320 d3d_out_vertex_size = 3;
1321 glEnable(GL_MAP2_VERTEX_3);
1322 if(patch->has_normals && patch->has_texcoords) {
1323 FIXME("Texcoords not handled yet\n");
1324 feedback_type = GL_3D_COLOR_TEXTURE;
1325 out_vertex_size += 8;
1326 d3d_out_vertex_size += 7;
1327 glEnable(GL_AUTO_NORMAL);
1328 glEnable(GL_MAP2_TEXTURE_COORD_4);
1329 } else if(patch->has_texcoords) {
1330 FIXME("Texcoords not handled yet\n");
1331 feedback_type = GL_3D_COLOR_TEXTURE;
1332 out_vertex_size += 7;
1333 d3d_out_vertex_size += 4;
1334 glEnable(GL_MAP2_TEXTURE_COORD_4);
1335 } else if(patch->has_normals) {
1336 feedback_type = GL_3D_COLOR;
1337 out_vertex_size += 4;
1338 d3d_out_vertex_size += 3;
1339 glEnable(GL_AUTO_NORMAL);
1341 feedback_type = GL_3D;
1343 checkGLcall("glEnable vertex attrib generation");
1345 buffer_size = num_quads * out_vertex_size * 2 /* triangle list */ * 3 /* verts per tri */
1346 + 4 * num_quads /* 2 triangle markers per quad + num verts in tri */;
1347 feedbuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, buffer_size * sizeof(float) * 8);
1349 glMap2f(GL_MAP2_VERTEX_3,
1350 0, 1, vtxStride / sizeof(float), info->Width,
1351 0, 1, info->Stride * vtxStride / sizeof(float), info->Height,
1353 checkGLcall("glMap2f");
1354 if(patch->has_texcoords) {
1355 glMap2f(GL_MAP2_TEXTURE_COORD_4,
1356 0, 1, vtxStride / sizeof(float), info->Width,
1357 0, 1, info->Stride * vtxStride / sizeof(float), info->Height,
1359 checkGLcall("glMap2f");
1361 glMapGrid2f(ceilf(patch->numSegs[0]), 0.0, 1.0, ceilf(patch->numSegs[1]), 0.0, 1.0);
1362 checkGLcall("glMapGrid2f");
1364 glFeedbackBuffer(buffer_size * 2, feedback_type, feedbuffer);
1365 checkGLcall("glFeedbackBuffer");
1366 glRenderMode(GL_FEEDBACK);
1368 glEvalMesh2(GL_FILL, 0, ceilf(patch->numSegs[0]), 0, ceilf(patch->numSegs[1]));
1369 checkGLcall("glEvalMesh2\n");
1371 i = glRenderMode(GL_RENDER);
1373 ERR("Feedback failed. Expected %d elements back\n", buffer_size);
1375 HeapFree(GetProcessHeap(), 0, feedbuffer);
1376 return WINED3DERR_DRIVERINTERNALERROR;
1377 } else if(i != buffer_size) {
1378 ERR("Unexpected amount of elements returned. Expected %d, got %d\n", buffer_size, i);
1380 HeapFree(GetProcessHeap(), 0, feedbuffer);
1381 return WINED3DERR_DRIVERINTERNALERROR;
1383 TRACE("Got %d elements as expected\n", i);
1386 HeapFree(GetProcessHeap(), 0, patch->mem);
1387 patch->mem = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, num_quads * 6 * d3d_out_vertex_size * sizeof(float) * 8);
1389 for(j = 0; j < buffer_size; j += (3 /* num verts */ * out_vertex_size + 2 /* tri marker */)) {
1390 if(feedbuffer[j] != GL_POLYGON_TOKEN) {
1391 ERR("Unexpected token: %f\n", feedbuffer[j]);
1394 if(feedbuffer[j + 1] != 3) {
1395 ERR("Unexpected polygon: %f corners\n", feedbuffer[j + 1]);
1398 /* Somehow there are different ideas about back / front facing, so fix up the
1401 patch->mem[i + 0] = feedbuffer[j + out_vertex_size * 2 + 2]; /* x, triangle 2 */
1402 patch->mem[i + 1] = feedbuffer[j + out_vertex_size * 2 + 3]; /* y, triangle 2 */
1403 patch->mem[i + 2] = (feedbuffer[j + out_vertex_size * 2 + 4] - 0.5) * 4 * max_z; /* z, triangle 3 */
1404 if(patch->has_normals) {
1405 patch->mem[i + 3] = feedbuffer[j + out_vertex_size * 2 + 5];
1406 patch->mem[i + 4] = feedbuffer[j + out_vertex_size * 2 + 6];
1407 patch->mem[i + 5] = feedbuffer[j + out_vertex_size * 2 + 7];
1409 i += d3d_out_vertex_size;
1411 patch->mem[i + 0] = feedbuffer[j + out_vertex_size * 1 + 2]; /* x, triangle 2 */
1412 patch->mem[i + 1] = feedbuffer[j + out_vertex_size * 1 + 3]; /* y, triangle 2 */
1413 patch->mem[i + 2] = (feedbuffer[j + out_vertex_size * 1 + 4] - 0.5) * 4 * max_z; /* z, triangle 2 */
1414 if(patch->has_normals) {
1415 patch->mem[i + 3] = feedbuffer[j + out_vertex_size * 1 + 5];
1416 patch->mem[i + 4] = feedbuffer[j + out_vertex_size * 1 + 6];
1417 patch->mem[i + 5] = feedbuffer[j + out_vertex_size * 1 + 7];
1419 i += d3d_out_vertex_size;
1421 patch->mem[i + 0] = feedbuffer[j + out_vertex_size * 0 + 2]; /* x, triangle 1 */
1422 patch->mem[i + 1] = feedbuffer[j + out_vertex_size * 0 + 3]; /* y, triangle 1 */
1423 patch->mem[i + 2] = (feedbuffer[j + out_vertex_size * 0 + 4] - 0.5) * 4 * max_z; /* z, triangle 1 */
1424 if(patch->has_normals) {
1425 patch->mem[i + 3] = feedbuffer[j + out_vertex_size * 0 + 5];
1426 patch->mem[i + 4] = feedbuffer[j + out_vertex_size * 0 + 6];
1427 patch->mem[i + 5] = feedbuffer[j + out_vertex_size * 0 + 7];
1429 i += d3d_out_vertex_size;
1432 if(patch->has_normals) {
1433 /* Now do the same with reverse light directions */
1434 float x[4] = {-1, 0, 0, 0};
1435 float y[4] = { 0, -1, 0, 0};
1436 float z[4] = { 0, 0, -1, 0};
1437 glLightfv(GL_LIGHT0, GL_POSITION, x);
1438 glLightfv(GL_LIGHT1, GL_POSITION, y);
1439 glLightfv(GL_LIGHT2, GL_POSITION, z);
1440 checkGLcall("Setting up reverse light directions\n");
1442 glRenderMode(GL_FEEDBACK);
1443 checkGLcall("glRenderMode(GL_FEEDBACK)");
1444 glEvalMesh2(GL_FILL, 0, ceilf(patch->numSegs[0]), 0, ceilf(patch->numSegs[1]));
1445 checkGLcall("glEvalMesh2\n");
1446 i = glRenderMode(GL_RENDER);
1447 checkGLcall("glRenderMode(GL_RENDER)");
1450 for(j = 0; j < buffer_size; j += (3 /* num verts */ * out_vertex_size + 2 /* tri marker */)) {
1451 if(feedbuffer[j] != GL_POLYGON_TOKEN) {
1452 ERR("Unexpected token: %f\n", feedbuffer[j]);
1455 if(feedbuffer[j + 1] != 3) {
1456 ERR("Unexpected polygon: %f corners\n", feedbuffer[j + 1]);
1459 if(patch->mem[i + 3] == 0.0)
1460 patch->mem[i + 3] = -feedbuffer[j + out_vertex_size * 2 + 5];
1461 if(patch->mem[i + 4] == 0.0)
1462 patch->mem[i + 4] = -feedbuffer[j + out_vertex_size * 2 + 6];
1463 if(patch->mem[i + 5] == 0.0)
1464 patch->mem[i + 5] = -feedbuffer[j + out_vertex_size * 2 + 7];
1465 normalize_normal(patch->mem + i + 3);
1466 i += d3d_out_vertex_size;
1468 if(patch->mem[i + 3] == 0.0)
1469 patch->mem[i + 3] = -feedbuffer[j + out_vertex_size * 1 + 5];
1470 if(patch->mem[i + 4] == 0.0)
1471 patch->mem[i + 4] = -feedbuffer[j + out_vertex_size * 1 + 6];
1472 if(patch->mem[i + 5] == 0.0)
1473 patch->mem[i + 5] = -feedbuffer[j + out_vertex_size * 1 + 7];
1474 normalize_normal(patch->mem + i + 3);
1475 i += d3d_out_vertex_size;
1477 if(patch->mem[i + 3] == 0.0)
1478 patch->mem[i + 3] = -feedbuffer[j + out_vertex_size * 0 + 5];
1479 if(patch->mem[i + 4] == 0.0)
1480 patch->mem[i + 4] = -feedbuffer[j + out_vertex_size * 0 + 6];
1481 if(patch->mem[i + 5] == 0.0)
1482 patch->mem[i + 5] = -feedbuffer[j + out_vertex_size * 0 + 7];
1483 normalize_normal(patch->mem + i + 3);
1484 i += d3d_out_vertex_size;
1488 glDisable(GL_MAP2_VERTEX_3);
1489 glDisable(GL_AUTO_NORMAL);
1490 glDisable(GL_MAP2_NORMAL);
1491 glDisable(GL_MAP2_TEXTURE_COORD_4);
1492 checkGLcall("glDisable vertex attrib generation");
1495 HeapFree(GetProcessHeap(), 0, feedbuffer);
1497 vtxStride = 3 * sizeof(float);
1498 if(patch->has_normals) {
1499 vtxStride += 3 * sizeof(float);
1501 if(patch->has_texcoords) {
1502 vtxStride += 4 * sizeof(float);
1504 memset(&patch->strided, 0, sizeof(&patch->strided));
1505 patch->strided.u.s.position.lpData = (BYTE *) patch->mem;
1506 patch->strided.u.s.position.dwStride = vtxStride;
1507 patch->strided.u.s.position.dwType = WINED3DDECLTYPE_FLOAT3;
1508 patch->strided.u.s.position.streamNo = 255;
1510 if(patch->has_normals) {
1511 patch->strided.u.s.normal.lpData = (BYTE *) patch->mem + 3 * sizeof(float) /* pos */;
1512 patch->strided.u.s.normal.dwStride = vtxStride;
1513 patch->strided.u.s.normal.dwType = WINED3DDECLTYPE_FLOAT3;
1514 patch->strided.u.s.normal.streamNo = 255;
1516 if(patch->has_texcoords) {
1517 patch->strided.u.s.texCoords[0].lpData = (BYTE *) patch->mem + 3 * sizeof(float) /* pos */;
1518 if(patch->has_normals) {
1519 patch->strided.u.s.texCoords[0].lpData += 3 * sizeof(float);
1521 patch->strided.u.s.texCoords[0].dwStride = vtxStride;
1522 patch->strided.u.s.texCoords[0].dwType = WINED3DDECLTYPE_FLOAT4;
1523 /* MAX_STREAMS index points to an unused element in stateblock->streamOffsets which
1524 * always remains set to 0. Windows uses stream 255 here, but this is not visible to the
1527 patch->strided.u.s.texCoords[0].streamNo = MAX_STREAMS;