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