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