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