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