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