wined3d: Print an error when drawStridedSlow() is called with 0 idxSize and non-NULL...
[wine] / dlls / wined3d / drawprim.c
1 /*
2  * WINED3D draw functions
3  *
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, 2008 Henri Verbeet
9  * Copyright 2007-2008 Stefan Dösinger for CodeWeavers
10  *
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.
15  *
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.
20  *
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
24  */
25
26 #include "config.h"
27 #include "wined3d_private.h"
28
29 WINE_DEFAULT_DEBUG_CHANNEL(d3d_draw);
30 #define GLINFO_LOCATION This->adapter->gl_info
31
32 #include <stdio.h>
33 #include <math.h>
34
35 /* Issues the glBegin call for gl given the primitive type and count */
36 static DWORD primitiveToGl(WINED3DPRIMITIVETYPE PrimitiveType,
37                     DWORD            NumPrimitives,
38                     GLenum          *primType)
39 {
40     DWORD   NumVertexes = NumPrimitives;
41
42     switch (PrimitiveType) {
43     case WINED3DPT_POINTLIST:
44         TRACE("POINTS\n");
45         *primType   = GL_POINTS;
46         NumVertexes = NumPrimitives;
47         break;
48
49     case WINED3DPT_LINELIST:
50         TRACE("LINES\n");
51         *primType   = GL_LINES;
52         NumVertexes = NumPrimitives * 2;
53         break;
54
55     case WINED3DPT_LINESTRIP:
56         TRACE("LINE_STRIP\n");
57         *primType   = GL_LINE_STRIP;
58         NumVertexes = NumPrimitives + 1;
59         break;
60
61     case WINED3DPT_TRIANGLELIST:
62         TRACE("TRIANGLES\n");
63         *primType   = GL_TRIANGLES;
64         NumVertexes = NumPrimitives * 3;
65         break;
66
67     case WINED3DPT_TRIANGLESTRIP:
68         TRACE("TRIANGLE_STRIP\n");
69         *primType   = GL_TRIANGLE_STRIP;
70         NumVertexes = NumPrimitives + 2;
71         break;
72
73     case WINED3DPT_TRIANGLEFAN:
74         TRACE("TRIANGLE_FAN\n");
75         *primType   = GL_TRIANGLE_FAN;
76         NumVertexes = NumPrimitives + 2;
77         break;
78
79     default:
80         FIXME("Unhandled primitive\n");
81         *primType    = GL_POINTS;
82         break;
83     }
84     return NumVertexes;
85 }
86
87 static BOOL fixed_get_input(
88     BYTE usage, BYTE usage_idx,
89     unsigned int* regnum) {
90
91     *regnum = -1;
92
93     /* Those positions must have the order in the
94      * named part of the strided data */
95
96     if ((usage == WINED3DDECLUSAGE_POSITION || usage == WINED3DDECLUSAGE_POSITIONT) && usage_idx == 0)
97         *regnum = 0;
98     else if (usage == WINED3DDECLUSAGE_BLENDWEIGHT && usage_idx == 0)
99         *regnum = 1;
100     else if (usage == WINED3DDECLUSAGE_BLENDINDICES && usage_idx == 0)
101         *regnum = 2;
102     else if (usage == WINED3DDECLUSAGE_NORMAL && usage_idx == 0)
103         *regnum = 3;
104     else if (usage == WINED3DDECLUSAGE_PSIZE && usage_idx == 0)
105         *regnum = 4;
106     else if (usage == WINED3DDECLUSAGE_COLOR && usage_idx == 0)
107         *regnum = 5;
108     else if (usage == WINED3DDECLUSAGE_COLOR && usage_idx == 1)
109         *regnum = 6;
110     else if (usage == WINED3DDECLUSAGE_TEXCOORD && usage_idx < WINED3DDP_MAXTEXCOORD)
111         *regnum = 7 + usage_idx;
112     else if ((usage == WINED3DDECLUSAGE_POSITION || usage == WINED3DDECLUSAGE_POSITIONT) && usage_idx == 1)
113         *regnum = 7 + WINED3DDP_MAXTEXCOORD;
114     else if (usage == WINED3DDECLUSAGE_NORMAL && usage_idx == 1)
115         *regnum = 8 + WINED3DDP_MAXTEXCOORD;
116     else if (usage == WINED3DDECLUSAGE_TANGENT && usage_idx == 0)
117         *regnum = 9 + WINED3DDP_MAXTEXCOORD;
118     else if (usage == WINED3DDECLUSAGE_BINORMAL && usage_idx == 0)
119         *regnum = 10 + WINED3DDP_MAXTEXCOORD;
120     else if (usage == WINED3DDECLUSAGE_TESSFACTOR && usage_idx == 0)
121         *regnum = 11 + WINED3DDP_MAXTEXCOORD;
122     else if (usage == WINED3DDECLUSAGE_FOG && usage_idx == 0)
123         *regnum = 12 + WINED3DDP_MAXTEXCOORD;
124     else if (usage == WINED3DDECLUSAGE_DEPTH && usage_idx == 0)
125         *regnum = 13 + WINED3DDP_MAXTEXCOORD;
126     else if (usage == WINED3DDECLUSAGE_SAMPLE && usage_idx == 0)
127         *regnum = 14 + WINED3DDP_MAXTEXCOORD;
128
129     if (*regnum == -1) {
130         FIXME("Unsupported input stream [usage=%s, usage_idx=%u]\n",
131             debug_d3ddeclusage(usage), usage_idx);
132         return FALSE;
133     }
134     return TRUE;
135 }
136
137 void primitiveDeclarationConvertToStridedData(
138      IWineD3DDevice *iface,
139      BOOL useVertexShaderFunction,
140      WineDirect3DVertexStridedData *strided,
141      BOOL *fixup) {
142
143      /* We need to deal with frequency data!*/
144
145     BYTE  *data    = NULL;
146     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
147     IWineD3DVertexDeclarationImpl* vertexDeclaration = (IWineD3DVertexDeclarationImpl *)This->stateBlock->vertexDecl;
148     int i;
149     WINED3DVERTEXELEMENT *element;
150     DWORD stride;
151     DWORD numPreloadStreams = This->stateBlock->streamIsUP ? 0 : vertexDeclaration->num_streams;
152     DWORD *streams = vertexDeclaration->streams;
153
154     /* Check for transformed vertices, disable vertex shader if present */
155     strided->u.s.position_transformed = vertexDeclaration->position_transformed;
156     if(vertexDeclaration->position_transformed) {
157         useVertexShaderFunction = FALSE;
158     }
159
160     /* Translate the declaration into strided data */
161     for (i = 0 ; i < vertexDeclaration->declarationWNumElements - 1; ++i) {
162         GLint streamVBO = 0;
163         BOOL stride_used;
164         unsigned int idx;
165
166         element = vertexDeclaration->pDeclarationWine + i;
167         TRACE("%p Element %p (%d of %d)\n", vertexDeclaration->pDeclarationWine,
168             element,  i + 1, vertexDeclaration->declarationWNumElements - 1);
169
170         if (This->stateBlock->streamSource[element->Stream] == NULL)
171             continue;
172
173         stride  = This->stateBlock->streamStride[element->Stream];
174         if (This->stateBlock->streamIsUP) {
175             TRACE("Stream is up %d, %p\n", element->Stream, This->stateBlock->streamSource[element->Stream]);
176             streamVBO = 0;
177             data    = (BYTE *)This->stateBlock->streamSource[element->Stream];
178         } else {
179             TRACE("Stream isn't up %d, %p\n", element->Stream, This->stateBlock->streamSource[element->Stream]);
180             data    = IWineD3DVertexBufferImpl_GetMemory(This->stateBlock->streamSource[element->Stream], 0, &streamVBO);
181
182             /* Can't use vbo's if the base vertex index is negative. OpenGL doesn't accept negative offsets
183              * (or rather offsets bigger than the vbo, because the pointer is unsigned), so use system memory
184              * sources. In most sane cases the pointer - offset will still be > 0, otherwise it will wrap
185              * around to some big value. Hope that with the indices, the driver wraps it back internally. If
186              * not, drawStridedSlow is needed, including a vertex buffer path.
187              */
188             if(This->stateBlock->loadBaseVertexIndex < 0) {
189                 WARN("loadBaseVertexIndex is < 0 (%d), not using vbos\n", This->stateBlock->loadBaseVertexIndex);
190                 streamVBO = 0;
191                 data = ((IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[element->Stream])->resource.allocatedMemory;
192                 if((UINT_PTR)data < -This->stateBlock->loadBaseVertexIndex * stride) {
193                     FIXME("System memory vertex data load offset is negative!\n");
194                 }
195             }
196
197             if(fixup) {
198                 if( streamVBO != 0) *fixup = TRUE;
199                 else if(*fixup && !useVertexShaderFunction &&
200                        (element->Usage == WINED3DDECLUSAGE_COLOR ||
201                         element->Usage == WINED3DDECLUSAGE_POSITIONT)) {
202                     static BOOL warned = FALSE;
203                     if(!warned) {
204                         /* This may be bad with the fixed function pipeline */
205                         FIXME("Missing vbo streams with unfixed colors or transformed position, expect problems\n");
206                         warned = TRUE;
207                     }
208                 }
209             }
210         }
211         data += element->Offset;
212
213         TRACE("Offset %d Stream %d UsageIndex %d\n", element->Offset, element->Stream, element->UsageIndex);
214
215         if (useVertexShaderFunction)
216             stride_used = vshader_get_input(This->stateBlock->vertexShader,
217                 element->Usage, element->UsageIndex, &idx);
218         else
219             stride_used = fixed_get_input(element->Usage, element->UsageIndex, &idx);
220
221         if (stride_used) {
222             TRACE("Load %s array %u [usage=%s, usage_idx=%u, "
223                     "stream=%u, offset=%u, stride=%u, type=%s, VBO=%u]\n",
224                     useVertexShaderFunction? "shader": "fixed function", idx,
225                     debug_d3ddeclusage(element->Usage), element->UsageIndex,
226                     element->Stream, element->Offset, stride, debug_d3ddecltype(element->Type), streamVBO);
227
228             if (!useVertexShaderFunction && !vertexDeclaration->ffp_valid[i]) {
229                 WARN("Skipping unsupported fixed function element of type %s and usage %s\n",
230                     debug_d3ddecltype(element->Type), debug_d3ddeclusage(element->Usage));
231             } else {
232                 strided->u.input[idx].lpData = data;
233                 strided->u.input[idx].dwType = element->Type;
234                 strided->u.input[idx].dwStride = stride;
235                 strided->u.input[idx].VBO = streamVBO;
236                 strided->u.input[idx].streamNo = element->Stream;
237             }
238         }
239     }
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
243      * own again.
244      *
245      * NULL streams won't be recorded in the array, UP streams won't be either. A stream is only
246      * once in there.
247      */
248     for(i=0; i < numPreloadStreams; i++) {
249         IWineD3DVertexBuffer *vb = This->stateBlock->streamSource[streams[i]];
250         if(vb) {
251             IWineD3DVertexBuffer_PreLoad(vb);
252         }
253     }
254 }
255
256 static void drawStridedFast(IWineD3DDevice *iface,UINT numberOfVertices, GLenum glPrimitiveType,
257                      const void *idxData, short idxSize, ULONG minIndex, ULONG startIdx, ULONG startVertex) {
258     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
259
260     if (idxSize != 0 /* This crashes sometimes!*/) {
261         TRACE("(%p) : glElements(%x, %d, %d, ...)\n", This, glPrimitiveType, numberOfVertices, minIndex);
262         idxData = idxData == (void *)-1 ? NULL : idxData;
263 #if 1
264         glDrawElements(glPrimitiveType, numberOfVertices, idxSize == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT,
265                      (const char *)idxData+(idxSize * startIdx));
266         checkGLcall("glDrawElements");
267 #else /* using drawRangeElements may be faster */
268
269         glDrawRangeElements(glPrimitiveType, minIndex, minIndex + numberOfVertices - 1, numberOfVertices,
270                       idxSize == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT,
271                       (const char *)idxData+(idxSize * startIdx));
272         checkGLcall("glDrawRangeElements");
273 #endif
274
275     } else {
276         TRACE("(%p) : glDrawArrays(%#x, %d, %d)\n", This, glPrimitiveType, startVertex, numberOfVertices);
277         glDrawArrays(glPrimitiveType, startVertex, numberOfVertices);
278         checkGLcall("glDrawArrays");
279     }
280
281     return;
282 }
283
284 /*
285  * Actually draw using the supplied information.
286  * Slower GL version which extracts info about each vertex in turn
287  */
288
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) {
292
293     unsigned int               textureNo    = 0;
294     const WORD                *pIdxBufS     = NULL;
295     const DWORD               *pIdxBufL     = NULL;
296     LONG                       vx_index;
297     DWORD diffuseColor = 0xFFFFFFFF;       /* Diffuse Color              */
298     DWORD specularColor = 0;               /* Specular Color             */
299     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
300     UINT *streamOffset = This->stateBlock->streamOffset;
301     long                      SkipnStrides = startVertex + This->stateBlock->loadBaseVertexIndex;
302     BOOL                      pixelShader = use_ps(This);
303
304     BYTE *texCoords[WINED3DDP_MAXTEXCOORD];
305     BYTE *diffuse = NULL, *specular = NULL, *normal = NULL, *position = NULL;
306
307     TRACE("Using slow vertex array code\n");
308
309     /* Variable Initialization */
310     if (idxSize != 0) {
311         /* Immediate mode drawing can't make use of indices in a vbo - get the data from the index buffer.
312          * If the index buffer has no vbo(not supported or other reason), or with user pointer drawing
313          * idxData will be != NULL
314          */
315         if(idxData == NULL) {
316             idxData = ((IWineD3DIndexBufferImpl *) This->stateBlock->pIndexData)->resource.allocatedMemory;
317         }
318
319         if (idxSize == 2) pIdxBufS = (const WORD *) idxData;
320         else pIdxBufL = (const DWORD *) idxData;
321     } else if (idxData) {
322         ERR("non-NULL idxData with 0 idxSize, this should never happen\n");
323         return;
324     }
325
326     /* Adding the stream offset once is cheaper than doing it every iteration. Do not modify the strided data, it is a pointer
327      * to the strided Data in the device and might be needed intact on the next draw
328      */
329     for (textureNo = 0; textureNo < GL_LIMITS(texture_stages); ++textureNo) {
330         if(sd->u.s.texCoords[textureNo].lpData) {
331             texCoords[textureNo] = sd->u.s.texCoords[textureNo].lpData + streamOffset[sd->u.s.texCoords[textureNo].streamNo];
332         } else {
333             texCoords[textureNo] = NULL;
334         }
335     }
336     if(sd->u.s.diffuse.lpData) {
337         diffuse = sd->u.s.diffuse.lpData + streamOffset[sd->u.s.diffuse.streamNo];
338     }
339     if(sd->u.s.specular.lpData) {
340         specular = sd->u.s.specular.lpData + streamOffset[sd->u.s.specular.streamNo];
341     }
342     if(sd->u.s.normal.lpData) {
343         normal = sd->u.s.normal.lpData + streamOffset[sd->u.s.normal.streamNo];
344     }
345     if(sd->u.s.position.lpData) {
346         position = sd->u.s.position.lpData + streamOffset[sd->u.s.position.streamNo];
347     }
348
349     if(FIXME_ON(d3d_draw)) {
350         if(specular && This->stateBlock->renderState[WINED3DRS_FOGENABLE] &&
351            (This->stateBlock->renderState[WINED3DRS_FOGVERTEXMODE] == WINED3DFOG_NONE || sd->u.s.position_transformed )&&
352            This->stateBlock->renderState[WINED3DRS_FOGTABLEMODE] == WINED3DFOG_NONE) {
353             if(GL_SUPPORT(EXT_FOG_COORD) && sd->u.s.specular.dwType != WINED3DDECLTYPE_D3DCOLOR) {
354                 FIXME("Implement fog coordinates from %s\n", debug_d3ddecltype(sd->u.s.specular.dwType));
355             }
356         }
357         if(This->activeContext->num_untracked_materials && sd->u.s.diffuse.dwType != WINED3DDECLTYPE_D3DCOLOR) {
358             FIXME("Implement diffuse color tracking from %s\n", debug_d3ddecltype(sd->u.s.diffuse.dwType));
359         }
360     }
361
362     /* Start drawing in GL */
363     VTRACE(("glBegin(%x)\n", glPrimType));
364     glBegin(glPrimType);
365
366     /* Default settings for data that is not passed */
367     if (sd->u.s.normal.lpData == NULL) {
368         glNormal3f(0, 0, 0);
369     }
370     if(sd->u.s.diffuse.lpData == NULL) {
371         glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
372     }
373     if(sd->u.s.specular.lpData == NULL) {
374         if (GL_SUPPORT(EXT_SECONDARY_COLOR)) {
375             GL_EXTCALL(glSecondaryColor3fEXT)(0, 0, 0);
376         }
377     }
378
379     /* We shouldn't start this function if any VBO is involved. Should I put a safety check here?
380      * Guess it's not necessary(we crash then anyway) and would only eat CPU time
381      */
382
383     /* For each primitive */
384     for (vx_index = 0; vx_index < NumVertexes; ++vx_index) {
385
386         /* Initialize diffuse color */
387         diffuseColor = 0xFFFFFFFF;
388
389         /* Blending data and Point sizes are not supported by this function. They are not supported by the fixed
390          * function pipeline at all. A Fixme for them is printed after decoding the vertex declaration
391          */
392
393         /* For indexed data, we need to go a few more strides in */
394         if (idxData != NULL) {
395
396             /* Indexed so work out the number of strides to skip */
397             if (idxSize == 2) {
398                 VTRACE(("Idx for vertex %d = %d\n", vx_index, pIdxBufS[startIdx+vx_index]));
399                 SkipnStrides = pIdxBufS[startIdx + vx_index] + This->stateBlock->loadBaseVertexIndex;
400             } else {
401                 VTRACE(("Idx for vertex %d = %d\n", vx_index, pIdxBufL[startIdx+vx_index]));
402                 SkipnStrides = pIdxBufL[startIdx + vx_index] + This->stateBlock->loadBaseVertexIndex;
403             }
404         }
405
406         /* Texture coords --------------------------- */
407         for (textureNo = 0; textureNo < GL_LIMITS(texture_stages); ++textureNo) {
408
409             if (!GL_SUPPORT(ARB_MULTITEXTURE) && textureNo > 0) {
410                 FIXME("Program using multiple concurrent textures which this opengl implementation doesn't support\n");
411                 continue ;
412             }
413
414             /* Query tex coords */
415             if (This->stateBlock->textures[textureNo] != NULL || pixelShader) {
416                 int    coordIdx = This->stateBlock->textureState[textureNo][WINED3DTSS_TEXCOORDINDEX];
417                 int texture_idx = This->texUnitMap[textureNo];
418                 void *ptrToCoords;
419
420                 if (coordIdx > 7) {
421                     VTRACE(("tex: %d - Skip tex coords, as being system generated\n", textureNo));
422                     continue;
423                 } else if (coordIdx < 0) {
424                     FIXME("tex: %d - Coord index %d is less than zero, expect a crash.\n", textureNo, coordIdx);
425                     continue;
426                 }
427
428                 if (texture_idx == -1) continue;
429
430                 if (texCoords[coordIdx] == NULL) {
431                     TRACE("tex: %d - Skipping tex coords, as no data supplied\n", textureNo);
432                     if (GL_SUPPORT(ARB_MULTITEXTURE)) {
433                         GL_EXTCALL(glMultiTexCoord4fARB(GL_TEXTURE0_ARB + texture_idx, 0, 0, 0, 1));
434                     } else {
435                         glTexCoord4f(0, 0, 0, 1);
436                     }
437                     continue;
438                 }
439
440                 ptrToCoords = texCoords[coordIdx] + (SkipnStrides * sd->u.s.texCoords[coordIdx].dwStride);
441                 if (GL_SUPPORT(ARB_MULTITEXTURE))
442                     multi_texcoord_funcs[sd->u.s.texCoords[coordIdx].dwType](GL_TEXTURE0_ARB + texture_idx, ptrToCoords);
443                 else
444                     texcoord_funcs[sd->u.s.texCoords[coordIdx].dwType](ptrToCoords);
445             }
446         } /* End of textures */
447
448         /* Diffuse -------------------------------- */
449         if (diffuse) {
450             DWORD *ptrToCoords = (DWORD *)(diffuse + (SkipnStrides * sd->u.s.diffuse.dwStride));
451
452             diffuse_funcs[sd->u.s.diffuse.dwType]((void *) ptrToCoords);
453             if(This->activeContext->num_untracked_materials) {
454                 unsigned char i;
455                 float color[4];
456
457                 diffuseColor = ptrToCoords[0];
458                 color[0] = D3DCOLOR_B_R(diffuseColor) / 255.0;
459                 color[1] = D3DCOLOR_B_G(diffuseColor) / 255.0;
460                 color[2] = D3DCOLOR_B_B(diffuseColor) / 255.0;
461                 color[3] = D3DCOLOR_B_A(diffuseColor) / 255.0;
462
463                 for(i = 0; i < This->activeContext->num_untracked_materials; i++) {
464                     glMaterialfv(GL_FRONT_AND_BACK, This->activeContext->untracked_materials[i], color);
465                 }
466             }
467         }
468
469         /* Specular ------------------------------- */
470         if (specular) {
471             DWORD *ptrToCoords = (DWORD *)(specular + (SkipnStrides * sd->u.s.specular.dwStride));
472
473             /* special case where the fog density is stored in the specular alpha channel */
474             if(This->stateBlock->renderState[WINED3DRS_FOGENABLE] &&
475               (This->stateBlock->renderState[WINED3DRS_FOGVERTEXMODE] == WINED3DFOG_NONE || sd->u.s.position.dwType == WINED3DDECLTYPE_FLOAT4 )&&
476               This->stateBlock->renderState[WINED3DRS_FOGTABLEMODE] == WINED3DFOG_NONE) {
477                 if(GL_SUPPORT(EXT_FOG_COORD)) {
478                     specularColor = ptrToCoords[0];
479                     GL_EXTCALL(glFogCoordfEXT(specularColor >> 24));
480                 } else {
481                     static BOOL warned = FALSE;
482                     if(!warned) {
483                         /* TODO: Use the fog table code from old ddraw */
484                         FIXME("Implement fog for transformed vertices in software\n");
485                         warned = TRUE;
486                     }
487                 }
488             }
489
490             specular_funcs[sd->u.s.specular.dwType]((void *) ptrToCoords);
491         }
492
493         /* Normal -------------------------------- */
494         if (normal != NULL) {
495             float *ptrToCoords = (float *)(normal + (SkipnStrides * sd->u.s.normal.dwStride));
496             normal_funcs[sd->u.s.normal.dwType](ptrToCoords);
497         }
498
499         /* Position -------------------------------- */
500         if (position) {
501             float *ptrToCoords = (float *)(position + (SkipnStrides * sd->u.s.position.dwStride));
502             position_funcs[sd->u.s.position.dwType](ptrToCoords);
503         }
504
505         /* For non indexed mode, step onto next parts */
506         if (idxData == NULL) {
507             ++SkipnStrides;
508         }
509     }
510
511     glEnd();
512     checkGLcall("glEnd and previous calls");
513 }
514
515 static inline void send_attribute(IWineD3DDeviceImpl *This, const DWORD type, const UINT index, const void *ptr) {
516     switch(type) {
517         case WINED3DDECLTYPE_FLOAT1:
518             GL_EXTCALL(glVertexAttrib1fvARB(index, (float *) ptr));
519             break;
520         case WINED3DDECLTYPE_FLOAT2:
521             GL_EXTCALL(glVertexAttrib2fvARB(index, (float *) ptr));
522             break;
523         case WINED3DDECLTYPE_FLOAT3:
524             GL_EXTCALL(glVertexAttrib3fvARB(index, (float *) ptr));
525             break;
526         case WINED3DDECLTYPE_FLOAT4:
527             GL_EXTCALL(glVertexAttrib4fvARB(index, (float *) ptr));
528             break;
529
530         case WINED3DDECLTYPE_UBYTE4:
531             GL_EXTCALL(glVertexAttrib4ubvARB(index, ptr));
532             break;
533         case WINED3DDECLTYPE_UBYTE4N:
534         case WINED3DDECLTYPE_D3DCOLOR:
535             GL_EXTCALL(glVertexAttrib4NubvARB(index, ptr));
536             break;
537
538         case WINED3DDECLTYPE_SHORT2:
539             GL_EXTCALL(glVertexAttrib4svARB(index, (GLshort *) ptr));
540             break;
541         case WINED3DDECLTYPE_SHORT4:
542             GL_EXTCALL(glVertexAttrib4svARB(index, (GLshort *) ptr));
543             break;
544
545         case WINED3DDECLTYPE_SHORT2N:
546         {
547             GLshort s[4] = {((short *) ptr)[0], ((short *) ptr)[1], 0, 1};
548             GL_EXTCALL(glVertexAttrib4NsvARB(index, s));
549             break;
550         }
551         case WINED3DDECLTYPE_USHORT2N:
552         {
553             GLushort s[4] = {((unsigned short *) ptr)[0], ((unsigned short *) ptr)[1], 0, 1};
554             GL_EXTCALL(glVertexAttrib4NusvARB(index, s));
555             break;
556         }
557         case WINED3DDECLTYPE_SHORT4N:
558             GL_EXTCALL(glVertexAttrib4NsvARB(index, (GLshort *) ptr));
559             break;
560         case WINED3DDECLTYPE_USHORT4N:
561             GL_EXTCALL(glVertexAttrib4NusvARB(index, (GLushort *) ptr));
562             break;
563
564         case WINED3DDECLTYPE_UDEC3:
565             FIXME("Unsure about WINED3DDECLTYPE_UDEC3\n");
566             /*glVertexAttrib3usvARB(instancedData[j], (GLushort *) ptr); Does not exist */
567             break;
568         case WINED3DDECLTYPE_DEC3N:
569             FIXME("Unsure about WINED3DDECLTYPE_DEC3N\n");
570             /*glVertexAttrib3NusvARB(instancedData[j], (GLushort *) ptr); Does not exist */
571             break;
572
573         case WINED3DDECLTYPE_FLOAT16_2:
574             /* Are those 16 bit floats. C doesn't have a 16 bit float type. I could read the single bits and calculate a 4
575              * byte float according to the IEEE standard
576              */
577             if (GL_SUPPORT(NV_HALF_FLOAT)) {
578                 GL_EXTCALL(glVertexAttrib2hvNV(index, (GLhalfNV *)ptr));
579             } else {
580                 float x = float_16_to_32(((unsigned short *) ptr) + 0);
581                 float y = float_16_to_32(((unsigned short *) ptr) + 1);
582                 GL_EXTCALL(glVertexAttrib2fARB(index, x, y));
583             }
584             break;
585         case WINED3DDECLTYPE_FLOAT16_4:
586             if (GL_SUPPORT(NV_HALF_FLOAT)) {
587                 GL_EXTCALL(glVertexAttrib4hvNV(index, (GLhalfNV *)ptr));
588             } else {
589                 float x = float_16_to_32(((unsigned short *) ptr) + 0);
590                 float y = float_16_to_32(((unsigned short *) ptr) + 1);
591                 float z = float_16_to_32(((unsigned short *) ptr) + 2);
592                 float w = float_16_to_32(((unsigned short *) ptr) + 3);
593                 GL_EXTCALL(glVertexAttrib4fARB(index, x, y, z, w));
594             }
595             break;
596
597         case WINED3DDECLTYPE_UNUSED:
598         default:
599             ERR("Unexpected attribute declaration: %d\n", type);
600             break;
601     }
602 }
603
604 static void drawStridedSlowVs(IWineD3DDevice *iface, WineDirect3DVertexStridedData *sd, UINT numberOfVertices,
605                               GLenum glPrimitiveType, const void *idxData, short idxSize, ULONG minIndex, ULONG startIdx,
606                               ULONG startVertex) {
607
608     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
609     long                      SkipnStrides = startVertex + This->stateBlock->loadBaseVertexIndex;
610     const WORD                *pIdxBufS     = NULL;
611     const DWORD               *pIdxBufL     = NULL;
612     LONG                       vx_index;
613     int i;
614     IWineD3DStateBlockImpl *stateblock = This->stateBlock;
615     BYTE *ptr;
616
617     if (idxSize != 0) {
618         /* Immediate mode drawing can't make use of indices in a vbo - get the data from the index buffer.
619          * If the index buffer has no vbo(not supported or other reason), or with user pointer drawing
620          * idxData will be != NULL
621          */
622         if(idxData == NULL) {
623             idxData = ((IWineD3DIndexBufferImpl *) stateblock->pIndexData)->resource.allocatedMemory;
624         }
625
626         if (idxSize == 2) pIdxBufS = (const WORD *) idxData;
627         else pIdxBufL = (const DWORD *) idxData;
628     }
629
630     /* Start drawing in GL */
631     VTRACE(("glBegin(%x)\n", glPrimitiveType));
632     glBegin(glPrimitiveType);
633
634     for (vx_index = 0; vx_index < numberOfVertices; ++vx_index) {
635         if (idxData != NULL) {
636
637             /* Indexed so work out the number of strides to skip */
638             if (idxSize == 2) {
639                 VTRACE(("Idx for vertex %d = %d\n", vx_index, pIdxBufS[startIdx+vx_index]));
640                 SkipnStrides = pIdxBufS[startIdx + vx_index] + stateblock->loadBaseVertexIndex;
641             } else {
642                 VTRACE(("Idx for vertex %d = %d\n", vx_index, pIdxBufL[startIdx+vx_index]));
643                 SkipnStrides = pIdxBufL[startIdx + vx_index] + stateblock->loadBaseVertexIndex;
644             }
645         }
646
647         for(i = MAX_ATTRIBS - 1; i >= 0; i--) {
648             if(!sd->u.input[i].lpData) continue;
649
650             ptr = sd->u.input[i].lpData +
651                   sd->u.input[i].dwStride * SkipnStrides +
652                   stateblock->streamOffset[sd->u.input[i].streamNo];
653
654             send_attribute(This, sd->u.input[i].dwType, i, ptr);
655         }
656         SkipnStrides++;
657     }
658
659     glEnd();
660 }
661
662 void depth_blt(IWineD3DDevice *iface, GLuint texture, GLsizei w, GLsizei h) {
663     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
664     GLint old_binding = 0;
665
666     glPushAttrib(GL_ENABLE_BIT | GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT | GL_VIEWPORT_BIT);
667
668     glDisable(GL_CULL_FACE);
669     glEnable(GL_BLEND);
670     glDisable(GL_ALPHA_TEST);
671     glDisable(GL_SCISSOR_TEST);
672     glDisable(GL_STENCIL_TEST);
673     glEnable(GL_DEPTH_TEST);
674     glDepthFunc(GL_ALWAYS);
675     glDepthMask(GL_TRUE);
676     glBlendFunc(GL_ZERO, GL_ONE);
677     glViewport(0, 0, w, h);
678
679     GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
680     glGetIntegerv(GL_TEXTURE_BINDING_2D, &old_binding);
681     glBindTexture(GL_TEXTURE_2D, texture);
682     glEnable(GL_TEXTURE_2D);
683
684     This->shader_backend->shader_select_depth_blt(iface);
685
686     glBegin(GL_TRIANGLE_STRIP);
687     glVertex2f(-1.0f, -1.0f);
688     glVertex2f(1.0f, -1.0f);
689     glVertex2f(-1.0f, 1.0f);
690     glVertex2f(1.0f, 1.0f);
691     glEnd();
692
693     glBindTexture(GL_TEXTURE_2D, old_binding);
694
695     glPopAttrib();
696
697     This->shader_backend->shader_deselect_depth_blt(iface);
698 }
699
700 static inline void drawStridedInstanced(IWineD3DDevice *iface, WineDirect3DVertexStridedData *sd, UINT numberOfVertices,
701                                  GLenum glPrimitiveType, const void *idxData, short idxSize, ULONG minIndex,
702                                  ULONG startIdx, ULONG startVertex) {
703     UINT numInstances = 0;
704     int numInstancedAttribs = 0, i, j;
705     UINT instancedData[sizeof(sd->u.input) / sizeof(sd->u.input[0]) /* 16 */];
706     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
707     IWineD3DStateBlockImpl *stateblock = This->stateBlock;
708
709     if (idxSize == 0) {
710         /* This is a nasty thing. MSDN says no hardware supports that and apps have to use software vertex processing.
711          * We don't support this for now
712          *
713          * Shouldn't be too hard to support with opengl, in theory just call glDrawArrays instead of drawElements.
714          * But the StreamSourceFreq value has a different meaning in that situation.
715          */
716         FIXME("Non-indexed instanced drawing is not supported\n");
717         return;
718     }
719
720     TRACE("(%p) : glElements(%x, %d, %d, ...)\n", This, glPrimitiveType, numberOfVertices, minIndex);
721     idxData = idxData == (void *)-1 ? NULL : idxData;
722
723     /* First, figure out how many instances we have to draw */
724     for(i = 0; i < MAX_STREAMS; i++) {
725         /* Look at the streams and take the first one which matches */
726         if(((stateblock->streamFlags[i] & WINED3DSTREAMSOURCE_INSTANCEDATA) || (stateblock->streamFlags[i] & WINED3DSTREAMSOURCE_INDEXEDDATA)) && stateblock->streamSource[i]) {
727             /* D3D9 could set streamFreq 0 with (INSTANCEDATA or INDEXEDDATA) and then it is handled as 1. See d3d9/tests/visual.c-> stream_test() */
728             if(stateblock->streamFreq[i] == 0){
729                 numInstances = 1;
730             } else {
731                 numInstances = stateblock->streamFreq[i]; /* use the specified number of instances from the first matched stream. See d3d9/tests/visual.c-> stream_test() */
732             }
733             break; /* break, because only the first suitable value is interesting */
734         }
735     }
736
737     for(i = 0; i < sizeof(sd->u.input) / sizeof(sd->u.input[0]); i++) {
738         if(stateblock->streamFlags[sd->u.input[i].streamNo] & WINED3DSTREAMSOURCE_INSTANCEDATA) {
739             instancedData[numInstancedAttribs] = i;
740             numInstancedAttribs++;
741         }
742     }
743
744     /* now draw numInstances instances :-) */
745     for(i = 0; i < numInstances; i++) {
746         /* Specify the instanced attributes using immediate mode calls */
747         for(j = 0; j < numInstancedAttribs; j++) {
748             BYTE *ptr = sd->u.input[instancedData[j]].lpData +
749                         sd->u.input[instancedData[j]].dwStride * i +
750                         stateblock->streamOffset[sd->u.input[instancedData[j]].streamNo];
751             if(sd->u.input[instancedData[j]].VBO) {
752                 IWineD3DVertexBufferImpl *vb = (IWineD3DVertexBufferImpl *) stateblock->streamSource[sd->u.input[instancedData[j]].streamNo];
753                 ptr += (long) vb->resource.allocatedMemory;
754             }
755
756             send_attribute(This, sd->u.input[instancedData[j]].dwType, instancedData[j], ptr);
757         }
758
759         glDrawElements(glPrimitiveType, numberOfVertices, idxSize == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT,
760                     (const char *)idxData+(idxSize * startIdx));
761         checkGLcall("glDrawElements");
762     }
763 }
764
765 static inline void remove_vbos(IWineD3DDeviceImpl *This, WineDirect3DVertexStridedData *s) {
766     unsigned char i;
767     IWineD3DVertexBufferImpl *vb;
768
769     if(s->u.s.position.VBO) {
770         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.position.streamNo];
771         s->u.s.position.VBO = 0;
772         s->u.s.position.lpData = (BYTE *) ((unsigned long) s->u.s.position.lpData + (unsigned long) vb->resource.allocatedMemory);
773     }
774     if(s->u.s.blendWeights.VBO) {
775         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.blendWeights.streamNo];
776         s->u.s.blendWeights.VBO = 0;
777         s->u.s.blendWeights.lpData = (BYTE *) ((unsigned long) s->u.s.blendWeights.lpData + (unsigned long) vb->resource.allocatedMemory);
778     }
779     if(s->u.s.blendMatrixIndices.VBO) {
780         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.blendMatrixIndices.streamNo];
781         s->u.s.blendMatrixIndices.VBO = 0;
782         s->u.s.blendMatrixIndices.lpData = (BYTE *) ((unsigned long) s->u.s.blendMatrixIndices.lpData + (unsigned long) vb->resource.allocatedMemory);
783     }
784     if(s->u.s.normal.VBO) {
785         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.normal.streamNo];
786         s->u.s.normal.VBO = 0;
787         s->u.s.normal.lpData = (BYTE *) ((unsigned long) s->u.s.normal.lpData + (unsigned long) vb->resource.allocatedMemory);
788     }
789     if(s->u.s.pSize.VBO) {
790         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.pSize.streamNo];
791         s->u.s.pSize.VBO = 0;
792         s->u.s.pSize.lpData = (BYTE *) ((unsigned long) s->u.s.pSize.lpData + (unsigned long) vb->resource.allocatedMemory);
793     }
794     if(s->u.s.diffuse.VBO) {
795         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.diffuse.streamNo];
796         s->u.s.diffuse.VBO = 0;
797         s->u.s.diffuse.lpData = (BYTE *) ((unsigned long) s->u.s.diffuse.lpData + (unsigned long) vb->resource.allocatedMemory);
798     }
799     if(s->u.s.specular.VBO) {
800         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.specular.streamNo];
801         s->u.s.specular.VBO = 0;
802         s->u.s.specular.lpData = (BYTE *) ((unsigned long) s->u.s.specular.lpData + (unsigned long) vb->resource.allocatedMemory);
803     }
804     for(i = 0; i < WINED3DDP_MAXTEXCOORD; i++) {
805         if(s->u.s.texCoords[i].VBO) {
806             vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.texCoords[i].streamNo];
807             s->u.s.texCoords[i].VBO = 0;
808             s->u.s.texCoords[i].lpData = (BYTE *) ((unsigned long) s->u.s.texCoords[i].lpData + (unsigned long) vb->resource.allocatedMemory);
809         }
810     }
811     if(s->u.s.position2.VBO) {
812         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.position2.streamNo];
813         s->u.s.position2.VBO = 0;
814         s->u.s.position2.lpData = (BYTE *) ((unsigned long) s->u.s.position2.lpData + (unsigned long) vb->resource.allocatedMemory);
815     }
816     if(s->u.s.normal2.VBO) {
817         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.normal2.streamNo];
818         s->u.s.normal2.VBO = 0;
819         s->u.s.normal2.lpData = (BYTE *) ((unsigned long) s->u.s.normal2.lpData + (unsigned long) vb->resource.allocatedMemory);
820     }
821     if(s->u.s.tangent.VBO) {
822         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.tangent.streamNo];
823         s->u.s.tangent.VBO = 0;
824         s->u.s.tangent.lpData = (BYTE *) ((unsigned long) s->u.s.tangent.lpData + (unsigned long) vb->resource.allocatedMemory);
825     }
826     if(s->u.s.binormal.VBO) {
827         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.binormal.streamNo];
828         s->u.s.binormal.VBO = 0;
829         s->u.s.binormal.lpData = (BYTE *) ((unsigned long) s->u.s.binormal.lpData + (unsigned long) vb->resource.allocatedMemory);
830     }
831     if(s->u.s.tessFactor.VBO) {
832         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.tessFactor.streamNo];
833         s->u.s.tessFactor.VBO = 0;
834         s->u.s.tessFactor.lpData = (BYTE *) ((unsigned long) s->u.s.tessFactor.lpData + (unsigned long) vb->resource.allocatedMemory);
835     }
836     if(s->u.s.fog.VBO) {
837         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.fog.streamNo];
838         s->u.s.fog.VBO = 0;
839         s->u.s.fog.lpData = (BYTE *) ((unsigned long) s->u.s.fog.lpData + (unsigned long) vb->resource.allocatedMemory);
840     }
841     if(s->u.s.depth.VBO) {
842         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.depth.streamNo];
843         s->u.s.depth.VBO = 0;
844         s->u.s.depth.lpData = (BYTE *) ((unsigned long) s->u.s.depth.lpData + (unsigned long) vb->resource.allocatedMemory);
845     }
846     if(s->u.s.sample.VBO) {
847         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.sample.streamNo];
848         s->u.s.sample.VBO = 0;
849         s->u.s.sample.lpData = (BYTE *) ((unsigned long) s->u.s.sample.lpData + (unsigned long) vb->resource.allocatedMemory);
850     }
851 }
852
853 /* Routine common to the draw primitive and draw indexed primitive routines */
854 void drawPrimitive(IWineD3DDevice *iface,
855                    int PrimitiveType,
856                    long NumPrimitives,
857                    /* for Indexed: */
858                    long  StartVertexIndex,
859                    UINT  numberOfVertices,
860                    long  StartIdx,
861                    short idxSize,
862                    const void *idxData,
863                    int   minIndex) {
864
865     IWineD3DDeviceImpl           *This = (IWineD3DDeviceImpl *)iface;
866     IWineD3DSurfaceImpl          *target;
867     int i;
868
869     if (NumPrimitives == 0) return;
870
871     /* Invalidate the back buffer memory so LockRect will read it the next time */
872     for(i = 0; i < GL_LIMITS(buffers); i++) {
873         target = (IWineD3DSurfaceImpl *) This->render_targets[i];
874         if (target) {
875             IWineD3DSurface_LoadLocation((IWineD3DSurface *) target, SFLAG_INDRAWABLE, NULL);
876             IWineD3DSurface_ModifyLocation((IWineD3DSurface *) target, SFLAG_INDRAWABLE, TRUE);
877         }
878     }
879
880     /* Signals other modules that a drawing is in progress and the stateblock finalized */
881     This->isInDraw = TRUE;
882
883     ActivateContext(This, This->render_targets[0], CTXUSAGE_DRAWPRIM);
884
885     if (This->stencilBufferTarget) {
886         /* Note that this depends on the ActivateContext call above to set
887          * This->render_offscreen properly */
888         DWORD location = This->render_offscreen ? SFLAG_DS_OFFSCREEN : SFLAG_DS_ONSCREEN;
889         surface_load_ds_location(This->stencilBufferTarget, location);
890         surface_modify_ds_location(This->stencilBufferTarget, location);
891     }
892
893     /* Ok, we will be updating the screen from here onwards so grab the lock */
894     ENTER_GL();
895     {
896         GLenum glPrimType;
897         BOOL emulation = FALSE;
898         WineDirect3DVertexStridedData *strided = &This->strided_streams;
899         WineDirect3DVertexStridedData stridedlcl;
900         /* Ok, Work out which primitive is requested and how many vertexes that
901            will be                                                              */
902         UINT calculatedNumberOfindices = primitiveToGl(PrimitiveType, NumPrimitives, &glPrimType);
903         if (numberOfVertices == 0 )
904             numberOfVertices = calculatedNumberOfindices;
905
906         if(!use_vs(This)) {
907             if(!This->strided_streams.u.s.position_transformed && This->activeContext->num_untracked_materials &&
908                 This->stateBlock->renderState[WINED3DRS_LIGHTING]) {
909                 static BOOL first = TRUE;
910                 if(first) {
911                     FIXME("Using software emulation because not all material properties could be tracked\n");
912                     first = FALSE;
913                 } else {
914                     TRACE("Using software emulation because not all material properties could be tracked\n");
915                 }
916                 emulation = TRUE;
917             }
918             else if(This->activeContext->fog_coord && This->stateBlock->renderState[WINED3DRS_FOGENABLE]) {
919                 /* Either write a pipeline replacement shader or convert the specular alpha from unsigned byte
920                  * to a float in the vertex buffer
921                  */
922                 static BOOL first = TRUE;
923                 if(first) {
924                     FIXME("Using software emulation because manual fog coordinates are provided\n");
925                     first = FALSE;
926                 } else {
927                     TRACE("Using software emulation because manual fog coordinates are provided\n");
928                 }
929                 emulation = TRUE;
930             }
931
932             if(emulation) {
933                 strided = &stridedlcl;
934                 memcpy(&stridedlcl, &This->strided_streams, sizeof(stridedlcl));
935                 remove_vbos(This, &stridedlcl);
936             }
937         }
938
939         if (This->useDrawStridedSlow || emulation) {
940             /* Immediate mode drawing */
941             if(use_vs(This)) {
942                 static BOOL first = TRUE;
943                 if(first) {
944                     FIXME("Using immediate mode with vertex shaders for half float emulation\n");
945                     first = FALSE;
946                 } else {
947                     TRACE("Using immediate mode with vertex shaders for half float emulation\n");
948                 }
949                 drawStridedSlowVs(iface, strided, calculatedNumberOfindices, glPrimType,
950                                   idxData, idxSize, minIndex, StartIdx, StartVertexIndex);
951             } else {
952                 drawStridedSlow(iface, strided, calculatedNumberOfindices,
953                                 glPrimType, idxData, idxSize, minIndex, StartIdx, StartVertexIndex);
954             }
955         } else if(This->instancedDraw) {
956             /* Instancing emulation with mixing immediate mode and arrays */
957             drawStridedInstanced(iface, &This->strided_streams, calculatedNumberOfindices, glPrimType,
958                             idxData, idxSize, minIndex, StartIdx, StartVertexIndex);
959         } else {
960             drawStridedFast(iface, calculatedNumberOfindices, glPrimType,
961                             idxData, idxSize, minIndex, StartIdx, StartVertexIndex);
962         }
963     }
964
965     /* Finished updating the screen, restore lock */
966     LEAVE_GL();
967     TRACE("Done all gl drawing\n");
968
969     /* Diagnostics */
970 #ifdef SHOW_FRAME_MAKEUP
971     {
972         static long int primCounter = 0;
973         /* NOTE: set primCounter to the value reported by drawprim 
974            before you want to to write frame makeup to /tmp */
975         if (primCounter >= 0) {
976             WINED3DLOCKED_RECT r;
977             char buffer[80];
978             IWineD3DSurface_LockRect(This->render_targets[0], &r, NULL, WINED3DLOCK_READONLY);
979             sprintf(buffer, "/tmp/backbuffer_%ld.tga", primCounter);
980             TRACE("Saving screenshot %s\n", buffer);
981             IWineD3DSurface_SaveSnapshot(This->render_targets[0], buffer);
982             IWineD3DSurface_UnlockRect(This->render_targets[0]);
983
984 #ifdef SHOW_TEXTURE_MAKEUP
985            {
986             IWineD3DSurface *pSur;
987             int textureNo;
988             for (textureNo = 0; textureNo < MAX_COMBINED_SAMPLERS; ++textureNo) {
989                 if (This->stateBlock->textures[textureNo] != NULL) {
990                     sprintf(buffer, "/tmp/texture_%p_%ld_%d.tga", This->stateBlock->textures[textureNo], primCounter, textureNo);
991                     TRACE("Saving texture %s\n", buffer);
992                     if (IWineD3DBaseTexture_GetType(This->stateBlock->textures[textureNo]) == WINED3DRTYPE_TEXTURE) {
993                             IWineD3DTexture_GetSurfaceLevel((IWineD3DTexture *)This->stateBlock->textures[textureNo], 0, &pSur);
994                             IWineD3DSurface_SaveSnapshot(pSur, buffer);
995                             IWineD3DSurface_Release(pSur);
996                     } else  {
997                         FIXME("base Texture isn't of type texture %d\n", IWineD3DBaseTexture_GetType(This->stateBlock->textures[textureNo]));
998                     }
999                 }
1000             }
1001            }
1002 #endif
1003         }
1004         TRACE("drawprim #%ld\n", primCounter);
1005         ++primCounter;
1006     }
1007 #endif
1008
1009     /* Control goes back to the device, stateblock values may change again */
1010     This->isInDraw = FALSE;
1011 }
1012
1013 static void normalize_normal(float *n) {
1014     float length = n[0] * n[0] + n[1] * n[1] + n[2] * n[2];
1015     if(length == 0.0) return;
1016     length = sqrt(length);
1017     n[0] = n[0] / length;
1018     n[1] = n[1] / length;
1019     n[2] = n[2] / length;
1020 }
1021
1022 /* Tesselates a high order rectangular patch into single triangles using gl evaluators
1023  *
1024  * The problem is that OpenGL does not offer a direct way to return the tesselated primitives,
1025  * and they can't be sent off for rendering directly either. Tesselating is slow, so we want
1026  * to cache the patches in a vertex buffer. But more importantly, gl can't bind generated
1027  * attributes to numbered shader attributes, so we have to store them and rebind them as needed
1028  * in drawprim.
1029  *
1030  * To read back, the opengl feedback mode is used. This creates a problem because we want
1031  * untransformed, unlit vertices, but feedback runs everything through transform and lighting.
1032  * Thus disable lighting and set identity matrices to get unmodified colors and positions.
1033  * To overcome clipping find the biggest x, y and z values of the vertices in the patch and scale
1034  * them to [-1.0;+1.0] and set the viewport up to scale them back.
1035  *
1036  * Normals are more tricky: Draw white vertices with 3 directional lights, and calculate the
1037  * resulting colors back to the normals.
1038  *
1039  * NOTE: This function activates a context for blitting, modifies matrices & viewport, but
1040  * does not restore it because normally a draw follows immediately afterwards. The caller is
1041  * responsible of taking care that either the gl states are restored, or the context activated
1042  * for drawing to reset the lastWasBlit flag.
1043  */
1044 HRESULT tesselate_rectpatch(IWineD3DDeviceImpl *This,
1045                             struct WineD3DRectPatch *patch) {
1046     unsigned int i, j, num_quads, out_vertex_size, buffer_size, d3d_out_vertex_size;
1047     float max_x = 0.0, max_y = 0.0, max_z = 0.0, neg_z = 0.0;
1048     WineDirect3DVertexStridedData strided;
1049     BYTE *data;
1050     WINED3DRECTPATCH_INFO *info = &patch->RectPatchInfo;
1051     DWORD vtxStride;
1052     GLenum feedback_type;
1053     GLfloat *feedbuffer;
1054
1055     /* First, locate the position data. This is provided in a vertex buffer in the stateblock.
1056      * Beware of vbos
1057      */
1058     memset(&strided, 0, sizeof(strided));
1059     primitiveDeclarationConvertToStridedData((IWineD3DDevice *) This, FALSE, &strided, NULL);
1060     if(strided.u.s.position.VBO) {
1061         IWineD3DVertexBufferImpl *vb;
1062         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[strided.u.s.position.streamNo];
1063         strided.u.s.position.lpData = (BYTE *) ((unsigned long) strided.u.s.position.lpData +
1064                                                 (unsigned long) vb->resource.allocatedMemory);
1065     }
1066     vtxStride = strided.u.s.position.dwStride;
1067     data = strided.u.s.position.lpData +
1068            vtxStride * info->Stride * info->StartVertexOffsetHeight +
1069            vtxStride * info->StartVertexOffsetWidth;
1070
1071     /* Not entirely sure about what happens with transformed vertices */
1072     if(strided.u.s.position_transformed) {
1073         FIXME("Transformed position in rectpatch generation\n");
1074     }
1075     if(vtxStride % sizeof(GLfloat)) {
1076         /* glMap2f reads vertex sizes in GLfloats, the d3d stride is in bytes.
1077          * I don't see how the stride could not be a multiple of 4, but make sure
1078          * to check it
1079          */
1080         ERR("Vertex stride is not a multiple of sizeof(GLfloat)\n");
1081     }
1082     if(info->Basis != WINED3DBASIS_BEZIER) {
1083         FIXME("Basis is %s, how to handle this?\n", debug_d3dbasis(info->Basis));
1084     }
1085     if(info->Degree != WINED3DDEGREE_CUBIC) {
1086         FIXME("Degree is %s, how to handle this?\n", debug_d3ddegree(info->Degree));
1087     }
1088
1089     /* First, get the boundary cube of the input data */
1090     for(j = 0; j < info->Height; j++) {
1091         for(i = 0; i < info->Width; i++) {
1092             float *v = (float *) (data + vtxStride * i + vtxStride * info->Stride * j);
1093             if(fabs(v[0]) > max_x) max_x = fabs(v[0]);
1094             if(fabs(v[1]) > max_y) max_y = fabs(v[1]);
1095             if(fabs(v[2]) > max_z) max_z = fabs(v[2]);
1096             if(v[2] < neg_z) neg_z = v[2];
1097         }
1098     }
1099
1100     /* This needs some improvements in the vertex decl code */
1101     FIXME("Cannot find data to generate. Only generating position and normals\n");
1102     patch->has_normals = TRUE;
1103     patch->has_texcoords = FALSE;
1104
1105     /* Simply activate the context for blitting. This disables all the things we don't want and
1106      * takes care of dirtifying. Dirtifying is preferred over pushing / popping, since drawing the
1107      * patch (as opposed to normal draws) will most likely need different changes anyway
1108      */
1109     ActivateContext(This, This->lastActiveRenderTarget, CTXUSAGE_BLIT);
1110     ENTER_GL();
1111
1112     glMatrixMode(GL_PROJECTION);
1113     checkGLcall("glMatrixMode(GL_PROJECTION)");
1114     glLoadIdentity();
1115     checkGLcall("glLoadIndentity()");
1116     glScalef(1 / (max_x) , 1 / (max_y), max_z == 0 ? 1 : 1 / ( 2 * max_z));
1117     glTranslatef(0, 0, 0.5);
1118     checkGLcall("glScalef");
1119     glViewport(-max_x, -max_y, 2 * (max_x), 2 * (max_y));
1120     checkGLcall("glViewport");
1121
1122     /* Some states to take care of. If we're in wireframe opengl will produce lines, and confuse
1123      * our feedback buffer parser
1124      */
1125     glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
1126     checkGLcall("glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)");
1127     IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_FILLMODE));
1128     if(patch->has_normals) {
1129         float black[4] = {0, 0, 0, 0};
1130         float red[4]   = {1, 0, 0, 0};
1131         float green[4] = {0, 1, 0, 0};
1132         float blue[4]  = {0, 0, 1, 0};
1133         float white[4] = {1, 1, 1, 1};
1134         glEnable(GL_LIGHTING);
1135         checkGLcall("glEnable(GL_LIGHTING)");
1136         glLightModelfv(GL_LIGHT_MODEL_AMBIENT, black);
1137         checkGLcall("glLightModel for MODEL_AMBIENT");
1138         IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_AMBIENT));
1139
1140         for(i = 3; i < GL_LIMITS(lights); i++) {
1141             glDisable(GL_LIGHT0 + i);
1142             checkGLcall("glDisable(GL_LIGHT0 + i)");
1143             IWineD3DDeviceImpl_MarkStateDirty(This, STATE_ACTIVELIGHT(i));
1144         }
1145
1146         IWineD3DDeviceImpl_MarkStateDirty(This, STATE_ACTIVELIGHT(0));
1147         glLightfv(GL_LIGHT0, GL_DIFFUSE, red);
1148         glLightfv(GL_LIGHT0, GL_SPECULAR, black);
1149         glLightfv(GL_LIGHT0, GL_AMBIENT, black);
1150         glLightfv(GL_LIGHT0, GL_POSITION, red);
1151         glEnable(GL_LIGHT0);
1152         checkGLcall("Setting up light 1\n");
1153         IWineD3DDeviceImpl_MarkStateDirty(This, STATE_ACTIVELIGHT(1));
1154         glLightfv(GL_LIGHT1, GL_DIFFUSE, green);
1155         glLightfv(GL_LIGHT1, GL_SPECULAR, black);
1156         glLightfv(GL_LIGHT1, GL_AMBIENT, black);
1157         glLightfv(GL_LIGHT1, GL_POSITION, green);
1158         glEnable(GL_LIGHT1);
1159         checkGLcall("Setting up light 2\n");
1160         IWineD3DDeviceImpl_MarkStateDirty(This, STATE_ACTIVELIGHT(2));
1161         glLightfv(GL_LIGHT2, GL_DIFFUSE, blue);
1162         glLightfv(GL_LIGHT2, GL_SPECULAR, black);
1163         glLightfv(GL_LIGHT2, GL_AMBIENT, black);
1164         glLightfv(GL_LIGHT2, GL_POSITION, blue);
1165         glEnable(GL_LIGHT2);
1166         checkGLcall("Setting up light 3\n");
1167
1168         IWineD3DDeviceImpl_MarkStateDirty(This, STATE_MATERIAL);
1169         IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_COLORVERTEX));
1170         glDisable(GL_COLOR_MATERIAL);
1171         glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, black);
1172         glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, black);
1173         glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, white);
1174         checkGLcall("Setting up materials\n");
1175     }
1176
1177     /* Enable the needed maps.
1178      * GL_MAP2_VERTEX_3 is needed for positional data.
1179      * GL_AUTO_NORMAL to generate normals from the position. Do not use GL_MAP2_NORMAL.
1180      * GL_MAP2_TEXTURE_COORD_4 for texture coords
1181      */
1182     num_quads = ceilf(patch->numSegs[0]) * ceilf(patch->numSegs[1]);
1183     out_vertex_size = 3 /* position */;
1184     d3d_out_vertex_size = 3;
1185     glEnable(GL_MAP2_VERTEX_3);
1186     if(patch->has_normals && patch->has_texcoords) {
1187         FIXME("Texcoords not handled yet\n");
1188         feedback_type = GL_3D_COLOR_TEXTURE;
1189         out_vertex_size += 8;
1190         d3d_out_vertex_size += 7;
1191         glEnable(GL_AUTO_NORMAL);
1192         glEnable(GL_MAP2_TEXTURE_COORD_4);
1193     } else if(patch->has_texcoords) {
1194         FIXME("Texcoords not handled yet\n");
1195         feedback_type = GL_3D_COLOR_TEXTURE;
1196         out_vertex_size += 7;
1197         d3d_out_vertex_size += 4;
1198         glEnable(GL_MAP2_TEXTURE_COORD_4);
1199     } else if(patch->has_normals) {
1200         feedback_type = GL_3D_COLOR;
1201         out_vertex_size += 4;
1202         d3d_out_vertex_size += 3;
1203         glEnable(GL_AUTO_NORMAL);
1204     } else {
1205         feedback_type = GL_3D;
1206     }
1207     checkGLcall("glEnable vertex attrib generation");
1208
1209     buffer_size = num_quads * out_vertex_size * 2 /* triangle list */ * 3 /* verts per tri */
1210                    + 4 * num_quads /* 2 triangle markers per quad + num verts in tri */;
1211     feedbuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, buffer_size * sizeof(float) * 8);
1212
1213     glMap2f(GL_MAP2_VERTEX_3,
1214             0, 1, vtxStride / sizeof(float), info->Width,
1215             0, 1, info->Stride * vtxStride / sizeof(float), info->Height,
1216             (float *) data);
1217     checkGLcall("glMap2f");
1218     if(patch->has_texcoords) {
1219         glMap2f(GL_MAP2_TEXTURE_COORD_4,
1220                 0, 1, vtxStride / sizeof(float), info->Width,
1221                 0, 1, info->Stride * vtxStride / sizeof(float), info->Height,
1222                 (float *) data);
1223         checkGLcall("glMap2f");
1224     }
1225     glMapGrid2f(ceilf(patch->numSegs[0]), 0.0, 1.0, ceilf(patch->numSegs[1]), 0.0, 1.0);
1226     checkGLcall("glMapGrid2f");
1227
1228     glFeedbackBuffer(buffer_size * 2, feedback_type, feedbuffer);
1229     checkGLcall("glFeedbackBuffer");
1230     glRenderMode(GL_FEEDBACK);
1231
1232     glEvalMesh2(GL_FILL, 0, ceilf(patch->numSegs[0]), 0, ceilf(patch->numSegs[1]));
1233     checkGLcall("glEvalMesh2\n");
1234
1235     i = glRenderMode(GL_RENDER);
1236     if(i == -1) {
1237         LEAVE_GL();
1238         ERR("Feedback failed. Expected %d elements back\n", buffer_size);
1239         Sleep(10000);
1240         HeapFree(GetProcessHeap(), 0, feedbuffer);
1241         return WINED3DERR_DRIVERINTERNALERROR;
1242     } else if(i != buffer_size) {
1243         LEAVE_GL();
1244         ERR("Unexpected amount of elements returned. Expected %d, got %d\n", buffer_size, i);
1245         Sleep(10000);
1246         HeapFree(GetProcessHeap(), 0, feedbuffer);
1247         return WINED3DERR_DRIVERINTERNALERROR;
1248     } else {
1249         TRACE("Got %d elements as expected\n", i);
1250     }
1251
1252     HeapFree(GetProcessHeap(), 0, patch->mem);
1253     patch->mem = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, num_quads * 6 * d3d_out_vertex_size * sizeof(float) * 8);
1254     i = 0;
1255     for(j = 0; j < buffer_size; j += (3 /* num verts */ * out_vertex_size + 2 /* tri marker */)) {
1256         if(feedbuffer[j] != GL_POLYGON_TOKEN) {
1257             ERR("Unexpected token: %f\n", feedbuffer[j]);
1258             continue;
1259         }
1260         if(feedbuffer[j + 1] != 3) {
1261             ERR("Unexpected polygon: %f corners\n", feedbuffer[j + 1]);
1262             continue;
1263         }
1264         /* Somehow there are different ideas about back / front facing, so fix up the
1265          * vertex order
1266          */
1267         patch->mem[i + 0] =  feedbuffer[j + out_vertex_size * 2 + 2]; /* x, triangle 2 */
1268         patch->mem[i + 1] =  feedbuffer[j + out_vertex_size * 2 + 3]; /* y, triangle 2 */
1269         patch->mem[i + 2] = (feedbuffer[j + out_vertex_size * 2 + 4] - 0.5) * 4 * max_z; /* z, triangle 3 */
1270         if(patch->has_normals) {
1271             patch->mem[i + 3] = feedbuffer[j + out_vertex_size * 2 + 5];
1272             patch->mem[i + 4] = feedbuffer[j + out_vertex_size * 2 + 6];
1273             patch->mem[i + 5] = feedbuffer[j + out_vertex_size * 2 + 7];
1274         }
1275         i += d3d_out_vertex_size;
1276
1277         patch->mem[i + 0] =  feedbuffer[j + out_vertex_size * 1 + 2]; /* x, triangle 2 */
1278         patch->mem[i + 1] =  feedbuffer[j + out_vertex_size * 1 + 3]; /* y, triangle 2 */
1279         patch->mem[i + 2] = (feedbuffer[j + out_vertex_size * 1 + 4] - 0.5) * 4 * max_z; /* z, triangle 2 */
1280         if(patch->has_normals) {
1281             patch->mem[i + 3] = feedbuffer[j + out_vertex_size * 1 + 5];
1282             patch->mem[i + 4] = feedbuffer[j + out_vertex_size * 1 + 6];
1283             patch->mem[i + 5] = feedbuffer[j + out_vertex_size * 1 + 7];
1284         }
1285         i += d3d_out_vertex_size;
1286
1287         patch->mem[i + 0] =  feedbuffer[j + out_vertex_size * 0 + 2]; /* x, triangle 1 */
1288         patch->mem[i + 1] =  feedbuffer[j + out_vertex_size * 0 + 3]; /* y, triangle 1 */
1289         patch->mem[i + 2] = (feedbuffer[j + out_vertex_size * 0 + 4] - 0.5) * 4 * max_z; /* z, triangle 1 */
1290         if(patch->has_normals) {
1291             patch->mem[i + 3] = feedbuffer[j + out_vertex_size * 0 + 5];
1292             patch->mem[i + 4] = feedbuffer[j + out_vertex_size * 0 + 6];
1293             patch->mem[i + 5] = feedbuffer[j + out_vertex_size * 0 + 7];
1294         }
1295         i += d3d_out_vertex_size;
1296     }
1297
1298     if(patch->has_normals) {
1299         /* Now do the same with reverse light directions */
1300         float x[4] = {-1,  0,  0, 0};
1301         float y[4] = { 0, -1,  0, 0};
1302         float z[4] = { 0,  0, -1, 0};
1303         glLightfv(GL_LIGHT0, GL_POSITION, x);
1304         glLightfv(GL_LIGHT1, GL_POSITION, y);
1305         glLightfv(GL_LIGHT2, GL_POSITION, z);
1306         checkGLcall("Setting up reverse light directions\n");
1307
1308         glRenderMode(GL_FEEDBACK);
1309         checkGLcall("glRenderMode(GL_FEEDBACK)");
1310         glEvalMesh2(GL_FILL, 0, ceilf(patch->numSegs[0]), 0, ceilf(patch->numSegs[1]));
1311         checkGLcall("glEvalMesh2\n");
1312         i = glRenderMode(GL_RENDER);
1313         checkGLcall("glRenderMode(GL_RENDER)");
1314
1315         i = 0;
1316         for(j = 0; j < buffer_size; j += (3 /* num verts */ * out_vertex_size + 2 /* tri marker */)) {
1317             if(feedbuffer[j] != GL_POLYGON_TOKEN) {
1318                 ERR("Unexpected token: %f\n", feedbuffer[j]);
1319                 continue;
1320             }
1321             if(feedbuffer[j + 1] != 3) {
1322                 ERR("Unexpected polygon: %f corners\n", feedbuffer[j + 1]);
1323                 continue;
1324             }
1325             if(patch->mem[i + 3] == 0.0)
1326                 patch->mem[i + 3] = -feedbuffer[j + out_vertex_size * 2 + 5];
1327             if(patch->mem[i + 4] == 0.0)
1328                 patch->mem[i + 4] = -feedbuffer[j + out_vertex_size * 2 + 6];
1329             if(patch->mem[i + 5] == 0.0)
1330                 patch->mem[i + 5] = -feedbuffer[j + out_vertex_size * 2 + 7];
1331             normalize_normal(patch->mem + i + 3);
1332             i += d3d_out_vertex_size;
1333
1334             if(patch->mem[i + 3] == 0.0)
1335                 patch->mem[i + 3] = -feedbuffer[j + out_vertex_size * 1 + 5];
1336             if(patch->mem[i + 4] == 0.0)
1337                 patch->mem[i + 4] = -feedbuffer[j + out_vertex_size * 1 + 6];
1338             if(patch->mem[i + 5] == 0.0)
1339                 patch->mem[i + 5] = -feedbuffer[j + out_vertex_size * 1 + 7];
1340             normalize_normal(patch->mem + i + 3);
1341             i += d3d_out_vertex_size;
1342
1343             if(patch->mem[i + 3] == 0.0)
1344                 patch->mem[i + 3] = -feedbuffer[j + out_vertex_size * 0 + 5];
1345             if(patch->mem[i + 4] == 0.0)
1346                 patch->mem[i + 4] = -feedbuffer[j + out_vertex_size * 0 + 6];
1347             if(patch->mem[i + 5] == 0.0)
1348                 patch->mem[i + 5] = -feedbuffer[j + out_vertex_size * 0 + 7];
1349             normalize_normal(patch->mem + i + 3);
1350             i += d3d_out_vertex_size;
1351         }
1352     }
1353
1354     glDisable(GL_MAP2_VERTEX_3);
1355     glDisable(GL_AUTO_NORMAL);
1356     glDisable(GL_MAP2_NORMAL);
1357     glDisable(GL_MAP2_TEXTURE_COORD_4);
1358     checkGLcall("glDisable vertex attrib generation");
1359     LEAVE_GL();
1360
1361     HeapFree(GetProcessHeap(), 0, feedbuffer);
1362
1363     vtxStride = 3 * sizeof(float);
1364     if(patch->has_normals) {
1365         vtxStride += 3 * sizeof(float);
1366     }
1367     if(patch->has_texcoords) {
1368         vtxStride += 4 * sizeof(float);
1369     }
1370     memset(&patch->strided, 0, sizeof(&patch->strided));
1371     patch->strided.u.s.position.lpData = (BYTE *) patch->mem;
1372     patch->strided.u.s.position.dwStride = vtxStride;
1373     patch->strided.u.s.position.dwType = WINED3DDECLTYPE_FLOAT3;
1374     patch->strided.u.s.position.streamNo = 255;
1375
1376     if(patch->has_normals) {
1377         patch->strided.u.s.normal.lpData = (BYTE *) patch->mem + 3 * sizeof(float) /* pos */;
1378         patch->strided.u.s.normal.dwStride = vtxStride;
1379         patch->strided.u.s.normal.dwType = WINED3DDECLTYPE_FLOAT3;
1380         patch->strided.u.s.normal.streamNo = 255;
1381     }
1382     if(patch->has_texcoords) {
1383         patch->strided.u.s.texCoords[0].lpData = (BYTE *) patch->mem + 3 * sizeof(float) /* pos */;
1384         if(patch->has_normals) {
1385             patch->strided.u.s.texCoords[0].lpData += 3 * sizeof(float);
1386         }
1387         patch->strided.u.s.texCoords[0].dwStride = vtxStride;
1388         patch->strided.u.s.texCoords[0].dwType = WINED3DDECLTYPE_FLOAT4;
1389         /* MAX_STREAMS index points to an unused element in stateblock->streamOffsets which
1390          * always remains set to 0. Windows uses stream 255 here, but this is not visible to the
1391          * application.
1392          */
1393         patch->strided.u.s.texCoords[0].streamNo = MAX_STREAMS;
1394     }
1395
1396     return WINED3D_OK;
1397 }