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