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
10 * Copyright 2009 Henri Verbeet for CodeWeavers
12 * This library is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Lesser General Public
14 * License as published by the Free Software Foundation; either
15 * version 2.1 of the License, or (at your option) any later version.
17 * This library is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Lesser General Public License for more details.
22 * You should have received a copy of the GNU Lesser General Public
23 * License along with this library; if not, write to the Free Software
24 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
28 #include "wined3d_private.h"
30 WINE_DEFAULT_DEBUG_CHANNEL(d3d_draw);
35 /* GL locking is done by the caller */
36 static void drawStridedFast(IWineD3DDevice *iface, GLenum primitive_type,
37 UINT count, UINT idx_size, const void *idx_data, UINT start_idx)
41 TRACE("(%p) : glElements(%x, %d, ...)\n", iface, primitive_type, count);
43 glDrawElements(primitive_type, count,
44 idx_size == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT,
45 (const char *)idx_data + (idx_size * start_idx));
46 checkGLcall("glDrawElements");
50 TRACE("(%p) : glDrawArrays(%#x, %d, %d)\n", iface, primitive_type, start_idx, count);
52 glDrawArrays(primitive_type, start_idx, count);
53 checkGLcall("glDrawArrays");
58 * Actually draw using the supplied information.
59 * Slower GL version which extracts info about each vertex in turn
62 /* GL locking is done by the caller */
63 static void drawStridedSlow(IWineD3DDevice *iface, const struct wined3d_context *context,
64 const struct wined3d_stream_info *si, UINT NumVertexes, GLenum glPrimType,
65 const void *idxData, UINT idxSize, UINT startIdx)
67 unsigned int textureNo = 0;
68 const WORD *pIdxBufS = NULL;
69 const DWORD *pIdxBufL = NULL;
71 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
72 const struct wined3d_stream_state *streams = This->stateBlock->state.streams;
73 LONG SkipnStrides = startIdx + This->stateBlock->loadBaseVertexIndex;
74 BOOL pixelShader = use_ps(This->stateBlock);
75 BOOL specular_fog = FALSE;
76 const BYTE *texCoords[WINED3DDP_MAXTEXCOORD];
77 const BYTE *diffuse = NULL, *specular = NULL, *normal = NULL, *position = NULL;
78 const struct wined3d_gl_info *gl_info = context->gl_info;
79 UINT texture_stages = gl_info->limits.texture_stages;
80 const struct wined3d_stream_info_element *element;
81 UINT num_untracked_materials;
84 TRACE("Using slow vertex array code\n");
86 /* Variable Initialization */
89 /* Immediate mode drawing can't make use of indices in a vbo - get the
90 * data from the index buffer. If the index buffer has no vbo (not
91 * supported or other reason), or with user pointer drawing idxData
92 * will be non-NULL. */
94 idxData = buffer_get_sysmem(This->stateBlock->state.index_buffer, gl_info);
96 if (idxSize == 2) pIdxBufS = idxData;
97 else pIdxBufL = idxData;
99 ERR("non-NULL idxData with 0 idxSize, this should never happen\n");
103 /* Start drawing in GL */
106 if (si->use_map & (1 << WINED3D_FFP_POSITION))
108 element = &si->elements[WINED3D_FFP_POSITION];
109 position = element->data + streams[element->stream_idx].offset;
112 if (si->use_map & (1 << WINED3D_FFP_NORMAL))
114 element = &si->elements[WINED3D_FFP_NORMAL];
115 normal = element->data + streams[element->stream_idx].offset;
122 num_untracked_materials = context->num_untracked_materials;
123 if (si->use_map & (1 << WINED3D_FFP_DIFFUSE))
125 element = &si->elements[WINED3D_FFP_DIFFUSE];
126 diffuse = element->data + streams[element->stream_idx].offset;
128 if (num_untracked_materials && element->format->id != WINED3DFMT_B8G8R8A8_UNORM)
129 FIXME("Implement diffuse color tracking from %s\n", debug_d3dformat(element->format->id));
133 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
136 if (si->use_map & (1 << WINED3D_FFP_SPECULAR))
138 element = &si->elements[WINED3D_FFP_SPECULAR];
139 specular = element->data + streams[element->stream_idx].offset;
141 /* special case where the fog density is stored in the specular alpha channel */
142 if (This->stateBlock->state.render_states[WINED3DRS_FOGENABLE]
143 && (This->stateBlock->state.render_states[WINED3DRS_FOGVERTEXMODE] == WINED3DFOG_NONE
144 || si->elements[WINED3D_FFP_POSITION].format->id == WINED3DFMT_R32G32B32A32_FLOAT)
145 && This->stateBlock->state.render_states[WINED3DRS_FOGTABLEMODE] == WINED3DFOG_NONE)
147 if (gl_info->supported[EXT_FOG_COORD])
149 if (element->format->id == WINED3DFMT_B8G8R8A8_UNORM) specular_fog = TRUE;
150 else FIXME("Implement fog coordinates from %s\n", debug_d3dformat(element->format->id));
158 /* TODO: Use the fog table code from old ddraw */
159 FIXME("Implement fog for transformed vertices in software\n");
165 else if (gl_info->supported[EXT_SECONDARY_COLOR])
167 GL_EXTCALL(glSecondaryColor3fEXT)(0, 0, 0);
170 for (textureNo = 0; textureNo < texture_stages; ++textureNo)
172 int coordIdx = This->stateBlock->state.texture_states[textureNo][WINED3DTSS_TEXCOORDINDEX];
173 DWORD texture_idx = This->texUnitMap[textureNo];
175 if (!gl_info->supported[ARB_MULTITEXTURE] && textureNo > 0)
177 FIXME("Program using multiple concurrent textures which this opengl implementation doesn't support\n");
181 if (!pixelShader && !This->stateBlock->state.textures[textureNo]) continue;
183 if (texture_idx == WINED3D_UNMAPPED_STAGE) continue;
187 TRACE("tex: %d - Skip tex coords, as being system generated\n", textureNo);
190 else if (coordIdx < 0)
192 FIXME("tex: %d - Coord index %d is less than zero, expect a crash.\n", textureNo, coordIdx);
196 if (si->use_map & (1 << (WINED3D_FFP_TEXCOORD0 + coordIdx)))
198 element = &si->elements[WINED3D_FFP_TEXCOORD0 + coordIdx];
199 texCoords[coordIdx] = element->data + streams[element->stream_idx].offset;
200 tex_mask |= (1 << textureNo);
204 TRACE("tex: %d - Skipping tex coords, as no data supplied\n", textureNo);
205 if (gl_info->supported[ARB_MULTITEXTURE])
206 GL_EXTCALL(glMultiTexCoord4fARB(GL_TEXTURE0_ARB + texture_idx, 0, 0, 0, 1));
208 glTexCoord4f(0, 0, 0, 1);
212 /* We shouldn't start this function if any VBO is involved. Should I put a safety check here?
213 * Guess it's not necessary(we crash then anyway) and would only eat CPU time
216 /* For each primitive */
217 for (vx_index = 0; vx_index < NumVertexes; ++vx_index) {
218 UINT texture, tmp_tex_mask;
219 /* Blending data and Point sizes are not supported by this function. They are not supported by the fixed
220 * function pipeline at all. A Fixme for them is printed after decoding the vertex declaration
223 /* For indexed data, we need to go a few more strides in */
226 /* Indexed so work out the number of strides to skip */
228 SkipnStrides = pIdxBufS[startIdx + vx_index] + This->stateBlock->loadBaseVertexIndex;
230 SkipnStrides = pIdxBufL[startIdx + vx_index] + This->stateBlock->loadBaseVertexIndex;
233 tmp_tex_mask = tex_mask;
234 for (texture = 0; tmp_tex_mask; tmp_tex_mask >>= 1, ++texture)
240 if (!(tmp_tex_mask & 1)) continue;
242 coord_idx = This->stateBlock->state.texture_states[texture][WINED3DTSS_TEXCOORDINDEX];
243 ptr = texCoords[coord_idx] + (SkipnStrides * si->elements[WINED3D_FFP_TEXCOORD0 + coord_idx].stride);
245 texture_idx = This->texUnitMap[texture];
246 multi_texcoord_funcs[si->elements[WINED3D_FFP_TEXCOORD0 + coord_idx].format->emit_idx](
247 GL_TEXTURE0_ARB + texture_idx, ptr);
250 /* Diffuse -------------------------------- */
252 const void *ptrToCoords = diffuse + SkipnStrides * si->elements[WINED3D_FFP_DIFFUSE].stride;
254 diffuse_funcs[si->elements[WINED3D_FFP_DIFFUSE].format->emit_idx](ptrToCoords);
255 if (num_untracked_materials)
257 DWORD diffuseColor = ((const DWORD *)ptrToCoords)[0];
261 color[0] = D3DCOLOR_B_R(diffuseColor) / 255.0f;
262 color[1] = D3DCOLOR_B_G(diffuseColor) / 255.0f;
263 color[2] = D3DCOLOR_B_B(diffuseColor) / 255.0f;
264 color[3] = D3DCOLOR_B_A(diffuseColor) / 255.0f;
266 for (i = 0; i < num_untracked_materials; ++i)
268 glMaterialfv(GL_FRONT_AND_BACK, context->untracked_materials[i], color);
273 /* Specular ------------------------------- */
275 const void *ptrToCoords = specular + SkipnStrides * si->elements[WINED3D_FFP_SPECULAR].stride;
277 specular_funcs[si->elements[WINED3D_FFP_SPECULAR].format->emit_idx](ptrToCoords);
281 DWORD specularColor = *(const DWORD *)ptrToCoords;
282 GL_EXTCALL(glFogCoordfEXT(specularColor >> 24));
286 /* Normal -------------------------------- */
289 const void *ptrToCoords = normal + SkipnStrides * si->elements[WINED3D_FFP_NORMAL].stride;
290 normal_funcs[si->elements[WINED3D_FFP_NORMAL].format->emit_idx](ptrToCoords);
293 /* Position -------------------------------- */
295 const void *ptrToCoords = position + SkipnStrides * si->elements[WINED3D_FFP_POSITION].stride;
296 position_funcs[si->elements[WINED3D_FFP_POSITION].format->emit_idx](ptrToCoords);
299 /* For non indexed mode, step onto next parts */
300 if (!idxData) ++SkipnStrides;
304 checkGLcall("glEnd and previous calls");
307 /* GL locking is done by the caller */
308 static inline void send_attribute(IWineD3DDeviceImpl *This,
309 enum wined3d_format_id format, const UINT index, const void *ptr)
311 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
315 case WINED3DFMT_R32_FLOAT:
316 GL_EXTCALL(glVertexAttrib1fvARB(index, ptr));
318 case WINED3DFMT_R32G32_FLOAT:
319 GL_EXTCALL(glVertexAttrib2fvARB(index, ptr));
321 case WINED3DFMT_R32G32B32_FLOAT:
322 GL_EXTCALL(glVertexAttrib3fvARB(index, ptr));
324 case WINED3DFMT_R32G32B32A32_FLOAT:
325 GL_EXTCALL(glVertexAttrib4fvARB(index, ptr));
328 case WINED3DFMT_R8G8B8A8_UINT:
329 GL_EXTCALL(glVertexAttrib4ubvARB(index, ptr));
331 case WINED3DFMT_B8G8R8A8_UNORM:
332 if (gl_info->supported[ARB_VERTEX_ARRAY_BGRA])
334 const DWORD *src = ptr;
335 DWORD c = *src & 0xff00ff00;
336 c |= (*src & 0xff0000) >> 16;
337 c |= (*src & 0xff) << 16;
338 GL_EXTCALL(glVertexAttrib4NubvARB(index, (GLubyte *)&c));
341 /* else fallthrough */
342 case WINED3DFMT_R8G8B8A8_UNORM:
343 GL_EXTCALL(glVertexAttrib4NubvARB(index, ptr));
346 case WINED3DFMT_R16G16_SINT:
347 GL_EXTCALL(glVertexAttrib4svARB(index, ptr));
349 case WINED3DFMT_R16G16B16A16_SINT:
350 GL_EXTCALL(glVertexAttrib4svARB(index, ptr));
353 case WINED3DFMT_R16G16_SNORM:
355 GLshort s[4] = {((const GLshort *)ptr)[0], ((const GLshort *)ptr)[1], 0, 1};
356 GL_EXTCALL(glVertexAttrib4NsvARB(index, s));
359 case WINED3DFMT_R16G16_UNORM:
361 GLushort s[4] = {((const GLushort *)ptr)[0], ((const GLushort *)ptr)[1], 0, 1};
362 GL_EXTCALL(glVertexAttrib4NusvARB(index, s));
365 case WINED3DFMT_R16G16B16A16_SNORM:
366 GL_EXTCALL(glVertexAttrib4NsvARB(index, ptr));
368 case WINED3DFMT_R16G16B16A16_UNORM:
369 GL_EXTCALL(glVertexAttrib4NusvARB(index, ptr));
372 case WINED3DFMT_R10G10B10A2_UINT:
373 FIXME("Unsure about WINED3DDECLTYPE_UDEC3\n");
374 /*glVertexAttrib3usvARB(instancedData[j], (GLushort *) ptr); Does not exist */
376 case WINED3DFMT_R10G10B10A2_SNORM:
377 FIXME("Unsure about WINED3DDECLTYPE_DEC3N\n");
378 /*glVertexAttrib3NusvARB(instancedData[j], (GLushort *) ptr); Does not exist */
381 case WINED3DFMT_R16G16_FLOAT:
382 /* Are those 16 bit floats. C doesn't have a 16 bit float type. I could read the single bits and calculate a 4
383 * byte float according to the IEEE standard
385 if (gl_info->supported[NV_HALF_FLOAT])
387 /* Not supported by GL_ARB_half_float_vertex */
388 GL_EXTCALL(glVertexAttrib2hvNV(index, ptr));
392 float x = float_16_to_32(((const unsigned short *)ptr) + 0);
393 float y = float_16_to_32(((const unsigned short *)ptr) + 1);
394 GL_EXTCALL(glVertexAttrib2fARB(index, x, y));
397 case WINED3DFMT_R16G16B16A16_FLOAT:
398 if (gl_info->supported[NV_HALF_FLOAT])
400 /* Not supported by GL_ARB_half_float_vertex */
401 GL_EXTCALL(glVertexAttrib4hvNV(index, ptr));
405 float x = float_16_to_32(((const unsigned short *)ptr) + 0);
406 float y = float_16_to_32(((const unsigned short *)ptr) + 1);
407 float z = float_16_to_32(((const unsigned short *)ptr) + 2);
408 float w = float_16_to_32(((const unsigned short *)ptr) + 3);
409 GL_EXTCALL(glVertexAttrib4fARB(index, x, y, z, w));
414 ERR("Unexpected attribute format: %s\n", debug_d3dformat(format));
419 /* GL locking is done by the caller */
420 static void drawStridedSlowVs(IWineD3DDevice *iface, const struct wined3d_stream_info *si, UINT numberOfVertices,
421 GLenum glPrimitiveType, const void *idxData, UINT idxSize, UINT startIdx)
423 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
424 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
425 LONG SkipnStrides = startIdx + This->stateBlock->loadBaseVertexIndex;
426 const WORD *pIdxBufS = NULL;
427 const DWORD *pIdxBufL = NULL;
430 IWineD3DStateBlockImpl *stateblock = This->stateBlock;
435 /* Immediate mode drawing can't make use of indices in a vbo - get the
436 * data from the index buffer. If the index buffer has no vbo (not
437 * supported or other reason), or with user pointer drawing idxData
438 * will be non-NULL. */
440 idxData = buffer_get_sysmem(This->stateBlock->state.index_buffer, gl_info);
442 if (idxSize == 2) pIdxBufS = idxData;
443 else pIdxBufL = idxData;
444 } else if (idxData) {
445 ERR("non-NULL idxData with 0 idxSize, this should never happen\n");
449 /* Start drawing in GL */
450 glBegin(glPrimitiveType);
452 for (vx_index = 0; vx_index < numberOfVertices; ++vx_index)
456 /* Indexed so work out the number of strides to skip */
458 SkipnStrides = pIdxBufS[startIdx + vx_index] + stateblock->loadBaseVertexIndex;
460 SkipnStrides = pIdxBufL[startIdx + vx_index] + stateblock->loadBaseVertexIndex;
463 for (i = MAX_ATTRIBS - 1; i >= 0; i--)
465 if (!(si->use_map & (1 << i))) continue;
467 ptr = si->elements[i].data
468 + si->elements[i].stride * SkipnStrides
469 + stateblock->state.streams[si->elements[i].stream_idx].offset;
471 send_attribute(This, si->elements[i].format->id, i, ptr);
479 /* GL locking is done by the caller */
480 static inline void drawStridedInstanced(IWineD3DDevice *iface, const struct wined3d_stream_info *si,
481 UINT numberOfVertices, GLenum glPrimitiveType, const void *idxData, UINT idxSize,
484 UINT numInstances = 0, i;
485 int numInstancedAttribs = 0, j;
486 UINT instancedData[sizeof(si->elements) / sizeof(*si->elements) /* 16 */];
487 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
488 IWineD3DStateBlockImpl *stateblock = This->stateBlock;
492 /* This is a nasty thing. MSDN says no hardware supports that and apps have to use software vertex processing.
493 * We don't support this for now
495 * Shouldn't be too hard to support with opengl, in theory just call glDrawArrays instead of drawElements.
496 * But the StreamSourceFreq value has a different meaning in that situation.
498 FIXME("Non-indexed instanced drawing is not supported\n");
502 TRACE("(%p) : glElements(%x, %d, ...)\n", This, glPrimitiveType, numberOfVertices);
504 /* First, figure out how many instances we have to draw */
505 for (i = 0; i < MAX_STREAMS; ++i)
507 /* Look at the streams and take the first one which matches */
508 if (stateblock->state.streams[i].buffer
509 && ((stateblock->state.streams[i].flags & WINED3DSTREAMSOURCE_INSTANCEDATA)
510 || (stateblock->state.streams[i].flags & WINED3DSTREAMSOURCE_INDEXEDDATA)))
512 /* Use the specified number of instances from the first matched
513 * stream. A streamFreq of 0 (with INSTANCEDATA or INDEXEDDATA)
514 * is handled as 1. See d3d9/tests/visual.c-> stream_test(). */
515 numInstances = stateblock->state.streams[i].frequency ? stateblock->state.streams[i].frequency : 1;
520 for (i = 0; i < sizeof(si->elements) / sizeof(*si->elements); ++i)
522 if (!(si->use_map & (1 << i))) continue;
524 if (stateblock->state.streams[si->elements[i].stream_idx].flags & WINED3DSTREAMSOURCE_INSTANCEDATA)
526 instancedData[numInstancedAttribs] = i;
527 numInstancedAttribs++;
531 /* now draw numInstances instances :-) */
532 for(i = 0; i < numInstances; i++) {
533 /* Specify the instanced attributes using immediate mode calls */
534 for(j = 0; j < numInstancedAttribs; j++) {
535 const BYTE *ptr = si->elements[instancedData[j]].data
536 + si->elements[instancedData[j]].stride * i
537 + stateblock->state.streams[si->elements[instancedData[j]].stream_idx].offset;
538 if (si->elements[instancedData[j]].buffer_object)
540 struct wined3d_buffer *vb = stateblock->state.streams[si->elements[instancedData[j]].stream_idx].buffer;
541 ptr += (ULONG_PTR)buffer_get_sysmem(vb, &This->adapter->gl_info);
544 send_attribute(This, si->elements[instancedData[j]].format->id, instancedData[j], ptr);
547 glDrawElements(glPrimitiveType, numberOfVertices, idxSize == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT,
548 (const char *)idxData+(idxSize * startIdx));
549 checkGLcall("glDrawElements");
553 static inline void remove_vbos(IWineD3DDeviceImpl *This, const struct wined3d_gl_info *gl_info,
554 struct wined3d_stream_info *s)
558 for (i = 0; i < (sizeof(s->elements) / sizeof(*s->elements)); ++i)
560 struct wined3d_stream_info_element *e;
562 if (!(s->use_map & (1 << i))) continue;
565 if (e->buffer_object)
567 struct wined3d_buffer *vb = This->stateBlock->state.streams[e->stream_idx].buffer;
568 e->buffer_object = 0;
569 e->data = (BYTE *)((ULONG_PTR)e->data + (ULONG_PTR)buffer_get_sysmem(vb, gl_info));
574 /* Routine common to the draw primitive and draw indexed primitive routines */
575 void drawPrimitive(IWineD3DDevice *iface, UINT index_count, UINT StartIdx, UINT idxSize, const void *idxData)
578 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
579 struct wined3d_context *context;
582 if (!index_count) return;
584 if (This->stateBlock->state.render_states[WINED3DRS_COLORWRITEENABLE])
586 /* Invalidate the back buffer memory so LockRect will read it the next time */
587 for (i = 0; i < This->adapter->gl_info.limits.buffers; ++i)
589 IWineD3DSurfaceImpl *target = This->render_targets[i];
592 surface_load_location(target, SFLAG_INDRAWABLE, NULL);
593 surface_modify_location(target, SFLAG_INDRAWABLE, TRUE);
598 /* Signals other modules that a drawing is in progress and the stateblock finalized */
599 This->isInDraw = TRUE;
601 context = context_acquire(This, This->render_targets[0]);
604 context_release(context);
605 WARN("Invalid context, skipping draw.\n");
609 context_apply_draw_state(context, This);
611 if (This->depth_stencil)
613 /* Note that this depends on the context_acquire() call above to set
614 * This->render_offscreen properly. We don't currently take the
615 * Z-compare function into account, but we could skip loading the
616 * depthstencil for D3DCMP_NEVER and D3DCMP_ALWAYS as well. Also note
617 * that we never copy the stencil data.*/
618 DWORD location = context->render_offscreen ? SFLAG_DS_OFFSCREEN : SFLAG_DS_ONSCREEN;
619 if (This->stateBlock->state.render_states[WINED3DRS_ZWRITEENABLE]
620 || This->stateBlock->state.render_states[WINED3DRS_ZENABLE])
622 RECT current_rect, draw_rect, r;
624 if (location == SFLAG_DS_ONSCREEN && This->depth_stencil != This->onscreen_depth_stencil)
625 device_switch_onscreen_ds(This, context, This->depth_stencil);
627 if (This->depth_stencil->Flags & location)
628 SetRect(¤t_rect, 0, 0,
629 This->depth_stencil->ds_current_size.cx,
630 This->depth_stencil->ds_current_size.cy);
632 SetRectEmpty(¤t_rect);
634 device_get_draw_rect(This, &draw_rect);
636 IntersectRect(&r, &draw_rect, ¤t_rect);
637 if (!EqualRect(&r, &draw_rect))
638 surface_load_ds_location(This->depth_stencil, context, location);
640 if (This->stateBlock->state.render_states[WINED3DRS_ZWRITEENABLE])
642 surface_modify_ds_location(This->depth_stencil, location,
643 This->depth_stencil->ds_current_size.cx,
644 This->depth_stencil->ds_current_size.cy);
645 surface_modify_location(This->depth_stencil, SFLAG_INDRAWABLE, TRUE);
650 if ((!context->gl_info->supported[WINED3D_GL_VERSION_2_0]
651 || (!glPointParameteri && !context->gl_info->supported[NV_POINT_SPRITE]))
652 && context->render_offscreen
653 && This->stateBlock->state.render_states[WINED3DRS_POINTSPRITEENABLE]
654 && This->stateBlock->gl_primitive_type == GL_POINTS)
656 FIXME("Point sprite coordinate origin switching not supported.\n");
659 /* Ok, we will be updating the screen from here onwards so grab the lock */
662 GLenum glPrimType = This->stateBlock->gl_primitive_type;
663 BOOL emulation = FALSE;
664 const struct wined3d_stream_info *stream_info = &This->strided_streams;
665 struct wined3d_stream_info stridedlcl;
667 if (!use_vs(This->stateBlock))
669 if (!This->strided_streams.position_transformed && context->num_untracked_materials
670 && This->stateBlock->state.render_states[WINED3DRS_LIGHTING])
674 FIXME("Using software emulation because not all material properties could be tracked\n");
677 TRACE("Using software emulation because not all material properties could be tracked\n");
681 else if (context->fog_coord && This->stateBlock->state.render_states[WINED3DRS_FOGENABLE])
683 /* Either write a pipeline replacement shader or convert the specular alpha from unsigned byte
684 * to a float in the vertex buffer
688 FIXME("Using software emulation because manual fog coordinates are provided\n");
691 TRACE("Using software emulation because manual fog coordinates are provided\n");
697 stream_info = &stridedlcl;
698 memcpy(&stridedlcl, &This->strided_streams, sizeof(stridedlcl));
699 remove_vbos(This, context->gl_info, &stridedlcl);
703 if (This->useDrawStridedSlow || emulation) {
704 /* Immediate mode drawing */
705 if (use_vs(This->stateBlock))
709 FIXME("Using immediate mode with vertex shaders for half float emulation\n");
712 TRACE("Using immediate mode with vertex shaders for half float emulation\n");
714 drawStridedSlowVs(iface, stream_info, index_count, glPrimType, idxData, idxSize, StartIdx);
716 drawStridedSlow(iface, context, stream_info, index_count,
717 glPrimType, idxData, idxSize, StartIdx);
719 } else if(This->instancedDraw) {
720 /* Instancing emulation with mixing immediate mode and arrays */
721 drawStridedInstanced(iface, &This->strided_streams, index_count,
722 glPrimType, idxData, idxSize, StartIdx);
724 drawStridedFast(iface, glPrimType, index_count, idxSize, idxData, StartIdx);
728 /* Finished updating the screen, restore lock */
731 for(i = 0; i < This->num_buffer_queries; i++)
733 wined3d_event_query_issue(This->buffer_queries[i], This);
736 if (wined3d_settings.strict_draw_ordering) wglFlush(); /* Flush to ensure ordering across contexts. */
738 context_release(context);
740 TRACE("Done all gl drawing\n");
742 /* Control goes back to the device, stateblock values may change again */
743 This->isInDraw = FALSE;
746 static void normalize_normal(float *n) {
747 float length = n[0] * n[0] + n[1] * n[1] + n[2] * n[2];
748 if (length == 0.0f) return;
749 length = sqrtf(length);
750 n[0] = n[0] / length;
751 n[1] = n[1] / length;
752 n[2] = n[2] / length;
755 /* Tesselates a high order rectangular patch into single triangles using gl evaluators
757 * The problem is that OpenGL does not offer a direct way to return the tesselated primitives,
758 * and they can't be sent off for rendering directly either. Tesselating is slow, so we want
759 * to cache the patches in a vertex buffer. But more importantly, gl can't bind generated
760 * attributes to numbered shader attributes, so we have to store them and rebind them as needed
763 * To read back, the opengl feedback mode is used. This creates a problem because we want
764 * untransformed, unlit vertices, but feedback runs everything through transform and lighting.
765 * Thus disable lighting and set identity matrices to get unmodified colors and positions.
766 * To overcome clipping find the biggest x, y and z values of the vertices in the patch and scale
767 * them to [-1.0;+1.0] and set the viewport up to scale them back.
769 * Normals are more tricky: Draw white vertices with 3 directional lights, and calculate the
770 * resulting colors back to the normals.
772 * NOTE: This function activates a context for blitting, modifies matrices & viewport, but
773 * does not restore it because normally a draw follows immediately afterwards. The caller is
774 * responsible of taking care that either the gl states are restored, or the context activated
775 * for drawing to reset the lastWasBlit flag.
777 HRESULT tesselate_rectpatch(IWineD3DDeviceImpl *This,
778 struct WineD3DRectPatch *patch) {
779 unsigned int i, j, num_quads, out_vertex_size, buffer_size, d3d_out_vertex_size;
780 float max_x = 0.0f, max_y = 0.0f, max_z = 0.0f, neg_z = 0.0f;
781 struct wined3d_stream_info stream_info;
782 struct wined3d_stream_info_element *e;
783 struct wined3d_context *context;
785 const WINED3DRECTPATCH_INFO *info = &patch->RectPatchInfo;
787 GLenum feedback_type;
790 /* Simply activate the context for blitting. This disables all the things we don't want and
791 * takes care of dirtifying. Dirtifying is preferred over pushing / popping, since drawing the
792 * patch (as opposed to normal draws) will most likely need different changes anyway. */
793 context = context_acquire(This, NULL);
794 context_apply_blit_state(context, This);
796 /* First, locate the position data. This is provided in a vertex buffer in the stateblock.
799 device_stream_info_from_declaration(This, FALSE, &stream_info, NULL);
801 e = &stream_info.elements[WINED3D_FFP_POSITION];
802 if (e->buffer_object)
804 struct wined3d_buffer *vb = This->stateBlock->state.streams[e->stream_idx].buffer;
805 e->data = (BYTE *)((ULONG_PTR)e->data + (ULONG_PTR)buffer_get_sysmem(vb, context->gl_info));
807 vtxStride = e->stride;
809 vtxStride * info->Stride * info->StartVertexOffsetHeight +
810 vtxStride * info->StartVertexOffsetWidth;
812 /* Not entirely sure about what happens with transformed vertices */
813 if (stream_info.position_transformed) FIXME("Transformed position in rectpatch generation\n");
815 if(vtxStride % sizeof(GLfloat)) {
816 /* glMap2f reads vertex sizes in GLfloats, the d3d stride is in bytes.
817 * I don't see how the stride could not be a multiple of 4, but make sure
820 ERR("Vertex stride is not a multiple of sizeof(GLfloat)\n");
822 if(info->Basis != WINED3DBASIS_BEZIER) {
823 FIXME("Basis is %s, how to handle this?\n", debug_d3dbasis(info->Basis));
825 if(info->Degree != WINED3DDEGREE_CUBIC) {
826 FIXME("Degree is %s, how to handle this?\n", debug_d3ddegree(info->Degree));
829 /* First, get the boundary cube of the input data */
830 for(j = 0; j < info->Height; j++) {
831 for(i = 0; i < info->Width; i++) {
832 const float *v = (const float *)(data + vtxStride * i + vtxStride * info->Stride * j);
833 if(fabs(v[0]) > max_x) max_x = fabsf(v[0]);
834 if(fabs(v[1]) > max_y) max_y = fabsf(v[1]);
835 if(fabs(v[2]) > max_z) max_z = fabsf(v[2]);
836 if(v[2] < neg_z) neg_z = v[2];
840 /* This needs some improvements in the vertex decl code */
841 FIXME("Cannot find data to generate. Only generating position and normals\n");
842 patch->has_normals = TRUE;
843 patch->has_texcoords = FALSE;
847 glMatrixMode(GL_PROJECTION);
848 checkGLcall("glMatrixMode(GL_PROJECTION)");
850 checkGLcall("glLoadIndentity()");
851 glScalef(1.0f / (max_x), 1.0f / (max_y), max_z == 0.0f ? 1.0f : 1.0f / (2.0f * max_z));
852 glTranslatef(0.0f, 0.0f, 0.5f);
853 checkGLcall("glScalef");
854 glViewport(-max_x, -max_y, 2 * (max_x), 2 * (max_y));
855 checkGLcall("glViewport");
857 /* Some states to take care of. If we're in wireframe opengl will produce lines, and confuse
858 * our feedback buffer parser
860 glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
861 checkGLcall("glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)");
862 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_FILLMODE));
863 if(patch->has_normals) {
864 static const GLfloat black[] = {0.0f, 0.0f, 0.0f, 0.0f};
865 static const GLfloat red[] = {1.0f, 0.0f, 0.0f, 0.0f};
866 static const GLfloat green[] = {0.0f, 1.0f, 0.0f, 0.0f};
867 static const GLfloat blue[] = {0.0f, 0.0f, 1.0f, 0.0f};
868 static const GLfloat white[] = {1.0f, 1.0f, 1.0f, 1.0f};
869 glEnable(GL_LIGHTING);
870 checkGLcall("glEnable(GL_LIGHTING)");
871 glLightModelfv(GL_LIGHT_MODEL_AMBIENT, black);
872 checkGLcall("glLightModel for MODEL_AMBIENT");
873 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_AMBIENT));
875 for (i = 3; i < context->gl_info->limits.lights; ++i)
877 glDisable(GL_LIGHT0 + i);
878 checkGLcall("glDisable(GL_LIGHT0 + i)");
879 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_ACTIVELIGHT(i));
882 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_ACTIVELIGHT(0));
883 glLightfv(GL_LIGHT0, GL_DIFFUSE, red);
884 glLightfv(GL_LIGHT0, GL_SPECULAR, black);
885 glLightfv(GL_LIGHT0, GL_AMBIENT, black);
886 glLightfv(GL_LIGHT0, GL_POSITION, red);
888 checkGLcall("Setting up light 1");
889 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_ACTIVELIGHT(1));
890 glLightfv(GL_LIGHT1, GL_DIFFUSE, green);
891 glLightfv(GL_LIGHT1, GL_SPECULAR, black);
892 glLightfv(GL_LIGHT1, GL_AMBIENT, black);
893 glLightfv(GL_LIGHT1, GL_POSITION, green);
895 checkGLcall("Setting up light 2");
896 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_ACTIVELIGHT(2));
897 glLightfv(GL_LIGHT2, GL_DIFFUSE, blue);
898 glLightfv(GL_LIGHT2, GL_SPECULAR, black);
899 glLightfv(GL_LIGHT2, GL_AMBIENT, black);
900 glLightfv(GL_LIGHT2, GL_POSITION, blue);
902 checkGLcall("Setting up light 3");
904 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_MATERIAL);
905 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_COLORVERTEX));
906 glDisable(GL_COLOR_MATERIAL);
907 glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, black);
908 glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, black);
909 glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, white);
910 checkGLcall("Setting up materials");
913 /* Enable the needed maps.
914 * GL_MAP2_VERTEX_3 is needed for positional data.
915 * GL_AUTO_NORMAL to generate normals from the position. Do not use GL_MAP2_NORMAL.
916 * GL_MAP2_TEXTURE_COORD_4 for texture coords
918 num_quads = ceilf(patch->numSegs[0]) * ceilf(patch->numSegs[1]);
919 out_vertex_size = 3 /* position */;
920 d3d_out_vertex_size = 3;
921 glEnable(GL_MAP2_VERTEX_3);
922 if(patch->has_normals && patch->has_texcoords) {
923 FIXME("Texcoords not handled yet\n");
924 feedback_type = GL_3D_COLOR_TEXTURE;
925 out_vertex_size += 8;
926 d3d_out_vertex_size += 7;
927 glEnable(GL_AUTO_NORMAL);
928 glEnable(GL_MAP2_TEXTURE_COORD_4);
929 } else if(patch->has_texcoords) {
930 FIXME("Texcoords not handled yet\n");
931 feedback_type = GL_3D_COLOR_TEXTURE;
932 out_vertex_size += 7;
933 d3d_out_vertex_size += 4;
934 glEnable(GL_MAP2_TEXTURE_COORD_4);
935 } else if(patch->has_normals) {
936 feedback_type = GL_3D_COLOR;
937 out_vertex_size += 4;
938 d3d_out_vertex_size += 3;
939 glEnable(GL_AUTO_NORMAL);
941 feedback_type = GL_3D;
943 checkGLcall("glEnable vertex attrib generation");
945 buffer_size = num_quads * out_vertex_size * 2 /* triangle list */ * 3 /* verts per tri */
946 + 4 * num_quads /* 2 triangle markers per quad + num verts in tri */;
947 feedbuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, buffer_size * sizeof(float) * 8);
949 glMap2f(GL_MAP2_VERTEX_3,
950 0.0f, 1.0f, vtxStride / sizeof(float), info->Width,
951 0.0f, 1.0f, info->Stride * vtxStride / sizeof(float), info->Height,
952 (const GLfloat *)data);
953 checkGLcall("glMap2f");
954 if(patch->has_texcoords) {
955 glMap2f(GL_MAP2_TEXTURE_COORD_4,
956 0.0f, 1.0f, vtxStride / sizeof(float), info->Width,
957 0.0f, 1.0f, info->Stride * vtxStride / sizeof(float), info->Height,
958 (const GLfloat *)data);
959 checkGLcall("glMap2f");
961 glMapGrid2f(ceilf(patch->numSegs[0]), 0.0f, 1.0f, ceilf(patch->numSegs[1]), 0.0f, 1.0f);
962 checkGLcall("glMapGrid2f");
964 glFeedbackBuffer(buffer_size * 2, feedback_type, feedbuffer);
965 checkGLcall("glFeedbackBuffer");
966 glRenderMode(GL_FEEDBACK);
968 glEvalMesh2(GL_FILL, 0, ceilf(patch->numSegs[0]), 0, ceilf(patch->numSegs[1]));
969 checkGLcall("glEvalMesh2");
971 i = glRenderMode(GL_RENDER);
974 ERR("Feedback failed. Expected %d elements back\n", buffer_size);
975 HeapFree(GetProcessHeap(), 0, feedbuffer);
976 context_release(context);
977 return WINED3DERR_DRIVERINTERNALERROR;
978 } else if(i != buffer_size) {
980 ERR("Unexpected amount of elements returned. Expected %d, got %d\n", buffer_size, i);
981 HeapFree(GetProcessHeap(), 0, feedbuffer);
982 context_release(context);
983 return WINED3DERR_DRIVERINTERNALERROR;
985 TRACE("Got %d elements as expected\n", i);
988 HeapFree(GetProcessHeap(), 0, patch->mem);
989 patch->mem = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, num_quads * 6 * d3d_out_vertex_size * sizeof(float) * 8);
991 for(j = 0; j < buffer_size; j += (3 /* num verts */ * out_vertex_size + 2 /* tri marker */)) {
992 if(feedbuffer[j] != GL_POLYGON_TOKEN) {
993 ERR("Unexpected token: %f\n", feedbuffer[j]);
996 if(feedbuffer[j + 1] != 3) {
997 ERR("Unexpected polygon: %f corners\n", feedbuffer[j + 1]);
1000 /* Somehow there are different ideas about back / front facing, so fix up the
1003 patch->mem[i + 0] = feedbuffer[j + out_vertex_size * 2 + 2]; /* x, triangle 2 */
1004 patch->mem[i + 1] = feedbuffer[j + out_vertex_size * 2 + 3]; /* y, triangle 2 */
1005 patch->mem[i + 2] = (feedbuffer[j + out_vertex_size * 2 + 4] - 0.5f) * 4.0f * max_z; /* z, triangle 3 */
1006 if(patch->has_normals) {
1007 patch->mem[i + 3] = feedbuffer[j + out_vertex_size * 2 + 5];
1008 patch->mem[i + 4] = feedbuffer[j + out_vertex_size * 2 + 6];
1009 patch->mem[i + 5] = feedbuffer[j + out_vertex_size * 2 + 7];
1011 i += d3d_out_vertex_size;
1013 patch->mem[i + 0] = feedbuffer[j + out_vertex_size * 1 + 2]; /* x, triangle 2 */
1014 patch->mem[i + 1] = feedbuffer[j + out_vertex_size * 1 + 3]; /* y, triangle 2 */
1015 patch->mem[i + 2] = (feedbuffer[j + out_vertex_size * 1 + 4] - 0.5f) * 4.0f * max_z; /* z, triangle 2 */
1016 if(patch->has_normals) {
1017 patch->mem[i + 3] = feedbuffer[j + out_vertex_size * 1 + 5];
1018 patch->mem[i + 4] = feedbuffer[j + out_vertex_size * 1 + 6];
1019 patch->mem[i + 5] = feedbuffer[j + out_vertex_size * 1 + 7];
1021 i += d3d_out_vertex_size;
1023 patch->mem[i + 0] = feedbuffer[j + out_vertex_size * 0 + 2]; /* x, triangle 1 */
1024 patch->mem[i + 1] = feedbuffer[j + out_vertex_size * 0 + 3]; /* y, triangle 1 */
1025 patch->mem[i + 2] = (feedbuffer[j + out_vertex_size * 0 + 4] - 0.5f) * 4.0f * max_z; /* z, triangle 1 */
1026 if(patch->has_normals) {
1027 patch->mem[i + 3] = feedbuffer[j + out_vertex_size * 0 + 5];
1028 patch->mem[i + 4] = feedbuffer[j + out_vertex_size * 0 + 6];
1029 patch->mem[i + 5] = feedbuffer[j + out_vertex_size * 0 + 7];
1031 i += d3d_out_vertex_size;
1034 if(patch->has_normals) {
1035 /* Now do the same with reverse light directions */
1036 static const GLfloat x[] = {-1.0f, 0.0f, 0.0f, 0.0f};
1037 static const GLfloat y[] = { 0.0f, -1.0f, 0.0f, 0.0f};
1038 static const GLfloat z[] = { 0.0f, 0.0f, -1.0f, 0.0f};
1039 glLightfv(GL_LIGHT0, GL_POSITION, x);
1040 glLightfv(GL_LIGHT1, GL_POSITION, y);
1041 glLightfv(GL_LIGHT2, GL_POSITION, z);
1042 checkGLcall("Setting up reverse light directions");
1044 glRenderMode(GL_FEEDBACK);
1045 checkGLcall("glRenderMode(GL_FEEDBACK)");
1046 glEvalMesh2(GL_FILL, 0, ceilf(patch->numSegs[0]), 0, ceilf(patch->numSegs[1]));
1047 checkGLcall("glEvalMesh2");
1048 i = glRenderMode(GL_RENDER);
1049 checkGLcall("glRenderMode(GL_RENDER)");
1052 for(j = 0; j < buffer_size; j += (3 /* num verts */ * out_vertex_size + 2 /* tri marker */)) {
1053 if(feedbuffer[j] != GL_POLYGON_TOKEN) {
1054 ERR("Unexpected token: %f\n", feedbuffer[j]);
1057 if(feedbuffer[j + 1] != 3) {
1058 ERR("Unexpected polygon: %f corners\n", feedbuffer[j + 1]);
1061 if(patch->mem[i + 3] == 0.0f)
1062 patch->mem[i + 3] = -feedbuffer[j + out_vertex_size * 2 + 5];
1063 if(patch->mem[i + 4] == 0.0f)
1064 patch->mem[i + 4] = -feedbuffer[j + out_vertex_size * 2 + 6];
1065 if(patch->mem[i + 5] == 0.0f)
1066 patch->mem[i + 5] = -feedbuffer[j + out_vertex_size * 2 + 7];
1067 normalize_normal(patch->mem + i + 3);
1068 i += d3d_out_vertex_size;
1070 if(patch->mem[i + 3] == 0.0f)
1071 patch->mem[i + 3] = -feedbuffer[j + out_vertex_size * 1 + 5];
1072 if(patch->mem[i + 4] == 0.0f)
1073 patch->mem[i + 4] = -feedbuffer[j + out_vertex_size * 1 + 6];
1074 if(patch->mem[i + 5] == 0.0f)
1075 patch->mem[i + 5] = -feedbuffer[j + out_vertex_size * 1 + 7];
1076 normalize_normal(patch->mem + i + 3);
1077 i += d3d_out_vertex_size;
1079 if(patch->mem[i + 3] == 0.0f)
1080 patch->mem[i + 3] = -feedbuffer[j + out_vertex_size * 0 + 5];
1081 if(patch->mem[i + 4] == 0.0f)
1082 patch->mem[i + 4] = -feedbuffer[j + out_vertex_size * 0 + 6];
1083 if(patch->mem[i + 5] == 0.0f)
1084 patch->mem[i + 5] = -feedbuffer[j + out_vertex_size * 0 + 7];
1085 normalize_normal(patch->mem + i + 3);
1086 i += d3d_out_vertex_size;
1090 glDisable(GL_MAP2_VERTEX_3);
1091 glDisable(GL_AUTO_NORMAL);
1092 glDisable(GL_MAP2_NORMAL);
1093 glDisable(GL_MAP2_TEXTURE_COORD_4);
1094 checkGLcall("glDisable vertex attrib generation");
1097 context_release(context);
1099 HeapFree(GetProcessHeap(), 0, feedbuffer);
1101 vtxStride = 3 * sizeof(float);
1102 if(patch->has_normals) {
1103 vtxStride += 3 * sizeof(float);
1105 if(patch->has_texcoords) {
1106 vtxStride += 4 * sizeof(float);
1108 memset(&patch->strided, 0, sizeof(patch->strided));
1109 patch->strided.position.format = WINED3DFMT_R32G32B32_FLOAT;
1110 patch->strided.position.lpData = (BYTE *) patch->mem;
1111 patch->strided.position.dwStride = vtxStride;
1113 if(patch->has_normals) {
1114 patch->strided.normal.format = WINED3DFMT_R32G32B32_FLOAT;
1115 patch->strided.normal.lpData = (BYTE *) patch->mem + 3 * sizeof(float) /* pos */;
1116 patch->strided.normal.dwStride = vtxStride;
1118 if(patch->has_texcoords) {
1119 patch->strided.texCoords[0].format = WINED3DFMT_R32G32B32A32_FLOAT;
1120 patch->strided.texCoords[0].lpData = (BYTE *) patch->mem + 3 * sizeof(float) /* pos */;
1121 if(patch->has_normals) {
1122 patch->strided.texCoords[0].lpData += 3 * sizeof(float);
1124 patch->strided.texCoords[0].dwStride = vtxStride;