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