msxml3: Fix attributes formatting.
[wine/multimedia.git] / dlls / wined3d / device.c
blobab9f657e878f3edae48a072e49a2accd49a5edd3
1 /*
2 * Copyright 2002 Lionel Ulmer
3 * Copyright 2002-2005 Jason Edmeades
4 * Copyright 2003-2004 Raphael Junqueira
5 * Copyright 2004 Christian Costa
6 * Copyright 2005 Oliver Stieber
7 * Copyright 2006-2008 Stefan Dösinger for CodeWeavers
8 * Copyright 2006-2008 Henri Verbeet
9 * Copyright 2007 Andrew Riedi
10 * Copyright 2009-2011 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
27 #include "config.h"
28 #include <stdio.h>
29 #ifdef HAVE_FLOAT_H
30 # include <float.h>
31 #endif
32 #include "wined3d_private.h"
34 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
36 /* Define the default light parameters as specified by MSDN */
37 const WINED3DLIGHT WINED3D_default_light = {
39 WINED3DLIGHT_DIRECTIONAL, /* Type */
40 { 1.0f, 1.0f, 1.0f, 0.0f }, /* Diffuse r,g,b,a */
41 { 0.0f, 0.0f, 0.0f, 0.0f }, /* Specular r,g,b,a */
42 { 0.0f, 0.0f, 0.0f, 0.0f }, /* Ambient r,g,b,a, */
43 { 0.0f, 0.0f, 0.0f }, /* Position x,y,z */
44 { 0.0f, 0.0f, 1.0f }, /* Direction x,y,z */
45 0.0f, /* Range */
46 0.0f, /* Falloff */
47 0.0f, 0.0f, 0.0f, /* Attenuation 0,1,2 */
48 0.0f, /* Theta */
49 0.0f /* Phi */
52 /**********************************************************
53 * Global variable / Constants follow
54 **********************************************************/
55 const float identity[] =
57 1.0f, 0.0f, 0.0f, 0.0f,
58 0.0f, 1.0f, 0.0f, 0.0f,
59 0.0f, 0.0f, 1.0f, 0.0f,
60 0.0f, 0.0f, 0.0f, 1.0f,
61 }; /* When needed for comparisons */
63 /* Note that except for WINED3DPT_POINTLIST and WINED3DPT_LINELIST these
64 * actually have the same values in GL and D3D. */
65 static GLenum gl_primitive_type_from_d3d(WINED3DPRIMITIVETYPE primitive_type)
67 switch(primitive_type)
69 case WINED3DPT_POINTLIST:
70 return GL_POINTS;
72 case WINED3DPT_LINELIST:
73 return GL_LINES;
75 case WINED3DPT_LINESTRIP:
76 return GL_LINE_STRIP;
78 case WINED3DPT_TRIANGLELIST:
79 return GL_TRIANGLES;
81 case WINED3DPT_TRIANGLESTRIP:
82 return GL_TRIANGLE_STRIP;
84 case WINED3DPT_TRIANGLEFAN:
85 return GL_TRIANGLE_FAN;
87 case WINED3DPT_LINELIST_ADJ:
88 return GL_LINES_ADJACENCY_ARB;
90 case WINED3DPT_LINESTRIP_ADJ:
91 return GL_LINE_STRIP_ADJACENCY_ARB;
93 case WINED3DPT_TRIANGLELIST_ADJ:
94 return GL_TRIANGLES_ADJACENCY_ARB;
96 case WINED3DPT_TRIANGLESTRIP_ADJ:
97 return GL_TRIANGLE_STRIP_ADJACENCY_ARB;
99 default:
100 FIXME("Unhandled primitive type %s\n", debug_d3dprimitivetype(primitive_type));
101 return GL_NONE;
105 static WINED3DPRIMITIVETYPE d3d_primitive_type_from_gl(GLenum primitive_type)
107 switch(primitive_type)
109 case GL_POINTS:
110 return WINED3DPT_POINTLIST;
112 case GL_LINES:
113 return WINED3DPT_LINELIST;
115 case GL_LINE_STRIP:
116 return WINED3DPT_LINESTRIP;
118 case GL_TRIANGLES:
119 return WINED3DPT_TRIANGLELIST;
121 case GL_TRIANGLE_STRIP:
122 return WINED3DPT_TRIANGLESTRIP;
124 case GL_TRIANGLE_FAN:
125 return WINED3DPT_TRIANGLEFAN;
127 case GL_LINES_ADJACENCY_ARB:
128 return WINED3DPT_LINELIST_ADJ;
130 case GL_LINE_STRIP_ADJACENCY_ARB:
131 return WINED3DPT_LINESTRIP_ADJ;
133 case GL_TRIANGLES_ADJACENCY_ARB:
134 return WINED3DPT_TRIANGLELIST_ADJ;
136 case GL_TRIANGLE_STRIP_ADJACENCY_ARB:
137 return WINED3DPT_TRIANGLESTRIP_ADJ;
139 default:
140 FIXME("Unhandled primitive type %s\n", debug_d3dprimitivetype(primitive_type));
141 return WINED3DPT_UNDEFINED;
145 static BOOL fixed_get_input(BYTE usage, BYTE usage_idx, unsigned int *regnum)
147 if ((usage == WINED3DDECLUSAGE_POSITION || usage == WINED3DDECLUSAGE_POSITIONT) && !usage_idx)
148 *regnum = WINED3D_FFP_POSITION;
149 else if (usage == WINED3DDECLUSAGE_BLENDWEIGHT && !usage_idx)
150 *regnum = WINED3D_FFP_BLENDWEIGHT;
151 else if (usage == WINED3DDECLUSAGE_BLENDINDICES && !usage_idx)
152 *regnum = WINED3D_FFP_BLENDINDICES;
153 else if (usage == WINED3DDECLUSAGE_NORMAL && !usage_idx)
154 *regnum = WINED3D_FFP_NORMAL;
155 else if (usage == WINED3DDECLUSAGE_PSIZE && !usage_idx)
156 *regnum = WINED3D_FFP_PSIZE;
157 else if (usage == WINED3DDECLUSAGE_COLOR && !usage_idx)
158 *regnum = WINED3D_FFP_DIFFUSE;
159 else if (usage == WINED3DDECLUSAGE_COLOR && usage_idx == 1)
160 *regnum = WINED3D_FFP_SPECULAR;
161 else if (usage == WINED3DDECLUSAGE_TEXCOORD && usage_idx < WINED3DDP_MAXTEXCOORD)
162 *regnum = WINED3D_FFP_TEXCOORD0 + usage_idx;
163 else
165 FIXME("Unsupported input stream [usage=%s, usage_idx=%u]\n", debug_d3ddeclusage(usage), usage_idx);
166 *regnum = ~0U;
167 return FALSE;
170 return TRUE;
173 /* Context activation is done by the caller. */
174 void device_stream_info_from_declaration(struct wined3d_device *device,
175 struct wined3d_stream_info *stream_info, BOOL *fixup)
177 const struct wined3d_state *state = &device->stateBlock->state;
178 /* We need to deal with frequency data! */
179 struct wined3d_vertex_declaration *declaration = state->vertex_declaration;
180 BOOL use_vshader;
181 unsigned int i;
183 stream_info->use_map = 0;
184 stream_info->swizzle_map = 0;
186 /* Check for transformed vertices, disable vertex shader if present. */
187 stream_info->position_transformed = declaration->position_transformed;
188 use_vshader = state->vertex_shader && !declaration->position_transformed;
190 /* Translate the declaration into strided data. */
191 for (i = 0; i < declaration->element_count; ++i)
193 const struct wined3d_vertex_declaration_element *element = &declaration->elements[i];
194 const struct wined3d_stream_state *stream = &state->streams[element->input_slot];
195 struct wined3d_buffer *buffer = stream->buffer;
196 struct wined3d_bo_address data;
197 BOOL stride_used;
198 unsigned int idx;
199 DWORD stride;
201 TRACE("%p Element %p (%u of %u)\n", declaration->elements,
202 element, i + 1, declaration->element_count);
204 if (!buffer) continue;
206 data.buffer_object = 0;
207 data.addr = NULL;
209 stride = stream->stride;
210 if (state->user_stream)
212 TRACE("Stream %u is UP, %p\n", element->input_slot, buffer);
213 data.buffer_object = 0;
214 data.addr = (BYTE *)buffer;
216 else
218 TRACE("Stream %u isn't UP, %p\n", element->input_slot, buffer);
219 buffer_get_memory(buffer, &device->adapter->gl_info, &data);
221 /* Can't use vbo's if the base vertex index is negative. OpenGL doesn't accept negative offsets
222 * (or rather offsets bigger than the vbo, because the pointer is unsigned), so use system memory
223 * sources. In most sane cases the pointer - offset will still be > 0, otherwise it will wrap
224 * around to some big value. Hope that with the indices, the driver wraps it back internally. If
225 * not, drawStridedSlow is needed, including a vertex buffer path. */
226 if (state->load_base_vertex_index < 0)
228 WARN("load_base_vertex_index is < 0 (%d), not using VBOs.\n",
229 state->load_base_vertex_index);
230 data.buffer_object = 0;
231 data.addr = buffer_get_sysmem(buffer, &device->adapter->gl_info);
232 if ((UINT_PTR)data.addr < -state->load_base_vertex_index * stride)
234 FIXME("System memory vertex data load offset is negative!\n");
238 if (fixup)
240 if (data.buffer_object)
241 *fixup = TRUE;
242 else if (*fixup && !use_vshader
243 && (element->usage == WINED3DDECLUSAGE_COLOR
244 || element->usage == WINED3DDECLUSAGE_POSITIONT))
246 static BOOL warned = FALSE;
247 if (!warned)
249 /* This may be bad with the fixed function pipeline. */
250 FIXME("Missing vbo streams with unfixed colors or transformed position, expect problems\n");
251 warned = TRUE;
256 data.addr += element->offset;
258 TRACE("offset %u input_slot %u usage_idx %d\n", element->offset, element->input_slot, element->usage_idx);
260 if (use_vshader)
262 if (element->output_slot == ~0U)
264 /* TODO: Assuming vertexdeclarations are usually used with the
265 * same or a similar shader, it might be worth it to store the
266 * last used output slot and try that one first. */
267 stride_used = vshader_get_input(state->vertex_shader,
268 element->usage, element->usage_idx, &idx);
270 else
272 idx = element->output_slot;
273 stride_used = TRUE;
276 else
278 if (!element->ffp_valid)
280 WARN("Skipping unsupported fixed function element of format %s and usage %s\n",
281 debug_d3dformat(element->format->id), debug_d3ddeclusage(element->usage));
282 stride_used = FALSE;
284 else
286 stride_used = fixed_get_input(element->usage, element->usage_idx, &idx);
290 if (stride_used)
292 TRACE("Load %s array %u [usage %s, usage_idx %u, "
293 "input_slot %u, offset %u, stride %u, format %s, buffer_object %u]\n",
294 use_vshader ? "shader": "fixed function", idx,
295 debug_d3ddeclusage(element->usage), element->usage_idx, element->input_slot,
296 element->offset, stride, debug_d3dformat(element->format->id), data.buffer_object);
298 data.addr += stream->offset;
300 stream_info->elements[idx].format = element->format;
301 stream_info->elements[idx].data = data;
302 stream_info->elements[idx].stride = stride;
303 stream_info->elements[idx].stream_idx = element->input_slot;
305 if (!device->adapter->gl_info.supported[ARB_VERTEX_ARRAY_BGRA]
306 && element->format->id == WINED3DFMT_B8G8R8A8_UNORM)
308 stream_info->swizzle_map |= 1 << idx;
310 stream_info->use_map |= 1 << idx;
314 device->num_buffer_queries = 0;
315 if (!state->user_stream)
317 WORD map = stream_info->use_map;
319 /* PreLoad all the vertex buffers. */
320 for (i = 0; map; map >>= 1, ++i)
322 struct wined3d_stream_info_element *element;
323 struct wined3d_buffer *buffer;
325 if (!(map & 1)) continue;
327 element = &stream_info->elements[i];
328 buffer = state->streams[element->stream_idx].buffer;
329 wined3d_buffer_preload(buffer);
331 /* If the preload dropped the buffer object, update the stream info. */
332 if (buffer->buffer_object != element->data.buffer_object)
334 element->data.buffer_object = 0;
335 element->data.addr = buffer_get_sysmem(buffer, &device->adapter->gl_info)
336 + (ptrdiff_t)element->data.addr;
339 if (buffer->query)
340 device->buffer_queries[device->num_buffer_queries++] = buffer->query;
345 static void stream_info_element_from_strided(const struct wined3d_gl_info *gl_info,
346 const struct WineDirect3DStridedData *strided, struct wined3d_stream_info_element *e)
348 e->data.addr = strided->lpData;
349 e->data.buffer_object = 0;
350 e->format = wined3d_get_format(gl_info, strided->format);
351 e->stride = strided->dwStride;
352 e->stream_idx = 0;
355 static void device_stream_info_from_strided(const struct wined3d_gl_info *gl_info,
356 const struct WineDirect3DVertexStridedData *strided, struct wined3d_stream_info *stream_info)
358 unsigned int i;
360 memset(stream_info, 0, sizeof(*stream_info));
362 if (strided->position.lpData)
363 stream_info_element_from_strided(gl_info, &strided->position, &stream_info->elements[WINED3D_FFP_POSITION]);
364 if (strided->normal.lpData)
365 stream_info_element_from_strided(gl_info, &strided->normal, &stream_info->elements[WINED3D_FFP_NORMAL]);
366 if (strided->diffuse.lpData)
367 stream_info_element_from_strided(gl_info, &strided->diffuse, &stream_info->elements[WINED3D_FFP_DIFFUSE]);
368 if (strided->specular.lpData)
369 stream_info_element_from_strided(gl_info, &strided->specular, &stream_info->elements[WINED3D_FFP_SPECULAR]);
371 for (i = 0; i < WINED3DDP_MAXTEXCOORD; ++i)
373 if (strided->texCoords[i].lpData)
374 stream_info_element_from_strided(gl_info, &strided->texCoords[i],
375 &stream_info->elements[WINED3D_FFP_TEXCOORD0 + i]);
378 stream_info->position_transformed = strided->position_transformed;
380 for (i = 0; i < sizeof(stream_info->elements) / sizeof(*stream_info->elements); ++i)
382 if (!stream_info->elements[i].format) continue;
384 if (!gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
385 && stream_info->elements[i].format->id == WINED3DFMT_B8G8R8A8_UNORM)
387 stream_info->swizzle_map |= 1 << i;
389 stream_info->use_map |= 1 << i;
393 static void device_trace_strided_stream_info(const struct wined3d_stream_info *stream_info)
395 TRACE("Strided Data:\n");
396 TRACE_STRIDED(stream_info, WINED3D_FFP_POSITION);
397 TRACE_STRIDED(stream_info, WINED3D_FFP_BLENDWEIGHT);
398 TRACE_STRIDED(stream_info, WINED3D_FFP_BLENDINDICES);
399 TRACE_STRIDED(stream_info, WINED3D_FFP_NORMAL);
400 TRACE_STRIDED(stream_info, WINED3D_FFP_PSIZE);
401 TRACE_STRIDED(stream_info, WINED3D_FFP_DIFFUSE);
402 TRACE_STRIDED(stream_info, WINED3D_FFP_SPECULAR);
403 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD0);
404 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD1);
405 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD2);
406 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD3);
407 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD4);
408 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD5);
409 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD6);
410 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD7);
413 /* Context activation is done by the caller. */
414 void device_update_stream_info(struct wined3d_device *device, const struct wined3d_gl_info *gl_info)
416 struct wined3d_stream_info *stream_info = &device->strided_streams;
417 const struct wined3d_state *state = &device->stateBlock->state;
418 BOOL fixup = FALSE;
420 if (device->up_strided)
422 /* Note: this is a ddraw fixed-function code path. */
423 TRACE("=============================== Strided Input ================================\n");
424 device_stream_info_from_strided(gl_info, device->up_strided, stream_info);
425 if (TRACE_ON(d3d)) device_trace_strided_stream_info(stream_info);
427 else
429 TRACE("============================= Vertex Declaration =============================\n");
430 device_stream_info_from_declaration(device, stream_info, &fixup);
433 if (state->vertex_shader && !stream_info->position_transformed)
435 if (state->vertex_declaration->half_float_conv_needed && !fixup)
437 TRACE("Using drawStridedSlow with vertex shaders for FLOAT16 conversion.\n");
438 device->useDrawStridedSlow = TRUE;
440 else
442 device->useDrawStridedSlow = FALSE;
445 else
447 WORD slow_mask = (1 << WINED3D_FFP_PSIZE);
448 slow_mask |= -!gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
449 & ((1 << WINED3D_FFP_DIFFUSE) | (1 << WINED3D_FFP_SPECULAR));
451 if ((stream_info->position_transformed || (stream_info->use_map & slow_mask)) && !fixup)
453 device->useDrawStridedSlow = TRUE;
455 else
457 device->useDrawStridedSlow = FALSE;
462 static void device_preload_texture(const struct wined3d_state *state, unsigned int idx)
464 struct wined3d_texture *texture;
465 enum WINED3DSRGB srgb;
467 if (!(texture = state->textures[idx])) return;
468 srgb = state->sampler_states[idx][WINED3DSAMP_SRGBTEXTURE] ? SRGB_SRGB : SRGB_RGB;
469 texture->texture_ops->texture_preload(texture, srgb);
472 void device_preload_textures(const struct wined3d_device *device)
474 const struct wined3d_state *state = &device->stateBlock->state;
475 unsigned int i;
477 if (use_vs(state))
479 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
481 if (state->vertex_shader->reg_maps.sampler_type[i])
482 device_preload_texture(state, MAX_FRAGMENT_SAMPLERS + i);
486 if (use_ps(state))
488 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
490 if (state->pixel_shader->reg_maps.sampler_type[i])
491 device_preload_texture(state, i);
494 else
496 WORD ffu_map = device->fixed_function_usage_map;
498 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
500 if (ffu_map & 1)
501 device_preload_texture(state, i);
506 BOOL device_context_add(struct wined3d_device *device, struct wined3d_context *context)
508 struct wined3d_context **new_array;
510 TRACE("Adding context %p.\n", context);
512 if (!device->contexts) new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*new_array));
513 else new_array = HeapReAlloc(GetProcessHeap(), 0, device->contexts,
514 sizeof(*new_array) * (device->context_count + 1));
516 if (!new_array)
518 ERR("Failed to grow the context array.\n");
519 return FALSE;
522 new_array[device->context_count++] = context;
523 device->contexts = new_array;
524 return TRUE;
527 void device_context_remove(struct wined3d_device *device, struct wined3d_context *context)
529 struct wined3d_context **new_array;
530 BOOL found = FALSE;
531 UINT i;
533 TRACE("Removing context %p.\n", context);
535 for (i = 0; i < device->context_count; ++i)
537 if (device->contexts[i] == context)
539 found = TRUE;
540 break;
544 if (!found)
546 ERR("Context %p doesn't exist in context array.\n", context);
547 return;
550 if (!--device->context_count)
552 HeapFree(GetProcessHeap(), 0, device->contexts);
553 device->contexts = NULL;
554 return;
557 memmove(&device->contexts[i], &device->contexts[i + 1], (device->context_count - i) * sizeof(*device->contexts));
558 new_array = HeapReAlloc(GetProcessHeap(), 0, device->contexts, device->context_count * sizeof(*device->contexts));
559 if (!new_array)
561 ERR("Failed to shrink context array. Oh well.\n");
562 return;
565 device->contexts = new_array;
568 /* Do not call while under the GL lock. */
569 void device_switch_onscreen_ds(struct wined3d_device *device,
570 struct wined3d_context *context, struct wined3d_surface *depth_stencil)
572 if (device->onscreen_depth_stencil)
574 surface_load_ds_location(device->onscreen_depth_stencil, context, SFLAG_DS_OFFSCREEN);
575 surface_modify_ds_location(device->onscreen_depth_stencil, SFLAG_DS_OFFSCREEN,
576 device->onscreen_depth_stencil->ds_current_size.cx,
577 device->onscreen_depth_stencil->ds_current_size.cy);
578 wined3d_surface_decref(device->onscreen_depth_stencil);
580 device->onscreen_depth_stencil = depth_stencil;
581 wined3d_surface_incref(device->onscreen_depth_stencil);
584 static BOOL is_full_clear(struct wined3d_surface *target, const RECT *draw_rect, const RECT *clear_rect)
586 /* partial draw rect */
587 if (draw_rect->left || draw_rect->top
588 || draw_rect->right < target->resource.width
589 || draw_rect->bottom < target->resource.height)
590 return FALSE;
592 /* partial clear rect */
593 if (clear_rect && (clear_rect->left > 0 || clear_rect->top > 0
594 || clear_rect->right < target->resource.width
595 || clear_rect->bottom < target->resource.height))
596 return FALSE;
598 return TRUE;
601 static void prepare_ds_clear(struct wined3d_surface *ds, struct wined3d_context *context,
602 DWORD location, const RECT *draw_rect, UINT rect_count, const RECT *clear_rect)
604 RECT current_rect, r;
606 if (ds->flags & location)
607 SetRect(&current_rect, 0, 0,
608 ds->ds_current_size.cx,
609 ds->ds_current_size.cy);
610 else
611 SetRectEmpty(&current_rect);
613 IntersectRect(&r, draw_rect, &current_rect);
614 if (EqualRect(&r, draw_rect))
616 /* current_rect ⊇ draw_rect, modify only. */
617 surface_modify_ds_location(ds, location, ds->ds_current_size.cx, ds->ds_current_size.cy);
618 return;
621 if (EqualRect(&r, &current_rect))
623 /* draw_rect ⊇ current_rect, test if we're doing a full clear. */
625 if (!clear_rect)
627 /* Full clear, modify only. */
628 surface_modify_ds_location(ds, location, draw_rect->right, draw_rect->bottom);
629 return;
632 IntersectRect(&r, draw_rect, clear_rect);
633 if (EqualRect(&r, draw_rect))
635 /* clear_rect ⊇ draw_rect, modify only. */
636 surface_modify_ds_location(ds, location, draw_rect->right, draw_rect->bottom);
637 return;
641 /* Full load. */
642 surface_load_ds_location(ds, context, location);
643 surface_modify_ds_location(ds, location, ds->ds_current_size.cx, ds->ds_current_size.cy);
646 /* Do not call while under the GL lock. */
647 HRESULT device_clear_render_targets(struct wined3d_device *device, UINT rt_count, const struct wined3d_fb_state *fb,
648 UINT rect_count, const RECT *rects, const RECT *draw_rect, DWORD flags, const WINED3DCOLORVALUE *color,
649 float depth, DWORD stencil)
651 const RECT *clear_rect = (rect_count > 0 && rects) ? (const RECT *)rects : NULL;
652 struct wined3d_surface *target = rt_count ? fb->render_targets[0] : NULL;
653 UINT drawable_width, drawable_height;
654 struct wined3d_context *context;
655 GLbitfield clear_mask = 0;
656 BOOL render_offscreen;
657 unsigned int i;
659 /* When we're clearing parts of the drawable, make sure that the target surface is well up to date in the
660 * drawable. After the clear we'll mark the drawable up to date, so we have to make sure that this is true
661 * for the cleared parts, and the untouched parts.
663 * If we're clearing the whole target there is no need to copy it into the drawable, it will be overwritten
664 * anyway. If we're not clearing the color buffer we don't have to copy either since we're not going to set
665 * the drawable up to date. We have to check all settings that limit the clear area though. Do not bother
666 * checking all this if the dest surface is in the drawable anyway. */
667 if (flags & WINED3DCLEAR_TARGET && !is_full_clear(target, draw_rect, clear_rect))
669 for (i = 0; i < rt_count; ++i)
671 struct wined3d_surface *rt = fb->render_targets[i];
672 if (rt)
673 surface_load_location(rt, rt->draw_binding, NULL);
677 context = context_acquire(device, target);
678 if (!context->valid)
680 context_release(context);
681 WARN("Invalid context, skipping clear.\n");
682 return WINED3D_OK;
685 if (target)
687 render_offscreen = context->render_offscreen;
688 target->get_drawable_size(context, &drawable_width, &drawable_height);
690 else
692 render_offscreen = TRUE;
693 drawable_width = fb->depth_stencil->pow2Width;
694 drawable_height = fb->depth_stencil->pow2Height;
697 if (flags & WINED3DCLEAR_ZBUFFER)
699 DWORD location = render_offscreen ? SFLAG_DS_OFFSCREEN : SFLAG_DS_ONSCREEN;
701 if (location == SFLAG_DS_ONSCREEN && fb->depth_stencil != device->onscreen_depth_stencil)
702 device_switch_onscreen_ds(device, context, fb->depth_stencil);
703 prepare_ds_clear(fb->depth_stencil, context, location, draw_rect, rect_count, clear_rect);
706 if (!context_apply_clear_state(context, device, rt_count, fb))
708 context_release(context);
709 WARN("Failed to apply clear state, skipping clear.\n");
710 return WINED3D_OK;
713 ENTER_GL();
715 /* Only set the values up once, as they are not changing. */
716 if (flags & WINED3DCLEAR_STENCIL)
718 if (context->gl_info->supported[EXT_STENCIL_TWO_SIDE])
720 glDisable(GL_STENCIL_TEST_TWO_SIDE_EXT);
721 context_invalidate_state(context, STATE_RENDER(WINED3DRS_TWOSIDEDSTENCILMODE));
723 glStencilMask(~0U);
724 context_invalidate_state(context, STATE_RENDER(WINED3DRS_STENCILWRITEMASK));
725 glClearStencil(stencil);
726 checkGLcall("glClearStencil");
727 clear_mask = clear_mask | GL_STENCIL_BUFFER_BIT;
730 if (flags & WINED3DCLEAR_ZBUFFER)
732 surface_modify_location(fb->depth_stencil, fb->depth_stencil->draw_binding, TRUE);
734 glDepthMask(GL_TRUE);
735 context_invalidate_state(context, STATE_RENDER(WINED3DRS_ZWRITEENABLE));
736 glClearDepth(depth);
737 checkGLcall("glClearDepth");
738 clear_mask = clear_mask | GL_DEPTH_BUFFER_BIT;
741 if (flags & WINED3DCLEAR_TARGET)
743 for (i = 0; i < rt_count; ++i)
745 struct wined3d_surface *rt = fb->render_targets[i];
747 if (rt)
748 surface_modify_location(rt, rt->draw_binding, TRUE);
751 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
752 context_invalidate_state(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE));
753 context_invalidate_state(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE1));
754 context_invalidate_state(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE2));
755 context_invalidate_state(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE3));
756 glClearColor(color->r, color->g, color->b, color->a);
757 checkGLcall("glClearColor");
758 clear_mask = clear_mask | GL_COLOR_BUFFER_BIT;
761 if (!clear_rect)
763 if (render_offscreen)
765 glScissor(draw_rect->left, draw_rect->top,
766 draw_rect->right - draw_rect->left, draw_rect->bottom - draw_rect->top);
768 else
770 glScissor(draw_rect->left, drawable_height - draw_rect->bottom,
771 draw_rect->right - draw_rect->left, draw_rect->bottom - draw_rect->top);
773 checkGLcall("glScissor");
774 glClear(clear_mask);
775 checkGLcall("glClear");
777 else
779 RECT current_rect;
781 /* Now process each rect in turn. */
782 for (i = 0; i < rect_count; ++i)
784 /* Note that GL uses lower left, width/height. */
785 IntersectRect(&current_rect, draw_rect, &clear_rect[i]);
787 TRACE("clear_rect[%u] %s, current_rect %s.\n", i,
788 wine_dbgstr_rect(&clear_rect[i]),
789 wine_dbgstr_rect(&current_rect));
791 /* Tests show that rectangles where x1 > x2 or y1 > y2 are ignored silently.
792 * The rectangle is not cleared, no error is returned, but further rectangles are
793 * still cleared if they are valid. */
794 if (current_rect.left > current_rect.right || current_rect.top > current_rect.bottom)
796 TRACE("Rectangle with negative dimensions, ignoring.\n");
797 continue;
800 if (render_offscreen)
802 glScissor(current_rect.left, current_rect.top,
803 current_rect.right - current_rect.left, current_rect.bottom - current_rect.top);
805 else
807 glScissor(current_rect.left, drawable_height - current_rect.bottom,
808 current_rect.right - current_rect.left, current_rect.bottom - current_rect.top);
810 checkGLcall("glScissor");
812 glClear(clear_mask);
813 checkGLcall("glClear");
817 LEAVE_GL();
819 if (wined3d_settings.strict_draw_ordering || (flags & WINED3DCLEAR_TARGET
820 && target->container.type == WINED3D_CONTAINER_SWAPCHAIN
821 && target->container.u.swapchain->front_buffer == target))
822 wglFlush(); /* Flush to ensure ordering across contexts. */
824 context_release(context);
826 return WINED3D_OK;
829 ULONG CDECL wined3d_device_incref(struct wined3d_device *device)
831 ULONG refcount = InterlockedIncrement(&device->ref);
833 TRACE("%p increasing refcount to %u.\n", device, refcount);
835 return refcount;
838 ULONG CDECL wined3d_device_decref(struct wined3d_device *device)
840 ULONG refcount = InterlockedDecrement(&device->ref);
842 TRACE("%p decreasing refcount to %u.\n", device, refcount);
844 if (!refcount)
846 UINT i;
848 for (i = 0; i < sizeof(device->multistate_funcs) / sizeof(device->multistate_funcs[0]); ++i)
850 HeapFree(GetProcessHeap(), 0, device->multistate_funcs[i]);
851 device->multistate_funcs[i] = NULL;
854 if (!list_empty(&device->resources))
856 struct wined3d_resource *resource;
858 FIXME("Device released with resources still bound, acceptable but unexpected.\n");
860 LIST_FOR_EACH_ENTRY(resource, &device->resources, struct wined3d_resource, resource_list_entry)
862 FIXME("Leftover resource %p with type %s (%#x).\n",
863 resource, debug_d3dresourcetype(resource->resourceType), resource->resourceType);
867 if (device->contexts)
868 ERR("Context array not freed!\n");
869 if (device->hardwareCursor)
870 DestroyCursor(device->hardwareCursor);
871 device->hardwareCursor = 0;
873 wined3d_decref(device->wined3d);
874 device->wined3d = NULL;
875 HeapFree(GetProcessHeap(), 0, device);
876 TRACE("Freed device %p.\n", device);
879 return refcount;
882 UINT CDECL wined3d_device_get_swapchain_count(struct wined3d_device *device)
884 TRACE("device %p.\n", device);
886 return device->swapchain_count;
889 HRESULT CDECL wined3d_device_get_swapchain(struct wined3d_device *device,
890 UINT swapchain_idx, struct wined3d_swapchain **swapchain)
892 TRACE("device %p, swapchain_idx %u, swapchain %p.\n",
893 device, swapchain_idx, swapchain);
895 if (swapchain_idx >= device->swapchain_count)
897 WARN("swapchain_idx %u >= swapchain_count %u.\n",
898 swapchain_idx, device->swapchain_count);
899 *swapchain = NULL;
901 return WINED3DERR_INVALIDCALL;
904 *swapchain = device->swapchains[swapchain_idx];
905 wined3d_swapchain_incref(*swapchain);
906 TRACE("Returning %p.\n", *swapchain);
908 return WINED3D_OK;
911 static void device_load_logo(struct wined3d_device *device, const char *filename)
913 HBITMAP hbm;
914 BITMAP bm;
915 HRESULT hr;
916 HDC dcb = NULL, dcs = NULL;
917 WINEDDCOLORKEY colorkey;
919 hbm = LoadImageA(NULL, filename, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE | LR_CREATEDIBSECTION);
920 if(hbm)
922 GetObjectA(hbm, sizeof(BITMAP), &bm);
923 dcb = CreateCompatibleDC(NULL);
924 if(!dcb) goto out;
925 SelectObject(dcb, hbm);
927 else
929 /* Create a 32x32 white surface to indicate that wined3d is used, but the specified image
930 * couldn't be loaded
932 memset(&bm, 0, sizeof(bm));
933 bm.bmWidth = 32;
934 bm.bmHeight = 32;
937 hr = wined3d_surface_create(device, bm.bmWidth, bm.bmHeight, WINED3DFMT_B5G6R5_UNORM, TRUE,
938 FALSE, 0, 0, WINED3DPOOL_DEFAULT, WINED3DMULTISAMPLE_NONE, 0, SURFACE_OPENGL, NULL,
939 &wined3d_null_parent_ops, &device->logo_surface);
940 if (FAILED(hr))
942 ERR("Wine logo requested, but failed to create surface, hr %#x.\n", hr);
943 goto out;
946 if (dcb)
948 if (FAILED(hr = wined3d_surface_getdc(device->logo_surface, &dcs)))
949 goto out;
950 BitBlt(dcs, 0, 0, bm.bmWidth, bm.bmHeight, dcb, 0, 0, SRCCOPY);
951 wined3d_surface_releasedc(device->logo_surface, dcs);
953 colorkey.dwColorSpaceLowValue = 0;
954 colorkey.dwColorSpaceHighValue = 0;
955 wined3d_surface_set_color_key(device->logo_surface, WINEDDCKEY_SRCBLT, &colorkey);
957 else
959 const WINED3DCOLORVALUE c = {1.0f, 1.0f, 1.0f, 1.0f};
960 /* Fill the surface with a white color to show that wined3d is there */
961 wined3d_device_color_fill(device, device->logo_surface, NULL, &c);
964 out:
965 if (dcb) DeleteDC(dcb);
966 if (hbm) DeleteObject(hbm);
969 /* Context activation is done by the caller. */
970 static void create_dummy_textures(struct wined3d_device *device, struct wined3d_context *context)
972 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
973 unsigned int i;
974 /* Under DirectX you can sample even if no texture is bound, whereas
975 * OpenGL will only allow that when a valid texture is bound.
976 * We emulate this by creating dummy textures and binding them
977 * to each texture stage when the currently set D3D texture is NULL. */
978 ENTER_GL();
980 if (gl_info->supported[APPLE_CLIENT_STORAGE])
982 /* The dummy texture does not have client storage backing */
983 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE);
984 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE)");
987 for (i = 0; i < gl_info->limits.textures; ++i)
989 DWORD color = 0x000000ff;
991 /* Make appropriate texture active */
992 context_active_texture(context, gl_info, i);
994 /* Generate an opengl texture name */
995 glGenTextures(1, &device->dummyTextureName[i]);
996 checkGLcall("glGenTextures");
997 TRACE("Dummy Texture %d given name %d.\n", i, device->dummyTextureName[i]);
999 /* Generate a dummy 2d texture (not using 1d because they cause many
1000 * DRI drivers fall back to sw) */
1001 glBindTexture(GL_TEXTURE_2D, device->dummyTextureName[i]);
1002 checkGLcall("glBindTexture");
1004 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 1, 1, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, &color);
1005 checkGLcall("glTexImage2D");
1008 if (gl_info->supported[APPLE_CLIENT_STORAGE])
1010 /* Reenable because if supported it is enabled by default */
1011 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
1012 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
1015 LEAVE_GL();
1018 /* Context activation is done by the caller. */
1019 static void destroy_dummy_textures(struct wined3d_device *device, const struct wined3d_gl_info *gl_info)
1021 ENTER_GL();
1022 glDeleteTextures(gl_info->limits.textures, device->dummyTextureName);
1023 checkGLcall("glDeleteTextures(gl_info->limits.textures, device->dummyTextureName)");
1024 LEAVE_GL();
1026 memset(device->dummyTextureName, 0, gl_info->limits.textures * sizeof(*device->dummyTextureName));
1029 static LONG fullscreen_style(LONG style)
1031 /* Make sure the window is managed, otherwise we won't get keyboard input. */
1032 style |= WS_POPUP | WS_SYSMENU;
1033 style &= ~(WS_CAPTION | WS_THICKFRAME);
1035 return style;
1038 static LONG fullscreen_exstyle(LONG exstyle)
1040 /* Filter out window decorations. */
1041 exstyle &= ~(WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE);
1043 return exstyle;
1046 void CDECL wined3d_device_setup_fullscreen_window(struct wined3d_device *device, HWND window, UINT w, UINT h)
1048 BOOL filter_messages;
1049 LONG style, exstyle;
1051 TRACE("Setting up window %p for fullscreen mode.\n", window);
1053 if (device->style || device->exStyle)
1055 ERR("Changing the window style for window %p, but another style (%08x, %08x) is already stored.\n",
1056 window, device->style, device->exStyle);
1059 device->style = GetWindowLongW(window, GWL_STYLE);
1060 device->exStyle = GetWindowLongW(window, GWL_EXSTYLE);
1062 style = fullscreen_style(device->style);
1063 exstyle = fullscreen_exstyle(device->exStyle);
1065 TRACE("Old style was %08x, %08x, setting to %08x, %08x.\n",
1066 device->style, device->exStyle, style, exstyle);
1068 filter_messages = device->filter_messages;
1069 device->filter_messages = TRUE;
1071 SetWindowLongW(window, GWL_STYLE, style);
1072 SetWindowLongW(window, GWL_EXSTYLE, exstyle);
1073 SetWindowPos(window, HWND_TOP, 0, 0, w, h, SWP_FRAMECHANGED | SWP_SHOWWINDOW | SWP_NOACTIVATE);
1075 device->filter_messages = filter_messages;
1078 void CDECL wined3d_device_restore_fullscreen_window(struct wined3d_device *device, HWND window)
1080 BOOL filter_messages;
1081 LONG style, exstyle;
1083 if (!device->style && !device->exStyle) return;
1085 TRACE("Restoring window style of window %p to %08x, %08x.\n",
1086 window, device->style, device->exStyle);
1088 style = GetWindowLongW(window, GWL_STYLE);
1089 exstyle = GetWindowLongW(window, GWL_EXSTYLE);
1091 filter_messages = device->filter_messages;
1092 device->filter_messages = TRUE;
1094 /* Only restore the style if the application didn't modify it during the
1095 * fullscreen phase. Some applications change it before calling Reset()
1096 * when switching between windowed and fullscreen modes (HL2), some
1097 * depend on the original style (Eve Online). */
1098 if (style == fullscreen_style(device->style) && exstyle == fullscreen_exstyle(device->exStyle))
1100 SetWindowLongW(window, GWL_STYLE, device->style);
1101 SetWindowLongW(window, GWL_EXSTYLE, device->exStyle);
1103 SetWindowPos(window, 0, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
1105 device->filter_messages = filter_messages;
1107 /* Delete the old values. */
1108 device->style = 0;
1109 device->exStyle = 0;
1112 HRESULT CDECL wined3d_device_acquire_focus_window(struct wined3d_device *device, HWND window)
1114 TRACE("device %p, window %p.\n", device, window);
1116 if (!wined3d_register_window(window, device))
1118 ERR("Failed to register window %p.\n", window);
1119 return E_FAIL;
1122 device->focus_window = window;
1123 SetWindowPos(window, 0, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
1125 return WINED3D_OK;
1128 void CDECL wined3d_device_release_focus_window(struct wined3d_device *device)
1130 TRACE("device %p.\n", device);
1132 if (device->focus_window) wined3d_unregister_window(device->focus_window);
1133 device->focus_window = NULL;
1136 HRESULT CDECL wined3d_device_init_3d(struct wined3d_device *device,
1137 WINED3DPRESENT_PARAMETERS *present_parameters)
1139 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1140 struct wined3d_swapchain *swapchain = NULL;
1141 struct wined3d_context *context;
1142 HRESULT hr;
1143 DWORD state;
1144 unsigned int i;
1146 TRACE("device %p, present_parameters %p.\n", device, present_parameters);
1148 if (device->d3d_initialized)
1149 return WINED3DERR_INVALIDCALL;
1150 if (!device->adapter->opengl)
1151 return WINED3DERR_INVALIDCALL;
1153 TRACE("Creating stateblock.\n");
1154 hr = wined3d_stateblock_create(device, WINED3DSBT_INIT, &device->stateBlock);
1155 if (FAILED(hr))
1157 WARN("Failed to create stateblock\n");
1158 goto err_out;
1161 TRACE("Created stateblock %p.\n", device->stateBlock);
1162 device->updateStateBlock = device->stateBlock;
1163 wined3d_stateblock_incref(device->updateStateBlock);
1165 device->valid_rt_mask = 0;
1166 for (i = 0; i < gl_info->limits.buffers; ++i)
1167 device->valid_rt_mask |= (1 << i);
1168 device->fb.render_targets = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1169 sizeof(*device->fb.render_targets) * gl_info->limits.buffers);
1171 device->palette_count = 1;
1172 device->palettes = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(PALETTEENTRY*));
1173 if (!device->palettes || !device->fb.render_targets)
1175 ERR("Out of memory!\n");
1176 hr = E_OUTOFMEMORY;
1177 goto err_out;
1180 device->palettes[0] = HeapAlloc(GetProcessHeap(), 0, sizeof(PALETTEENTRY) * 256);
1181 if (!device->palettes[0])
1183 ERR("Out of memory!\n");
1184 hr = E_OUTOFMEMORY;
1185 goto err_out;
1188 for (i = 0; i < 256; ++i)
1190 device->palettes[0][i].peRed = 0xff;
1191 device->palettes[0][i].peGreen = 0xff;
1192 device->palettes[0][i].peBlue = 0xff;
1193 device->palettes[0][i].peFlags = 0xff;
1195 device->currentPalette = 0;
1197 /* Initialize the texture unit mapping to a 1:1 mapping */
1198 for (state = 0; state < MAX_COMBINED_SAMPLERS; ++state)
1200 if (state < gl_info->limits.fragment_samplers)
1202 device->texUnitMap[state] = state;
1203 device->rev_tex_unit_map[state] = state;
1205 else
1207 device->texUnitMap[state] = WINED3D_UNMAPPED_STAGE;
1208 device->rev_tex_unit_map[state] = WINED3D_UNMAPPED_STAGE;
1212 /* Setup the implicit swapchain. This also initializes a context. */
1213 TRACE("Creating implicit swapchain\n");
1214 hr = device->device_parent->ops->create_swapchain(device->device_parent,
1215 present_parameters, &swapchain);
1216 if (FAILED(hr))
1218 WARN("Failed to create implicit swapchain\n");
1219 goto err_out;
1222 device->swapchain_count = 1;
1223 device->swapchains = HeapAlloc(GetProcessHeap(), 0, device->swapchain_count * sizeof(*device->swapchains));
1224 if (!device->swapchains)
1226 ERR("Out of memory!\n");
1227 goto err_out;
1229 device->swapchains[0] = swapchain;
1231 if (swapchain->back_buffers && swapchain->back_buffers[0])
1233 TRACE("Setting rendertarget to %p.\n", swapchain->back_buffers);
1234 device->fb.render_targets[0] = swapchain->back_buffers[0];
1236 else
1238 TRACE("Setting rendertarget to %p.\n", swapchain->front_buffer);
1239 device->fb.render_targets[0] = swapchain->front_buffer;
1241 wined3d_surface_incref(device->fb.render_targets[0]);
1243 /* Depth Stencil support */
1244 device->fb.depth_stencil = device->auto_depth_stencil;
1245 if (device->fb.depth_stencil)
1246 wined3d_surface_incref(device->fb.depth_stencil);
1248 hr = device->shader_backend->shader_alloc_private(device);
1249 if (FAILED(hr))
1251 TRACE("Shader private data couldn't be allocated\n");
1252 goto err_out;
1254 hr = device->frag_pipe->alloc_private(device);
1255 if (FAILED(hr))
1257 TRACE("Fragment pipeline private data couldn't be allocated\n");
1258 goto err_out;
1260 hr = device->blitter->alloc_private(device);
1261 if (FAILED(hr))
1263 TRACE("Blitter private data couldn't be allocated\n");
1264 goto err_out;
1267 /* Set up some starting GL setup */
1269 /* Setup all the devices defaults */
1270 stateblock_init_default_state(device->stateBlock);
1272 context = context_acquire(device, swapchain->front_buffer);
1274 create_dummy_textures(device, context);
1276 ENTER_GL();
1278 /* Initialize the current view state */
1279 device->view_ident = 1;
1280 device->contexts[0]->last_was_rhw = 0;
1282 switch (wined3d_settings.offscreen_rendering_mode)
1284 case ORM_FBO:
1285 device->offscreenBuffer = GL_COLOR_ATTACHMENT0;
1286 break;
1288 case ORM_BACKBUFFER:
1290 if (context_get_current()->aux_buffers > 0)
1292 TRACE("Using auxiliary buffer for offscreen rendering\n");
1293 device->offscreenBuffer = GL_AUX0;
1295 else
1297 TRACE("Using back buffer for offscreen rendering\n");
1298 device->offscreenBuffer = GL_BACK;
1303 TRACE("All defaults now set up, leaving 3D init.\n");
1304 LEAVE_GL();
1306 context_release(context);
1308 /* Clear the screen */
1309 wined3d_device_clear(device, 0, NULL, WINED3DCLEAR_TARGET
1310 | (present_parameters->EnableAutoDepthStencil ? WINED3DCLEAR_ZBUFFER | WINED3DCLEAR_STENCIL : 0),
1311 0x00, 1.0f, 0);
1313 device->d3d_initialized = TRUE;
1315 if (wined3d_settings.logo)
1316 device_load_logo(device, wined3d_settings.logo);
1317 device->highest_dirty_ps_const = 0;
1318 device->highest_dirty_vs_const = 0;
1319 return WINED3D_OK;
1321 err_out:
1322 HeapFree(GetProcessHeap(), 0, device->fb.render_targets);
1323 HeapFree(GetProcessHeap(), 0, device->swapchains);
1324 device->swapchain_count = 0;
1325 if (device->palettes)
1327 HeapFree(GetProcessHeap(), 0, device->palettes[0]);
1328 HeapFree(GetProcessHeap(), 0, device->palettes);
1330 device->palette_count = 0;
1331 if (swapchain)
1332 wined3d_swapchain_decref(swapchain);
1333 if (device->stateBlock)
1335 wined3d_stateblock_decref(device->stateBlock);
1336 device->stateBlock = NULL;
1338 if (device->blit_priv)
1339 device->blitter->free_private(device);
1340 if (device->fragment_priv)
1341 device->frag_pipe->free_private(device);
1342 if (device->shader_priv)
1343 device->shader_backend->shader_free_private(device);
1345 return hr;
1348 HRESULT CDECL wined3d_device_init_gdi(struct wined3d_device *device,
1349 WINED3DPRESENT_PARAMETERS *present_parameters)
1351 struct wined3d_swapchain *swapchain = NULL;
1352 HRESULT hr;
1354 TRACE("device %p, present_parameters %p.\n", device, present_parameters);
1356 /* Setup the implicit swapchain */
1357 TRACE("Creating implicit swapchain\n");
1358 hr = device->device_parent->ops->create_swapchain(device->device_parent,
1359 present_parameters, &swapchain);
1360 if (FAILED(hr))
1362 WARN("Failed to create implicit swapchain\n");
1363 goto err_out;
1366 device->swapchain_count = 1;
1367 device->swapchains = HeapAlloc(GetProcessHeap(), 0, device->swapchain_count * sizeof(*device->swapchains));
1368 if (!device->swapchains)
1370 ERR("Out of memory!\n");
1371 goto err_out;
1373 device->swapchains[0] = swapchain;
1374 return WINED3D_OK;
1376 err_out:
1377 wined3d_swapchain_decref(swapchain);
1378 return hr;
1381 HRESULT CDECL wined3d_device_uninit_3d(struct wined3d_device *device)
1383 struct wined3d_resource *resource, *cursor;
1384 const struct wined3d_gl_info *gl_info;
1385 struct wined3d_context *context;
1386 struct wined3d_surface *surface;
1387 UINT i;
1389 TRACE("device %p.\n", device);
1391 if (!device->d3d_initialized)
1392 return WINED3DERR_INVALIDCALL;
1394 /* Force making the context current again, to verify it is still valid
1395 * (workaround for broken drivers) */
1396 context_set_current(NULL);
1397 /* I don't think that the interface guarantees that the device is destroyed from the same thread
1398 * it was created. Thus make sure a context is active for the glDelete* calls
1400 context = context_acquire(device, NULL);
1401 gl_info = context->gl_info;
1403 if (device->logo_surface)
1404 wined3d_surface_decref(device->logo_surface);
1406 /* Unload resources */
1407 LIST_FOR_EACH_ENTRY_SAFE(resource, cursor, &device->resources, struct wined3d_resource, resource_list_entry)
1409 TRACE("Unloading resource %p.\n", resource);
1411 resource->resource_ops->resource_unload(resource);
1414 TRACE("Deleting high order patches\n");
1415 for(i = 0; i < PATCHMAP_SIZE; i++) {
1416 struct list *e1, *e2;
1417 struct WineD3DRectPatch *patch;
1418 LIST_FOR_EACH_SAFE(e1, e2, &device->patches[i])
1420 patch = LIST_ENTRY(e1, struct WineD3DRectPatch, entry);
1421 wined3d_device_delete_patch(device, patch->Handle);
1425 /* Delete the mouse cursor texture */
1426 if (device->cursorTexture)
1428 ENTER_GL();
1429 glDeleteTextures(1, &device->cursorTexture);
1430 LEAVE_GL();
1431 device->cursorTexture = 0;
1434 /* Destroy the depth blt resources, they will be invalid after the reset. Also free shader
1435 * private data, it might contain opengl pointers
1437 if (device->depth_blt_texture)
1439 ENTER_GL();
1440 glDeleteTextures(1, &device->depth_blt_texture);
1441 LEAVE_GL();
1442 device->depth_blt_texture = 0;
1445 /* Release the update stateblock */
1446 if (wined3d_stateblock_decref(device->updateStateBlock))
1448 if (device->updateStateBlock != device->stateBlock)
1449 FIXME("Something's still holding the update stateblock.\n");
1451 device->updateStateBlock = NULL;
1454 struct wined3d_stateblock *stateblock = device->stateBlock;
1455 device->stateBlock = NULL;
1457 /* Release the stateblock */
1458 if (wined3d_stateblock_decref(stateblock))
1459 FIXME("Something's still holding the stateblock.\n");
1462 /* Destroy the shader backend. Note that this has to happen after all shaders are destroyed. */
1463 device->blitter->free_private(device);
1464 device->frag_pipe->free_private(device);
1465 device->shader_backend->shader_free_private(device);
1467 /* Release the buffers (with sanity checks)*/
1468 if (device->onscreen_depth_stencil)
1470 surface = device->onscreen_depth_stencil;
1471 device->onscreen_depth_stencil = NULL;
1472 wined3d_surface_decref(surface);
1475 if (device->fb.depth_stencil)
1477 surface = device->fb.depth_stencil;
1479 TRACE("Releasing depth/stencil buffer %p.\n", surface);
1481 device->fb.depth_stencil = NULL;
1482 if (wined3d_surface_decref(surface)
1483 && surface != device->auto_depth_stencil)
1484 ERR("Something is still holding a reference to depth/stencil buffer %p.\n", surface);
1487 if (device->auto_depth_stencil)
1489 surface = device->auto_depth_stencil;
1490 device->auto_depth_stencil = NULL;
1491 if (wined3d_surface_decref(surface))
1492 FIXME("Something's still holding the auto depth stencil buffer (%p).\n", surface);
1495 for (i = 1; i < gl_info->limits.buffers; ++i)
1497 wined3d_device_set_render_target(device, i, NULL, FALSE);
1500 surface = device->fb.render_targets[0];
1501 TRACE("Setting rendertarget 0 to NULL\n");
1502 device->fb.render_targets[0] = NULL;
1503 TRACE("Releasing the render target at %p\n", surface);
1504 wined3d_surface_decref(surface);
1506 context_release(context);
1508 for (i = 0; i < device->swapchain_count; ++i)
1510 TRACE("Releasing the implicit swapchain %u.\n", i);
1511 if (wined3d_swapchain_decref(device->swapchains[i]))
1512 FIXME("Something's still holding the implicit swapchain.\n");
1515 HeapFree(GetProcessHeap(), 0, device->swapchains);
1516 device->swapchains = NULL;
1517 device->swapchain_count = 0;
1519 for (i = 0; i < device->palette_count; ++i)
1520 HeapFree(GetProcessHeap(), 0, device->palettes[i]);
1521 HeapFree(GetProcessHeap(), 0, device->palettes);
1522 device->palettes = NULL;
1523 device->palette_count = 0;
1525 HeapFree(GetProcessHeap(), 0, device->fb.render_targets);
1526 device->fb.render_targets = NULL;
1528 device->d3d_initialized = FALSE;
1530 return WINED3D_OK;
1533 HRESULT CDECL wined3d_device_uninit_gdi(struct wined3d_device *device)
1535 unsigned int i;
1537 for (i = 0; i < device->swapchain_count; ++i)
1539 TRACE("Releasing the implicit swapchain %u.\n", i);
1540 if (wined3d_swapchain_decref(device->swapchains[i]))
1541 FIXME("Something's still holding the implicit swapchain.\n");
1544 HeapFree(GetProcessHeap(), 0, device->swapchains);
1545 device->swapchains = NULL;
1546 device->swapchain_count = 0;
1547 return WINED3D_OK;
1550 /* Enables thread safety in the wined3d device and its resources. Called by DirectDraw
1551 * from SetCooperativeLevel if DDSCL_MULTITHREADED is specified, and by d3d8/9 from
1552 * CreateDevice if D3DCREATE_MULTITHREADED is passed.
1554 * There is no way to deactivate thread safety once it is enabled.
1556 void CDECL wined3d_device_set_multithreaded(struct wined3d_device *device)
1558 TRACE("device %p.\n", device);
1560 /* For now just store the flag (needed in case of ddraw). */
1561 device->createParms.BehaviorFlags |= WINED3DCREATE_MULTITHREADED;
1564 HRESULT CDECL wined3d_device_set_display_mode(struct wined3d_device *device,
1565 UINT swapchain_idx, const WINED3DDISPLAYMODE *mode)
1567 const struct wined3d_format *format = wined3d_get_format(&device->adapter->gl_info, mode->Format);
1568 DEVMODEW devmode;
1569 LONG ret;
1570 RECT clip_rc;
1572 TRACE("device %p, swapchain_idx %u, mode %p (%ux%u@%u %s).\n", device, swapchain_idx, mode,
1573 mode->Width, mode->Height, mode->RefreshRate, debug_d3dformat(mode->Format));
1575 /* Resize the screen even without a window:
1576 * The app could have unset it with SetCooperativeLevel, but not called
1577 * RestoreDisplayMode first. Then the release will call RestoreDisplayMode,
1578 * but we don't have any hwnd
1581 memset(&devmode, 0, sizeof(devmode));
1582 devmode.dmSize = sizeof(devmode);
1583 devmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
1584 devmode.dmBitsPerPel = format->byte_count * CHAR_BIT;
1585 devmode.dmPelsWidth = mode->Width;
1586 devmode.dmPelsHeight = mode->Height;
1588 devmode.dmDisplayFrequency = mode->RefreshRate;
1589 if (mode->RefreshRate)
1590 devmode.dmFields |= DM_DISPLAYFREQUENCY;
1592 /* Only change the mode if necessary */
1593 if (device->ddraw_width == mode->Width && device->ddraw_height == mode->Height
1594 && device->ddraw_format == mode->Format && !mode->RefreshRate)
1595 return WINED3D_OK;
1597 ret = ChangeDisplaySettingsExW(NULL, &devmode, NULL, CDS_FULLSCREEN, NULL);
1598 if (ret != DISP_CHANGE_SUCCESSFUL)
1600 if (devmode.dmDisplayFrequency)
1602 WARN("ChangeDisplaySettingsExW failed, trying without the refresh rate\n");
1603 devmode.dmFields &= ~DM_DISPLAYFREQUENCY;
1604 devmode.dmDisplayFrequency = 0;
1605 ret = ChangeDisplaySettingsExW(NULL, &devmode, NULL, CDS_FULLSCREEN, NULL) != DISP_CHANGE_SUCCESSFUL;
1607 if(ret != DISP_CHANGE_SUCCESSFUL) {
1608 return WINED3DERR_NOTAVAILABLE;
1612 /* Store the new values */
1613 device->ddraw_width = mode->Width;
1614 device->ddraw_height = mode->Height;
1615 device->ddraw_format = mode->Format;
1617 /* And finally clip mouse to our screen */
1618 SetRect(&clip_rc, 0, 0, mode->Width, mode->Height);
1619 ClipCursor(&clip_rc);
1621 return WINED3D_OK;
1624 HRESULT CDECL wined3d_device_get_wined3d(struct wined3d_device *device, struct wined3d **wined3d)
1626 TRACE("device %p, wined3d %p.\n", device, wined3d);
1628 *wined3d = device->wined3d;
1629 wined3d_incref(*wined3d);
1631 TRACE("Returning %p.\n", *wined3d);
1633 return WINED3D_OK;
1636 UINT CDECL wined3d_device_get_available_texture_mem(struct wined3d_device *device)
1638 TRACE("device %p.\n", device);
1640 TRACE("Emulating %d MB, returning %d MB left.\n",
1641 device->adapter->TextureRam / (1024 * 1024),
1642 (device->adapter->TextureRam - device->adapter->UsedTextureRam) / (1024 * 1024));
1644 return device->adapter->TextureRam - device->adapter->UsedTextureRam;
1647 HRESULT CDECL wined3d_device_set_stream_source(struct wined3d_device *device, UINT stream_idx,
1648 struct wined3d_buffer *buffer, UINT offset, UINT stride)
1650 struct wined3d_stream_state *stream;
1651 struct wined3d_buffer *prev_buffer;
1653 TRACE("device %p, stream_idx %u, buffer %p, offset %u, stride %u.\n",
1654 device, stream_idx, buffer, offset, stride);
1656 if (stream_idx >= MAX_STREAMS)
1658 WARN("Stream index %u out of range.\n", stream_idx);
1659 return WINED3DERR_INVALIDCALL;
1661 else if (offset & 0x3)
1663 WARN("Offset %u is not 4 byte aligned.\n", offset);
1664 return WINED3DERR_INVALIDCALL;
1667 stream = &device->updateStateBlock->state.streams[stream_idx];
1668 prev_buffer = stream->buffer;
1670 device->updateStateBlock->changed.streamSource |= 1 << stream_idx;
1672 if (prev_buffer == buffer
1673 && stream->stride == stride
1674 && stream->offset == offset)
1676 TRACE("Application is setting the old values over, nothing to do.\n");
1677 return WINED3D_OK;
1680 stream->buffer = buffer;
1681 if (buffer)
1683 stream->stride = stride;
1684 stream->offset = offset;
1687 /* Handle recording of state blocks. */
1688 if (device->isRecordingState)
1690 TRACE("Recording... not performing anything.\n");
1691 if (buffer)
1692 wined3d_buffer_incref(buffer);
1693 if (prev_buffer)
1694 wined3d_buffer_decref(prev_buffer);
1695 return WINED3D_OK;
1698 if (buffer)
1700 InterlockedIncrement(&buffer->bind_count);
1701 wined3d_buffer_incref(buffer);
1703 if (prev_buffer)
1705 InterlockedDecrement(&prev_buffer->bind_count);
1706 wined3d_buffer_decref(prev_buffer);
1709 device_invalidate_state(device, STATE_STREAMSRC);
1711 return WINED3D_OK;
1714 HRESULT CDECL wined3d_device_get_stream_source(struct wined3d_device *device,
1715 UINT stream_idx, struct wined3d_buffer **buffer, UINT *offset, UINT *stride)
1717 struct wined3d_stream_state *stream;
1719 TRACE("device %p, stream_idx %u, buffer %p, offset %p, stride %p.\n",
1720 device, stream_idx, buffer, offset, stride);
1722 if (stream_idx >= MAX_STREAMS)
1724 WARN("Stream index %u out of range.\n", stream_idx);
1725 return WINED3DERR_INVALIDCALL;
1728 stream = &device->stateBlock->state.streams[stream_idx];
1729 *buffer = stream->buffer;
1730 if (*buffer)
1731 wined3d_buffer_incref(*buffer);
1732 if (offset)
1733 *offset = stream->offset;
1734 *stride = stream->stride;
1736 return WINED3D_OK;
1739 HRESULT CDECL wined3d_device_set_stream_source_freq(struct wined3d_device *device, UINT stream_idx, UINT divider)
1741 struct wined3d_stream_state *stream;
1742 UINT old_flags, old_freq;
1744 TRACE("device %p, stream_idx %u, divider %#x.\n", device, stream_idx, divider);
1746 /* Verify input. At least in d3d9 this is invalid. */
1747 if ((divider & WINED3DSTREAMSOURCE_INSTANCEDATA) && (divider & WINED3DSTREAMSOURCE_INDEXEDDATA))
1749 WARN("INSTANCEDATA and INDEXEDDATA were set, returning D3DERR_INVALIDCALL.\n");
1750 return WINED3DERR_INVALIDCALL;
1752 if ((divider & WINED3DSTREAMSOURCE_INSTANCEDATA) && !stream_idx)
1754 WARN("INSTANCEDATA used on stream 0, returning D3DERR_INVALIDCALL.\n");
1755 return WINED3DERR_INVALIDCALL;
1757 if (!divider)
1759 WARN("Divider is 0, returning D3DERR_INVALIDCALL.\n");
1760 return WINED3DERR_INVALIDCALL;
1763 stream = &device->updateStateBlock->state.streams[stream_idx];
1764 old_flags = stream->flags;
1765 old_freq = stream->frequency;
1767 stream->flags = divider & (WINED3DSTREAMSOURCE_INSTANCEDATA | WINED3DSTREAMSOURCE_INDEXEDDATA);
1768 stream->frequency = divider & 0x7fffff;
1770 device->updateStateBlock->changed.streamFreq |= 1 << stream_idx;
1772 if (stream->frequency != old_freq || stream->flags != old_flags)
1773 device_invalidate_state(device, STATE_STREAMSRC);
1775 return WINED3D_OK;
1778 HRESULT CDECL wined3d_device_get_stream_source_freq(struct wined3d_device *device, UINT stream_idx, UINT *divider)
1780 struct wined3d_stream_state *stream;
1782 TRACE("device %p, stream_idx %u, divider %p.\n", device, stream_idx, divider);
1784 stream = &device->updateStateBlock->state.streams[stream_idx];
1785 *divider = stream->flags | stream->frequency;
1787 TRACE("Returning %#x.\n", *divider);
1789 return WINED3D_OK;
1792 HRESULT CDECL wined3d_device_set_transform(struct wined3d_device *device,
1793 WINED3DTRANSFORMSTATETYPE d3dts, const WINED3DMATRIX *matrix)
1795 TRACE("device %p, state %s, matrix %p.\n",
1796 device, debug_d3dtstype(d3dts), matrix);
1798 /* Handle recording of state blocks. */
1799 if (device->isRecordingState)
1801 TRACE("Recording... not performing anything.\n");
1802 device->updateStateBlock->changed.transform[d3dts >> 5] |= 1 << (d3dts & 0x1f);
1803 device->updateStateBlock->state.transforms[d3dts] = *matrix;
1804 return WINED3D_OK;
1807 /* If the new matrix is the same as the current one,
1808 * we cut off any further processing. this seems to be a reasonable
1809 * optimization because as was noticed, some apps (warcraft3 for example)
1810 * tend towards setting the same matrix repeatedly for some reason.
1812 * From here on we assume that the new matrix is different, wherever it matters. */
1813 if (!memcmp(&device->stateBlock->state.transforms[d3dts].u.m[0][0], matrix, sizeof(*matrix)))
1815 TRACE("The application is setting the same matrix over again.\n");
1816 return WINED3D_OK;
1819 conv_mat(matrix, &device->stateBlock->state.transforms[d3dts].u.m[0][0]);
1821 /* ScreenCoord = ProjectionMat * ViewMat * WorldMat * ObjectCoord
1822 * where ViewMat = Camera space, WorldMat = world space.
1824 * In OpenGL, camera and world space is combined into GL_MODELVIEW
1825 * matrix. The Projection matrix stay projection matrix. */
1827 if (d3dts == WINED3DTS_VIEW)
1828 device->view_ident = !memcmp(matrix, identity, 16 * sizeof(float));
1830 if (d3dts < WINED3DTS_WORLDMATRIX(device->adapter->gl_info.limits.blends))
1831 device_invalidate_state(device, STATE_TRANSFORM(d3dts));
1833 return WINED3D_OK;
1837 HRESULT CDECL wined3d_device_get_transform(struct wined3d_device *device,
1838 WINED3DTRANSFORMSTATETYPE state, WINED3DMATRIX *matrix)
1840 TRACE("device %p, state %s, matrix %p.\n", device, debug_d3dtstype(state), matrix);
1842 *matrix = device->stateBlock->state.transforms[state];
1844 return WINED3D_OK;
1847 HRESULT CDECL wined3d_device_multiply_transform(struct wined3d_device *device,
1848 WINED3DTRANSFORMSTATETYPE state, const WINED3DMATRIX *matrix)
1850 const WINED3DMATRIX *mat = NULL;
1851 WINED3DMATRIX temp;
1853 TRACE("device %p, state %s, matrix %p.\n", device, debug_d3dtstype(state), matrix);
1855 /* Note: Using 'updateStateBlock' rather than 'stateblock' in the code
1856 * below means it will be recorded in a state block change, but it
1857 * works regardless where it is recorded.
1858 * If this is found to be wrong, change to StateBlock. */
1859 if (state > HIGHEST_TRANSFORMSTATE)
1861 WARN("Unhandled transform state %#x.\n", state);
1862 return WINED3D_OK;
1865 mat = &device->updateStateBlock->state.transforms[state];
1866 multiply_matrix(&temp, mat, matrix);
1868 /* Apply change via set transform - will reapply to eg. lights this way. */
1869 return wined3d_device_set_transform(device, state, &temp);
1872 /* Note lights are real special cases. Although the device caps state only
1873 * e.g. 8 are supported, you can reference any indexes you want as long as
1874 * that number max are enabled at any one point in time. Therefore since the
1875 * indices can be anything, we need a hashmap of them. However, this causes
1876 * stateblock problems. When capturing the state block, I duplicate the
1877 * hashmap, but when recording, just build a chain pretty much of commands to
1878 * be replayed. */
1879 HRESULT CDECL wined3d_device_set_light(struct wined3d_device *device, UINT light_idx, const WINED3DLIGHT *light)
1881 UINT hash_idx = LIGHTMAP_HASHFUNC(light_idx);
1882 struct wined3d_light_info *object = NULL;
1883 struct list *e;
1884 float rho;
1886 TRACE("device %p, light_idx %u, light %p.\n", device, light_idx, light);
1888 /* Check the parameter range. Need for speed most wanted sets junk lights
1889 * which confuse the GL driver. */
1890 if (!light)
1891 return WINED3DERR_INVALIDCALL;
1893 switch (light->Type)
1895 case WINED3DLIGHT_POINT:
1896 case WINED3DLIGHT_SPOT:
1897 case WINED3DLIGHT_PARALLELPOINT:
1898 case WINED3DLIGHT_GLSPOT:
1899 /* Incorrect attenuation values can cause the gl driver to crash.
1900 * Happens with Need for speed most wanted. */
1901 if (light->Attenuation0 < 0.0f || light->Attenuation1 < 0.0f || light->Attenuation2 < 0.0f)
1903 WARN("Attenuation is negative, returning WINED3DERR_INVALIDCALL.\n");
1904 return WINED3DERR_INVALIDCALL;
1906 break;
1908 case WINED3DLIGHT_DIRECTIONAL:
1909 /* Ignores attenuation */
1910 break;
1912 default:
1913 WARN("Light type out of range, returning WINED3DERR_INVALIDCALL\n");
1914 return WINED3DERR_INVALIDCALL;
1917 LIST_FOR_EACH(e, &device->updateStateBlock->state.light_map[hash_idx])
1919 object = LIST_ENTRY(e, struct wined3d_light_info, entry);
1920 if (object->OriginalIndex == light_idx)
1921 break;
1922 object = NULL;
1925 if (!object)
1927 TRACE("Adding new light\n");
1928 object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
1929 if (!object)
1931 ERR("Out of memory error when allocating a light\n");
1932 return E_OUTOFMEMORY;
1934 list_add_head(&device->updateStateBlock->state.light_map[hash_idx], &object->entry);
1935 object->glIndex = -1;
1936 object->OriginalIndex = light_idx;
1939 /* Initialize the object. */
1940 TRACE("Light %d setting to type %d, Diffuse(%f,%f,%f,%f), Specular(%f,%f,%f,%f), Ambient(%f,%f,%f,%f)\n",
1941 light_idx, light->Type,
1942 light->Diffuse.r, light->Diffuse.g, light->Diffuse.b, light->Diffuse.a,
1943 light->Specular.r, light->Specular.g, light->Specular.b, light->Specular.a,
1944 light->Ambient.r, light->Ambient.g, light->Ambient.b, light->Ambient.a);
1945 TRACE("... Pos(%f,%f,%f), Dir(%f,%f,%f)\n", light->Position.x, light->Position.y, light->Position.z,
1946 light->Direction.x, light->Direction.y, light->Direction.z);
1947 TRACE("... Range(%f), Falloff(%f), Theta(%f), Phi(%f)\n",
1948 light->Range, light->Falloff, light->Theta, light->Phi);
1950 /* Save away the information. */
1951 object->OriginalParms = *light;
1953 switch (light->Type)
1955 case WINED3DLIGHT_POINT:
1956 /* Position */
1957 object->lightPosn[0] = light->Position.x;
1958 object->lightPosn[1] = light->Position.y;
1959 object->lightPosn[2] = light->Position.z;
1960 object->lightPosn[3] = 1.0f;
1961 object->cutoff = 180.0f;
1962 /* FIXME: Range */
1963 break;
1965 case WINED3DLIGHT_DIRECTIONAL:
1966 /* Direction */
1967 object->lightPosn[0] = -light->Direction.x;
1968 object->lightPosn[1] = -light->Direction.y;
1969 object->lightPosn[2] = -light->Direction.z;
1970 object->lightPosn[3] = 0.0f;
1971 object->exponent = 0.0f;
1972 object->cutoff = 180.0f;
1973 break;
1975 case WINED3DLIGHT_SPOT:
1976 /* Position */
1977 object->lightPosn[0] = light->Position.x;
1978 object->lightPosn[1] = light->Position.y;
1979 object->lightPosn[2] = light->Position.z;
1980 object->lightPosn[3] = 1.0f;
1982 /* Direction */
1983 object->lightDirn[0] = light->Direction.x;
1984 object->lightDirn[1] = light->Direction.y;
1985 object->lightDirn[2] = light->Direction.z;
1986 object->lightDirn[3] = 1.0f;
1988 /* opengl-ish and d3d-ish spot lights use too different models
1989 * for the light "intensity" as a function of the angle towards
1990 * the main light direction, so we only can approximate very
1991 * roughly. However, spot lights are rather rarely used in games
1992 * (if ever used at all). Furthermore if still used, probably
1993 * nobody pays attention to such details. */
1994 if (!light->Falloff)
1996 /* Falloff = 0 is easy, because d3d's and opengl's spot light
1997 * equations have the falloff resp. exponent parameter as an
1998 * exponent, so the spot light lighting will always be 1.0 for
1999 * both of them, and we don't have to care for the rest of the
2000 * rather complex calculation. */
2001 object->exponent = 0.0f;
2003 else
2005 rho = light->Theta + (light->Phi - light->Theta) / (2 * light->Falloff);
2006 if (rho < 0.0001f)
2007 rho = 0.0001f;
2008 object->exponent = -0.3f / logf(cosf(rho / 2));
2011 if (object->exponent > 128.0f)
2012 object->exponent = 128.0f;
2014 object->cutoff = (float)(light->Phi * 90 / M_PI);
2015 /* FIXME: Range */
2016 break;
2018 default:
2019 FIXME("Unrecognized light type %#x.\n", light->Type);
2022 /* Update the live definitions if the light is currently assigned a glIndex. */
2023 if (object->glIndex != -1 && !device->isRecordingState)
2024 device_invalidate_state(device, STATE_ACTIVELIGHT(object->glIndex));
2026 return WINED3D_OK;
2029 HRESULT CDECL wined3d_device_get_light(struct wined3d_device *device, UINT light_idx, WINED3DLIGHT *light)
2031 UINT hash_idx = LIGHTMAP_HASHFUNC(light_idx);
2032 struct wined3d_light_info *light_info = NULL;
2033 struct list *e;
2035 TRACE("device %p, light_idx %u, light %p.\n", device, light_idx, light);
2037 LIST_FOR_EACH(e, &device->stateBlock->state.light_map[hash_idx])
2039 light_info = LIST_ENTRY(e, struct wined3d_light_info, entry);
2040 if (light_info->OriginalIndex == light_idx)
2041 break;
2042 light_info = NULL;
2045 if (!light_info)
2047 TRACE("Light information requested but light not defined\n");
2048 return WINED3DERR_INVALIDCALL;
2051 *light = light_info->OriginalParms;
2052 return WINED3D_OK;
2055 HRESULT CDECL wined3d_device_set_light_enable(struct wined3d_device *device, UINT light_idx, BOOL enable)
2057 UINT hash_idx = LIGHTMAP_HASHFUNC(light_idx);
2058 struct wined3d_light_info *light_info = NULL;
2059 struct list *e;
2061 TRACE("device %p, light_idx %u, enable %#x.\n", device, light_idx, enable);
2063 LIST_FOR_EACH(e, &device->updateStateBlock->state.light_map[hash_idx])
2065 light_info = LIST_ENTRY(e, struct wined3d_light_info, entry);
2066 if (light_info->OriginalIndex == light_idx)
2067 break;
2068 light_info = NULL;
2070 TRACE("Found light %p.\n", light_info);
2072 /* Special case - enabling an undefined light creates one with a strict set of parameters. */
2073 if (!light_info)
2075 TRACE("Light enabled requested but light not defined, so defining one!\n");
2076 wined3d_device_set_light(device, light_idx, &WINED3D_default_light);
2078 /* Search for it again! Should be fairly quick as near head of list. */
2079 LIST_FOR_EACH(e, &device->updateStateBlock->state.light_map[hash_idx])
2081 light_info = LIST_ENTRY(e, struct wined3d_light_info, entry);
2082 if (light_info->OriginalIndex == light_idx)
2083 break;
2084 light_info = NULL;
2086 if (!light_info)
2088 FIXME("Adding default lights has failed dismally\n");
2089 return WINED3DERR_INVALIDCALL;
2093 if (!enable)
2095 if (light_info->glIndex != -1)
2097 if (!device->isRecordingState)
2098 device_invalidate_state(device, STATE_ACTIVELIGHT(light_info->glIndex));
2100 device->updateStateBlock->state.lights[light_info->glIndex] = NULL;
2101 light_info->glIndex = -1;
2103 else
2105 TRACE("Light already disabled, nothing to do\n");
2107 light_info->enabled = FALSE;
2109 else
2111 light_info->enabled = TRUE;
2112 if (light_info->glIndex != -1)
2114 TRACE("Nothing to do as light was enabled\n");
2116 else
2118 unsigned int i;
2119 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
2120 /* Find a free GL light. */
2121 for (i = 0; i < gl_info->limits.lights; ++i)
2123 if (!device->updateStateBlock->state.lights[i])
2125 device->updateStateBlock->state.lights[i] = light_info;
2126 light_info->glIndex = i;
2127 break;
2130 if (light_info->glIndex == -1)
2132 /* Our tests show that Windows returns D3D_OK in this situation, even with
2133 * D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_PUREDEVICE devices. This
2134 * is consistent among ddraw, d3d8 and d3d9. GetLightEnable returns TRUE
2135 * as well for those lights.
2137 * TODO: Test how this affects rendering. */
2138 WARN("Too many concurrently active lights\n");
2139 return WINED3D_OK;
2142 /* i == light_info->glIndex */
2143 if (!device->isRecordingState)
2144 device_invalidate_state(device, STATE_ACTIVELIGHT(i));
2148 return WINED3D_OK;
2151 HRESULT CDECL wined3d_device_get_light_enable(struct wined3d_device *device, UINT light_idx, BOOL *enable)
2153 UINT hash_idx = LIGHTMAP_HASHFUNC(light_idx);
2154 struct wined3d_light_info *light_info = NULL;
2155 struct list *e;
2157 TRACE("device %p, light_idx %u, enable %p.\n", device, light_idx, enable);
2159 LIST_FOR_EACH(e, &device->stateBlock->state.light_map[hash_idx])
2161 light_info = LIST_ENTRY(e, struct wined3d_light_info, entry);
2162 if (light_info->OriginalIndex == light_idx)
2163 break;
2164 light_info = NULL;
2167 if (!light_info)
2169 TRACE("Light enabled state requested but light not defined.\n");
2170 return WINED3DERR_INVALIDCALL;
2172 /* true is 128 according to SetLightEnable */
2173 *enable = light_info->enabled ? 128 : 0;
2174 return WINED3D_OK;
2177 HRESULT CDECL wined3d_device_set_clip_plane(struct wined3d_device *device, UINT plane_idx, const float *plane)
2179 TRACE("device %p, plane_idx %u, plane %p.\n", device, plane_idx, plane);
2181 /* Validate plane_idx. */
2182 if (plane_idx >= device->adapter->gl_info.limits.clipplanes)
2184 TRACE("Application has requested clipplane this device doesn't support.\n");
2185 return WINED3DERR_INVALIDCALL;
2188 device->updateStateBlock->changed.clipplane |= 1 << plane_idx;
2190 if (device->updateStateBlock->state.clip_planes[plane_idx][0] == plane[0]
2191 && device->updateStateBlock->state.clip_planes[plane_idx][1] == plane[1]
2192 && device->updateStateBlock->state.clip_planes[plane_idx][2] == plane[2]
2193 && device->updateStateBlock->state.clip_planes[plane_idx][3] == plane[3])
2195 TRACE("Application is setting old values over, nothing to do.\n");
2196 return WINED3D_OK;
2199 device->updateStateBlock->state.clip_planes[plane_idx][0] = plane[0];
2200 device->updateStateBlock->state.clip_planes[plane_idx][1] = plane[1];
2201 device->updateStateBlock->state.clip_planes[plane_idx][2] = plane[2];
2202 device->updateStateBlock->state.clip_planes[plane_idx][3] = plane[3];
2204 /* Handle recording of state blocks. */
2205 if (device->isRecordingState)
2207 TRACE("Recording... not performing anything.\n");
2208 return WINED3D_OK;
2211 device_invalidate_state(device, STATE_CLIPPLANE(plane_idx));
2213 return WINED3D_OK;
2216 HRESULT CDECL wined3d_device_get_clip_plane(struct wined3d_device *device, UINT plane_idx, float *plane)
2218 TRACE("device %p, plane_idx %u, plane %p.\n", device, plane_idx, plane);
2220 /* Validate plane_idx. */
2221 if (plane_idx >= device->adapter->gl_info.limits.clipplanes)
2223 TRACE("Application has requested clipplane this device doesn't support.\n");
2224 return WINED3DERR_INVALIDCALL;
2227 plane[0] = (float)device->stateBlock->state.clip_planes[plane_idx][0];
2228 plane[1] = (float)device->stateBlock->state.clip_planes[plane_idx][1];
2229 plane[2] = (float)device->stateBlock->state.clip_planes[plane_idx][2];
2230 plane[3] = (float)device->stateBlock->state.clip_planes[plane_idx][3];
2232 return WINED3D_OK;
2235 HRESULT CDECL wined3d_device_set_clip_status(struct wined3d_device *device, const WINED3DCLIPSTATUS *clip_status)
2237 FIXME("device %p, clip_status %p stub!\n", device, clip_status);
2239 if (!clip_status)
2240 return WINED3DERR_INVALIDCALL;
2242 return WINED3D_OK;
2245 HRESULT CDECL wined3d_device_get_clip_status(struct wined3d_device *device, WINED3DCLIPSTATUS *clip_status)
2247 FIXME("device %p, clip_status %p stub!\n", device, clip_status);
2249 if (!clip_status)
2250 return WINED3DERR_INVALIDCALL;
2252 return WINED3D_OK;
2255 HRESULT CDECL wined3d_device_set_material(struct wined3d_device *device, const WINED3DMATERIAL *material)
2257 TRACE("device %p, material %p.\n", device, material);
2259 device->updateStateBlock->changed.material = TRUE;
2260 device->updateStateBlock->state.material = *material;
2262 /* Handle recording of state blocks */
2263 if (device->isRecordingState)
2265 TRACE("Recording... not performing anything.\n");
2266 return WINED3D_OK;
2269 device_invalidate_state(device, STATE_MATERIAL);
2271 return WINED3D_OK;
2274 HRESULT CDECL wined3d_device_get_material(struct wined3d_device *device, WINED3DMATERIAL *material)
2276 TRACE("device %p, material %p.\n", device, material);
2278 *material = device->updateStateBlock->state.material;
2280 TRACE("Diffuse {%.8e, %.8e, %.8e, %.8e}\n",
2281 material->Diffuse.r, material->Diffuse.g,
2282 material->Diffuse.b, material->Diffuse.a);
2283 TRACE("Ambient {%.8e, %.8e, %.8e, %.8e}\n",
2284 material->Ambient.r, material->Ambient.g,
2285 material->Ambient.b, material->Ambient.a);
2286 TRACE("Specular {%.8e, %.8e, %.8e, %.8e}\n",
2287 material->Specular.r, material->Specular.g,
2288 material->Specular.b, material->Specular.a);
2289 TRACE("Emissive {%.8e, %.8e, %.8e, %.8e}\n",
2290 material->Emissive.r, material->Emissive.g,
2291 material->Emissive.b, material->Emissive.a);
2292 TRACE("Power %.8e.\n", material->Power);
2294 return WINED3D_OK;
2297 HRESULT CDECL wined3d_device_set_index_buffer(struct wined3d_device *device,
2298 struct wined3d_buffer *buffer, enum wined3d_format_id format_id)
2300 struct wined3d_buffer *prev_buffer;
2302 TRACE("device %p, buffer %p, format %s.\n",
2303 device, buffer, debug_d3dformat(format_id));
2305 prev_buffer = device->updateStateBlock->state.index_buffer;
2307 device->updateStateBlock->changed.indices = TRUE;
2308 device->updateStateBlock->state.index_buffer = buffer;
2309 device->updateStateBlock->state.index_format = format_id;
2311 /* Handle recording of state blocks. */
2312 if (device->isRecordingState)
2314 TRACE("Recording... not performing anything.\n");
2315 if (buffer)
2316 wined3d_buffer_incref(buffer);
2317 if (prev_buffer)
2318 wined3d_buffer_decref(prev_buffer);
2319 return WINED3D_OK;
2322 if (prev_buffer != buffer)
2324 device_invalidate_state(device, STATE_INDEXBUFFER);
2325 if (buffer)
2327 InterlockedIncrement(&buffer->bind_count);
2328 wined3d_buffer_incref(buffer);
2330 if (prev_buffer)
2332 InterlockedDecrement(&prev_buffer->bind_count);
2333 wined3d_buffer_decref(prev_buffer);
2337 return WINED3D_OK;
2340 HRESULT CDECL wined3d_device_get_index_buffer(struct wined3d_device *device, struct wined3d_buffer **buffer)
2342 TRACE("device %p, buffer %p.\n", device, buffer);
2344 *buffer = device->stateBlock->state.index_buffer;
2346 if (*buffer)
2347 wined3d_buffer_incref(*buffer);
2349 TRACE("Returning %p.\n", *buffer);
2351 return WINED3D_OK;
2354 /* Method to offer d3d9 a simple way to set the base vertex index without messing with the index buffer */
2355 HRESULT CDECL wined3d_device_set_base_vertex_index(struct wined3d_device *device, INT base_index)
2357 TRACE("device %p, base_index %d.\n", device, base_index);
2359 if (device->updateStateBlock->state.base_vertex_index == base_index)
2361 TRACE("Application is setting the old value over, nothing to do\n");
2362 return WINED3D_OK;
2365 device->updateStateBlock->state.base_vertex_index = base_index;
2367 if (device->isRecordingState)
2369 TRACE("Recording... not performing anything\n");
2370 return WINED3D_OK;
2372 return WINED3D_OK;
2375 INT CDECL wined3d_device_get_base_vertex_index(struct wined3d_device *device)
2377 TRACE("device %p.\n", device);
2379 return device->stateBlock->state.base_vertex_index;
2382 HRESULT CDECL wined3d_device_set_viewport(struct wined3d_device *device, const WINED3DVIEWPORT *viewport)
2384 TRACE("device %p, viewport %p.\n", device, viewport);
2385 TRACE("x %u, y %u, w %u, h %u, minz %.8e, maxz %.8e.\n",
2386 viewport->X, viewport->Y, viewport->Width, viewport->Height, viewport->MinZ, viewport->MaxZ);
2388 device->updateStateBlock->changed.viewport = TRUE;
2389 device->updateStateBlock->state.viewport = *viewport;
2391 /* Handle recording of state blocks */
2392 if (device->isRecordingState)
2394 TRACE("Recording... not performing anything\n");
2395 return WINED3D_OK;
2398 device_invalidate_state(device, STATE_VIEWPORT);
2400 return WINED3D_OK;
2403 HRESULT CDECL wined3d_device_get_viewport(struct wined3d_device *device, WINED3DVIEWPORT *viewport)
2405 TRACE("device %p, viewport %p.\n", device, viewport);
2407 *viewport = device->stateBlock->state.viewport;
2409 return WINED3D_OK;
2412 HRESULT CDECL wined3d_device_set_render_state(struct wined3d_device *device,
2413 WINED3DRENDERSTATETYPE state, DWORD value)
2415 DWORD old_value = device->stateBlock->state.render_states[state];
2417 TRACE("device %p, state %s (%#x), value %#x.\n", device, debug_d3drenderstate(state), state, value);
2419 device->updateStateBlock->changed.renderState[state >> 5] |= 1 << (state & 0x1f);
2420 device->updateStateBlock->state.render_states[state] = value;
2422 /* Handle recording of state blocks. */
2423 if (device->isRecordingState)
2425 TRACE("Recording... not performing anything.\n");
2426 return WINED3D_OK;
2429 /* Compared here and not before the assignment to allow proper stateblock recording. */
2430 if (value == old_value)
2431 TRACE("Application is setting the old value over, nothing to do.\n");
2432 else
2433 device_invalidate_state(device, STATE_RENDER(state));
2435 return WINED3D_OK;
2438 HRESULT CDECL wined3d_device_get_render_state(struct wined3d_device *device,
2439 WINED3DRENDERSTATETYPE state, DWORD *value)
2441 TRACE("device %p, state %s (%#x), value %p.\n", device, debug_d3drenderstate(state), state, value);
2443 *value = device->stateBlock->state.render_states[state];
2445 return WINED3D_OK;
2448 HRESULT CDECL wined3d_device_set_sampler_state(struct wined3d_device *device,
2449 UINT sampler_idx, WINED3DSAMPLERSTATETYPE state, DWORD value)
2451 DWORD old_value;
2453 TRACE("device %p, sampler_idx %u, state %s, value %#x.\n",
2454 device, sampler_idx, debug_d3dsamplerstate(state), value);
2456 if (sampler_idx >= WINED3DVERTEXTEXTURESAMPLER0 && sampler_idx <= WINED3DVERTEXTEXTURESAMPLER3)
2457 sampler_idx -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
2459 if (sampler_idx >= sizeof(device->stateBlock->state.sampler_states)
2460 / sizeof(*device->stateBlock->state.sampler_states))
2462 WARN("Invalid sampler %u.\n", sampler_idx);
2463 return WINED3D_OK; /* Windows accepts overflowing this array ... we do not. */
2466 old_value = device->stateBlock->state.sampler_states[sampler_idx][state];
2467 device->updateStateBlock->state.sampler_states[sampler_idx][state] = value;
2468 device->updateStateBlock->changed.samplerState[sampler_idx] |= 1 << state;
2470 /* Handle recording of state blocks. */
2471 if (device->isRecordingState)
2473 TRACE("Recording... not performing anything.\n");
2474 return WINED3D_OK;
2477 if (old_value == value)
2479 TRACE("Application is setting the old value over, nothing to do.\n");
2480 return WINED3D_OK;
2483 device_invalidate_state(device, STATE_SAMPLER(sampler_idx));
2485 return WINED3D_OK;
2488 HRESULT CDECL wined3d_device_get_sampler_state(struct wined3d_device *device,
2489 UINT sampler_idx, WINED3DSAMPLERSTATETYPE state, DWORD *value)
2491 TRACE("device %p, sampler_idx %u, state %s, value %p.\n",
2492 device, sampler_idx, debug_d3dsamplerstate(state), value);
2494 if (sampler_idx >= WINED3DVERTEXTEXTURESAMPLER0 && sampler_idx <= WINED3DVERTEXTEXTURESAMPLER3)
2495 sampler_idx -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
2497 if (sampler_idx >= sizeof(device->stateBlock->state.sampler_states)
2498 / sizeof(*device->stateBlock->state.sampler_states))
2500 WARN("Invalid sampler %u.\n", sampler_idx);
2501 return WINED3D_OK; /* Windows accepts overflowing this array ... we do not. */
2504 *value = device->stateBlock->state.sampler_states[sampler_idx][state];
2505 TRACE("Returning %#x.\n", *value);
2507 return WINED3D_OK;
2510 HRESULT CDECL wined3d_device_set_scissor_rect(struct wined3d_device *device, const RECT *rect)
2512 TRACE("device %p, rect %s.\n", device, wine_dbgstr_rect(rect));
2514 device->updateStateBlock->changed.scissorRect = TRUE;
2515 if (EqualRect(&device->updateStateBlock->state.scissor_rect, rect))
2517 TRACE("App is setting the old scissor rectangle over, nothing to do.\n");
2518 return WINED3D_OK;
2520 CopyRect(&device->updateStateBlock->state.scissor_rect, rect);
2522 if (device->isRecordingState)
2524 TRACE("Recording... not performing anything.\n");
2525 return WINED3D_OK;
2528 device_invalidate_state(device, STATE_SCISSORRECT);
2530 return WINED3D_OK;
2533 HRESULT CDECL wined3d_device_get_scissor_rect(struct wined3d_device *device, RECT *rect)
2535 TRACE("device %p, rect %p.\n", device, rect);
2537 *rect = device->updateStateBlock->state.scissor_rect;
2538 TRACE("Returning rect %s.\n", wine_dbgstr_rect(rect));
2540 return WINED3D_OK;
2543 HRESULT CDECL wined3d_device_set_vertex_declaration(struct wined3d_device *device,
2544 struct wined3d_vertex_declaration *declaration)
2546 struct wined3d_vertex_declaration *prev = device->updateStateBlock->state.vertex_declaration;
2548 TRACE("device %p, declaration %p.\n", device, declaration);
2550 if (declaration)
2551 wined3d_vertex_declaration_incref(declaration);
2552 if (prev)
2553 wined3d_vertex_declaration_decref(prev);
2555 device->updateStateBlock->state.vertex_declaration = declaration;
2556 device->updateStateBlock->changed.vertexDecl = TRUE;
2558 if (device->isRecordingState)
2560 TRACE("Recording... not performing anything.\n");
2561 return WINED3D_OK;
2563 else if (declaration == prev)
2565 /* Checked after the assignment to allow proper stateblock recording. */
2566 TRACE("Application is setting the old declaration over, nothing to do.\n");
2567 return WINED3D_OK;
2570 device_invalidate_state(device, STATE_VDECL);
2571 return WINED3D_OK;
2574 HRESULT CDECL wined3d_device_get_vertex_declaration(struct wined3d_device *device,
2575 struct wined3d_vertex_declaration **declaration)
2577 TRACE("device %p, declaration %p.\n", device, declaration);
2579 *declaration = device->stateBlock->state.vertex_declaration;
2580 if (*declaration)
2581 wined3d_vertex_declaration_incref(*declaration);
2583 return WINED3D_OK;
2586 HRESULT CDECL wined3d_device_set_vertex_shader(struct wined3d_device *device, struct wined3d_shader *shader)
2588 struct wined3d_shader *prev = device->updateStateBlock->state.vertex_shader;
2590 TRACE("device %p, shader %p.\n", device, shader);
2592 device->updateStateBlock->state.vertex_shader = shader;
2593 device->updateStateBlock->changed.vertexShader = TRUE;
2595 if (device->isRecordingState)
2597 if (shader)
2598 wined3d_shader_incref(shader);
2599 if (prev)
2600 wined3d_shader_decref(prev);
2601 TRACE("Recording... not performing anything.\n");
2602 return WINED3D_OK;
2605 if (shader == prev)
2607 TRACE("Application is setting the old shader over, nothing to do.\n");
2608 return WINED3D_OK;
2611 if (shader)
2612 wined3d_shader_incref(shader);
2613 if (prev)
2614 wined3d_shader_decref(prev);
2616 device_invalidate_state(device, STATE_VSHADER);
2618 return WINED3D_OK;
2621 struct wined3d_shader * CDECL wined3d_device_get_vertex_shader(struct wined3d_device *device)
2623 struct wined3d_shader *shader;
2625 TRACE("device %p.\n", device);
2627 shader = device->stateBlock->state.vertex_shader;
2628 if (shader)
2629 wined3d_shader_incref(shader);
2631 TRACE("Returning %p.\n", shader);
2632 return shader;
2635 HRESULT CDECL wined3d_device_set_vs_consts_b(struct wined3d_device *device,
2636 UINT start_register, const BOOL *constants, UINT bool_count)
2638 UINT count = min(bool_count, MAX_CONST_B - start_register);
2639 UINT i;
2641 TRACE("device %p, start_register %u, constants %p, bool_count %u.\n",
2642 device, start_register, constants, bool_count);
2644 if (!constants || start_register >= MAX_CONST_B)
2645 return WINED3DERR_INVALIDCALL;
2647 memcpy(&device->updateStateBlock->state.vs_consts_b[start_register], constants, count * sizeof(BOOL));
2648 for (i = 0; i < count; ++i)
2649 TRACE("Set BOOL constant %u to %s.\n", start_register + i, constants[i] ? "true" : "false");
2651 for (i = start_register; i < count + start_register; ++i)
2652 device->updateStateBlock->changed.vertexShaderConstantsB |= (1 << i);
2654 if (!device->isRecordingState)
2655 device_invalidate_state(device, STATE_VERTEXSHADERCONSTANT);
2657 return WINED3D_OK;
2660 HRESULT CDECL wined3d_device_get_vs_consts_b(struct wined3d_device *device,
2661 UINT start_register, BOOL *constants, UINT bool_count)
2663 UINT count = min(bool_count, MAX_CONST_B - start_register);
2665 TRACE("device %p, start_register %u, constants %p, bool_count %u.\n",
2666 device, start_register, constants, bool_count);
2668 if (!constants || start_register >= MAX_CONST_B)
2669 return WINED3DERR_INVALIDCALL;
2671 memcpy(constants, &device->stateBlock->state.vs_consts_b[start_register], count * sizeof(BOOL));
2673 return WINED3D_OK;
2676 HRESULT CDECL wined3d_device_set_vs_consts_i(struct wined3d_device *device,
2677 UINT start_register, const int *constants, UINT vector4i_count)
2679 UINT count = min(vector4i_count, MAX_CONST_I - start_register);
2680 UINT i;
2682 TRACE("device %p, start_register %u, constants %p, vector4i_count %u.\n",
2683 device, start_register, constants, vector4i_count);
2685 if (!constants || start_register >= MAX_CONST_I)
2686 return WINED3DERR_INVALIDCALL;
2688 memcpy(&device->updateStateBlock->state.vs_consts_i[start_register * 4], constants, count * sizeof(int) * 4);
2689 for (i = 0; i < count; ++i)
2690 TRACE("Set INT constant %u to {%d, %d, %d, %d}.\n", start_register + i,
2691 constants[i * 4], constants[i * 4 + 1],
2692 constants[i * 4 + 2], constants[i * 4 + 3]);
2694 for (i = start_register; i < count + start_register; ++i)
2695 device->updateStateBlock->changed.vertexShaderConstantsI |= (1 << i);
2697 if (!device->isRecordingState)
2698 device_invalidate_state(device, STATE_VERTEXSHADERCONSTANT);
2700 return WINED3D_OK;
2703 HRESULT CDECL wined3d_device_get_vs_consts_i(struct wined3d_device *device,
2704 UINT start_register, int *constants, UINT vector4i_count)
2706 UINT count = min(vector4i_count, MAX_CONST_I - start_register);
2708 TRACE("device %p, start_register %u, constants %p, vector4i_count %u.\n",
2709 device, start_register, constants, vector4i_count);
2711 if (!constants || start_register >= MAX_CONST_I)
2712 return WINED3DERR_INVALIDCALL;
2714 memcpy(constants, &device->stateBlock->state.vs_consts_i[start_register * 4], count * sizeof(int) * 4);
2715 return WINED3D_OK;
2718 HRESULT CDECL wined3d_device_set_vs_consts_f(struct wined3d_device *device,
2719 UINT start_register, const float *constants, UINT vector4f_count)
2721 UINT i;
2723 TRACE("device %p, start_register %u, constants %p, vector4f_count %u.\n",
2724 device, start_register, constants, vector4f_count);
2726 /* Specifically test start_register > limit to catch MAX_UINT overflows
2727 * when adding start_register + vector4f_count. */
2728 if (!constants
2729 || start_register + vector4f_count > device->d3d_vshader_constantF
2730 || start_register > device->d3d_vshader_constantF)
2731 return WINED3DERR_INVALIDCALL;
2733 memcpy(&device->updateStateBlock->state.vs_consts_f[start_register * 4],
2734 constants, vector4f_count * sizeof(float) * 4);
2735 if (TRACE_ON(d3d))
2737 for (i = 0; i < vector4f_count; ++i)
2738 TRACE("Set FLOAT constant %u to {%.8e, %.8e, %.8e, %.8e}.\n", start_register + i,
2739 constants[i * 4], constants[i * 4 + 1],
2740 constants[i * 4 + 2], constants[i * 4 + 3]);
2743 if (!device->isRecordingState)
2745 device->shader_backend->shader_update_float_vertex_constants(device, start_register, vector4f_count);
2746 device_invalidate_state(device, STATE_VERTEXSHADERCONSTANT);
2749 memset(device->updateStateBlock->changed.vertexShaderConstantsF + start_register, 1,
2750 sizeof(*device->updateStateBlock->changed.vertexShaderConstantsF) * vector4f_count);
2752 return WINED3D_OK;
2755 HRESULT CDECL wined3d_device_get_vs_consts_f(struct wined3d_device *device,
2756 UINT start_register, float *constants, UINT vector4f_count)
2758 int count = min(vector4f_count, device->d3d_vshader_constantF - start_register);
2760 TRACE("device %p, start_register %u, constants %p, vector4f_count %u.\n",
2761 device, start_register, constants, vector4f_count);
2763 if (!constants || count < 0)
2764 return WINED3DERR_INVALIDCALL;
2766 memcpy(constants, &device->stateBlock->state.vs_consts_f[start_register * 4], count * sizeof(float) * 4);
2768 return WINED3D_OK;
2771 static inline void markTextureStagesDirty(struct wined3d_device *device, DWORD stage)
2773 DWORD i;
2775 for (i = 0; i <= WINED3D_HIGHEST_TEXTURE_STATE; ++i)
2777 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, i));
2781 static void device_map_stage(struct wined3d_device *device, DWORD stage, DWORD unit)
2783 DWORD i = device->rev_tex_unit_map[unit];
2784 DWORD j = device->texUnitMap[stage];
2786 device->texUnitMap[stage] = unit;
2787 if (i != WINED3D_UNMAPPED_STAGE && i != stage)
2788 device->texUnitMap[i] = WINED3D_UNMAPPED_STAGE;
2790 device->rev_tex_unit_map[unit] = stage;
2791 if (j != WINED3D_UNMAPPED_STAGE && j != unit)
2792 device->rev_tex_unit_map[j] = WINED3D_UNMAPPED_STAGE;
2795 static void device_update_fixed_function_usage_map(struct wined3d_device *device)
2797 UINT i;
2799 device->fixed_function_usage_map = 0;
2800 for (i = 0; i < MAX_TEXTURES; ++i)
2802 const struct wined3d_state *state = &device->stateBlock->state;
2803 WINED3DTEXTUREOP color_op = state->texture_states[i][WINED3DTSS_COLOROP];
2804 WINED3DTEXTUREOP alpha_op = state->texture_states[i][WINED3DTSS_ALPHAOP];
2805 DWORD color_arg1 = state->texture_states[i][WINED3DTSS_COLORARG1] & WINED3DTA_SELECTMASK;
2806 DWORD color_arg2 = state->texture_states[i][WINED3DTSS_COLORARG2] & WINED3DTA_SELECTMASK;
2807 DWORD color_arg3 = state->texture_states[i][WINED3DTSS_COLORARG0] & WINED3DTA_SELECTMASK;
2808 DWORD alpha_arg1 = state->texture_states[i][WINED3DTSS_ALPHAARG1] & WINED3DTA_SELECTMASK;
2809 DWORD alpha_arg2 = state->texture_states[i][WINED3DTSS_ALPHAARG2] & WINED3DTA_SELECTMASK;
2810 DWORD alpha_arg3 = state->texture_states[i][WINED3DTSS_ALPHAARG0] & WINED3DTA_SELECTMASK;
2812 if (color_op == WINED3DTOP_DISABLE) {
2813 /* Not used, and disable higher stages */
2814 break;
2817 if (((color_arg1 == WINED3DTA_TEXTURE) && color_op != WINED3DTOP_SELECTARG2)
2818 || ((color_arg2 == WINED3DTA_TEXTURE) && color_op != WINED3DTOP_SELECTARG1)
2819 || ((color_arg3 == WINED3DTA_TEXTURE)
2820 && (color_op == WINED3DTOP_MULTIPLYADD || color_op == WINED3DTOP_LERP))
2821 || ((alpha_arg1 == WINED3DTA_TEXTURE) && alpha_op != WINED3DTOP_SELECTARG2)
2822 || ((alpha_arg2 == WINED3DTA_TEXTURE) && alpha_op != WINED3DTOP_SELECTARG1)
2823 || ((alpha_arg3 == WINED3DTA_TEXTURE)
2824 && (alpha_op == WINED3DTOP_MULTIPLYADD || alpha_op == WINED3DTOP_LERP)))
2825 device->fixed_function_usage_map |= (1 << i);
2827 if ((color_op == WINED3DTOP_BUMPENVMAP || color_op == WINED3DTOP_BUMPENVMAPLUMINANCE) && i < MAX_TEXTURES - 1)
2828 device->fixed_function_usage_map |= (1 << (i + 1));
2832 static void device_map_fixed_function_samplers(struct wined3d_device *device, const struct wined3d_gl_info *gl_info)
2834 unsigned int i, tex;
2835 WORD ffu_map;
2837 device_update_fixed_function_usage_map(device);
2838 ffu_map = device->fixed_function_usage_map;
2840 if (device->max_ffp_textures == gl_info->limits.texture_stages
2841 || device->stateBlock->state.lowest_disabled_stage <= device->max_ffp_textures)
2843 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2845 if (!(ffu_map & 1)) continue;
2847 if (device->texUnitMap[i] != i)
2849 device_map_stage(device, i, i);
2850 device_invalidate_state(device, STATE_SAMPLER(i));
2851 markTextureStagesDirty(device, i);
2854 return;
2857 /* Now work out the mapping */
2858 tex = 0;
2859 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2861 if (!(ffu_map & 1)) continue;
2863 if (device->texUnitMap[i] != tex)
2865 device_map_stage(device, i, tex);
2866 device_invalidate_state(device, STATE_SAMPLER(i));
2867 markTextureStagesDirty(device, i);
2870 ++tex;
2874 static void device_map_psamplers(struct wined3d_device *device, const struct wined3d_gl_info *gl_info)
2876 const WINED3DSAMPLER_TEXTURE_TYPE *sampler_type =
2877 device->stateBlock->state.pixel_shader->reg_maps.sampler_type;
2878 unsigned int i;
2880 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
2882 if (sampler_type[i] && device->texUnitMap[i] != i)
2884 device_map_stage(device, i, i);
2885 device_invalidate_state(device, STATE_SAMPLER(i));
2886 if (i < gl_info->limits.texture_stages)
2888 markTextureStagesDirty(device, i);
2894 static BOOL device_unit_free_for_vs(struct wined3d_device *device,
2895 const WINED3DSAMPLER_TEXTURE_TYPE *pshader_sampler_tokens,
2896 const WINED3DSAMPLER_TEXTURE_TYPE *vshader_sampler_tokens, DWORD unit)
2898 DWORD current_mapping = device->rev_tex_unit_map[unit];
2900 /* Not currently used */
2901 if (current_mapping == WINED3D_UNMAPPED_STAGE) return TRUE;
2903 if (current_mapping < MAX_FRAGMENT_SAMPLERS) {
2904 /* Used by a fragment sampler */
2906 if (!pshader_sampler_tokens) {
2907 /* No pixel shader, check fixed function */
2908 return current_mapping >= MAX_TEXTURES || !(device->fixed_function_usage_map & (1 << current_mapping));
2911 /* Pixel shader, check the shader's sampler map */
2912 return !pshader_sampler_tokens[current_mapping];
2915 /* Used by a vertex sampler */
2916 return !vshader_sampler_tokens[current_mapping - MAX_FRAGMENT_SAMPLERS];
2919 static void device_map_vsamplers(struct wined3d_device *device, BOOL ps, const struct wined3d_gl_info *gl_info)
2921 const WINED3DSAMPLER_TEXTURE_TYPE *vshader_sampler_type =
2922 device->stateBlock->state.vertex_shader->reg_maps.sampler_type;
2923 const WINED3DSAMPLER_TEXTURE_TYPE *pshader_sampler_type = NULL;
2924 int start = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers) - 1;
2925 int i;
2927 if (ps)
2929 /* Note that we only care if a sampler is sampled or not, not the sampler's specific type.
2930 * Otherwise we'd need to call shader_update_samplers() here for 1.x pixelshaders. */
2931 pshader_sampler_type = device->stateBlock->state.pixel_shader->reg_maps.sampler_type;
2934 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i) {
2935 DWORD vsampler_idx = i + MAX_FRAGMENT_SAMPLERS;
2936 if (vshader_sampler_type[i])
2938 if (device->texUnitMap[vsampler_idx] != WINED3D_UNMAPPED_STAGE)
2940 /* Already mapped somewhere */
2941 continue;
2944 while (start >= 0)
2946 if (device_unit_free_for_vs(device, pshader_sampler_type, vshader_sampler_type, start))
2948 device_map_stage(device, vsampler_idx, start);
2949 device_invalidate_state(device, STATE_SAMPLER(vsampler_idx));
2951 --start;
2952 break;
2955 --start;
2961 void device_update_tex_unit_map(struct wined3d_device *device)
2963 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
2964 const struct wined3d_state *state = &device->stateBlock->state;
2965 BOOL vs = use_vs(state);
2966 BOOL ps = use_ps(state);
2968 * Rules are:
2969 * -> Pixel shaders need a 1:1 map. In theory the shader input could be mapped too, but
2970 * that would be really messy and require shader recompilation
2971 * -> When the mapping of a stage is changed, sampler and ALL texture stage states have
2972 * to be reset. Because of that try to work with a 1:1 mapping as much as possible
2974 if (ps)
2975 device_map_psamplers(device, gl_info);
2976 else
2977 device_map_fixed_function_samplers(device, gl_info);
2979 if (vs)
2980 device_map_vsamplers(device, ps, gl_info);
2983 HRESULT CDECL wined3d_device_set_pixel_shader(struct wined3d_device *device, struct wined3d_shader *shader)
2985 struct wined3d_shader *prev = device->updateStateBlock->state.pixel_shader;
2987 TRACE("device %p, shader %p.\n", device, shader);
2989 device->updateStateBlock->state.pixel_shader = shader;
2990 device->updateStateBlock->changed.pixelShader = TRUE;
2992 if (device->isRecordingState)
2994 if (shader)
2995 wined3d_shader_incref(shader);
2996 if (prev)
2997 wined3d_shader_decref(prev);
2998 TRACE("Recording... not performing anything.\n");
2999 return WINED3D_OK;
3002 if (shader == prev)
3004 TRACE("Application is setting the old shader over, nothing to do.\n");
3005 return WINED3D_OK;
3008 if (shader)
3009 wined3d_shader_incref(shader);
3010 if (prev)
3011 wined3d_shader_decref(prev);
3013 device_invalidate_state(device, STATE_PIXELSHADER);
3015 return WINED3D_OK;
3018 struct wined3d_shader * CDECL wined3d_device_get_pixel_shader(struct wined3d_device *device)
3020 struct wined3d_shader *shader;
3022 TRACE("device %p.\n", device);
3024 shader = device->stateBlock->state.pixel_shader;
3025 if (shader)
3026 wined3d_shader_incref(shader);
3028 TRACE("Returning %p.\n", shader);
3029 return shader;
3032 HRESULT CDECL wined3d_device_set_ps_consts_b(struct wined3d_device *device,
3033 UINT start_register, const BOOL *constants, UINT bool_count)
3035 UINT count = min(bool_count, MAX_CONST_B - start_register);
3036 UINT i;
3038 TRACE("device %p, start_register %u, constants %p, bool_count %u.\n",
3039 device, start_register, constants, bool_count);
3041 if (!constants || start_register >= MAX_CONST_B)
3042 return WINED3DERR_INVALIDCALL;
3044 memcpy(&device->updateStateBlock->state.ps_consts_b[start_register], constants, count * sizeof(BOOL));
3045 for (i = 0; i < count; ++i)
3046 TRACE("Set BOOL constant %u to %s.\n", start_register + i, constants[i] ? "true" : "false");
3048 for (i = start_register; i < count + start_register; ++i)
3049 device->updateStateBlock->changed.pixelShaderConstantsB |= (1 << i);
3051 if (!device->isRecordingState)
3052 device_invalidate_state(device, STATE_PIXELSHADERCONSTANT);
3054 return WINED3D_OK;
3057 HRESULT CDECL wined3d_device_get_ps_consts_b(struct wined3d_device *device,
3058 UINT start_register, BOOL *constants, UINT bool_count)
3060 UINT count = min(bool_count, MAX_CONST_B - start_register);
3062 TRACE("device %p, start_register %u, constants %p, bool_count %u.\n",
3063 device, start_register, constants, bool_count);
3065 if (!constants || start_register >= MAX_CONST_B)
3066 return WINED3DERR_INVALIDCALL;
3068 memcpy(constants, &device->stateBlock->state.ps_consts_b[start_register], count * sizeof(BOOL));
3070 return WINED3D_OK;
3073 HRESULT CDECL wined3d_device_set_ps_consts_i(struct wined3d_device *device,
3074 UINT start_register, const int *constants, UINT vector4i_count)
3076 UINT count = min(vector4i_count, MAX_CONST_I - start_register);
3077 UINT i;
3079 TRACE("device %p, start_register %u, constants %p, vector4i_count %u.\n",
3080 device, start_register, constants, vector4i_count);
3082 if (!constants || start_register >= MAX_CONST_I)
3083 return WINED3DERR_INVALIDCALL;
3085 memcpy(&device->updateStateBlock->state.ps_consts_i[start_register * 4], constants, count * sizeof(int) * 4);
3086 for (i = 0; i < count; ++i)
3087 TRACE("Set INT constant %u to {%d, %d, %d, %d}.\n", start_register + i,
3088 constants[i * 4], constants[i * 4 + 1],
3089 constants[i * 4 + 2], constants[i * 4 + 3]);
3091 for (i = start_register; i < count + start_register; ++i)
3092 device->updateStateBlock->changed.pixelShaderConstantsI |= (1 << i);
3094 if (!device->isRecordingState)
3095 device_invalidate_state(device, STATE_PIXELSHADERCONSTANT);
3097 return WINED3D_OK;
3100 HRESULT CDECL wined3d_device_get_ps_consts_i(struct wined3d_device *device,
3101 UINT start_register, int *constants, UINT vector4i_count)
3103 UINT count = min(vector4i_count, MAX_CONST_I - start_register);
3105 TRACE("device %p, start_register %u, constants %p, vector4i_count %u.\n",
3106 device, start_register, constants, vector4i_count);
3108 if (!constants || start_register >= MAX_CONST_I)
3109 return WINED3DERR_INVALIDCALL;
3111 memcpy(constants, &device->stateBlock->state.ps_consts_i[start_register * 4], count * sizeof(int) * 4);
3113 return WINED3D_OK;
3116 HRESULT CDECL wined3d_device_set_ps_consts_f(struct wined3d_device *device,
3117 UINT start_register, const float *constants, UINT vector4f_count)
3119 UINT i;
3121 TRACE("device %p, start_register %u, constants %p, vector4f_count %u.\n",
3122 device, start_register, constants, vector4f_count);
3124 /* Specifically test start_register > limit to catch MAX_UINT overflows
3125 * when adding start_register + vector4f_count. */
3126 if (!constants
3127 || start_register + vector4f_count > device->d3d_pshader_constantF
3128 || start_register > device->d3d_pshader_constantF)
3129 return WINED3DERR_INVALIDCALL;
3131 memcpy(&device->updateStateBlock->state.ps_consts_f[start_register * 4],
3132 constants, vector4f_count * sizeof(float) * 4);
3133 if (TRACE_ON(d3d))
3135 for (i = 0; i < vector4f_count; ++i)
3136 TRACE("Set FLOAT constant %u to {%.8e, %.8e, %.8e, %.8e}.\n", start_register + i,
3137 constants[i * 4], constants[i * 4 + 1],
3138 constants[i * 4 + 2], constants[i * 4 + 3]);
3141 if (!device->isRecordingState)
3143 device->shader_backend->shader_update_float_pixel_constants(device, start_register, vector4f_count);
3144 device_invalidate_state(device, STATE_PIXELSHADERCONSTANT);
3147 memset(device->updateStateBlock->changed.pixelShaderConstantsF + start_register, 1,
3148 sizeof(*device->updateStateBlock->changed.pixelShaderConstantsF) * vector4f_count);
3150 return WINED3D_OK;
3153 HRESULT CDECL wined3d_device_get_ps_consts_f(struct wined3d_device *device,
3154 UINT start_register, float *constants, UINT vector4f_count)
3156 int count = min(vector4f_count, device->d3d_pshader_constantF - start_register);
3158 TRACE("device %p, start_register %u, constants %p, vector4f_count %u.\n",
3159 device, start_register, constants, vector4f_count);
3161 if (!constants || count < 0)
3162 return WINED3DERR_INVALIDCALL;
3164 memcpy(constants, &device->stateBlock->state.ps_consts_f[start_register * 4], count * sizeof(float) * 4);
3166 return WINED3D_OK;
3169 /* Context activation is done by the caller. */
3170 /* Do not call while under the GL lock. */
3171 #define copy_and_next(dest, src, size) memcpy(dest, src, size); dest += (size)
3172 static HRESULT process_vertices_strided(struct wined3d_device *device, DWORD dwDestIndex, DWORD dwCount,
3173 const struct wined3d_stream_info *stream_info, struct wined3d_buffer *dest, DWORD flags,
3174 DWORD DestFVF)
3176 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
3177 char *dest_ptr, *dest_conv = NULL, *dest_conv_addr = NULL;
3178 unsigned int i;
3179 WINED3DVIEWPORT vp;
3180 WINED3DMATRIX mat, proj_mat, view_mat, world_mat;
3181 BOOL doClip;
3182 DWORD numTextures;
3184 if (stream_info->use_map & (1 << WINED3D_FFP_NORMAL))
3186 WARN(" lighting state not saved yet... Some strange stuff may happen !\n");
3189 if (!(stream_info->use_map & (1 << WINED3D_FFP_POSITION)))
3191 ERR("Source has no position mask\n");
3192 return WINED3DERR_INVALIDCALL;
3195 if (!dest->resource.allocatedMemory)
3196 buffer_get_sysmem(dest, gl_info);
3198 /* Get a pointer into the destination vbo(create one if none exists) and
3199 * write correct opengl data into it. It's cheap and allows us to run drawStridedFast
3201 if (!dest->buffer_object && gl_info->supported[ARB_VERTEX_BUFFER_OBJECT])
3203 dest->flags |= WINED3D_BUFFER_CREATEBO;
3204 wined3d_buffer_preload(dest);
3207 if (dest->buffer_object)
3209 unsigned char extrabytes = 0;
3210 /* If the destination vertex buffer has D3DFVF_XYZ position(non-rhw), native d3d writes RHW position, where the RHW
3211 * gets written into the 4 bytes after the Z position. In the case of a dest buffer that only has D3DFVF_XYZ data,
3212 * this may write 4 extra bytes beyond the area that should be written
3214 if(DestFVF == WINED3DFVF_XYZ) extrabytes = 4;
3215 dest_conv_addr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwCount * get_flexible_vertex_size(DestFVF) + extrabytes);
3216 if(!dest_conv_addr) {
3217 ERR("Out of memory\n");
3218 /* Continue without storing converted vertices */
3220 dest_conv = dest_conv_addr;
3223 if (device->stateBlock->state.render_states[WINED3DRS_CLIPPING])
3225 static BOOL warned = FALSE;
3227 * The clipping code is not quite correct. Some things need
3228 * to be checked against IDirect3DDevice3 (!), d3d8 and d3d9,
3229 * so disable clipping for now.
3230 * (The graphics in Half-Life are broken, and my processvertices
3231 * test crashes with IDirect3DDevice3)
3232 doClip = TRUE;
3234 doClip = FALSE;
3235 if(!warned) {
3236 warned = TRUE;
3237 FIXME("Clipping is broken and disabled for now\n");
3239 } else doClip = FALSE;
3240 dest_ptr = ((char *)buffer_get_sysmem(dest, gl_info)) + dwDestIndex * get_flexible_vertex_size(DestFVF);
3242 wined3d_device_get_transform(device, WINED3DTS_VIEW, &view_mat);
3243 wined3d_device_get_transform(device, WINED3DTS_PROJECTION, &proj_mat);
3244 wined3d_device_get_transform(device, WINED3DTS_WORLDMATRIX(0), &world_mat);
3246 TRACE("View mat:\n");
3247 TRACE("%f %f %f %f\n", view_mat.u.s._11, view_mat.u.s._12, view_mat.u.s._13, view_mat.u.s._14);
3248 TRACE("%f %f %f %f\n", view_mat.u.s._21, view_mat.u.s._22, view_mat.u.s._23, view_mat.u.s._24);
3249 TRACE("%f %f %f %f\n", view_mat.u.s._31, view_mat.u.s._32, view_mat.u.s._33, view_mat.u.s._34);
3250 TRACE("%f %f %f %f\n", view_mat.u.s._41, view_mat.u.s._42, view_mat.u.s._43, view_mat.u.s._44);
3252 TRACE("Proj mat:\n");
3253 TRACE("%f %f %f %f\n", proj_mat.u.s._11, proj_mat.u.s._12, proj_mat.u.s._13, proj_mat.u.s._14);
3254 TRACE("%f %f %f %f\n", proj_mat.u.s._21, proj_mat.u.s._22, proj_mat.u.s._23, proj_mat.u.s._24);
3255 TRACE("%f %f %f %f\n", proj_mat.u.s._31, proj_mat.u.s._32, proj_mat.u.s._33, proj_mat.u.s._34);
3256 TRACE("%f %f %f %f\n", proj_mat.u.s._41, proj_mat.u.s._42, proj_mat.u.s._43, proj_mat.u.s._44);
3258 TRACE("World mat:\n");
3259 TRACE("%f %f %f %f\n", world_mat.u.s._11, world_mat.u.s._12, world_mat.u.s._13, world_mat.u.s._14);
3260 TRACE("%f %f %f %f\n", world_mat.u.s._21, world_mat.u.s._22, world_mat.u.s._23, world_mat.u.s._24);
3261 TRACE("%f %f %f %f\n", world_mat.u.s._31, world_mat.u.s._32, world_mat.u.s._33, world_mat.u.s._34);
3262 TRACE("%f %f %f %f\n", world_mat.u.s._41, world_mat.u.s._42, world_mat.u.s._43, world_mat.u.s._44);
3264 /* Get the viewport */
3265 wined3d_device_get_viewport(device, &vp);
3266 TRACE("Viewport: X=%d, Y=%d, Width=%d, Height=%d, MinZ=%f, MaxZ=%f\n",
3267 vp.X, vp.Y, vp.Width, vp.Height, vp.MinZ, vp.MaxZ);
3269 multiply_matrix(&mat,&view_mat,&world_mat);
3270 multiply_matrix(&mat,&proj_mat,&mat);
3272 numTextures = (DestFVF & WINED3DFVF_TEXCOUNT_MASK) >> WINED3DFVF_TEXCOUNT_SHIFT;
3274 for (i = 0; i < dwCount; i+= 1) {
3275 unsigned int tex_index;
3277 if ( ((DestFVF & WINED3DFVF_POSITION_MASK) == WINED3DFVF_XYZ ) ||
3278 ((DestFVF & WINED3DFVF_POSITION_MASK) == WINED3DFVF_XYZRHW ) ) {
3279 /* The position first */
3280 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_POSITION];
3281 const float *p = (const float *)(element->data.addr + i * element->stride);
3282 float x, y, z, rhw;
3283 TRACE("In: ( %06.2f %06.2f %06.2f )\n", p[0], p[1], p[2]);
3285 /* Multiplication with world, view and projection matrix */
3286 x = (p[0] * mat.u.s._11) + (p[1] * mat.u.s._21) + (p[2] * mat.u.s._31) + (1.0f * mat.u.s._41);
3287 y = (p[0] * mat.u.s._12) + (p[1] * mat.u.s._22) + (p[2] * mat.u.s._32) + (1.0f * mat.u.s._42);
3288 z = (p[0] * mat.u.s._13) + (p[1] * mat.u.s._23) + (p[2] * mat.u.s._33) + (1.0f * mat.u.s._43);
3289 rhw = (p[0] * mat.u.s._14) + (p[1] * mat.u.s._24) + (p[2] * mat.u.s._34) + (1.0f * mat.u.s._44);
3291 TRACE("x=%f y=%f z=%f rhw=%f\n", x, y, z, rhw);
3293 /* WARNING: The following things are taken from d3d7 and were not yet checked
3294 * against d3d8 or d3d9!
3297 /* Clipping conditions: From msdn
3299 * A vertex is clipped if it does not match the following requirements
3300 * -rhw < x <= rhw
3301 * -rhw < y <= rhw
3302 * 0 < z <= rhw
3303 * 0 < rhw ( Not in d3d7, but tested in d3d7)
3305 * If clipping is on is determined by the D3DVOP_CLIP flag in D3D7, and
3306 * by the D3DRS_CLIPPING in D3D9(according to the msdn, not checked)
3310 if( !doClip ||
3311 ( (-rhw -eps < x) && (-rhw -eps < y) && ( -eps < z) &&
3312 (x <= rhw + eps) && (y <= rhw + eps ) && (z <= rhw + eps) &&
3313 ( rhw > eps ) ) ) {
3315 /* "Normal" viewport transformation (not clipped)
3316 * 1) The values are divided by rhw
3317 * 2) The y axis is negative, so multiply it with -1
3318 * 3) Screen coordinates go from -(Width/2) to +(Width/2) and
3319 * -(Height/2) to +(Height/2). The z range is MinZ to MaxZ
3320 * 4) Multiply x with Width/2 and add Width/2
3321 * 5) The same for the height
3322 * 6) Add the viewpoint X and Y to the 2D coordinates and
3323 * The minimum Z value to z
3324 * 7) rhw = 1 / rhw Reciprocal of Homogeneous W....
3326 * Well, basically it's simply a linear transformation into viewport
3327 * coordinates
3330 x /= rhw;
3331 y /= rhw;
3332 z /= rhw;
3334 y *= -1;
3336 x *= vp.Width / 2;
3337 y *= vp.Height / 2;
3338 z *= vp.MaxZ - vp.MinZ;
3340 x += vp.Width / 2 + vp.X;
3341 y += vp.Height / 2 + vp.Y;
3342 z += vp.MinZ;
3344 rhw = 1 / rhw;
3345 } else {
3346 /* That vertex got clipped
3347 * Contrary to OpenGL it is not dropped completely, it just
3348 * undergoes a different calculation.
3350 TRACE("Vertex got clipped\n");
3351 x += rhw;
3352 y += rhw;
3354 x /= 2;
3355 y /= 2;
3357 /* Msdn mentions that Direct3D9 keeps a list of clipped vertices
3358 * outside of the main vertex buffer memory. That needs some more
3359 * investigation...
3363 TRACE("Writing (%f %f %f) %f\n", x, y, z, rhw);
3366 ( (float *) dest_ptr)[0] = x;
3367 ( (float *) dest_ptr)[1] = y;
3368 ( (float *) dest_ptr)[2] = z;
3369 ( (float *) dest_ptr)[3] = rhw; /* SIC, see ddraw test! */
3371 dest_ptr += 3 * sizeof(float);
3373 if((DestFVF & WINED3DFVF_POSITION_MASK) == WINED3DFVF_XYZRHW) {
3374 dest_ptr += sizeof(float);
3377 if(dest_conv) {
3378 float w = 1 / rhw;
3379 ( (float *) dest_conv)[0] = x * w;
3380 ( (float *) dest_conv)[1] = y * w;
3381 ( (float *) dest_conv)[2] = z * w;
3382 ( (float *) dest_conv)[3] = w;
3384 dest_conv += 3 * sizeof(float);
3386 if((DestFVF & WINED3DFVF_POSITION_MASK) == WINED3DFVF_XYZRHW) {
3387 dest_conv += sizeof(float);
3391 if (DestFVF & WINED3DFVF_PSIZE) {
3392 dest_ptr += sizeof(DWORD);
3393 if(dest_conv) dest_conv += sizeof(DWORD);
3395 if (DestFVF & WINED3DFVF_NORMAL)
3397 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_NORMAL];
3398 const float *normal = (const float *)(element->data.addr + i * element->stride);
3399 /* AFAIK this should go into the lighting information */
3400 FIXME("Didn't expect the destination to have a normal\n");
3401 copy_and_next(dest_ptr, normal, 3 * sizeof(float));
3402 if(dest_conv) {
3403 copy_and_next(dest_conv, normal, 3 * sizeof(float));
3407 if (DestFVF & WINED3DFVF_DIFFUSE)
3409 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_DIFFUSE];
3410 const DWORD *color_d = (const DWORD *)(element->data.addr + i * element->stride);
3411 if (!(stream_info->use_map & (1 << WINED3D_FFP_DIFFUSE)))
3413 static BOOL warned = FALSE;
3415 if(!warned) {
3416 ERR("No diffuse color in source, but destination has one\n");
3417 warned = TRUE;
3420 *( (DWORD *) dest_ptr) = 0xffffffff;
3421 dest_ptr += sizeof(DWORD);
3423 if(dest_conv) {
3424 *( (DWORD *) dest_conv) = 0xffffffff;
3425 dest_conv += sizeof(DWORD);
3428 else {
3429 copy_and_next(dest_ptr, color_d, sizeof(DWORD));
3430 if(dest_conv) {
3431 *( (DWORD *) dest_conv) = (*color_d & 0xff00ff00) ; /* Alpha + green */
3432 *( (DWORD *) dest_conv) |= (*color_d & 0x00ff0000) >> 16; /* Red */
3433 *( (DWORD *) dest_conv) |= (*color_d & 0xff0000ff) << 16; /* Blue */
3434 dest_conv += sizeof(DWORD);
3439 if (DestFVF & WINED3DFVF_SPECULAR)
3441 /* What's the color value in the feedback buffer? */
3442 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_SPECULAR];
3443 const DWORD *color_s = (const DWORD *)(element->data.addr + i * element->stride);
3444 if (!(stream_info->use_map & (1 << WINED3D_FFP_SPECULAR)))
3446 static BOOL warned = FALSE;
3448 if(!warned) {
3449 ERR("No specular color in source, but destination has one\n");
3450 warned = TRUE;
3453 *( (DWORD *) dest_ptr) = 0xFF000000;
3454 dest_ptr += sizeof(DWORD);
3456 if(dest_conv) {
3457 *( (DWORD *) dest_conv) = 0xFF000000;
3458 dest_conv += sizeof(DWORD);
3461 else {
3462 copy_and_next(dest_ptr, color_s, sizeof(DWORD));
3463 if(dest_conv) {
3464 *( (DWORD *) dest_conv) = (*color_s & 0xff00ff00) ; /* Alpha + green */
3465 *( (DWORD *) dest_conv) |= (*color_s & 0x00ff0000) >> 16; /* Red */
3466 *( (DWORD *) dest_conv) |= (*color_s & 0xff0000ff) << 16; /* Blue */
3467 dest_conv += sizeof(DWORD);
3472 for (tex_index = 0; tex_index < numTextures; ++tex_index)
3474 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_TEXCOORD0 + tex_index];
3475 const float *tex_coord = (const float *)(element->data.addr + i * element->stride);
3476 if (!(stream_info->use_map & (1 << (WINED3D_FFP_TEXCOORD0 + tex_index))))
3478 ERR("No source texture, but destination requests one\n");
3479 dest_ptr+=GET_TEXCOORD_SIZE_FROM_FVF(DestFVF, tex_index) * sizeof(float);
3480 if(dest_conv) dest_conv += GET_TEXCOORD_SIZE_FROM_FVF(DestFVF, tex_index) * sizeof(float);
3482 else {
3483 copy_and_next(dest_ptr, tex_coord, GET_TEXCOORD_SIZE_FROM_FVF(DestFVF, tex_index) * sizeof(float));
3484 if(dest_conv) {
3485 copy_and_next(dest_conv, tex_coord, GET_TEXCOORD_SIZE_FROM_FVF(DestFVF, tex_index) * sizeof(float));
3491 if (dest_conv)
3493 ENTER_GL();
3495 GL_EXTCALL(glBindBufferARB(GL_ARRAY_BUFFER_ARB, dest->buffer_object));
3496 checkGLcall("glBindBufferARB(GL_ARRAY_BUFFER_ARB)");
3497 GL_EXTCALL(glBufferSubDataARB(GL_ARRAY_BUFFER_ARB, dwDestIndex * get_flexible_vertex_size(DestFVF),
3498 dwCount * get_flexible_vertex_size(DestFVF),
3499 dest_conv_addr));
3500 checkGLcall("glBufferSubDataARB(GL_ARRAY_BUFFER_ARB)");
3502 LEAVE_GL();
3504 HeapFree(GetProcessHeap(), 0, dest_conv_addr);
3507 return WINED3D_OK;
3509 #undef copy_and_next
3511 /* Do not call while under the GL lock. */
3512 HRESULT CDECL wined3d_device_process_vertices(struct wined3d_device *device,
3513 UINT src_start_idx, UINT dst_idx, UINT vertex_count, struct wined3d_buffer *dst_buffer,
3514 struct wined3d_vertex_declaration *declaration, DWORD flags, DWORD dst_fvf)
3516 struct wined3d_state *state = &device->stateBlock->state;
3517 BOOL vbo = FALSE, streamWasUP = state->user_stream;
3518 struct wined3d_stream_info stream_info;
3519 const struct wined3d_gl_info *gl_info;
3520 struct wined3d_context *context;
3521 struct wined3d_shader *vs;
3522 HRESULT hr;
3524 TRACE("device %p, src_start_idx %u, dst_idx %u, vertex_count %u, "
3525 "dst_buffer %p, declaration %p, flags %#x, dst_fvf %#x.\n",
3526 device, src_start_idx, dst_idx, vertex_count,
3527 dst_buffer, declaration, flags, dst_fvf);
3529 if (declaration)
3530 FIXME("Output vertex declaration not implemented yet.\n");
3532 /* Need any context to write to the vbo. */
3533 context = context_acquire(device, NULL);
3534 gl_info = context->gl_info;
3536 /* ProcessVertices reads from vertex buffers, which have to be assigned.
3537 * DrawPrimitive and DrawPrimitiveUP control the streamIsUP flag, thus
3538 * restore it afterwards. */
3539 vs = state->vertex_shader;
3540 state->vertex_shader = NULL;
3541 state->user_stream = FALSE;
3542 device_stream_info_from_declaration(device, &stream_info, &vbo);
3543 state->user_stream = streamWasUP;
3544 state->vertex_shader = vs;
3546 if (vbo || src_start_idx)
3548 unsigned int i;
3549 /* ProcessVertices can't convert FROM a vbo, and vertex buffers used to source into ProcessVertices are
3550 * unlikely to ever be used for drawing. Release vbos in those buffers and fix up the stream_info structure
3552 * Also get the start index in, but only loop over all elements if there's something to add at all.
3554 for (i = 0; i < (sizeof(stream_info.elements) / sizeof(*stream_info.elements)); ++i)
3556 struct wined3d_stream_info_element *e;
3558 if (!(stream_info.use_map & (1 << i))) continue;
3560 e = &stream_info.elements[i];
3561 if (e->data.buffer_object)
3563 struct wined3d_buffer *vb = state->streams[e->stream_idx].buffer;
3564 e->data.buffer_object = 0;
3565 e->data.addr = (BYTE *)((ULONG_PTR)e->data.addr + (ULONG_PTR)buffer_get_sysmem(vb, gl_info));
3566 ENTER_GL();
3567 GL_EXTCALL(glDeleteBuffersARB(1, &vb->buffer_object));
3568 vb->buffer_object = 0;
3569 LEAVE_GL();
3571 if (e->data.addr)
3572 e->data.addr += e->stride * src_start_idx;
3576 hr = process_vertices_strided(device, dst_idx, vertex_count,
3577 &stream_info, dst_buffer, flags, dst_fvf);
3579 context_release(context);
3581 return hr;
3584 HRESULT CDECL wined3d_device_set_texture_stage_state(struct wined3d_device *device,
3585 UINT stage, WINED3DTEXTURESTAGESTATETYPE state, DWORD value)
3587 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
3588 DWORD old_value;
3590 TRACE("device %p, stage %u, state %s, value %#x.\n",
3591 device, stage, debug_d3dtexturestate(state), value);
3593 if (state > WINED3D_HIGHEST_TEXTURE_STATE)
3595 WARN("Invalid state %#x passed.\n", state);
3596 return WINED3D_OK;
3599 if (stage >= gl_info->limits.texture_stages)
3601 WARN("Attempting to set stage %u which is higher than the max stage %u, ignoring.\n",
3602 stage, gl_info->limits.texture_stages - 1);
3603 return WINED3D_OK;
3606 old_value = device->updateStateBlock->state.texture_states[stage][state];
3607 device->updateStateBlock->changed.textureState[stage] |= 1 << state;
3608 device->updateStateBlock->state.texture_states[stage][state] = value;
3610 if (device->isRecordingState)
3612 TRACE("Recording... not performing anything.\n");
3613 return WINED3D_OK;
3616 /* Checked after the assignments to allow proper stateblock recording. */
3617 if (old_value == value)
3619 TRACE("Application is setting the old value over, nothing to do.\n");
3620 return WINED3D_OK;
3623 if (stage > device->stateBlock->state.lowest_disabled_stage
3624 && device->StateTable[STATE_TEXTURESTAGE(0, state)].representative
3625 == STATE_TEXTURESTAGE(0, WINED3DTSS_COLOROP))
3627 /* Colorop change above lowest disabled stage? That won't change
3628 * anything in the GL setup. Changes in other states are important on
3629 * disabled stages too. */
3630 return WINED3D_OK;
3633 if (state == WINED3DTSS_COLOROP)
3635 unsigned int i;
3637 if (value == WINED3DTOP_DISABLE && old_value != WINED3DTOP_DISABLE)
3639 /* Previously enabled stage disabled now. Make sure to dirtify
3640 * all enabled stages above stage, they have to be disabled.
3642 * The current stage is dirtified below. */
3643 for (i = stage + 1; i < device->stateBlock->state.lowest_disabled_stage; ++i)
3645 TRACE("Additionally dirtifying stage %u.\n", i);
3646 device_invalidate_state(device, STATE_TEXTURESTAGE(i, WINED3DTSS_COLOROP));
3648 device->stateBlock->state.lowest_disabled_stage = stage;
3649 TRACE("New lowest disabled: %u.\n", stage);
3651 else if (value != WINED3DTOP_DISABLE && old_value == WINED3DTOP_DISABLE)
3653 /* Previously disabled stage enabled. Stages above it may need
3654 * enabling. Stage must be lowest_disabled_stage here, if it's
3655 * bigger success is returned above, and stages below the lowest
3656 * disabled stage can't be enabled (because they are enabled
3657 * already).
3659 * Again stage stage doesn't need to be dirtified here, it is
3660 * handled below. */
3661 for (i = stage + 1; i < gl_info->limits.texture_stages; ++i)
3663 if (device->updateStateBlock->state.texture_states[i][WINED3DTSS_COLOROP] == WINED3DTOP_DISABLE)
3664 break;
3665 TRACE("Additionally dirtifying stage %u due to enable.\n", i);
3666 device_invalidate_state(device, STATE_TEXTURESTAGE(i, WINED3DTSS_COLOROP));
3668 device->stateBlock->state.lowest_disabled_stage = i;
3669 TRACE("New lowest disabled: %u.\n", i);
3673 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, state));
3675 return WINED3D_OK;
3678 HRESULT CDECL wined3d_device_get_texture_stage_state(struct wined3d_device *device,
3679 UINT stage, WINED3DTEXTURESTAGESTATETYPE state, DWORD *value)
3681 TRACE("device %p, stage %u, state %s, value %p.\n",
3682 device, stage, debug_d3dtexturestate(state), value);
3684 if (state > WINED3D_HIGHEST_TEXTURE_STATE)
3686 WARN("Invalid state %#x passed.\n", state);
3687 return WINED3D_OK;
3690 *value = device->updateStateBlock->state.texture_states[stage][state];
3691 TRACE("Returning %#x.\n", *value);
3693 return WINED3D_OK;
3696 HRESULT CDECL wined3d_device_set_texture(struct wined3d_device *device,
3697 UINT stage, struct wined3d_texture *texture)
3699 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
3700 struct wined3d_texture *prev;
3702 TRACE("device %p, stage %u, texture %p.\n", device, stage, texture);
3704 if (stage >= WINED3DVERTEXTEXTURESAMPLER0 && stage <= WINED3DVERTEXTEXTURESAMPLER3)
3705 stage -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
3707 /* Windows accepts overflowing this array... we do not. */
3708 if (stage >= sizeof(device->stateBlock->state.textures) / sizeof(*device->stateBlock->state.textures))
3710 WARN("Ignoring invalid stage %u.\n", stage);
3711 return WINED3D_OK;
3714 /* SetTexture isn't allowed on textures in WINED3DPOOL_SCRATCH */
3715 if (texture && texture->resource.pool == WINED3DPOOL_SCRATCH)
3717 WARN("Rejecting attempt to set scratch texture.\n");
3718 return WINED3DERR_INVALIDCALL;
3721 device->updateStateBlock->changed.textures |= 1 << stage;
3723 prev = device->updateStateBlock->state.textures[stage];
3724 TRACE("Previous texture %p.\n", prev);
3726 if (texture == prev)
3728 TRACE("App is setting the same texture again, nothing to do.\n");
3729 return WINED3D_OK;
3732 TRACE("Setting new texture to %p.\n", texture);
3733 device->updateStateBlock->state.textures[stage] = texture;
3735 if (device->isRecordingState)
3737 TRACE("Recording... not performing anything\n");
3739 if (texture) wined3d_texture_incref(texture);
3740 if (prev) wined3d_texture_decref(prev);
3742 return WINED3D_OK;
3745 if (texture)
3747 LONG bind_count = InterlockedIncrement(&texture->bind_count);
3749 wined3d_texture_incref(texture);
3751 if (!prev || texture->target != prev->target)
3752 device_invalidate_state(device, STATE_PIXELSHADER);
3754 if (!prev && stage < gl_info->limits.texture_stages)
3756 /* The source arguments for color and alpha ops have different
3757 * meanings when a NULL texture is bound, so the COLOROP and
3758 * ALPHAOP have to be dirtified. */
3759 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, WINED3DTSS_COLOROP));
3760 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, WINED3DTSS_ALPHAOP));
3763 if (bind_count == 1)
3764 texture->sampler = stage;
3767 if (prev)
3769 LONG bind_count = InterlockedDecrement(&prev->bind_count);
3771 wined3d_texture_decref(prev);
3773 if (!texture && stage < gl_info->limits.texture_stages)
3775 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, WINED3DTSS_COLOROP));
3776 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, WINED3DTSS_ALPHAOP));
3779 if (bind_count && prev->sampler == stage)
3781 unsigned int i;
3783 /* Search for other stages the texture is bound to. Shouldn't
3784 * happen if applications bind textures to a single stage only. */
3785 TRACE("Searching for other stages the texture is bound to.\n");
3786 for (i = 0; i < MAX_COMBINED_SAMPLERS; ++i)
3788 if (device->updateStateBlock->state.textures[i] == prev)
3790 TRACE("Texture is also bound to stage %u.\n", i);
3791 prev->sampler = i;
3792 break;
3798 device_invalidate_state(device, STATE_SAMPLER(stage));
3800 return WINED3D_OK;
3803 HRESULT CDECL wined3d_device_get_texture(struct wined3d_device *device,
3804 UINT stage, struct wined3d_texture **texture)
3806 TRACE("device %p, stage %u, texture %p.\n", device, stage, texture);
3808 if (stage >= WINED3DVERTEXTEXTURESAMPLER0 && stage <= WINED3DVERTEXTEXTURESAMPLER3)
3809 stage -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
3811 if (stage >= sizeof(device->stateBlock->state.textures) / sizeof(*device->stateBlock->state.textures))
3813 WARN("Ignoring invalid stage %u.\n", stage);
3814 return WINED3D_OK; /* Windows accepts overflowing this array ... we do not. */
3817 *texture = device->stateBlock->state.textures[stage];
3818 if (*texture)
3819 wined3d_texture_incref(*texture);
3821 TRACE("Returning %p.\n", *texture);
3823 return WINED3D_OK;
3826 HRESULT CDECL wined3d_device_get_back_buffer(struct wined3d_device *device, UINT swapchain_idx,
3827 UINT backbuffer_idx, WINED3DBACKBUFFER_TYPE backbuffer_type, struct wined3d_surface **backbuffer)
3829 struct wined3d_swapchain *swapchain;
3830 HRESULT hr;
3832 TRACE("device %p, swapchain_idx %u, backbuffer_idx %u, backbuffer_type %#x, backbuffer %p.\n",
3833 device, swapchain_idx, backbuffer_idx, backbuffer_type, backbuffer);
3835 hr = wined3d_device_get_swapchain(device, swapchain_idx, &swapchain);
3836 if (FAILED(hr))
3838 WARN("Failed to get swapchain %u, hr %#x.\n", swapchain_idx, hr);
3839 return hr;
3842 hr = wined3d_swapchain_get_back_buffer(swapchain, backbuffer_idx, backbuffer_type, backbuffer);
3843 wined3d_swapchain_decref(swapchain);
3844 if (FAILED(hr))
3846 WARN("Failed to get backbuffer %u, hr %#x.\n", backbuffer_idx, hr);
3847 return hr;
3850 return WINED3D_OK;
3853 HRESULT CDECL wined3d_device_get_device_caps(struct wined3d_device *device, WINED3DCAPS *caps)
3855 TRACE("device %p, caps %p.\n", device, caps);
3857 return wined3d_get_device_caps(device->wined3d, device->adapter->ordinal, device->devType, caps);
3860 HRESULT CDECL wined3d_device_get_display_mode(struct wined3d_device *device,
3861 UINT swapchain_idx, WINED3DDISPLAYMODE *mode)
3863 struct wined3d_swapchain *swapchain;
3864 HRESULT hr;
3866 TRACE("device %p, swapchain_idx %u, mode %p.\n", device, swapchain_idx, mode);
3868 if (swapchain_idx)
3870 hr = wined3d_device_get_swapchain(device, swapchain_idx, &swapchain);
3871 if (SUCCEEDED(hr))
3873 hr = wined3d_swapchain_get_display_mode(swapchain, mode);
3874 wined3d_swapchain_decref(swapchain);
3877 else
3879 /* Don't read the real display mode, but return the stored mode
3880 * instead. X11 can't change the color depth, and some apps are
3881 * pretty angry if they SetDisplayMode from 24 to 16 bpp and find out
3882 * that GetDisplayMode still returns 24 bpp.
3884 * Also don't relay to the swapchain because with ddraw it's possible
3885 * that there isn't a swapchain at all. */
3886 mode->Width = device->ddraw_width;
3887 mode->Height = device->ddraw_height;
3888 mode->Format = device->ddraw_format;
3889 mode->RefreshRate = 0;
3890 hr = WINED3D_OK;
3893 return hr;
3896 HRESULT CDECL wined3d_device_begin_stateblock(struct wined3d_device *device)
3898 struct wined3d_stateblock *stateblock;
3899 HRESULT hr;
3901 TRACE("device %p.\n", device);
3903 if (device->isRecordingState)
3904 return WINED3DERR_INVALIDCALL;
3906 hr = wined3d_stateblock_create(device, WINED3DSBT_RECORDED, &stateblock);
3907 if (FAILED(hr))
3908 return hr;
3910 wined3d_stateblock_decref(device->updateStateBlock);
3911 device->updateStateBlock = stateblock;
3912 device->isRecordingState = TRUE;
3914 TRACE("Recording stateblock %p.\n", stateblock);
3916 return WINED3D_OK;
3919 HRESULT CDECL wined3d_device_end_stateblock(struct wined3d_device *device,
3920 struct wined3d_stateblock **stateblock)
3922 struct wined3d_stateblock *object = device->updateStateBlock;
3924 TRACE("device %p, stateblock %p.\n", device, stateblock);
3926 if (!device->isRecordingState)
3928 WARN("Not recording.\n");
3929 *stateblock = NULL;
3930 return WINED3DERR_INVALIDCALL;
3933 stateblock_init_contained_states(object);
3935 *stateblock = object;
3936 device->isRecordingState = FALSE;
3937 device->updateStateBlock = device->stateBlock;
3938 wined3d_stateblock_incref(device->updateStateBlock);
3940 TRACE("Returning stateblock %p.\n", *stateblock);
3942 return WINED3D_OK;
3945 HRESULT CDECL wined3d_device_begin_scene(struct wined3d_device *device)
3947 /* At the moment we have no need for any functionality at the beginning
3948 * of a scene. */
3949 TRACE("device %p.\n", device);
3951 if (device->inScene)
3953 WARN("Already in scene, returning WINED3DERR_INVALIDCALL.\n");
3954 return WINED3DERR_INVALIDCALL;
3956 device->inScene = TRUE;
3957 return WINED3D_OK;
3960 HRESULT CDECL wined3d_device_end_scene(struct wined3d_device *device)
3962 struct wined3d_context *context;
3964 TRACE("device %p.\n", device);
3966 if (!device->inScene)
3968 WARN("Not in scene, returning WINED3DERR_INVALIDCALL.\n");
3969 return WINED3DERR_INVALIDCALL;
3972 context = context_acquire(device, NULL);
3973 /* We only have to do this if we need to read the, swapbuffers performs a flush for us */
3974 wglFlush();
3975 /* No checkGLcall here to avoid locking the lock just for checking a call that hardly ever
3976 * fails. */
3977 context_release(context);
3979 device->inScene = FALSE;
3980 return WINED3D_OK;
3983 HRESULT CDECL wined3d_device_present(struct wined3d_device *device, const RECT *src_rect,
3984 const RECT *dst_rect, HWND dst_window_override, const RGNDATA *dirty_region)
3986 UINT i;
3988 TRACE("device %p, src_rect %s, dst_rect %s, dst_window_override %p, dirty_region %p.\n",
3989 device, wine_dbgstr_rect(src_rect), wine_dbgstr_rect(dst_rect),
3990 dst_window_override, dirty_region);
3992 for (i = 0; i < device->swapchain_count; ++i)
3994 wined3d_swapchain_present(device->swapchains[i], src_rect,
3995 dst_rect, dst_window_override, dirty_region, 0);
3998 return WINED3D_OK;
4001 /* Do not call while under the GL lock. */
4002 HRESULT CDECL wined3d_device_clear(struct wined3d_device *device, DWORD rect_count,
4003 const RECT *rects, DWORD flags, WINED3DCOLOR color, float depth, DWORD stencil)
4005 const WINED3DCOLORVALUE c = {D3DCOLOR_R(color), D3DCOLOR_G(color), D3DCOLOR_B(color), D3DCOLOR_A(color)};
4006 RECT draw_rect;
4008 TRACE("device %p, rect_count %u, rects %p, flags %#x, color 0x%08x, depth %.8e, stencil %u.\n",
4009 device, rect_count, rects, flags, color, depth, stencil);
4011 if (flags & (WINED3DCLEAR_ZBUFFER | WINED3DCLEAR_STENCIL))
4013 struct wined3d_surface *ds = device->fb.depth_stencil;
4014 if (!ds)
4016 WARN("Clearing depth and/or stencil without a depth stencil buffer attached, returning WINED3DERR_INVALIDCALL\n");
4017 /* TODO: What about depth stencil buffers without stencil bits? */
4018 return WINED3DERR_INVALIDCALL;
4020 else if (flags & WINED3DCLEAR_TARGET)
4022 if (ds->resource.width < device->fb.render_targets[0]->resource.width
4023 || ds->resource.height < device->fb.render_targets[0]->resource.height)
4025 WARN("Silently ignoring depth and target clear with mismatching sizes\n");
4026 return WINED3D_OK;
4031 wined3d_get_draw_rect(&device->stateBlock->state, &draw_rect);
4033 return device_clear_render_targets(device, device->adapter->gl_info.limits.buffers,
4034 &device->fb, rect_count, rects,
4035 &draw_rect, flags, &c, depth, stencil);
4038 void CDECL wined3d_device_set_primitive_type(struct wined3d_device *device,
4039 WINED3DPRIMITIVETYPE primitive_type)
4041 TRACE("device %p, primitive_type %s\n", device, debug_d3dprimitivetype(primitive_type));
4043 device->updateStateBlock->changed.primitive_type = TRUE;
4044 device->updateStateBlock->state.gl_primitive_type = gl_primitive_type_from_d3d(primitive_type);
4047 void CDECL wined3d_device_get_primitive_type(struct wined3d_device *device,
4048 WINED3DPRIMITIVETYPE *primitive_type)
4050 TRACE("device %p, primitive_type %p\n", device, primitive_type);
4052 *primitive_type = d3d_primitive_type_from_gl(device->stateBlock->state.gl_primitive_type);
4054 TRACE("Returning %s\n", debug_d3dprimitivetype(*primitive_type));
4057 HRESULT CDECL wined3d_device_draw_primitive(struct wined3d_device *device, UINT start_vertex, UINT vertex_count)
4059 TRACE("device %p, start_vertex %u, vertex_count %u.\n", device, start_vertex, vertex_count);
4061 if (!device->stateBlock->state.vertex_declaration)
4063 WARN("Called without a valid vertex declaration set.\n");
4064 return WINED3DERR_INVALIDCALL;
4067 /* The index buffer is not needed here, but restore it, otherwise it is hell to keep track of */
4068 if (device->stateBlock->state.user_stream)
4070 device_invalidate_state(device, STATE_INDEXBUFFER);
4071 device->stateBlock->state.user_stream = FALSE;
4074 if (device->stateBlock->state.load_base_vertex_index)
4076 device->stateBlock->state.load_base_vertex_index = 0;
4077 device_invalidate_state(device, STATE_BASEVERTEXINDEX);
4080 /* Account for the loading offset due to index buffers. Instead of
4081 * reloading all sources correct it with the startvertex parameter. */
4082 drawPrimitive(device, vertex_count, start_vertex, 0, NULL);
4083 return WINED3D_OK;
4086 HRESULT CDECL wined3d_device_draw_indexed_primitive(struct wined3d_device *device, UINT start_idx, UINT index_count)
4088 struct wined3d_buffer *index_buffer;
4089 UINT index_size = 2;
4090 GLuint vbo;
4091 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4093 TRACE("device %p, start_idx %u, index_count %u.\n", device, start_idx, index_count);
4095 index_buffer = device->stateBlock->state.index_buffer;
4096 if (!index_buffer)
4098 /* D3D9 returns D3DERR_INVALIDCALL when DrawIndexedPrimitive is called
4099 * without an index buffer set. (The first time at least...)
4100 * D3D8 simply dies, but I doubt it can do much harm to return
4101 * D3DERR_INVALIDCALL there as well. */
4102 WARN("Called without a valid index buffer set, returning WINED3DERR_INVALIDCALL.\n");
4103 return WINED3DERR_INVALIDCALL;
4106 if (!device->stateBlock->state.vertex_declaration)
4108 WARN("Called without a valid vertex declaration set.\n");
4109 return WINED3DERR_INVALIDCALL;
4112 if (device->stateBlock->state.user_stream)
4114 device_invalidate_state(device, STATE_INDEXBUFFER);
4115 device->stateBlock->state.user_stream = FALSE;
4117 vbo = index_buffer->buffer_object;
4119 if (device->stateBlock->state.index_format == WINED3DFMT_R16_UINT)
4120 index_size = 2;
4121 else
4122 index_size = 4;
4124 if (!gl_info->supported[ARB_DRAW_ELEMENTS_BASE_VERTEX] &&
4125 device->stateBlock->state.load_base_vertex_index != device->stateBlock->state.base_vertex_index)
4127 device->stateBlock->state.load_base_vertex_index = device->stateBlock->state.base_vertex_index;
4128 device_invalidate_state(device, STATE_BASEVERTEXINDEX);
4131 drawPrimitive(device, index_count, start_idx, index_size,
4132 vbo ? NULL : index_buffer->resource.allocatedMemory);
4134 return WINED3D_OK;
4137 HRESULT CDECL wined3d_device_draw_primitive_up(struct wined3d_device *device, UINT vertex_count,
4138 const void *stream_data, UINT stream_stride)
4140 struct wined3d_stream_state *stream;
4141 struct wined3d_buffer *vb;
4143 TRACE("device %p, vertex count %u, stream_data %p, stream_stride %u.\n",
4144 device, vertex_count, stream_data, stream_stride);
4146 if (!device->stateBlock->state.vertex_declaration)
4148 WARN("Called without a valid vertex declaration set.\n");
4149 return WINED3DERR_INVALIDCALL;
4152 /* Note in the following, it's not this type, but that's the purpose of streamIsUP */
4153 stream = &device->stateBlock->state.streams[0];
4154 vb = stream->buffer;
4155 stream->buffer = (struct wined3d_buffer *)stream_data;
4156 if (vb)
4157 wined3d_buffer_decref(vb);
4158 stream->offset = 0;
4159 stream->stride = stream_stride;
4160 device->stateBlock->state.user_stream = TRUE;
4161 if (device->stateBlock->state.load_base_vertex_index)
4163 device->stateBlock->state.load_base_vertex_index = 0;
4164 device_invalidate_state(device, STATE_BASEVERTEXINDEX);
4167 /* TODO: Only mark dirty if drawing from a different UP address */
4168 device_invalidate_state(device, STATE_STREAMSRC);
4170 drawPrimitive(device, vertex_count, 0, 0, NULL);
4172 /* MSDN specifies stream zero settings must be set to NULL */
4173 stream->buffer = NULL;
4174 stream->stride = 0;
4176 /* stream zero settings set to null at end, as per the msdn. No need to
4177 * mark dirty here, the app has to set the new stream sources or use UP
4178 * drawing again. */
4179 return WINED3D_OK;
4182 HRESULT CDECL wined3d_device_draw_indexed_primitive_up(struct wined3d_device *device,
4183 UINT index_count, const void *index_data, enum wined3d_format_id index_data_format_id,
4184 const void *stream_data, UINT stream_stride)
4186 struct wined3d_stream_state *stream;
4187 struct wined3d_buffer *vb, *ib;
4188 UINT index_size;
4190 TRACE("device %p, index_count %u, index_data %p, index_data_format %s, stream_data %p, stream_stride %u.\n",
4191 device, index_count, index_data, debug_d3dformat(index_data_format_id), stream_data, stream_stride);
4193 if (!device->stateBlock->state.vertex_declaration)
4195 WARN("(%p) : Called without a valid vertex declaration set\n", device);
4196 return WINED3DERR_INVALIDCALL;
4199 if (index_data_format_id == WINED3DFMT_R16_UINT)
4200 index_size = 2;
4201 else
4202 index_size = 4;
4204 stream = &device->stateBlock->state.streams[0];
4205 vb = stream->buffer;
4206 stream->buffer = (struct wined3d_buffer *)stream_data;
4207 if (vb)
4208 wined3d_buffer_decref(vb);
4209 stream->offset = 0;
4210 stream->stride = stream_stride;
4211 device->stateBlock->state.user_stream = TRUE;
4213 /* Set to 0 as per msdn. Do it now due to the stream source loading during drawPrimitive */
4214 device->stateBlock->state.base_vertex_index = 0;
4215 if (device->stateBlock->state.load_base_vertex_index)
4217 device->stateBlock->state.load_base_vertex_index = 0;
4218 device_invalidate_state(device, STATE_BASEVERTEXINDEX);
4220 /* Invalidate the state until we have nicer tracking of the stream source pointers */
4221 device_invalidate_state(device, STATE_STREAMSRC);
4222 device_invalidate_state(device, STATE_INDEXBUFFER);
4224 drawPrimitive(device, index_count, 0, index_size, index_data);
4226 /* MSDN specifies stream zero settings and index buffer must be set to NULL */
4227 stream->buffer = NULL;
4228 stream->stride = 0;
4229 ib = device->stateBlock->state.index_buffer;
4230 if (ib)
4232 wined3d_buffer_decref(ib);
4233 device->stateBlock->state.index_buffer = NULL;
4235 /* No need to mark the stream source state dirty here. Either the app calls UP drawing again, or it has to call
4236 * SetStreamSource to specify a vertex buffer
4239 return WINED3D_OK;
4242 HRESULT CDECL wined3d_device_draw_primitive_strided(struct wined3d_device *device,
4243 UINT vertex_count, const WineDirect3DVertexStridedData *strided_data)
4245 /* Mark the state dirty until we have nicer tracking. It's fine to change
4246 * baseVertexIndex because that call is only called by ddraw which does
4247 * not need that value. */
4248 device_invalidate_state(device, STATE_VDECL);
4249 device_invalidate_state(device, STATE_STREAMSRC);
4250 device_invalidate_state(device, STATE_INDEXBUFFER);
4252 device->stateBlock->state.base_vertex_index = 0;
4253 device->up_strided = strided_data;
4254 drawPrimitive(device, vertex_count, 0, 0, NULL);
4255 device->up_strided = NULL;
4257 /* Invalidate the states again to make sure the values from the stateblock
4258 * are properly applied in the next regular draw. Note that the application-
4259 * provided strided data has ovwritten pretty much the entire vertex and
4260 * and index stream related states */
4261 device_invalidate_state(device, STATE_VDECL);
4262 device_invalidate_state(device, STATE_STREAMSRC);
4263 device_invalidate_state(device, STATE_INDEXBUFFER);
4264 return WINED3D_OK;
4267 HRESULT CDECL wined3d_device_draw_indexed_primitive_strided(struct wined3d_device *device,
4268 UINT index_count, const WineDirect3DVertexStridedData *strided_data,
4269 UINT vertex_count, const void *index_data, enum wined3d_format_id index_data_format_id)
4271 UINT index_size = index_data_format_id == WINED3DFMT_R32_UINT ? 4 : 2;
4273 /* Mark the state dirty until we have nicer tracking
4274 * its fine to change baseVertexIndex because that call is only called by ddraw which does not need
4275 * that value.
4277 device_invalidate_state(device, STATE_VDECL);
4278 device_invalidate_state(device, STATE_STREAMSRC);
4279 device_invalidate_state(device, STATE_INDEXBUFFER);
4281 device->stateBlock->state.user_stream = TRUE;
4282 device->stateBlock->state.base_vertex_index = 0;
4283 device->up_strided = strided_data;
4284 drawPrimitive(device, index_count, 0, index_size, index_data);
4285 device->up_strided = NULL;
4287 device_invalidate_state(device, STATE_VDECL);
4288 device_invalidate_state(device, STATE_STREAMSRC);
4289 device_invalidate_state(device, STATE_INDEXBUFFER);
4290 return WINED3D_OK;
4293 /* This is a helper function for UpdateTexture, there is no UpdateVolume method in D3D. */
4294 static HRESULT device_update_volume(struct wined3d_device *device,
4295 struct wined3d_volume *src_volume, struct wined3d_volume *dst_volume)
4297 WINED3DLOCKED_BOX src;
4298 WINED3DLOCKED_BOX dst;
4299 HRESULT hr;
4301 TRACE("device %p, src_volume %p, dst_volume %p.\n",
4302 device, src_volume, dst_volume);
4304 /* TODO: Implement direct loading into the gl volume instead of using
4305 * memcpy and dirtification to improve loading performance. */
4306 hr = wined3d_volume_map(src_volume, &src, NULL, WINED3DLOCK_READONLY);
4307 if (FAILED(hr)) return hr;
4308 hr = wined3d_volume_map(dst_volume, &dst, NULL, WINED3DLOCK_DISCARD);
4309 if (FAILED(hr))
4311 wined3d_volume_unmap(src_volume);
4312 return hr;
4315 memcpy(dst.pBits, src.pBits, dst_volume->resource.size);
4317 hr = wined3d_volume_unmap(dst_volume);
4318 if (FAILED(hr))
4319 wined3d_volume_unmap(src_volume);
4320 else
4321 hr = wined3d_volume_unmap(src_volume);
4323 return hr;
4326 HRESULT CDECL wined3d_device_update_texture(struct wined3d_device *device,
4327 struct wined3d_texture *src_texture, struct wined3d_texture *dst_texture)
4329 unsigned int level_count, i;
4330 WINED3DRESOURCETYPE type;
4331 HRESULT hr;
4333 TRACE("device %p, src_texture %p, dst_texture %p.\n", device, src_texture, dst_texture);
4335 /* Verify that the source and destination textures are non-NULL. */
4336 if (!src_texture || !dst_texture)
4338 WARN("Source and destination textures must be non-NULL, returning WINED3DERR_INVALIDCALL.\n");
4339 return WINED3DERR_INVALIDCALL;
4342 if (src_texture == dst_texture)
4344 WARN("Source and destination are the same object, returning WINED3DERR_INVALIDCALL.\n");
4345 return WINED3DERR_INVALIDCALL;
4348 /* Verify that the source and destination textures are the same type. */
4349 type = src_texture->resource.resourceType;
4350 if (dst_texture->resource.resourceType != type)
4352 WARN("Source and destination have different types, returning WINED3DERR_INVALIDCALL.\n");
4353 return WINED3DERR_INVALIDCALL;
4356 /* Check that both textures have the identical numbers of levels. */
4357 level_count = wined3d_texture_get_level_count(src_texture);
4358 if (wined3d_texture_get_level_count(dst_texture) != level_count)
4360 WARN("Source and destination have different level counts, returning WINED3DERR_INVALIDCALL.\n");
4361 return WINED3DERR_INVALIDCALL;
4364 /* Make sure that the destination texture is loaded. */
4365 dst_texture->texture_ops->texture_preload(dst_texture, SRGB_RGB);
4367 /* Update every surface level of the texture. */
4368 switch (type)
4370 case WINED3DRTYPE_TEXTURE:
4372 struct wined3d_surface *src_surface;
4373 struct wined3d_surface *dst_surface;
4375 for (i = 0; i < level_count; ++i)
4377 src_surface = surface_from_resource(wined3d_texture_get_sub_resource(src_texture, i));
4378 dst_surface = surface_from_resource(wined3d_texture_get_sub_resource(dst_texture, i));
4379 hr = wined3d_device_update_surface(device, src_surface, NULL, dst_surface, NULL);
4380 if (FAILED(hr))
4382 WARN("Failed to update surface, hr %#x.\n", hr);
4383 return hr;
4386 break;
4389 case WINED3DRTYPE_CUBETEXTURE:
4391 struct wined3d_surface *src_surface;
4392 struct wined3d_surface *dst_surface;
4394 for (i = 0; i < level_count * 6; ++i)
4396 src_surface = surface_from_resource(wined3d_texture_get_sub_resource(src_texture, i));
4397 dst_surface = surface_from_resource(wined3d_texture_get_sub_resource(dst_texture, i));
4398 hr = wined3d_device_update_surface(device, src_surface, NULL, dst_surface, NULL);
4399 if (FAILED(hr))
4401 WARN("Failed to update surface, hr %#x.\n", hr);
4402 return hr;
4405 break;
4408 case WINED3DRTYPE_VOLUMETEXTURE:
4410 for (i = 0; i < level_count; ++i)
4412 hr = device_update_volume(device,
4413 volume_from_resource(wined3d_texture_get_sub_resource(src_texture, i)),
4414 volume_from_resource(wined3d_texture_get_sub_resource(dst_texture, i)));
4415 if (FAILED(hr))
4417 WARN("Failed to update volume, hr %#x.\n", hr);
4418 return hr;
4421 break;
4424 default:
4425 FIXME("Unsupported texture type %#x.\n", type);
4426 return WINED3DERR_INVALIDCALL;
4429 return WINED3D_OK;
4432 HRESULT CDECL wined3d_device_get_front_buffer_data(struct wined3d_device *device,
4433 UINT swapchain_idx, struct wined3d_surface *dst_surface)
4435 struct wined3d_swapchain *swapchain;
4436 HRESULT hr;
4438 TRACE("device %p, swapchain_idx %u, dst_surface %p.\n", device, swapchain_idx, dst_surface);
4440 hr = wined3d_device_get_swapchain(device, swapchain_idx, &swapchain);
4441 if (FAILED(hr)) return hr;
4443 hr = wined3d_swapchain_get_front_buffer_data(swapchain, dst_surface);
4444 wined3d_swapchain_decref(swapchain);
4446 return hr;
4449 HRESULT CDECL wined3d_device_validate_device(struct wined3d_device *device, DWORD *num_passes)
4451 const struct wined3d_state *state = &device->stateBlock->state;
4452 struct wined3d_texture *texture;
4453 DWORD i;
4455 TRACE("device %p, num_passes %p.\n", device, num_passes);
4457 for (i = 0; i < MAX_COMBINED_SAMPLERS; ++i)
4459 if (state->sampler_states[i][WINED3DSAMP_MINFILTER] == WINED3DTEXF_NONE)
4461 WARN("Sampler state %u has minfilter D3DTEXF_NONE, returning D3DERR_UNSUPPORTEDTEXTUREFILTER\n", i);
4462 return WINED3DERR_UNSUPPORTEDTEXTUREFILTER;
4464 if (state->sampler_states[i][WINED3DSAMP_MAGFILTER] == WINED3DTEXF_NONE)
4466 WARN("Sampler state %u has magfilter D3DTEXF_NONE, returning D3DERR_UNSUPPORTEDTEXTUREFILTER\n", i);
4467 return WINED3DERR_UNSUPPORTEDTEXTUREFILTER;
4470 texture = state->textures[i];
4471 if (!texture || texture->resource.format->flags & WINED3DFMT_FLAG_FILTERING) continue;
4473 if (state->sampler_states[i][WINED3DSAMP_MAGFILTER] != WINED3DTEXF_POINT)
4475 WARN("Non-filterable texture and mag filter enabled on samper %u, returning E_FAIL\n", i);
4476 return E_FAIL;
4478 if (state->sampler_states[i][WINED3DSAMP_MINFILTER] != WINED3DTEXF_POINT)
4480 WARN("Non-filterable texture and min filter enabled on samper %u, returning E_FAIL\n", i);
4481 return E_FAIL;
4483 if (state->sampler_states[i][WINED3DSAMP_MIPFILTER] != WINED3DTEXF_NONE
4484 && state->sampler_states[i][WINED3DSAMP_MIPFILTER] != WINED3DTEXF_POINT)
4486 WARN("Non-filterable texture and mip filter enabled on samper %u, returning E_FAIL\n", i);
4487 return E_FAIL;
4491 if (state->render_states[WINED3DRS_ZENABLE] || state->render_states[WINED3DRS_ZWRITEENABLE] ||
4492 state->render_states[WINED3DRS_STENCILENABLE])
4494 struct wined3d_surface *ds = device->fb.depth_stencil;
4495 struct wined3d_surface *target = device->fb.render_targets[0];
4497 if(ds && target
4498 && (ds->resource.width < target->resource.width || ds->resource.height < target->resource.height))
4500 WARN("Depth stencil is smaller than the color buffer, returning D3DERR_CONFLICTINGRENDERSTATE\n");
4501 return WINED3DERR_CONFLICTINGRENDERSTATE;
4505 /* return a sensible default */
4506 *num_passes = 1;
4508 TRACE("returning D3D_OK\n");
4509 return WINED3D_OK;
4512 static void dirtify_p8_texture_samplers(struct wined3d_device *device)
4514 UINT i;
4516 for (i = 0; i < MAX_COMBINED_SAMPLERS; ++i)
4518 struct wined3d_texture *texture = device->stateBlock->state.textures[i];
4519 if (texture && (texture->resource.format->id == WINED3DFMT_P8_UINT
4520 || texture->resource.format->id == WINED3DFMT_P8_UINT_A8_UNORM))
4521 device_invalidate_state(device, STATE_SAMPLER(i));
4525 HRESULT CDECL wined3d_device_set_palette_entries(struct wined3d_device *device,
4526 UINT palette_idx, const PALETTEENTRY *entries)
4528 UINT i;
4530 TRACE("device %p, palette_idx %u, entries %p.\n", device, palette_idx, entries);
4532 if (palette_idx >= MAX_PALETTES)
4534 WARN("Invalid palette index %u.\n", palette_idx);
4535 return WINED3DERR_INVALIDCALL;
4538 if (palette_idx >= device->palette_count)
4540 UINT new_size = device->palette_count;
4541 PALETTEENTRY **palettes;
4545 new_size *= 2;
4546 } while (palette_idx >= new_size);
4547 palettes = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, device->palettes, sizeof(*palettes) * new_size);
4548 if (!palettes)
4550 ERR("Out of memory!\n");
4551 return E_OUTOFMEMORY;
4553 device->palettes = palettes;
4554 device->palette_count = new_size;
4557 if (!device->palettes[palette_idx])
4559 device->palettes[palette_idx] = HeapAlloc(GetProcessHeap(), 0, sizeof(PALETTEENTRY) * 256);
4560 if (!device->palettes[palette_idx])
4562 ERR("Out of memory!\n");
4563 return E_OUTOFMEMORY;
4567 for (i = 0; i < 256; ++i)
4569 device->palettes[palette_idx][i].peRed = entries[i].peRed;
4570 device->palettes[palette_idx][i].peGreen = entries[i].peGreen;
4571 device->palettes[palette_idx][i].peBlue = entries[i].peBlue;
4572 device->palettes[palette_idx][i].peFlags = entries[i].peFlags;
4575 if (palette_idx == device->currentPalette)
4576 dirtify_p8_texture_samplers(device);
4578 return WINED3D_OK;
4581 HRESULT CDECL wined3d_device_get_palette_entries(struct wined3d_device *device,
4582 UINT palette_idx, PALETTEENTRY *entries)
4584 UINT i;
4586 TRACE("device %p, palette_idx %u, entries %p.\n", device, palette_idx, entries);
4588 if (palette_idx >= device->palette_count || !device->palettes[palette_idx])
4590 /* What happens in such situation isn't documented; Native seems to
4591 * silently abort on such conditions. */
4592 WARN("Invalid palette index %u.\n", palette_idx);
4593 return WINED3DERR_INVALIDCALL;
4596 for (i = 0; i < 256; ++i)
4598 entries[i].peRed = device->palettes[palette_idx][i].peRed;
4599 entries[i].peGreen = device->palettes[palette_idx][i].peGreen;
4600 entries[i].peBlue = device->palettes[palette_idx][i].peBlue;
4601 entries[i].peFlags = device->palettes[palette_idx][i].peFlags;
4604 return WINED3D_OK;
4607 HRESULT CDECL wined3d_device_set_current_texture_palette(struct wined3d_device *device, UINT palette_idx)
4609 TRACE("device %p, palette_idx %u.\n", device, palette_idx);
4611 /* Native appears to silently abort on attempt to make an uninitialized
4612 * palette current and render. (tested with reference rasterizer). */
4613 if (palette_idx >= device->palette_count || !device->palettes[palette_idx])
4615 WARN("Invalid palette index %u.\n", palette_idx);
4616 return WINED3DERR_INVALIDCALL;
4619 /* TODO: stateblocks? */
4620 if (device->currentPalette != palette_idx)
4622 device->currentPalette = palette_idx;
4623 dirtify_p8_texture_samplers(device);
4626 return WINED3D_OK;
4629 HRESULT CDECL wined3d_device_get_current_texture_palette(struct wined3d_device *device, UINT *palette_idx)
4631 TRACE("device %p, palette_idx %p.\n", device, palette_idx);
4633 if (!palette_idx)
4634 return WINED3DERR_INVALIDCALL;
4636 *palette_idx = device->currentPalette;
4638 return WINED3D_OK;
4641 HRESULT CDECL wined3d_device_set_software_vertex_processing(struct wined3d_device *device, BOOL software)
4643 static BOOL warned;
4645 TRACE("device %p, software %#x.\n", device, software);
4647 if (!warned)
4649 FIXME("device %p, software %#x stub!\n", device, software);
4650 warned = TRUE;
4653 device->softwareVertexProcessing = software;
4655 return WINED3D_OK;
4658 BOOL CDECL wined3d_device_get_software_vertex_processing(struct wined3d_device *device)
4660 static BOOL warned;
4662 TRACE("device %p.\n", device);
4664 if (!warned)
4666 TRACE("device %p stub!\n", device);
4667 warned = TRUE;
4670 return device->softwareVertexProcessing;
4673 HRESULT CDECL wined3d_device_get_raster_status(struct wined3d_device *device,
4674 UINT swapchain_idx, WINED3DRASTER_STATUS *raster_status)
4676 struct wined3d_swapchain *swapchain;
4677 HRESULT hr;
4679 TRACE("device %p, swapchain_idx %u, raster_status %p.\n",
4680 device, swapchain_idx, raster_status);
4682 hr = wined3d_device_get_swapchain(device, swapchain_idx, &swapchain);
4683 if (FAILED(hr))
4685 WARN("Failed to get swapchain %u, hr %#x.\n", swapchain_idx, hr);
4686 return hr;
4689 hr = wined3d_swapchain_get_raster_status(swapchain, raster_status);
4690 wined3d_swapchain_decref(swapchain);
4691 if (FAILED(hr))
4693 WARN("Failed to get raster status, hr %#x.\n", hr);
4694 return hr;
4697 return WINED3D_OK;
4700 HRESULT CDECL wined3d_device_set_npatch_mode(struct wined3d_device *device, float segments)
4702 static BOOL warned;
4704 TRACE("device %p, segments %.8e.\n", device, segments);
4706 if (segments != 0.0f)
4708 if (!warned)
4710 FIXME("device %p, segments %.8e stub!\n", device, segments);
4711 warned = TRUE;
4715 return WINED3D_OK;
4718 float CDECL wined3d_device_get_npatch_mode(struct wined3d_device *device)
4720 static BOOL warned;
4722 TRACE("device %p.\n", device);
4724 if (!warned)
4726 FIXME("device %p stub!\n", device);
4727 warned = TRUE;
4730 return 0.0f;
4733 static inline void invalidate_active_texture(struct wined3d_device *device, struct wined3d_context *context)
4735 DWORD sampler = device->rev_tex_unit_map[context->active_texture];
4736 if (sampler != WINED3D_UNMAPPED_STAGE)
4737 context_invalidate_state(context, STATE_SAMPLER(sampler));
4740 HRESULT CDECL wined3d_device_update_surface(struct wined3d_device *device,
4741 struct wined3d_surface *src_surface, const RECT *src_rect,
4742 struct wined3d_surface *dst_surface, const POINT *dst_point)
4744 const struct wined3d_format *src_format;
4745 const struct wined3d_format *dst_format;
4746 const struct wined3d_gl_info *gl_info;
4747 struct wined3d_context *context;
4748 struct wined3d_bo_address data;
4749 struct wined3d_format format;
4750 UINT update_w, update_h;
4751 CONVERT_TYPES convert;
4752 UINT dst_w, dst_h;
4753 UINT src_w, src_h;
4754 POINT p;
4755 RECT r;
4757 TRACE("device %p, src_surface %p, src_rect %s, dst_surface %p, dst_point %s.\n",
4758 device, src_surface, wine_dbgstr_rect(src_rect),
4759 dst_surface, wine_dbgstr_point(dst_point));
4761 if (src_surface->resource.pool != WINED3DPOOL_SYSTEMMEM || dst_surface->resource.pool != WINED3DPOOL_DEFAULT)
4763 WARN("source %p must be SYSTEMMEM and dest %p must be DEFAULT, returning WINED3DERR_INVALIDCALL\n",
4764 src_surface, dst_surface);
4765 return WINED3DERR_INVALIDCALL;
4768 src_format = src_surface->resource.format;
4769 dst_format = dst_surface->resource.format;
4771 if (src_format->id != dst_format->id)
4773 WARN("Source and destination surfaces should have the same format.\n");
4774 return WINED3DERR_INVALIDCALL;
4777 if (!dst_point)
4779 p.x = 0;
4780 p.y = 0;
4781 dst_point = &p;
4783 else if (dst_point->x < 0 || dst_point->y < 0)
4785 WARN("Invalid destination point.\n");
4786 return WINED3DERR_INVALIDCALL;
4789 if (!src_rect)
4791 r.left = 0;
4792 r.top = 0;
4793 r.right = src_surface->resource.width;
4794 r.bottom = src_surface->resource.height;
4795 src_rect = &r;
4797 else if (src_rect->left < 0 || src_rect->left >= src_rect->right
4798 || src_rect->top < 0 || src_rect->top >= src_rect->bottom)
4800 WARN("Invalid source rectangle.\n");
4801 return WINED3DERR_INVALIDCALL;
4804 src_w = src_surface->resource.width;
4805 src_h = src_surface->resource.height;
4807 dst_w = dst_surface->resource.width;
4808 dst_h = dst_surface->resource.height;
4810 update_w = src_rect->right - src_rect->left;
4811 update_h = src_rect->bottom - src_rect->top;
4813 if (update_w > dst_w || dst_point->x > dst_w - update_w
4814 || update_h > dst_h || dst_point->y > dst_h - update_h)
4816 WARN("Destination out of bounds.\n");
4817 return WINED3DERR_INVALIDCALL;
4820 /* NPOT block sizes would be silly. */
4821 if ((src_format->flags & WINED3DFMT_FLAG_COMPRESSED)
4822 && ((update_w & (src_format->block_width - 1) || update_h & (src_format->block_height - 1))
4823 && (src_w != update_w || dst_w != update_w || src_h != update_h || dst_h != update_h)))
4825 WARN("Update rect not block-aligned.\n");
4826 return WINED3DERR_INVALIDCALL;
4829 /* This call loads the OpenGL surface directly, instead of copying the
4830 * surface to the destination's sysmem copy. If surface conversion is
4831 * needed, use BltFast instead to copy in sysmem and use regular surface
4832 * loading. */
4833 d3dfmt_get_conv(dst_surface, FALSE, TRUE, &format, &convert);
4834 if (convert != NO_CONVERSION || format.convert)
4835 return wined3d_surface_bltfast(dst_surface, dst_point->x, dst_point->y, src_surface, src_rect, 0);
4837 context = context_acquire(device, NULL);
4838 gl_info = context->gl_info;
4840 /* Only load the surface for partial updates. For newly allocated texture
4841 * the texture wouldn't be the current location, and we'd upload zeroes
4842 * just to overwrite them again. */
4843 if (update_w == dst_w && update_h == dst_h)
4844 surface_prepare_texture(dst_surface, context, FALSE);
4845 else
4846 surface_load_location(dst_surface, SFLAG_INTEXTURE, NULL);
4847 surface_bind(dst_surface, context, FALSE);
4849 data.buffer_object = 0;
4850 data.addr = src_surface->resource.allocatedMemory;
4852 if (!data.addr)
4853 ERR("Source surface has no allocated memory, but should be a sysmem surface.\n");
4855 surface_upload_data(dst_surface, gl_info, src_format, src_rect, src_w, dst_point, FALSE, &data);
4857 invalidate_active_texture(device, context);
4859 context_release(context);
4861 surface_modify_location(dst_surface, SFLAG_INTEXTURE, TRUE);
4862 return WINED3D_OK;
4865 HRESULT CDECL wined3d_device_draw_rect_patch(struct wined3d_device *device, UINT handle,
4866 const float *num_segs, const WINED3DRECTPATCH_INFO *rect_patch_info)
4868 struct WineD3DRectPatch *patch;
4869 GLenum old_primitive_type;
4870 unsigned int i;
4871 struct list *e;
4872 BOOL found;
4874 TRACE("device %p, handle %#x, num_segs %p, rect_patch_info %p.\n",
4875 device, handle, num_segs, rect_patch_info);
4877 if (!(handle || rect_patch_info))
4879 /* TODO: Write a test for the return value, thus the FIXME */
4880 FIXME("Both handle and rect_patch_info are NULL.\n");
4881 return WINED3DERR_INVALIDCALL;
4884 if (handle)
4886 i = PATCHMAP_HASHFUNC(handle);
4887 found = FALSE;
4888 LIST_FOR_EACH(e, &device->patches[i])
4890 patch = LIST_ENTRY(e, struct WineD3DRectPatch, entry);
4891 if (patch->Handle == handle)
4893 found = TRUE;
4894 break;
4898 if (!found)
4900 TRACE("Patch does not exist. Creating a new one\n");
4901 patch = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*patch));
4902 patch->Handle = handle;
4903 list_add_head(&device->patches[i], &patch->entry);
4904 } else {
4905 TRACE("Found existing patch %p\n", patch);
4908 else
4910 /* Since opengl does not load tesselated vertex attributes into numbered vertex
4911 * attributes we have to tesselate, read back, and draw. This needs a patch
4912 * management structure instance. Create one.
4914 * A possible improvement is to check if a vertex shader is used, and if not directly
4915 * draw the patch.
4917 FIXME("Drawing an uncached patch. This is slow\n");
4918 patch = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*patch));
4921 if (num_segs[0] != patch->numSegs[0] || num_segs[1] != patch->numSegs[1]
4922 || num_segs[2] != patch->numSegs[2] || num_segs[3] != patch->numSegs[3]
4923 || (rect_patch_info && memcmp(rect_patch_info, &patch->RectPatchInfo, sizeof(*rect_patch_info))))
4925 HRESULT hr;
4926 TRACE("Tesselation density or patch info changed, retesselating\n");
4928 if (rect_patch_info)
4929 patch->RectPatchInfo = *rect_patch_info;
4931 patch->numSegs[0] = num_segs[0];
4932 patch->numSegs[1] = num_segs[1];
4933 patch->numSegs[2] = num_segs[2];
4934 patch->numSegs[3] = num_segs[3];
4936 hr = tesselate_rectpatch(device, patch);
4937 if (FAILED(hr))
4939 WARN("Patch tesselation failed.\n");
4941 /* Do not release the handle to store the params of the patch */
4942 if (!handle)
4943 HeapFree(GetProcessHeap(), 0, patch);
4945 return hr;
4949 old_primitive_type = device->stateBlock->state.gl_primitive_type;
4950 device->stateBlock->state.gl_primitive_type = GL_TRIANGLES;
4951 wined3d_device_draw_primitive_strided(device, patch->numSegs[0] * patch->numSegs[1] * 2 * 3, &patch->strided);
4952 device->stateBlock->state.gl_primitive_type = old_primitive_type;
4954 /* Destroy uncached patches */
4955 if (!handle)
4957 HeapFree(GetProcessHeap(), 0, patch->mem);
4958 HeapFree(GetProcessHeap(), 0, patch);
4960 return WINED3D_OK;
4963 HRESULT CDECL wined3d_device_draw_tri_patch(struct wined3d_device *device, UINT handle,
4964 const float *segment_count, const WINED3DTRIPATCH_INFO *patch_info)
4966 FIXME("device %p, handle %#x, segment_count %p, patch_info %p stub!\n",
4967 device, handle, segment_count, patch_info);
4969 return WINED3D_OK;
4972 HRESULT CDECL wined3d_device_delete_patch(struct wined3d_device *device, UINT handle)
4974 struct WineD3DRectPatch *patch;
4975 struct list *e;
4976 int i;
4978 TRACE("device %p, handle %#x.\n", device, handle);
4980 i = PATCHMAP_HASHFUNC(handle);
4981 LIST_FOR_EACH(e, &device->patches[i])
4983 patch = LIST_ENTRY(e, struct WineD3DRectPatch, entry);
4984 if (patch->Handle == handle)
4986 TRACE("Deleting patch %p\n", patch);
4987 list_remove(&patch->entry);
4988 HeapFree(GetProcessHeap(), 0, patch->mem);
4989 HeapFree(GetProcessHeap(), 0, patch);
4990 return WINED3D_OK;
4994 /* TODO: Write a test for the return value */
4995 FIXME("Attempt to destroy nonexistent patch\n");
4996 return WINED3DERR_INVALIDCALL;
4999 /* Do not call while under the GL lock. */
5000 HRESULT CDECL wined3d_device_color_fill(struct wined3d_device *device,
5001 struct wined3d_surface *surface, const RECT *rect, const WINED3DCOLORVALUE *color)
5003 RECT r;
5005 TRACE("device %p, surface %p, rect %s, color {%.8e, %.8e, %.8e, %.8e}.\n",
5006 device, surface, wine_dbgstr_rect(rect),
5007 color->r, color->g, color->b, color->a);
5009 if (surface->resource.pool != WINED3DPOOL_DEFAULT && surface->resource.pool != WINED3DPOOL_SYSTEMMEM)
5011 FIXME("call to colorfill with non WINED3DPOOL_DEFAULT or WINED3DPOOL_SYSTEMMEM surface\n");
5012 return WINED3DERR_INVALIDCALL;
5015 if (!rect)
5017 SetRect(&r, 0, 0, surface->resource.width, surface->resource.height);
5018 rect = &r;
5021 return surface_color_fill(surface, rect, color);
5024 /* Do not call while under the GL lock. */
5025 void CDECL wined3d_device_clear_rendertarget_view(struct wined3d_device *device,
5026 struct wined3d_rendertarget_view *rendertarget_view, const WINED3DCOLORVALUE *color)
5028 struct wined3d_resource *resource;
5029 HRESULT hr;
5030 RECT rect;
5032 resource = rendertarget_view->resource;
5033 if (resource->resourceType != WINED3DRTYPE_SURFACE)
5035 FIXME("Only supported on surface resources\n");
5036 return;
5039 SetRect(&rect, 0, 0, resource->width, resource->height);
5040 hr = surface_color_fill(surface_from_resource(resource), &rect, color);
5041 if (FAILED(hr)) ERR("Color fill failed, hr %#x.\n", hr);
5044 HRESULT CDECL wined3d_device_get_render_target(struct wined3d_device *device,
5045 UINT render_target_idx, struct wined3d_surface **render_target)
5047 TRACE("device %p, render_target_idx %u, render_target %p.\n",
5048 device, render_target_idx, render_target);
5050 if (render_target_idx >= device->adapter->gl_info.limits.buffers)
5052 WARN("Only %u render targets are supported.\n", device->adapter->gl_info.limits.buffers);
5053 return WINED3DERR_INVALIDCALL;
5056 *render_target = device->fb.render_targets[render_target_idx];
5057 if (*render_target)
5058 wined3d_surface_incref(*render_target);
5060 TRACE("Returning render target %p.\n", *render_target);
5062 return WINED3D_OK;
5065 HRESULT CDECL wined3d_device_get_depth_stencil(struct wined3d_device *device, struct wined3d_surface **depth_stencil)
5067 TRACE("device %p, depth_stencil %p.\n", device, depth_stencil);
5069 *depth_stencil = device->fb.depth_stencil;
5070 TRACE("Returning depth/stencil surface %p.\n", *depth_stencil);
5072 if (!*depth_stencil)
5073 return WINED3DERR_NOTFOUND;
5075 wined3d_surface_incref(*depth_stencil);
5077 return WINED3D_OK;
5080 HRESULT CDECL wined3d_device_set_render_target(struct wined3d_device *device,
5081 UINT render_target_idx, struct wined3d_surface *render_target, BOOL set_viewport)
5083 struct wined3d_surface *prev;
5085 TRACE("device %p, render_target_idx %u, render_target %p, set_viewport %#x.\n",
5086 device, render_target_idx, render_target, set_viewport);
5088 if (render_target_idx >= device->adapter->gl_info.limits.buffers)
5090 WARN("Only %u render targets are supported.\n", device->adapter->gl_info.limits.buffers);
5091 return WINED3DERR_INVALIDCALL;
5094 prev = device->fb.render_targets[render_target_idx];
5095 if (render_target == prev)
5097 TRACE("Trying to do a NOP SetRenderTarget operation.\n");
5098 return WINED3D_OK;
5101 /* Render target 0 can't be set to NULL. */
5102 if (!render_target && !render_target_idx)
5104 WARN("Trying to set render target 0 to NULL.\n");
5105 return WINED3DERR_INVALIDCALL;
5108 if (render_target && !(render_target->resource.usage & WINED3DUSAGE_RENDERTARGET))
5110 FIXME("Surface %p doesn't have render target usage.\n", render_target);
5111 return WINED3DERR_INVALIDCALL;
5114 if (render_target)
5115 wined3d_surface_incref(render_target);
5116 device->fb.render_targets[render_target_idx] = render_target;
5117 /* Release after the assignment, to prevent device_resource_released()
5118 * from seeing the surface as still in use. */
5119 if (prev)
5120 wined3d_surface_decref(prev);
5122 /* Render target 0 is special. */
5123 if (!render_target_idx && set_viewport)
5125 /* Set the viewport and scissor rectangles, if requested. Tests show
5126 * that stateblock recording is ignored, the change goes directly
5127 * into the primary stateblock. */
5128 device->stateBlock->state.viewport.Height = device->fb.render_targets[0]->resource.height;
5129 device->stateBlock->state.viewport.Width = device->fb.render_targets[0]->resource.width;
5130 device->stateBlock->state.viewport.X = 0;
5131 device->stateBlock->state.viewport.Y = 0;
5132 device->stateBlock->state.viewport.MaxZ = 1.0f;
5133 device->stateBlock->state.viewport.MinZ = 0.0f;
5134 device_invalidate_state(device, STATE_VIEWPORT);
5136 device->stateBlock->state.scissor_rect.top = 0;
5137 device->stateBlock->state.scissor_rect.left = 0;
5138 device->stateBlock->state.scissor_rect.right = device->stateBlock->state.viewport.Width;
5139 device->stateBlock->state.scissor_rect.bottom = device->stateBlock->state.viewport.Height;
5140 device_invalidate_state(device, STATE_SCISSORRECT);
5143 device_invalidate_state(device, STATE_FRAMEBUFFER);
5145 return WINED3D_OK;
5148 HRESULT CDECL wined3d_device_set_depth_stencil(struct wined3d_device *device, struct wined3d_surface *depth_stencil)
5150 struct wined3d_surface *prev = device->fb.depth_stencil;
5152 TRACE("device %p, depth_stencil %p, old depth_stencil %p.\n",
5153 device, depth_stencil, prev);
5155 if (prev == depth_stencil)
5157 TRACE("Trying to do a NOP SetRenderTarget operation.\n");
5158 return WINED3D_OK;
5161 if (prev)
5163 if (device->swapchains[0]->presentParms.Flags & WINED3DPRESENTFLAG_DISCARD_DEPTHSTENCIL
5164 || prev->flags & SFLAG_DISCARD)
5166 surface_modify_ds_location(prev, SFLAG_DS_DISCARDED,
5167 prev->resource.width, prev->resource.height);
5168 if (prev == device->onscreen_depth_stencil)
5170 wined3d_surface_decref(device->onscreen_depth_stencil);
5171 device->onscreen_depth_stencil = NULL;
5176 device->fb.depth_stencil = depth_stencil;
5177 if (depth_stencil)
5178 wined3d_surface_incref(depth_stencil);
5180 if (!prev != !depth_stencil)
5182 /* Swapping NULL / non NULL depth stencil affects the depth and tests */
5183 device_invalidate_state(device, STATE_RENDER(WINED3DRS_ZENABLE));
5184 device_invalidate_state(device, STATE_RENDER(WINED3DRS_STENCILENABLE));
5185 device_invalidate_state(device, STATE_RENDER(WINED3DRS_STENCILWRITEMASK));
5186 device_invalidate_state(device, STATE_RENDER(WINED3DRS_DEPTHBIAS));
5188 else if (prev && prev->resource.format->depth_size != depth_stencil->resource.format->depth_size)
5190 device_invalidate_state(device, STATE_RENDER(WINED3DRS_DEPTHBIAS));
5192 if (prev)
5193 wined3d_surface_decref(prev);
5195 device_invalidate_state(device, STATE_FRAMEBUFFER);
5197 return WINED3D_OK;
5200 HRESULT CDECL wined3d_device_set_cursor_properties(struct wined3d_device *device,
5201 UINT x_hotspot, UINT y_hotspot, struct wined3d_surface *cursor_image)
5203 WINED3DLOCKED_RECT lockedRect;
5205 TRACE("device %p, x_hotspot %u, y_hotspot %u, cursor_image %p.\n",
5206 device, x_hotspot, y_hotspot, cursor_image);
5208 /* some basic validation checks */
5209 if (device->cursorTexture)
5211 struct wined3d_context *context = context_acquire(device, NULL);
5212 ENTER_GL();
5213 glDeleteTextures(1, &device->cursorTexture);
5214 LEAVE_GL();
5215 context_release(context);
5216 device->cursorTexture = 0;
5219 if (cursor_image)
5221 WINED3DLOCKED_RECT rect;
5223 /* MSDN: Cursor must be A8R8G8B8 */
5224 if (cursor_image->resource.format->id != WINED3DFMT_B8G8R8A8_UNORM)
5226 WARN("surface %p has an invalid format.\n", cursor_image);
5227 return WINED3DERR_INVALIDCALL;
5230 /* MSDN: Cursor must be smaller than the display mode */
5231 if (cursor_image->resource.width > device->ddraw_width
5232 || cursor_image->resource.height > device->ddraw_height)
5234 WARN("Surface %p dimensions are %ux%u, but screen dimensions are %ux%u.\n",
5235 cursor_image, cursor_image->resource.width, cursor_image->resource.height,
5236 device->ddraw_width, device->ddraw_height);
5237 return WINED3DERR_INVALIDCALL;
5240 /* TODO: MSDN: Cursor sizes must be a power of 2 */
5242 /* Do not store the surface's pointer because the application may
5243 * release it after setting the cursor image. Windows doesn't
5244 * addref the set surface, so we can't do this either without
5245 * creating circular refcount dependencies. Copy out the gl texture
5246 * instead. */
5247 device->cursorWidth = cursor_image->resource.width;
5248 device->cursorHeight = cursor_image->resource.height;
5249 if (SUCCEEDED(wined3d_surface_map(cursor_image, &rect, NULL, WINED3DLOCK_READONLY)))
5251 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
5252 const struct wined3d_format *format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
5253 struct wined3d_context *context;
5254 char *mem, *bits = rect.pBits;
5255 GLint intfmt = format->glInternal;
5256 GLint gl_format = format->glFormat;
5257 GLint type = format->glType;
5258 INT height = device->cursorHeight;
5259 INT width = device->cursorWidth;
5260 INT bpp = format->byte_count;
5261 INT i;
5263 /* Reformat the texture memory (pitch and width can be
5264 * different) */
5265 mem = HeapAlloc(GetProcessHeap(), 0, width * height * bpp);
5266 for(i = 0; i < height; i++)
5267 memcpy(&mem[width * bpp * i], &bits[rect.Pitch * i], width * bpp);
5268 wined3d_surface_unmap(cursor_image);
5270 context = context_acquire(device, NULL);
5272 ENTER_GL();
5274 if (gl_info->supported[APPLE_CLIENT_STORAGE])
5276 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE);
5277 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE)");
5280 invalidate_active_texture(device, context);
5281 /* Create a new cursor texture */
5282 glGenTextures(1, &device->cursorTexture);
5283 checkGLcall("glGenTextures");
5284 glBindTexture(GL_TEXTURE_2D, device->cursorTexture);
5285 checkGLcall("glBindTexture");
5286 /* Copy the bitmap memory into the cursor texture */
5287 glTexImage2D(GL_TEXTURE_2D, 0, intfmt, width, height, 0, gl_format, type, mem);
5288 checkGLcall("glTexImage2D");
5289 HeapFree(GetProcessHeap(), 0, mem);
5291 if (gl_info->supported[APPLE_CLIENT_STORAGE])
5293 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
5294 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
5297 LEAVE_GL();
5299 context_release(context);
5301 else
5303 FIXME("A cursor texture was not returned.\n");
5304 device->cursorTexture = 0;
5307 if (cursor_image->resource.width == 32 && cursor_image->resource.height == 32)
5309 /* Draw a hardware cursor */
5310 ICONINFO cursorInfo;
5311 HCURSOR cursor;
5312 /* Create and clear maskBits because it is not needed for
5313 * 32-bit cursors. 32x32 bits split into 32-bit chunks == 32
5314 * chunks. */
5315 DWORD *maskBits = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
5316 (cursor_image->resource.width * cursor_image->resource.height / 8));
5317 wined3d_surface_map(cursor_image, &lockedRect, NULL,
5318 WINED3DLOCK_NO_DIRTY_UPDATE | WINED3DLOCK_READONLY);
5319 TRACE("width: %u height: %u.\n", cursor_image->resource.width, cursor_image->resource.height);
5321 cursorInfo.fIcon = FALSE;
5322 cursorInfo.xHotspot = x_hotspot;
5323 cursorInfo.yHotspot = y_hotspot;
5324 cursorInfo.hbmMask = CreateBitmap(cursor_image->resource.width, cursor_image->resource.height,
5325 1, 1, maskBits);
5326 cursorInfo.hbmColor = CreateBitmap(cursor_image->resource.width, cursor_image->resource.height,
5327 1, 32, lockedRect.pBits);
5328 wined3d_surface_unmap(cursor_image);
5329 /* Create our cursor and clean up. */
5330 cursor = CreateIconIndirect(&cursorInfo);
5331 if (cursorInfo.hbmMask) DeleteObject(cursorInfo.hbmMask);
5332 if (cursorInfo.hbmColor) DeleteObject(cursorInfo.hbmColor);
5333 if (device->hardwareCursor) DestroyCursor(device->hardwareCursor);
5334 device->hardwareCursor = cursor;
5335 if (device->bCursorVisible) SetCursor( cursor );
5336 HeapFree(GetProcessHeap(), 0, maskBits);
5340 device->xHotSpot = x_hotspot;
5341 device->yHotSpot = y_hotspot;
5342 return WINED3D_OK;
5345 void CDECL wined3d_device_set_cursor_position(struct wined3d_device *device,
5346 int x_screen_space, int y_screen_space, DWORD flags)
5348 TRACE("device %p, x %d, y %d, flags %#x.\n",
5349 device, x_screen_space, y_screen_space, flags);
5351 device->xScreenSpace = x_screen_space;
5352 device->yScreenSpace = y_screen_space;
5354 /* switch to the software cursor if position diverges from the hardware one */
5355 if (device->hardwareCursor)
5357 POINT pt;
5358 GetCursorPos( &pt );
5359 if (x_screen_space != pt.x || y_screen_space != pt.y)
5361 if (device->bCursorVisible) SetCursor( NULL );
5362 DestroyCursor( device->hardwareCursor );
5363 device->hardwareCursor = 0;
5368 BOOL CDECL wined3d_device_show_cursor(struct wined3d_device *device, BOOL show)
5370 BOOL oldVisible = device->bCursorVisible;
5372 TRACE("device %p, show %#x.\n", device, show);
5375 * When ShowCursor is first called it should make the cursor appear at the OS's last
5376 * known cursor position.
5378 if (show && !oldVisible)
5380 POINT pt;
5381 GetCursorPos(&pt);
5382 device->xScreenSpace = pt.x;
5383 device->yScreenSpace = pt.y;
5386 if (device->hardwareCursor)
5388 device->bCursorVisible = show;
5389 if (show)
5390 SetCursor(device->hardwareCursor);
5391 else
5392 SetCursor(NULL);
5394 else
5396 if (device->cursorTexture)
5397 device->bCursorVisible = show;
5400 return oldVisible;
5403 void CDECL wined3d_device_evict_managed_resources(struct wined3d_device *device)
5405 struct wined3d_resource *resource, *cursor;
5407 TRACE("device %p.\n", device);
5409 LIST_FOR_EACH_ENTRY_SAFE(resource, cursor, &device->resources, struct wined3d_resource, resource_list_entry)
5411 TRACE("Checking resource %p for eviction.\n", resource);
5413 if (resource->pool == WINED3DPOOL_MANAGED)
5415 TRACE("Evicting %p.\n", resource);
5416 resource->resource_ops->resource_unload(resource);
5420 /* Invalidate stream sources, the buffer(s) may have been evicted. */
5421 device_invalidate_state(device, STATE_STREAMSRC);
5424 static HRESULT updateSurfaceDesc(struct wined3d_surface *surface,
5425 const WINED3DPRESENT_PARAMETERS *pPresentationParameters)
5427 struct wined3d_device *device = surface->resource.device;
5428 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
5430 /* Reallocate proper memory for the front and back buffer and adjust their sizes */
5431 if (surface->flags & SFLAG_DIBSECTION)
5433 /* Release the DC */
5434 SelectObject(surface->hDC, surface->dib.holdbitmap);
5435 DeleteDC(surface->hDC);
5436 /* Release the DIB section */
5437 DeleteObject(surface->dib.DIBsection);
5438 surface->dib.bitmap_data = NULL;
5439 surface->resource.allocatedMemory = NULL;
5440 surface->flags &= ~SFLAG_DIBSECTION;
5442 surface->resource.width = pPresentationParameters->BackBufferWidth;
5443 surface->resource.height = pPresentationParameters->BackBufferHeight;
5444 if (gl_info->supported[ARB_TEXTURE_NON_POWER_OF_TWO] || gl_info->supported[ARB_TEXTURE_RECTANGLE]
5445 || gl_info->supported[WINED3D_GL_NORMALIZED_TEXRECT])
5447 surface->pow2Width = pPresentationParameters->BackBufferWidth;
5448 surface->pow2Height = pPresentationParameters->BackBufferHeight;
5449 } else {
5450 surface->pow2Width = surface->pow2Height = 1;
5451 while (surface->pow2Width < pPresentationParameters->BackBufferWidth) surface->pow2Width <<= 1;
5452 while (surface->pow2Height < pPresentationParameters->BackBufferHeight) surface->pow2Height <<= 1;
5455 surface->resource.multisample_type = pPresentationParameters->MultiSampleType;
5456 surface->resource.multisample_quality = pPresentationParameters->MultiSampleQuality;
5458 surface->resource.resource_ops->resource_unload(&surface->resource);
5460 if (surface->pow2Width != pPresentationParameters->BackBufferWidth
5461 || surface->pow2Height != pPresentationParameters->BackBufferHeight)
5463 surface->flags |= SFLAG_NONPOW2;
5465 else
5467 surface->flags &= ~SFLAG_NONPOW2;
5469 HeapFree(GetProcessHeap(), 0, surface->resource.heapMemory);
5470 surface->resource.allocatedMemory = NULL;
5471 surface->resource.heapMemory = NULL;
5472 surface->resource.size = wined3d_surface_get_pitch(surface) * surface->pow2Width;
5474 /* Put all surfaces into sysmem - the drawable might disappear if the backbuffer was rendered
5475 * to a FBO */
5476 if (!surface_init_sysmem(surface))
5478 return E_OUTOFMEMORY;
5480 return WINED3D_OK;
5483 static BOOL is_display_mode_supported(struct wined3d_device *device, const WINED3DPRESENT_PARAMETERS *pp)
5485 UINT i, count;
5486 WINED3DDISPLAYMODE m;
5487 HRESULT hr;
5489 /* All Windowed modes are supported, as is leaving the current mode */
5490 if(pp->Windowed) return TRUE;
5491 if(!pp->BackBufferWidth) return TRUE;
5492 if(!pp->BackBufferHeight) return TRUE;
5494 count = wined3d_get_adapter_mode_count(device->wined3d, device->adapter->ordinal, WINED3DFMT_UNKNOWN);
5495 for (i = 0; i < count; ++i)
5497 memset(&m, 0, sizeof(m));
5498 hr = wined3d_enum_adapter_modes(device->wined3d, device->adapter->ordinal, WINED3DFMT_UNKNOWN, i, &m);
5499 if (FAILED(hr))
5500 ERR("Failed to enumerate adapter mode.\n");
5501 if (m.Width == pp->BackBufferWidth && m.Height == pp->BackBufferHeight)
5502 /* Mode found, it is supported. */
5503 return TRUE;
5505 /* Mode not found -> not supported */
5506 return FALSE;
5509 /* Do not call while under the GL lock. */
5510 static void delete_opengl_contexts(struct wined3d_device *device, struct wined3d_swapchain *swapchain)
5512 struct wined3d_resource *resource, *cursor;
5513 const struct wined3d_gl_info *gl_info;
5514 struct wined3d_context *context;
5515 struct wined3d_shader *shader;
5517 context = context_acquire(device, NULL);
5518 gl_info = context->gl_info;
5520 LIST_FOR_EACH_ENTRY_SAFE(resource, cursor, &device->resources, struct wined3d_resource, resource_list_entry)
5522 TRACE("Unloading resource %p.\n", resource);
5524 resource->resource_ops->resource_unload(resource);
5527 LIST_FOR_EACH_ENTRY(shader, &device->shaders, struct wined3d_shader, shader_list_entry)
5529 device->shader_backend->shader_destroy(shader);
5532 ENTER_GL();
5533 if (device->depth_blt_texture)
5535 glDeleteTextures(1, &device->depth_blt_texture);
5536 device->depth_blt_texture = 0;
5538 if (device->cursorTexture)
5540 glDeleteTextures(1, &device->cursorTexture);
5541 device->cursorTexture = 0;
5543 LEAVE_GL();
5545 device->blitter->free_private(device);
5546 device->frag_pipe->free_private(device);
5547 device->shader_backend->shader_free_private(device);
5548 destroy_dummy_textures(device, gl_info);
5550 context_release(context);
5552 while (device->context_count)
5554 swapchain_destroy_contexts(device->contexts[0]->swapchain);
5557 HeapFree(GetProcessHeap(), 0, swapchain->context);
5558 swapchain->context = NULL;
5561 /* Do not call while under the GL lock. */
5562 static HRESULT create_primary_opengl_context(struct wined3d_device *device, struct wined3d_swapchain *swapchain)
5564 struct wined3d_context *context;
5565 struct wined3d_surface *target;
5566 HRESULT hr;
5568 /* Recreate the primary swapchain's context */
5569 swapchain->context = HeapAlloc(GetProcessHeap(), 0, sizeof(*swapchain->context));
5570 if (!swapchain->context)
5572 ERR("Failed to allocate memory for swapchain context array.\n");
5573 return E_OUTOFMEMORY;
5576 target = swapchain->back_buffers ? swapchain->back_buffers[0] : swapchain->front_buffer;
5577 if (!(context = context_create(swapchain, target, swapchain->ds_format)))
5579 WARN("Failed to create context.\n");
5580 HeapFree(GetProcessHeap(), 0, swapchain->context);
5581 return E_FAIL;
5584 swapchain->context[0] = context;
5585 swapchain->num_contexts = 1;
5586 create_dummy_textures(device, context);
5587 context_release(context);
5589 hr = device->shader_backend->shader_alloc_private(device);
5590 if (FAILED(hr))
5592 ERR("Failed to allocate shader private data, hr %#x.\n", hr);
5593 goto err;
5596 hr = device->frag_pipe->alloc_private(device);
5597 if (FAILED(hr))
5599 ERR("Failed to allocate fragment pipe private data, hr %#x.\n", hr);
5600 device->shader_backend->shader_free_private(device);
5601 goto err;
5604 hr = device->blitter->alloc_private(device);
5605 if (FAILED(hr))
5607 ERR("Failed to allocate blitter private data, hr %#x.\n", hr);
5608 device->frag_pipe->free_private(device);
5609 device->shader_backend->shader_free_private(device);
5610 goto err;
5613 return WINED3D_OK;
5615 err:
5616 context_acquire(device, NULL);
5617 destroy_dummy_textures(device, context->gl_info);
5618 context_release(context);
5619 context_destroy(device, context);
5620 HeapFree(GetProcessHeap(), 0, swapchain->context);
5621 swapchain->num_contexts = 0;
5622 return hr;
5625 /* Do not call while under the GL lock. */
5626 HRESULT CDECL wined3d_device_reset(struct wined3d_device *device,
5627 WINED3DPRESENT_PARAMETERS *present_parameters,
5628 wined3d_device_reset_cb callback)
5630 struct wined3d_resource *resource, *cursor;
5631 struct wined3d_swapchain *swapchain;
5632 BOOL DisplayModeChanged = FALSE;
5633 BOOL update_desc = FALSE;
5634 WINED3DDISPLAYMODE mode;
5635 unsigned int i;
5636 HRESULT hr;
5638 TRACE("device %p, present_parameters %p.\n", device, present_parameters);
5640 wined3d_device_set_index_buffer(device, NULL, WINED3DFMT_UNKNOWN);
5641 for (i = 0; i < MAX_STREAMS; ++i)
5643 wined3d_device_set_stream_source(device, i, NULL, 0, 0);
5645 for (i = 0; i < MAX_COMBINED_SAMPLERS; ++i)
5647 wined3d_device_set_texture(device, i, NULL);
5649 if (device->onscreen_depth_stencil)
5651 wined3d_surface_decref(device->onscreen_depth_stencil);
5652 device->onscreen_depth_stencil = NULL;
5655 LIST_FOR_EACH_ENTRY_SAFE(resource, cursor, &device->resources, struct wined3d_resource, resource_list_entry)
5657 TRACE("Enumerating resource %p.\n", resource);
5658 if (FAILED(hr = callback(resource)))
5659 return hr;
5662 hr = wined3d_device_get_swapchain(device, 0, &swapchain);
5663 if (FAILED(hr))
5665 ERR("Failed to get the first implicit swapchain\n");
5666 return hr;
5669 if (!is_display_mode_supported(device, present_parameters))
5671 WARN("Rejecting Reset() call because the requested display mode is not supported\n");
5672 WARN("Requested mode: %d, %d.\n",
5673 present_parameters->BackBufferWidth,
5674 present_parameters->BackBufferHeight);
5675 wined3d_swapchain_decref(swapchain);
5676 return WINED3DERR_INVALIDCALL;
5679 /* Is it necessary to recreate the gl context? Actually every setting can be changed
5680 * on an existing gl context, so there's no real need for recreation.
5682 * TODO: Figure out how Reset influences resources in D3DPOOL_DEFAULT, D3DPOOL_SYSTEMMEMORY and D3DPOOL_MANAGED
5684 * TODO: Figure out what happens to explicit swapchains, or if we have more than one implicit swapchain
5686 TRACE("New params:\n");
5687 TRACE("BackBufferWidth = %d\n", present_parameters->BackBufferWidth);
5688 TRACE("BackBufferHeight = %d\n", present_parameters->BackBufferHeight);
5689 TRACE("BackBufferFormat = %s\n", debug_d3dformat(present_parameters->BackBufferFormat));
5690 TRACE("BackBufferCount = %d\n", present_parameters->BackBufferCount);
5691 TRACE("MultiSampleType = %d\n", present_parameters->MultiSampleType);
5692 TRACE("MultiSampleQuality = %d\n", present_parameters->MultiSampleQuality);
5693 TRACE("SwapEffect = %d\n", present_parameters->SwapEffect);
5694 TRACE("hDeviceWindow = %p\n", present_parameters->hDeviceWindow);
5695 TRACE("Windowed = %s\n", present_parameters->Windowed ? "true" : "false");
5696 TRACE("EnableAutoDepthStencil = %s\n", present_parameters->EnableAutoDepthStencil ? "true" : "false");
5697 TRACE("Flags = %08x\n", present_parameters->Flags);
5698 TRACE("FullScreen_RefreshRateInHz = %d\n", present_parameters->FullScreen_RefreshRateInHz);
5699 TRACE("PresentationInterval = %d\n", present_parameters->PresentationInterval);
5701 /* No special treatment of these parameters. Just store them */
5702 swapchain->presentParms.SwapEffect = present_parameters->SwapEffect;
5703 swapchain->presentParms.Flags = present_parameters->Flags;
5704 swapchain->presentParms.PresentationInterval = present_parameters->PresentationInterval;
5705 swapchain->presentParms.FullScreen_RefreshRateInHz = present_parameters->FullScreen_RefreshRateInHz;
5707 /* What to do about these? */
5708 if (present_parameters->BackBufferCount
5709 && present_parameters->BackBufferCount != swapchain->presentParms.BackBufferCount)
5710 FIXME("Cannot change the back buffer count yet.\n");
5712 if (present_parameters->BackBufferFormat != WINED3DFMT_UNKNOWN
5713 && present_parameters->BackBufferFormat != swapchain->presentParms.BackBufferFormat)
5714 FIXME("Cannot change the back buffer format yet.\n");
5716 if (present_parameters->hDeviceWindow
5717 && present_parameters->hDeviceWindow != swapchain->presentParms.hDeviceWindow)
5718 FIXME("Cannot change the device window yet.\n");
5720 if (present_parameters->EnableAutoDepthStencil && !device->auto_depth_stencil)
5722 HRESULT hrc;
5724 TRACE("Creating the depth stencil buffer\n");
5726 hrc = device->device_parent->ops->create_depth_stencil(device->device_parent,
5727 present_parameters->BackBufferWidth,
5728 present_parameters->BackBufferHeight,
5729 present_parameters->AutoDepthStencilFormat,
5730 present_parameters->MultiSampleType,
5731 present_parameters->MultiSampleQuality,
5732 FALSE,
5733 &device->auto_depth_stencil);
5734 if (FAILED(hrc))
5736 ERR("Failed to create the depth stencil buffer.\n");
5737 wined3d_swapchain_decref(swapchain);
5738 return WINED3DERR_INVALIDCALL;
5742 if (device->onscreen_depth_stencil)
5744 wined3d_surface_decref(device->onscreen_depth_stencil);
5745 device->onscreen_depth_stencil = NULL;
5748 /* Reset the depth stencil */
5749 if (present_parameters->EnableAutoDepthStencil)
5750 wined3d_device_set_depth_stencil(device, device->auto_depth_stencil);
5751 else
5752 wined3d_device_set_depth_stencil(device, NULL);
5754 TRACE("Resetting stateblock\n");
5755 wined3d_stateblock_decref(device->updateStateBlock);
5756 wined3d_stateblock_decref(device->stateBlock);
5758 if (present_parameters->Windowed)
5760 mode.Width = swapchain->orig_width;
5761 mode.Height = swapchain->orig_height;
5762 mode.RefreshRate = 0;
5763 mode.Format = swapchain->presentParms.BackBufferFormat;
5765 else
5767 mode.Width = present_parameters->BackBufferWidth;
5768 mode.Height = present_parameters->BackBufferHeight;
5769 mode.RefreshRate = present_parameters->FullScreen_RefreshRateInHz;
5770 mode.Format = swapchain->presentParms.BackBufferFormat;
5773 /* Should Width == 800 && Height == 0 set 800x600? */
5774 if (present_parameters->BackBufferWidth && present_parameters->BackBufferHeight
5775 && (present_parameters->BackBufferWidth != swapchain->presentParms.BackBufferWidth
5776 || present_parameters->BackBufferHeight != swapchain->presentParms.BackBufferHeight))
5778 if (!present_parameters->Windowed)
5779 DisplayModeChanged = TRUE;
5781 swapchain->presentParms.BackBufferWidth = present_parameters->BackBufferWidth;
5782 swapchain->presentParms.BackBufferHeight = present_parameters->BackBufferHeight;
5783 update_desc = TRUE;
5786 if (present_parameters->MultiSampleType != swapchain->presentParms.MultiSampleType
5787 || present_parameters->MultiSampleQuality != swapchain->presentParms.MultiSampleQuality)
5789 swapchain->presentParms.MultiSampleType = present_parameters->MultiSampleType;
5790 swapchain->presentParms.MultiSampleQuality = present_parameters->MultiSampleQuality;
5791 update_desc = TRUE;
5794 if (update_desc)
5796 UINT i;
5798 hr = updateSurfaceDesc(swapchain->front_buffer, &swapchain->presentParms);
5799 if (FAILED(hr))
5801 wined3d_swapchain_decref(swapchain);
5802 return hr;
5805 for (i = 0; i < swapchain->presentParms.BackBufferCount; ++i)
5807 hr = updateSurfaceDesc(swapchain->back_buffers[i], &swapchain->presentParms);
5808 if (FAILED(hr))
5810 wined3d_swapchain_decref(swapchain);
5811 return hr;
5814 if (device->auto_depth_stencil)
5816 hr = updateSurfaceDesc(device->auto_depth_stencil, &swapchain->presentParms);
5817 if (FAILED(hr))
5819 wined3d_swapchain_decref(swapchain);
5820 return hr;
5825 delete_opengl_contexts(device, swapchain);
5827 if (!present_parameters->Windowed != !swapchain->presentParms.Windowed
5828 || DisplayModeChanged)
5830 wined3d_device_set_display_mode(device, 0, &mode);
5832 if (!present_parameters->Windowed)
5834 if (swapchain->presentParms.Windowed)
5836 HWND focus_window = device->createParms.hFocusWindow;
5837 if (!focus_window)
5838 focus_window = present_parameters->hDeviceWindow;
5839 if (FAILED(hr = wined3d_device_acquire_focus_window(device, focus_window)))
5841 ERR("Failed to acquire focus window, hr %#x.\n", hr);
5842 wined3d_swapchain_decref(swapchain);
5843 return hr;
5846 /* switch from windowed to fs */
5847 wined3d_device_setup_fullscreen_window(device, swapchain->device_window,
5848 present_parameters->BackBufferWidth,
5849 present_parameters->BackBufferHeight);
5851 else
5853 /* Fullscreen -> fullscreen mode change */
5854 MoveWindow(swapchain->device_window, 0, 0,
5855 present_parameters->BackBufferWidth, present_parameters->BackBufferHeight,
5856 TRUE);
5859 else if (!swapchain->presentParms.Windowed)
5861 /* Fullscreen -> windowed switch */
5862 wined3d_device_restore_fullscreen_window(device, swapchain->device_window);
5863 wined3d_device_release_focus_window(device);
5865 swapchain->presentParms.Windowed = present_parameters->Windowed;
5867 else if (!present_parameters->Windowed)
5869 DWORD style = device->style;
5870 DWORD exStyle = device->exStyle;
5871 /* If we're in fullscreen, and the mode wasn't changed, we have to get the window back into
5872 * the right position. Some applications(Battlefield 2, Guild Wars) move it and then call
5873 * Reset to clear up their mess. Guild Wars also loses the device during that.
5875 device->style = 0;
5876 device->exStyle = 0;
5877 wined3d_device_setup_fullscreen_window(device, swapchain->device_window,
5878 present_parameters->BackBufferWidth,
5879 present_parameters->BackBufferHeight);
5880 device->style = style;
5881 device->exStyle = exStyle;
5884 /* Note: No parent needed for initial internal stateblock */
5885 hr = wined3d_stateblock_create(device, WINED3DSBT_INIT, &device->stateBlock);
5886 if (FAILED(hr))
5887 ERR("Resetting the stateblock failed with error %#x.\n", hr);
5888 else
5889 TRACE("Created stateblock %p.\n", device->stateBlock);
5890 device->updateStateBlock = device->stateBlock;
5891 wined3d_stateblock_incref(device->updateStateBlock);
5893 stateblock_init_default_state(device->stateBlock);
5895 swapchain_update_render_to_fbo(swapchain);
5896 swapchain_update_draw_bindings(swapchain);
5898 hr = create_primary_opengl_context(device, swapchain);
5899 wined3d_swapchain_decref(swapchain);
5901 /* All done. There is no need to reload resources or shaders, this will happen automatically on the
5902 * first use
5904 return hr;
5907 HRESULT CDECL wined3d_device_set_dialog_box_mode(struct wined3d_device *device, BOOL enable_dialogs)
5909 TRACE("device %p, enable_dialogs %#x.\n", device, enable_dialogs);
5911 if (!enable_dialogs) FIXME("Dialogs cannot be disabled yet.\n");
5913 return WINED3D_OK;
5917 HRESULT CDECL wined3d_device_get_creation_parameters(struct wined3d_device *device,
5918 WINED3DDEVICE_CREATION_PARAMETERS *parameters)
5920 TRACE("device %p, parameters %p.\n", device, parameters);
5922 *parameters = device->createParms;
5923 return WINED3D_OK;
5926 void CDECL wined3d_device_set_gamma_ramp(struct wined3d_device *device,
5927 UINT swapchain_idx, DWORD flags, const WINED3DGAMMARAMP *ramp)
5929 struct wined3d_swapchain *swapchain;
5931 TRACE("device %p, swapchain_idx %u, flags %#x, ramp %p.\n",
5932 device, swapchain_idx, flags, ramp);
5934 if (SUCCEEDED(wined3d_device_get_swapchain(device, swapchain_idx, &swapchain)))
5936 wined3d_swapchain_set_gamma_ramp(swapchain, flags, ramp);
5937 wined3d_swapchain_decref(swapchain);
5941 void CDECL wined3d_device_get_gamma_ramp(struct wined3d_device *device, UINT swapchain_idx, WINED3DGAMMARAMP *ramp)
5943 struct wined3d_swapchain *swapchain;
5945 TRACE("device %p, swapchain_idx %u, ramp %p.\n",
5946 device, swapchain_idx, ramp);
5948 if (SUCCEEDED(wined3d_device_get_swapchain(device, swapchain_idx, &swapchain)))
5950 wined3d_swapchain_get_gamma_ramp(swapchain, ramp);
5951 wined3d_swapchain_decref(swapchain);
5955 void device_resource_add(struct wined3d_device *device, struct wined3d_resource *resource)
5957 TRACE("device %p, resource %p.\n", device, resource);
5959 list_add_head(&device->resources, &resource->resource_list_entry);
5962 static void device_resource_remove(struct wined3d_device *device, struct wined3d_resource *resource)
5964 TRACE("device %p, resource %p.\n", device, resource);
5966 list_remove(&resource->resource_list_entry);
5969 void device_resource_released(struct wined3d_device *device, struct wined3d_resource *resource)
5971 WINED3DRESOURCETYPE type = resource->resourceType;
5972 unsigned int i;
5974 TRACE("device %p, resource %p, type %s.\n", device, resource, debug_d3dresourcetype(type));
5976 context_resource_released(device, resource, type);
5978 switch (type)
5980 case WINED3DRTYPE_SURFACE:
5982 struct wined3d_surface *surface = surface_from_resource(resource);
5984 if (!device->d3d_initialized) break;
5986 for (i = 0; i < device->adapter->gl_info.limits.buffers; ++i)
5988 if (device->fb.render_targets[i] == surface)
5990 ERR("Surface %p is still in use as render target %u.\n", surface, i);
5991 device->fb.render_targets[i] = NULL;
5995 if (device->fb.depth_stencil == surface)
5997 ERR("Surface %p is still in use as depth/stencil buffer.\n", surface);
5998 device->fb.depth_stencil = NULL;
6001 break;
6003 case WINED3DRTYPE_TEXTURE:
6004 case WINED3DRTYPE_CUBETEXTURE:
6005 case WINED3DRTYPE_VOLUMETEXTURE:
6006 for (i = 0; i < MAX_COMBINED_SAMPLERS; ++i)
6008 struct wined3d_texture *texture = wined3d_texture_from_resource(resource);
6010 if (device->stateBlock && device->stateBlock->state.textures[i] == texture)
6012 ERR("Texture %p is still in use by stateblock %p, stage %u.\n",
6013 texture, device->stateBlock, i);
6014 device->stateBlock->state.textures[i] = NULL;
6017 if (device->updateStateBlock != device->stateBlock
6018 && device->updateStateBlock->state.textures[i] == texture)
6020 ERR("Texture %p is still in use by stateblock %p, stage %u.\n",
6021 texture, device->updateStateBlock, i);
6022 device->updateStateBlock->state.textures[i] = NULL;
6025 break;
6027 case WINED3DRTYPE_BUFFER:
6029 struct wined3d_buffer *buffer = buffer_from_resource(resource);
6031 for (i = 0; i < MAX_STREAMS; ++i)
6033 if (device->stateBlock && device->stateBlock->state.streams[i].buffer == buffer)
6035 ERR("Buffer %p is still in use by stateblock %p, stream %u.\n",
6036 buffer, device->stateBlock, i);
6037 device->stateBlock->state.streams[i].buffer = NULL;
6040 if (device->updateStateBlock != device->stateBlock
6041 && device->updateStateBlock->state.streams[i].buffer == buffer)
6043 ERR("Buffer %p is still in use by stateblock %p, stream %u.\n",
6044 buffer, device->updateStateBlock, i);
6045 device->updateStateBlock->state.streams[i].buffer = NULL;
6050 if (device->stateBlock && device->stateBlock->state.index_buffer == buffer)
6052 ERR("Buffer %p is still in use by stateblock %p as index buffer.\n",
6053 buffer, device->stateBlock);
6054 device->stateBlock->state.index_buffer = NULL;
6057 if (device->updateStateBlock != device->stateBlock
6058 && device->updateStateBlock->state.index_buffer == buffer)
6060 ERR("Buffer %p is still in use by stateblock %p as index buffer.\n",
6061 buffer, device->updateStateBlock);
6062 device->updateStateBlock->state.index_buffer = NULL;
6065 break;
6067 default:
6068 break;
6071 /* Remove the resource from the resourceStore */
6072 device_resource_remove(device, resource);
6074 TRACE("Resource released.\n");
6077 HRESULT CDECL wined3d_device_get_surface_from_dc(struct wined3d_device *device,
6078 HDC dc, struct wined3d_surface **surface)
6080 struct wined3d_resource *resource;
6082 TRACE("device %p, dc %p, surface %p.\n", device, dc, surface);
6084 LIST_FOR_EACH_ENTRY(resource, &device->resources, struct wined3d_resource, resource_list_entry)
6086 if (resource->resourceType == WINED3DRTYPE_SURFACE)
6088 struct wined3d_surface *s = surface_from_resource(resource);
6090 if (s->hDC == dc)
6092 TRACE("Found surface %p for dc %p.\n", s, dc);
6093 *surface = s;
6094 return WINED3D_OK;
6099 return WINED3DERR_INVALIDCALL;
6102 HRESULT device_init(struct wined3d_device *device, struct wined3d *wined3d,
6103 UINT adapter_idx, WINED3DDEVTYPE device_type, HWND focus_window, DWORD flags,
6104 BYTE surface_alignment, struct wined3d_device_parent *device_parent)
6106 struct wined3d_adapter *adapter = &wined3d->adapters[adapter_idx];
6107 const struct fragment_pipeline *fragment_pipeline;
6108 struct shader_caps shader_caps;
6109 struct fragment_caps ffp_caps;
6110 WINED3DDISPLAYMODE mode;
6111 unsigned int i;
6112 HRESULT hr;
6114 device->ref = 1;
6115 device->wined3d = wined3d;
6116 wined3d_incref(device->wined3d);
6117 device->adapter = wined3d->adapter_count ? adapter : NULL;
6118 device->device_parent = device_parent;
6119 list_init(&device->resources);
6120 list_init(&device->shaders);
6121 device->surface_alignment = surface_alignment;
6123 /* Get the initial screen setup for ddraw. */
6124 hr = wined3d_get_adapter_display_mode(wined3d, adapter_idx, &mode);
6125 if (FAILED(hr))
6127 ERR("Failed to get the adapter's display mode, hr %#x.\n", hr);
6128 wined3d_decref(device->wined3d);
6129 return hr;
6131 device->ddraw_width = mode.Width;
6132 device->ddraw_height = mode.Height;
6133 device->ddraw_format = mode.Format;
6135 /* Save the creation parameters. */
6136 device->createParms.AdapterOrdinal = adapter_idx;
6137 device->createParms.DeviceType = device_type;
6138 device->createParms.hFocusWindow = focus_window;
6139 device->createParms.BehaviorFlags = flags;
6141 device->devType = device_type;
6142 for (i = 0; i < PATCHMAP_SIZE; ++i) list_init(&device->patches[i]);
6144 select_shader_mode(&adapter->gl_info, &device->ps_selected_mode, &device->vs_selected_mode);
6145 device->shader_backend = adapter->shader_backend;
6147 if (device->shader_backend)
6149 device->shader_backend->shader_get_caps(&adapter->gl_info, &shader_caps);
6150 device->d3d_vshader_constantF = shader_caps.MaxVertexShaderConst;
6151 device->d3d_pshader_constantF = shader_caps.MaxPixelShaderConst;
6152 device->vs_clipping = shader_caps.VSClipping;
6154 fragment_pipeline = adapter->fragment_pipe;
6155 device->frag_pipe = fragment_pipeline;
6156 if (fragment_pipeline)
6158 fragment_pipeline->get_caps(&adapter->gl_info, &ffp_caps);
6159 device->max_ffp_textures = ffp_caps.MaxSimultaneousTextures;
6161 hr = compile_state_table(device->StateTable, device->multistate_funcs, &adapter->gl_info,
6162 ffp_vertexstate_template, fragment_pipeline, misc_state_template);
6163 if (FAILED(hr))
6165 ERR("Failed to compile state table, hr %#x.\n", hr);
6166 wined3d_decref(device->wined3d);
6167 return hr;
6170 device->blitter = adapter->blitter;
6172 return WINED3D_OK;
6176 void device_invalidate_state(const struct wined3d_device *device, DWORD state)
6178 DWORD rep = device->StateTable[state].representative;
6179 struct wined3d_context *context;
6180 DWORD idx;
6181 BYTE shift;
6182 UINT i;
6184 for (i = 0; i < device->context_count; ++i)
6186 context = device->contexts[i];
6187 if(isStateDirty(context, rep)) continue;
6189 context->dirtyArray[context->numDirtyEntries++] = rep;
6190 idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
6191 shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
6192 context->isStateDirty[idx] |= (1 << shift);
6196 void get_drawable_size_fbo(const struct wined3d_context *context, UINT *width, UINT *height)
6198 /* The drawable size of a fbo target is the opengl texture size, which is the power of two size. */
6199 *width = context->current_rt->pow2Width;
6200 *height = context->current_rt->pow2Height;
6203 void get_drawable_size_backbuffer(const struct wined3d_context *context, UINT *width, UINT *height)
6205 const struct wined3d_swapchain *swapchain = context->swapchain;
6206 /* The drawable size of a backbuffer / aux buffer offscreen target is the size of the
6207 * current context's drawable, which is the size of the back buffer of the swapchain
6208 * the active context belongs to. */
6209 *width = swapchain->presentParms.BackBufferWidth;
6210 *height = swapchain->presentParms.BackBufferHeight;
6213 LRESULT device_process_message(struct wined3d_device *device, HWND window, BOOL unicode,
6214 UINT message, WPARAM wparam, LPARAM lparam, WNDPROC proc)
6216 if (device->filter_messages)
6218 TRACE("Filtering message: window %p, message %#x, wparam %#lx, lparam %#lx.\n",
6219 window, message, wparam, lparam);
6220 if (unicode)
6221 return DefWindowProcW(window, message, wparam, lparam);
6222 else
6223 return DefWindowProcA(window, message, wparam, lparam);
6226 if (message == WM_DESTROY)
6228 TRACE("unregister window %p.\n", window);
6229 wined3d_unregister_window(window);
6231 if (device->focus_window == window) device->focus_window = NULL;
6232 else ERR("Window %p is not the focus window for device %p.\n", window, device);
6235 if (unicode)
6236 return CallWindowProcW(proc, window, message, wparam, lparam);
6237 else
6238 return CallWindowProcA(proc, window, message, wparam, lparam);