wined3d: Only use 4 component specular colors if GL allows it.
[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, 2008 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 /* GL locking is done by the caller */
36 static void drawStridedFast(IWineD3DDevice *iface, GLenum primitive_type,
37         UINT min_vertex_idx, UINT max_vertex_idx, UINT count, UINT idx_size,
38         const void *idx_data, UINT start_idx)
39 {
40     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
41
42     if (idx_size)
43     {
44         TRACE("(%p) : glElements(%x, %d, %d, ...)\n", This, primitive_type, count, min_vertex_idx);
45
46 #if 1
47         glDrawElements(primitive_type, count,
48                 idx_size == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT,
49                 (const char *)idx_data + (idx_size * start_idx));
50         checkGLcall("glDrawElements");
51 #else
52         glDrawRangeElements(primitive_type, min_vertex_idx, max_vertex_idx, count,
53                 idx_size == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT,
54                 (const char *)idx_data + (idx_size * start_idx));
55         checkGLcall("glDrawRangeElements");
56 #endif
57     }
58     else
59     {
60         TRACE("(%p) : glDrawArrays(%#x, %d, %d)\n", This, primitive_type, start_idx, count);
61
62         glDrawArrays(primitive_type, start_idx, count);
63         checkGLcall("glDrawArrays");
64     }
65 }
66
67 /*
68  * Actually draw using the supplied information.
69  * Slower GL version which extracts info about each vertex in turn
70  */
71
72 /* GL locking is done by the caller */
73 static void drawStridedSlow(IWineD3DDevice *iface, const struct wined3d_stream_info *si, UINT NumVertexes,
74         GLenum glPrimType, const void *idxData, UINT idxSize, UINT minIndex, UINT startIdx)
75 {
76     unsigned int               textureNo    = 0;
77     const WORD                *pIdxBufS     = NULL;
78     const DWORD               *pIdxBufL     = NULL;
79     UINT vx_index;
80     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
81     const UINT *streamOffset = This->stateBlock->streamOffset;
82     long                      SkipnStrides = startIdx + This->stateBlock->loadBaseVertexIndex;
83     BOOL                      pixelShader = use_ps(This->stateBlock);
84     BOOL specular_fog = FALSE;
85     UINT texture_stages = GL_LIMITS(texture_stages);
86     const BYTE *texCoords[WINED3DDP_MAXTEXCOORD];
87     const BYTE *diffuse = NULL, *specular = NULL, *normal = NULL, *position = NULL;
88     const struct wined3d_stream_info_element *element;
89     UINT num_untracked_materials;
90     DWORD tex_mask = 0;
91
92     TRACE("Using slow vertex array code\n");
93
94     /* Variable Initialization */
95     if (idxSize != 0) {
96         /* Immediate mode drawing can't make use of indices in a vbo - get the data from the index buffer.
97          * If the index buffer has no vbo(not supported or other reason), or with user pointer drawing
98          * idxData will be != NULL
99          */
100         if(idxData == NULL) {
101             idxData = buffer_get_sysmem((struct wined3d_buffer *) This->stateBlock->pIndexData);
102         }
103
104         if (idxSize == 2) pIdxBufS = idxData;
105         else pIdxBufL = idxData;
106     } else if (idxData) {
107         ERR("non-NULL idxData with 0 idxSize, this should never happen\n");
108         return;
109     }
110
111     /* Start drawing in GL */
112     VTRACE(("glBegin(%x)\n", glPrimType));
113     glBegin(glPrimType);
114
115     element = &si->elements[WINED3D_FFP_POSITION];
116     if (element->data) position = element->data + streamOffset[element->stream_idx];
117
118     element = &si->elements[WINED3D_FFP_NORMAL];
119     if (element->data) normal = element->data + streamOffset[element->stream_idx];
120     else glNormal3f(0, 0, 0);
121
122     element = &si->elements[WINED3D_FFP_DIFFUSE];
123     if (element->data) diffuse = element->data + streamOffset[element->stream_idx];
124     else glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
125     num_untracked_materials = This->activeContext->num_untracked_materials;
126     if (num_untracked_materials && element->format_desc->format != WINED3DFMT_A8R8G8B8)
127         FIXME("Implement diffuse color tracking from %s\n", debug_d3dformat(element->format_desc->format));
128
129     element = &si->elements[WINED3D_FFP_SPECULAR];
130     if (element->data)
131     {
132         specular = element->data + streamOffset[element->stream_idx];
133
134         /* special case where the fog density is stored in the specular alpha channel */
135         if (This->stateBlock->renderState[WINED3DRS_FOGENABLE]
136                 && (This->stateBlock->renderState[WINED3DRS_FOGVERTEXMODE] == WINED3DFOG_NONE
137                     || si->elements[WINED3D_FFP_POSITION].format_desc->format == WINED3DFMT_R32G32B32A32_FLOAT)
138                 && This->stateBlock->renderState[WINED3DRS_FOGTABLEMODE] == WINED3DFOG_NONE)
139         {
140             if (GL_SUPPORT(EXT_FOG_COORD))
141             {
142                 if (element->format_desc->format == WINED3DFMT_A8R8G8B8) specular_fog = TRUE;
143                 else FIXME("Implement fog coordinates from %s\n", debug_d3dformat(element->format_desc->format));
144             }
145             else
146             {
147                 static BOOL warned;
148
149                 if (!warned)
150                 {
151                     /* TODO: Use the fog table code from old ddraw */
152                     FIXME("Implement fog for transformed vertices in software\n");
153                     warned = TRUE;
154                 }
155             }
156         }
157     }
158     else if (GL_SUPPORT(EXT_SECONDARY_COLOR))
159     {
160         GL_EXTCALL(glSecondaryColor3fEXT)(0, 0, 0);
161     }
162
163     for (textureNo = 0; textureNo < texture_stages; ++textureNo)
164     {
165         int coordIdx = This->stateBlock->textureState[textureNo][WINED3DTSS_TEXCOORDINDEX];
166         int texture_idx = This->texUnitMap[textureNo];
167
168         if (!GL_SUPPORT(ARB_MULTITEXTURE) && textureNo > 0)
169         {
170             FIXME("Program using multiple concurrent textures which this opengl implementation doesn't support\n");
171             continue;
172         }
173
174         if (!pixelShader && !This->stateBlock->textures[textureNo]) continue;
175
176         if (texture_idx == -1) continue;
177
178         if (coordIdx > 7)
179         {
180             TRACE("tex: %d - Skip tex coords, as being system generated\n", textureNo);
181             continue;
182         }
183         else if (coordIdx < 0)
184         {
185             FIXME("tex: %d - Coord index %d is less than zero, expect a crash.\n", textureNo, coordIdx);
186             continue;
187         }
188
189         element = &si->elements[WINED3D_FFP_TEXCOORD0 + coordIdx];
190         if (element->data)
191         {
192             texCoords[coordIdx] = element->data + streamOffset[element->stream_idx];
193             tex_mask |= (1 << textureNo);
194         }
195         else
196         {
197             TRACE("tex: %d - Skipping tex coords, as no data supplied\n", textureNo);
198             if (GL_SUPPORT(ARB_MULTITEXTURE))
199                 GL_EXTCALL(glMultiTexCoord4fARB(GL_TEXTURE0_ARB + texture_idx, 0, 0, 0, 1));
200             else
201                 glTexCoord4f(0, 0, 0, 1);
202         }
203     }
204
205     /* We shouldn't start this function if any VBO is involved. Should I put a safety check here?
206      * Guess it's not necessary(we crash then anyway) and would only eat CPU time
207      */
208
209     /* For each primitive */
210     for (vx_index = 0; vx_index < NumVertexes; ++vx_index) {
211         UINT texture, tmp_tex_mask;
212         /* Blending data and Point sizes are not supported by this function. They are not supported by the fixed
213          * function pipeline at all. A Fixme for them is printed after decoding the vertex declaration
214          */
215
216         /* For indexed data, we need to go a few more strides in */
217         if (idxData != NULL) {
218
219             /* Indexed so work out the number of strides to skip */
220             if (idxSize == 2) {
221                 VTRACE(("Idx for vertex %u = %u\n", vx_index, pIdxBufS[startIdx+vx_index]));
222                 SkipnStrides = pIdxBufS[startIdx + vx_index] + This->stateBlock->loadBaseVertexIndex;
223             } else {
224                 VTRACE(("Idx for vertex %u = %u\n", vx_index, pIdxBufL[startIdx+vx_index]));
225                 SkipnStrides = pIdxBufL[startIdx + vx_index] + This->stateBlock->loadBaseVertexIndex;
226             }
227         }
228
229         tmp_tex_mask = tex_mask;
230         for (texture = 0; tmp_tex_mask; tmp_tex_mask >>= 1, ++texture)
231         {
232             int coord_idx;
233             const void *ptr;
234             int texture_idx;
235
236             if (!(tmp_tex_mask & 1)) continue;
237
238             coord_idx = This->stateBlock->textureState[texture][WINED3DTSS_TEXCOORDINDEX];
239             ptr = texCoords[coord_idx] + (SkipnStrides * si->elements[WINED3D_FFP_TEXCOORD0 + coord_idx].stride);
240
241             texture_idx = This->texUnitMap[texture];
242             multi_texcoord_funcs[si->elements[WINED3D_FFP_TEXCOORD0 + coord_idx].format_desc->emit_idx](
243                     GL_TEXTURE0_ARB + texture_idx, ptr);
244         }
245
246         /* Diffuse -------------------------------- */
247         if (diffuse) {
248             const void *ptrToCoords = diffuse + SkipnStrides * si->elements[WINED3D_FFP_DIFFUSE].stride;
249
250             diffuse_funcs[si->elements[WINED3D_FFP_DIFFUSE].format_desc->emit_idx](ptrToCoords);
251             if (num_untracked_materials)
252             {
253                 DWORD diffuseColor = ((const DWORD *)ptrToCoords)[0];
254                 unsigned char i;
255                 float color[4];
256
257                 color[0] = D3DCOLOR_B_R(diffuseColor) / 255.0f;
258                 color[1] = D3DCOLOR_B_G(diffuseColor) / 255.0f;
259                 color[2] = D3DCOLOR_B_B(diffuseColor) / 255.0f;
260                 color[3] = D3DCOLOR_B_A(diffuseColor) / 255.0f;
261
262                 for (i = 0; i < num_untracked_materials; ++i)
263                 {
264                     glMaterialfv(GL_FRONT_AND_BACK, This->activeContext->untracked_materials[i], color);
265                 }
266             }
267         }
268
269         /* Specular ------------------------------- */
270         if (specular) {
271             const void *ptrToCoords = specular + SkipnStrides * si->elements[WINED3D_FFP_SPECULAR].stride;
272
273             specular_funcs[si->elements[WINED3D_FFP_SPECULAR].format_desc->emit_idx](ptrToCoords);
274
275             if (specular_fog)
276             {
277                 DWORD specularColor = *(const DWORD *)ptrToCoords;
278                 GL_EXTCALL(glFogCoordfEXT(specularColor >> 24));
279             }
280         }
281
282         /* Normal -------------------------------- */
283         if (normal != NULL) {
284             const void *ptrToCoords = normal + SkipnStrides * si->elements[WINED3D_FFP_NORMAL].stride;
285             normal_funcs[si->elements[WINED3D_FFP_NORMAL].format_desc->emit_idx](ptrToCoords);
286         }
287
288         /* Position -------------------------------- */
289         if (position) {
290             const void *ptrToCoords = position + SkipnStrides * si->elements[WINED3D_FFP_POSITION].stride;
291             position_funcs[si->elements[WINED3D_FFP_POSITION].format_desc->emit_idx](ptrToCoords);
292         }
293
294         /* For non indexed mode, step onto next parts */
295         if (idxData == NULL) {
296             ++SkipnStrides;
297         }
298     }
299
300     glEnd();
301     checkGLcall("glEnd and previous calls");
302 }
303
304 /* GL locking is done by the caller */
305 static inline void send_attribute(IWineD3DDeviceImpl *This, WINED3DFORMAT format, const UINT index, const void *ptr)
306 {
307     switch(format)
308     {
309         case WINED3DFMT_R32_FLOAT:
310             GL_EXTCALL(glVertexAttrib1fvARB(index, ptr));
311             break;
312         case WINED3DFMT_R32G32_FLOAT:
313             GL_EXTCALL(glVertexAttrib2fvARB(index, ptr));
314             break;
315         case WINED3DFMT_R32G32B32_FLOAT:
316             GL_EXTCALL(glVertexAttrib3fvARB(index, ptr));
317             break;
318         case WINED3DFMT_R32G32B32A32_FLOAT:
319             GL_EXTCALL(glVertexAttrib4fvARB(index, ptr));
320             break;
321
322         case WINED3DFMT_R8G8B8A8_UINT:
323             GL_EXTCALL(glVertexAttrib4ubvARB(index, ptr));
324             break;
325         case WINED3DFMT_A8R8G8B8:
326             if (GL_SUPPORT(EXT_VERTEX_ARRAY_BGRA))
327             {
328                 const DWORD *src = ptr;
329                 DWORD c = *src & 0xff00ff00;
330                 c |= (*src & 0xff0000) >> 16;
331                 c |= (*src & 0xff) << 16;
332                 GL_EXTCALL(glVertexAttrib4NubvARB(index, (GLubyte *)&c));
333                 break;
334             }
335             /* else fallthrough */
336         case WINED3DFMT_R8G8B8A8_UNORM:
337             GL_EXTCALL(glVertexAttrib4NubvARB(index, ptr));
338             break;
339
340         case WINED3DFMT_R16G16_SINT:
341             GL_EXTCALL(glVertexAttrib4svARB(index, ptr));
342             break;
343         case WINED3DFMT_R16G16B16A16_SINT:
344             GL_EXTCALL(glVertexAttrib4svARB(index, ptr));
345             break;
346
347         case WINED3DFMT_R16G16_SNORM:
348         {
349             GLshort s[4] = {((const GLshort *)ptr)[0], ((const GLshort *)ptr)[1], 0, 1};
350             GL_EXTCALL(glVertexAttrib4NsvARB(index, s));
351             break;
352         }
353         case WINED3DFMT_R16G16_UNORM:
354         {
355             GLushort s[4] = {((const GLushort *)ptr)[0], ((const GLushort *)ptr)[1], 0, 1};
356             GL_EXTCALL(glVertexAttrib4NusvARB(index, s));
357             break;
358         }
359         case WINED3DFMT_R16G16B16A16_SNORM:
360             GL_EXTCALL(glVertexAttrib4NsvARB(index, ptr));
361             break;
362         case WINED3DFMT_R16G16B16A16_UNORM:
363             GL_EXTCALL(glVertexAttrib4NusvARB(index, ptr));
364             break;
365
366         case WINED3DFMT_R10G10B10A2_UINT:
367             FIXME("Unsure about WINED3DDECLTYPE_UDEC3\n");
368             /*glVertexAttrib3usvARB(instancedData[j], (GLushort *) ptr); Does not exist */
369             break;
370         case WINED3DFMT_R10G10B10A2_SNORM:
371             FIXME("Unsure about WINED3DDECLTYPE_DEC3N\n");
372             /*glVertexAttrib3NusvARB(instancedData[j], (GLushort *) ptr); Does not exist */
373             break;
374
375         case WINED3DFMT_R16G16_FLOAT:
376             /* Are those 16 bit floats. C doesn't have a 16 bit float type. I could read the single bits and calculate a 4
377              * byte float according to the IEEE standard
378              */
379             if (GL_SUPPORT(NV_HALF_FLOAT)) {
380                 /* Not supported by GL_ARB_half_float_vertex */
381                 GL_EXTCALL(glVertexAttrib2hvNV(index, ptr));
382             } else {
383                 float x = float_16_to_32(((const unsigned short *)ptr) + 0);
384                 float y = float_16_to_32(((const unsigned short *)ptr) + 1);
385                 GL_EXTCALL(glVertexAttrib2fARB(index, x, y));
386             }
387             break;
388         case WINED3DFMT_R16G16B16A16_FLOAT:
389             if (GL_SUPPORT(NV_HALF_FLOAT)) {
390                 /* Not supported by GL_ARB_half_float_vertex */
391                 GL_EXTCALL(glVertexAttrib4hvNV(index, ptr));
392             } else {
393                 float x = float_16_to_32(((const unsigned short *)ptr) + 0);
394                 float y = float_16_to_32(((const unsigned short *)ptr) + 1);
395                 float z = float_16_to_32(((const unsigned short *)ptr) + 2);
396                 float w = float_16_to_32(((const unsigned short *)ptr) + 3);
397                 GL_EXTCALL(glVertexAttrib4fARB(index, x, y, z, w));
398             }
399             break;
400
401         default:
402             ERR("Unexpected attribute format: %s\n", debug_d3dformat(format));
403             break;
404     }
405 }
406
407 /* GL locking is done by the caller */
408 static void drawStridedSlowVs(IWineD3DDevice *iface, const struct wined3d_stream_info *si, UINT numberOfVertices,
409         GLenum glPrimitiveType, const void *idxData, UINT idxSize, UINT minIndex, UINT startIdx)
410 {
411     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
412     long                      SkipnStrides = startIdx + This->stateBlock->loadBaseVertexIndex;
413     const WORD                *pIdxBufS     = NULL;
414     const DWORD               *pIdxBufL     = NULL;
415     UINT vx_index;
416     int i;
417     IWineD3DStateBlockImpl *stateblock = This->stateBlock;
418     const BYTE *ptr;
419
420     if (idxSize != 0) {
421         /* Immediate mode drawing can't make use of indices in a vbo - get the data from the index buffer.
422          * If the index buffer has no vbo(not supported or other reason), or with user pointer drawing
423          * idxData will be != NULL
424          */
425         if(idxData == NULL) {
426             idxData = buffer_get_sysmem((struct wined3d_buffer *) This->stateBlock->pIndexData);
427         }
428
429         if (idxSize == 2) pIdxBufS = idxData;
430         else pIdxBufL = idxData;
431     } else if (idxData) {
432         ERR("non-NULL idxData with 0 idxSize, this should never happen\n");
433         return;
434     }
435
436     /* Start drawing in GL */
437     VTRACE(("glBegin(%x)\n", glPrimitiveType));
438     glBegin(glPrimitiveType);
439
440     for (vx_index = 0; vx_index < numberOfVertices; ++vx_index) {
441         if (idxData != NULL) {
442
443             /* Indexed so work out the number of strides to skip */
444             if (idxSize == 2) {
445                 VTRACE(("Idx for vertex %d = %d\n", vx_index, pIdxBufS[startIdx+vx_index]));
446                 SkipnStrides = pIdxBufS[startIdx + vx_index] + stateblock->loadBaseVertexIndex;
447             } else {
448                 VTRACE(("Idx for vertex %d = %d\n", vx_index, pIdxBufL[startIdx+vx_index]));
449                 SkipnStrides = pIdxBufL[startIdx + vx_index] + stateblock->loadBaseVertexIndex;
450             }
451         }
452
453         for(i = MAX_ATTRIBS - 1; i >= 0; i--) {
454             if(!si->elements[i].data) continue;
455
456             ptr = si->elements[i].data +
457                   si->elements[i].stride * SkipnStrides +
458                   stateblock->streamOffset[si->elements[i].stream_idx];
459
460             send_attribute(This, si->elements[i].format_desc->format, i, ptr);
461         }
462         SkipnStrides++;
463     }
464
465     glEnd();
466 }
467
468 /* GL locking is done by the caller */
469 static inline void drawStridedInstanced(IWineD3DDevice *iface, const struct wined3d_stream_info *si,
470         UINT numberOfVertices, GLenum glPrimitiveType, const void *idxData, UINT idxSize, UINT minIndex,
471         UINT startIdx)
472 {
473     UINT numInstances = 0, i;
474     int numInstancedAttribs = 0, j;
475     UINT instancedData[sizeof(si->elements) / sizeof(*si->elements) /* 16 */];
476     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
477     IWineD3DStateBlockImpl *stateblock = This->stateBlock;
478
479     if (idxSize == 0) {
480         /* This is a nasty thing. MSDN says no hardware supports that and apps have to use software vertex processing.
481          * We don't support this for now
482          *
483          * Shouldn't be too hard to support with opengl, in theory just call glDrawArrays instead of drawElements.
484          * But the StreamSourceFreq value has a different meaning in that situation.
485          */
486         FIXME("Non-indexed instanced drawing is not supported\n");
487         return;
488     }
489
490     TRACE("(%p) : glElements(%x, %d, %d, ...)\n", This, glPrimitiveType, numberOfVertices, minIndex);
491
492     /* First, figure out how many instances we have to draw */
493     for(i = 0; i < MAX_STREAMS; i++) {
494         /* Look at the streams and take the first one which matches */
495         if(((stateblock->streamFlags[i] & WINED3DSTREAMSOURCE_INSTANCEDATA) || (stateblock->streamFlags[i] & WINED3DSTREAMSOURCE_INDEXEDDATA)) && stateblock->streamSource[i]) {
496             /* D3D9 could set streamFreq 0 with (INSTANCEDATA or INDEXEDDATA) and then it is handled as 1. See d3d9/tests/visual.c-> stream_test() */
497             if(stateblock->streamFreq[i] == 0){
498                 numInstances = 1;
499             } else {
500                 numInstances = stateblock->streamFreq[i]; /* use the specified number of instances from the first matched stream. See d3d9/tests/visual.c-> stream_test() */
501             }
502             break; /* break, because only the first suitable value is interesting */
503         }
504     }
505
506     for (i = 0; i < sizeof(si->elements) / sizeof(*si->elements); ++i)
507     {
508         if (stateblock->streamFlags[si->elements[i].stream_idx] & WINED3DSTREAMSOURCE_INSTANCEDATA)
509         {
510             instancedData[numInstancedAttribs] = i;
511             numInstancedAttribs++;
512         }
513     }
514
515     /* now draw numInstances instances :-) */
516     for(i = 0; i < numInstances; i++) {
517         /* Specify the instanced attributes using immediate mode calls */
518         for(j = 0; j < numInstancedAttribs; j++) {
519             const BYTE *ptr = si->elements[instancedData[j]].data +
520                         si->elements[instancedData[j]].stride * i +
521                         stateblock->streamOffset[si->elements[instancedData[j]].stream_idx];
522             if (si->elements[instancedData[j]].buffer_object)
523             {
524                 struct wined3d_buffer *vb =
525                         (struct wined3d_buffer *)stateblock->streamSource[si->elements[instancedData[j]].stream_idx];
526                 ptr += (long) buffer_get_sysmem(vb);
527             }
528
529             send_attribute(This, si->elements[instancedData[j]].format_desc->format, instancedData[j], ptr);
530         }
531
532         glDrawElements(glPrimitiveType, numberOfVertices, idxSize == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT,
533                     (const char *)idxData+(idxSize * startIdx));
534         checkGLcall("glDrawElements");
535     }
536 }
537
538 static inline void remove_vbos(IWineD3DDeviceImpl *This, struct wined3d_stream_info *s)
539 {
540     unsigned int i;
541
542     for (i = 0; i < (sizeof(s->elements) / sizeof(*s->elements)); ++i)
543     {
544         struct wined3d_stream_info_element *e = &s->elements[i];
545         if (e->buffer_object)
546         {
547             struct wined3d_buffer *vb = (struct wined3d_buffer *)This->stateBlock->streamSource[e->stream_idx];
548             e->buffer_object = 0;
549             e->data = (BYTE *)((unsigned long)e->data + (unsigned long)buffer_get_sysmem(vb));
550         }
551     }
552 }
553
554 /* Routine common to the draw primitive and draw indexed primitive routines */
555 void drawPrimitive(IWineD3DDevice *iface, UINT index_count, UINT numberOfVertices,
556         UINT StartIdx, UINT idxSize, const void *idxData, UINT minIndex)
557 {
558
559     IWineD3DDeviceImpl           *This = (IWineD3DDeviceImpl *)iface;
560     IWineD3DSurfaceImpl          *target;
561     unsigned int i;
562
563     if (!index_count) return;
564
565     if (This->stateBlock->renderState[WINED3DRS_COLORWRITEENABLE])
566     {
567         /* Invalidate the back buffer memory so LockRect will read it the next time */
568         for (i = 0; i < GL_LIMITS(buffers); ++i)
569         {
570             target = (IWineD3DSurfaceImpl *)This->render_targets[i];
571             if (target)
572             {
573                 IWineD3DSurface_LoadLocation((IWineD3DSurface *)target, SFLAG_INDRAWABLE, NULL);
574                 IWineD3DSurface_ModifyLocation((IWineD3DSurface *)target, SFLAG_INDRAWABLE, TRUE);
575             }
576         }
577     }
578
579     /* Signals other modules that a drawing is in progress and the stateblock finalized */
580     This->isInDraw = TRUE;
581
582     ActivateContext(This, This->render_targets[0], CTXUSAGE_DRAWPRIM);
583
584     if (This->stencilBufferTarget) {
585         /* Note that this depends on the ActivateContext call above to set
586          * This->render_offscreen properly. We don't currently take the
587          * Z-compare function into account, but we could skip loading the
588          * depthstencil for D3DCMP_NEVER and D3DCMP_ALWAYS as well. Also note
589          * that we never copy the stencil data.*/
590         DWORD location = This->render_offscreen ? SFLAG_DS_OFFSCREEN : SFLAG_DS_ONSCREEN;
591         if (This->stateBlock->renderState[WINED3DRS_ZWRITEENABLE]
592                 || This->stateBlock->renderState[WINED3DRS_ZENABLE])
593             surface_load_ds_location(This->stencilBufferTarget, location);
594         if (This->stateBlock->renderState[WINED3DRS_ZWRITEENABLE])
595             surface_modify_ds_location(This->stencilBufferTarget, location);
596     }
597
598     /* Ok, we will be updating the screen from here onwards so grab the lock */
599     ENTER_GL();
600     {
601         GLenum glPrimType = This->stateBlock->gl_primitive_type;
602         BOOL emulation = FALSE;
603         const struct wined3d_stream_info *stream_info = &This->strided_streams;
604         struct wined3d_stream_info stridedlcl;
605
606         if (!numberOfVertices) numberOfVertices = index_count;
607
608         if (!use_vs(This->stateBlock))
609         {
610             if (!This->strided_streams.position_transformed && This->activeContext->num_untracked_materials
611                     && This->stateBlock->renderState[WINED3DRS_LIGHTING])
612             {
613                 static BOOL warned;
614                 if (!warned) {
615                     FIXME("Using software emulation because not all material properties could be tracked\n");
616                     warned = TRUE;
617                 } else {
618                     TRACE("Using software emulation because not all material properties could be tracked\n");
619                 }
620                 emulation = TRUE;
621             }
622             else if(This->activeContext->fog_coord && This->stateBlock->renderState[WINED3DRS_FOGENABLE]) {
623                 /* Either write a pipeline replacement shader or convert the specular alpha from unsigned byte
624                  * to a float in the vertex buffer
625                  */
626                 static BOOL warned;
627                 if (!warned) {
628                     FIXME("Using software emulation because manual fog coordinates are provided\n");
629                     warned = TRUE;
630                 } else {
631                     TRACE("Using software emulation because manual fog coordinates are provided\n");
632                 }
633                 emulation = TRUE;
634             }
635
636             if(emulation) {
637                 stream_info = &stridedlcl;
638                 memcpy(&stridedlcl, &This->strided_streams, sizeof(stridedlcl));
639                 remove_vbos(This, &stridedlcl);
640             }
641         }
642
643         if (This->useDrawStridedSlow || emulation) {
644             /* Immediate mode drawing */
645             if (use_vs(This->stateBlock))
646             {
647                 static BOOL warned;
648                 if (!warned) {
649                     FIXME("Using immediate mode with vertex shaders for half float emulation\n");
650                     warned = TRUE;
651                 } else {
652                     TRACE("Using immediate mode with vertex shaders for half float emulation\n");
653                 }
654                 drawStridedSlowVs(iface, stream_info, index_count, glPrimType, idxData, idxSize, minIndex, StartIdx);
655             } else {
656                 drawStridedSlow(iface, stream_info, index_count, glPrimType, idxData, idxSize, minIndex, StartIdx);
657             }
658         } else if(This->instancedDraw) {
659             /* Instancing emulation with mixing immediate mode and arrays */
660             drawStridedInstanced(iface, &This->strided_streams, index_count,
661                     glPrimType, idxData, idxSize, minIndex, StartIdx);
662         } else {
663             drawStridedFast(iface, glPrimType, minIndex, minIndex + numberOfVertices - 1,
664                     index_count, idxSize, idxData, StartIdx);
665         }
666     }
667
668     /* Finished updating the screen, restore lock */
669     LEAVE_GL();
670     TRACE("Done all gl drawing\n");
671
672     /* Diagnostics */
673 #ifdef SHOW_FRAME_MAKEUP
674     {
675         static long int primCounter = 0;
676         /* NOTE: set primCounter to the value reported by drawprim 
677            before you want to to write frame makeup to /tmp */
678         if (primCounter >= 0) {
679             WINED3DLOCKED_RECT r;
680             char buffer[80];
681             IWineD3DSurface_LockRect(This->render_targets[0], &r, NULL, WINED3DLOCK_READONLY);
682             sprintf(buffer, "/tmp/backbuffer_%ld.tga", primCounter);
683             TRACE("Saving screenshot %s\n", buffer);
684             IWineD3DSurface_SaveSnapshot(This->render_targets[0], buffer);
685             IWineD3DSurface_UnlockRect(This->render_targets[0]);
686
687 #ifdef SHOW_TEXTURE_MAKEUP
688            {
689             IWineD3DSurface *pSur;
690             int textureNo;
691             for (textureNo = 0; textureNo < MAX_COMBINED_SAMPLERS; ++textureNo) {
692                 if (This->stateBlock->textures[textureNo] != NULL) {
693                     sprintf(buffer, "/tmp/texture_%p_%ld_%d.tga", This->stateBlock->textures[textureNo], primCounter, textureNo);
694                     TRACE("Saving texture %s\n", buffer);
695                     if (IWineD3DBaseTexture_GetType(This->stateBlock->textures[textureNo]) == WINED3DRTYPE_TEXTURE) {
696                             IWineD3DTexture_GetSurfaceLevel(This->stateBlock->textures[textureNo], 0, &pSur);
697                             IWineD3DSurface_SaveSnapshot(pSur, buffer);
698                             IWineD3DSurface_Release(pSur);
699                     } else  {
700                         FIXME("base Texture isn't of type texture %d\n", IWineD3DBaseTexture_GetType(This->stateBlock->textures[textureNo]));
701                     }
702                 }
703             }
704            }
705 #endif
706         }
707         TRACE("drawprim #%ld\n", primCounter);
708         ++primCounter;
709     }
710 #endif
711
712     /* Control goes back to the device, stateblock values may change again */
713     This->isInDraw = FALSE;
714 }
715
716 static void normalize_normal(float *n) {
717     float length = n[0] * n[0] + n[1] * n[1] + n[2] * n[2];
718     if (length == 0.0f) return;
719     length = sqrt(length);
720     n[0] = n[0] / length;
721     n[1] = n[1] / length;
722     n[2] = n[2] / length;
723 }
724
725 /* Tesselates a high order rectangular patch into single triangles using gl evaluators
726  *
727  * The problem is that OpenGL does not offer a direct way to return the tesselated primitives,
728  * and they can't be sent off for rendering directly either. Tesselating is slow, so we want
729  * to cache the patches in a vertex buffer. But more importantly, gl can't bind generated
730  * attributes to numbered shader attributes, so we have to store them and rebind them as needed
731  * in drawprim.
732  *
733  * To read back, the opengl feedback mode is used. This creates a problem because we want
734  * untransformed, unlit vertices, but feedback runs everything through transform and lighting.
735  * Thus disable lighting and set identity matrices to get unmodified colors and positions.
736  * To overcome clipping find the biggest x, y and z values of the vertices in the patch and scale
737  * them to [-1.0;+1.0] and set the viewport up to scale them back.
738  *
739  * Normals are more tricky: Draw white vertices with 3 directional lights, and calculate the
740  * resulting colors back to the normals.
741  *
742  * NOTE: This function activates a context for blitting, modifies matrices & viewport, but
743  * does not restore it because normally a draw follows immediately afterwards. The caller is
744  * responsible of taking care that either the gl states are restored, or the context activated
745  * for drawing to reset the lastWasBlit flag.
746  */
747 HRESULT tesselate_rectpatch(IWineD3DDeviceImpl *This,
748                             struct WineD3DRectPatch *patch) {
749     unsigned int i, j, num_quads, out_vertex_size, buffer_size, d3d_out_vertex_size;
750     float max_x = 0.0f, max_y = 0.0f, max_z = 0.0f, neg_z = 0.0f;
751     struct wined3d_stream_info stream_info;
752     struct wined3d_stream_info_element *e;
753     const BYTE *data;
754     const WINED3DRECTPATCH_INFO *info = &patch->RectPatchInfo;
755     DWORD vtxStride;
756     GLenum feedback_type;
757     GLfloat *feedbuffer;
758
759     /* Simply activate the context for blitting. This disables all the things we don't want and
760      * takes care of dirtifying. Dirtifying is preferred over pushing / popping, since drawing the
761      * patch (as opposed to normal draws) will most likely need different changes anyway. */
762     ActivateContext(This, This->lastActiveRenderTarget, CTXUSAGE_BLIT);
763
764     /* First, locate the position data. This is provided in a vertex buffer in the stateblock.
765      * Beware of vbos
766      */
767     device_stream_info_from_declaration(This, FALSE, &stream_info, NULL);
768
769     e = &stream_info.elements[WINED3D_FFP_POSITION];
770     if (e->buffer_object)
771     {
772         struct wined3d_buffer *vb;
773         vb = (struct wined3d_buffer *)This->stateBlock->streamSource[e->stream_idx];
774         e->data = (BYTE *)((unsigned long)e->data + (unsigned long)buffer_get_sysmem(vb));
775     }
776     vtxStride = e->stride;
777     data = e->data +
778            vtxStride * info->Stride * info->StartVertexOffsetHeight +
779            vtxStride * info->StartVertexOffsetWidth;
780
781     /* Not entirely sure about what happens with transformed vertices */
782     if (stream_info.position_transformed) FIXME("Transformed position in rectpatch generation\n");
783
784     if(vtxStride % sizeof(GLfloat)) {
785         /* glMap2f reads vertex sizes in GLfloats, the d3d stride is in bytes.
786          * I don't see how the stride could not be a multiple of 4, but make sure
787          * to check it
788          */
789         ERR("Vertex stride is not a multiple of sizeof(GLfloat)\n");
790     }
791     if(info->Basis != WINED3DBASIS_BEZIER) {
792         FIXME("Basis is %s, how to handle this?\n", debug_d3dbasis(info->Basis));
793     }
794     if(info->Degree != WINED3DDEGREE_CUBIC) {
795         FIXME("Degree is %s, how to handle this?\n", debug_d3ddegree(info->Degree));
796     }
797
798     /* First, get the boundary cube of the input data */
799     for(j = 0; j < info->Height; j++) {
800         for(i = 0; i < info->Width; i++) {
801             const float *v = (const float *)(data + vtxStride * i + vtxStride * info->Stride * j);
802             if(fabs(v[0]) > max_x) max_x = fabs(v[0]);
803             if(fabs(v[1]) > max_y) max_y = fabs(v[1]);
804             if(fabs(v[2]) > max_z) max_z = fabs(v[2]);
805             if(v[2] < neg_z) neg_z = v[2];
806         }
807     }
808
809     /* This needs some improvements in the vertex decl code */
810     FIXME("Cannot find data to generate. Only generating position and normals\n");
811     patch->has_normals = TRUE;
812     patch->has_texcoords = FALSE;
813
814     ENTER_GL();
815
816     glMatrixMode(GL_PROJECTION);
817     checkGLcall("glMatrixMode(GL_PROJECTION)");
818     glLoadIdentity();
819     checkGLcall("glLoadIndentity()");
820     glScalef(1.0f / (max_x), 1.0f / (max_y), max_z == 0.0f ? 1.0f : 1.0f / (2.0f * max_z));
821     glTranslatef(0.0f, 0.0f, 0.5f);
822     checkGLcall("glScalef");
823     glViewport(-max_x, -max_y, 2 * (max_x), 2 * (max_y));
824     checkGLcall("glViewport");
825
826     /* Some states to take care of. If we're in wireframe opengl will produce lines, and confuse
827      * our feedback buffer parser
828      */
829     glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
830     checkGLcall("glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)");
831     IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_FILLMODE));
832     if(patch->has_normals) {
833         static const GLfloat black[] = {0.0f, 0.0f, 0.0f, 0.0f};
834         static const GLfloat red[]   = {1.0f, 0.0f, 0.0f, 0.0f};
835         static const GLfloat green[] = {0.0f, 1.0f, 0.0f, 0.0f};
836         static const GLfloat blue[]  = {0.0f, 0.0f, 1.0f, 0.0f};
837         static const GLfloat white[] = {1.0f, 1.0f, 1.0f, 1.0f};
838         glEnable(GL_LIGHTING);
839         checkGLcall("glEnable(GL_LIGHTING)");
840         glLightModelfv(GL_LIGHT_MODEL_AMBIENT, black);
841         checkGLcall("glLightModel for MODEL_AMBIENT");
842         IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_AMBIENT));
843
844         for(i = 3; i < GL_LIMITS(lights); i++) {
845             glDisable(GL_LIGHT0 + i);
846             checkGLcall("glDisable(GL_LIGHT0 + i)");
847             IWineD3DDeviceImpl_MarkStateDirty(This, STATE_ACTIVELIGHT(i));
848         }
849
850         IWineD3DDeviceImpl_MarkStateDirty(This, STATE_ACTIVELIGHT(0));
851         glLightfv(GL_LIGHT0, GL_DIFFUSE, red);
852         glLightfv(GL_LIGHT0, GL_SPECULAR, black);
853         glLightfv(GL_LIGHT0, GL_AMBIENT, black);
854         glLightfv(GL_LIGHT0, GL_POSITION, red);
855         glEnable(GL_LIGHT0);
856         checkGLcall("Setting up light 1");
857         IWineD3DDeviceImpl_MarkStateDirty(This, STATE_ACTIVELIGHT(1));
858         glLightfv(GL_LIGHT1, GL_DIFFUSE, green);
859         glLightfv(GL_LIGHT1, GL_SPECULAR, black);
860         glLightfv(GL_LIGHT1, GL_AMBIENT, black);
861         glLightfv(GL_LIGHT1, GL_POSITION, green);
862         glEnable(GL_LIGHT1);
863         checkGLcall("Setting up light 2");
864         IWineD3DDeviceImpl_MarkStateDirty(This, STATE_ACTIVELIGHT(2));
865         glLightfv(GL_LIGHT2, GL_DIFFUSE, blue);
866         glLightfv(GL_LIGHT2, GL_SPECULAR, black);
867         glLightfv(GL_LIGHT2, GL_AMBIENT, black);
868         glLightfv(GL_LIGHT2, GL_POSITION, blue);
869         glEnable(GL_LIGHT2);
870         checkGLcall("Setting up light 3");
871
872         IWineD3DDeviceImpl_MarkStateDirty(This, STATE_MATERIAL);
873         IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_COLORVERTEX));
874         glDisable(GL_COLOR_MATERIAL);
875         glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, black);
876         glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, black);
877         glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, white);
878         checkGLcall("Setting up materials");
879     }
880
881     /* Enable the needed maps.
882      * GL_MAP2_VERTEX_3 is needed for positional data.
883      * GL_AUTO_NORMAL to generate normals from the position. Do not use GL_MAP2_NORMAL.
884      * GL_MAP2_TEXTURE_COORD_4 for texture coords
885      */
886     num_quads = ceilf(patch->numSegs[0]) * ceilf(patch->numSegs[1]);
887     out_vertex_size = 3 /* position */;
888     d3d_out_vertex_size = 3;
889     glEnable(GL_MAP2_VERTEX_3);
890     if(patch->has_normals && patch->has_texcoords) {
891         FIXME("Texcoords not handled yet\n");
892         feedback_type = GL_3D_COLOR_TEXTURE;
893         out_vertex_size += 8;
894         d3d_out_vertex_size += 7;
895         glEnable(GL_AUTO_NORMAL);
896         glEnable(GL_MAP2_TEXTURE_COORD_4);
897     } else if(patch->has_texcoords) {
898         FIXME("Texcoords not handled yet\n");
899         feedback_type = GL_3D_COLOR_TEXTURE;
900         out_vertex_size += 7;
901         d3d_out_vertex_size += 4;
902         glEnable(GL_MAP2_TEXTURE_COORD_4);
903     } else if(patch->has_normals) {
904         feedback_type = GL_3D_COLOR;
905         out_vertex_size += 4;
906         d3d_out_vertex_size += 3;
907         glEnable(GL_AUTO_NORMAL);
908     } else {
909         feedback_type = GL_3D;
910     }
911     checkGLcall("glEnable vertex attrib generation");
912
913     buffer_size = num_quads * out_vertex_size * 2 /* triangle list */ * 3 /* verts per tri */
914                    + 4 * num_quads /* 2 triangle markers per quad + num verts in tri */;
915     feedbuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, buffer_size * sizeof(float) * 8);
916
917     glMap2f(GL_MAP2_VERTEX_3,
918             0.0f, 1.0f, vtxStride / sizeof(float), info->Width,
919             0.0f, 1.0f, info->Stride * vtxStride / sizeof(float), info->Height,
920             (const GLfloat *)data);
921     checkGLcall("glMap2f");
922     if(patch->has_texcoords) {
923         glMap2f(GL_MAP2_TEXTURE_COORD_4,
924                 0.0f, 1.0f, vtxStride / sizeof(float), info->Width,
925                 0.0f, 1.0f, info->Stride * vtxStride / sizeof(float), info->Height,
926                 (const GLfloat *)data);
927         checkGLcall("glMap2f");
928     }
929     glMapGrid2f(ceilf(patch->numSegs[0]), 0.0f, 1.0f, ceilf(patch->numSegs[1]), 0.0f, 1.0f);
930     checkGLcall("glMapGrid2f");
931
932     glFeedbackBuffer(buffer_size * 2, feedback_type, feedbuffer);
933     checkGLcall("glFeedbackBuffer");
934     glRenderMode(GL_FEEDBACK);
935
936     glEvalMesh2(GL_FILL, 0, ceilf(patch->numSegs[0]), 0, ceilf(patch->numSegs[1]));
937     checkGLcall("glEvalMesh2");
938
939     i = glRenderMode(GL_RENDER);
940     if(i == -1) {
941         LEAVE_GL();
942         ERR("Feedback failed. Expected %d elements back\n", buffer_size);
943         HeapFree(GetProcessHeap(), 0, feedbuffer);
944         return WINED3DERR_DRIVERINTERNALERROR;
945     } else if(i != buffer_size) {
946         LEAVE_GL();
947         ERR("Unexpected amount of elements returned. Expected %d, got %d\n", buffer_size, i);
948         HeapFree(GetProcessHeap(), 0, feedbuffer);
949         return WINED3DERR_DRIVERINTERNALERROR;
950     } else {
951         TRACE("Got %d elements as expected\n", i);
952     }
953
954     HeapFree(GetProcessHeap(), 0, patch->mem);
955     patch->mem = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, num_quads * 6 * d3d_out_vertex_size * sizeof(float) * 8);
956     i = 0;
957     for(j = 0; j < buffer_size; j += (3 /* num verts */ * out_vertex_size + 2 /* tri marker */)) {
958         if(feedbuffer[j] != GL_POLYGON_TOKEN) {
959             ERR("Unexpected token: %f\n", feedbuffer[j]);
960             continue;
961         }
962         if(feedbuffer[j + 1] != 3) {
963             ERR("Unexpected polygon: %f corners\n", feedbuffer[j + 1]);
964             continue;
965         }
966         /* Somehow there are different ideas about back / front facing, so fix up the
967          * vertex order
968          */
969         patch->mem[i + 0] =  feedbuffer[j + out_vertex_size * 2 + 2]; /* x, triangle 2 */
970         patch->mem[i + 1] =  feedbuffer[j + out_vertex_size * 2 + 3]; /* y, triangle 2 */
971         patch->mem[i + 2] = (feedbuffer[j + out_vertex_size * 2 + 4] - 0.5f) * 4.0f * max_z; /* z, triangle 3 */
972         if(patch->has_normals) {
973             patch->mem[i + 3] = feedbuffer[j + out_vertex_size * 2 + 5];
974             patch->mem[i + 4] = feedbuffer[j + out_vertex_size * 2 + 6];
975             patch->mem[i + 5] = feedbuffer[j + out_vertex_size * 2 + 7];
976         }
977         i += d3d_out_vertex_size;
978
979         patch->mem[i + 0] =  feedbuffer[j + out_vertex_size * 1 + 2]; /* x, triangle 2 */
980         patch->mem[i + 1] =  feedbuffer[j + out_vertex_size * 1 + 3]; /* y, triangle 2 */
981         patch->mem[i + 2] = (feedbuffer[j + out_vertex_size * 1 + 4] - 0.5f) * 4.0f * max_z; /* z, triangle 2 */
982         if(patch->has_normals) {
983             patch->mem[i + 3] = feedbuffer[j + out_vertex_size * 1 + 5];
984             patch->mem[i + 4] = feedbuffer[j + out_vertex_size * 1 + 6];
985             patch->mem[i + 5] = feedbuffer[j + out_vertex_size * 1 + 7];
986         }
987         i += d3d_out_vertex_size;
988
989         patch->mem[i + 0] =  feedbuffer[j + out_vertex_size * 0 + 2]; /* x, triangle 1 */
990         patch->mem[i + 1] =  feedbuffer[j + out_vertex_size * 0 + 3]; /* y, triangle 1 */
991         patch->mem[i + 2] = (feedbuffer[j + out_vertex_size * 0 + 4] - 0.5f) * 4.0f * max_z; /* z, triangle 1 */
992         if(patch->has_normals) {
993             patch->mem[i + 3] = feedbuffer[j + out_vertex_size * 0 + 5];
994             patch->mem[i + 4] = feedbuffer[j + out_vertex_size * 0 + 6];
995             patch->mem[i + 5] = feedbuffer[j + out_vertex_size * 0 + 7];
996         }
997         i += d3d_out_vertex_size;
998     }
999
1000     if(patch->has_normals) {
1001         /* Now do the same with reverse light directions */
1002         static const GLfloat x[] = {-1.0f,  0.0f,  0.0f, 0.0f};
1003         static const GLfloat y[] = { 0.0f, -1.0f,  0.0f, 0.0f};
1004         static const GLfloat z[] = { 0.0f,  0.0f, -1.0f, 0.0f};
1005         glLightfv(GL_LIGHT0, GL_POSITION, x);
1006         glLightfv(GL_LIGHT1, GL_POSITION, y);
1007         glLightfv(GL_LIGHT2, GL_POSITION, z);
1008         checkGLcall("Setting up reverse light directions");
1009
1010         glRenderMode(GL_FEEDBACK);
1011         checkGLcall("glRenderMode(GL_FEEDBACK)");
1012         glEvalMesh2(GL_FILL, 0, ceilf(patch->numSegs[0]), 0, ceilf(patch->numSegs[1]));
1013         checkGLcall("glEvalMesh2");
1014         i = glRenderMode(GL_RENDER);
1015         checkGLcall("glRenderMode(GL_RENDER)");
1016
1017         i = 0;
1018         for(j = 0; j < buffer_size; j += (3 /* num verts */ * out_vertex_size + 2 /* tri marker */)) {
1019             if(feedbuffer[j] != GL_POLYGON_TOKEN) {
1020                 ERR("Unexpected token: %f\n", feedbuffer[j]);
1021                 continue;
1022             }
1023             if(feedbuffer[j + 1] != 3) {
1024                 ERR("Unexpected polygon: %f corners\n", feedbuffer[j + 1]);
1025                 continue;
1026             }
1027             if(patch->mem[i + 3] == 0.0f)
1028                 patch->mem[i + 3] = -feedbuffer[j + out_vertex_size * 2 + 5];
1029             if(patch->mem[i + 4] == 0.0f)
1030                 patch->mem[i + 4] = -feedbuffer[j + out_vertex_size * 2 + 6];
1031             if(patch->mem[i + 5] == 0.0f)
1032                 patch->mem[i + 5] = -feedbuffer[j + out_vertex_size * 2 + 7];
1033             normalize_normal(patch->mem + i + 3);
1034             i += d3d_out_vertex_size;
1035
1036             if(patch->mem[i + 3] == 0.0f)
1037                 patch->mem[i + 3] = -feedbuffer[j + out_vertex_size * 1 + 5];
1038             if(patch->mem[i + 4] == 0.0f)
1039                 patch->mem[i + 4] = -feedbuffer[j + out_vertex_size * 1 + 6];
1040             if(patch->mem[i + 5] == 0.0f)
1041                 patch->mem[i + 5] = -feedbuffer[j + out_vertex_size * 1 + 7];
1042             normalize_normal(patch->mem + i + 3);
1043             i += d3d_out_vertex_size;
1044
1045             if(patch->mem[i + 3] == 0.0f)
1046                 patch->mem[i + 3] = -feedbuffer[j + out_vertex_size * 0 + 5];
1047             if(patch->mem[i + 4] == 0.0f)
1048                 patch->mem[i + 4] = -feedbuffer[j + out_vertex_size * 0 + 6];
1049             if(patch->mem[i + 5] == 0.0f)
1050                 patch->mem[i + 5] = -feedbuffer[j + out_vertex_size * 0 + 7];
1051             normalize_normal(patch->mem + i + 3);
1052             i += d3d_out_vertex_size;
1053         }
1054     }
1055
1056     glDisable(GL_MAP2_VERTEX_3);
1057     glDisable(GL_AUTO_NORMAL);
1058     glDisable(GL_MAP2_NORMAL);
1059     glDisable(GL_MAP2_TEXTURE_COORD_4);
1060     checkGLcall("glDisable vertex attrib generation");
1061     LEAVE_GL();
1062
1063     HeapFree(GetProcessHeap(), 0, feedbuffer);
1064
1065     vtxStride = 3 * sizeof(float);
1066     if(patch->has_normals) {
1067         vtxStride += 3 * sizeof(float);
1068     }
1069     if(patch->has_texcoords) {
1070         vtxStride += 4 * sizeof(float);
1071     }
1072     memset(&patch->strided, 0, sizeof(&patch->strided));
1073     patch->strided.position.format = WINED3DFMT_R32G32B32_FLOAT;
1074     patch->strided.position.lpData = (BYTE *) patch->mem;
1075     patch->strided.position.dwStride = vtxStride;
1076
1077     if(patch->has_normals) {
1078         patch->strided.normal.format = WINED3DFMT_R32G32B32_FLOAT;
1079         patch->strided.normal.lpData = (BYTE *) patch->mem + 3 * sizeof(float) /* pos */;
1080         patch->strided.normal.dwStride = vtxStride;
1081     }
1082     if(patch->has_texcoords) {
1083         patch->strided.texCoords[0].format = WINED3DFMT_R32G32B32A32_FLOAT;
1084         patch->strided.texCoords[0].lpData = (BYTE *) patch->mem + 3 * sizeof(float) /* pos */;
1085         if(patch->has_normals) {
1086             patch->strided.texCoords[0].lpData += 3 * sizeof(float);
1087         }
1088         patch->strided.texCoords[0].dwStride = vtxStride;
1089     }
1090
1091     return WINED3D_OK;
1092 }