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