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