2 * WINED3D draw functions
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
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.
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.
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
27 #include "wined3d_private.h"
29 WINE_DEFAULT_DEBUG_CHANNEL(d3d_draw);
30 #define GLINFO_LOCATION This->adapter->gl_info
35 static void drawStridedFast(IWineD3DDevice *iface, GLenum primitive_type,
36 UINT min_vertex_idx, UINT max_vertex_idx, UINT count, UINT idx_size,
37 const void *idx_data, UINT start_idx)
39 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
43 TRACE("(%p) : glElements(%x, %d, %d, ...)\n", This, primitive_type, count, min_vertex_idx);
46 glDrawElements(primitive_type, count,
47 idx_size == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT,
48 (const char *)idx_data + (idx_size * start_idx));
49 checkGLcall("glDrawElements");
51 glDrawRangeElements(primitive_type, min_vertex_idx, max_vertex_idx, count,
52 idx_size == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT,
53 (const char *)idx_data + (idx_size * start_idx));
54 checkGLcall("glDrawRangeElements");
59 TRACE("(%p) : glDrawArrays(%#x, %d, %d)\n", This, primitive_type, start_idx, count);
61 glDrawArrays(primitive_type, start_idx, count);
62 checkGLcall("glDrawArrays");
67 * Actually draw using the supplied information.
68 * Slower GL version which extracts info about each vertex in turn
71 static void drawStridedSlow(IWineD3DDevice *iface, const struct wined3d_stream_info *si, UINT NumVertexes,
72 GLenum glPrimType, const void *idxData, UINT idxSize, UINT minIndex, UINT startIdx)
74 unsigned int textureNo = 0;
75 const WORD *pIdxBufS = NULL;
76 const DWORD *pIdxBufL = NULL;
78 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
79 const UINT *streamOffset = This->stateBlock->streamOffset;
80 long SkipnStrides = startIdx + This->stateBlock->loadBaseVertexIndex;
81 BOOL pixelShader = use_ps(This->stateBlock);
82 BOOL specular_fog = FALSE;
83 UINT texture_stages = GL_LIMITS(texture_stages);
84 const BYTE *texCoords[WINED3DDP_MAXTEXCOORD];
85 const BYTE *diffuse = NULL, *specular = NULL, *normal = NULL, *position = NULL;
86 const struct wined3d_stream_info_element *element;
89 TRACE("Using slow vertex array code\n");
91 /* Variable Initialization */
93 /* Immediate mode drawing can't make use of indices in a vbo - get the data from the index buffer.
94 * If the index buffer has no vbo(not supported or other reason), or with user pointer drawing
95 * idxData will be != NULL
98 idxData = buffer_get_sysmem((struct wined3d_buffer *) This->stateBlock->pIndexData);
101 if (idxSize == 2) pIdxBufS = idxData;
102 else pIdxBufL = idxData;
103 } else if (idxData) {
104 ERR("non-NULL idxData with 0 idxSize, this should never happen\n");
108 /* Start drawing in GL */
109 VTRACE(("glBegin(%x)\n", glPrimType));
112 element = &si->elements[WINED3D_FFP_POSITION];
113 if (element->data) position = element->data + streamOffset[element->stream_idx];
115 element = &si->elements[WINED3D_FFP_NORMAL];
116 if (element->data) normal = element->data + streamOffset[element->stream_idx];
117 else glNormal3f(0, 0, 0);
119 element = &si->elements[WINED3D_FFP_DIFFUSE];
120 if (element->data) diffuse = element->data + streamOffset[element->stream_idx];
121 else glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
122 if (This->activeContext->num_untracked_materials && element->format_desc->format != WINED3DFMT_A8R8G8B8)
123 FIXME("Implement diffuse color tracking from %s\n", debug_d3dformat(element->format_desc->format));
125 element = &si->elements[WINED3D_FFP_SPECULAR];
128 specular = element->data + streamOffset[element->stream_idx];
130 /* special case where the fog density is stored in the specular alpha channel */
131 if (This->stateBlock->renderState[WINED3DRS_FOGENABLE]
132 && (This->stateBlock->renderState[WINED3DRS_FOGVERTEXMODE] == WINED3DFOG_NONE
133 || si->elements[WINED3D_FFP_POSITION].format_desc->format == WINED3DFMT_R32G32B32A32_FLOAT)
134 && This->stateBlock->renderState[WINED3DRS_FOGTABLEMODE] == WINED3DFOG_NONE)
136 if (GL_SUPPORT(EXT_FOG_COORD))
138 if (element->format_desc->format == WINED3DFMT_A8R8G8B8) specular_fog = TRUE;
139 else FIXME("Implement fog coordinates from %s\n", debug_d3dformat(element->format_desc->format));
147 /* TODO: Use the fog table code from old ddraw */
148 FIXME("Implement fog for transformed vertices in software\n");
154 else if (GL_SUPPORT(EXT_SECONDARY_COLOR))
156 GL_EXTCALL(glSecondaryColor3fEXT)(0, 0, 0);
159 for (textureNo = 0; textureNo < texture_stages; ++textureNo)
161 int coordIdx = This->stateBlock->textureState[textureNo][WINED3DTSS_TEXCOORDINDEX];
162 int texture_idx = This->texUnitMap[textureNo];
164 if (!GL_SUPPORT(ARB_MULTITEXTURE) && textureNo > 0)
166 FIXME("Program using multiple concurrent textures which this opengl implementation doesn't support\n");
170 if (!pixelShader && !This->stateBlock->textures[textureNo]) continue;
172 if (texture_idx == -1) continue;
176 TRACE("tex: %d - Skip tex coords, as being system generated\n", textureNo);
179 else if (coordIdx < 0)
181 FIXME("tex: %d - Coord index %d is less than zero, expect a crash.\n", textureNo, coordIdx);
185 element = &si->elements[WINED3D_FFP_TEXCOORD0 + coordIdx];
188 texCoords[coordIdx] = element->data + streamOffset[element->stream_idx];
189 tex_mask |= (1 << textureNo);
193 TRACE("tex: %d - Skipping tex coords, as no data supplied\n", textureNo);
194 if (GL_SUPPORT(ARB_MULTITEXTURE))
195 GL_EXTCALL(glMultiTexCoord4fARB(GL_TEXTURE0_ARB + texture_idx, 0, 0, 0, 1));
197 glTexCoord4f(0, 0, 0, 1);
201 /* We shouldn't start this function if any VBO is involved. Should I put a safety check here?
202 * Guess it's not necessary(we crash then anyway) and would only eat CPU time
205 /* For each primitive */
206 for (vx_index = 0; vx_index < NumVertexes; ++vx_index) {
207 UINT texture, tmp_tex_mask;
208 /* Blending data and Point sizes are not supported by this function. They are not supported by the fixed
209 * function pipeline at all. A Fixme for them is printed after decoding the vertex declaration
212 /* For indexed data, we need to go a few more strides in */
213 if (idxData != NULL) {
215 /* Indexed so work out the number of strides to skip */
217 VTRACE(("Idx for vertex %u = %u\n", vx_index, pIdxBufS[startIdx+vx_index]));
218 SkipnStrides = pIdxBufS[startIdx + vx_index] + This->stateBlock->loadBaseVertexIndex;
220 VTRACE(("Idx for vertex %u = %u\n", vx_index, pIdxBufL[startIdx+vx_index]));
221 SkipnStrides = pIdxBufL[startIdx + vx_index] + This->stateBlock->loadBaseVertexIndex;
225 tmp_tex_mask = tex_mask;
226 for (texture = 0; tmp_tex_mask; tmp_tex_mask >>= 1, ++texture)
232 if (!(tmp_tex_mask & 1)) continue;
234 coord_idx = This->stateBlock->textureState[texture][WINED3DTSS_TEXCOORDINDEX];
235 ptr = texCoords[coord_idx] + (SkipnStrides * si->elements[WINED3D_FFP_TEXCOORD0 + coord_idx].stride);
237 texture_idx = This->texUnitMap[texture];
238 multi_texcoord_funcs[si->elements[WINED3D_FFP_TEXCOORD0 + coord_idx].format_desc->emit_idx](
239 GL_TEXTURE0_ARB + texture_idx, ptr);
242 /* Diffuse -------------------------------- */
244 const void *ptrToCoords = diffuse + SkipnStrides * si->elements[WINED3D_FFP_DIFFUSE].stride;
246 diffuse_funcs[si->elements[WINED3D_FFP_DIFFUSE].format_desc->emit_idx](ptrToCoords);
247 if(This->activeContext->num_untracked_materials) {
248 DWORD diffuseColor = ((const DWORD *)ptrToCoords)[0];
252 color[0] = D3DCOLOR_B_R(diffuseColor) / 255.0;
253 color[1] = D3DCOLOR_B_G(diffuseColor) / 255.0;
254 color[2] = D3DCOLOR_B_B(diffuseColor) / 255.0;
255 color[3] = D3DCOLOR_B_A(diffuseColor) / 255.0;
257 for(i = 0; i < This->activeContext->num_untracked_materials; i++) {
258 glMaterialfv(GL_FRONT_AND_BACK, This->activeContext->untracked_materials[i], color);
263 /* Specular ------------------------------- */
265 const void *ptrToCoords = specular + SkipnStrides * si->elements[WINED3D_FFP_SPECULAR].stride;
267 specular_funcs[si->elements[WINED3D_FFP_SPECULAR].format_desc->emit_idx](ptrToCoords);
271 DWORD specularColor = *(const DWORD *)ptrToCoords;
272 GL_EXTCALL(glFogCoordfEXT(specularColor >> 24));
276 /* Normal -------------------------------- */
277 if (normal != NULL) {
278 const void *ptrToCoords = normal + SkipnStrides * si->elements[WINED3D_FFP_NORMAL].stride;
279 normal_funcs[si->elements[WINED3D_FFP_NORMAL].format_desc->emit_idx](ptrToCoords);
282 /* Position -------------------------------- */
284 const void *ptrToCoords = position + SkipnStrides * si->elements[WINED3D_FFP_POSITION].stride;
285 position_funcs[si->elements[WINED3D_FFP_POSITION].format_desc->emit_idx](ptrToCoords);
288 /* For non indexed mode, step onto next parts */
289 if (idxData == NULL) {
295 checkGLcall("glEnd and previous calls");
298 static inline void send_attribute(IWineD3DDeviceImpl *This, WINED3DFORMAT format, const UINT index, const void *ptr)
302 case WINED3DFMT_R32_FLOAT:
303 GL_EXTCALL(glVertexAttrib1fvARB(index, ptr));
305 case WINED3DFMT_R32G32_FLOAT:
306 GL_EXTCALL(glVertexAttrib2fvARB(index, ptr));
308 case WINED3DFMT_R32G32B32_FLOAT:
309 GL_EXTCALL(glVertexAttrib3fvARB(index, ptr));
311 case WINED3DFMT_R32G32B32A32_FLOAT:
312 GL_EXTCALL(glVertexAttrib4fvARB(index, ptr));
315 case WINED3DFMT_R8G8B8A8_UINT:
316 GL_EXTCALL(glVertexAttrib4ubvARB(index, ptr));
318 case WINED3DFMT_A8R8G8B8:
319 if (GL_SUPPORT(EXT_VERTEX_ARRAY_BGRA))
321 const DWORD *src = ptr;
322 DWORD c = *src & 0xff00ff00;
323 c |= (*src & 0xff0000) >> 16;
324 c |= (*src & 0xff) << 16;
325 GL_EXTCALL(glVertexAttrib4NubvARB(index, (GLubyte *)&c));
328 /* else fallthrough */
329 case WINED3DFMT_R8G8B8A8_UNORM:
330 GL_EXTCALL(glVertexAttrib4NubvARB(index, ptr));
333 case WINED3DFMT_R16G16_SINT:
334 GL_EXTCALL(glVertexAttrib4svARB(index, ptr));
336 case WINED3DFMT_R16G16B16A16_SINT:
337 GL_EXTCALL(glVertexAttrib4svARB(index, ptr));
340 case WINED3DFMT_R16G16_SNORM:
342 GLshort s[4] = {((const GLshort *)ptr)[0], ((const GLshort *)ptr)[1], 0, 1};
343 GL_EXTCALL(glVertexAttrib4NsvARB(index, s));
346 case WINED3DFMT_R16G16_UNORM:
348 GLushort s[4] = {((const GLushort *)ptr)[0], ((const GLushort *)ptr)[1], 0, 1};
349 GL_EXTCALL(glVertexAttrib4NusvARB(index, s));
352 case WINED3DFMT_R16G16B16A16_SNORM:
353 GL_EXTCALL(glVertexAttrib4NsvARB(index, ptr));
355 case WINED3DFMT_R16G16B16A16_UNORM:
356 GL_EXTCALL(glVertexAttrib4NusvARB(index, ptr));
359 case WINED3DFMT_R10G10B10A2_UINT:
360 FIXME("Unsure about WINED3DDECLTYPE_UDEC3\n");
361 /*glVertexAttrib3usvARB(instancedData[j], (GLushort *) ptr); Does not exist */
363 case WINED3DFMT_R10G10B10A2_SNORM:
364 FIXME("Unsure about WINED3DDECLTYPE_DEC3N\n");
365 /*glVertexAttrib3NusvARB(instancedData[j], (GLushort *) ptr); Does not exist */
368 case WINED3DFMT_R16G16_FLOAT:
369 /* Are those 16 bit floats. C doesn't have a 16 bit float type. I could read the single bits and calculate a 4
370 * byte float according to the IEEE standard
372 if (GL_SUPPORT(NV_HALF_FLOAT)) {
373 /* Not supported by GL_ARB_half_float_vertex */
374 GL_EXTCALL(glVertexAttrib2hvNV(index, ptr));
376 float x = float_16_to_32(((const unsigned short *)ptr) + 0);
377 float y = float_16_to_32(((const unsigned short *)ptr) + 1);
378 GL_EXTCALL(glVertexAttrib2fARB(index, x, y));
381 case WINED3DFMT_R16G16B16A16_FLOAT:
382 if (GL_SUPPORT(NV_HALF_FLOAT)) {
383 /* Not supported by GL_ARB_half_float_vertex */
384 GL_EXTCALL(glVertexAttrib4hvNV(index, ptr));
386 float x = float_16_to_32(((const unsigned short *)ptr) + 0);
387 float y = float_16_to_32(((const unsigned short *)ptr) + 1);
388 float z = float_16_to_32(((const unsigned short *)ptr) + 2);
389 float w = float_16_to_32(((const unsigned short *)ptr) + 3);
390 GL_EXTCALL(glVertexAttrib4fARB(index, x, y, z, w));
395 ERR("Unexpected attribute format: %s\n", debug_d3dformat(format));
400 static void drawStridedSlowVs(IWineD3DDevice *iface, const struct wined3d_stream_info *si, UINT numberOfVertices,
401 GLenum glPrimitiveType, const void *idxData, UINT idxSize, UINT minIndex, UINT startIdx)
403 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
404 long SkipnStrides = startIdx + This->stateBlock->loadBaseVertexIndex;
405 const WORD *pIdxBufS = NULL;
406 const DWORD *pIdxBufL = NULL;
409 IWineD3DStateBlockImpl *stateblock = This->stateBlock;
413 /* Immediate mode drawing can't make use of indices in a vbo - get the data from the index buffer.
414 * If the index buffer has no vbo(not supported or other reason), or with user pointer drawing
415 * idxData will be != NULL
417 if(idxData == NULL) {
418 idxData = buffer_get_sysmem((struct wined3d_buffer *) This->stateBlock->pIndexData);
421 if (idxSize == 2) pIdxBufS = idxData;
422 else pIdxBufL = idxData;
423 } else if (idxData) {
424 ERR("non-NULL idxData with 0 idxSize, this should never happen\n");
428 /* Start drawing in GL */
429 VTRACE(("glBegin(%x)\n", glPrimitiveType));
430 glBegin(glPrimitiveType);
432 for (vx_index = 0; vx_index < numberOfVertices; ++vx_index) {
433 if (idxData != NULL) {
435 /* Indexed so work out the number of strides to skip */
437 VTRACE(("Idx for vertex %d = %d\n", vx_index, pIdxBufS[startIdx+vx_index]));
438 SkipnStrides = pIdxBufS[startIdx + vx_index] + stateblock->loadBaseVertexIndex;
440 VTRACE(("Idx for vertex %d = %d\n", vx_index, pIdxBufL[startIdx+vx_index]));
441 SkipnStrides = pIdxBufL[startIdx + vx_index] + stateblock->loadBaseVertexIndex;
445 for(i = MAX_ATTRIBS - 1; i >= 0; i--) {
446 if(!si->elements[i].data) continue;
448 ptr = si->elements[i].data +
449 si->elements[i].stride * SkipnStrides +
450 stateblock->streamOffset[si->elements[i].stream_idx];
452 send_attribute(This, si->elements[i].format_desc->format, i, ptr);
460 static inline void drawStridedInstanced(IWineD3DDevice *iface, const struct wined3d_stream_info *si,
461 UINT numberOfVertices, GLenum glPrimitiveType, const void *idxData, UINT idxSize, UINT minIndex,
464 UINT numInstances = 0, i;
465 int numInstancedAttribs = 0, j;
466 UINT instancedData[sizeof(si->elements) / sizeof(*si->elements) /* 16 */];
467 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
468 IWineD3DStateBlockImpl *stateblock = This->stateBlock;
471 /* This is a nasty thing. MSDN says no hardware supports that and apps have to use software vertex processing.
472 * We don't support this for now
474 * Shouldn't be too hard to support with opengl, in theory just call glDrawArrays instead of drawElements.
475 * But the StreamSourceFreq value has a different meaning in that situation.
477 FIXME("Non-indexed instanced drawing is not supported\n");
481 TRACE("(%p) : glElements(%x, %d, %d, ...)\n", This, glPrimitiveType, numberOfVertices, minIndex);
483 /* First, figure out how many instances we have to draw */
484 for(i = 0; i < MAX_STREAMS; i++) {
485 /* Look at the streams and take the first one which matches */
486 if(((stateblock->streamFlags[i] & WINED3DSTREAMSOURCE_INSTANCEDATA) || (stateblock->streamFlags[i] & WINED3DSTREAMSOURCE_INDEXEDDATA)) && stateblock->streamSource[i]) {
487 /* D3D9 could set streamFreq 0 with (INSTANCEDATA or INDEXEDDATA) and then it is handled as 1. See d3d9/tests/visual.c-> stream_test() */
488 if(stateblock->streamFreq[i] == 0){
491 numInstances = stateblock->streamFreq[i]; /* use the specified number of instances from the first matched stream. See d3d9/tests/visual.c-> stream_test() */
493 break; /* break, because only the first suitable value is interesting */
497 for (i = 0; i < sizeof(si->elements) / sizeof(*si->elements); ++i)
499 if (stateblock->streamFlags[si->elements[i].stream_idx] & WINED3DSTREAMSOURCE_INSTANCEDATA)
501 instancedData[numInstancedAttribs] = i;
502 numInstancedAttribs++;
506 /* now draw numInstances instances :-) */
507 for(i = 0; i < numInstances; i++) {
508 /* Specify the instanced attributes using immediate mode calls */
509 for(j = 0; j < numInstancedAttribs; j++) {
510 const BYTE *ptr = si->elements[instancedData[j]].data +
511 si->elements[instancedData[j]].stride * i +
512 stateblock->streamOffset[si->elements[instancedData[j]].stream_idx];
513 if (si->elements[instancedData[j]].buffer_object)
515 struct wined3d_buffer *vb =
516 (struct wined3d_buffer *)stateblock->streamSource[si->elements[instancedData[j]].stream_idx];
517 ptr += (long) buffer_get_sysmem(vb);
520 send_attribute(This, si->elements[instancedData[j]].format_desc->format, instancedData[j], ptr);
523 glDrawElements(glPrimitiveType, numberOfVertices, idxSize == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT,
524 (const char *)idxData+(idxSize * startIdx));
525 checkGLcall("glDrawElements");
529 static inline void remove_vbos(IWineD3DDeviceImpl *This, struct wined3d_stream_info *s)
533 for (i = 0; i < (sizeof(s->elements) / sizeof(*s->elements)); ++i)
535 struct wined3d_stream_info_element *e = &s->elements[i];
536 if (e->buffer_object)
538 struct wined3d_buffer *vb = (struct wined3d_buffer *)This->stateBlock->streamSource[e->stream_idx];
539 e->buffer_object = 0;
540 e->data = (BYTE *)((unsigned long)e->data + (unsigned long)buffer_get_sysmem(vb));
545 /* Routine common to the draw primitive and draw indexed primitive routines */
546 void drawPrimitive(IWineD3DDevice *iface, UINT index_count, UINT numberOfVertices,
547 UINT StartIdx, UINT idxSize, const void *idxData, UINT minIndex)
550 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
551 IWineD3DSurfaceImpl *target;
554 if (!index_count) return;
556 /* Invalidate the back buffer memory so LockRect will read it the next time */
557 for(i = 0; i < GL_LIMITS(buffers); i++) {
558 target = (IWineD3DSurfaceImpl *) This->render_targets[i];
560 IWineD3DSurface_LoadLocation((IWineD3DSurface *) target, SFLAG_INDRAWABLE, NULL);
561 IWineD3DSurface_ModifyLocation((IWineD3DSurface *) target, SFLAG_INDRAWABLE, TRUE);
565 /* Signals other modules that a drawing is in progress and the stateblock finalized */
566 This->isInDraw = TRUE;
568 ActivateContext(This, This->render_targets[0], CTXUSAGE_DRAWPRIM);
570 if (This->stencilBufferTarget) {
571 /* Note that this depends on the ActivateContext call above to set
572 * This->render_offscreen properly */
573 DWORD location = This->render_offscreen ? SFLAG_DS_OFFSCREEN : SFLAG_DS_ONSCREEN;
574 surface_load_ds_location(This->stencilBufferTarget, location);
575 surface_modify_ds_location(This->stencilBufferTarget, location);
578 /* Ok, we will be updating the screen from here onwards so grab the lock */
581 GLenum glPrimType = This->stateBlock->gl_primitive_type;
582 BOOL emulation = FALSE;
583 const struct wined3d_stream_info *stream_info = &This->strided_streams;
584 struct wined3d_stream_info stridedlcl;
586 if (!numberOfVertices) numberOfVertices = index_count;
588 if (!use_vs(This->stateBlock))
590 if (!This->strided_streams.position_transformed && This->activeContext->num_untracked_materials
591 && This->stateBlock->renderState[WINED3DRS_LIGHTING])
595 FIXME("Using software emulation because not all material properties could be tracked\n");
598 TRACE("Using software emulation because not all material properties could be tracked\n");
602 else if(This->activeContext->fog_coord && This->stateBlock->renderState[WINED3DRS_FOGENABLE]) {
603 /* Either write a pipeline replacement shader or convert the specular alpha from unsigned byte
604 * to a float in the vertex buffer
608 FIXME("Using software emulation because manual fog coordinates are provided\n");
611 TRACE("Using software emulation because manual fog coordinates are provided\n");
617 stream_info = &stridedlcl;
618 memcpy(&stridedlcl, &This->strided_streams, sizeof(stridedlcl));
619 remove_vbos(This, &stridedlcl);
623 if (This->useDrawStridedSlow || emulation) {
624 /* Immediate mode drawing */
625 if (use_vs(This->stateBlock))
629 FIXME("Using immediate mode with vertex shaders for half float emulation\n");
632 TRACE("Using immediate mode with vertex shaders for half float emulation\n");
634 drawStridedSlowVs(iface, stream_info, index_count, glPrimType, idxData, idxSize, minIndex, StartIdx);
636 drawStridedSlow(iface, stream_info, index_count, glPrimType, idxData, idxSize, minIndex, StartIdx);
638 } else if(This->instancedDraw) {
639 /* Instancing emulation with mixing immediate mode and arrays */
640 drawStridedInstanced(iface, &This->strided_streams, index_count,
641 glPrimType, idxData, idxSize, minIndex, StartIdx);
643 drawStridedFast(iface, glPrimType, minIndex, minIndex + numberOfVertices - 1,
644 index_count, idxSize, idxData, StartIdx);
648 /* Finished updating the screen, restore lock */
650 TRACE("Done all gl drawing\n");
653 #ifdef SHOW_FRAME_MAKEUP
655 static long int primCounter = 0;
656 /* NOTE: set primCounter to the value reported by drawprim
657 before you want to to write frame makeup to /tmp */
658 if (primCounter >= 0) {
659 WINED3DLOCKED_RECT r;
661 IWineD3DSurface_LockRect(This->render_targets[0], &r, NULL, WINED3DLOCK_READONLY);
662 sprintf(buffer, "/tmp/backbuffer_%ld.tga", primCounter);
663 TRACE("Saving screenshot %s\n", buffer);
664 IWineD3DSurface_SaveSnapshot(This->render_targets[0], buffer);
665 IWineD3DSurface_UnlockRect(This->render_targets[0]);
667 #ifdef SHOW_TEXTURE_MAKEUP
669 IWineD3DSurface *pSur;
671 for (textureNo = 0; textureNo < MAX_COMBINED_SAMPLERS; ++textureNo) {
672 if (This->stateBlock->textures[textureNo] != NULL) {
673 sprintf(buffer, "/tmp/texture_%p_%ld_%d.tga", This->stateBlock->textures[textureNo], primCounter, textureNo);
674 TRACE("Saving texture %s\n", buffer);
675 if (IWineD3DBaseTexture_GetType(This->stateBlock->textures[textureNo]) == WINED3DRTYPE_TEXTURE) {
676 IWineD3DTexture_GetSurfaceLevel(This->stateBlock->textures[textureNo], 0, &pSur);
677 IWineD3DSurface_SaveSnapshot(pSur, buffer);
678 IWineD3DSurface_Release(pSur);
680 FIXME("base Texture isn't of type texture %d\n", IWineD3DBaseTexture_GetType(This->stateBlock->textures[textureNo]));
687 TRACE("drawprim #%ld\n", primCounter);
692 /* Control goes back to the device, stateblock values may change again */
693 This->isInDraw = FALSE;
696 static void normalize_normal(float *n) {
697 float length = n[0] * n[0] + n[1] * n[1] + n[2] * n[2];
698 if(length == 0.0) return;
699 length = sqrt(length);
700 n[0] = n[0] / length;
701 n[1] = n[1] / length;
702 n[2] = n[2] / length;
705 /* Tesselates a high order rectangular patch into single triangles using gl evaluators
707 * The problem is that OpenGL does not offer a direct way to return the tesselated primitives,
708 * and they can't be sent off for rendering directly either. Tesselating is slow, so we want
709 * to cache the patches in a vertex buffer. But more importantly, gl can't bind generated
710 * attributes to numbered shader attributes, so we have to store them and rebind them as needed
713 * To read back, the opengl feedback mode is used. This creates a problem because we want
714 * untransformed, unlit vertices, but feedback runs everything through transform and lighting.
715 * Thus disable lighting and set identity matrices to get unmodified colors and positions.
716 * To overcome clipping find the biggest x, y and z values of the vertices in the patch and scale
717 * them to [-1.0;+1.0] and set the viewport up to scale them back.
719 * Normals are more tricky: Draw white vertices with 3 directional lights, and calculate the
720 * resulting colors back to the normals.
722 * NOTE: This function activates a context for blitting, modifies matrices & viewport, but
723 * does not restore it because normally a draw follows immediately afterwards. The caller is
724 * responsible of taking care that either the gl states are restored, or the context activated
725 * for drawing to reset the lastWasBlit flag.
727 HRESULT tesselate_rectpatch(IWineD3DDeviceImpl *This,
728 struct WineD3DRectPatch *patch) {
729 unsigned int i, j, num_quads, out_vertex_size, buffer_size, d3d_out_vertex_size;
730 float max_x = 0.0, max_y = 0.0, max_z = 0.0, neg_z = 0.0;
731 struct wined3d_stream_info stream_info;
732 struct wined3d_stream_info_element *e;
734 const WINED3DRECTPATCH_INFO *info = &patch->RectPatchInfo;
736 GLenum feedback_type;
739 /* First, locate the position data. This is provided in a vertex buffer in the stateblock.
742 device_stream_info_from_declaration(This, FALSE, &stream_info, NULL);
744 e = &stream_info.elements[WINED3D_FFP_POSITION];
745 if (e->buffer_object)
747 struct wined3d_buffer *vb;
748 vb = (struct wined3d_buffer *)This->stateBlock->streamSource[e->stream_idx];
749 e->data = (BYTE *)((unsigned long)e->data + (unsigned long)buffer_get_sysmem(vb));
751 vtxStride = e->stride;
753 vtxStride * info->Stride * info->StartVertexOffsetHeight +
754 vtxStride * info->StartVertexOffsetWidth;
756 /* Not entirely sure about what happens with transformed vertices */
757 if (stream_info.position_transformed) FIXME("Transformed position in rectpatch generation\n");
759 if(vtxStride % sizeof(GLfloat)) {
760 /* glMap2f reads vertex sizes in GLfloats, the d3d stride is in bytes.
761 * I don't see how the stride could not be a multiple of 4, but make sure
764 ERR("Vertex stride is not a multiple of sizeof(GLfloat)\n");
766 if(info->Basis != WINED3DBASIS_BEZIER) {
767 FIXME("Basis is %s, how to handle this?\n", debug_d3dbasis(info->Basis));
769 if(info->Degree != WINED3DDEGREE_CUBIC) {
770 FIXME("Degree is %s, how to handle this?\n", debug_d3ddegree(info->Degree));
773 /* First, get the boundary cube of the input data */
774 for(j = 0; j < info->Height; j++) {
775 for(i = 0; i < info->Width; i++) {
776 const float *v = (const float *)(data + vtxStride * i + vtxStride * info->Stride * j);
777 if(fabs(v[0]) > max_x) max_x = fabs(v[0]);
778 if(fabs(v[1]) > max_y) max_y = fabs(v[1]);
779 if(fabs(v[2]) > max_z) max_z = fabs(v[2]);
780 if(v[2] < neg_z) neg_z = v[2];
784 /* This needs some improvements in the vertex decl code */
785 FIXME("Cannot find data to generate. Only generating position and normals\n");
786 patch->has_normals = TRUE;
787 patch->has_texcoords = FALSE;
789 /* Simply activate the context for blitting. This disables all the things we don't want and
790 * takes care of dirtifying. Dirtifying is preferred over pushing / popping, since drawing the
791 * patch (as opposed to normal draws) will most likely need different changes anyway
793 ActivateContext(This, This->lastActiveRenderTarget, CTXUSAGE_BLIT);
796 glMatrixMode(GL_PROJECTION);
797 checkGLcall("glMatrixMode(GL_PROJECTION)");
799 checkGLcall("glLoadIndentity()");
800 glScalef(1 / (max_x) , 1 / (max_y), max_z == 0 ? 1 : 1 / ( 2 * max_z));
801 glTranslatef(0, 0, 0.5);
802 checkGLcall("glScalef");
803 glViewport(-max_x, -max_y, 2 * (max_x), 2 * (max_y));
804 checkGLcall("glViewport");
806 /* Some states to take care of. If we're in wireframe opengl will produce lines, and confuse
807 * our feedback buffer parser
809 glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
810 checkGLcall("glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)");
811 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_FILLMODE));
812 if(patch->has_normals) {
813 static const GLfloat black[] = {0, 0, 0, 0};
814 static const GLfloat red[] = {1, 0, 0, 0};
815 static const GLfloat green[] = {0, 1, 0, 0};
816 static const GLfloat blue[] = {0, 0, 1, 0};
817 static const GLfloat white[] = {1, 1, 1, 1};
818 glEnable(GL_LIGHTING);
819 checkGLcall("glEnable(GL_LIGHTING)");
820 glLightModelfv(GL_LIGHT_MODEL_AMBIENT, black);
821 checkGLcall("glLightModel for MODEL_AMBIENT");
822 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_AMBIENT));
824 for(i = 3; i < GL_LIMITS(lights); i++) {
825 glDisable(GL_LIGHT0 + i);
826 checkGLcall("glDisable(GL_LIGHT0 + i)");
827 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_ACTIVELIGHT(i));
830 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_ACTIVELIGHT(0));
831 glLightfv(GL_LIGHT0, GL_DIFFUSE, red);
832 glLightfv(GL_LIGHT0, GL_SPECULAR, black);
833 glLightfv(GL_LIGHT0, GL_AMBIENT, black);
834 glLightfv(GL_LIGHT0, GL_POSITION, red);
836 checkGLcall("Setting up light 1\n");
837 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_ACTIVELIGHT(1));
838 glLightfv(GL_LIGHT1, GL_DIFFUSE, green);
839 glLightfv(GL_LIGHT1, GL_SPECULAR, black);
840 glLightfv(GL_LIGHT1, GL_AMBIENT, black);
841 glLightfv(GL_LIGHT1, GL_POSITION, green);
843 checkGLcall("Setting up light 2\n");
844 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_ACTIVELIGHT(2));
845 glLightfv(GL_LIGHT2, GL_DIFFUSE, blue);
846 glLightfv(GL_LIGHT2, GL_SPECULAR, black);
847 glLightfv(GL_LIGHT2, GL_AMBIENT, black);
848 glLightfv(GL_LIGHT2, GL_POSITION, blue);
850 checkGLcall("Setting up light 3\n");
852 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_MATERIAL);
853 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_COLORVERTEX));
854 glDisable(GL_COLOR_MATERIAL);
855 glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, black);
856 glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, black);
857 glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, white);
858 checkGLcall("Setting up materials\n");
861 /* Enable the needed maps.
862 * GL_MAP2_VERTEX_3 is needed for positional data.
863 * GL_AUTO_NORMAL to generate normals from the position. Do not use GL_MAP2_NORMAL.
864 * GL_MAP2_TEXTURE_COORD_4 for texture coords
866 num_quads = ceilf(patch->numSegs[0]) * ceilf(patch->numSegs[1]);
867 out_vertex_size = 3 /* position */;
868 d3d_out_vertex_size = 3;
869 glEnable(GL_MAP2_VERTEX_3);
870 if(patch->has_normals && patch->has_texcoords) {
871 FIXME("Texcoords not handled yet\n");
872 feedback_type = GL_3D_COLOR_TEXTURE;
873 out_vertex_size += 8;
874 d3d_out_vertex_size += 7;
875 glEnable(GL_AUTO_NORMAL);
876 glEnable(GL_MAP2_TEXTURE_COORD_4);
877 } else if(patch->has_texcoords) {
878 FIXME("Texcoords not handled yet\n");
879 feedback_type = GL_3D_COLOR_TEXTURE;
880 out_vertex_size += 7;
881 d3d_out_vertex_size += 4;
882 glEnable(GL_MAP2_TEXTURE_COORD_4);
883 } else if(patch->has_normals) {
884 feedback_type = GL_3D_COLOR;
885 out_vertex_size += 4;
886 d3d_out_vertex_size += 3;
887 glEnable(GL_AUTO_NORMAL);
889 feedback_type = GL_3D;
891 checkGLcall("glEnable vertex attrib generation");
893 buffer_size = num_quads * out_vertex_size * 2 /* triangle list */ * 3 /* verts per tri */
894 + 4 * num_quads /* 2 triangle markers per quad + num verts in tri */;
895 feedbuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, buffer_size * sizeof(float) * 8);
897 glMap2f(GL_MAP2_VERTEX_3,
898 0, 1, vtxStride / sizeof(float), info->Width,
899 0, 1, info->Stride * vtxStride / sizeof(float), info->Height,
900 (const GLfloat *)data);
901 checkGLcall("glMap2f");
902 if(patch->has_texcoords) {
903 glMap2f(GL_MAP2_TEXTURE_COORD_4,
904 0, 1, vtxStride / sizeof(float), info->Width,
905 0, 1, info->Stride * vtxStride / sizeof(float), info->Height,
906 (const GLfloat *)data);
907 checkGLcall("glMap2f");
909 glMapGrid2f(ceilf(patch->numSegs[0]), 0.0, 1.0, ceilf(patch->numSegs[1]), 0.0, 1.0);
910 checkGLcall("glMapGrid2f");
912 glFeedbackBuffer(buffer_size * 2, feedback_type, feedbuffer);
913 checkGLcall("glFeedbackBuffer");
914 glRenderMode(GL_FEEDBACK);
916 glEvalMesh2(GL_FILL, 0, ceilf(patch->numSegs[0]), 0, ceilf(patch->numSegs[1]));
917 checkGLcall("glEvalMesh2\n");
919 i = glRenderMode(GL_RENDER);
922 ERR("Feedback failed. Expected %d elements back\n", buffer_size);
924 HeapFree(GetProcessHeap(), 0, feedbuffer);
925 return WINED3DERR_DRIVERINTERNALERROR;
926 } else if(i != buffer_size) {
928 ERR("Unexpected amount of elements returned. Expected %d, got %d\n", buffer_size, i);
930 HeapFree(GetProcessHeap(), 0, feedbuffer);
931 return WINED3DERR_DRIVERINTERNALERROR;
933 TRACE("Got %d elements as expected\n", i);
936 HeapFree(GetProcessHeap(), 0, patch->mem);
937 patch->mem = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, num_quads * 6 * d3d_out_vertex_size * sizeof(float) * 8);
939 for(j = 0; j < buffer_size; j += (3 /* num verts */ * out_vertex_size + 2 /* tri marker */)) {
940 if(feedbuffer[j] != GL_POLYGON_TOKEN) {
941 ERR("Unexpected token: %f\n", feedbuffer[j]);
944 if(feedbuffer[j + 1] != 3) {
945 ERR("Unexpected polygon: %f corners\n", feedbuffer[j + 1]);
948 /* Somehow there are different ideas about back / front facing, so fix up the
951 patch->mem[i + 0] = feedbuffer[j + out_vertex_size * 2 + 2]; /* x, triangle 2 */
952 patch->mem[i + 1] = feedbuffer[j + out_vertex_size * 2 + 3]; /* y, triangle 2 */
953 patch->mem[i + 2] = (feedbuffer[j + out_vertex_size * 2 + 4] - 0.5) * 4 * max_z; /* z, triangle 3 */
954 if(patch->has_normals) {
955 patch->mem[i + 3] = feedbuffer[j + out_vertex_size * 2 + 5];
956 patch->mem[i + 4] = feedbuffer[j + out_vertex_size * 2 + 6];
957 patch->mem[i + 5] = feedbuffer[j + out_vertex_size * 2 + 7];
959 i += d3d_out_vertex_size;
961 patch->mem[i + 0] = feedbuffer[j + out_vertex_size * 1 + 2]; /* x, triangle 2 */
962 patch->mem[i + 1] = feedbuffer[j + out_vertex_size * 1 + 3]; /* y, triangle 2 */
963 patch->mem[i + 2] = (feedbuffer[j + out_vertex_size * 1 + 4] - 0.5) * 4 * max_z; /* z, triangle 2 */
964 if(patch->has_normals) {
965 patch->mem[i + 3] = feedbuffer[j + out_vertex_size * 1 + 5];
966 patch->mem[i + 4] = feedbuffer[j + out_vertex_size * 1 + 6];
967 patch->mem[i + 5] = feedbuffer[j + out_vertex_size * 1 + 7];
969 i += d3d_out_vertex_size;
971 patch->mem[i + 0] = feedbuffer[j + out_vertex_size * 0 + 2]; /* x, triangle 1 */
972 patch->mem[i + 1] = feedbuffer[j + out_vertex_size * 0 + 3]; /* y, triangle 1 */
973 patch->mem[i + 2] = (feedbuffer[j + out_vertex_size * 0 + 4] - 0.5) * 4 * max_z; /* z, triangle 1 */
974 if(patch->has_normals) {
975 patch->mem[i + 3] = feedbuffer[j + out_vertex_size * 0 + 5];
976 patch->mem[i + 4] = feedbuffer[j + out_vertex_size * 0 + 6];
977 patch->mem[i + 5] = feedbuffer[j + out_vertex_size * 0 + 7];
979 i += d3d_out_vertex_size;
982 if(patch->has_normals) {
983 /* Now do the same with reverse light directions */
984 static const GLfloat x[] = {-1, 0, 0, 0};
985 static const GLfloat y[] = { 0, -1, 0, 0};
986 static const GLfloat z[] = { 0, 0, -1, 0};
987 glLightfv(GL_LIGHT0, GL_POSITION, x);
988 glLightfv(GL_LIGHT1, GL_POSITION, y);
989 glLightfv(GL_LIGHT2, GL_POSITION, z);
990 checkGLcall("Setting up reverse light directions\n");
992 glRenderMode(GL_FEEDBACK);
993 checkGLcall("glRenderMode(GL_FEEDBACK)");
994 glEvalMesh2(GL_FILL, 0, ceilf(patch->numSegs[0]), 0, ceilf(patch->numSegs[1]));
995 checkGLcall("glEvalMesh2\n");
996 i = glRenderMode(GL_RENDER);
997 checkGLcall("glRenderMode(GL_RENDER)");
1000 for(j = 0; j < buffer_size; j += (3 /* num verts */ * out_vertex_size + 2 /* tri marker */)) {
1001 if(feedbuffer[j] != GL_POLYGON_TOKEN) {
1002 ERR("Unexpected token: %f\n", feedbuffer[j]);
1005 if(feedbuffer[j + 1] != 3) {
1006 ERR("Unexpected polygon: %f corners\n", feedbuffer[j + 1]);
1009 if(patch->mem[i + 3] == 0.0)
1010 patch->mem[i + 3] = -feedbuffer[j + out_vertex_size * 2 + 5];
1011 if(patch->mem[i + 4] == 0.0)
1012 patch->mem[i + 4] = -feedbuffer[j + out_vertex_size * 2 + 6];
1013 if(patch->mem[i + 5] == 0.0)
1014 patch->mem[i + 5] = -feedbuffer[j + out_vertex_size * 2 + 7];
1015 normalize_normal(patch->mem + i + 3);
1016 i += d3d_out_vertex_size;
1018 if(patch->mem[i + 3] == 0.0)
1019 patch->mem[i + 3] = -feedbuffer[j + out_vertex_size * 1 + 5];
1020 if(patch->mem[i + 4] == 0.0)
1021 patch->mem[i + 4] = -feedbuffer[j + out_vertex_size * 1 + 6];
1022 if(patch->mem[i + 5] == 0.0)
1023 patch->mem[i + 5] = -feedbuffer[j + out_vertex_size * 1 + 7];
1024 normalize_normal(patch->mem + i + 3);
1025 i += d3d_out_vertex_size;
1027 if(patch->mem[i + 3] == 0.0)
1028 patch->mem[i + 3] = -feedbuffer[j + out_vertex_size * 0 + 5];
1029 if(patch->mem[i + 4] == 0.0)
1030 patch->mem[i + 4] = -feedbuffer[j + out_vertex_size * 0 + 6];
1031 if(patch->mem[i + 5] == 0.0)
1032 patch->mem[i + 5] = -feedbuffer[j + out_vertex_size * 0 + 7];
1033 normalize_normal(patch->mem + i + 3);
1034 i += d3d_out_vertex_size;
1038 glDisable(GL_MAP2_VERTEX_3);
1039 glDisable(GL_AUTO_NORMAL);
1040 glDisable(GL_MAP2_NORMAL);
1041 glDisable(GL_MAP2_TEXTURE_COORD_4);
1042 checkGLcall("glDisable vertex attrib generation");
1045 HeapFree(GetProcessHeap(), 0, feedbuffer);
1047 vtxStride = 3 * sizeof(float);
1048 if(patch->has_normals) {
1049 vtxStride += 3 * sizeof(float);
1051 if(patch->has_texcoords) {
1052 vtxStride += 4 * sizeof(float);
1054 memset(&patch->strided, 0, sizeof(&patch->strided));
1055 patch->strided.position.format = WINED3DFMT_R32G32B32_FLOAT;
1056 patch->strided.position.lpData = (BYTE *) patch->mem;
1057 patch->strided.position.dwStride = vtxStride;
1059 if(patch->has_normals) {
1060 patch->strided.normal.format = WINED3DFMT_R32G32B32_FLOAT;
1061 patch->strided.normal.lpData = (BYTE *) patch->mem + 3 * sizeof(float) /* pos */;
1062 patch->strided.normal.dwStride = vtxStride;
1064 if(patch->has_texcoords) {
1065 patch->strided.texCoords[0].format = WINED3DFMT_R32G32B32A32_FLOAT;
1066 patch->strided.texCoords[0].lpData = (BYTE *) patch->mem + 3 * sizeof(float) /* pos */;
1067 if(patch->has_normals) {
1068 patch->strided.texCoords[0].lpData += 3 * sizeof(float);
1070 patch->strided.texCoords[0].dwStride = vtxStride;