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