dsound: Add support for 24/32 bits input sound buffers.
[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 static inline void remove_vbos(IWineD3DDeviceImpl *This, WineDirect3DVertexStridedData *s) {
833     unsigned char i;
834     IWineD3DVertexBufferImpl *vb;
835
836     if(s->u.s.position.VBO) {
837         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.position.streamNo];
838         s->u.s.position.VBO = 0;
839         s->u.s.position.lpData = (BYTE *) ((unsigned long) s->u.s.position.lpData + (unsigned long) vb->resource.allocatedMemory);
840     }
841     if(s->u.s.blendWeights.VBO) {
842         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.blendWeights.streamNo];
843         s->u.s.blendWeights.VBO = 0;
844         s->u.s.blendWeights.lpData = (BYTE *) ((unsigned long) s->u.s.blendWeights.lpData + (unsigned long) vb->resource.allocatedMemory);
845     }
846     if(s->u.s.blendMatrixIndices.VBO) {
847         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.blendMatrixIndices.streamNo];
848         s->u.s.blendMatrixIndices.VBO = 0;
849         s->u.s.blendMatrixIndices.lpData = (BYTE *) ((unsigned long) s->u.s.blendMatrixIndices.lpData + (unsigned long) vb->resource.allocatedMemory);
850     }
851     if(s->u.s.normal.VBO) {
852         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.normal.streamNo];
853         s->u.s.normal.VBO = 0;
854         s->u.s.normal.lpData = (BYTE *) ((unsigned long) s->u.s.normal.lpData + (unsigned long) vb->resource.allocatedMemory);
855     }
856     if(s->u.s.pSize.VBO) {
857         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.pSize.streamNo];
858         s->u.s.pSize.VBO = 0;
859         s->u.s.pSize.lpData = (BYTE *) ((unsigned long) s->u.s.pSize.lpData + (unsigned long) vb->resource.allocatedMemory);
860     }
861     if(s->u.s.diffuse.VBO) {
862         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.diffuse.streamNo];
863         s->u.s.diffuse.VBO = 0;
864         s->u.s.diffuse.lpData = (BYTE *) ((unsigned long) s->u.s.diffuse.lpData + (unsigned long) vb->resource.allocatedMemory);
865     }
866     if(s->u.s.specular.VBO) {
867         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.specular.streamNo];
868         s->u.s.specular.VBO = 0;
869         s->u.s.specular.lpData = (BYTE *) ((unsigned long) s->u.s.specular.lpData + (unsigned long) vb->resource.allocatedMemory);
870     }
871     for(i = 0; i < WINED3DDP_MAXTEXCOORD; i++) {
872         if(s->u.s.texCoords[i].VBO) {
873             vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.texCoords[i].streamNo];
874             s->u.s.texCoords[i].VBO = 0;
875             s->u.s.texCoords[i].lpData = (BYTE *) ((unsigned long) s->u.s.texCoords[i].lpData + (unsigned long) vb->resource.allocatedMemory);
876         }
877     }
878     if(s->u.s.position2.VBO) {
879         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.position2.streamNo];
880         s->u.s.position2.VBO = 0;
881         s->u.s.position2.lpData = (BYTE *) ((unsigned long) s->u.s.position2.lpData + (unsigned long) vb->resource.allocatedMemory);
882     }
883     if(s->u.s.normal2.VBO) {
884         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.normal2.streamNo];
885         s->u.s.normal2.VBO = 0;
886         s->u.s.normal2.lpData = (BYTE *) ((unsigned long) s->u.s.normal2.lpData + (unsigned long) vb->resource.allocatedMemory);
887     }
888     if(s->u.s.tangent.VBO) {
889         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.tangent.streamNo];
890         s->u.s.tangent.VBO = 0;
891         s->u.s.tangent.lpData = (BYTE *) ((unsigned long) s->u.s.tangent.lpData + (unsigned long) vb->resource.allocatedMemory);
892     }
893     if(s->u.s.binormal.VBO) {
894         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.binormal.streamNo];
895         s->u.s.binormal.VBO = 0;
896         s->u.s.binormal.lpData = (BYTE *) ((unsigned long) s->u.s.binormal.lpData + (unsigned long) vb->resource.allocatedMemory);
897     }
898     if(s->u.s.tessFactor.VBO) {
899         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.tessFactor.streamNo];
900         s->u.s.tessFactor.VBO = 0;
901         s->u.s.tessFactor.lpData = (BYTE *) ((unsigned long) s->u.s.tessFactor.lpData + (unsigned long) vb->resource.allocatedMemory);
902     }
903     if(s->u.s.fog.VBO) {
904         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.fog.streamNo];
905         s->u.s.fog.VBO = 0;
906         s->u.s.fog.lpData = (BYTE *) ((unsigned long) s->u.s.fog.lpData + (unsigned long) vb->resource.allocatedMemory);
907     }
908     if(s->u.s.depth.VBO) {
909         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.depth.streamNo];
910         s->u.s.depth.VBO = 0;
911         s->u.s.depth.lpData = (BYTE *) ((unsigned long) s->u.s.depth.lpData + (unsigned long) vb->resource.allocatedMemory);
912     }
913     if(s->u.s.sample.VBO) {
914         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[s->u.s.sample.streamNo];
915         s->u.s.sample.VBO = 0;
916         s->u.s.sample.lpData = (BYTE *) ((unsigned long) s->u.s.sample.lpData + (unsigned long) vb->resource.allocatedMemory);
917     }
918 }
919
920 /* Routine common to the draw primitive and draw indexed primitive routines */
921 void drawPrimitive(IWineD3DDevice *iface,
922                    int PrimitiveType,
923                    long NumPrimitives,
924                    /* for Indexed: */
925                    long  StartVertexIndex,
926                    UINT  numberOfVertices,
927                    long  StartIdx,
928                    short idxSize,
929                    const void *idxData,
930                    int   minIndex) {
931
932     IWineD3DDeviceImpl           *This = (IWineD3DDeviceImpl *)iface;
933     IWineD3DSwapChain            *swapchain;
934     IWineD3DBaseTexture          *texture = NULL;
935     IWineD3DSurfaceImpl          *target;
936     int i;
937
938     /* Signals other modules that a drawing is in progress and the stateblock finalized */
939     This->isInDraw = TRUE;
940
941     /* Invalidate the back buffer memory so LockRect will read it the next time */
942     for(i = 0; i < GL_LIMITS(buffers); i++) {
943         target = (IWineD3DSurfaceImpl *) This->render_targets[i];
944
945         /* TODO: Only do all that if we're going to change anything
946          * Texture container dirtification does not work quite right yet
947          */
948         if(target /*&& target->Flags & (SFLAG_INTEXTURE | SFLAG_INSYSMEM)*/) {
949             swapchain = NULL;
950             texture = NULL;
951
952             if(i == 0) {
953                 IWineD3DSurface_GetContainer((IWineD3DSurface *) target, &IID_IWineD3DSwapChain, (void **)&swapchain);
954
955                 /* Need the surface in the drawable! */
956                 IWineD3DSurface_LoadLocation((IWineD3DSurface *) target, SFLAG_INDRAWABLE, NULL);
957
958                 /* TODO: Move fbo logic to ModifyLocation */
959                 IWineD3DSurface_ModifyLocation((IWineD3DSurface *) target, SFLAG_INDRAWABLE, TRUE);
960                 if(swapchain) {
961                     /* Onscreen target. Invalidate system memory copy and texture copy */
962                     IWineD3DSwapChain_Release(swapchain);
963                 } else if(wined3d_settings.offscreen_rendering_mode != ORM_FBO) {
964                     /* Non-FBO target: Invalidate system copy, texture copy and dirtify the container */
965                     /* TODO: Move container dirtification to ModifyLocation */
966                     IWineD3DSurface_GetContainer((IWineD3DSurface *) target, &IID_IWineD3DBaseTexture, (void **)&texture);
967
968                     if(texture) {
969                         IWineD3DBaseTexture_SetDirty(texture, TRUE);
970                         IWineD3DTexture_Release(texture);
971                     }
972                 } else {
973                     /* FBO offscreen target. Texture == Drawable */
974                     target->Flags |= SFLAG_INTEXTURE;
975                 }
976             } else {
977                 /* Must be an fbo render target */
978                 IWineD3DSurface_ModifyLocation((IWineD3DSurface *) target, SFLAG_INDRAWABLE, TRUE);
979                 target->Flags |=  SFLAG_INTEXTURE;
980             }
981         }
982     }
983
984     /* Ok, we will be updating the screen from here onwards so grab the lock */
985
986     if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
987         ENTER_GL();
988         apply_fbo_state(iface);
989         LEAVE_GL();
990     }
991
992     ActivateContext(This, This->render_targets[0], CTXUSAGE_DRAWPRIM);
993     ENTER_GL();
994
995     if (This->depth_copy_state == WINED3D_DCS_COPY) {
996         depth_copy(iface);
997     }
998     This->depth_copy_state = WINED3D_DCS_INITIAL;
999
1000     {
1001         GLenum glPrimType;
1002         BOOL emulation = FALSE;
1003         WineDirect3DVertexStridedData *strided = &This->strided_streams;
1004         WineDirect3DVertexStridedData stridedlcl;
1005         /* Ok, Work out which primitive is requested and how many vertexes that
1006            will be                                                              */
1007         UINT calculatedNumberOfindices = primitiveToGl(PrimitiveType, NumPrimitives, &glPrimType);
1008         if (numberOfVertices == 0 )
1009             numberOfVertices = calculatedNumberOfindices;
1010
1011         if(!use_vs(This)) {
1012             if(!This->strided_streams.u.s.position_transformed && This->activeContext->num_untracked_materials &&
1013                 This->stateBlock->renderState[WINED3DRS_LIGHTING]) {
1014                 FIXME("Using software emulation because not all material properties could be tracked\n");
1015                 emulation = TRUE;
1016             }
1017             else if(This->activeContext->fog_coord && This->stateBlock->renderState[WINED3DRS_FOGENABLE]) {
1018                 /* Either write a pipeline replacement shader or convert the specular alpha from unsigned byte
1019                  * to a float in the vertex buffer
1020                  */
1021                 FIXME("Using software emulation because manual fog coordinates are provided\n");
1022                 emulation = TRUE;
1023             }
1024
1025             if(emulation) {
1026                 strided = &stridedlcl;
1027                 memcpy(&stridedlcl, &This->strided_streams, sizeof(stridedlcl));
1028                 remove_vbos(This, &stridedlcl);
1029             }
1030         }
1031
1032         if (This->useDrawStridedSlow || emulation) {
1033             /* Immediate mode drawing */
1034             drawStridedSlow(iface, strided, calculatedNumberOfindices,
1035                             glPrimType, idxData, idxSize, minIndex, StartIdx, StartVertexIndex);
1036         } else if(This->instancedDraw) {
1037             /* Instancing emulation with mixing immediate mode and arrays */
1038             drawStridedInstanced(iface, &This->strided_streams, calculatedNumberOfindices, glPrimType,
1039                             idxData, idxSize, minIndex, StartIdx, StartVertexIndex);
1040         } else {
1041             /* Simple array draw call */
1042             drawStridedFast(iface, calculatedNumberOfindices, glPrimType,
1043                             idxData, idxSize, minIndex, StartIdx, StartVertexIndex);
1044         }
1045     }
1046
1047     /* Finshed updating the screen, restore lock */
1048     LEAVE_GL();
1049     TRACE("Done all gl drawing\n");
1050
1051     /* Diagnostics */
1052 #ifdef SHOW_FRAME_MAKEUP
1053     {
1054         static long int primCounter = 0;
1055         /* NOTE: set primCounter to the value reported by drawprim 
1056            before you want to to write frame makeup to /tmp */
1057         if (primCounter >= 0) {
1058             WINED3DLOCKED_RECT r;
1059             char buffer[80];
1060             IWineD3DSurface_LockRect(This->renderTarget, &r, NULL, WINED3DLOCK_READONLY);
1061             sprintf(buffer, "/tmp/backbuffer_%d.tga", primCounter);
1062             TRACE("Saving screenshot %s\n", buffer);
1063             IWineD3DSurface_SaveSnapshot(This->renderTarget, buffer);
1064             IWineD3DSurface_UnlockRect(This->renderTarget);
1065
1066 #ifdef SHOW_TEXTURE_MAKEUP
1067            {
1068             IWineD3DSurface *pSur;
1069             int textureNo;
1070             for (textureNo = 0; textureNo < MAX_COMBINED_SAMPLERS; ++textureNo) {
1071                 if (This->stateBlock->textures[textureNo] != NULL) {
1072                     sprintf(buffer, "/tmp/texture_%p_%d_%d.tga", This->stateBlock->textures[textureNo], primCounter, textureNo);
1073                     TRACE("Saving texture %s\n", buffer);
1074                     if (IWineD3DBaseTexture_GetType(This->stateBlock->textures[textureNo]) == WINED3DRTYPE_TEXTURE) {
1075                             IWineD3DTexture_GetSurfaceLevel((IWineD3DTexture *)This->stateBlock->textures[textureNo], 0, &pSur);
1076                             IWineD3DSurface_SaveSnapshot(pSur, buffer);
1077                             IWineD3DSurface_Release(pSur);
1078                     } else  {
1079                         FIXME("base Texture isn't of type texture %d\n", IWineD3DBaseTexture_GetType(This->stateBlock->textures[textureNo]));
1080                     }
1081                 }
1082             }
1083            }
1084 #endif
1085         }
1086         TRACE("drawprim #%d\n", primCounter);
1087         ++primCounter;
1088     }
1089 #endif
1090
1091     /* Control goes back to the device, stateblock values may change again */
1092     This->isInDraw = FALSE;
1093 }
1094
1095 static void normalize_normal(float *n) {
1096     float length = n[0] * n[0] + n[1] * n[1] + n[2] * n[2];
1097     if(length == 0.0) return;
1098     length = sqrt(length);
1099     n[0] = n[0] / length;
1100     n[1] = n[1] / length;
1101     n[2] = n[2] / length;
1102 }
1103
1104 /* Tesselates a high order rectangular patch into single triangles using gl evaluators
1105  *
1106  * The problem is that OpenGL does not offer a direct way to return the tesselated primitives,
1107  * and they can't be sent off for rendering directly either. Tesselating is slow, so we want
1108  * to chache the patches in a vertex buffer. But more importantly, gl can't bind generated
1109  * attributes to numbered shader attributes, so we have to store them and rebind them as needed
1110  * in drawprim.
1111  *
1112  * To read back, the opengl feedback mode is used. This creates a proplem because we want
1113  * untransformed, unlit vertices, but feedback runs everything through transform and lighting.
1114  * Thus disable lighting and set identity matrices to get unmodified colors and positions.
1115  * To overcome clipping find the biggest x, y and z values of the vertices in the patch and scale
1116  * them to [-1.0;+1.0] and set the viewport up to scale them back.
1117  *
1118  * Normals are more tricky: Draw white vertices with 3 directional lights, and calculate the
1119  * resulting colors back to the normals.
1120  *
1121  * NOTE: This function activates a context for blitting, modifies matrices & viewport, but
1122  * does not restore it because normally a draw follows immediately afterwards. The caller is
1123  * responsible of taking care that either the gl states are restored, or the context activated
1124  * for drawing to reset the lastWasBlit flag.
1125  */
1126 HRESULT tesselate_rectpatch(IWineD3DDeviceImpl *This,
1127                             struct WineD3DRectPatch *patch) {
1128     unsigned int i, j, num_quads, out_vertex_size, buffer_size, d3d_out_vertex_size;
1129     float max_x = 0.0, max_y = 0.0, max_z = 0.0, neg_z = 0.0;
1130     WineDirect3DVertexStridedData strided;
1131     BYTE *data;
1132     WINED3DRECTPATCH_INFO *info = &patch->RectPatchInfo;
1133     DWORD vtxStride;
1134     GLenum feedback_type;
1135     GLfloat *feedbuffer;
1136
1137     /* First, locate the position data. This is provided in a vertex buffer in the stateblock.
1138      * Beware of vbos
1139      */
1140     memset(&strided, 0, sizeof(strided));
1141     primitiveDeclarationConvertToStridedData((IWineD3DDevice *) This, FALSE, &strided, NULL);
1142     if(strided.u.s.position.VBO) {
1143         IWineD3DVertexBufferImpl *vb;
1144         vb = (IWineD3DVertexBufferImpl *) This->stateBlock->streamSource[strided.u.s.position.streamNo];
1145         strided.u.s.position.lpData = (BYTE *) ((unsigned long) strided.u.s.position.lpData +
1146                                                 (unsigned long) vb->resource.allocatedMemory);
1147     }
1148     vtxStride = strided.u.s.position.dwStride;
1149     data = strided.u.s.position.lpData +
1150            vtxStride * info->Stride * info->StartVertexOffsetHeight +
1151            vtxStride * info->StartVertexOffsetWidth;
1152
1153     /* Not entirely sure about what happens with transformed vertices */
1154     if(strided.u.s.position_transformed) {
1155         FIXME("Transformed position in rectpatch generation\n");
1156     }
1157     if(vtxStride % sizeof(GLfloat)) {
1158         /* glMap2f reads vertex sizes in GLfloats, the d3d stride is in bytes.
1159          * I don't see how the stride could not be a multiple of 4, but make sure
1160          * to check it
1161          */
1162         ERR("Vertex stride is not a multiple of sizeof(GLfloat)\n");
1163     }
1164     if(info->Basis != WINED3DBASIS_BEZIER) {
1165         FIXME("Basis is %s, how to handle this?\n", debug_d3dbasis(info->Basis));
1166     }
1167     if(info->Degree != WINED3DDEGREE_CUBIC) {
1168         FIXME("Degree is %s, how to handle this?\n", debug_d3ddegree(info->Degree));
1169     }
1170
1171     /* First, get the boundary cube of the input data */
1172     for(j = 0; j < info->Height; j++) {
1173         for(i = 0; i < info->Width; i++) {
1174             float *v = (float *) (data + vtxStride * i + vtxStride * info->Stride * j);
1175             if(fabs(v[0]) > max_x) max_x = fabs(v[0]);
1176             if(fabs(v[1]) > max_y) max_y = fabs(v[1]);
1177             if(fabs(v[2]) > max_z) max_z = fabs(v[2]);
1178             if(v[2] < neg_z) neg_z = v[2];
1179         }
1180     }
1181
1182     /* This needs some improvements in the vertex decl code */
1183     FIXME("Cannot find data to generate. Only generating position and normals\n");
1184     patch->has_normals = TRUE;
1185     patch->has_texcoords = FALSE;
1186
1187     /* Simply activate the context for blitting. This disables all the things we don't want and
1188      * takes care of dirtifying. Dirtifying is preferred over pushing / popping, since drawing the
1189      * patch (as opposed to normal draws) will most likely need different changes anyway
1190      */
1191     ActivateContext(This, This->lastActiveRenderTarget, CTXUSAGE_BLIT);
1192     ENTER_GL();
1193
1194     glMatrixMode(GL_PROJECTION);
1195     checkGLcall("glMatrixMode(GL_PROJECTION)");
1196     glLoadIdentity();
1197     checkGLcall("glLoadIndentity()");
1198     glScalef(1 / (max_x) , 1 / (max_y), max_z == 0 ? 1 : 1 / ( 2 * max_z));
1199     glTranslatef(0, 0, 0.5);
1200     checkGLcall("glScalef");
1201     glViewport(-max_x, -max_y, 2 * (max_x), 2 * (max_y));
1202     checkGLcall("glViewport");
1203
1204     /* Some states to take care of. If we're in wireframe opengl will produce lines, and confuse
1205      * our feedback buffer parser
1206      */
1207     glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
1208     checkGLcall("glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)");
1209     IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_FILLMODE));
1210     if(patch->has_normals) {
1211         float black[4] = {0, 0, 0, 0};
1212         float red[4]   = {1, 0, 0, 0};
1213         float green[4] = {0, 1, 0, 0};
1214         float blue[4]  = {0, 0, 1, 0};
1215         float white[4] = {1, 1, 1, 1};
1216         glEnable(GL_LIGHTING);
1217         checkGLcall("glEnable(GL_LIGHTING)");
1218         glLightModelfv(GL_LIGHT_MODEL_AMBIENT, black);
1219         checkGLcall("glLightModel for MODEL_AMBIENT");
1220         IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_AMBIENT));
1221
1222         for(i = 3; i < GL_LIMITS(lights); i++) {
1223             glDisable(GL_LIGHT0 + i);
1224             checkGLcall("glDisable(GL_LIGHT0 + i)");
1225             IWineD3DDeviceImpl_MarkStateDirty(This, STATE_ACTIVELIGHT(i));
1226         }
1227
1228         IWineD3DDeviceImpl_MarkStateDirty(This, STATE_ACTIVELIGHT(0));
1229         glLightfv(GL_LIGHT0, GL_DIFFUSE, red);
1230         glLightfv(GL_LIGHT0, GL_SPECULAR, black);
1231         glLightfv(GL_LIGHT0, GL_AMBIENT, black);
1232         glLightfv(GL_LIGHT0, GL_POSITION, red);
1233         glEnable(GL_LIGHT0);
1234         checkGLcall("Setting up light 1\n");
1235         IWineD3DDeviceImpl_MarkStateDirty(This, STATE_ACTIVELIGHT(1));
1236         glLightfv(GL_LIGHT1, GL_DIFFUSE, green);
1237         glLightfv(GL_LIGHT1, GL_SPECULAR, black);
1238         glLightfv(GL_LIGHT1, GL_AMBIENT, black);
1239         glLightfv(GL_LIGHT1, GL_POSITION, green);
1240         glEnable(GL_LIGHT1);
1241         checkGLcall("Setting up light 2\n");
1242         IWineD3DDeviceImpl_MarkStateDirty(This, STATE_ACTIVELIGHT(2));
1243         glLightfv(GL_LIGHT2, GL_DIFFUSE, blue);
1244         glLightfv(GL_LIGHT2, GL_SPECULAR, black);
1245         glLightfv(GL_LIGHT2, GL_AMBIENT, black);
1246         glLightfv(GL_LIGHT2, GL_POSITION, blue);
1247         glEnable(GL_LIGHT2);
1248         checkGLcall("Setting up light 3\n");
1249
1250         IWineD3DDeviceImpl_MarkStateDirty(This, STATE_MATERIAL);
1251         IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_COLORVERTEX));
1252         glDisable(GL_COLOR_MATERIAL);
1253         glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, black);
1254         glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, black);
1255         glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, white);
1256         checkGLcall("Setting up materials\n");
1257     }
1258
1259     /* Enable the needed maps.
1260      * GL_MAP2_VERTEX_3 is needed for positional data.
1261      * GL_AUTO_NORMAL to generate normals from the position. Do not use GL_MAP2_NORMAL.
1262      * GL_MAP2_TEXTURE_COORD_4 for texture coords
1263      */
1264     num_quads = ceilf(patch->numSegs[0]) * ceilf(patch->numSegs[1]);
1265     out_vertex_size = 3 /* position */;
1266     d3d_out_vertex_size = 3;
1267     glEnable(GL_MAP2_VERTEX_3);
1268     if(patch->has_normals && patch->has_texcoords) {
1269         FIXME("Texcoords not handled yet\n");
1270         feedback_type = GL_3D_COLOR_TEXTURE;
1271         out_vertex_size += 8;
1272         d3d_out_vertex_size += 7;
1273         glEnable(GL_AUTO_NORMAL);
1274         glEnable(GL_MAP2_TEXTURE_COORD_4);
1275     } else if(patch->has_texcoords) {
1276         FIXME("Texcoords not handled yet\n");
1277         feedback_type = GL_3D_COLOR_TEXTURE;
1278         out_vertex_size += 7;
1279         d3d_out_vertex_size += 4;
1280         glEnable(GL_MAP2_TEXTURE_COORD_4);
1281     } else if(patch->has_normals) {
1282         feedback_type = GL_3D_COLOR;
1283         out_vertex_size += 4;
1284         d3d_out_vertex_size += 3;
1285         glEnable(GL_AUTO_NORMAL);
1286     } else {
1287         feedback_type = GL_3D;
1288     }
1289     checkGLcall("glEnable vertex attrib generation");
1290
1291     buffer_size = num_quads * out_vertex_size * 2 /* triangle list */ * 3 /* verts per tri */
1292                    + 4 * num_quads /* 2 triangle markers per quad + num verts in tri */;
1293     feedbuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, buffer_size * sizeof(float) * 8);
1294
1295     glMap2f(GL_MAP2_VERTEX_3,
1296             0, 1, vtxStride / sizeof(float), info->Width,
1297             0, 1, info->Stride * vtxStride / sizeof(float), info->Height,
1298             (float *) data);
1299     checkGLcall("glMap2f");
1300     if(patch->has_texcoords) {
1301         glMap2f(GL_MAP2_TEXTURE_COORD_4,
1302                 0, 1, vtxStride / sizeof(float), info->Width,
1303                 0, 1, info->Stride * vtxStride / sizeof(float), info->Height,
1304                 (float *) data);
1305         checkGLcall("glMap2f");
1306     }
1307     glMapGrid2f(ceilf(patch->numSegs[0]), 0.0, 1.0, ceilf(patch->numSegs[1]), 0.0, 1.0);
1308     checkGLcall("glMapGrid2f");
1309
1310     glFeedbackBuffer(buffer_size * 2, feedback_type, feedbuffer);
1311     checkGLcall("glFeedbackBuffer");
1312     glRenderMode(GL_FEEDBACK);
1313
1314     glEvalMesh2(GL_FILL, 0, ceilf(patch->numSegs[0]), 0, ceilf(patch->numSegs[1]));
1315     checkGLcall("glEvalMesh2\n");
1316
1317     i = glRenderMode(GL_RENDER);
1318     if(i == -1) {
1319         ERR("Feedback failed. Expected %d elements back\n", buffer_size);
1320         Sleep(10000);
1321         HeapFree(GetProcessHeap(), 0, feedbuffer);
1322         return WINED3DERR_DRIVERINTERNALERROR;
1323     } else if(i != buffer_size) {
1324         ERR("Unexpected amount of elements returned. Expected %d, got %d\n", buffer_size, i);
1325         Sleep(10000);
1326         HeapFree(GetProcessHeap(), 0, feedbuffer);
1327         return WINED3DERR_DRIVERINTERNALERROR;
1328     } else {
1329         TRACE("Got %d elements as expected\n", i);
1330     }
1331
1332     HeapFree(GetProcessHeap(), 0, patch->mem);
1333     patch->mem = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, num_quads * 6 * d3d_out_vertex_size * sizeof(float) * 8);
1334     i = 0;
1335     for(j = 0; j < buffer_size; j += (3 /* num verts */ * out_vertex_size + 2 /* tri marker */)) {
1336         if(feedbuffer[j] != GL_POLYGON_TOKEN) {
1337             ERR("Unexpected token: %f\n", feedbuffer[j]);
1338             continue;
1339         }
1340         if(feedbuffer[j + 1] != 3) {
1341             ERR("Unexpected polygon: %f corners\n", feedbuffer[j + 1]);
1342             continue;
1343         }
1344         /* Somehow there are different ideas about back / front facing, so fix up the
1345          * vertex order
1346          */
1347         patch->mem[i + 0] =  feedbuffer[j + out_vertex_size * 2 + 2]; /* x, triangle 2 */
1348         patch->mem[i + 1] =  feedbuffer[j + out_vertex_size * 2 + 3]; /* y, triangle 2 */
1349         patch->mem[i + 2] = (feedbuffer[j + out_vertex_size * 2 + 4] - 0.5) * 4 * max_z; /* z, triangle 3 */
1350         if(patch->has_normals) {
1351             patch->mem[i + 3] = feedbuffer[j + out_vertex_size * 2 + 5];
1352             patch->mem[i + 4] = feedbuffer[j + out_vertex_size * 2 + 6];
1353             patch->mem[i + 5] = feedbuffer[j + out_vertex_size * 2 + 7];
1354         }
1355         i += d3d_out_vertex_size;
1356
1357         patch->mem[i + 0] =  feedbuffer[j + out_vertex_size * 1 + 2]; /* x, triangle 2 */
1358         patch->mem[i + 1] =  feedbuffer[j + out_vertex_size * 1 + 3]; /* y, triangle 2 */
1359         patch->mem[i + 2] = (feedbuffer[j + out_vertex_size * 1 + 4] - 0.5) * 4 * max_z; /* z, triangle 2 */
1360         if(patch->has_normals) {
1361             patch->mem[i + 3] = feedbuffer[j + out_vertex_size * 1 + 5];
1362             patch->mem[i + 4] = feedbuffer[j + out_vertex_size * 1 + 6];
1363             patch->mem[i + 5] = feedbuffer[j + out_vertex_size * 1 + 7];
1364         }
1365         i += d3d_out_vertex_size;
1366
1367         patch->mem[i + 0] =  feedbuffer[j + out_vertex_size * 0 + 2]; /* x, triangle 1 */
1368         patch->mem[i + 1] =  feedbuffer[j + out_vertex_size * 0 + 3]; /* y, triangle 1 */
1369         patch->mem[i + 2] = (feedbuffer[j + out_vertex_size * 0 + 4] - 0.5) * 4 * max_z; /* z, triangle 1 */
1370         if(patch->has_normals) {
1371             patch->mem[i + 3] = feedbuffer[j + out_vertex_size * 0 + 5];
1372             patch->mem[i + 4] = feedbuffer[j + out_vertex_size * 0 + 6];
1373             patch->mem[i + 5] = feedbuffer[j + out_vertex_size * 0 + 7];
1374         }
1375         i += d3d_out_vertex_size;
1376     }
1377
1378     if(patch->has_normals) {
1379         /* Now do the same with reverse light directions */
1380         float x[4] = {-1,  0,  0, 0};
1381         float y[4] = { 0, -1,  0, 0};
1382         float z[4] = { 0,  0, -1, 0};
1383         glLightfv(GL_LIGHT0, GL_POSITION, x);
1384         glLightfv(GL_LIGHT1, GL_POSITION, y);
1385         glLightfv(GL_LIGHT2, GL_POSITION, z);
1386         checkGLcall("Setting up reverse light directions\n");
1387
1388         glRenderMode(GL_FEEDBACK);
1389         checkGLcall("glRenderMode(GL_FEEDBACK)");
1390         glEvalMesh2(GL_FILL, 0, ceilf(patch->numSegs[0]), 0, ceilf(patch->numSegs[1]));
1391         checkGLcall("glEvalMesh2\n");
1392         i = glRenderMode(GL_RENDER);
1393         checkGLcall("glRenderMode(GL_RENDER)");
1394
1395         i = 0;
1396         for(j = 0; j < buffer_size; j += (3 /* num verts */ * out_vertex_size + 2 /* tri marker */)) {
1397             if(feedbuffer[j] != GL_POLYGON_TOKEN) {
1398                 ERR("Unexpected token: %f\n", feedbuffer[j]);
1399                 continue;
1400             }
1401             if(feedbuffer[j + 1] != 3) {
1402                 ERR("Unexpected polygon: %f corners\n", feedbuffer[j + 1]);
1403                 continue;
1404             }
1405             if(patch->mem[i + 3] == 0.0)
1406                 patch->mem[i + 3] = -feedbuffer[j + out_vertex_size * 2 + 5];
1407             if(patch->mem[i + 4] == 0.0)
1408                 patch->mem[i + 4] = -feedbuffer[j + out_vertex_size * 2 + 6];
1409             if(patch->mem[i + 5] == 0.0)
1410                 patch->mem[i + 5] = -feedbuffer[j + out_vertex_size * 2 + 7];
1411             normalize_normal(patch->mem + i + 3);
1412             i += d3d_out_vertex_size;
1413
1414             if(patch->mem[i + 3] == 0.0)
1415                 patch->mem[i + 3] = -feedbuffer[j + out_vertex_size * 1 + 5];
1416             if(patch->mem[i + 4] == 0.0)
1417                 patch->mem[i + 4] = -feedbuffer[j + out_vertex_size * 1 + 6];
1418             if(patch->mem[i + 5] == 0.0)
1419                 patch->mem[i + 5] = -feedbuffer[j + out_vertex_size * 1 + 7];
1420             normalize_normal(patch->mem + i + 3);
1421             i += d3d_out_vertex_size;
1422
1423             if(patch->mem[i + 3] == 0.0)
1424                 patch->mem[i + 3] = -feedbuffer[j + out_vertex_size * 0 + 5];
1425             if(patch->mem[i + 4] == 0.0)
1426                 patch->mem[i + 4] = -feedbuffer[j + out_vertex_size * 0 + 6];
1427             if(patch->mem[i + 5] == 0.0)
1428                 patch->mem[i + 5] = -feedbuffer[j + out_vertex_size * 0 + 7];
1429             normalize_normal(patch->mem + i + 3);
1430             i += d3d_out_vertex_size;
1431         }
1432     }
1433
1434     glDisable(GL_MAP2_VERTEX_3);
1435     glDisable(GL_AUTO_NORMAL);
1436     glDisable(GL_MAP2_NORMAL);
1437     glDisable(GL_MAP2_TEXTURE_COORD_4);
1438     checkGLcall("glDisable vertex attrib generation");
1439     LEAVE_GL();
1440
1441     HeapFree(GetProcessHeap(), 0, feedbuffer);
1442
1443     vtxStride = 3 * sizeof(float);
1444     if(patch->has_normals) {
1445         vtxStride += 3 * sizeof(float);
1446     }
1447     if(patch->has_texcoords) {
1448         vtxStride += 4 * sizeof(float);
1449     }
1450     memset(&patch->strided, 0, sizeof(&patch->strided));
1451     patch->strided.u.s.position.lpData = (BYTE *) patch->mem;
1452     patch->strided.u.s.position.dwStride = vtxStride;
1453     patch->strided.u.s.position.dwType = WINED3DDECLTYPE_FLOAT3;
1454     patch->strided.u.s.position.streamNo = 255;
1455
1456     if(patch->has_normals) {
1457         patch->strided.u.s.normal.lpData = (BYTE *) patch->mem + 3 * sizeof(float) /* pos */;
1458         patch->strided.u.s.normal.dwStride = vtxStride;
1459         patch->strided.u.s.normal.dwType = WINED3DDECLTYPE_FLOAT3;
1460         patch->strided.u.s.normal.streamNo = 255;
1461     }
1462     if(patch->has_texcoords) {
1463         patch->strided.u.s.texCoords[0].lpData = (BYTE *) patch->mem + 3 * sizeof(float) /* pos */;
1464         if(patch->has_normals) {
1465             patch->strided.u.s.texCoords[0].lpData += 3 * sizeof(float);
1466         }
1467         patch->strided.u.s.texCoords[0].dwStride = vtxStride;
1468         patch->strided.u.s.texCoords[0].dwType = WINED3DDECLTYPE_FLOAT4;
1469         /* MAX_STREAMS index points to an unused element in stateblock->streamOffsets which
1470          * always remains set to 0. Windows uses stream 255 here, but this is not visible to the
1471          * application.
1472          */
1473         patch->strided.u.s.texCoords[0].streamNo = MAX_STREAMS;
1474     }
1475
1476     return WINED3D_OK;
1477 }