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