wined3d: wined3d_device_set_base_vertex_index() never fails.
[wine.git] / dlls / wined3d / device.c
blobe5cf69bae6ecc937fdb1606242400a93085f077e
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 "wine/port.h"
30 #include <stdio.h>
31 #ifdef HAVE_FLOAT_H
32 # include <float.h>
33 #endif
35 #include "wined3d_private.h"
37 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
39 /* Define the default light parameters as specified by MSDN. */
40 const struct wined3d_light WINED3D_default_light =
42 WINED3D_LIGHT_DIRECTIONAL, /* Type */
43 { 1.0f, 1.0f, 1.0f, 0.0f }, /* Diffuse r,g,b,a */
44 { 0.0f, 0.0f, 0.0f, 0.0f }, /* Specular r,g,b,a */
45 { 0.0f, 0.0f, 0.0f, 0.0f }, /* Ambient r,g,b,a, */
46 { 0.0f, 0.0f, 0.0f }, /* Position x,y,z */
47 { 0.0f, 0.0f, 1.0f }, /* Direction x,y,z */
48 0.0f, /* Range */
49 0.0f, /* Falloff */
50 0.0f, 0.0f, 0.0f, /* Attenuation 0,1,2 */
51 0.0f, /* Theta */
52 0.0f /* Phi */
55 /**********************************************************
56 * Global variable / Constants follow
57 **********************************************************/
58 const struct wined3d_matrix identity =
59 {{{
60 1.0f, 0.0f, 0.0f, 0.0f,
61 0.0f, 1.0f, 0.0f, 0.0f,
62 0.0f, 0.0f, 1.0f, 0.0f,
63 0.0f, 0.0f, 0.0f, 1.0f,
64 }}}; /* When needed for comparisons */
66 /* Note that except for WINED3DPT_POINTLIST and WINED3DPT_LINELIST these
67 * actually have the same values in GL and D3D. */
68 static GLenum gl_primitive_type_from_d3d(enum wined3d_primitive_type primitive_type)
70 switch(primitive_type)
72 case WINED3D_PT_POINTLIST:
73 return GL_POINTS;
75 case WINED3D_PT_LINELIST:
76 return GL_LINES;
78 case WINED3D_PT_LINESTRIP:
79 return GL_LINE_STRIP;
81 case WINED3D_PT_TRIANGLELIST:
82 return GL_TRIANGLES;
84 case WINED3D_PT_TRIANGLESTRIP:
85 return GL_TRIANGLE_STRIP;
87 case WINED3D_PT_TRIANGLEFAN:
88 return GL_TRIANGLE_FAN;
90 case WINED3D_PT_LINELIST_ADJ:
91 return GL_LINES_ADJACENCY_ARB;
93 case WINED3D_PT_LINESTRIP_ADJ:
94 return GL_LINE_STRIP_ADJACENCY_ARB;
96 case WINED3D_PT_TRIANGLELIST_ADJ:
97 return GL_TRIANGLES_ADJACENCY_ARB;
99 case WINED3D_PT_TRIANGLESTRIP_ADJ:
100 return GL_TRIANGLE_STRIP_ADJACENCY_ARB;
102 default:
103 FIXME("Unhandled primitive type %s\n", debug_d3dprimitivetype(primitive_type));
104 return GL_NONE;
108 static enum wined3d_primitive_type d3d_primitive_type_from_gl(GLenum primitive_type)
110 switch(primitive_type)
112 case GL_POINTS:
113 return WINED3D_PT_POINTLIST;
115 case GL_LINES:
116 return WINED3D_PT_LINELIST;
118 case GL_LINE_STRIP:
119 return WINED3D_PT_LINESTRIP;
121 case GL_TRIANGLES:
122 return WINED3D_PT_TRIANGLELIST;
124 case GL_TRIANGLE_STRIP:
125 return WINED3D_PT_TRIANGLESTRIP;
127 case GL_TRIANGLE_FAN:
128 return WINED3D_PT_TRIANGLEFAN;
130 case GL_LINES_ADJACENCY_ARB:
131 return WINED3D_PT_LINELIST_ADJ;
133 case GL_LINE_STRIP_ADJACENCY_ARB:
134 return WINED3D_PT_LINESTRIP_ADJ;
136 case GL_TRIANGLES_ADJACENCY_ARB:
137 return WINED3D_PT_TRIANGLELIST_ADJ;
139 case GL_TRIANGLE_STRIP_ADJACENCY_ARB:
140 return WINED3D_PT_TRIANGLESTRIP_ADJ;
142 default:
143 FIXME("Unhandled primitive type %s\n", debug_d3dprimitivetype(primitive_type));
144 return WINED3D_PT_UNDEFINED;
148 static BOOL fixed_get_input(BYTE usage, BYTE usage_idx, unsigned int *regnum)
150 if ((usage == WINED3D_DECL_USAGE_POSITION || usage == WINED3D_DECL_USAGE_POSITIONT) && !usage_idx)
151 *regnum = WINED3D_FFP_POSITION;
152 else if (usage == WINED3D_DECL_USAGE_BLEND_WEIGHT && !usage_idx)
153 *regnum = WINED3D_FFP_BLENDWEIGHT;
154 else if (usage == WINED3D_DECL_USAGE_BLEND_INDICES && !usage_idx)
155 *regnum = WINED3D_FFP_BLENDINDICES;
156 else if (usage == WINED3D_DECL_USAGE_NORMAL && !usage_idx)
157 *regnum = WINED3D_FFP_NORMAL;
158 else if (usage == WINED3D_DECL_USAGE_PSIZE && !usage_idx)
159 *regnum = WINED3D_FFP_PSIZE;
160 else if (usage == WINED3D_DECL_USAGE_COLOR && !usage_idx)
161 *regnum = WINED3D_FFP_DIFFUSE;
162 else if (usage == WINED3D_DECL_USAGE_COLOR && usage_idx == 1)
163 *regnum = WINED3D_FFP_SPECULAR;
164 else if (usage == WINED3D_DECL_USAGE_TEXCOORD && usage_idx < WINED3DDP_MAXTEXCOORD)
165 *regnum = WINED3D_FFP_TEXCOORD0 + usage_idx;
166 else
168 FIXME("Unsupported input stream [usage=%s, usage_idx=%u]\n", debug_d3ddeclusage(usage), usage_idx);
169 *regnum = ~0U;
170 return FALSE;
173 return TRUE;
176 /* Context activation is done by the caller. */
177 void device_stream_info_from_declaration(struct wined3d_device *device, struct wined3d_stream_info *stream_info)
179 const struct wined3d_state *state = &device->stateBlock->state;
180 /* We need to deal with frequency data! */
181 struct wined3d_vertex_declaration *declaration = state->vertex_declaration;
182 BOOL use_vshader;
183 unsigned int i;
185 stream_info->use_map = 0;
186 stream_info->swizzle_map = 0;
188 /* Check for transformed vertices, disable vertex shader if present. */
189 stream_info->position_transformed = declaration->position_transformed;
190 use_vshader = state->vertex_shader && !declaration->position_transformed;
192 /* Translate the declaration into strided data. */
193 for (i = 0; i < declaration->element_count; ++i)
195 const struct wined3d_vertex_declaration_element *element = &declaration->elements[i];
196 const struct wined3d_stream_state *stream = &state->streams[element->input_slot];
197 struct wined3d_buffer *buffer = stream->buffer;
198 struct wined3d_bo_address data;
199 BOOL stride_used;
200 unsigned int idx;
201 DWORD stride;
203 TRACE("%p Element %p (%u of %u)\n", declaration->elements,
204 element, i + 1, declaration->element_count);
206 if (!buffer) continue;
208 data.buffer_object = 0;
209 data.addr = NULL;
211 stride = stream->stride;
212 if (state->user_stream)
214 TRACE("Stream %u is UP, %p\n", element->input_slot, buffer);
215 data.buffer_object = 0;
216 data.addr = (BYTE *)buffer;
218 else
220 TRACE("Stream %u isn't UP, %p\n", element->input_slot, buffer);
221 buffer_get_memory(buffer, &device->adapter->gl_info, &data);
223 /* Can't use vbo's if the base vertex index is negative. OpenGL doesn't accept negative offsets
224 * (or rather offsets bigger than the vbo, because the pointer is unsigned), so use system memory
225 * sources. In most sane cases the pointer - offset will still be > 0, otherwise it will wrap
226 * around to some big value. Hope that with the indices, the driver wraps it back internally. If
227 * not, drawStridedSlow is needed, including a vertex buffer path. */
228 if (state->load_base_vertex_index < 0)
230 WARN("load_base_vertex_index is < 0 (%d), not using VBOs.\n",
231 state->load_base_vertex_index);
232 data.buffer_object = 0;
233 data.addr = buffer_get_sysmem(buffer, &device->adapter->gl_info);
234 if ((UINT_PTR)data.addr < -state->load_base_vertex_index * stride)
236 FIXME("System memory vertex data load offset is negative!\n");
240 data.addr += element->offset;
242 TRACE("offset %u input_slot %u usage_idx %d\n", element->offset, element->input_slot, element->usage_idx);
244 if (use_vshader)
246 if (element->output_slot == ~0U)
248 /* TODO: Assuming vertexdeclarations are usually used with the
249 * same or a similar shader, it might be worth it to store the
250 * last used output slot and try that one first. */
251 stride_used = vshader_get_input(state->vertex_shader,
252 element->usage, element->usage_idx, &idx);
254 else
256 idx = element->output_slot;
257 stride_used = TRUE;
260 else
262 if (!element->ffp_valid)
264 WARN("Skipping unsupported fixed function element of format %s and usage %s\n",
265 debug_d3dformat(element->format->id), debug_d3ddeclusage(element->usage));
266 stride_used = FALSE;
268 else
270 stride_used = fixed_get_input(element->usage, element->usage_idx, &idx);
274 if (stride_used)
276 TRACE("Load %s array %u [usage %s, usage_idx %u, "
277 "input_slot %u, offset %u, stride %u, format %s, buffer_object %u]\n",
278 use_vshader ? "shader": "fixed function", idx,
279 debug_d3ddeclusage(element->usage), element->usage_idx, element->input_slot,
280 element->offset, stride, debug_d3dformat(element->format->id), data.buffer_object);
282 data.addr += stream->offset;
284 stream_info->elements[idx].format = element->format;
285 stream_info->elements[idx].data = data;
286 stream_info->elements[idx].stride = stride;
287 stream_info->elements[idx].stream_idx = element->input_slot;
289 if (!device->adapter->gl_info.supported[ARB_VERTEX_ARRAY_BGRA]
290 && element->format->id == WINED3DFMT_B8G8R8A8_UNORM)
292 stream_info->swizzle_map |= 1 << idx;
294 stream_info->use_map |= 1 << idx;
298 device->num_buffer_queries = 0;
299 if (!state->user_stream)
301 WORD map = stream_info->use_map;
302 stream_info->all_vbo = 1;
304 /* PreLoad all the vertex buffers. */
305 for (i = 0; map; map >>= 1, ++i)
307 struct wined3d_stream_info_element *element;
308 struct wined3d_buffer *buffer;
310 if (!(map & 1)) continue;
312 element = &stream_info->elements[i];
313 buffer = state->streams[element->stream_idx].buffer;
314 wined3d_buffer_preload(buffer);
316 /* If the preload dropped the buffer object, update the stream info. */
317 if (buffer->buffer_object != element->data.buffer_object)
319 element->data.buffer_object = 0;
320 element->data.addr = buffer_get_sysmem(buffer, &device->adapter->gl_info)
321 + (ptrdiff_t)element->data.addr;
324 if (!buffer->buffer_object)
325 stream_info->all_vbo = 0;
327 if (buffer->query)
328 device->buffer_queries[device->num_buffer_queries++] = buffer->query;
331 else
333 stream_info->all_vbo = 0;
337 static void stream_info_element_from_strided(const struct wined3d_gl_info *gl_info,
338 const struct wined3d_strided_element *strided, struct wined3d_stream_info_element *e)
340 e->data.addr = strided->data;
341 e->data.buffer_object = 0;
342 e->format = wined3d_get_format(gl_info, strided->format);
343 e->stride = strided->stride;
344 e->stream_idx = 0;
347 static void device_stream_info_from_strided(const struct wined3d_gl_info *gl_info,
348 const struct wined3d_strided_data *strided, struct wined3d_stream_info *stream_info)
350 unsigned int i;
352 memset(stream_info, 0, sizeof(*stream_info));
354 if (strided->position.data)
355 stream_info_element_from_strided(gl_info, &strided->position, &stream_info->elements[WINED3D_FFP_POSITION]);
356 if (strided->normal.data)
357 stream_info_element_from_strided(gl_info, &strided->normal, &stream_info->elements[WINED3D_FFP_NORMAL]);
358 if (strided->diffuse.data)
359 stream_info_element_from_strided(gl_info, &strided->diffuse, &stream_info->elements[WINED3D_FFP_DIFFUSE]);
360 if (strided->specular.data)
361 stream_info_element_from_strided(gl_info, &strided->specular, &stream_info->elements[WINED3D_FFP_SPECULAR]);
363 for (i = 0; i < WINED3DDP_MAXTEXCOORD; ++i)
365 if (strided->tex_coords[i].data)
366 stream_info_element_from_strided(gl_info, &strided->tex_coords[i],
367 &stream_info->elements[WINED3D_FFP_TEXCOORD0 + i]);
370 stream_info->position_transformed = strided->position_transformed;
372 for (i = 0; i < sizeof(stream_info->elements) / sizeof(*stream_info->elements); ++i)
374 if (!stream_info->elements[i].format) continue;
376 if (!gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
377 && stream_info->elements[i].format->id == WINED3DFMT_B8G8R8A8_UNORM)
379 stream_info->swizzle_map |= 1 << i;
381 stream_info->use_map |= 1 << i;
385 static void device_trace_strided_stream_info(const struct wined3d_stream_info *stream_info)
387 TRACE("Strided Data:\n");
388 TRACE_STRIDED(stream_info, WINED3D_FFP_POSITION);
389 TRACE_STRIDED(stream_info, WINED3D_FFP_BLENDWEIGHT);
390 TRACE_STRIDED(stream_info, WINED3D_FFP_BLENDINDICES);
391 TRACE_STRIDED(stream_info, WINED3D_FFP_NORMAL);
392 TRACE_STRIDED(stream_info, WINED3D_FFP_PSIZE);
393 TRACE_STRIDED(stream_info, WINED3D_FFP_DIFFUSE);
394 TRACE_STRIDED(stream_info, WINED3D_FFP_SPECULAR);
395 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD0);
396 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD1);
397 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD2);
398 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD3);
399 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD4);
400 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD5);
401 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD6);
402 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD7);
405 /* Context activation is done by the caller. */
406 void device_update_stream_info(struct wined3d_device *device, const struct wined3d_gl_info *gl_info)
408 struct wined3d_stream_info *stream_info = &device->strided_streams;
409 const struct wined3d_state *state = &device->stateBlock->state;
410 DWORD prev_all_vbo = stream_info->all_vbo;
412 if (device->up_strided)
414 /* Note: this is a ddraw fixed-function code path. */
415 TRACE("=============================== Strided Input ================================\n");
416 device_stream_info_from_strided(gl_info, device->up_strided, stream_info);
417 if (TRACE_ON(d3d)) device_trace_strided_stream_info(stream_info);
419 else
421 TRACE("============================= Vertex Declaration =============================\n");
422 device_stream_info_from_declaration(device, stream_info);
425 if (state->vertex_shader && !stream_info->position_transformed)
427 if (state->vertex_declaration->half_float_conv_needed && !stream_info->all_vbo)
429 TRACE("Using drawStridedSlow with vertex shaders for FLOAT16 conversion.\n");
430 device->useDrawStridedSlow = TRUE;
432 else
434 device->useDrawStridedSlow = FALSE;
437 else
439 WORD slow_mask = (1 << WINED3D_FFP_PSIZE);
440 slow_mask |= -!gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
441 & ((1 << WINED3D_FFP_DIFFUSE) | (1 << WINED3D_FFP_SPECULAR));
443 if ((stream_info->position_transformed || (stream_info->use_map & slow_mask)) && !stream_info->all_vbo)
445 device->useDrawStridedSlow = TRUE;
447 else
449 device->useDrawStridedSlow = FALSE;
453 if (prev_all_vbo != stream_info->all_vbo)
454 device_invalidate_state(device, STATE_INDEXBUFFER);
457 static void device_preload_texture(const struct wined3d_state *state, unsigned int idx)
459 struct wined3d_texture *texture;
460 enum WINED3DSRGB srgb;
462 if (!(texture = state->textures[idx])) return;
463 srgb = state->sampler_states[idx][WINED3D_SAMP_SRGB_TEXTURE] ? SRGB_SRGB : SRGB_RGB;
464 texture->texture_ops->texture_preload(texture, srgb);
467 void device_preload_textures(const struct wined3d_device *device)
469 const struct wined3d_state *state = &device->stateBlock->state;
470 unsigned int i;
472 if (use_vs(state))
474 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
476 if (state->vertex_shader->reg_maps.sampler_type[i])
477 device_preload_texture(state, MAX_FRAGMENT_SAMPLERS + i);
481 if (use_ps(state))
483 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
485 if (state->pixel_shader->reg_maps.sampler_type[i])
486 device_preload_texture(state, i);
489 else
491 WORD ffu_map = device->fixed_function_usage_map;
493 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
495 if (ffu_map & 1)
496 device_preload_texture(state, i);
501 BOOL device_context_add(struct wined3d_device *device, struct wined3d_context *context)
503 struct wined3d_context **new_array;
505 TRACE("Adding context %p.\n", context);
507 if (!device->contexts) new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*new_array));
508 else new_array = HeapReAlloc(GetProcessHeap(), 0, device->contexts,
509 sizeof(*new_array) * (device->context_count + 1));
511 if (!new_array)
513 ERR("Failed to grow the context array.\n");
514 return FALSE;
517 new_array[device->context_count++] = context;
518 device->contexts = new_array;
519 return TRUE;
522 void device_context_remove(struct wined3d_device *device, struct wined3d_context *context)
524 struct wined3d_context **new_array;
525 BOOL found = FALSE;
526 UINT i;
528 TRACE("Removing context %p.\n", context);
530 for (i = 0; i < device->context_count; ++i)
532 if (device->contexts[i] == context)
534 found = TRUE;
535 break;
539 if (!found)
541 ERR("Context %p doesn't exist in context array.\n", context);
542 return;
545 if (!--device->context_count)
547 HeapFree(GetProcessHeap(), 0, device->contexts);
548 device->contexts = NULL;
549 return;
552 memmove(&device->contexts[i], &device->contexts[i + 1], (device->context_count - i) * sizeof(*device->contexts));
553 new_array = HeapReAlloc(GetProcessHeap(), 0, device->contexts, device->context_count * sizeof(*device->contexts));
554 if (!new_array)
556 ERR("Failed to shrink context array. Oh well.\n");
557 return;
560 device->contexts = new_array;
563 /* Do not call while under the GL lock. */
564 void device_switch_onscreen_ds(struct wined3d_device *device,
565 struct wined3d_context *context, struct wined3d_surface *depth_stencil)
567 if (device->onscreen_depth_stencil)
569 surface_load_ds_location(device->onscreen_depth_stencil, context, SFLAG_INTEXTURE);
571 surface_modify_ds_location(device->onscreen_depth_stencil, SFLAG_INTEXTURE,
572 device->onscreen_depth_stencil->ds_current_size.cx,
573 device->onscreen_depth_stencil->ds_current_size.cy);
574 wined3d_surface_decref(device->onscreen_depth_stencil);
576 device->onscreen_depth_stencil = depth_stencil;
577 wined3d_surface_incref(device->onscreen_depth_stencil);
580 static BOOL is_full_clear(const struct wined3d_surface *target, const RECT *draw_rect, const RECT *clear_rect)
582 /* partial draw rect */
583 if (draw_rect->left || draw_rect->top
584 || draw_rect->right < target->resource.width
585 || draw_rect->bottom < target->resource.height)
586 return FALSE;
588 /* partial clear rect */
589 if (clear_rect && (clear_rect->left > 0 || clear_rect->top > 0
590 || clear_rect->right < target->resource.width
591 || clear_rect->bottom < target->resource.height))
592 return FALSE;
594 return TRUE;
597 static void prepare_ds_clear(struct wined3d_surface *ds, struct wined3d_context *context,
598 DWORD location, const RECT *draw_rect, UINT rect_count, const RECT *clear_rect, RECT *out_rect)
600 RECT current_rect, r;
602 if (ds->flags & location)
603 SetRect(&current_rect, 0, 0,
604 ds->ds_current_size.cx,
605 ds->ds_current_size.cy);
606 else
607 SetRectEmpty(&current_rect);
609 IntersectRect(&r, draw_rect, &current_rect);
610 if (EqualRect(&r, draw_rect))
612 /* current_rect ⊇ draw_rect, modify only. */
613 SetRect(out_rect, 0, 0, ds->ds_current_size.cx, ds->ds_current_size.cy);
614 return;
617 if (EqualRect(&r, &current_rect))
619 /* draw_rect ⊇ current_rect, test if we're doing a full clear. */
621 if (!clear_rect)
623 /* Full clear, modify only. */
624 *out_rect = *draw_rect;
625 return;
628 IntersectRect(&r, draw_rect, clear_rect);
629 if (EqualRect(&r, draw_rect))
631 /* clear_rect ⊇ draw_rect, modify only. */
632 *out_rect = *draw_rect;
633 return;
637 /* Full load. */
638 surface_load_ds_location(ds, context, location);
639 SetRect(out_rect, 0, 0, ds->ds_current_size.cx, ds->ds_current_size.cy);
642 /* Do not call while under the GL lock. */
643 void device_clear_render_targets(struct wined3d_device *device, UINT rt_count, const struct wined3d_fb_state *fb,
644 UINT rect_count, const RECT *rects, const RECT *draw_rect, DWORD flags, const struct wined3d_color *color,
645 float depth, DWORD stencil)
647 const RECT *clear_rect = (rect_count > 0 && rects) ? (const RECT *)rects : NULL;
648 struct wined3d_surface *target = rt_count ? fb->render_targets[0] : NULL;
649 const struct wined3d_gl_info *gl_info;
650 UINT drawable_width, drawable_height;
651 struct wined3d_context *context;
652 GLbitfield clear_mask = 0;
653 BOOL render_offscreen;
654 unsigned int i;
655 RECT ds_rect;
657 /* When we're clearing parts of the drawable, make sure that the target surface is well up to date in the
658 * drawable. After the clear we'll mark the drawable up to date, so we have to make sure that this is true
659 * for the cleared parts, and the untouched parts.
661 * If we're clearing the whole target there is no need to copy it into the drawable, it will be overwritten
662 * anyway. If we're not clearing the color buffer we don't have to copy either since we're not going to set
663 * the drawable up to date. We have to check all settings that limit the clear area though. Do not bother
664 * checking all this if the dest surface is in the drawable anyway. */
665 if (flags & WINED3DCLEAR_TARGET && !is_full_clear(target, draw_rect, clear_rect))
667 for (i = 0; i < rt_count; ++i)
669 struct wined3d_surface *rt = fb->render_targets[i];
670 if (rt)
671 surface_load_location(rt, rt->draw_binding, NULL);
675 context = context_acquire(device, target);
676 if (!context->valid)
678 context_release(context);
679 WARN("Invalid context, skipping clear.\n");
680 return;
682 gl_info = context->gl_info;
684 if (target)
686 render_offscreen = context->render_offscreen;
687 target->get_drawable_size(context, &drawable_width, &drawable_height);
689 else
691 render_offscreen = TRUE;
692 drawable_width = fb->depth_stencil->pow2Width;
693 drawable_height = fb->depth_stencil->pow2Height;
696 if (flags & WINED3DCLEAR_ZBUFFER)
698 DWORD location = render_offscreen ? fb->depth_stencil->draw_binding : SFLAG_INDRAWABLE;
700 if (!render_offscreen && fb->depth_stencil != device->onscreen_depth_stencil)
701 device_switch_onscreen_ds(device, context, fb->depth_stencil);
702 prepare_ds_clear(fb->depth_stencil, context, location,
703 draw_rect, rect_count, clear_rect, &ds_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;
713 ENTER_GL();
715 /* Only set the values up once, as they are not changing. */
716 if (flags & WINED3DCLEAR_STENCIL)
718 if (gl_info->supported[EXT_STENCIL_TWO_SIDE])
720 gl_info->gl_ops.gl.p_glDisable(GL_STENCIL_TEST_TWO_SIDE_EXT);
721 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_TWOSIDEDSTENCILMODE));
723 gl_info->gl_ops.gl.p_glStencilMask(~0U);
724 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_STENCILWRITEMASK));
725 gl_info->gl_ops.gl.p_glClearStencil(stencil);
726 checkGLcall("glClearStencil");
727 clear_mask = clear_mask | GL_STENCIL_BUFFER_BIT;
730 if (flags & WINED3DCLEAR_ZBUFFER)
732 DWORD location = render_offscreen ? fb->depth_stencil->draw_binding : SFLAG_INDRAWABLE;
734 surface_modify_ds_location(fb->depth_stencil, location, ds_rect.right, ds_rect.bottom);
736 gl_info->gl_ops.gl.p_glDepthMask(GL_TRUE);
737 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ZWRITEENABLE));
738 gl_info->gl_ops.gl.p_glClearDepth(depth);
739 checkGLcall("glClearDepth");
740 clear_mask = clear_mask | GL_DEPTH_BUFFER_BIT;
743 if (flags & WINED3DCLEAR_TARGET)
745 for (i = 0; i < rt_count; ++i)
747 struct wined3d_surface *rt = fb->render_targets[i];
749 if (rt)
750 surface_modify_location(rt, rt->draw_binding, TRUE);
753 gl_info->gl_ops.gl.p_glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
754 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE));
755 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE1));
756 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE2));
757 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE3));
758 gl_info->gl_ops.gl.p_glClearColor(color->r, color->g, color->b, color->a);
759 checkGLcall("glClearColor");
760 clear_mask = clear_mask | GL_COLOR_BUFFER_BIT;
763 if (!clear_rect)
765 if (render_offscreen)
767 gl_info->gl_ops.gl.p_glScissor(draw_rect->left, draw_rect->top,
768 draw_rect->right - draw_rect->left, draw_rect->bottom - draw_rect->top);
770 else
772 gl_info->gl_ops.gl.p_glScissor(draw_rect->left, drawable_height - draw_rect->bottom,
773 draw_rect->right - draw_rect->left, draw_rect->bottom - draw_rect->top);
775 checkGLcall("glScissor");
776 gl_info->gl_ops.gl.p_glClear(clear_mask);
777 checkGLcall("glClear");
779 else
781 RECT current_rect;
783 /* Now process each rect in turn. */
784 for (i = 0; i < rect_count; ++i)
786 /* Note that GL uses lower left, width/height. */
787 IntersectRect(&current_rect, draw_rect, &clear_rect[i]);
789 TRACE("clear_rect[%u] %s, current_rect %s.\n", i,
790 wine_dbgstr_rect(&clear_rect[i]),
791 wine_dbgstr_rect(&current_rect));
793 /* Tests show that rectangles where x1 > x2 or y1 > y2 are ignored silently.
794 * The rectangle is not cleared, no error is returned, but further rectangles are
795 * still cleared if they are valid. */
796 if (current_rect.left > current_rect.right || current_rect.top > current_rect.bottom)
798 TRACE("Rectangle with negative dimensions, ignoring.\n");
799 continue;
802 if (render_offscreen)
804 gl_info->gl_ops.gl.p_glScissor(current_rect.left, current_rect.top,
805 current_rect.right - current_rect.left, current_rect.bottom - current_rect.top);
807 else
809 gl_info->gl_ops.gl.p_glScissor(current_rect.left, drawable_height - current_rect.bottom,
810 current_rect.right - current_rect.left, current_rect.bottom - current_rect.top);
812 checkGLcall("glScissor");
814 gl_info->gl_ops.gl.p_glClear(clear_mask);
815 checkGLcall("glClear");
819 LEAVE_GL();
821 if (wined3d_settings.strict_draw_ordering || (flags & WINED3DCLEAR_TARGET
822 && target->container.type == WINED3D_CONTAINER_SWAPCHAIN
823 && target->container.u.swapchain->front_buffer == target))
824 gl_info->gl_ops.gl.p_glFlush(); /* Flush to ensure ordering across contexts. */
826 context_release(context);
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 struct wined3d_stateblock *stateblock;
847 UINT i;
849 if (wined3d_stateblock_decref(device->updateStateBlock)
850 && device->updateStateBlock != device->stateBlock)
851 FIXME("Something's still holding the update stateblock.\n");
852 device->updateStateBlock = NULL;
854 stateblock = device->stateBlock;
855 device->stateBlock = NULL;
856 if (wined3d_stateblock_decref(stateblock))
857 FIXME("Something's still holding the stateblock.\n");
859 for (i = 0; i < sizeof(device->multistate_funcs) / sizeof(device->multistate_funcs[0]); ++i)
861 HeapFree(GetProcessHeap(), 0, device->multistate_funcs[i]);
862 device->multistate_funcs[i] = NULL;
865 if (!list_empty(&device->resources))
867 struct wined3d_resource *resource;
869 FIXME("Device released with resources still bound, acceptable but unexpected.\n");
871 LIST_FOR_EACH_ENTRY(resource, &device->resources, struct wined3d_resource, resource_list_entry)
873 FIXME("Leftover resource %p with type %s (%#x).\n",
874 resource, debug_d3dresourcetype(resource->type), resource->type);
878 if (device->contexts)
879 ERR("Context array not freed!\n");
880 if (device->hardwareCursor)
881 DestroyCursor(device->hardwareCursor);
882 device->hardwareCursor = 0;
884 wined3d_decref(device->wined3d);
885 device->wined3d = NULL;
886 HeapFree(GetProcessHeap(), 0, device);
887 TRACE("Freed device %p.\n", device);
890 return refcount;
893 UINT CDECL wined3d_device_get_swapchain_count(const struct wined3d_device *device)
895 TRACE("device %p.\n", device);
897 return device->swapchain_count;
900 struct wined3d_swapchain * CDECL wined3d_device_get_swapchain(const struct wined3d_device *device, UINT swapchain_idx)
902 TRACE("device %p, swapchain_idx %u.\n", device, swapchain_idx);
904 if (swapchain_idx >= device->swapchain_count)
906 WARN("swapchain_idx %u >= swapchain_count %u.\n",
907 swapchain_idx, device->swapchain_count);
908 return NULL;
911 return device->swapchains[swapchain_idx];
914 static void device_load_logo(struct wined3d_device *device, const char *filename)
916 struct wined3d_color_key color_key;
917 HBITMAP hbm;
918 BITMAP bm;
919 HRESULT hr;
920 HDC dcb = NULL, dcs = NULL;
922 hbm = LoadImageA(NULL, filename, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE | LR_CREATEDIBSECTION);
923 if(hbm)
925 GetObjectA(hbm, sizeof(BITMAP), &bm);
926 dcb = CreateCompatibleDC(NULL);
927 if(!dcb) goto out;
928 SelectObject(dcb, hbm);
930 else
932 /* Create a 32x32 white surface to indicate that wined3d is used, but the specified image
933 * couldn't be loaded
935 memset(&bm, 0, sizeof(bm));
936 bm.bmWidth = 32;
937 bm.bmHeight = 32;
940 hr = wined3d_surface_create(device, bm.bmWidth, bm.bmHeight, WINED3DFMT_B5G6R5_UNORM, 0, 0,
941 WINED3D_POOL_SYSTEM_MEM, WINED3D_MULTISAMPLE_NONE, 0, WINED3D_SURFACE_TYPE_OPENGL, WINED3D_SURFACE_MAPPABLE,
942 NULL, &wined3d_null_parent_ops, &device->logo_surface);
943 if (FAILED(hr))
945 ERR("Wine logo requested, but failed to create surface, hr %#x.\n", hr);
946 goto out;
949 if (dcb)
951 if (FAILED(hr = wined3d_surface_getdc(device->logo_surface, &dcs)))
952 goto out;
953 BitBlt(dcs, 0, 0, bm.bmWidth, bm.bmHeight, dcb, 0, 0, SRCCOPY);
954 wined3d_surface_releasedc(device->logo_surface, dcs);
956 color_key.color_space_low_value = 0;
957 color_key.color_space_high_value = 0;
958 wined3d_surface_set_color_key(device->logo_surface, WINEDDCKEY_SRCBLT, &color_key);
960 else
962 const struct wined3d_color c = {1.0f, 1.0f, 1.0f, 1.0f};
963 /* Fill the surface with a white color to show that wined3d is there */
964 wined3d_device_color_fill(device, device->logo_surface, NULL, &c);
967 out:
968 if (dcb) DeleteDC(dcb);
969 if (hbm) DeleteObject(hbm);
972 /* Context activation is done by the caller. */
973 static void create_dummy_textures(struct wined3d_device *device, struct wined3d_context *context)
975 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
976 unsigned int i, j, count;
977 /* Under DirectX you can sample even if no texture is bound, whereas
978 * OpenGL will only allow that when a valid texture is bound.
979 * We emulate this by creating dummy textures and binding them
980 * to each texture stage when the currently set D3D texture is NULL. */
981 ENTER_GL();
983 if (gl_info->supported[APPLE_CLIENT_STORAGE])
985 /* The dummy texture does not have client storage backing */
986 gl_info->gl_ops.gl.p_glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE);
987 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE)");
990 count = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers);
991 for (i = 0; i < count; ++i)
993 DWORD color = 0x000000ff;
995 /* Make appropriate texture active */
996 context_active_texture(context, gl_info, i);
998 gl_info->gl_ops.gl.p_glGenTextures(1, &device->dummy_texture_2d[i]);
999 checkGLcall("glGenTextures");
1000 TRACE("Dummy 2D texture %u given name %u.\n", i, device->dummy_texture_2d[i]);
1002 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D, device->dummy_texture_2d[i]);
1003 checkGLcall("glBindTexture");
1005 gl_info->gl_ops.gl.p_glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 1, 1, 0,
1006 GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, &color);
1007 checkGLcall("glTexImage2D");
1009 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1011 gl_info->gl_ops.gl.p_glGenTextures(1, &device->dummy_texture_rect[i]);
1012 checkGLcall("glGenTextures");
1013 TRACE("Dummy rectangle texture %u given name %u.\n", i, device->dummy_texture_rect[i]);
1015 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_texture_rect[i]);
1016 checkGLcall("glBindTexture");
1018 gl_info->gl_ops.gl.p_glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGBA8, 1, 1, 0,
1019 GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, &color);
1020 checkGLcall("glTexImage2D");
1023 if (gl_info->supported[EXT_TEXTURE3D])
1025 gl_info->gl_ops.gl.p_glGenTextures(1, &device->dummy_texture_3d[i]);
1026 checkGLcall("glGenTextures");
1027 TRACE("Dummy 3D texture %u given name %u.\n", i, device->dummy_texture_3d[i]);
1029 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_3D, device->dummy_texture_3d[i]);
1030 checkGLcall("glBindTexture");
1032 GL_EXTCALL(glTexImage3DEXT(GL_TEXTURE_3D, 0, GL_RGBA8, 1, 1, 1, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, &color));
1033 checkGLcall("glTexImage3D");
1036 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1038 gl_info->gl_ops.gl.p_glGenTextures(1, &device->dummy_texture_cube[i]);
1039 checkGLcall("glGenTextures");
1040 TRACE("Dummy cube texture %u given name %u.\n", i, device->dummy_texture_cube[i]);
1042 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_texture_cube[i]);
1043 checkGLcall("glBindTexture");
1045 for (j = GL_TEXTURE_CUBE_MAP_POSITIVE_X; j <= GL_TEXTURE_CUBE_MAP_NEGATIVE_Z; ++j)
1047 gl_info->gl_ops.gl.p_glTexImage2D(j, 0, GL_RGBA8, 1, 1, 0,
1048 GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, &color);
1049 checkGLcall("glTexImage2D");
1054 if (gl_info->supported[APPLE_CLIENT_STORAGE])
1056 /* Re-enable because if supported it is enabled by default */
1057 gl_info->gl_ops.gl.p_glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
1058 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
1061 LEAVE_GL();
1064 /* Context activation is done by the caller. */
1065 static void destroy_dummy_textures(struct wined3d_device *device, const struct wined3d_gl_info *gl_info)
1067 unsigned int count = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers);
1069 ENTER_GL();
1070 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1072 gl_info->gl_ops.gl.p_glDeleteTextures(count, device->dummy_texture_cube);
1073 checkGLcall("glDeleteTextures(count, device->dummy_texture_cube)");
1076 if (gl_info->supported[EXT_TEXTURE3D])
1078 gl_info->gl_ops.gl.p_glDeleteTextures(count, device->dummy_texture_3d);
1079 checkGLcall("glDeleteTextures(count, device->dummy_texture_3d)");
1082 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1084 gl_info->gl_ops.gl.p_glDeleteTextures(count, device->dummy_texture_rect);
1085 checkGLcall("glDeleteTextures(count, device->dummy_texture_rect)");
1088 gl_info->gl_ops.gl.p_glDeleteTextures(count, device->dummy_texture_2d);
1089 checkGLcall("glDeleteTextures(count, device->dummy_texture_2d)");
1090 LEAVE_GL();
1092 memset(device->dummy_texture_cube, 0, gl_info->limits.textures * sizeof(*device->dummy_texture_cube));
1093 memset(device->dummy_texture_3d, 0, gl_info->limits.textures * sizeof(*device->dummy_texture_3d));
1094 memset(device->dummy_texture_rect, 0, gl_info->limits.textures * sizeof(*device->dummy_texture_rect));
1095 memset(device->dummy_texture_2d, 0, gl_info->limits.textures * sizeof(*device->dummy_texture_2d));
1098 static LONG fullscreen_style(LONG style)
1100 /* Make sure the window is managed, otherwise we won't get keyboard input. */
1101 style |= WS_POPUP | WS_SYSMENU;
1102 style &= ~(WS_CAPTION | WS_THICKFRAME);
1104 return style;
1107 static LONG fullscreen_exstyle(LONG exstyle)
1109 /* Filter out window decorations. */
1110 exstyle &= ~(WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE);
1112 return exstyle;
1115 void CDECL wined3d_device_setup_fullscreen_window(struct wined3d_device *device, HWND window, UINT w, UINT h)
1117 BOOL filter_messages;
1118 LONG style, exstyle;
1120 TRACE("Setting up window %p for fullscreen mode.\n", window);
1122 if (device->style || device->exStyle)
1124 ERR("Changing the window style for window %p, but another style (%08x, %08x) is already stored.\n",
1125 window, device->style, device->exStyle);
1128 device->style = GetWindowLongW(window, GWL_STYLE);
1129 device->exStyle = GetWindowLongW(window, GWL_EXSTYLE);
1131 style = fullscreen_style(device->style);
1132 exstyle = fullscreen_exstyle(device->exStyle);
1134 TRACE("Old style was %08x, %08x, setting to %08x, %08x.\n",
1135 device->style, device->exStyle, style, exstyle);
1137 filter_messages = device->filter_messages;
1138 device->filter_messages = TRUE;
1140 SetWindowLongW(window, GWL_STYLE, style);
1141 SetWindowLongW(window, GWL_EXSTYLE, exstyle);
1142 SetWindowPos(window, HWND_TOP, 0, 0, w, h, SWP_FRAMECHANGED | SWP_SHOWWINDOW | SWP_NOACTIVATE);
1144 device->filter_messages = filter_messages;
1147 void CDECL wined3d_device_restore_fullscreen_window(struct wined3d_device *device, HWND window)
1149 BOOL filter_messages;
1150 LONG style, exstyle;
1152 if (!device->style && !device->exStyle) return;
1154 TRACE("Restoring window style of window %p to %08x, %08x.\n",
1155 window, device->style, device->exStyle);
1157 style = GetWindowLongW(window, GWL_STYLE);
1158 exstyle = GetWindowLongW(window, GWL_EXSTYLE);
1160 filter_messages = device->filter_messages;
1161 device->filter_messages = TRUE;
1163 /* Only restore the style if the application didn't modify it during the
1164 * fullscreen phase. Some applications change it before calling Reset()
1165 * when switching between windowed and fullscreen modes (HL2), some
1166 * depend on the original style (Eve Online). */
1167 if (style == fullscreen_style(device->style) && exstyle == fullscreen_exstyle(device->exStyle))
1169 SetWindowLongW(window, GWL_STYLE, device->style);
1170 SetWindowLongW(window, GWL_EXSTYLE, device->exStyle);
1172 SetWindowPos(window, 0, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
1174 device->filter_messages = filter_messages;
1176 /* Delete the old values. */
1177 device->style = 0;
1178 device->exStyle = 0;
1181 HRESULT CDECL wined3d_device_acquire_focus_window(struct wined3d_device *device, HWND window)
1183 TRACE("device %p, window %p.\n", device, window);
1185 if (!wined3d_register_window(window, device))
1187 ERR("Failed to register window %p.\n", window);
1188 return E_FAIL;
1191 InterlockedExchangePointer((void **)&device->focus_window, window);
1192 SetWindowPos(window, 0, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
1194 return WINED3D_OK;
1197 void CDECL wined3d_device_release_focus_window(struct wined3d_device *device)
1199 TRACE("device %p.\n", device);
1201 if (device->focus_window) wined3d_unregister_window(device->focus_window);
1202 InterlockedExchangePointer((void **)&device->focus_window, NULL);
1205 HRESULT CDECL wined3d_device_init_3d(struct wined3d_device *device,
1206 struct wined3d_swapchain_desc *swapchain_desc)
1208 static const struct wined3d_color black = {0.0f, 0.0f, 0.0f, 0.0f};
1209 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1210 struct wined3d_swapchain *swapchain = NULL;
1211 struct wined3d_context *context;
1212 HRESULT hr;
1213 DWORD state;
1214 unsigned int i;
1216 TRACE("device %p, swapchain_desc %p.\n", device, swapchain_desc);
1218 if (device->d3d_initialized)
1219 return WINED3DERR_INVALIDCALL;
1220 if (!device->adapter->opengl)
1221 return WINED3DERR_INVALIDCALL;
1223 device->valid_rt_mask = 0;
1224 for (i = 0; i < gl_info->limits.buffers; ++i)
1225 device->valid_rt_mask |= (1 << i);
1226 device->fb.render_targets = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1227 sizeof(*device->fb.render_targets) * gl_info->limits.buffers);
1229 /* Initialize the texture unit mapping to a 1:1 mapping */
1230 for (state = 0; state < MAX_COMBINED_SAMPLERS; ++state)
1232 if (state < gl_info->limits.fragment_samplers)
1234 device->texUnitMap[state] = state;
1235 device->rev_tex_unit_map[state] = state;
1237 else
1239 device->texUnitMap[state] = WINED3D_UNMAPPED_STAGE;
1240 device->rev_tex_unit_map[state] = WINED3D_UNMAPPED_STAGE;
1244 /* Setup the implicit swapchain. This also initializes a context. */
1245 TRACE("Creating implicit swapchain\n");
1246 hr = device->device_parent->ops->create_swapchain(device->device_parent,
1247 swapchain_desc, &swapchain);
1248 if (FAILED(hr))
1250 WARN("Failed to create implicit swapchain\n");
1251 goto err_out;
1254 device->swapchain_count = 1;
1255 device->swapchains = HeapAlloc(GetProcessHeap(), 0, device->swapchain_count * sizeof(*device->swapchains));
1256 if (!device->swapchains)
1258 ERR("Out of memory!\n");
1259 goto err_out;
1261 device->swapchains[0] = swapchain;
1263 if (swapchain->back_buffers && swapchain->back_buffers[0])
1265 TRACE("Setting rendertarget to %p.\n", swapchain->back_buffers);
1266 device->fb.render_targets[0] = swapchain->back_buffers[0];
1268 else
1270 TRACE("Setting rendertarget to %p.\n", swapchain->front_buffer);
1271 device->fb.render_targets[0] = swapchain->front_buffer;
1273 wined3d_surface_incref(device->fb.render_targets[0]);
1275 /* Depth Stencil support */
1276 device->fb.depth_stencil = device->auto_depth_stencil;
1277 if (device->fb.depth_stencil)
1278 wined3d_surface_incref(device->fb.depth_stencil);
1280 hr = device->shader_backend->shader_alloc_private(device);
1281 if (FAILED(hr))
1283 TRACE("Shader private data couldn't be allocated\n");
1284 goto err_out;
1286 hr = device->frag_pipe->alloc_private(device);
1287 if (FAILED(hr))
1289 TRACE("Fragment pipeline private data couldn't be allocated\n");
1290 goto err_out;
1292 hr = device->blitter->alloc_private(device);
1293 if (FAILED(hr))
1295 TRACE("Blitter private data couldn't be allocated\n");
1296 goto err_out;
1299 /* Set up some starting GL setup */
1301 /* Setup all the devices defaults */
1302 stateblock_init_default_state(device->stateBlock);
1304 context = context_acquire(device, swapchain->front_buffer);
1306 create_dummy_textures(device, context);
1308 ENTER_GL();
1310 /* Initialize the current view state */
1311 device->view_ident = 1;
1312 device->contexts[0]->last_was_rhw = 0;
1314 switch (wined3d_settings.offscreen_rendering_mode)
1316 case ORM_FBO:
1317 device->offscreenBuffer = GL_COLOR_ATTACHMENT0;
1318 break;
1320 case ORM_BACKBUFFER:
1322 if (context_get_current()->aux_buffers > 0)
1324 TRACE("Using auxiliary buffer for offscreen rendering\n");
1325 device->offscreenBuffer = GL_AUX0;
1327 else
1329 TRACE("Using back buffer for offscreen rendering\n");
1330 device->offscreenBuffer = GL_BACK;
1335 TRACE("All defaults now set up, leaving 3D init.\n");
1336 LEAVE_GL();
1338 context_release(context);
1340 /* Clear the screen */
1341 wined3d_device_clear(device, 0, NULL, WINED3DCLEAR_TARGET
1342 | (swapchain_desc->enable_auto_depth_stencil ? WINED3DCLEAR_ZBUFFER | WINED3DCLEAR_STENCIL : 0),
1343 &black, 1.0f, 0);
1345 device->d3d_initialized = TRUE;
1347 if (wined3d_settings.logo)
1348 device_load_logo(device, wined3d_settings.logo);
1349 return WINED3D_OK;
1351 err_out:
1352 HeapFree(GetProcessHeap(), 0, device->fb.render_targets);
1353 HeapFree(GetProcessHeap(), 0, device->swapchains);
1354 device->swapchain_count = 0;
1355 if (swapchain)
1356 wined3d_swapchain_decref(swapchain);
1357 if (device->blit_priv)
1358 device->blitter->free_private(device);
1359 if (device->fragment_priv)
1360 device->frag_pipe->free_private(device);
1361 if (device->shader_priv)
1362 device->shader_backend->shader_free_private(device);
1364 return hr;
1367 HRESULT CDECL wined3d_device_init_gdi(struct wined3d_device *device,
1368 struct wined3d_swapchain_desc *swapchain_desc)
1370 struct wined3d_swapchain *swapchain = NULL;
1371 HRESULT hr;
1373 TRACE("device %p, swapchain_desc %p.\n", device, swapchain_desc);
1375 /* Setup the implicit swapchain */
1376 TRACE("Creating implicit swapchain\n");
1377 hr = device->device_parent->ops->create_swapchain(device->device_parent,
1378 swapchain_desc, &swapchain);
1379 if (FAILED(hr))
1381 WARN("Failed to create implicit swapchain\n");
1382 goto err_out;
1385 device->swapchain_count = 1;
1386 device->swapchains = HeapAlloc(GetProcessHeap(), 0, device->swapchain_count * sizeof(*device->swapchains));
1387 if (!device->swapchains)
1389 ERR("Out of memory!\n");
1390 goto err_out;
1392 device->swapchains[0] = swapchain;
1393 return WINED3D_OK;
1395 err_out:
1396 wined3d_swapchain_decref(swapchain);
1397 return hr;
1400 HRESULT CDECL wined3d_device_uninit_3d(struct wined3d_device *device)
1402 struct wined3d_resource *resource, *cursor;
1403 const struct wined3d_gl_info *gl_info;
1404 struct wined3d_context *context;
1405 struct wined3d_surface *surface;
1406 UINT i;
1408 TRACE("device %p.\n", device);
1410 if (!device->d3d_initialized)
1411 return WINED3DERR_INVALIDCALL;
1413 /* Force making the context current again, to verify it is still valid
1414 * (workaround for broken drivers) */
1415 context_set_current(NULL);
1416 /* I don't think that the interface guarantees that the device is destroyed from the same thread
1417 * it was created. Thus make sure a context is active for the glDelete* calls
1419 context = context_acquire(device, NULL);
1420 gl_info = context->gl_info;
1422 if (device->logo_surface)
1423 wined3d_surface_decref(device->logo_surface);
1425 stateblock_unbind_resources(device->stateBlock);
1427 /* Unload resources */
1428 LIST_FOR_EACH_ENTRY_SAFE(resource, cursor, &device->resources, struct wined3d_resource, resource_list_entry)
1430 TRACE("Unloading resource %p.\n", resource);
1432 resource->resource_ops->resource_unload(resource);
1435 TRACE("Deleting high order patches\n");
1436 for (i = 0; i < PATCHMAP_SIZE; ++i)
1438 struct wined3d_rect_patch *patch;
1439 struct list *e1, *e2;
1441 LIST_FOR_EACH_SAFE(e1, e2, &device->patches[i])
1443 patch = LIST_ENTRY(e1, struct wined3d_rect_patch, entry);
1444 wined3d_device_delete_patch(device, patch->Handle);
1448 /* Delete the mouse cursor texture */
1449 if (device->cursorTexture)
1451 ENTER_GL();
1452 gl_info->gl_ops.gl.p_glDeleteTextures(1, &device->cursorTexture);
1453 LEAVE_GL();
1454 device->cursorTexture = 0;
1457 /* Destroy the depth blt resources, they will be invalid after the reset. Also free shader
1458 * private data, it might contain opengl pointers
1460 if (device->depth_blt_texture)
1462 ENTER_GL();
1463 gl_info->gl_ops.gl.p_glDeleteTextures(1, &device->depth_blt_texture);
1464 LEAVE_GL();
1465 device->depth_blt_texture = 0;
1468 /* Destroy the shader backend. Note that this has to happen after all shaders are destroyed. */
1469 device->blitter->free_private(device);
1470 device->frag_pipe->free_private(device);
1471 device->shader_backend->shader_free_private(device);
1473 /* Release the buffers (with sanity checks)*/
1474 if (device->onscreen_depth_stencil)
1476 surface = device->onscreen_depth_stencil;
1477 device->onscreen_depth_stencil = NULL;
1478 wined3d_surface_decref(surface);
1481 if (device->fb.depth_stencil)
1483 surface = device->fb.depth_stencil;
1485 TRACE("Releasing depth/stencil buffer %p.\n", surface);
1487 device->fb.depth_stencil = NULL;
1488 wined3d_surface_decref(surface);
1491 if (device->auto_depth_stencil)
1493 surface = device->auto_depth_stencil;
1494 device->auto_depth_stencil = NULL;
1495 if (wined3d_surface_decref(surface))
1496 FIXME("Something's still holding the auto depth stencil buffer (%p).\n", surface);
1499 for (i = 1; i < gl_info->limits.buffers; ++i)
1501 wined3d_device_set_render_target(device, i, NULL, FALSE);
1504 surface = device->fb.render_targets[0];
1505 TRACE("Setting rendertarget 0 to NULL\n");
1506 device->fb.render_targets[0] = NULL;
1507 TRACE("Releasing the render target at %p\n", surface);
1508 wined3d_surface_decref(surface);
1510 context_release(context);
1512 for (i = 0; i < device->swapchain_count; ++i)
1514 TRACE("Releasing the implicit swapchain %u.\n", i);
1515 if (wined3d_swapchain_decref(device->swapchains[i]))
1516 FIXME("Something's still holding the implicit swapchain.\n");
1519 HeapFree(GetProcessHeap(), 0, device->swapchains);
1520 device->swapchains = NULL;
1521 device->swapchain_count = 0;
1523 HeapFree(GetProcessHeap(), 0, device->fb.render_targets);
1524 device->fb.render_targets = NULL;
1526 device->d3d_initialized = FALSE;
1528 return WINED3D_OK;
1531 HRESULT CDECL wined3d_device_uninit_gdi(struct wined3d_device *device)
1533 unsigned int i;
1535 for (i = 0; i < device->swapchain_count; ++i)
1537 TRACE("Releasing the implicit swapchain %u.\n", i);
1538 if (wined3d_swapchain_decref(device->swapchains[i]))
1539 FIXME("Something's still holding the implicit swapchain.\n");
1542 HeapFree(GetProcessHeap(), 0, device->swapchains);
1543 device->swapchains = NULL;
1544 device->swapchain_count = 0;
1545 return WINED3D_OK;
1548 /* Enables thread safety in the wined3d device and its resources. Called by DirectDraw
1549 * from SetCooperativeLevel if DDSCL_MULTITHREADED is specified, and by d3d8/9 from
1550 * CreateDevice if D3DCREATE_MULTITHREADED is passed.
1552 * There is no way to deactivate thread safety once it is enabled.
1554 void CDECL wined3d_device_set_multithreaded(struct wined3d_device *device)
1556 TRACE("device %p.\n", device);
1558 /* For now just store the flag (needed in case of ddraw). */
1559 device->create_parms.flags |= WINED3DCREATE_MULTITHREADED;
1562 UINT CDECL wined3d_device_get_available_texture_mem(const struct wined3d_device *device)
1564 TRACE("device %p.\n", device);
1566 TRACE("Emulating %d MB, returning %d MB left.\n",
1567 device->adapter->TextureRam / (1024 * 1024),
1568 (device->adapter->TextureRam - device->adapter->UsedTextureRam) / (1024 * 1024));
1570 return device->adapter->TextureRam - device->adapter->UsedTextureRam;
1573 HRESULT CDECL wined3d_device_set_stream_source(struct wined3d_device *device, UINT stream_idx,
1574 struct wined3d_buffer *buffer, UINT offset, UINT stride)
1576 struct wined3d_stream_state *stream;
1577 struct wined3d_buffer *prev_buffer;
1579 TRACE("device %p, stream_idx %u, buffer %p, offset %u, stride %u.\n",
1580 device, stream_idx, buffer, offset, stride);
1582 if (stream_idx >= MAX_STREAMS)
1584 WARN("Stream index %u out of range.\n", stream_idx);
1585 return WINED3DERR_INVALIDCALL;
1587 else if (offset & 0x3)
1589 WARN("Offset %u is not 4 byte aligned.\n", offset);
1590 return WINED3DERR_INVALIDCALL;
1593 stream = &device->updateStateBlock->state.streams[stream_idx];
1594 prev_buffer = stream->buffer;
1596 device->updateStateBlock->changed.streamSource |= 1 << stream_idx;
1598 if (prev_buffer == buffer
1599 && stream->stride == stride
1600 && stream->offset == offset)
1602 TRACE("Application is setting the old values over, nothing to do.\n");
1603 return WINED3D_OK;
1606 stream->buffer = buffer;
1607 if (buffer)
1609 stream->stride = stride;
1610 stream->offset = offset;
1613 /* Handle recording of state blocks. */
1614 if (device->isRecordingState)
1616 TRACE("Recording... not performing anything.\n");
1617 if (buffer)
1618 wined3d_buffer_incref(buffer);
1619 if (prev_buffer)
1620 wined3d_buffer_decref(prev_buffer);
1621 return WINED3D_OK;
1624 if (buffer)
1626 InterlockedIncrement(&buffer->resource.bind_count);
1627 wined3d_buffer_incref(buffer);
1629 if (prev_buffer)
1631 InterlockedDecrement(&prev_buffer->resource.bind_count);
1632 wined3d_buffer_decref(prev_buffer);
1635 device_invalidate_state(device, STATE_STREAMSRC);
1637 return WINED3D_OK;
1640 HRESULT CDECL wined3d_device_get_stream_source(const struct wined3d_device *device,
1641 UINT stream_idx, struct wined3d_buffer **buffer, UINT *offset, UINT *stride)
1643 struct wined3d_stream_state *stream;
1645 TRACE("device %p, stream_idx %u, buffer %p, offset %p, stride %p.\n",
1646 device, stream_idx, buffer, offset, stride);
1648 if (stream_idx >= MAX_STREAMS)
1650 WARN("Stream index %u out of range.\n", stream_idx);
1651 return WINED3DERR_INVALIDCALL;
1654 stream = &device->stateBlock->state.streams[stream_idx];
1655 *buffer = stream->buffer;
1656 if (*buffer)
1657 wined3d_buffer_incref(*buffer);
1658 if (offset)
1659 *offset = stream->offset;
1660 *stride = stream->stride;
1662 return WINED3D_OK;
1665 HRESULT CDECL wined3d_device_set_stream_source_freq(struct wined3d_device *device, UINT stream_idx, UINT divider)
1667 struct wined3d_stream_state *stream;
1668 UINT old_flags, old_freq;
1670 TRACE("device %p, stream_idx %u, divider %#x.\n", device, stream_idx, divider);
1672 /* Verify input. At least in d3d9 this is invalid. */
1673 if ((divider & WINED3DSTREAMSOURCE_INSTANCEDATA) && (divider & WINED3DSTREAMSOURCE_INDEXEDDATA))
1675 WARN("INSTANCEDATA and INDEXEDDATA were set, returning D3DERR_INVALIDCALL.\n");
1676 return WINED3DERR_INVALIDCALL;
1678 if ((divider & WINED3DSTREAMSOURCE_INSTANCEDATA) && !stream_idx)
1680 WARN("INSTANCEDATA used on stream 0, returning D3DERR_INVALIDCALL.\n");
1681 return WINED3DERR_INVALIDCALL;
1683 if (!divider)
1685 WARN("Divider is 0, returning D3DERR_INVALIDCALL.\n");
1686 return WINED3DERR_INVALIDCALL;
1689 stream = &device->updateStateBlock->state.streams[stream_idx];
1690 old_flags = stream->flags;
1691 old_freq = stream->frequency;
1693 stream->flags = divider & (WINED3DSTREAMSOURCE_INSTANCEDATA | WINED3DSTREAMSOURCE_INDEXEDDATA);
1694 stream->frequency = divider & 0x7fffff;
1696 device->updateStateBlock->changed.streamFreq |= 1 << stream_idx;
1698 if (stream->frequency != old_freq || stream->flags != old_flags)
1699 device_invalidate_state(device, STATE_STREAMSRC);
1701 return WINED3D_OK;
1704 HRESULT CDECL wined3d_device_get_stream_source_freq(const struct wined3d_device *device,
1705 UINT stream_idx, UINT *divider)
1707 struct wined3d_stream_state *stream;
1709 TRACE("device %p, stream_idx %u, divider %p.\n", device, stream_idx, divider);
1711 stream = &device->updateStateBlock->state.streams[stream_idx];
1712 *divider = stream->flags | stream->frequency;
1714 TRACE("Returning %#x.\n", *divider);
1716 return WINED3D_OK;
1719 void CDECL wined3d_device_set_transform(struct wined3d_device *device,
1720 enum wined3d_transform_state d3dts, const struct wined3d_matrix *matrix)
1722 TRACE("device %p, state %s, matrix %p.\n",
1723 device, debug_d3dtstype(d3dts), matrix);
1724 TRACE("%.8e %.8e %.8e %.8e\n", matrix->u.s._11, matrix->u.s._12, matrix->u.s._13, matrix->u.s._14);
1725 TRACE("%.8e %.8e %.8e %.8e\n", matrix->u.s._21, matrix->u.s._22, matrix->u.s._23, matrix->u.s._24);
1726 TRACE("%.8e %.8e %.8e %.8e\n", matrix->u.s._31, matrix->u.s._32, matrix->u.s._33, matrix->u.s._34);
1727 TRACE("%.8e %.8e %.8e %.8e\n", matrix->u.s._41, matrix->u.s._42, matrix->u.s._43, matrix->u.s._44);
1729 /* Handle recording of state blocks. */
1730 if (device->isRecordingState)
1732 TRACE("Recording... not performing anything.\n");
1733 device->updateStateBlock->changed.transform[d3dts >> 5] |= 1 << (d3dts & 0x1f);
1734 device->updateStateBlock->state.transforms[d3dts] = *matrix;
1735 return;
1738 /* If the new matrix is the same as the current one,
1739 * we cut off any further processing. this seems to be a reasonable
1740 * optimization because as was noticed, some apps (warcraft3 for example)
1741 * tend towards setting the same matrix repeatedly for some reason.
1743 * From here on we assume that the new matrix is different, wherever it matters. */
1744 if (!memcmp(&device->stateBlock->state.transforms[d3dts].u.m[0][0], matrix, sizeof(*matrix)))
1746 TRACE("The application is setting the same matrix over again.\n");
1747 return;
1750 device->stateBlock->state.transforms[d3dts] = *matrix;
1751 if (d3dts == WINED3D_TS_VIEW)
1752 device->view_ident = !memcmp(matrix, &identity, sizeof(identity));
1754 if (d3dts < WINED3D_TS_WORLD_MATRIX(device->adapter->gl_info.limits.blends))
1755 device_invalidate_state(device, STATE_TRANSFORM(d3dts));
1758 void CDECL wined3d_device_get_transform(const struct wined3d_device *device,
1759 enum wined3d_transform_state state, struct wined3d_matrix *matrix)
1761 TRACE("device %p, state %s, matrix %p.\n", device, debug_d3dtstype(state), matrix);
1763 *matrix = device->stateBlock->state.transforms[state];
1766 HRESULT CDECL wined3d_device_multiply_transform(struct wined3d_device *device,
1767 enum wined3d_transform_state state, const struct wined3d_matrix *matrix)
1769 const struct wined3d_matrix *mat = NULL;
1770 struct wined3d_matrix temp;
1772 TRACE("device %p, state %s, matrix %p.\n", device, debug_d3dtstype(state), matrix);
1774 /* Note: Using 'updateStateBlock' rather than 'stateblock' in the code
1775 * below means it will be recorded in a state block change, but it
1776 * works regardless where it is recorded.
1777 * If this is found to be wrong, change to StateBlock. */
1778 if (state > HIGHEST_TRANSFORMSTATE)
1780 WARN("Unhandled transform state %#x.\n", state);
1781 return WINED3D_OK;
1784 mat = &device->updateStateBlock->state.transforms[state];
1785 multiply_matrix(&temp, mat, matrix);
1787 /* Apply change via set transform - will reapply to eg. lights this way. */
1788 wined3d_device_set_transform(device, state, &temp);
1790 return WINED3D_OK;
1793 /* Note lights are real special cases. Although the device caps state only
1794 * e.g. 8 are supported, you can reference any indexes you want as long as
1795 * that number max are enabled at any one point in time. Therefore since the
1796 * indices can be anything, we need a hashmap of them. However, this causes
1797 * stateblock problems. When capturing the state block, I duplicate the
1798 * hashmap, but when recording, just build a chain pretty much of commands to
1799 * be replayed. */
1800 HRESULT CDECL wined3d_device_set_light(struct wined3d_device *device,
1801 UINT light_idx, const struct wined3d_light *light)
1803 UINT hash_idx = LIGHTMAP_HASHFUNC(light_idx);
1804 struct wined3d_light_info *object = NULL;
1805 struct list *e;
1806 float rho;
1808 TRACE("device %p, light_idx %u, light %p.\n", device, light_idx, light);
1810 /* Check the parameter range. Need for speed most wanted sets junk lights
1811 * which confuse the GL driver. */
1812 if (!light)
1813 return WINED3DERR_INVALIDCALL;
1815 switch (light->type)
1817 case WINED3D_LIGHT_POINT:
1818 case WINED3D_LIGHT_SPOT:
1819 case WINED3D_LIGHT_PARALLELPOINT:
1820 case WINED3D_LIGHT_GLSPOT:
1821 /* Incorrect attenuation values can cause the gl driver to crash.
1822 * Happens with Need for speed most wanted. */
1823 if (light->attenuation0 < 0.0f || light->attenuation1 < 0.0f || light->attenuation2 < 0.0f)
1825 WARN("Attenuation is negative, returning WINED3DERR_INVALIDCALL.\n");
1826 return WINED3DERR_INVALIDCALL;
1828 break;
1830 case WINED3D_LIGHT_DIRECTIONAL:
1831 /* Ignores attenuation */
1832 break;
1834 default:
1835 WARN("Light type out of range, returning WINED3DERR_INVALIDCALL\n");
1836 return WINED3DERR_INVALIDCALL;
1839 LIST_FOR_EACH(e, &device->updateStateBlock->state.light_map[hash_idx])
1841 object = LIST_ENTRY(e, struct wined3d_light_info, entry);
1842 if (object->OriginalIndex == light_idx)
1843 break;
1844 object = NULL;
1847 if (!object)
1849 TRACE("Adding new light\n");
1850 object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
1851 if (!object)
1853 ERR("Out of memory error when allocating a light\n");
1854 return E_OUTOFMEMORY;
1856 list_add_head(&device->updateStateBlock->state.light_map[hash_idx], &object->entry);
1857 object->glIndex = -1;
1858 object->OriginalIndex = light_idx;
1861 /* Initialize the object. */
1862 TRACE("Light %d setting to type %d, Diffuse(%f,%f,%f,%f), Specular(%f,%f,%f,%f), Ambient(%f,%f,%f,%f)\n",
1863 light_idx, light->type,
1864 light->diffuse.r, light->diffuse.g, light->diffuse.b, light->diffuse.a,
1865 light->specular.r, light->specular.g, light->specular.b, light->specular.a,
1866 light->ambient.r, light->ambient.g, light->ambient.b, light->ambient.a);
1867 TRACE("... Pos(%f,%f,%f), Dir(%f,%f,%f)\n", light->position.x, light->position.y, light->position.z,
1868 light->direction.x, light->direction.y, light->direction.z);
1869 TRACE("... Range(%f), Falloff(%f), Theta(%f), Phi(%f)\n",
1870 light->range, light->falloff, light->theta, light->phi);
1872 /* Save away the information. */
1873 object->OriginalParms = *light;
1875 switch (light->type)
1877 case WINED3D_LIGHT_POINT:
1878 /* Position */
1879 object->lightPosn[0] = light->position.x;
1880 object->lightPosn[1] = light->position.y;
1881 object->lightPosn[2] = light->position.z;
1882 object->lightPosn[3] = 1.0f;
1883 object->cutoff = 180.0f;
1884 /* FIXME: Range */
1885 break;
1887 case WINED3D_LIGHT_DIRECTIONAL:
1888 /* Direction */
1889 object->lightPosn[0] = -light->direction.x;
1890 object->lightPosn[1] = -light->direction.y;
1891 object->lightPosn[2] = -light->direction.z;
1892 object->lightPosn[3] = 0.0f;
1893 object->exponent = 0.0f;
1894 object->cutoff = 180.0f;
1895 break;
1897 case WINED3D_LIGHT_SPOT:
1898 /* Position */
1899 object->lightPosn[0] = light->position.x;
1900 object->lightPosn[1] = light->position.y;
1901 object->lightPosn[2] = light->position.z;
1902 object->lightPosn[3] = 1.0f;
1904 /* Direction */
1905 object->lightDirn[0] = light->direction.x;
1906 object->lightDirn[1] = light->direction.y;
1907 object->lightDirn[2] = light->direction.z;
1908 object->lightDirn[3] = 1.0f;
1910 /* opengl-ish and d3d-ish spot lights use too different models
1911 * for the light "intensity" as a function of the angle towards
1912 * the main light direction, so we only can approximate very
1913 * roughly. However, spot lights are rather rarely used in games
1914 * (if ever used at all). Furthermore if still used, probably
1915 * nobody pays attention to such details. */
1916 if (!light->falloff)
1918 /* Falloff = 0 is easy, because d3d's and opengl's spot light
1919 * equations have the falloff resp. exponent parameter as an
1920 * exponent, so the spot light lighting will always be 1.0 for
1921 * both of them, and we don't have to care for the rest of the
1922 * rather complex calculation. */
1923 object->exponent = 0.0f;
1925 else
1927 rho = light->theta + (light->phi - light->theta) / (2 * light->falloff);
1928 if (rho < 0.0001f)
1929 rho = 0.0001f;
1930 object->exponent = -0.3f / logf(cosf(rho / 2));
1933 if (object->exponent > 128.0f)
1934 object->exponent = 128.0f;
1936 object->cutoff = (float)(light->phi * 90 / M_PI);
1937 /* FIXME: Range */
1938 break;
1940 default:
1941 FIXME("Unrecognized light type %#x.\n", light->type);
1944 /* Update the live definitions if the light is currently assigned a glIndex. */
1945 if (object->glIndex != -1 && !device->isRecordingState)
1946 device_invalidate_state(device, STATE_ACTIVELIGHT(object->glIndex));
1948 return WINED3D_OK;
1951 HRESULT CDECL wined3d_device_get_light(const struct wined3d_device *device,
1952 UINT light_idx, struct wined3d_light *light)
1954 UINT hash_idx = LIGHTMAP_HASHFUNC(light_idx);
1955 struct wined3d_light_info *light_info = NULL;
1956 struct list *e;
1958 TRACE("device %p, light_idx %u, light %p.\n", device, light_idx, light);
1960 LIST_FOR_EACH(e, &device->stateBlock->state.light_map[hash_idx])
1962 light_info = LIST_ENTRY(e, struct wined3d_light_info, entry);
1963 if (light_info->OriginalIndex == light_idx)
1964 break;
1965 light_info = NULL;
1968 if (!light_info)
1970 TRACE("Light information requested but light not defined\n");
1971 return WINED3DERR_INVALIDCALL;
1974 *light = light_info->OriginalParms;
1975 return WINED3D_OK;
1978 HRESULT CDECL wined3d_device_set_light_enable(struct wined3d_device *device, UINT light_idx, BOOL enable)
1980 UINT hash_idx = LIGHTMAP_HASHFUNC(light_idx);
1981 struct wined3d_light_info *light_info = NULL;
1982 struct list *e;
1984 TRACE("device %p, light_idx %u, enable %#x.\n", device, light_idx, enable);
1986 LIST_FOR_EACH(e, &device->updateStateBlock->state.light_map[hash_idx])
1988 light_info = LIST_ENTRY(e, struct wined3d_light_info, entry);
1989 if (light_info->OriginalIndex == light_idx)
1990 break;
1991 light_info = NULL;
1993 TRACE("Found light %p.\n", light_info);
1995 /* Special case - enabling an undefined light creates one with a strict set of parameters. */
1996 if (!light_info)
1998 TRACE("Light enabled requested but light not defined, so defining one!\n");
1999 wined3d_device_set_light(device, light_idx, &WINED3D_default_light);
2001 /* Search for it again! Should be fairly quick as near head of list. */
2002 LIST_FOR_EACH(e, &device->updateStateBlock->state.light_map[hash_idx])
2004 light_info = LIST_ENTRY(e, struct wined3d_light_info, entry);
2005 if (light_info->OriginalIndex == light_idx)
2006 break;
2007 light_info = NULL;
2009 if (!light_info)
2011 FIXME("Adding default lights has failed dismally\n");
2012 return WINED3DERR_INVALIDCALL;
2016 if (!enable)
2018 if (light_info->glIndex != -1)
2020 if (!device->isRecordingState)
2021 device_invalidate_state(device, STATE_ACTIVELIGHT(light_info->glIndex));
2023 device->updateStateBlock->state.lights[light_info->glIndex] = NULL;
2024 light_info->glIndex = -1;
2026 else
2028 TRACE("Light already disabled, nothing to do\n");
2030 light_info->enabled = FALSE;
2032 else
2034 light_info->enabled = TRUE;
2035 if (light_info->glIndex != -1)
2037 TRACE("Nothing to do as light was enabled\n");
2039 else
2041 unsigned int i;
2042 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
2043 /* Find a free GL light. */
2044 for (i = 0; i < gl_info->limits.lights; ++i)
2046 if (!device->updateStateBlock->state.lights[i])
2048 device->updateStateBlock->state.lights[i] = light_info;
2049 light_info->glIndex = i;
2050 break;
2053 if (light_info->glIndex == -1)
2055 /* Our tests show that Windows returns D3D_OK in this situation, even with
2056 * D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_PUREDEVICE devices. This
2057 * is consistent among ddraw, d3d8 and d3d9. GetLightEnable returns TRUE
2058 * as well for those lights.
2060 * TODO: Test how this affects rendering. */
2061 WARN("Too many concurrently active lights\n");
2062 return WINED3D_OK;
2065 /* i == light_info->glIndex */
2066 if (!device->isRecordingState)
2067 device_invalidate_state(device, STATE_ACTIVELIGHT(i));
2071 return WINED3D_OK;
2074 HRESULT CDECL wined3d_device_get_light_enable(const struct wined3d_device *device, UINT light_idx, BOOL *enable)
2076 UINT hash_idx = LIGHTMAP_HASHFUNC(light_idx);
2077 struct wined3d_light_info *light_info = NULL;
2078 struct list *e;
2080 TRACE("device %p, light_idx %u, enable %p.\n", device, light_idx, enable);
2082 LIST_FOR_EACH(e, &device->stateBlock->state.light_map[hash_idx])
2084 light_info = LIST_ENTRY(e, struct wined3d_light_info, entry);
2085 if (light_info->OriginalIndex == light_idx)
2086 break;
2087 light_info = NULL;
2090 if (!light_info)
2092 TRACE("Light enabled state requested but light not defined.\n");
2093 return WINED3DERR_INVALIDCALL;
2095 /* true is 128 according to SetLightEnable */
2096 *enable = light_info->enabled ? 128 : 0;
2097 return WINED3D_OK;
2100 HRESULT CDECL wined3d_device_set_clip_plane(struct wined3d_device *device,
2101 UINT plane_idx, const struct wined3d_vec4 *plane)
2103 TRACE("device %p, plane_idx %u, plane %p.\n", device, plane_idx, plane);
2105 /* Validate plane_idx. */
2106 if (plane_idx >= device->adapter->gl_info.limits.clipplanes)
2108 TRACE("Application has requested clipplane this device doesn't support.\n");
2109 return WINED3DERR_INVALIDCALL;
2112 device->updateStateBlock->changed.clipplane |= 1 << plane_idx;
2114 if (!memcmp(&device->updateStateBlock->state.clip_planes[plane_idx], plane, sizeof(*plane)))
2116 TRACE("Application is setting old values over, nothing to do.\n");
2117 return WINED3D_OK;
2120 device->updateStateBlock->state.clip_planes[plane_idx] = *plane;
2122 /* Handle recording of state blocks. */
2123 if (device->isRecordingState)
2125 TRACE("Recording... not performing anything.\n");
2126 return WINED3D_OK;
2129 device_invalidate_state(device, STATE_CLIPPLANE(plane_idx));
2131 return WINED3D_OK;
2134 HRESULT CDECL wined3d_device_get_clip_plane(const struct wined3d_device *device,
2135 UINT plane_idx, struct wined3d_vec4 *plane)
2137 TRACE("device %p, plane_idx %u, plane %p.\n", device, plane_idx, plane);
2139 /* Validate plane_idx. */
2140 if (plane_idx >= device->adapter->gl_info.limits.clipplanes)
2142 TRACE("Application has requested clipplane this device doesn't support.\n");
2143 return WINED3DERR_INVALIDCALL;
2146 *plane = device->stateBlock->state.clip_planes[plane_idx];
2148 return WINED3D_OK;
2151 HRESULT CDECL wined3d_device_set_clip_status(struct wined3d_device *device,
2152 const struct wined3d_clip_status *clip_status)
2154 FIXME("device %p, clip_status %p stub!\n", device, clip_status);
2156 if (!clip_status)
2157 return WINED3DERR_INVALIDCALL;
2159 return WINED3D_OK;
2162 HRESULT CDECL wined3d_device_get_clip_status(const struct wined3d_device *device,
2163 struct wined3d_clip_status *clip_status)
2165 FIXME("device %p, clip_status %p stub!\n", device, clip_status);
2167 if (!clip_status)
2168 return WINED3DERR_INVALIDCALL;
2170 return WINED3D_OK;
2173 HRESULT CDECL wined3d_device_set_material(struct wined3d_device *device, const struct wined3d_material *material)
2175 TRACE("device %p, material %p.\n", device, material);
2177 device->updateStateBlock->changed.material = TRUE;
2178 device->updateStateBlock->state.material = *material;
2180 /* Handle recording of state blocks */
2181 if (device->isRecordingState)
2183 TRACE("Recording... not performing anything.\n");
2184 return WINED3D_OK;
2187 device_invalidate_state(device, STATE_MATERIAL);
2189 return WINED3D_OK;
2192 HRESULT CDECL wined3d_device_get_material(const struct wined3d_device *device, struct wined3d_material *material)
2194 TRACE("device %p, material %p.\n", device, material);
2196 *material = device->updateStateBlock->state.material;
2198 TRACE("diffuse {%.8e, %.8e, %.8e, %.8e}\n",
2199 material->diffuse.r, material->diffuse.g,
2200 material->diffuse.b, material->diffuse.a);
2201 TRACE("ambient {%.8e, %.8e, %.8e, %.8e}\n",
2202 material->ambient.r, material->ambient.g,
2203 material->ambient.b, material->ambient.a);
2204 TRACE("specular {%.8e, %.8e, %.8e, %.8e}\n",
2205 material->specular.r, material->specular.g,
2206 material->specular.b, material->specular.a);
2207 TRACE("emissive {%.8e, %.8e, %.8e, %.8e}\n",
2208 material->emissive.r, material->emissive.g,
2209 material->emissive.b, material->emissive.a);
2210 TRACE("power %.8e.\n", material->power);
2212 return WINED3D_OK;
2215 void CDECL wined3d_device_set_index_buffer(struct wined3d_device *device,
2216 struct wined3d_buffer *buffer, enum wined3d_format_id format_id)
2218 struct wined3d_buffer *prev_buffer;
2220 TRACE("device %p, buffer %p, format %s.\n",
2221 device, buffer, debug_d3dformat(format_id));
2223 prev_buffer = device->updateStateBlock->state.index_buffer;
2225 device->updateStateBlock->changed.indices = TRUE;
2226 device->updateStateBlock->state.index_buffer = buffer;
2227 device->updateStateBlock->state.index_format = format_id;
2229 /* Handle recording of state blocks. */
2230 if (device->isRecordingState)
2232 TRACE("Recording... not performing anything.\n");
2233 if (buffer)
2234 wined3d_buffer_incref(buffer);
2235 if (prev_buffer)
2236 wined3d_buffer_decref(prev_buffer);
2237 return;
2240 if (prev_buffer != buffer)
2242 device_invalidate_state(device, STATE_INDEXBUFFER);
2243 if (buffer)
2245 InterlockedIncrement(&buffer->resource.bind_count);
2246 wined3d_buffer_incref(buffer);
2248 if (prev_buffer)
2250 InterlockedDecrement(&prev_buffer->resource.bind_count);
2251 wined3d_buffer_decref(prev_buffer);
2256 struct wined3d_buffer * CDECL wined3d_device_get_index_buffer(const struct wined3d_device *device)
2258 TRACE("device %p.\n", device);
2260 return device->stateBlock->state.index_buffer;
2263 void CDECL wined3d_device_set_base_vertex_index(struct wined3d_device *device, INT base_index)
2265 TRACE("device %p, base_index %d.\n", device, base_index);
2267 device->updateStateBlock->state.base_vertex_index = base_index;
2270 INT CDECL wined3d_device_get_base_vertex_index(const struct wined3d_device *device)
2272 TRACE("device %p.\n", device);
2274 return device->stateBlock->state.base_vertex_index;
2277 void CDECL wined3d_device_set_viewport(struct wined3d_device *device, const struct wined3d_viewport *viewport)
2279 TRACE("device %p, viewport %p.\n", device, viewport);
2280 TRACE("x %u, y %u, w %u, h %u, min_z %.8e, max_z %.8e.\n",
2281 viewport->x, viewport->y, viewport->width, viewport->height, viewport->min_z, viewport->max_z);
2283 device->updateStateBlock->changed.viewport = TRUE;
2284 device->updateStateBlock->state.viewport = *viewport;
2286 /* Handle recording of state blocks */
2287 if (device->isRecordingState)
2289 TRACE("Recording... not performing anything\n");
2290 return;
2293 device_invalidate_state(device, STATE_VIEWPORT);
2296 void CDECL wined3d_device_get_viewport(const struct wined3d_device *device, struct wined3d_viewport *viewport)
2298 TRACE("device %p, viewport %p.\n", device, viewport);
2300 *viewport = device->stateBlock->state.viewport;
2303 void CDECL wined3d_device_set_render_state(struct wined3d_device *device,
2304 enum wined3d_render_state state, DWORD value)
2306 DWORD old_value = device->stateBlock->state.render_states[state];
2308 TRACE("device %p, state %s (%#x), value %#x.\n", device, debug_d3drenderstate(state), state, value);
2310 device->updateStateBlock->changed.renderState[state >> 5] |= 1 << (state & 0x1f);
2311 device->updateStateBlock->state.render_states[state] = value;
2313 /* Handle recording of state blocks. */
2314 if (device->isRecordingState)
2316 TRACE("Recording... not performing anything.\n");
2317 return;
2320 /* Compared here and not before the assignment to allow proper stateblock recording. */
2321 if (value == old_value)
2322 TRACE("Application is setting the old value over, nothing to do.\n");
2323 else
2324 device_invalidate_state(device, STATE_RENDER(state));
2327 DWORD CDECL wined3d_device_get_render_state(const struct wined3d_device *device, enum wined3d_render_state state)
2329 TRACE("device %p, state %s (%#x).\n", device, debug_d3drenderstate(state), state);
2331 return device->stateBlock->state.render_states[state];
2334 HRESULT CDECL wined3d_device_set_sampler_state(struct wined3d_device *device,
2335 UINT sampler_idx, enum wined3d_sampler_state state, DWORD value)
2337 DWORD old_value;
2339 TRACE("device %p, sampler_idx %u, state %s, value %#x.\n",
2340 device, sampler_idx, debug_d3dsamplerstate(state), value);
2342 if (sampler_idx >= WINED3DVERTEXTEXTURESAMPLER0 && sampler_idx <= WINED3DVERTEXTEXTURESAMPLER3)
2343 sampler_idx -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
2345 if (sampler_idx >= sizeof(device->stateBlock->state.sampler_states)
2346 / sizeof(*device->stateBlock->state.sampler_states))
2348 WARN("Invalid sampler %u.\n", sampler_idx);
2349 return WINED3D_OK; /* Windows accepts overflowing this array ... we do not. */
2352 old_value = device->stateBlock->state.sampler_states[sampler_idx][state];
2353 device->updateStateBlock->state.sampler_states[sampler_idx][state] = value;
2354 device->updateStateBlock->changed.samplerState[sampler_idx] |= 1 << state;
2356 /* Handle recording of state blocks. */
2357 if (device->isRecordingState)
2359 TRACE("Recording... not performing anything.\n");
2360 return WINED3D_OK;
2363 if (old_value == value)
2365 TRACE("Application is setting the old value over, nothing to do.\n");
2366 return WINED3D_OK;
2369 device_invalidate_state(device, STATE_SAMPLER(sampler_idx));
2371 return WINED3D_OK;
2374 HRESULT CDECL wined3d_device_get_sampler_state(const struct wined3d_device *device,
2375 UINT sampler_idx, enum wined3d_sampler_state state, DWORD *value)
2377 TRACE("device %p, sampler_idx %u, state %s, value %p.\n",
2378 device, sampler_idx, debug_d3dsamplerstate(state), value);
2380 if (sampler_idx >= WINED3DVERTEXTEXTURESAMPLER0 && sampler_idx <= WINED3DVERTEXTEXTURESAMPLER3)
2381 sampler_idx -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
2383 if (sampler_idx >= sizeof(device->stateBlock->state.sampler_states)
2384 / sizeof(*device->stateBlock->state.sampler_states))
2386 WARN("Invalid sampler %u.\n", sampler_idx);
2387 return WINED3D_OK; /* Windows accepts overflowing this array ... we do not. */
2390 *value = device->stateBlock->state.sampler_states[sampler_idx][state];
2391 TRACE("Returning %#x.\n", *value);
2393 return WINED3D_OK;
2396 HRESULT CDECL wined3d_device_set_scissor_rect(struct wined3d_device *device, const RECT *rect)
2398 TRACE("device %p, rect %s.\n", device, wine_dbgstr_rect(rect));
2400 device->updateStateBlock->changed.scissorRect = TRUE;
2401 if (EqualRect(&device->updateStateBlock->state.scissor_rect, rect))
2403 TRACE("App is setting the old scissor rectangle over, nothing to do.\n");
2404 return WINED3D_OK;
2406 CopyRect(&device->updateStateBlock->state.scissor_rect, rect);
2408 if (device->isRecordingState)
2410 TRACE("Recording... not performing anything.\n");
2411 return WINED3D_OK;
2414 device_invalidate_state(device, STATE_SCISSORRECT);
2416 return WINED3D_OK;
2419 HRESULT CDECL wined3d_device_get_scissor_rect(const struct wined3d_device *device, RECT *rect)
2421 TRACE("device %p, rect %p.\n", device, rect);
2423 *rect = device->updateStateBlock->state.scissor_rect;
2424 TRACE("Returning rect %s.\n", wine_dbgstr_rect(rect));
2426 return WINED3D_OK;
2429 HRESULT CDECL wined3d_device_set_vertex_declaration(struct wined3d_device *device,
2430 struct wined3d_vertex_declaration *declaration)
2432 struct wined3d_vertex_declaration *prev = device->updateStateBlock->state.vertex_declaration;
2434 TRACE("device %p, declaration %p.\n", device, declaration);
2436 if (declaration)
2437 wined3d_vertex_declaration_incref(declaration);
2438 if (prev)
2439 wined3d_vertex_declaration_decref(prev);
2441 device->updateStateBlock->state.vertex_declaration = declaration;
2442 device->updateStateBlock->changed.vertexDecl = TRUE;
2444 if (device->isRecordingState)
2446 TRACE("Recording... not performing anything.\n");
2447 return WINED3D_OK;
2449 else if (declaration == prev)
2451 /* Checked after the assignment to allow proper stateblock recording. */
2452 TRACE("Application is setting the old declaration over, nothing to do.\n");
2453 return WINED3D_OK;
2456 device_invalidate_state(device, STATE_VDECL);
2457 return WINED3D_OK;
2460 HRESULT CDECL wined3d_device_get_vertex_declaration(const struct wined3d_device *device,
2461 struct wined3d_vertex_declaration **declaration)
2463 TRACE("device %p, declaration %p.\n", device, declaration);
2465 *declaration = device->stateBlock->state.vertex_declaration;
2466 if (*declaration)
2467 wined3d_vertex_declaration_incref(*declaration);
2469 return WINED3D_OK;
2472 HRESULT CDECL wined3d_device_set_vertex_shader(struct wined3d_device *device, struct wined3d_shader *shader)
2474 struct wined3d_shader *prev = device->updateStateBlock->state.vertex_shader;
2476 TRACE("device %p, shader %p.\n", device, shader);
2478 device->updateStateBlock->state.vertex_shader = shader;
2479 device->updateStateBlock->changed.vertexShader = TRUE;
2481 if (device->isRecordingState)
2483 if (shader)
2484 wined3d_shader_incref(shader);
2485 if (prev)
2486 wined3d_shader_decref(prev);
2487 TRACE("Recording... not performing anything.\n");
2488 return WINED3D_OK;
2491 if (shader == prev)
2493 TRACE("Application is setting the old shader over, nothing to do.\n");
2494 return WINED3D_OK;
2497 if (shader)
2498 wined3d_shader_incref(shader);
2499 if (prev)
2500 wined3d_shader_decref(prev);
2502 device_invalidate_state(device, STATE_VSHADER);
2504 return WINED3D_OK;
2507 struct wined3d_shader * CDECL wined3d_device_get_vertex_shader(const struct wined3d_device *device)
2509 struct wined3d_shader *shader;
2511 TRACE("device %p.\n", device);
2513 shader = device->stateBlock->state.vertex_shader;
2514 if (shader)
2515 wined3d_shader_incref(shader);
2517 TRACE("Returning %p.\n", shader);
2518 return shader;
2521 HRESULT CDECL wined3d_device_set_vs_consts_b(struct wined3d_device *device,
2522 UINT start_register, const BOOL *constants, UINT bool_count)
2524 UINT count = min(bool_count, MAX_CONST_B - start_register);
2525 UINT i;
2527 TRACE("device %p, start_register %u, constants %p, bool_count %u.\n",
2528 device, start_register, constants, bool_count);
2530 if (!constants || start_register >= MAX_CONST_B)
2531 return WINED3DERR_INVALIDCALL;
2533 memcpy(&device->updateStateBlock->state.vs_consts_b[start_register], constants, count * sizeof(BOOL));
2534 for (i = 0; i < count; ++i)
2535 TRACE("Set BOOL constant %u to %s.\n", start_register + i, constants[i] ? "true" : "false");
2537 for (i = start_register; i < count + start_register; ++i)
2538 device->updateStateBlock->changed.vertexShaderConstantsB |= (1 << i);
2540 if (!device->isRecordingState)
2541 device_invalidate_state(device, STATE_VERTEXSHADERCONSTANT);
2543 return WINED3D_OK;
2546 HRESULT CDECL wined3d_device_get_vs_consts_b(const struct wined3d_device *device,
2547 UINT start_register, BOOL *constants, UINT bool_count)
2549 UINT count = min(bool_count, MAX_CONST_B - start_register);
2551 TRACE("device %p, start_register %u, constants %p, bool_count %u.\n",
2552 device, start_register, constants, bool_count);
2554 if (!constants || start_register >= MAX_CONST_B)
2555 return WINED3DERR_INVALIDCALL;
2557 memcpy(constants, &device->stateBlock->state.vs_consts_b[start_register], count * sizeof(BOOL));
2559 return WINED3D_OK;
2562 HRESULT CDECL wined3d_device_set_vs_consts_i(struct wined3d_device *device,
2563 UINT start_register, const int *constants, UINT vector4i_count)
2565 UINT count = min(vector4i_count, MAX_CONST_I - start_register);
2566 UINT i;
2568 TRACE("device %p, start_register %u, constants %p, vector4i_count %u.\n",
2569 device, start_register, constants, vector4i_count);
2571 if (!constants || start_register >= MAX_CONST_I)
2572 return WINED3DERR_INVALIDCALL;
2574 memcpy(&device->updateStateBlock->state.vs_consts_i[start_register * 4], constants, count * sizeof(int) * 4);
2575 for (i = 0; i < count; ++i)
2576 TRACE("Set INT constant %u to {%d, %d, %d, %d}.\n", start_register + i,
2577 constants[i * 4], constants[i * 4 + 1],
2578 constants[i * 4 + 2], constants[i * 4 + 3]);
2580 for (i = start_register; i < count + start_register; ++i)
2581 device->updateStateBlock->changed.vertexShaderConstantsI |= (1 << i);
2583 if (!device->isRecordingState)
2584 device_invalidate_state(device, STATE_VERTEXSHADERCONSTANT);
2586 return WINED3D_OK;
2589 HRESULT CDECL wined3d_device_get_vs_consts_i(const struct wined3d_device *device,
2590 UINT start_register, int *constants, UINT vector4i_count)
2592 UINT count = min(vector4i_count, MAX_CONST_I - start_register);
2594 TRACE("device %p, start_register %u, constants %p, vector4i_count %u.\n",
2595 device, start_register, constants, vector4i_count);
2597 if (!constants || start_register >= MAX_CONST_I)
2598 return WINED3DERR_INVALIDCALL;
2600 memcpy(constants, &device->stateBlock->state.vs_consts_i[start_register * 4], count * sizeof(int) * 4);
2601 return WINED3D_OK;
2604 HRESULT CDECL wined3d_device_set_vs_consts_f(struct wined3d_device *device,
2605 UINT start_register, const float *constants, UINT vector4f_count)
2607 UINT i;
2609 TRACE("device %p, start_register %u, constants %p, vector4f_count %u.\n",
2610 device, start_register, constants, vector4f_count);
2612 /* Specifically test start_register > limit to catch MAX_UINT overflows
2613 * when adding start_register + vector4f_count. */
2614 if (!constants
2615 || start_register + vector4f_count > device->d3d_vshader_constantF
2616 || start_register > device->d3d_vshader_constantF)
2617 return WINED3DERR_INVALIDCALL;
2619 memcpy(&device->updateStateBlock->state.vs_consts_f[start_register * 4],
2620 constants, vector4f_count * sizeof(float) * 4);
2621 if (TRACE_ON(d3d))
2623 for (i = 0; i < vector4f_count; ++i)
2624 TRACE("Set FLOAT constant %u to {%.8e, %.8e, %.8e, %.8e}.\n", start_register + i,
2625 constants[i * 4], constants[i * 4 + 1],
2626 constants[i * 4 + 2], constants[i * 4 + 3]);
2629 if (!device->isRecordingState)
2631 device->shader_backend->shader_update_float_vertex_constants(device, start_register, vector4f_count);
2632 device_invalidate_state(device, STATE_VERTEXSHADERCONSTANT);
2635 memset(device->updateStateBlock->changed.vertexShaderConstantsF + start_register, 1,
2636 sizeof(*device->updateStateBlock->changed.vertexShaderConstantsF) * vector4f_count);
2638 return WINED3D_OK;
2641 HRESULT CDECL wined3d_device_get_vs_consts_f(const struct wined3d_device *device,
2642 UINT start_register, float *constants, UINT vector4f_count)
2644 int count = min(vector4f_count, device->d3d_vshader_constantF - start_register);
2646 TRACE("device %p, start_register %u, constants %p, vector4f_count %u.\n",
2647 device, start_register, constants, vector4f_count);
2649 if (!constants || count < 0)
2650 return WINED3DERR_INVALIDCALL;
2652 memcpy(constants, &device->stateBlock->state.vs_consts_f[start_register * 4], count * sizeof(float) * 4);
2654 return WINED3D_OK;
2657 static void device_invalidate_texture_stage(const struct wined3d_device *device, DWORD stage)
2659 DWORD i;
2661 for (i = 0; i <= WINED3D_HIGHEST_TEXTURE_STATE; ++i)
2663 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, i));
2667 static void device_map_stage(struct wined3d_device *device, DWORD stage, DWORD unit)
2669 DWORD i = device->rev_tex_unit_map[unit];
2670 DWORD j = device->texUnitMap[stage];
2672 device->texUnitMap[stage] = unit;
2673 if (i != WINED3D_UNMAPPED_STAGE && i != stage)
2674 device->texUnitMap[i] = WINED3D_UNMAPPED_STAGE;
2676 device->rev_tex_unit_map[unit] = stage;
2677 if (j != WINED3D_UNMAPPED_STAGE && j != unit)
2678 device->rev_tex_unit_map[j] = WINED3D_UNMAPPED_STAGE;
2681 static void device_update_fixed_function_usage_map(struct wined3d_device *device)
2683 UINT i;
2685 device->fixed_function_usage_map = 0;
2686 for (i = 0; i < MAX_TEXTURES; ++i)
2688 const struct wined3d_state *state = &device->stateBlock->state;
2689 enum wined3d_texture_op color_op = state->texture_states[i][WINED3D_TSS_COLOR_OP];
2690 enum wined3d_texture_op alpha_op = state->texture_states[i][WINED3D_TSS_ALPHA_OP];
2691 DWORD color_arg1 = state->texture_states[i][WINED3D_TSS_COLOR_ARG1] & WINED3DTA_SELECTMASK;
2692 DWORD color_arg2 = state->texture_states[i][WINED3D_TSS_COLOR_ARG2] & WINED3DTA_SELECTMASK;
2693 DWORD color_arg3 = state->texture_states[i][WINED3D_TSS_COLOR_ARG0] & WINED3DTA_SELECTMASK;
2694 DWORD alpha_arg1 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG1] & WINED3DTA_SELECTMASK;
2695 DWORD alpha_arg2 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG2] & WINED3DTA_SELECTMASK;
2696 DWORD alpha_arg3 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG0] & WINED3DTA_SELECTMASK;
2698 /* Not used, and disable higher stages. */
2699 if (color_op == WINED3D_TOP_DISABLE)
2700 break;
2702 if (((color_arg1 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG2)
2703 || ((color_arg2 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG1)
2704 || ((color_arg3 == WINED3DTA_TEXTURE)
2705 && (color_op == WINED3D_TOP_MULTIPLY_ADD || color_op == WINED3D_TOP_LERP))
2706 || ((alpha_arg1 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG2)
2707 || ((alpha_arg2 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG1)
2708 || ((alpha_arg3 == WINED3DTA_TEXTURE)
2709 && (alpha_op == WINED3D_TOP_MULTIPLY_ADD || alpha_op == WINED3D_TOP_LERP)))
2710 device->fixed_function_usage_map |= (1 << i);
2712 if ((color_op == WINED3D_TOP_BUMPENVMAP || color_op == WINED3D_TOP_BUMPENVMAP_LUMINANCE)
2713 && i < MAX_TEXTURES - 1)
2714 device->fixed_function_usage_map |= (1 << (i + 1));
2718 static void device_map_fixed_function_samplers(struct wined3d_device *device, const struct wined3d_gl_info *gl_info)
2720 unsigned int i, tex;
2721 WORD ffu_map;
2723 device_update_fixed_function_usage_map(device);
2724 ffu_map = device->fixed_function_usage_map;
2726 if (device->max_ffp_textures == gl_info->limits.texture_stages
2727 || device->stateBlock->state.lowest_disabled_stage <= device->max_ffp_textures)
2729 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2731 if (!(ffu_map & 1)) continue;
2733 if (device->texUnitMap[i] != i)
2735 device_map_stage(device, i, i);
2736 device_invalidate_state(device, STATE_SAMPLER(i));
2737 device_invalidate_texture_stage(device, i);
2740 return;
2743 /* Now work out the mapping */
2744 tex = 0;
2745 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2747 if (!(ffu_map & 1)) continue;
2749 if (device->texUnitMap[i] != tex)
2751 device_map_stage(device, i, tex);
2752 device_invalidate_state(device, STATE_SAMPLER(i));
2753 device_invalidate_texture_stage(device, i);
2756 ++tex;
2760 static void device_map_psamplers(struct wined3d_device *device, const struct wined3d_gl_info *gl_info)
2762 const enum wined3d_sampler_texture_type *sampler_type =
2763 device->stateBlock->state.pixel_shader->reg_maps.sampler_type;
2764 unsigned int i;
2766 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
2768 if (sampler_type[i] && device->texUnitMap[i] != i)
2770 device_map_stage(device, i, i);
2771 device_invalidate_state(device, STATE_SAMPLER(i));
2772 if (i < gl_info->limits.texture_stages)
2773 device_invalidate_texture_stage(device, i);
2778 static BOOL device_unit_free_for_vs(const struct wined3d_device *device,
2779 const enum wined3d_sampler_texture_type *pshader_sampler_tokens,
2780 const enum wined3d_sampler_texture_type *vshader_sampler_tokens, DWORD unit)
2782 DWORD current_mapping = device->rev_tex_unit_map[unit];
2784 /* Not currently used */
2785 if (current_mapping == WINED3D_UNMAPPED_STAGE) return TRUE;
2787 if (current_mapping < MAX_FRAGMENT_SAMPLERS) {
2788 /* Used by a fragment sampler */
2790 if (!pshader_sampler_tokens) {
2791 /* No pixel shader, check fixed function */
2792 return current_mapping >= MAX_TEXTURES || !(device->fixed_function_usage_map & (1 << current_mapping));
2795 /* Pixel shader, check the shader's sampler map */
2796 return !pshader_sampler_tokens[current_mapping];
2799 /* Used by a vertex sampler */
2800 return !vshader_sampler_tokens[current_mapping - MAX_FRAGMENT_SAMPLERS];
2803 static void device_map_vsamplers(struct wined3d_device *device, BOOL ps, const struct wined3d_gl_info *gl_info)
2805 const enum wined3d_sampler_texture_type *vshader_sampler_type =
2806 device->stateBlock->state.vertex_shader->reg_maps.sampler_type;
2807 const enum wined3d_sampler_texture_type *pshader_sampler_type = NULL;
2808 int start = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers) - 1;
2809 int i;
2811 if (ps)
2813 /* Note that we only care if a sampler is sampled or not, not the sampler's specific type.
2814 * Otherwise we'd need to call shader_update_samplers() here for 1.x pixelshaders. */
2815 pshader_sampler_type = device->stateBlock->state.pixel_shader->reg_maps.sampler_type;
2818 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i) {
2819 DWORD vsampler_idx = i + MAX_FRAGMENT_SAMPLERS;
2820 if (vshader_sampler_type[i])
2822 if (device->texUnitMap[vsampler_idx] != WINED3D_UNMAPPED_STAGE)
2824 /* Already mapped somewhere */
2825 continue;
2828 while (start >= 0)
2830 if (device_unit_free_for_vs(device, pshader_sampler_type, vshader_sampler_type, start))
2832 device_map_stage(device, vsampler_idx, start);
2833 device_invalidate_state(device, STATE_SAMPLER(vsampler_idx));
2835 --start;
2836 break;
2839 --start;
2845 void device_update_tex_unit_map(struct wined3d_device *device)
2847 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
2848 const struct wined3d_state *state = &device->stateBlock->state;
2849 BOOL vs = use_vs(state);
2850 BOOL ps = use_ps(state);
2852 * Rules are:
2853 * -> Pixel shaders need a 1:1 map. In theory the shader input could be mapped too, but
2854 * that would be really messy and require shader recompilation
2855 * -> When the mapping of a stage is changed, sampler and ALL texture stage states have
2856 * to be reset. Because of that try to work with a 1:1 mapping as much as possible
2858 if (ps)
2859 device_map_psamplers(device, gl_info);
2860 else
2861 device_map_fixed_function_samplers(device, gl_info);
2863 if (vs)
2864 device_map_vsamplers(device, ps, gl_info);
2867 HRESULT CDECL wined3d_device_set_pixel_shader(struct wined3d_device *device, struct wined3d_shader *shader)
2869 struct wined3d_shader *prev = device->updateStateBlock->state.pixel_shader;
2871 TRACE("device %p, shader %p.\n", device, shader);
2873 device->updateStateBlock->state.pixel_shader = shader;
2874 device->updateStateBlock->changed.pixelShader = TRUE;
2876 if (device->isRecordingState)
2878 if (shader)
2879 wined3d_shader_incref(shader);
2880 if (prev)
2881 wined3d_shader_decref(prev);
2882 TRACE("Recording... not performing anything.\n");
2883 return WINED3D_OK;
2886 if (shader == prev)
2888 TRACE("Application is setting the old shader over, nothing to do.\n");
2889 return WINED3D_OK;
2892 if (shader)
2893 wined3d_shader_incref(shader);
2894 if (prev)
2895 wined3d_shader_decref(prev);
2897 device_invalidate_state(device, STATE_PIXELSHADER);
2899 return WINED3D_OK;
2902 struct wined3d_shader * CDECL wined3d_device_get_pixel_shader(const struct wined3d_device *device)
2904 struct wined3d_shader *shader;
2906 TRACE("device %p.\n", device);
2908 shader = device->stateBlock->state.pixel_shader;
2909 if (shader)
2910 wined3d_shader_incref(shader);
2912 TRACE("Returning %p.\n", shader);
2913 return shader;
2916 HRESULT CDECL wined3d_device_set_ps_consts_b(struct wined3d_device *device,
2917 UINT start_register, const BOOL *constants, UINT bool_count)
2919 UINT count = min(bool_count, MAX_CONST_B - start_register);
2920 UINT i;
2922 TRACE("device %p, start_register %u, constants %p, bool_count %u.\n",
2923 device, start_register, constants, bool_count);
2925 if (!constants || start_register >= MAX_CONST_B)
2926 return WINED3DERR_INVALIDCALL;
2928 memcpy(&device->updateStateBlock->state.ps_consts_b[start_register], constants, count * sizeof(BOOL));
2929 for (i = 0; i < count; ++i)
2930 TRACE("Set BOOL constant %u to %s.\n", start_register + i, constants[i] ? "true" : "false");
2932 for (i = start_register; i < count + start_register; ++i)
2933 device->updateStateBlock->changed.pixelShaderConstantsB |= (1 << i);
2935 if (!device->isRecordingState)
2936 device_invalidate_state(device, STATE_PIXELSHADERCONSTANT);
2938 return WINED3D_OK;
2941 HRESULT CDECL wined3d_device_get_ps_consts_b(const struct wined3d_device *device,
2942 UINT start_register, BOOL *constants, UINT bool_count)
2944 UINT count = min(bool_count, MAX_CONST_B - start_register);
2946 TRACE("device %p, start_register %u, constants %p, bool_count %u.\n",
2947 device, start_register, constants, bool_count);
2949 if (!constants || start_register >= MAX_CONST_B)
2950 return WINED3DERR_INVALIDCALL;
2952 memcpy(constants, &device->stateBlock->state.ps_consts_b[start_register], count * sizeof(BOOL));
2954 return WINED3D_OK;
2957 HRESULT CDECL wined3d_device_set_ps_consts_i(struct wined3d_device *device,
2958 UINT start_register, const int *constants, UINT vector4i_count)
2960 UINT count = min(vector4i_count, MAX_CONST_I - start_register);
2961 UINT i;
2963 TRACE("device %p, start_register %u, constants %p, vector4i_count %u.\n",
2964 device, start_register, constants, vector4i_count);
2966 if (!constants || start_register >= MAX_CONST_I)
2967 return WINED3DERR_INVALIDCALL;
2969 memcpy(&device->updateStateBlock->state.ps_consts_i[start_register * 4], constants, count * sizeof(int) * 4);
2970 for (i = 0; i < count; ++i)
2971 TRACE("Set INT constant %u to {%d, %d, %d, %d}.\n", start_register + i,
2972 constants[i * 4], constants[i * 4 + 1],
2973 constants[i * 4 + 2], constants[i * 4 + 3]);
2975 for (i = start_register; i < count + start_register; ++i)
2976 device->updateStateBlock->changed.pixelShaderConstantsI |= (1 << i);
2978 if (!device->isRecordingState)
2979 device_invalidate_state(device, STATE_PIXELSHADERCONSTANT);
2981 return WINED3D_OK;
2984 HRESULT CDECL wined3d_device_get_ps_consts_i(const struct wined3d_device *device,
2985 UINT start_register, int *constants, UINT vector4i_count)
2987 UINT count = min(vector4i_count, MAX_CONST_I - start_register);
2989 TRACE("device %p, start_register %u, constants %p, vector4i_count %u.\n",
2990 device, start_register, constants, vector4i_count);
2992 if (!constants || start_register >= MAX_CONST_I)
2993 return WINED3DERR_INVALIDCALL;
2995 memcpy(constants, &device->stateBlock->state.ps_consts_i[start_register * 4], count * sizeof(int) * 4);
2997 return WINED3D_OK;
3000 HRESULT CDECL wined3d_device_set_ps_consts_f(struct wined3d_device *device,
3001 UINT start_register, const float *constants, UINT vector4f_count)
3003 UINT i;
3005 TRACE("device %p, start_register %u, constants %p, vector4f_count %u.\n",
3006 device, start_register, constants, vector4f_count);
3008 /* Specifically test start_register > limit to catch MAX_UINT overflows
3009 * when adding start_register + vector4f_count. */
3010 if (!constants
3011 || start_register + vector4f_count > device->d3d_pshader_constantF
3012 || start_register > device->d3d_pshader_constantF)
3013 return WINED3DERR_INVALIDCALL;
3015 memcpy(&device->updateStateBlock->state.ps_consts_f[start_register * 4],
3016 constants, vector4f_count * sizeof(float) * 4);
3017 if (TRACE_ON(d3d))
3019 for (i = 0; i < vector4f_count; ++i)
3020 TRACE("Set FLOAT constant %u to {%.8e, %.8e, %.8e, %.8e}.\n", start_register + i,
3021 constants[i * 4], constants[i * 4 + 1],
3022 constants[i * 4 + 2], constants[i * 4 + 3]);
3025 if (!device->isRecordingState)
3027 device->shader_backend->shader_update_float_pixel_constants(device, start_register, vector4f_count);
3028 device_invalidate_state(device, STATE_PIXELSHADERCONSTANT);
3031 memset(device->updateStateBlock->changed.pixelShaderConstantsF + start_register, 1,
3032 sizeof(*device->updateStateBlock->changed.pixelShaderConstantsF) * vector4f_count);
3034 return WINED3D_OK;
3037 HRESULT CDECL wined3d_device_get_ps_consts_f(const struct wined3d_device *device,
3038 UINT start_register, float *constants, UINT vector4f_count)
3040 int count = min(vector4f_count, device->d3d_pshader_constantF - start_register);
3042 TRACE("device %p, start_register %u, constants %p, vector4f_count %u.\n",
3043 device, start_register, constants, vector4f_count);
3045 if (!constants || count < 0)
3046 return WINED3DERR_INVALIDCALL;
3048 memcpy(constants, &device->stateBlock->state.ps_consts_f[start_register * 4], count * sizeof(float) * 4);
3050 return WINED3D_OK;
3053 /* Context activation is done by the caller. */
3054 /* Do not call while under the GL lock. */
3055 #define copy_and_next(dest, src, size) memcpy(dest, src, size); dest += (size)
3056 static HRESULT process_vertices_strided(const struct wined3d_device *device, DWORD dwDestIndex, DWORD dwCount,
3057 const struct wined3d_stream_info *stream_info, struct wined3d_buffer *dest, DWORD flags,
3058 DWORD DestFVF)
3060 struct wined3d_matrix mat, proj_mat, view_mat, world_mat;
3061 struct wined3d_viewport vp;
3062 UINT vertex_size;
3063 unsigned int i;
3064 BYTE *dest_ptr;
3065 BOOL doClip;
3066 DWORD numTextures;
3067 HRESULT hr;
3069 if (stream_info->use_map & (1 << WINED3D_FFP_NORMAL))
3071 WARN(" lighting state not saved yet... Some strange stuff may happen !\n");
3074 if (!(stream_info->use_map & (1 << WINED3D_FFP_POSITION)))
3076 ERR("Source has no position mask\n");
3077 return WINED3DERR_INVALIDCALL;
3080 if (device->stateBlock->state.render_states[WINED3D_RS_CLIPPING])
3082 static BOOL warned = FALSE;
3084 * The clipping code is not quite correct. Some things need
3085 * to be checked against IDirect3DDevice3 (!), d3d8 and d3d9,
3086 * so disable clipping for now.
3087 * (The graphics in Half-Life are broken, and my processvertices
3088 * test crashes with IDirect3DDevice3)
3089 doClip = TRUE;
3091 doClip = FALSE;
3092 if(!warned) {
3093 warned = TRUE;
3094 FIXME("Clipping is broken and disabled for now\n");
3097 else
3098 doClip = FALSE;
3100 vertex_size = get_flexible_vertex_size(DestFVF);
3101 if (FAILED(hr = wined3d_buffer_map(dest, dwDestIndex * vertex_size, dwCount * vertex_size, &dest_ptr, 0)))
3103 WARN("Failed to map buffer, hr %#x.\n", hr);
3104 return hr;
3107 wined3d_device_get_transform(device, WINED3D_TS_VIEW, &view_mat);
3108 wined3d_device_get_transform(device, WINED3D_TS_PROJECTION, &proj_mat);
3109 wined3d_device_get_transform(device, WINED3D_TS_WORLD_MATRIX(0), &world_mat);
3111 TRACE("View mat:\n");
3112 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);
3113 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);
3114 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);
3115 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);
3117 TRACE("Proj mat:\n");
3118 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);
3119 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);
3120 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);
3121 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);
3123 TRACE("World mat:\n");
3124 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);
3125 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);
3126 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);
3127 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);
3129 /* Get the viewport */
3130 wined3d_device_get_viewport(device, &vp);
3131 TRACE("viewport x %u, y %u, width %u, height %u, min_z %.8e, max_z %.8e.\n",
3132 vp.x, vp.y, vp.width, vp.height, vp.min_z, vp.max_z);
3134 multiply_matrix(&mat,&view_mat,&world_mat);
3135 multiply_matrix(&mat,&proj_mat,&mat);
3137 numTextures = (DestFVF & WINED3DFVF_TEXCOUNT_MASK) >> WINED3DFVF_TEXCOUNT_SHIFT;
3139 for (i = 0; i < dwCount; i+= 1) {
3140 unsigned int tex_index;
3142 if ( ((DestFVF & WINED3DFVF_POSITION_MASK) == WINED3DFVF_XYZ ) ||
3143 ((DestFVF & WINED3DFVF_POSITION_MASK) == WINED3DFVF_XYZRHW ) ) {
3144 /* The position first */
3145 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_POSITION];
3146 const float *p = (const float *)(element->data.addr + i * element->stride);
3147 float x, y, z, rhw;
3148 TRACE("In: ( %06.2f %06.2f %06.2f )\n", p[0], p[1], p[2]);
3150 /* Multiplication with world, view and projection matrix */
3151 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);
3152 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);
3153 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);
3154 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);
3156 TRACE("x=%f y=%f z=%f rhw=%f\n", x, y, z, rhw);
3158 /* WARNING: The following things are taken from d3d7 and were not yet checked
3159 * against d3d8 or d3d9!
3162 /* Clipping conditions: From msdn
3164 * A vertex is clipped if it does not match the following requirements
3165 * -rhw < x <= rhw
3166 * -rhw < y <= rhw
3167 * 0 < z <= rhw
3168 * 0 < rhw ( Not in d3d7, but tested in d3d7)
3170 * If clipping is on is determined by the D3DVOP_CLIP flag in D3D7, and
3171 * by the D3DRS_CLIPPING in D3D9(according to the msdn, not checked)
3175 if( !doClip ||
3176 ( (-rhw -eps < x) && (-rhw -eps < y) && ( -eps < z) &&
3177 (x <= rhw + eps) && (y <= rhw + eps ) && (z <= rhw + eps) &&
3178 ( rhw > eps ) ) ) {
3180 /* "Normal" viewport transformation (not clipped)
3181 * 1) The values are divided by rhw
3182 * 2) The y axis is negative, so multiply it with -1
3183 * 3) Screen coordinates go from -(Width/2) to +(Width/2) and
3184 * -(Height/2) to +(Height/2). The z range is MinZ to MaxZ
3185 * 4) Multiply x with Width/2 and add Width/2
3186 * 5) The same for the height
3187 * 6) Add the viewpoint X and Y to the 2D coordinates and
3188 * The minimum Z value to z
3189 * 7) rhw = 1 / rhw Reciprocal of Homogeneous W....
3191 * Well, basically it's simply a linear transformation into viewport
3192 * coordinates
3195 x /= rhw;
3196 y /= rhw;
3197 z /= rhw;
3199 y *= -1;
3201 x *= vp.width / 2;
3202 y *= vp.height / 2;
3203 z *= vp.max_z - vp.min_z;
3205 x += vp.width / 2 + vp.x;
3206 y += vp.height / 2 + vp.y;
3207 z += vp.min_z;
3209 rhw = 1 / rhw;
3210 } else {
3211 /* That vertex got clipped
3212 * Contrary to OpenGL it is not dropped completely, it just
3213 * undergoes a different calculation.
3215 TRACE("Vertex got clipped\n");
3216 x += rhw;
3217 y += rhw;
3219 x /= 2;
3220 y /= 2;
3222 /* Msdn mentions that Direct3D9 keeps a list of clipped vertices
3223 * outside of the main vertex buffer memory. That needs some more
3224 * investigation...
3228 TRACE("Writing (%f %f %f) %f\n", x, y, z, rhw);
3231 ( (float *) dest_ptr)[0] = x;
3232 ( (float *) dest_ptr)[1] = y;
3233 ( (float *) dest_ptr)[2] = z;
3234 ( (float *) dest_ptr)[3] = rhw; /* SIC, see ddraw test! */
3236 dest_ptr += 3 * sizeof(float);
3238 if ((DestFVF & WINED3DFVF_POSITION_MASK) == WINED3DFVF_XYZRHW)
3239 dest_ptr += sizeof(float);
3242 if (DestFVF & WINED3DFVF_PSIZE)
3243 dest_ptr += sizeof(DWORD);
3245 if (DestFVF & WINED3DFVF_NORMAL)
3247 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_NORMAL];
3248 const float *normal = (const float *)(element->data.addr + i * element->stride);
3249 /* AFAIK this should go into the lighting information */
3250 FIXME("Didn't expect the destination to have a normal\n");
3251 copy_and_next(dest_ptr, normal, 3 * sizeof(float));
3254 if (DestFVF & WINED3DFVF_DIFFUSE)
3256 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_DIFFUSE];
3257 const DWORD *color_d = (const DWORD *)(element->data.addr + i * element->stride);
3258 if (!(stream_info->use_map & (1 << WINED3D_FFP_DIFFUSE)))
3260 static BOOL warned = FALSE;
3262 if(!warned) {
3263 ERR("No diffuse color in source, but destination has one\n");
3264 warned = TRUE;
3267 *( (DWORD *) dest_ptr) = 0xffffffff;
3268 dest_ptr += sizeof(DWORD);
3270 else
3272 copy_and_next(dest_ptr, color_d, sizeof(DWORD));
3276 if (DestFVF & WINED3DFVF_SPECULAR)
3278 /* What's the color value in the feedback buffer? */
3279 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_SPECULAR];
3280 const DWORD *color_s = (const DWORD *)(element->data.addr + i * element->stride);
3281 if (!(stream_info->use_map & (1 << WINED3D_FFP_SPECULAR)))
3283 static BOOL warned = FALSE;
3285 if(!warned) {
3286 ERR("No specular color in source, but destination has one\n");
3287 warned = TRUE;
3290 *(DWORD *)dest_ptr = 0xff000000;
3291 dest_ptr += sizeof(DWORD);
3293 else
3295 copy_and_next(dest_ptr, color_s, sizeof(DWORD));
3299 for (tex_index = 0; tex_index < numTextures; ++tex_index)
3301 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_TEXCOORD0 + tex_index];
3302 const float *tex_coord = (const float *)(element->data.addr + i * element->stride);
3303 if (!(stream_info->use_map & (1 << (WINED3D_FFP_TEXCOORD0 + tex_index))))
3305 ERR("No source texture, but destination requests one\n");
3306 dest_ptr += GET_TEXCOORD_SIZE_FROM_FVF(DestFVF, tex_index) * sizeof(float);
3308 else
3310 copy_and_next(dest_ptr, tex_coord, GET_TEXCOORD_SIZE_FROM_FVF(DestFVF, tex_index) * sizeof(float));
3315 wined3d_buffer_unmap(dest);
3317 return WINED3D_OK;
3319 #undef copy_and_next
3321 /* Do not call while under the GL lock. */
3322 HRESULT CDECL wined3d_device_process_vertices(struct wined3d_device *device,
3323 UINT src_start_idx, UINT dst_idx, UINT vertex_count, struct wined3d_buffer *dst_buffer,
3324 const struct wined3d_vertex_declaration *declaration, DWORD flags, DWORD dst_fvf)
3326 struct wined3d_state *state = &device->stateBlock->state;
3327 struct wined3d_stream_info stream_info;
3328 const struct wined3d_gl_info *gl_info;
3329 BOOL streamWasUP = state->user_stream;
3330 struct wined3d_context *context;
3331 struct wined3d_shader *vs;
3332 unsigned int i;
3333 HRESULT hr;
3335 TRACE("device %p, src_start_idx %u, dst_idx %u, vertex_count %u, "
3336 "dst_buffer %p, declaration %p, flags %#x, dst_fvf %#x.\n",
3337 device, src_start_idx, dst_idx, vertex_count,
3338 dst_buffer, declaration, flags, dst_fvf);
3340 if (declaration)
3341 FIXME("Output vertex declaration not implemented yet.\n");
3343 /* Need any context to write to the vbo. */
3344 context = context_acquire(device, NULL);
3345 gl_info = context->gl_info;
3347 /* ProcessVertices reads from vertex buffers, which have to be assigned.
3348 * DrawPrimitive and DrawPrimitiveUP control the streamIsUP flag, thus
3349 * restore it afterwards. */
3350 vs = state->vertex_shader;
3351 state->vertex_shader = NULL;
3352 state->user_stream = FALSE;
3353 device_stream_info_from_declaration(device, &stream_info);
3354 state->user_stream = streamWasUP;
3355 state->vertex_shader = vs;
3357 /* We can't convert FROM a VBO, and vertex buffers used to source into
3358 * process_vertices() are unlikely to ever be used for drawing. Release
3359 * VBOs in those buffers and fix up the stream_info structure.
3361 * Also apply the start index. */
3362 for (i = 0; i < (sizeof(stream_info.elements) / sizeof(*stream_info.elements)); ++i)
3364 struct wined3d_stream_info_element *e;
3366 if (!(stream_info.use_map & (1 << i)))
3367 continue;
3369 e = &stream_info.elements[i];
3370 if (e->data.buffer_object)
3372 struct wined3d_buffer *vb = state->streams[e->stream_idx].buffer;
3373 e->data.buffer_object = 0;
3374 e->data.addr = (BYTE *)((ULONG_PTR)e->data.addr + (ULONG_PTR)buffer_get_sysmem(vb, gl_info));
3375 ENTER_GL();
3376 GL_EXTCALL(glDeleteBuffersARB(1, &vb->buffer_object));
3377 vb->buffer_object = 0;
3378 LEAVE_GL();
3380 if (e->data.addr)
3381 e->data.addr += e->stride * src_start_idx;
3384 hr = process_vertices_strided(device, dst_idx, vertex_count,
3385 &stream_info, dst_buffer, flags, dst_fvf);
3387 context_release(context);
3389 return hr;
3392 HRESULT CDECL wined3d_device_set_texture_stage_state(struct wined3d_device *device,
3393 UINT stage, enum wined3d_texture_stage_state state, DWORD value)
3395 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
3396 DWORD old_value;
3398 TRACE("device %p, stage %u, state %s, value %#x.\n",
3399 device, stage, debug_d3dtexturestate(state), value);
3401 if (state > WINED3D_HIGHEST_TEXTURE_STATE)
3403 WARN("Invalid state %#x passed.\n", state);
3404 return WINED3D_OK;
3407 if (stage >= gl_info->limits.texture_stages)
3409 WARN("Attempting to set stage %u which is higher than the max stage %u, ignoring.\n",
3410 stage, gl_info->limits.texture_stages - 1);
3411 return WINED3D_OK;
3414 old_value = device->updateStateBlock->state.texture_states[stage][state];
3415 device->updateStateBlock->changed.textureState[stage] |= 1 << state;
3416 device->updateStateBlock->state.texture_states[stage][state] = value;
3418 if (device->isRecordingState)
3420 TRACE("Recording... not performing anything.\n");
3421 return WINED3D_OK;
3424 /* Checked after the assignments to allow proper stateblock recording. */
3425 if (old_value == value)
3427 TRACE("Application is setting the old value over, nothing to do.\n");
3428 return WINED3D_OK;
3431 if (stage > device->stateBlock->state.lowest_disabled_stage
3432 && device->StateTable[STATE_TEXTURESTAGE(0, state)].representative
3433 == STATE_TEXTURESTAGE(0, WINED3D_TSS_COLOR_OP))
3435 /* Colorop change above lowest disabled stage? That won't change
3436 * anything in the GL setup. Changes in other states are important on
3437 * disabled stages too. */
3438 return WINED3D_OK;
3441 if (state == WINED3D_TSS_COLOR_OP)
3443 unsigned int i;
3445 if (value == WINED3D_TOP_DISABLE && old_value != WINED3D_TOP_DISABLE)
3447 /* Previously enabled stage disabled now. Make sure to dirtify
3448 * all enabled stages above stage, they have to be disabled.
3450 * The current stage is dirtified below. */
3451 for (i = stage + 1; i < device->stateBlock->state.lowest_disabled_stage; ++i)
3453 TRACE("Additionally dirtifying stage %u.\n", i);
3454 device_invalidate_state(device, STATE_TEXTURESTAGE(i, WINED3D_TSS_COLOR_OP));
3456 device->stateBlock->state.lowest_disabled_stage = stage;
3457 TRACE("New lowest disabled: %u.\n", stage);
3459 else if (value != WINED3D_TOP_DISABLE && old_value == WINED3D_TOP_DISABLE)
3461 /* Previously disabled stage enabled. Stages above it may need
3462 * enabling. Stage must be lowest_disabled_stage here, if it's
3463 * bigger success is returned above, and stages below the lowest
3464 * disabled stage can't be enabled (because they are enabled
3465 * already).
3467 * Again stage stage doesn't need to be dirtified here, it is
3468 * handled below. */
3469 for (i = stage + 1; i < gl_info->limits.texture_stages; ++i)
3471 if (device->updateStateBlock->state.texture_states[i][WINED3D_TSS_COLOR_OP] == WINED3D_TOP_DISABLE)
3472 break;
3473 TRACE("Additionally dirtifying stage %u due to enable.\n", i);
3474 device_invalidate_state(device, STATE_TEXTURESTAGE(i, WINED3D_TSS_COLOR_OP));
3476 device->stateBlock->state.lowest_disabled_stage = i;
3477 TRACE("New lowest disabled: %u.\n", i);
3481 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, state));
3483 return WINED3D_OK;
3486 HRESULT CDECL wined3d_device_get_texture_stage_state(const struct wined3d_device *device,
3487 UINT stage, enum wined3d_texture_stage_state state, DWORD *value)
3489 TRACE("device %p, stage %u, state %s, value %p.\n",
3490 device, stage, debug_d3dtexturestate(state), value);
3492 if (state > WINED3D_HIGHEST_TEXTURE_STATE)
3494 WARN("Invalid state %#x passed.\n", state);
3495 return WINED3D_OK;
3498 *value = device->updateStateBlock->state.texture_states[stage][state];
3499 TRACE("Returning %#x.\n", *value);
3501 return WINED3D_OK;
3504 HRESULT CDECL wined3d_device_set_texture(struct wined3d_device *device,
3505 UINT stage, struct wined3d_texture *texture)
3507 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
3508 struct wined3d_texture *prev;
3510 TRACE("device %p, stage %u, texture %p.\n", device, stage, texture);
3512 if (stage >= WINED3DVERTEXTEXTURESAMPLER0 && stage <= WINED3DVERTEXTEXTURESAMPLER3)
3513 stage -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
3515 /* Windows accepts overflowing this array... we do not. */
3516 if (stage >= sizeof(device->stateBlock->state.textures) / sizeof(*device->stateBlock->state.textures))
3518 WARN("Ignoring invalid stage %u.\n", stage);
3519 return WINED3D_OK;
3522 if (texture && texture->resource.pool == WINED3D_POOL_SCRATCH)
3524 WARN("Rejecting attempt to set scratch texture.\n");
3525 return WINED3DERR_INVALIDCALL;
3528 device->updateStateBlock->changed.textures |= 1 << stage;
3530 prev = device->updateStateBlock->state.textures[stage];
3531 TRACE("Previous texture %p.\n", prev);
3533 if (texture == prev)
3535 TRACE("App is setting the same texture again, nothing to do.\n");
3536 return WINED3D_OK;
3539 TRACE("Setting new texture to %p.\n", texture);
3540 device->updateStateBlock->state.textures[stage] = texture;
3542 if (device->isRecordingState)
3544 TRACE("Recording... not performing anything\n");
3546 if (texture) wined3d_texture_incref(texture);
3547 if (prev) wined3d_texture_decref(prev);
3549 return WINED3D_OK;
3552 if (texture)
3554 LONG bind_count = InterlockedIncrement(&texture->resource.bind_count);
3556 wined3d_texture_incref(texture);
3558 if (!prev || texture->target != prev->target)
3559 device_invalidate_state(device, STATE_PIXELSHADER);
3561 if (!prev && stage < gl_info->limits.texture_stages)
3563 /* The source arguments for color and alpha ops have different
3564 * meanings when a NULL texture is bound, so the COLOR_OP and
3565 * ALPHA_OP have to be dirtified. */
3566 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, WINED3D_TSS_COLOR_OP));
3567 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, WINED3D_TSS_ALPHA_OP));
3570 if (bind_count == 1)
3571 texture->sampler = stage;
3574 if (prev)
3576 LONG bind_count = InterlockedDecrement(&prev->resource.bind_count);
3578 wined3d_texture_decref(prev);
3580 if (!texture && stage < gl_info->limits.texture_stages)
3582 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, WINED3D_TSS_COLOR_OP));
3583 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, WINED3D_TSS_ALPHA_OP));
3586 if (bind_count && prev->sampler == stage)
3588 unsigned int i;
3590 /* Search for other stages the texture is bound to. Shouldn't
3591 * happen if applications bind textures to a single stage only. */
3592 TRACE("Searching for other stages the texture is bound to.\n");
3593 for (i = 0; i < MAX_COMBINED_SAMPLERS; ++i)
3595 if (device->updateStateBlock->state.textures[i] == prev)
3597 TRACE("Texture is also bound to stage %u.\n", i);
3598 prev->sampler = i;
3599 break;
3605 device_invalidate_state(device, STATE_SAMPLER(stage));
3607 return WINED3D_OK;
3610 HRESULT CDECL wined3d_device_get_texture(const struct wined3d_device *device,
3611 UINT stage, struct wined3d_texture **texture)
3613 TRACE("device %p, stage %u, texture %p.\n", device, stage, texture);
3615 if (stage >= WINED3DVERTEXTEXTURESAMPLER0 && stage <= WINED3DVERTEXTEXTURESAMPLER3)
3616 stage -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
3618 if (stage >= sizeof(device->stateBlock->state.textures) / sizeof(*device->stateBlock->state.textures))
3620 WARN("Ignoring invalid stage %u.\n", stage);
3621 return WINED3D_OK; /* Windows accepts overflowing this array ... we do not. */
3624 *texture = device->stateBlock->state.textures[stage];
3625 if (*texture)
3626 wined3d_texture_incref(*texture);
3628 TRACE("Returning %p.\n", *texture);
3630 return WINED3D_OK;
3633 HRESULT CDECL wined3d_device_get_back_buffer(const struct wined3d_device *device, UINT swapchain_idx,
3634 UINT backbuffer_idx, enum wined3d_backbuffer_type backbuffer_type, struct wined3d_surface **backbuffer)
3636 struct wined3d_swapchain *swapchain;
3638 TRACE("device %p, swapchain_idx %u, backbuffer_idx %u, backbuffer_type %#x, backbuffer %p.\n",
3639 device, swapchain_idx, backbuffer_idx, backbuffer_type, backbuffer);
3641 if (!(swapchain = wined3d_device_get_swapchain(device, swapchain_idx)))
3642 return WINED3DERR_INVALIDCALL;
3644 return wined3d_swapchain_get_back_buffer(swapchain, backbuffer_idx, backbuffer_type, backbuffer);
3647 HRESULT CDECL wined3d_device_get_device_caps(const struct wined3d_device *device, WINED3DCAPS *caps)
3649 TRACE("device %p, caps %p.\n", device, caps);
3651 return wined3d_get_device_caps(device->wined3d, device->adapter->ordinal,
3652 device->create_parms.device_type, caps);
3655 HRESULT CDECL wined3d_device_get_display_mode(const struct wined3d_device *device, UINT swapchain_idx,
3656 struct wined3d_display_mode *mode, enum wined3d_display_rotation *rotation)
3658 struct wined3d_swapchain *swapchain;
3660 TRACE("device %p, swapchain_idx %u, mode %p, rotation %p.\n",
3661 device, swapchain_idx, mode, rotation);
3663 if (!(swapchain = wined3d_device_get_swapchain(device, swapchain_idx)))
3664 return WINED3DERR_INVALIDCALL;
3666 return wined3d_swapchain_get_display_mode(swapchain, mode, rotation);
3669 HRESULT CDECL wined3d_device_begin_stateblock(struct wined3d_device *device)
3671 struct wined3d_stateblock *stateblock;
3672 HRESULT hr;
3674 TRACE("device %p.\n", device);
3676 if (device->isRecordingState)
3677 return WINED3DERR_INVALIDCALL;
3679 hr = wined3d_stateblock_create(device, WINED3D_SBT_RECORDED, &stateblock);
3680 if (FAILED(hr))
3681 return hr;
3683 wined3d_stateblock_decref(device->updateStateBlock);
3684 device->updateStateBlock = stateblock;
3685 device->isRecordingState = TRUE;
3687 TRACE("Recording stateblock %p.\n", stateblock);
3689 return WINED3D_OK;
3692 HRESULT CDECL wined3d_device_end_stateblock(struct wined3d_device *device,
3693 struct wined3d_stateblock **stateblock)
3695 struct wined3d_stateblock *object = device->updateStateBlock;
3697 TRACE("device %p, stateblock %p.\n", device, stateblock);
3699 if (!device->isRecordingState)
3701 WARN("Not recording.\n");
3702 *stateblock = NULL;
3703 return WINED3DERR_INVALIDCALL;
3706 stateblock_init_contained_states(object);
3708 *stateblock = object;
3709 device->isRecordingState = FALSE;
3710 device->updateStateBlock = device->stateBlock;
3711 wined3d_stateblock_incref(device->updateStateBlock);
3713 TRACE("Returning stateblock %p.\n", *stateblock);
3715 return WINED3D_OK;
3718 HRESULT CDECL wined3d_device_begin_scene(struct wined3d_device *device)
3720 /* At the moment we have no need for any functionality at the beginning
3721 * of a scene. */
3722 TRACE("device %p.\n", device);
3724 if (device->inScene)
3726 WARN("Already in scene, returning WINED3DERR_INVALIDCALL.\n");
3727 return WINED3DERR_INVALIDCALL;
3729 device->inScene = TRUE;
3730 return WINED3D_OK;
3733 HRESULT CDECL wined3d_device_end_scene(struct wined3d_device *device)
3735 struct wined3d_context *context;
3737 TRACE("device %p.\n", device);
3739 if (!device->inScene)
3741 WARN("Not in scene, returning WINED3DERR_INVALIDCALL.\n");
3742 return WINED3DERR_INVALIDCALL;
3745 context = context_acquire(device, NULL);
3746 /* We only have to do this if we need to read the, swapbuffers performs a flush for us */
3747 context->gl_info->gl_ops.gl.p_glFlush();
3748 /* No checkGLcall here to avoid locking the lock just for checking a call that hardly ever
3749 * fails. */
3750 context_release(context);
3752 device->inScene = FALSE;
3753 return WINED3D_OK;
3756 HRESULT CDECL wined3d_device_present(const struct wined3d_device *device, const RECT *src_rect,
3757 const RECT *dst_rect, HWND dst_window_override, const RGNDATA *dirty_region, DWORD flags)
3759 UINT i;
3761 TRACE("device %p, src_rect %s, dst_rect %s, dst_window_override %p, dirty_region %p, flags %#x.\n",
3762 device, wine_dbgstr_rect(src_rect), wine_dbgstr_rect(dst_rect),
3763 dst_window_override, dirty_region, flags);
3765 for (i = 0; i < device->swapchain_count; ++i)
3767 wined3d_swapchain_present(device->swapchains[i], src_rect,
3768 dst_rect, dst_window_override, dirty_region, flags);
3771 return WINED3D_OK;
3774 /* Do not call while under the GL lock. */
3775 HRESULT CDECL wined3d_device_clear(struct wined3d_device *device, DWORD rect_count,
3776 const RECT *rects, DWORD flags, const struct wined3d_color *color, float depth, DWORD stencil)
3778 RECT draw_rect;
3780 TRACE("device %p, rect_count %u, rects %p, flags %#x, color {%.8e, %.8e, %.8e, %.8e}, depth %.8e, stencil %u.\n",
3781 device, rect_count, rects, flags, color->r, color->g, color->b, color->a, depth, stencil);
3783 if (flags & (WINED3DCLEAR_ZBUFFER | WINED3DCLEAR_STENCIL))
3785 struct wined3d_surface *ds = device->fb.depth_stencil;
3786 if (!ds)
3788 WARN("Clearing depth and/or stencil without a depth stencil buffer attached, returning WINED3DERR_INVALIDCALL\n");
3789 /* TODO: What about depth stencil buffers without stencil bits? */
3790 return WINED3DERR_INVALIDCALL;
3792 else if (flags & WINED3DCLEAR_TARGET)
3794 if (ds->resource.width < device->fb.render_targets[0]->resource.width
3795 || ds->resource.height < device->fb.render_targets[0]->resource.height)
3797 WARN("Silently ignoring depth and target clear with mismatching sizes\n");
3798 return WINED3D_OK;
3803 wined3d_get_draw_rect(&device->stateBlock->state, &draw_rect);
3804 device_clear_render_targets(device, device->adapter->gl_info.limits.buffers,
3805 &device->fb, rect_count, rects, &draw_rect, flags, color, depth, stencil);
3807 return WINED3D_OK;
3810 void CDECL wined3d_device_set_primitive_type(struct wined3d_device *device,
3811 enum wined3d_primitive_type primitive_type)
3813 TRACE("device %p, primitive_type %s\n", device, debug_d3dprimitivetype(primitive_type));
3815 device->updateStateBlock->changed.primitive_type = TRUE;
3816 device->updateStateBlock->state.gl_primitive_type = gl_primitive_type_from_d3d(primitive_type);
3819 void CDECL wined3d_device_get_primitive_type(const struct wined3d_device *device,
3820 enum wined3d_primitive_type *primitive_type)
3822 TRACE("device %p, primitive_type %p\n", device, primitive_type);
3824 *primitive_type = d3d_primitive_type_from_gl(device->stateBlock->state.gl_primitive_type);
3826 TRACE("Returning %s\n", debug_d3dprimitivetype(*primitive_type));
3829 HRESULT CDECL wined3d_device_draw_primitive(struct wined3d_device *device, UINT start_vertex, UINT vertex_count)
3831 TRACE("device %p, start_vertex %u, vertex_count %u.\n", device, start_vertex, vertex_count);
3833 if (!device->stateBlock->state.vertex_declaration)
3835 WARN("Called without a valid vertex declaration set.\n");
3836 return WINED3DERR_INVALIDCALL;
3839 /* The index buffer is not needed here, but restore it, otherwise it is hell to keep track of */
3840 if (device->stateBlock->state.user_stream)
3842 device_invalidate_state(device, STATE_INDEXBUFFER);
3843 device->stateBlock->state.user_stream = FALSE;
3846 if (device->stateBlock->state.load_base_vertex_index)
3848 device->stateBlock->state.load_base_vertex_index = 0;
3849 device_invalidate_state(device, STATE_BASEVERTEXINDEX);
3852 /* Account for the loading offset due to index buffers. Instead of
3853 * reloading all sources correct it with the startvertex parameter. */
3854 drawPrimitive(device, vertex_count, start_vertex, FALSE, NULL);
3855 return WINED3D_OK;
3858 HRESULT CDECL wined3d_device_draw_indexed_primitive(struct wined3d_device *device, UINT start_idx, UINT index_count)
3860 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
3862 TRACE("device %p, start_idx %u, index_count %u.\n", device, start_idx, index_count);
3864 if (!device->stateBlock->state.index_buffer)
3866 /* D3D9 returns D3DERR_INVALIDCALL when DrawIndexedPrimitive is called
3867 * without an index buffer set. (The first time at least...)
3868 * D3D8 simply dies, but I doubt it can do much harm to return
3869 * D3DERR_INVALIDCALL there as well. */
3870 WARN("Called without a valid index buffer set, returning WINED3DERR_INVALIDCALL.\n");
3871 return WINED3DERR_INVALIDCALL;
3874 if (!device->stateBlock->state.vertex_declaration)
3876 WARN("Called without a valid vertex declaration set.\n");
3877 return WINED3DERR_INVALIDCALL;
3880 if (device->stateBlock->state.user_stream)
3882 device_invalidate_state(device, STATE_INDEXBUFFER);
3883 device->stateBlock->state.user_stream = FALSE;
3886 if (!gl_info->supported[ARB_DRAW_ELEMENTS_BASE_VERTEX] &&
3887 device->stateBlock->state.load_base_vertex_index != device->stateBlock->state.base_vertex_index)
3889 device->stateBlock->state.load_base_vertex_index = device->stateBlock->state.base_vertex_index;
3890 device_invalidate_state(device, STATE_BASEVERTEXINDEX);
3893 drawPrimitive(device, index_count, start_idx, TRUE, NULL);
3895 return WINED3D_OK;
3898 HRESULT CDECL wined3d_device_draw_primitive_up(struct wined3d_device *device, UINT vertex_count,
3899 const void *stream_data, UINT stream_stride)
3901 struct wined3d_stream_state *stream;
3902 struct wined3d_buffer *vb;
3904 TRACE("device %p, vertex count %u, stream_data %p, stream_stride %u.\n",
3905 device, vertex_count, stream_data, stream_stride);
3907 if (!device->stateBlock->state.vertex_declaration)
3909 WARN("Called without a valid vertex declaration set.\n");
3910 return WINED3DERR_INVALIDCALL;
3913 /* Note in the following, it's not this type, but that's the purpose of streamIsUP */
3914 stream = &device->stateBlock->state.streams[0];
3915 vb = stream->buffer;
3916 stream->buffer = (struct wined3d_buffer *)stream_data;
3917 if (vb)
3918 wined3d_buffer_decref(vb);
3919 stream->offset = 0;
3920 stream->stride = stream_stride;
3921 device->stateBlock->state.user_stream = TRUE;
3922 if (device->stateBlock->state.load_base_vertex_index)
3924 device->stateBlock->state.load_base_vertex_index = 0;
3925 device_invalidate_state(device, STATE_BASEVERTEXINDEX);
3928 /* TODO: Only mark dirty if drawing from a different UP address */
3929 device_invalidate_state(device, STATE_STREAMSRC);
3931 drawPrimitive(device, vertex_count, 0, FALSE, NULL);
3933 /* MSDN specifies stream zero settings must be set to NULL */
3934 stream->buffer = NULL;
3935 stream->stride = 0;
3937 /* stream zero settings set to null at end, as per the msdn. No need to
3938 * mark dirty here, the app has to set the new stream sources or use UP
3939 * drawing again. */
3940 return WINED3D_OK;
3943 HRESULT CDECL wined3d_device_draw_indexed_primitive_up(struct wined3d_device *device,
3944 UINT index_count, const void *index_data, enum wined3d_format_id index_data_format_id,
3945 const void *stream_data, UINT stream_stride)
3947 struct wined3d_stream_state *stream;
3948 struct wined3d_buffer *vb, *ib;
3950 TRACE("device %p, index_count %u, index_data %p, index_data_format %s, stream_data %p, stream_stride %u.\n",
3951 device, index_count, index_data, debug_d3dformat(index_data_format_id), stream_data, stream_stride);
3953 if (!device->stateBlock->state.vertex_declaration)
3955 WARN("(%p) : Called without a valid vertex declaration set\n", device);
3956 return WINED3DERR_INVALIDCALL;
3959 stream = &device->stateBlock->state.streams[0];
3960 vb = stream->buffer;
3961 stream->buffer = (struct wined3d_buffer *)stream_data;
3962 if (vb)
3963 wined3d_buffer_decref(vb);
3964 stream->offset = 0;
3965 stream->stride = stream_stride;
3966 device->stateBlock->state.user_stream = TRUE;
3967 device->stateBlock->state.index_format = index_data_format_id;
3969 /* Set to 0 as per msdn. Do it now due to the stream source loading during drawPrimitive */
3970 device->stateBlock->state.base_vertex_index = 0;
3971 if (device->stateBlock->state.load_base_vertex_index)
3973 device->stateBlock->state.load_base_vertex_index = 0;
3974 device_invalidate_state(device, STATE_BASEVERTEXINDEX);
3976 /* Invalidate the state until we have nicer tracking of the stream source pointers */
3977 device_invalidate_state(device, STATE_STREAMSRC);
3978 device_invalidate_state(device, STATE_INDEXBUFFER);
3980 drawPrimitive(device, index_count, 0, TRUE, index_data);
3982 /* MSDN specifies stream zero settings and index buffer must be set to NULL */
3983 stream->buffer = NULL;
3984 stream->stride = 0;
3985 ib = device->stateBlock->state.index_buffer;
3986 if (ib)
3988 wined3d_buffer_decref(ib);
3989 device->stateBlock->state.index_buffer = NULL;
3991 /* No need to mark the stream source state dirty here. Either the app calls UP drawing again, or it has to call
3992 * SetStreamSource to specify a vertex buffer
3995 return WINED3D_OK;
3998 HRESULT CDECL wined3d_device_draw_primitive_strided(struct wined3d_device *device,
3999 UINT vertex_count, const struct wined3d_strided_data *strided_data)
4001 /* Mark the state dirty until we have nicer tracking. It's fine to change
4002 * baseVertexIndex because that call is only called by ddraw which does
4003 * not need that value. */
4004 device_invalidate_state(device, STATE_VDECL);
4005 device_invalidate_state(device, STATE_STREAMSRC);
4006 device_invalidate_state(device, STATE_INDEXBUFFER);
4008 device->stateBlock->state.base_vertex_index = 0;
4009 device->up_strided = strided_data;
4010 drawPrimitive(device, vertex_count, 0, FALSE, NULL);
4011 device->up_strided = NULL;
4013 /* Invalidate the states again to make sure the values from the stateblock
4014 * are properly applied in the next regular draw. Note that the application-
4015 * provided strided data has ovwritten pretty much the entire vertex and
4016 * and index stream related states */
4017 device_invalidate_state(device, STATE_VDECL);
4018 device_invalidate_state(device, STATE_STREAMSRC);
4019 device_invalidate_state(device, STATE_INDEXBUFFER);
4020 return WINED3D_OK;
4023 HRESULT CDECL wined3d_device_draw_indexed_primitive_strided(struct wined3d_device *device,
4024 UINT index_count, const struct wined3d_strided_data *strided_data,
4025 UINT vertex_count, const void *index_data, enum wined3d_format_id index_data_format_id)
4027 enum wined3d_format_id prev_idx_format;
4029 /* Mark the state dirty until we have nicer tracking
4030 * its fine to change baseVertexIndex because that call is only called by ddraw which does not need
4031 * that value.
4033 device_invalidate_state(device, STATE_VDECL);
4034 device_invalidate_state(device, STATE_STREAMSRC);
4035 device_invalidate_state(device, STATE_INDEXBUFFER);
4037 prev_idx_format = device->stateBlock->state.index_format;
4038 device->stateBlock->state.index_format = index_data_format_id;
4039 device->stateBlock->state.user_stream = TRUE;
4040 device->stateBlock->state.base_vertex_index = 0;
4041 device->up_strided = strided_data;
4042 drawPrimitive(device, index_count, 0, TRUE, index_data);
4043 device->up_strided = NULL;
4044 device->stateBlock->state.index_format = prev_idx_format;
4046 device_invalidate_state(device, STATE_VDECL);
4047 device_invalidate_state(device, STATE_STREAMSRC);
4048 device_invalidate_state(device, STATE_INDEXBUFFER);
4049 return WINED3D_OK;
4052 /* This is a helper function for UpdateTexture, there is no UpdateVolume method in D3D. */
4053 static HRESULT device_update_volume(struct wined3d_device *device,
4054 struct wined3d_volume *src_volume, struct wined3d_volume *dst_volume)
4056 struct wined3d_map_desc src;
4057 struct wined3d_map_desc dst;
4058 HRESULT hr;
4060 TRACE("device %p, src_volume %p, dst_volume %p.\n",
4061 device, src_volume, dst_volume);
4063 /* TODO: Implement direct loading into the gl volume instead of using
4064 * memcpy and dirtification to improve loading performance. */
4065 if (FAILED(hr = wined3d_volume_map(src_volume, &src, NULL, WINED3D_MAP_READONLY)))
4066 return hr;
4067 if (FAILED(hr = wined3d_volume_map(dst_volume, &dst, NULL, WINED3D_MAP_DISCARD)))
4069 wined3d_volume_unmap(src_volume);
4070 return hr;
4073 memcpy(dst.data, src.data, dst_volume->resource.size);
4075 hr = wined3d_volume_unmap(dst_volume);
4076 if (FAILED(hr))
4077 wined3d_volume_unmap(src_volume);
4078 else
4079 hr = wined3d_volume_unmap(src_volume);
4081 return hr;
4084 HRESULT CDECL wined3d_device_update_texture(struct wined3d_device *device,
4085 struct wined3d_texture *src_texture, struct wined3d_texture *dst_texture)
4087 enum wined3d_resource_type type;
4088 unsigned int level_count, i;
4089 HRESULT hr;
4091 TRACE("device %p, src_texture %p, dst_texture %p.\n", device, src_texture, dst_texture);
4093 /* Verify that the source and destination textures are non-NULL. */
4094 if (!src_texture || !dst_texture)
4096 WARN("Source and destination textures must be non-NULL, returning WINED3DERR_INVALIDCALL.\n");
4097 return WINED3DERR_INVALIDCALL;
4100 if (src_texture == dst_texture)
4102 WARN("Source and destination are the same object, returning WINED3DERR_INVALIDCALL.\n");
4103 return WINED3DERR_INVALIDCALL;
4106 /* Verify that the source and destination textures are the same type. */
4107 type = src_texture->resource.type;
4108 if (dst_texture->resource.type != type)
4110 WARN("Source and destination have different types, returning WINED3DERR_INVALIDCALL.\n");
4111 return WINED3DERR_INVALIDCALL;
4114 /* Check that both textures have the identical numbers of levels. */
4115 level_count = wined3d_texture_get_level_count(src_texture);
4116 if (wined3d_texture_get_level_count(dst_texture) != level_count)
4118 WARN("Source and destination have different level counts, returning WINED3DERR_INVALIDCALL.\n");
4119 return WINED3DERR_INVALIDCALL;
4122 /* Make sure that the destination texture is loaded. */
4123 dst_texture->texture_ops->texture_preload(dst_texture, SRGB_RGB);
4125 /* Update every surface level of the texture. */
4126 switch (type)
4128 case WINED3D_RTYPE_TEXTURE:
4130 struct wined3d_surface *src_surface;
4131 struct wined3d_surface *dst_surface;
4133 for (i = 0; i < level_count; ++i)
4135 src_surface = surface_from_resource(wined3d_texture_get_sub_resource(src_texture, i));
4136 dst_surface = surface_from_resource(wined3d_texture_get_sub_resource(dst_texture, i));
4137 hr = wined3d_device_update_surface(device, src_surface, NULL, dst_surface, NULL);
4138 if (FAILED(hr))
4140 WARN("Failed to update surface, hr %#x.\n", hr);
4141 return hr;
4144 break;
4147 case WINED3D_RTYPE_CUBE_TEXTURE:
4149 struct wined3d_surface *src_surface;
4150 struct wined3d_surface *dst_surface;
4152 for (i = 0; i < level_count * 6; ++i)
4154 src_surface = surface_from_resource(wined3d_texture_get_sub_resource(src_texture, i));
4155 dst_surface = surface_from_resource(wined3d_texture_get_sub_resource(dst_texture, i));
4156 hr = wined3d_device_update_surface(device, src_surface, NULL, dst_surface, NULL);
4157 if (FAILED(hr))
4159 WARN("Failed to update surface, hr %#x.\n", hr);
4160 return hr;
4163 break;
4166 case WINED3D_RTYPE_VOLUME_TEXTURE:
4168 for (i = 0; i < level_count; ++i)
4170 hr = device_update_volume(device,
4171 volume_from_resource(wined3d_texture_get_sub_resource(src_texture, i)),
4172 volume_from_resource(wined3d_texture_get_sub_resource(dst_texture, i)));
4173 if (FAILED(hr))
4175 WARN("Failed to update volume, hr %#x.\n", hr);
4176 return hr;
4179 break;
4182 default:
4183 FIXME("Unsupported texture type %#x.\n", type);
4184 return WINED3DERR_INVALIDCALL;
4187 return WINED3D_OK;
4190 HRESULT CDECL wined3d_device_get_front_buffer_data(const struct wined3d_device *device,
4191 UINT swapchain_idx, struct wined3d_surface *dst_surface)
4193 struct wined3d_swapchain *swapchain;
4195 TRACE("device %p, swapchain_idx %u, dst_surface %p.\n", device, swapchain_idx, dst_surface);
4197 if (!(swapchain = wined3d_device_get_swapchain(device, swapchain_idx)))
4198 return WINED3DERR_INVALIDCALL;
4200 return wined3d_swapchain_get_front_buffer_data(swapchain, dst_surface);
4203 HRESULT CDECL wined3d_device_validate_device(const struct wined3d_device *device, DWORD *num_passes)
4205 const struct wined3d_state *state = &device->stateBlock->state;
4206 struct wined3d_texture *texture;
4207 DWORD i;
4209 TRACE("device %p, num_passes %p.\n", device, num_passes);
4211 for (i = 0; i < MAX_COMBINED_SAMPLERS; ++i)
4213 if (state->sampler_states[i][WINED3D_SAMP_MIN_FILTER] == WINED3D_TEXF_NONE)
4215 WARN("Sampler state %u has minfilter D3DTEXF_NONE, returning D3DERR_UNSUPPORTEDTEXTUREFILTER\n", i);
4216 return WINED3DERR_UNSUPPORTEDTEXTUREFILTER;
4218 if (state->sampler_states[i][WINED3D_SAMP_MAG_FILTER] == WINED3D_TEXF_NONE)
4220 WARN("Sampler state %u has magfilter D3DTEXF_NONE, returning D3DERR_UNSUPPORTEDTEXTUREFILTER\n", i);
4221 return WINED3DERR_UNSUPPORTEDTEXTUREFILTER;
4224 texture = state->textures[i];
4225 if (!texture || texture->resource.format->flags & WINED3DFMT_FLAG_FILTERING) continue;
4227 if (state->sampler_states[i][WINED3D_SAMP_MAG_FILTER] != WINED3D_TEXF_POINT)
4229 WARN("Non-filterable texture and mag filter enabled on samper %u, returning E_FAIL\n", i);
4230 return E_FAIL;
4232 if (state->sampler_states[i][WINED3D_SAMP_MIN_FILTER] != WINED3D_TEXF_POINT)
4234 WARN("Non-filterable texture and min filter enabled on samper %u, returning E_FAIL\n", i);
4235 return E_FAIL;
4237 if (state->sampler_states[i][WINED3D_SAMP_MIP_FILTER] != WINED3D_TEXF_NONE
4238 && state->sampler_states[i][WINED3D_SAMP_MIP_FILTER] != WINED3D_TEXF_POINT)
4240 WARN("Non-filterable texture and mip filter enabled on samper %u, returning E_FAIL\n", i);
4241 return E_FAIL;
4245 if (state->render_states[WINED3D_RS_ZENABLE] || state->render_states[WINED3D_RS_ZWRITEENABLE]
4246 || state->render_states[WINED3D_RS_STENCILENABLE])
4248 struct wined3d_surface *ds = device->fb.depth_stencil;
4249 struct wined3d_surface *target = device->fb.render_targets[0];
4251 if(ds && target
4252 && (ds->resource.width < target->resource.width || ds->resource.height < target->resource.height))
4254 WARN("Depth stencil is smaller than the color buffer, returning D3DERR_CONFLICTINGRENDERSTATE\n");
4255 return WINED3DERR_CONFLICTINGRENDERSTATE;
4259 /* return a sensible default */
4260 *num_passes = 1;
4262 TRACE("returning D3D_OK\n");
4263 return WINED3D_OK;
4266 HRESULT CDECL wined3d_device_set_software_vertex_processing(struct wined3d_device *device, BOOL software)
4268 static BOOL warned;
4270 TRACE("device %p, software %#x.\n", device, software);
4272 if (!warned)
4274 FIXME("device %p, software %#x stub!\n", device, software);
4275 warned = TRUE;
4278 device->softwareVertexProcessing = software;
4280 return WINED3D_OK;
4283 BOOL CDECL wined3d_device_get_software_vertex_processing(const struct wined3d_device *device)
4285 static BOOL warned;
4287 TRACE("device %p.\n", device);
4289 if (!warned)
4291 TRACE("device %p stub!\n", device);
4292 warned = TRUE;
4295 return device->softwareVertexProcessing;
4298 HRESULT CDECL wined3d_device_get_raster_status(const struct wined3d_device *device,
4299 UINT swapchain_idx, struct wined3d_raster_status *raster_status)
4301 struct wined3d_swapchain *swapchain;
4303 TRACE("device %p, swapchain_idx %u, raster_status %p.\n",
4304 device, swapchain_idx, raster_status);
4306 if (!(swapchain = wined3d_device_get_swapchain(device, swapchain_idx)))
4307 return WINED3DERR_INVALIDCALL;
4309 return wined3d_swapchain_get_raster_status(swapchain, raster_status);
4312 HRESULT CDECL wined3d_device_set_npatch_mode(struct wined3d_device *device, float segments)
4314 static BOOL warned;
4316 TRACE("device %p, segments %.8e.\n", device, segments);
4318 if (segments != 0.0f)
4320 if (!warned)
4322 FIXME("device %p, segments %.8e stub!\n", device, segments);
4323 warned = TRUE;
4327 return WINED3D_OK;
4330 float CDECL wined3d_device_get_npatch_mode(const struct wined3d_device *device)
4332 static BOOL warned;
4334 TRACE("device %p.\n", device);
4336 if (!warned)
4338 FIXME("device %p stub!\n", device);
4339 warned = TRUE;
4342 return 0.0f;
4345 HRESULT CDECL wined3d_device_update_surface(struct wined3d_device *device,
4346 struct wined3d_surface *src_surface, const RECT *src_rect,
4347 struct wined3d_surface *dst_surface, const POINT *dst_point)
4349 TRACE("device %p, src_surface %p, src_rect %s, dst_surface %p, dst_point %s.\n",
4350 device, src_surface, wine_dbgstr_rect(src_rect),
4351 dst_surface, wine_dbgstr_point(dst_point));
4353 if (src_surface->resource.pool != WINED3D_POOL_SYSTEM_MEM || dst_surface->resource.pool != WINED3D_POOL_DEFAULT)
4355 WARN("source %p must be SYSTEMMEM and dest %p must be DEFAULT, returning WINED3DERR_INVALIDCALL\n",
4356 src_surface, dst_surface);
4357 return WINED3DERR_INVALIDCALL;
4360 return surface_upload_from_surface(dst_surface, dst_point, src_surface, src_rect);
4363 HRESULT CDECL wined3d_device_draw_rect_patch(struct wined3d_device *device, UINT handle,
4364 const float *num_segs, const struct wined3d_rect_patch_info *rect_patch_info)
4366 struct wined3d_rect_patch *patch;
4367 GLenum old_primitive_type;
4368 unsigned int i;
4369 struct list *e;
4370 BOOL found;
4372 TRACE("device %p, handle %#x, num_segs %p, rect_patch_info %p.\n",
4373 device, handle, num_segs, rect_patch_info);
4375 if (!(handle || rect_patch_info))
4377 /* TODO: Write a test for the return value, thus the FIXME */
4378 FIXME("Both handle and rect_patch_info are NULL.\n");
4379 return WINED3DERR_INVALIDCALL;
4382 if (handle)
4384 i = PATCHMAP_HASHFUNC(handle);
4385 found = FALSE;
4386 LIST_FOR_EACH(e, &device->patches[i])
4388 patch = LIST_ENTRY(e, struct wined3d_rect_patch, entry);
4389 if (patch->Handle == handle)
4391 found = TRUE;
4392 break;
4396 if (!found)
4398 TRACE("Patch does not exist. Creating a new one\n");
4399 patch = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*patch));
4400 patch->Handle = handle;
4401 list_add_head(&device->patches[i], &patch->entry);
4402 } else {
4403 TRACE("Found existing patch %p\n", patch);
4406 else
4408 /* Since opengl does not load tesselated vertex attributes into numbered vertex
4409 * attributes we have to tesselate, read back, and draw. This needs a patch
4410 * management structure instance. Create one.
4412 * A possible improvement is to check if a vertex shader is used, and if not directly
4413 * draw the patch.
4415 FIXME("Drawing an uncached patch. This is slow\n");
4416 patch = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*patch));
4419 if (num_segs[0] != patch->numSegs[0] || num_segs[1] != patch->numSegs[1]
4420 || num_segs[2] != patch->numSegs[2] || num_segs[3] != patch->numSegs[3]
4421 || (rect_patch_info && memcmp(rect_patch_info, &patch->rect_patch_info, sizeof(*rect_patch_info))))
4423 HRESULT hr;
4424 TRACE("Tesselation density or patch info changed, retesselating\n");
4426 if (rect_patch_info)
4427 patch->rect_patch_info = *rect_patch_info;
4429 patch->numSegs[0] = num_segs[0];
4430 patch->numSegs[1] = num_segs[1];
4431 patch->numSegs[2] = num_segs[2];
4432 patch->numSegs[3] = num_segs[3];
4434 hr = tesselate_rectpatch(device, patch);
4435 if (FAILED(hr))
4437 WARN("Patch tesselation failed.\n");
4439 /* Do not release the handle to store the params of the patch */
4440 if (!handle)
4441 HeapFree(GetProcessHeap(), 0, patch);
4443 return hr;
4447 old_primitive_type = device->stateBlock->state.gl_primitive_type;
4448 device->stateBlock->state.gl_primitive_type = GL_TRIANGLES;
4449 wined3d_device_draw_primitive_strided(device, patch->numSegs[0] * patch->numSegs[1] * 2 * 3, &patch->strided);
4450 device->stateBlock->state.gl_primitive_type = old_primitive_type;
4452 /* Destroy uncached patches */
4453 if (!handle)
4455 HeapFree(GetProcessHeap(), 0, patch->mem);
4456 HeapFree(GetProcessHeap(), 0, patch);
4458 return WINED3D_OK;
4461 HRESULT CDECL wined3d_device_draw_tri_patch(struct wined3d_device *device, UINT handle,
4462 const float *segment_count, const struct wined3d_tri_patch_info *patch_info)
4464 FIXME("device %p, handle %#x, segment_count %p, patch_info %p stub!\n",
4465 device, handle, segment_count, patch_info);
4467 return WINED3D_OK;
4470 HRESULT CDECL wined3d_device_delete_patch(struct wined3d_device *device, UINT handle)
4472 struct wined3d_rect_patch *patch;
4473 struct list *e;
4474 int i;
4476 TRACE("device %p, handle %#x.\n", device, handle);
4478 i = PATCHMAP_HASHFUNC(handle);
4479 LIST_FOR_EACH(e, &device->patches[i])
4481 patch = LIST_ENTRY(e, struct wined3d_rect_patch, entry);
4482 if (patch->Handle == handle)
4484 TRACE("Deleting patch %p\n", patch);
4485 list_remove(&patch->entry);
4486 HeapFree(GetProcessHeap(), 0, patch->mem);
4487 HeapFree(GetProcessHeap(), 0, patch);
4488 return WINED3D_OK;
4492 /* TODO: Write a test for the return value */
4493 FIXME("Attempt to destroy nonexistent patch\n");
4494 return WINED3DERR_INVALIDCALL;
4497 /* Do not call while under the GL lock. */
4498 HRESULT CDECL wined3d_device_color_fill(struct wined3d_device *device,
4499 struct wined3d_surface *surface, const RECT *rect, const struct wined3d_color *color)
4501 RECT r;
4503 TRACE("device %p, surface %p, rect %s, color {%.8e, %.8e, %.8e, %.8e}.\n",
4504 device, surface, wine_dbgstr_rect(rect),
4505 color->r, color->g, color->b, color->a);
4507 if (surface->resource.pool != WINED3D_POOL_DEFAULT && surface->resource.pool != WINED3D_POOL_SYSTEM_MEM)
4509 WARN("Color-fill not allowed on %s surfaces.\n", debug_d3dpool(surface->resource.pool));
4510 return WINED3DERR_INVALIDCALL;
4513 if (!rect)
4515 SetRect(&r, 0, 0, surface->resource.width, surface->resource.height);
4516 rect = &r;
4519 return surface_color_fill(surface, rect, color);
4522 /* Do not call while under the GL lock. */
4523 void CDECL wined3d_device_clear_rendertarget_view(struct wined3d_device *device,
4524 struct wined3d_rendertarget_view *rendertarget_view, const struct wined3d_color *color)
4526 struct wined3d_resource *resource;
4527 HRESULT hr;
4528 RECT rect;
4530 resource = rendertarget_view->resource;
4531 if (resource->type != WINED3D_RTYPE_SURFACE)
4533 FIXME("Only supported on surface resources\n");
4534 return;
4537 SetRect(&rect, 0, 0, resource->width, resource->height);
4538 hr = surface_color_fill(surface_from_resource(resource), &rect, color);
4539 if (FAILED(hr)) ERR("Color fill failed, hr %#x.\n", hr);
4542 HRESULT CDECL wined3d_device_get_render_target(const struct wined3d_device *device,
4543 UINT render_target_idx, struct wined3d_surface **render_target)
4545 TRACE("device %p, render_target_idx %u, render_target %p.\n",
4546 device, render_target_idx, render_target);
4548 if (render_target_idx >= device->adapter->gl_info.limits.buffers)
4550 WARN("Only %u render targets are supported.\n", device->adapter->gl_info.limits.buffers);
4551 return WINED3DERR_INVALIDCALL;
4554 *render_target = device->fb.render_targets[render_target_idx];
4555 TRACE("Returning render target %p.\n", *render_target);
4557 if (!*render_target)
4558 return WINED3DERR_NOTFOUND;
4560 wined3d_surface_incref(*render_target);
4562 return WINED3D_OK;
4565 HRESULT CDECL wined3d_device_get_depth_stencil(const struct wined3d_device *device,
4566 struct wined3d_surface **depth_stencil)
4568 TRACE("device %p, depth_stencil %p.\n", device, depth_stencil);
4570 *depth_stencil = device->fb.depth_stencil;
4571 TRACE("Returning depth/stencil surface %p.\n", *depth_stencil);
4573 if (!*depth_stencil)
4574 return WINED3DERR_NOTFOUND;
4576 wined3d_surface_incref(*depth_stencil);
4578 return WINED3D_OK;
4581 HRESULT CDECL wined3d_device_set_render_target(struct wined3d_device *device,
4582 UINT render_target_idx, struct wined3d_surface *render_target, BOOL set_viewport)
4584 struct wined3d_surface *prev;
4586 TRACE("device %p, render_target_idx %u, render_target %p, set_viewport %#x.\n",
4587 device, render_target_idx, render_target, set_viewport);
4589 if (render_target_idx >= device->adapter->gl_info.limits.buffers)
4591 WARN("Only %u render targets are supported.\n", device->adapter->gl_info.limits.buffers);
4592 return WINED3DERR_INVALIDCALL;
4595 prev = device->fb.render_targets[render_target_idx];
4596 if (render_target == prev)
4598 TRACE("Trying to do a NOP SetRenderTarget operation.\n");
4599 return WINED3D_OK;
4602 /* Render target 0 can't be set to NULL. */
4603 if (!render_target && !render_target_idx)
4605 WARN("Trying to set render target 0 to NULL.\n");
4606 return WINED3DERR_INVALIDCALL;
4609 if (render_target && !(render_target->resource.usage & WINED3DUSAGE_RENDERTARGET))
4611 FIXME("Surface %p doesn't have render target usage.\n", render_target);
4612 return WINED3DERR_INVALIDCALL;
4615 if (render_target)
4616 wined3d_surface_incref(render_target);
4617 device->fb.render_targets[render_target_idx] = render_target;
4618 /* Release after the assignment, to prevent device_resource_released()
4619 * from seeing the surface as still in use. */
4620 if (prev)
4621 wined3d_surface_decref(prev);
4623 /* Render target 0 is special. */
4624 if (!render_target_idx && set_viewport)
4626 /* Set the viewport and scissor rectangles, if requested. Tests show
4627 * that stateblock recording is ignored, the change goes directly
4628 * into the primary stateblock. */
4629 device->stateBlock->state.viewport.height = device->fb.render_targets[0]->resource.height;
4630 device->stateBlock->state.viewport.width = device->fb.render_targets[0]->resource.width;
4631 device->stateBlock->state.viewport.x = 0;
4632 device->stateBlock->state.viewport.y = 0;
4633 device->stateBlock->state.viewport.max_z = 1.0f;
4634 device->stateBlock->state.viewport.min_z = 0.0f;
4635 device_invalidate_state(device, STATE_VIEWPORT);
4637 device->stateBlock->state.scissor_rect.top = 0;
4638 device->stateBlock->state.scissor_rect.left = 0;
4639 device->stateBlock->state.scissor_rect.right = device->stateBlock->state.viewport.width;
4640 device->stateBlock->state.scissor_rect.bottom = device->stateBlock->state.viewport.height;
4641 device_invalidate_state(device, STATE_SCISSORRECT);
4644 device_invalidate_state(device, STATE_FRAMEBUFFER);
4646 return WINED3D_OK;
4649 HRESULT CDECL wined3d_device_set_depth_stencil(struct wined3d_device *device, struct wined3d_surface *depth_stencil)
4651 struct wined3d_surface *prev = device->fb.depth_stencil;
4653 TRACE("device %p, depth_stencil %p, old depth_stencil %p.\n",
4654 device, depth_stencil, prev);
4656 if (prev == depth_stencil)
4658 TRACE("Trying to do a NOP SetRenderTarget operation.\n");
4659 return WINED3D_OK;
4662 if (prev)
4664 if (device->swapchains[0]->desc.flags & WINED3DPRESENTFLAG_DISCARD_DEPTHSTENCIL
4665 || prev->flags & SFLAG_DISCARD)
4667 surface_modify_ds_location(prev, SFLAG_DISCARDED,
4668 prev->resource.width, prev->resource.height);
4669 if (prev == device->onscreen_depth_stencil)
4671 wined3d_surface_decref(device->onscreen_depth_stencil);
4672 device->onscreen_depth_stencil = NULL;
4677 device->fb.depth_stencil = depth_stencil;
4678 if (depth_stencil)
4679 wined3d_surface_incref(depth_stencil);
4681 if (!prev != !depth_stencil)
4683 /* Swapping NULL / non NULL depth stencil affects the depth and tests */
4684 device_invalidate_state(device, STATE_RENDER(WINED3D_RS_ZENABLE));
4685 device_invalidate_state(device, STATE_RENDER(WINED3D_RS_STENCILENABLE));
4686 device_invalidate_state(device, STATE_RENDER(WINED3D_RS_STENCILWRITEMASK));
4687 device_invalidate_state(device, STATE_RENDER(WINED3D_RS_DEPTHBIAS));
4689 else if (prev && prev->resource.format->depth_size != depth_stencil->resource.format->depth_size)
4691 device_invalidate_state(device, STATE_RENDER(WINED3D_RS_DEPTHBIAS));
4693 if (prev)
4694 wined3d_surface_decref(prev);
4696 device_invalidate_state(device, STATE_FRAMEBUFFER);
4698 return WINED3D_OK;
4701 HRESULT CDECL wined3d_device_set_cursor_properties(struct wined3d_device *device,
4702 UINT x_hotspot, UINT y_hotspot, struct wined3d_surface *cursor_image)
4704 TRACE("device %p, x_hotspot %u, y_hotspot %u, cursor_image %p.\n",
4705 device, x_hotspot, y_hotspot, cursor_image);
4707 /* some basic validation checks */
4708 if (device->cursorTexture)
4710 struct wined3d_context *context = context_acquire(device, NULL);
4711 ENTER_GL();
4712 context->gl_info->gl_ops.gl.p_glDeleteTextures(1, &device->cursorTexture);
4713 LEAVE_GL();
4714 context_release(context);
4715 device->cursorTexture = 0;
4718 if (cursor_image)
4720 struct wined3d_display_mode mode;
4721 struct wined3d_map_desc map_desc;
4722 HRESULT hr;
4724 /* MSDN: Cursor must be A8R8G8B8 */
4725 if (cursor_image->resource.format->id != WINED3DFMT_B8G8R8A8_UNORM)
4727 WARN("surface %p has an invalid format.\n", cursor_image);
4728 return WINED3DERR_INVALIDCALL;
4731 if (FAILED(hr = wined3d_get_adapter_display_mode(device->wined3d, device->adapter->ordinal, &mode, NULL)))
4733 ERR("Failed to get display mode, hr %#x.\n", hr);
4734 return WINED3DERR_INVALIDCALL;
4737 /* MSDN: Cursor must be smaller than the display mode */
4738 if (cursor_image->resource.width > mode.width || cursor_image->resource.height > mode.height)
4740 WARN("Surface %p dimensions are %ux%u, but screen dimensions are %ux%u.\n",
4741 cursor_image, cursor_image->resource.width, cursor_image->resource.height,
4742 mode.width, mode.height);
4743 return WINED3DERR_INVALIDCALL;
4746 /* TODO: MSDN: Cursor sizes must be a power of 2 */
4748 /* Do not store the surface's pointer because the application may
4749 * release it after setting the cursor image. Windows doesn't
4750 * addref the set surface, so we can't do this either without
4751 * creating circular refcount dependencies. Copy out the gl texture
4752 * instead. */
4753 device->cursorWidth = cursor_image->resource.width;
4754 device->cursorHeight = cursor_image->resource.height;
4755 if (SUCCEEDED(wined3d_surface_map(cursor_image, &map_desc, NULL, WINED3D_MAP_READONLY)))
4757 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4758 const struct wined3d_format *format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
4759 struct wined3d_context *context;
4760 char *mem, *bits = map_desc.data;
4761 GLint intfmt = format->glInternal;
4762 GLint gl_format = format->glFormat;
4763 GLint type = format->glType;
4764 INT height = device->cursorHeight;
4765 INT width = device->cursorWidth;
4766 INT bpp = format->byte_count;
4767 INT i;
4769 /* Reformat the texture memory (pitch and width can be
4770 * different) */
4771 mem = HeapAlloc(GetProcessHeap(), 0, width * height * bpp);
4772 for (i = 0; i < height; ++i)
4773 memcpy(&mem[width * bpp * i], &bits[map_desc.row_pitch * i], width * bpp);
4774 wined3d_surface_unmap(cursor_image);
4776 context = context_acquire(device, NULL);
4778 ENTER_GL();
4780 if (gl_info->supported[APPLE_CLIENT_STORAGE])
4782 gl_info->gl_ops.gl.p_glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE);
4783 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE)");
4786 invalidate_active_texture(device, context);
4787 /* Create a new cursor texture */
4788 gl_info->gl_ops.gl.p_glGenTextures(1, &device->cursorTexture);
4789 checkGLcall("glGenTextures");
4790 context_bind_texture(context, GL_TEXTURE_2D, device->cursorTexture);
4791 /* Copy the bitmap memory into the cursor texture */
4792 gl_info->gl_ops.gl.p_glTexImage2D(GL_TEXTURE_2D, 0, intfmt, width, height, 0, gl_format, type, mem);
4793 checkGLcall("glTexImage2D");
4794 HeapFree(GetProcessHeap(), 0, mem);
4796 if (gl_info->supported[APPLE_CLIENT_STORAGE])
4798 gl_info->gl_ops.gl.p_glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
4799 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
4802 LEAVE_GL();
4804 context_release(context);
4806 else
4808 FIXME("A cursor texture was not returned.\n");
4809 device->cursorTexture = 0;
4812 if (cursor_image->resource.width == 32 && cursor_image->resource.height == 32)
4814 UINT mask_size = cursor_image->resource.width * cursor_image->resource.height / 8;
4815 ICONINFO cursorInfo;
4816 DWORD *maskBits;
4817 HCURSOR cursor;
4819 /* 32-bit user32 cursors ignore the alpha channel if it's all
4820 * zeroes, and use the mask instead. Fill the mask with all ones
4821 * to ensure we still get a fully transparent cursor. */
4822 maskBits = HeapAlloc(GetProcessHeap(), 0, mask_size);
4823 memset(maskBits, 0xff, mask_size);
4824 wined3d_surface_map(cursor_image, &map_desc, NULL,
4825 WINED3D_MAP_NO_DIRTY_UPDATE | WINED3D_MAP_READONLY);
4826 TRACE("width: %u height: %u.\n", cursor_image->resource.width, cursor_image->resource.height);
4828 cursorInfo.fIcon = FALSE;
4829 cursorInfo.xHotspot = x_hotspot;
4830 cursorInfo.yHotspot = y_hotspot;
4831 cursorInfo.hbmMask = CreateBitmap(cursor_image->resource.width, cursor_image->resource.height,
4832 1, 1, maskBits);
4833 cursorInfo.hbmColor = CreateBitmap(cursor_image->resource.width, cursor_image->resource.height,
4834 1, 32, map_desc.data);
4835 wined3d_surface_unmap(cursor_image);
4836 /* Create our cursor and clean up. */
4837 cursor = CreateIconIndirect(&cursorInfo);
4838 if (cursorInfo.hbmMask) DeleteObject(cursorInfo.hbmMask);
4839 if (cursorInfo.hbmColor) DeleteObject(cursorInfo.hbmColor);
4840 if (device->hardwareCursor) DestroyCursor(device->hardwareCursor);
4841 device->hardwareCursor = cursor;
4842 if (device->bCursorVisible) SetCursor( cursor );
4843 HeapFree(GetProcessHeap(), 0, maskBits);
4847 device->xHotSpot = x_hotspot;
4848 device->yHotSpot = y_hotspot;
4849 return WINED3D_OK;
4852 void CDECL wined3d_device_set_cursor_position(struct wined3d_device *device,
4853 int x_screen_space, int y_screen_space, DWORD flags)
4855 TRACE("device %p, x %d, y %d, flags %#x.\n",
4856 device, x_screen_space, y_screen_space, flags);
4858 device->xScreenSpace = x_screen_space;
4859 device->yScreenSpace = y_screen_space;
4861 if (device->hardwareCursor)
4863 POINT pt;
4865 GetCursorPos( &pt );
4866 if (x_screen_space == pt.x && y_screen_space == pt.y)
4867 return;
4868 SetCursorPos( x_screen_space, y_screen_space );
4870 /* Switch to the software cursor if position diverges from the hardware one. */
4871 GetCursorPos( &pt );
4872 if (x_screen_space != pt.x || y_screen_space != pt.y)
4874 if (device->bCursorVisible) SetCursor( NULL );
4875 DestroyCursor( device->hardwareCursor );
4876 device->hardwareCursor = 0;
4881 BOOL CDECL wined3d_device_show_cursor(struct wined3d_device *device, BOOL show)
4883 BOOL oldVisible = device->bCursorVisible;
4885 TRACE("device %p, show %#x.\n", device, show);
4888 * When ShowCursor is first called it should make the cursor appear at the OS's last
4889 * known cursor position.
4891 if (show && !oldVisible)
4893 POINT pt;
4894 GetCursorPos(&pt);
4895 device->xScreenSpace = pt.x;
4896 device->yScreenSpace = pt.y;
4899 if (device->hardwareCursor)
4901 device->bCursorVisible = show;
4902 if (show)
4903 SetCursor(device->hardwareCursor);
4904 else
4905 SetCursor(NULL);
4907 else
4909 if (device->cursorTexture)
4910 device->bCursorVisible = show;
4913 return oldVisible;
4916 void CDECL wined3d_device_evict_managed_resources(struct wined3d_device *device)
4918 struct wined3d_resource *resource, *cursor;
4920 TRACE("device %p.\n", device);
4922 LIST_FOR_EACH_ENTRY_SAFE(resource, cursor, &device->resources, struct wined3d_resource, resource_list_entry)
4924 TRACE("Checking resource %p for eviction.\n", resource);
4926 if (resource->pool == WINED3D_POOL_MANAGED && !resource->map_count)
4928 TRACE("Evicting %p.\n", resource);
4929 resource->resource_ops->resource_unload(resource);
4933 /* Invalidate stream sources, the buffer(s) may have been evicted. */
4934 device_invalidate_state(device, STATE_STREAMSRC);
4937 /* Do not call while under the GL lock. */
4938 static void delete_opengl_contexts(struct wined3d_device *device, struct wined3d_swapchain *swapchain)
4940 struct wined3d_resource *resource, *cursor;
4941 const struct wined3d_gl_info *gl_info;
4942 struct wined3d_context *context;
4943 struct wined3d_shader *shader;
4945 context = context_acquire(device, NULL);
4946 gl_info = context->gl_info;
4948 LIST_FOR_EACH_ENTRY_SAFE(resource, cursor, &device->resources, struct wined3d_resource, resource_list_entry)
4950 TRACE("Unloading resource %p.\n", resource);
4952 resource->resource_ops->resource_unload(resource);
4955 LIST_FOR_EACH_ENTRY(shader, &device->shaders, struct wined3d_shader, shader_list_entry)
4957 device->shader_backend->shader_destroy(shader);
4960 ENTER_GL();
4961 if (device->depth_blt_texture)
4963 gl_info->gl_ops.gl.p_glDeleteTextures(1, &device->depth_blt_texture);
4964 device->depth_blt_texture = 0;
4966 if (device->cursorTexture)
4968 gl_info->gl_ops.gl.p_glDeleteTextures(1, &device->cursorTexture);
4969 device->cursorTexture = 0;
4971 LEAVE_GL();
4973 device->blitter->free_private(device);
4974 device->frag_pipe->free_private(device);
4975 device->shader_backend->shader_free_private(device);
4976 destroy_dummy_textures(device, gl_info);
4978 context_release(context);
4980 while (device->context_count)
4982 swapchain_destroy_contexts(device->contexts[0]->swapchain);
4985 HeapFree(GetProcessHeap(), 0, swapchain->context);
4986 swapchain->context = NULL;
4989 /* Do not call while under the GL lock. */
4990 static HRESULT create_primary_opengl_context(struct wined3d_device *device, struct wined3d_swapchain *swapchain)
4992 struct wined3d_context *context;
4993 struct wined3d_surface *target;
4994 HRESULT hr;
4996 /* Recreate the primary swapchain's context */
4997 swapchain->context = HeapAlloc(GetProcessHeap(), 0, sizeof(*swapchain->context));
4998 if (!swapchain->context)
5000 ERR("Failed to allocate memory for swapchain context array.\n");
5001 return E_OUTOFMEMORY;
5004 target = swapchain->back_buffers ? swapchain->back_buffers[0] : swapchain->front_buffer;
5005 if (!(context = context_create(swapchain, target, swapchain->ds_format)))
5007 WARN("Failed to create context.\n");
5008 HeapFree(GetProcessHeap(), 0, swapchain->context);
5009 return E_FAIL;
5012 swapchain->context[0] = context;
5013 swapchain->num_contexts = 1;
5014 create_dummy_textures(device, context);
5015 context_release(context);
5017 hr = device->shader_backend->shader_alloc_private(device);
5018 if (FAILED(hr))
5020 ERR("Failed to allocate shader private data, hr %#x.\n", hr);
5021 goto err;
5024 hr = device->frag_pipe->alloc_private(device);
5025 if (FAILED(hr))
5027 ERR("Failed to allocate fragment pipe private data, hr %#x.\n", hr);
5028 device->shader_backend->shader_free_private(device);
5029 goto err;
5032 hr = device->blitter->alloc_private(device);
5033 if (FAILED(hr))
5035 ERR("Failed to allocate blitter private data, hr %#x.\n", hr);
5036 device->frag_pipe->free_private(device);
5037 device->shader_backend->shader_free_private(device);
5038 goto err;
5041 return WINED3D_OK;
5043 err:
5044 context_acquire(device, NULL);
5045 destroy_dummy_textures(device, context->gl_info);
5046 context_release(context);
5047 context_destroy(device, context);
5048 HeapFree(GetProcessHeap(), 0, swapchain->context);
5049 swapchain->num_contexts = 0;
5050 return hr;
5053 /* Do not call while under the GL lock. */
5054 HRESULT CDECL wined3d_device_reset(struct wined3d_device *device,
5055 const struct wined3d_swapchain_desc *swapchain_desc, const struct wined3d_display_mode *mode,
5056 wined3d_device_reset_cb callback)
5058 struct wined3d_resource *resource, *cursor;
5059 struct wined3d_swapchain *swapchain;
5060 struct wined3d_display_mode m;
5061 BOOL DisplayModeChanged = FALSE;
5062 BOOL update_desc = FALSE;
5063 unsigned int i;
5064 HRESULT hr;
5066 TRACE("device %p, swapchain_desc %p, mode %p, callback %p.\n", device, swapchain_desc, mode, callback);
5068 if (!(swapchain = wined3d_device_get_swapchain(device, 0)))
5070 ERR("Failed to get the first implicit swapchain.\n");
5071 return WINED3DERR_INVALIDCALL;
5074 stateblock_unbind_resources(device->stateBlock);
5075 if (device->fb.render_targets)
5077 if (swapchain->back_buffers && swapchain->back_buffers[0])
5078 wined3d_device_set_render_target(device, 0, swapchain->back_buffers[0], FALSE);
5079 else
5080 wined3d_device_set_render_target(device, 0, swapchain->front_buffer, FALSE);
5081 for (i = 1; i < device->adapter->gl_info.limits.buffers; ++i)
5083 wined3d_device_set_render_target(device, i, NULL, FALSE);
5086 wined3d_device_set_depth_stencil(device, NULL);
5088 if (device->onscreen_depth_stencil)
5090 wined3d_surface_decref(device->onscreen_depth_stencil);
5091 device->onscreen_depth_stencil = NULL;
5094 LIST_FOR_EACH_ENTRY_SAFE(resource, cursor, &device->resources, struct wined3d_resource, resource_list_entry)
5096 TRACE("Enumerating resource %p.\n", resource);
5097 if (FAILED(hr = callback(resource)))
5098 return hr;
5101 /* Is it necessary to recreate the gl context? Actually every setting can be changed
5102 * on an existing gl context, so there's no real need for recreation.
5104 * TODO: Figure out how Reset influences resources in D3DPOOL_DEFAULT, D3DPOOL_SYSTEMMEMORY and D3DPOOL_MANAGED
5106 * TODO: Figure out what happens to explicit swapchains, or if we have more than one implicit swapchain
5108 TRACE("New params:\n");
5109 TRACE("backbuffer_width %u\n", swapchain_desc->backbuffer_width);
5110 TRACE("backbuffer_height %u\n", swapchain_desc->backbuffer_height);
5111 TRACE("backbuffer_format %s\n", debug_d3dformat(swapchain_desc->backbuffer_format));
5112 TRACE("backbuffer_count %u\n", swapchain_desc->backbuffer_count);
5113 TRACE("multisample_type %#x\n", swapchain_desc->multisample_type);
5114 TRACE("multisample_quality %u\n", swapchain_desc->multisample_quality);
5115 TRACE("swap_effect %#x\n", swapchain_desc->swap_effect);
5116 TRACE("device_window %p\n", swapchain_desc->device_window);
5117 TRACE("windowed %#x\n", swapchain_desc->windowed);
5118 TRACE("enable_auto_depth_stencil %#x\n", swapchain_desc->enable_auto_depth_stencil);
5119 if (swapchain_desc->enable_auto_depth_stencil)
5120 TRACE("auto_depth_stencil_format %s\n", debug_d3dformat(swapchain_desc->auto_depth_stencil_format));
5121 TRACE("flags %#x\n", swapchain_desc->flags);
5122 TRACE("refresh_rate %u\n", swapchain_desc->refresh_rate);
5123 TRACE("swap_interval %u\n", swapchain_desc->swap_interval);
5124 TRACE("auto_restore_display_mode %#x\n", swapchain_desc->auto_restore_display_mode);
5126 /* No special treatment of these parameters. Just store them */
5127 swapchain->desc.swap_effect = swapchain_desc->swap_effect;
5128 swapchain->desc.flags = swapchain_desc->flags;
5129 swapchain->desc.swap_interval = swapchain_desc->swap_interval;
5130 swapchain->desc.refresh_rate = swapchain_desc->refresh_rate;
5132 /* What to do about these? */
5133 if (swapchain_desc->backbuffer_count
5134 && swapchain_desc->backbuffer_count != swapchain->desc.backbuffer_count)
5135 FIXME("Cannot change the back buffer count yet.\n");
5137 if (swapchain_desc->device_window
5138 && swapchain_desc->device_window != swapchain->desc.device_window)
5140 TRACE("Changing the device window from %p to %p.\n",
5141 swapchain->desc.device_window, swapchain_desc->device_window);
5142 swapchain->desc.device_window = swapchain_desc->device_window;
5143 swapchain->device_window = swapchain_desc->device_window;
5144 wined3d_swapchain_set_window(swapchain, NULL);
5147 if (swapchain_desc->enable_auto_depth_stencil && !device->auto_depth_stencil)
5149 HRESULT hr;
5151 TRACE("Creating the depth stencil buffer\n");
5153 if (FAILED(hr = device->device_parent->ops->create_swapchain_surface(device->device_parent,
5154 device->device_parent, swapchain_desc->backbuffer_width, swapchain_desc->backbuffer_height,
5155 swapchain_desc->auto_depth_stencil_format, WINED3DUSAGE_DEPTHSTENCIL,
5156 swapchain_desc->multisample_type, swapchain_desc->multisample_quality,
5157 &device->auto_depth_stencil)))
5159 ERR("Failed to create the depth stencil buffer, hr %#x.\n", hr);
5160 return WINED3DERR_INVALIDCALL;
5164 /* Reset the depth stencil */
5165 if (swapchain_desc->enable_auto_depth_stencil)
5166 wined3d_device_set_depth_stencil(device, device->auto_depth_stencil);
5168 if (mode)
5170 DisplayModeChanged = TRUE;
5171 m = *mode;
5173 else if (swapchain_desc->windowed)
5175 m.width = swapchain->orig_width;
5176 m.height = swapchain->orig_height;
5177 m.refresh_rate = 0;
5178 m.format_id = swapchain->desc.backbuffer_format;
5179 m.scanline_ordering = WINED3D_SCANLINE_ORDERING_UNKNOWN;
5181 else
5183 m.width = swapchain_desc->backbuffer_width;
5184 m.height = swapchain_desc->backbuffer_height;
5185 m.refresh_rate = swapchain_desc->refresh_rate;
5186 m.format_id = swapchain_desc->backbuffer_format;
5187 m.scanline_ordering = WINED3D_SCANLINE_ORDERING_UNKNOWN;
5190 /* Should Width == 800 && Height == 0 set 800x600? */
5191 if (swapchain_desc->backbuffer_width && swapchain_desc->backbuffer_height
5192 && (swapchain_desc->backbuffer_width != swapchain->desc.backbuffer_width
5193 || swapchain_desc->backbuffer_height != swapchain->desc.backbuffer_height))
5195 if (!swapchain_desc->windowed)
5196 DisplayModeChanged = TRUE;
5198 swapchain->desc.backbuffer_width = swapchain_desc->backbuffer_width;
5199 swapchain->desc.backbuffer_height = swapchain_desc->backbuffer_height;
5200 update_desc = TRUE;
5203 if (swapchain_desc->backbuffer_format != WINED3DFMT_UNKNOWN
5204 && swapchain_desc->backbuffer_format != swapchain->desc.backbuffer_format)
5206 swapchain->desc.backbuffer_format = swapchain_desc->backbuffer_format;
5207 update_desc = TRUE;
5210 if (swapchain_desc->multisample_type != swapchain->desc.multisample_type
5211 || swapchain_desc->multisample_quality != swapchain->desc.multisample_quality)
5213 swapchain->desc.multisample_type = swapchain_desc->multisample_type;
5214 swapchain->desc.multisample_quality = swapchain_desc->multisample_quality;
5215 update_desc = TRUE;
5218 if (update_desc)
5220 UINT i;
5222 if (FAILED(hr = wined3d_surface_update_desc(swapchain->front_buffer, swapchain->desc.backbuffer_width,
5223 swapchain->desc.backbuffer_height, swapchain->desc.backbuffer_format,
5224 swapchain->desc.multisample_type, swapchain->desc.multisample_quality)))
5225 return hr;
5227 for (i = 0; i < swapchain->desc.backbuffer_count; ++i)
5229 if (FAILED(hr = wined3d_surface_update_desc(swapchain->back_buffers[i], swapchain->desc.backbuffer_width,
5230 swapchain->desc.backbuffer_height, swapchain->desc.backbuffer_format,
5231 swapchain->desc.multisample_type, swapchain->desc.multisample_quality)))
5232 return hr;
5234 if (device->auto_depth_stencil)
5236 if (FAILED(hr = wined3d_surface_update_desc(device->auto_depth_stencil, swapchain->desc.backbuffer_width,
5237 swapchain->desc.backbuffer_height, device->auto_depth_stencil->resource.format->id,
5238 swapchain->desc.multisample_type, swapchain->desc.multisample_quality)))
5239 return hr;
5243 if (!swapchain_desc->windowed != !swapchain->desc.windowed
5244 || DisplayModeChanged)
5246 if (FAILED(hr = wined3d_set_adapter_display_mode(device->wined3d, device->adapter->ordinal, &m)))
5248 WARN("Failed to set display mode, hr %#x.\n", hr);
5249 return WINED3DERR_INVALIDCALL;
5252 if (!swapchain_desc->windowed)
5254 if (swapchain->desc.windowed)
5256 HWND focus_window = device->create_parms.focus_window;
5257 if (!focus_window)
5258 focus_window = swapchain_desc->device_window;
5259 if (FAILED(hr = wined3d_device_acquire_focus_window(device, focus_window)))
5261 ERR("Failed to acquire focus window, hr %#x.\n", hr);
5262 return hr;
5265 /* switch from windowed to fs */
5266 wined3d_device_setup_fullscreen_window(device, swapchain->device_window,
5267 swapchain_desc->backbuffer_width,
5268 swapchain_desc->backbuffer_height);
5270 else
5272 /* Fullscreen -> fullscreen mode change */
5273 MoveWindow(swapchain->device_window, 0, 0,
5274 swapchain_desc->backbuffer_width,
5275 swapchain_desc->backbuffer_height,
5276 TRUE);
5279 else if (!swapchain->desc.windowed)
5281 /* Fullscreen -> windowed switch */
5282 wined3d_device_restore_fullscreen_window(device, swapchain->device_window);
5283 wined3d_device_release_focus_window(device);
5285 swapchain->desc.windowed = swapchain_desc->windowed;
5287 else if (!swapchain_desc->windowed)
5289 DWORD style = device->style;
5290 DWORD exStyle = device->exStyle;
5291 /* If we're in fullscreen, and the mode wasn't changed, we have to get the window back into
5292 * the right position. Some applications(Battlefield 2, Guild Wars) move it and then call
5293 * Reset to clear up their mess. Guild Wars also loses the device during that.
5295 device->style = 0;
5296 device->exStyle = 0;
5297 wined3d_device_setup_fullscreen_window(device, swapchain->device_window,
5298 swapchain_desc->backbuffer_width,
5299 swapchain_desc->backbuffer_height);
5300 device->style = style;
5301 device->exStyle = exStyle;
5304 TRACE("Resetting stateblock.\n");
5305 wined3d_stateblock_decref(device->updateStateBlock);
5306 wined3d_stateblock_decref(device->stateBlock);
5308 if (device->d3d_initialized)
5309 delete_opengl_contexts(device, swapchain);
5311 /* Note: No parent needed for initial internal stateblock */
5312 hr = wined3d_stateblock_create(device, WINED3D_SBT_INIT, &device->stateBlock);
5313 if (FAILED(hr))
5314 ERR("Resetting the stateblock failed with error %#x.\n", hr);
5315 else
5316 TRACE("Created stateblock %p.\n", device->stateBlock);
5317 device->updateStateBlock = device->stateBlock;
5318 wined3d_stateblock_incref(device->updateStateBlock);
5320 stateblock_init_default_state(device->stateBlock);
5322 swapchain_update_render_to_fbo(swapchain);
5323 swapchain_update_draw_bindings(swapchain);
5325 if (device->d3d_initialized)
5326 hr = create_primary_opengl_context(device, swapchain);
5328 /* All done. There is no need to reload resources or shaders, this will happen automatically on the
5329 * first use
5331 return hr;
5334 HRESULT CDECL wined3d_device_set_dialog_box_mode(struct wined3d_device *device, BOOL enable_dialogs)
5336 TRACE("device %p, enable_dialogs %#x.\n", device, enable_dialogs);
5338 if (!enable_dialogs) FIXME("Dialogs cannot be disabled yet.\n");
5340 return WINED3D_OK;
5344 HRESULT CDECL wined3d_device_get_creation_parameters(const struct wined3d_device *device,
5345 struct wined3d_device_creation_parameters *parameters)
5347 TRACE("device %p, parameters %p.\n", device, parameters);
5349 *parameters = device->create_parms;
5350 return WINED3D_OK;
5353 void CDECL wined3d_device_set_gamma_ramp(const struct wined3d_device *device,
5354 UINT swapchain_idx, DWORD flags, const struct wined3d_gamma_ramp *ramp)
5356 struct wined3d_swapchain *swapchain;
5358 TRACE("device %p, swapchain_idx %u, flags %#x, ramp %p.\n",
5359 device, swapchain_idx, flags, ramp);
5361 if ((swapchain = wined3d_device_get_swapchain(device, swapchain_idx)))
5362 wined3d_swapchain_set_gamma_ramp(swapchain, flags, ramp);
5365 void CDECL wined3d_device_get_gamma_ramp(const struct wined3d_device *device,
5366 UINT swapchain_idx, struct wined3d_gamma_ramp *ramp)
5368 struct wined3d_swapchain *swapchain;
5370 TRACE("device %p, swapchain_idx %u, ramp %p.\n",
5371 device, swapchain_idx, ramp);
5373 if ((swapchain = wined3d_device_get_swapchain(device, swapchain_idx)))
5374 wined3d_swapchain_get_gamma_ramp(swapchain, ramp);
5377 void device_resource_add(struct wined3d_device *device, struct wined3d_resource *resource)
5379 TRACE("device %p, resource %p.\n", device, resource);
5381 list_add_head(&device->resources, &resource->resource_list_entry);
5384 static void device_resource_remove(struct wined3d_device *device, struct wined3d_resource *resource)
5386 TRACE("device %p, resource %p.\n", device, resource);
5388 list_remove(&resource->resource_list_entry);
5391 void device_resource_released(struct wined3d_device *device, struct wined3d_resource *resource)
5393 enum wined3d_resource_type type = resource->type;
5394 unsigned int i;
5396 TRACE("device %p, resource %p, type %s.\n", device, resource, debug_d3dresourcetype(type));
5398 context_resource_released(device, resource, type);
5400 switch (type)
5402 case WINED3D_RTYPE_SURFACE:
5404 struct wined3d_surface *surface = surface_from_resource(resource);
5406 if (!device->d3d_initialized) break;
5408 for (i = 0; i < device->adapter->gl_info.limits.buffers; ++i)
5410 if (device->fb.render_targets[i] == surface)
5412 ERR("Surface %p is still in use as render target %u.\n", surface, i);
5413 device->fb.render_targets[i] = NULL;
5417 if (device->fb.depth_stencil == surface)
5419 ERR("Surface %p is still in use as depth/stencil buffer.\n", surface);
5420 device->fb.depth_stencil = NULL;
5423 break;
5425 case WINED3D_RTYPE_TEXTURE:
5426 case WINED3D_RTYPE_CUBE_TEXTURE:
5427 case WINED3D_RTYPE_VOLUME_TEXTURE:
5428 for (i = 0; i < MAX_COMBINED_SAMPLERS; ++i)
5430 struct wined3d_texture *texture = wined3d_texture_from_resource(resource);
5432 if (device->stateBlock && device->stateBlock->state.textures[i] == texture)
5434 ERR("Texture %p is still in use by stateblock %p, stage %u.\n",
5435 texture, device->stateBlock, i);
5436 device->stateBlock->state.textures[i] = NULL;
5439 if (device->updateStateBlock != device->stateBlock
5440 && device->updateStateBlock->state.textures[i] == texture)
5442 ERR("Texture %p is still in use by stateblock %p, stage %u.\n",
5443 texture, device->updateStateBlock, i);
5444 device->updateStateBlock->state.textures[i] = NULL;
5447 break;
5449 case WINED3D_RTYPE_BUFFER:
5451 struct wined3d_buffer *buffer = buffer_from_resource(resource);
5453 for (i = 0; i < MAX_STREAMS; ++i)
5455 if (device->stateBlock && device->stateBlock->state.streams[i].buffer == buffer)
5457 ERR("Buffer %p is still in use by stateblock %p, stream %u.\n",
5458 buffer, device->stateBlock, i);
5459 device->stateBlock->state.streams[i].buffer = NULL;
5462 if (device->updateStateBlock != device->stateBlock
5463 && device->updateStateBlock->state.streams[i].buffer == buffer)
5465 ERR("Buffer %p is still in use by stateblock %p, stream %u.\n",
5466 buffer, device->updateStateBlock, i);
5467 device->updateStateBlock->state.streams[i].buffer = NULL;
5472 if (device->stateBlock && device->stateBlock->state.index_buffer == buffer)
5474 ERR("Buffer %p is still in use by stateblock %p as index buffer.\n",
5475 buffer, device->stateBlock);
5476 device->stateBlock->state.index_buffer = NULL;
5479 if (device->updateStateBlock != device->stateBlock
5480 && device->updateStateBlock->state.index_buffer == buffer)
5482 ERR("Buffer %p is still in use by stateblock %p as index buffer.\n",
5483 buffer, device->updateStateBlock);
5484 device->updateStateBlock->state.index_buffer = NULL;
5487 break;
5489 default:
5490 break;
5493 /* Remove the resource from the resourceStore */
5494 device_resource_remove(device, resource);
5496 TRACE("Resource released.\n");
5499 HRESULT CDECL wined3d_device_get_surface_from_dc(const struct wined3d_device *device,
5500 HDC dc, struct wined3d_surface **surface)
5502 struct wined3d_resource *resource;
5504 TRACE("device %p, dc %p, surface %p.\n", device, dc, surface);
5506 if (!dc)
5507 return WINED3DERR_INVALIDCALL;
5509 LIST_FOR_EACH_ENTRY(resource, &device->resources, struct wined3d_resource, resource_list_entry)
5511 if (resource->type == WINED3D_RTYPE_SURFACE)
5513 struct wined3d_surface *s = surface_from_resource(resource);
5515 if (s->hDC == dc)
5517 TRACE("Found surface %p for dc %p.\n", s, dc);
5518 *surface = s;
5519 return WINED3D_OK;
5524 return WINED3DERR_INVALIDCALL;
5527 HRESULT device_init(struct wined3d_device *device, struct wined3d *wined3d,
5528 UINT adapter_idx, enum wined3d_device_type device_type, HWND focus_window, DWORD flags,
5529 BYTE surface_alignment, struct wined3d_device_parent *device_parent)
5531 struct wined3d_adapter *adapter = &wined3d->adapters[adapter_idx];
5532 const struct fragment_pipeline *fragment_pipeline;
5533 struct shader_caps shader_caps;
5534 struct fragment_caps ffp_caps;
5535 unsigned int i;
5536 HRESULT hr;
5538 device->ref = 1;
5539 device->wined3d = wined3d;
5540 wined3d_incref(device->wined3d);
5541 device->adapter = wined3d->adapter_count ? adapter : NULL;
5542 device->device_parent = device_parent;
5543 list_init(&device->resources);
5544 list_init(&device->shaders);
5545 device->surface_alignment = surface_alignment;
5547 /* Save the creation parameters. */
5548 device->create_parms.adapter_idx = adapter_idx;
5549 device->create_parms.device_type = device_type;
5550 device->create_parms.focus_window = focus_window;
5551 device->create_parms.flags = flags;
5553 for (i = 0; i < PATCHMAP_SIZE; ++i) list_init(&device->patches[i]);
5555 select_shader_mode(&adapter->gl_info, &device->ps_selected_mode, &device->vs_selected_mode);
5556 device->shader_backend = adapter->shader_backend;
5558 if (device->shader_backend)
5560 device->shader_backend->shader_get_caps(&adapter->gl_info, &shader_caps);
5561 device->vshader_version = shader_caps.VertexShaderVersion;
5562 device->pshader_version = shader_caps.PixelShaderVersion;
5563 device->d3d_vshader_constantF = shader_caps.MaxVertexShaderConst;
5564 device->d3d_pshader_constantF = shader_caps.MaxPixelShaderConst;
5565 device->vs_clipping = shader_caps.VSClipping;
5567 fragment_pipeline = adapter->fragment_pipe;
5568 device->frag_pipe = fragment_pipeline;
5569 if (fragment_pipeline)
5571 fragment_pipeline->get_caps(&adapter->gl_info, &ffp_caps);
5572 device->max_ffp_textures = ffp_caps.MaxSimultaneousTextures;
5574 hr = compile_state_table(device->StateTable, device->multistate_funcs, &adapter->gl_info,
5575 ffp_vertexstate_template, fragment_pipeline, misc_state_template);
5576 if (FAILED(hr))
5578 ERR("Failed to compile state table, hr %#x.\n", hr);
5579 wined3d_decref(device->wined3d);
5580 return hr;
5583 device->blitter = adapter->blitter;
5585 hr = wined3d_stateblock_create(device, WINED3D_SBT_INIT, &device->stateBlock);
5586 if (FAILED(hr))
5588 WARN("Failed to create stateblock.\n");
5589 for (i = 0; i < sizeof(device->multistate_funcs) / sizeof(device->multistate_funcs[0]); ++i)
5591 HeapFree(GetProcessHeap(), 0, device->multistate_funcs[i]);
5593 wined3d_decref(device->wined3d);
5594 return hr;
5597 TRACE("Created stateblock %p.\n", device->stateBlock);
5598 device->updateStateBlock = device->stateBlock;
5599 wined3d_stateblock_incref(device->updateStateBlock);
5601 return WINED3D_OK;
5605 void device_invalidate_state(const struct wined3d_device *device, DWORD state)
5607 DWORD rep = device->StateTable[state].representative;
5608 struct wined3d_context *context;
5609 DWORD idx;
5610 BYTE shift;
5611 UINT i;
5613 for (i = 0; i < device->context_count; ++i)
5615 context = device->contexts[i];
5616 if(isStateDirty(context, rep)) continue;
5618 context->dirtyArray[context->numDirtyEntries++] = rep;
5619 idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
5620 shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
5621 context->isStateDirty[idx] |= (1 << shift);
5625 void get_drawable_size_fbo(const struct wined3d_context *context, UINT *width, UINT *height)
5627 /* The drawable size of a fbo target is the opengl texture size, which is the power of two size. */
5628 *width = context->current_rt->pow2Width;
5629 *height = context->current_rt->pow2Height;
5632 void get_drawable_size_backbuffer(const struct wined3d_context *context, UINT *width, UINT *height)
5634 const struct wined3d_swapchain *swapchain = context->swapchain;
5635 /* The drawable size of a backbuffer / aux buffer offscreen target is the size of the
5636 * current context's drawable, which is the size of the back buffer of the swapchain
5637 * the active context belongs to. */
5638 *width = swapchain->desc.backbuffer_width;
5639 *height = swapchain->desc.backbuffer_height;
5642 LRESULT device_process_message(struct wined3d_device *device, HWND window, BOOL unicode,
5643 UINT message, WPARAM wparam, LPARAM lparam, WNDPROC proc)
5645 if (device->filter_messages)
5647 TRACE("Filtering message: window %p, message %#x, wparam %#lx, lparam %#lx.\n",
5648 window, message, wparam, lparam);
5649 if (unicode)
5650 return DefWindowProcW(window, message, wparam, lparam);
5651 else
5652 return DefWindowProcA(window, message, wparam, lparam);
5655 if (message == WM_DESTROY)
5657 TRACE("unregister window %p.\n", window);
5658 wined3d_unregister_window(window);
5660 if (InterlockedCompareExchangePointer((void **)&device->focus_window, NULL, window) != window)
5661 ERR("Window %p is not the focus window for device %p.\n", window, device);
5663 else if (message == WM_DISPLAYCHANGE)
5665 device->device_parent->ops->mode_changed(device->device_parent);
5668 if (unicode)
5669 return CallWindowProcW(proc, window, message, wparam, lparam);
5670 else
5671 return CallWindowProcA(proc, window, message, wparam, lparam);