wined3d: Fix the VBO check in device_stream_info_from_declaration().
[wine/multimedia.git] / dlls / wined3d / device.c
blob674c528b787d9cf9be7e1dcbd87a6f9b870098ec
1 /*
2 * Copyright 2002 Lionel Ulmer
3 * Copyright 2002-2005 Jason Edmeades
4 * Copyright 2003-2004 Raphael Junqueira
5 * Copyright 2004 Christian Costa
6 * Copyright 2005 Oliver Stieber
7 * Copyright 2006-2008 Stefan Dösinger for CodeWeavers
8 * Copyright 2006-2008 Henri Verbeet
9 * Copyright 2007 Andrew Riedi
10 * Copyright 2009-2011 Henri Verbeet for CodeWeavers
12 * This library is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Lesser General Public
14 * License as published by the Free Software Foundation; either
15 * version 2.1 of the License, or (at your option) any later version.
17 * This library is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Lesser General Public License for more details.
22 * You should have received a copy of the GNU Lesser General Public
23 * License along with this library; if not, write to the Free Software
24 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
27 #include "config.h"
28 #include <stdio.h>
29 #ifdef HAVE_FLOAT_H
30 # include <float.h>
31 #endif
32 #include "wined3d_private.h"
34 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
36 /* Define the default light parameters as specified by MSDN. */
37 const struct wined3d_light WINED3D_default_light =
39 WINED3D_LIGHT_DIRECTIONAL, /* Type */
40 { 1.0f, 1.0f, 1.0f, 0.0f }, /* Diffuse r,g,b,a */
41 { 0.0f, 0.0f, 0.0f, 0.0f }, /* Specular r,g,b,a */
42 { 0.0f, 0.0f, 0.0f, 0.0f }, /* Ambient r,g,b,a, */
43 { 0.0f, 0.0f, 0.0f }, /* Position x,y,z */
44 { 0.0f, 0.0f, 1.0f }, /* Direction x,y,z */
45 0.0f, /* Range */
46 0.0f, /* Falloff */
47 0.0f, 0.0f, 0.0f, /* Attenuation 0,1,2 */
48 0.0f, /* Theta */
49 0.0f /* Phi */
52 /**********************************************************
53 * Global variable / Constants follow
54 **********************************************************/
55 const float identity[] =
57 1.0f, 0.0f, 0.0f, 0.0f,
58 0.0f, 1.0f, 0.0f, 0.0f,
59 0.0f, 0.0f, 1.0f, 0.0f,
60 0.0f, 0.0f, 0.0f, 1.0f,
61 }; /* When needed for comparisons */
63 /* Note that except for WINED3DPT_POINTLIST and WINED3DPT_LINELIST these
64 * actually have the same values in GL and D3D. */
65 static GLenum gl_primitive_type_from_d3d(enum wined3d_primitive_type primitive_type)
67 switch(primitive_type)
69 case WINED3D_PT_POINTLIST:
70 return GL_POINTS;
72 case WINED3D_PT_LINELIST:
73 return GL_LINES;
75 case WINED3D_PT_LINESTRIP:
76 return GL_LINE_STRIP;
78 case WINED3D_PT_TRIANGLELIST:
79 return GL_TRIANGLES;
81 case WINED3D_PT_TRIANGLESTRIP:
82 return GL_TRIANGLE_STRIP;
84 case WINED3D_PT_TRIANGLEFAN:
85 return GL_TRIANGLE_FAN;
87 case WINED3D_PT_LINELIST_ADJ:
88 return GL_LINES_ADJACENCY_ARB;
90 case WINED3D_PT_LINESTRIP_ADJ:
91 return GL_LINE_STRIP_ADJACENCY_ARB;
93 case WINED3D_PT_TRIANGLELIST_ADJ:
94 return GL_TRIANGLES_ADJACENCY_ARB;
96 case WINED3D_PT_TRIANGLESTRIP_ADJ:
97 return GL_TRIANGLE_STRIP_ADJACENCY_ARB;
99 default:
100 FIXME("Unhandled primitive type %s\n", debug_d3dprimitivetype(primitive_type));
101 return GL_NONE;
105 static enum wined3d_primitive_type d3d_primitive_type_from_gl(GLenum primitive_type)
107 switch(primitive_type)
109 case GL_POINTS:
110 return WINED3D_PT_POINTLIST;
112 case GL_LINES:
113 return WINED3D_PT_LINELIST;
115 case GL_LINE_STRIP:
116 return WINED3D_PT_LINESTRIP;
118 case GL_TRIANGLES:
119 return WINED3D_PT_TRIANGLELIST;
121 case GL_TRIANGLE_STRIP:
122 return WINED3D_PT_TRIANGLESTRIP;
124 case GL_TRIANGLE_FAN:
125 return WINED3D_PT_TRIANGLEFAN;
127 case GL_LINES_ADJACENCY_ARB:
128 return WINED3D_PT_LINELIST_ADJ;
130 case GL_LINE_STRIP_ADJACENCY_ARB:
131 return WINED3D_PT_LINESTRIP_ADJ;
133 case GL_TRIANGLES_ADJACENCY_ARB:
134 return WINED3D_PT_TRIANGLELIST_ADJ;
136 case GL_TRIANGLE_STRIP_ADJACENCY_ARB:
137 return WINED3D_PT_TRIANGLESTRIP_ADJ;
139 default:
140 FIXME("Unhandled primitive type %s\n", debug_d3dprimitivetype(primitive_type));
141 return WINED3D_PT_UNDEFINED;
145 static BOOL fixed_get_input(BYTE usage, BYTE usage_idx, unsigned int *regnum)
147 if ((usage == WINED3D_DECL_USAGE_POSITION || usage == WINED3D_DECL_USAGE_POSITIONT) && !usage_idx)
148 *regnum = WINED3D_FFP_POSITION;
149 else if (usage == WINED3D_DECL_USAGE_BLEND_WEIGHT && !usage_idx)
150 *regnum = WINED3D_FFP_BLENDWEIGHT;
151 else if (usage == WINED3D_DECL_USAGE_BLEND_INDICES && !usage_idx)
152 *regnum = WINED3D_FFP_BLENDINDICES;
153 else if (usage == WINED3D_DECL_USAGE_NORMAL && !usage_idx)
154 *regnum = WINED3D_FFP_NORMAL;
155 else if (usage == WINED3D_DECL_USAGE_PSIZE && !usage_idx)
156 *regnum = WINED3D_FFP_PSIZE;
157 else if (usage == WINED3D_DECL_USAGE_COLOR && !usage_idx)
158 *regnum = WINED3D_FFP_DIFFUSE;
159 else if (usage == WINED3D_DECL_USAGE_COLOR && usage_idx == 1)
160 *regnum = WINED3D_FFP_SPECULAR;
161 else if (usage == WINED3D_DECL_USAGE_TEXCOORD && usage_idx < WINED3DDP_MAXTEXCOORD)
162 *regnum = WINED3D_FFP_TEXCOORD0 + usage_idx;
163 else
165 FIXME("Unsupported input stream [usage=%s, usage_idx=%u]\n", debug_d3ddeclusage(usage), usage_idx);
166 *regnum = ~0U;
167 return FALSE;
170 return TRUE;
173 /* Context activation is done by the caller. */
174 void device_stream_info_from_declaration(struct wined3d_device *device,
175 struct wined3d_stream_info *stream_info, BOOL *all_vbo)
177 const struct wined3d_state *state = &device->stateBlock->state;
178 /* We need to deal with frequency data! */
179 struct wined3d_vertex_declaration *declaration = state->vertex_declaration;
180 BOOL use_vshader;
181 unsigned int i;
183 stream_info->use_map = 0;
184 stream_info->swizzle_map = 0;
186 /* Check for transformed vertices, disable vertex shader if present. */
187 stream_info->position_transformed = declaration->position_transformed;
188 use_vshader = state->vertex_shader && !declaration->position_transformed;
190 /* Translate the declaration into strided data. */
191 for (i = 0; i < declaration->element_count; ++i)
193 const struct wined3d_vertex_declaration_element *element = &declaration->elements[i];
194 const struct wined3d_stream_state *stream = &state->streams[element->input_slot];
195 struct wined3d_buffer *buffer = stream->buffer;
196 struct wined3d_bo_address data;
197 BOOL stride_used;
198 unsigned int idx;
199 DWORD stride;
201 TRACE("%p Element %p (%u of %u)\n", declaration->elements,
202 element, i + 1, declaration->element_count);
204 if (!buffer) continue;
206 data.buffer_object = 0;
207 data.addr = NULL;
209 stride = stream->stride;
210 if (state->user_stream)
212 TRACE("Stream %u is UP, %p\n", element->input_slot, buffer);
213 data.buffer_object = 0;
214 data.addr = (BYTE *)buffer;
216 else
218 TRACE("Stream %u isn't UP, %p\n", element->input_slot, buffer);
219 buffer_get_memory(buffer, &device->adapter->gl_info, &data);
221 /* Can't use vbo's if the base vertex index is negative. OpenGL doesn't accept negative offsets
222 * (or rather offsets bigger than the vbo, because the pointer is unsigned), so use system memory
223 * sources. In most sane cases the pointer - offset will still be > 0, otherwise it will wrap
224 * around to some big value. Hope that with the indices, the driver wraps it back internally. If
225 * not, drawStridedSlow is needed, including a vertex buffer path. */
226 if (state->load_base_vertex_index < 0)
228 WARN("load_base_vertex_index is < 0 (%d), not using VBOs.\n",
229 state->load_base_vertex_index);
230 data.buffer_object = 0;
231 data.addr = buffer_get_sysmem(buffer, &device->adapter->gl_info);
232 if ((UINT_PTR)data.addr < -state->load_base_vertex_index * stride)
234 FIXME("System memory vertex data load offset is negative!\n");
238 data.addr += element->offset;
240 TRACE("offset %u input_slot %u usage_idx %d\n", element->offset, element->input_slot, element->usage_idx);
242 if (use_vshader)
244 if (element->output_slot == ~0U)
246 /* TODO: Assuming vertexdeclarations are usually used with the
247 * same or a similar shader, it might be worth it to store the
248 * last used output slot and try that one first. */
249 stride_used = vshader_get_input(state->vertex_shader,
250 element->usage, element->usage_idx, &idx);
252 else
254 idx = element->output_slot;
255 stride_used = TRUE;
258 else
260 if (!element->ffp_valid)
262 WARN("Skipping unsupported fixed function element of format %s and usage %s\n",
263 debug_d3dformat(element->format->id), debug_d3ddeclusage(element->usage));
264 stride_used = FALSE;
266 else
268 stride_used = fixed_get_input(element->usage, element->usage_idx, &idx);
272 if (stride_used)
274 TRACE("Load %s array %u [usage %s, usage_idx %u, "
275 "input_slot %u, offset %u, stride %u, format %s, buffer_object %u]\n",
276 use_vshader ? "shader": "fixed function", idx,
277 debug_d3ddeclusage(element->usage), element->usage_idx, element->input_slot,
278 element->offset, stride, debug_d3dformat(element->format->id), data.buffer_object);
280 data.addr += stream->offset;
282 stream_info->elements[idx].format = element->format;
283 stream_info->elements[idx].data = data;
284 stream_info->elements[idx].stride = stride;
285 stream_info->elements[idx].stream_idx = element->input_slot;
287 if (!device->adapter->gl_info.supported[ARB_VERTEX_ARRAY_BGRA]
288 && element->format->id == WINED3DFMT_B8G8R8A8_UNORM)
290 stream_info->swizzle_map |= 1 << idx;
292 stream_info->use_map |= 1 << idx;
296 device->num_buffer_queries = 0;
297 if (!state->user_stream)
299 WORD map = stream_info->use_map;
300 if (all_vbo)
301 *all_vbo = TRUE;
303 /* PreLoad all the vertex buffers. */
304 for (i = 0; map; map >>= 1, ++i)
306 struct wined3d_stream_info_element *element;
307 struct wined3d_buffer *buffer;
309 if (!(map & 1)) continue;
311 element = &stream_info->elements[i];
312 buffer = state->streams[element->stream_idx].buffer;
313 wined3d_buffer_preload(buffer);
315 /* If the preload dropped the buffer object, update the stream info. */
316 if (buffer->buffer_object != element->data.buffer_object)
318 element->data.buffer_object = 0;
319 element->data.addr = buffer_get_sysmem(buffer, &device->adapter->gl_info)
320 + (ptrdiff_t)element->data.addr;
323 if (!buffer->buffer_object && all_vbo)
324 *all_vbo = FALSE;
326 if (buffer->query)
327 device->buffer_queries[device->num_buffer_queries++] = buffer->query;
330 else if (all_vbo)
332 *all_vbo = FALSE;
336 static void stream_info_element_from_strided(const struct wined3d_gl_info *gl_info,
337 const struct wined3d_strided_element *strided, struct wined3d_stream_info_element *e)
339 e->data.addr = strided->data;
340 e->data.buffer_object = 0;
341 e->format = wined3d_get_format(gl_info, strided->format);
342 e->stride = strided->stride;
343 e->stream_idx = 0;
346 static void device_stream_info_from_strided(const struct wined3d_gl_info *gl_info,
347 const struct wined3d_strided_data *strided, struct wined3d_stream_info *stream_info)
349 unsigned int i;
351 memset(stream_info, 0, sizeof(*stream_info));
353 if (strided->position.data)
354 stream_info_element_from_strided(gl_info, &strided->position, &stream_info->elements[WINED3D_FFP_POSITION]);
355 if (strided->normal.data)
356 stream_info_element_from_strided(gl_info, &strided->normal, &stream_info->elements[WINED3D_FFP_NORMAL]);
357 if (strided->diffuse.data)
358 stream_info_element_from_strided(gl_info, &strided->diffuse, &stream_info->elements[WINED3D_FFP_DIFFUSE]);
359 if (strided->specular.data)
360 stream_info_element_from_strided(gl_info, &strided->specular, &stream_info->elements[WINED3D_FFP_SPECULAR]);
362 for (i = 0; i < WINED3DDP_MAXTEXCOORD; ++i)
364 if (strided->tex_coords[i].data)
365 stream_info_element_from_strided(gl_info, &strided->tex_coords[i],
366 &stream_info->elements[WINED3D_FFP_TEXCOORD0 + i]);
369 stream_info->position_transformed = strided->position_transformed;
371 for (i = 0; i < sizeof(stream_info->elements) / sizeof(*stream_info->elements); ++i)
373 if (!stream_info->elements[i].format) continue;
375 if (!gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
376 && stream_info->elements[i].format->id == WINED3DFMT_B8G8R8A8_UNORM)
378 stream_info->swizzle_map |= 1 << i;
380 stream_info->use_map |= 1 << i;
384 static void device_trace_strided_stream_info(const struct wined3d_stream_info *stream_info)
386 TRACE("Strided Data:\n");
387 TRACE_STRIDED(stream_info, WINED3D_FFP_POSITION);
388 TRACE_STRIDED(stream_info, WINED3D_FFP_BLENDWEIGHT);
389 TRACE_STRIDED(stream_info, WINED3D_FFP_BLENDINDICES);
390 TRACE_STRIDED(stream_info, WINED3D_FFP_NORMAL);
391 TRACE_STRIDED(stream_info, WINED3D_FFP_PSIZE);
392 TRACE_STRIDED(stream_info, WINED3D_FFP_DIFFUSE);
393 TRACE_STRIDED(stream_info, WINED3D_FFP_SPECULAR);
394 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD0);
395 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD1);
396 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD2);
397 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD3);
398 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD4);
399 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD5);
400 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD6);
401 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD7);
404 /* Context activation is done by the caller. */
405 void device_update_stream_info(struct wined3d_device *device, const struct wined3d_gl_info *gl_info)
407 struct wined3d_stream_info *stream_info = &device->strided_streams;
408 const struct wined3d_state *state = &device->stateBlock->state;
409 BOOL all_vbo;
411 if (device->up_strided)
413 /* Note: this is a ddraw fixed-function code path. */
414 TRACE("=============================== Strided Input ================================\n");
415 device_stream_info_from_strided(gl_info, device->up_strided, stream_info);
416 if (TRACE_ON(d3d)) device_trace_strided_stream_info(stream_info);
417 all_vbo = FALSE;
419 else
421 TRACE("============================= Vertex Declaration =============================\n");
422 device_stream_info_from_declaration(device, stream_info, &all_vbo);
425 if (state->vertex_shader && !stream_info->position_transformed)
427 if (state->vertex_declaration->half_float_conv_needed && !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)) && !all_vbo)
445 device->useDrawStridedSlow = TRUE;
447 else
449 device->useDrawStridedSlow = FALSE;
454 static void device_preload_texture(const struct wined3d_state *state, unsigned int idx)
456 struct wined3d_texture *texture;
457 enum WINED3DSRGB srgb;
459 if (!(texture = state->textures[idx])) return;
460 srgb = state->sampler_states[idx][WINED3D_SAMP_SRGB_TEXTURE] ? SRGB_SRGB : SRGB_RGB;
461 texture->texture_ops->texture_preload(texture, srgb);
464 void device_preload_textures(const struct wined3d_device *device)
466 const struct wined3d_state *state = &device->stateBlock->state;
467 unsigned int i;
469 if (use_vs(state))
471 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
473 if (state->vertex_shader->reg_maps.sampler_type[i])
474 device_preload_texture(state, MAX_FRAGMENT_SAMPLERS + i);
478 if (use_ps(state))
480 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
482 if (state->pixel_shader->reg_maps.sampler_type[i])
483 device_preload_texture(state, i);
486 else
488 WORD ffu_map = device->fixed_function_usage_map;
490 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
492 if (ffu_map & 1)
493 device_preload_texture(state, i);
498 BOOL device_context_add(struct wined3d_device *device, struct wined3d_context *context)
500 struct wined3d_context **new_array;
502 TRACE("Adding context %p.\n", context);
504 if (!device->contexts) new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*new_array));
505 else new_array = HeapReAlloc(GetProcessHeap(), 0, device->contexts,
506 sizeof(*new_array) * (device->context_count + 1));
508 if (!new_array)
510 ERR("Failed to grow the context array.\n");
511 return FALSE;
514 new_array[device->context_count++] = context;
515 device->contexts = new_array;
516 return TRUE;
519 void device_context_remove(struct wined3d_device *device, struct wined3d_context *context)
521 struct wined3d_context **new_array;
522 BOOL found = FALSE;
523 UINT i;
525 TRACE("Removing context %p.\n", context);
527 for (i = 0; i < device->context_count; ++i)
529 if (device->contexts[i] == context)
531 found = TRUE;
532 break;
536 if (!found)
538 ERR("Context %p doesn't exist in context array.\n", context);
539 return;
542 if (!--device->context_count)
544 HeapFree(GetProcessHeap(), 0, device->contexts);
545 device->contexts = NULL;
546 return;
549 memmove(&device->contexts[i], &device->contexts[i + 1], (device->context_count - i) * sizeof(*device->contexts));
550 new_array = HeapReAlloc(GetProcessHeap(), 0, device->contexts, device->context_count * sizeof(*device->contexts));
551 if (!new_array)
553 ERR("Failed to shrink context array. Oh well.\n");
554 return;
557 device->contexts = new_array;
560 /* Do not call while under the GL lock. */
561 void device_switch_onscreen_ds(struct wined3d_device *device,
562 struct wined3d_context *context, struct wined3d_surface *depth_stencil)
564 if (device->onscreen_depth_stencil)
566 surface_load_ds_location(device->onscreen_depth_stencil, context, SFLAG_INTEXTURE);
568 surface_modify_ds_location(device->onscreen_depth_stencil, SFLAG_INTEXTURE,
569 device->onscreen_depth_stencil->ds_current_size.cx,
570 device->onscreen_depth_stencil->ds_current_size.cy);
571 wined3d_surface_decref(device->onscreen_depth_stencil);
573 device->onscreen_depth_stencil = depth_stencil;
574 wined3d_surface_incref(device->onscreen_depth_stencil);
577 static BOOL is_full_clear(const struct wined3d_surface *target, const RECT *draw_rect, const RECT *clear_rect)
579 /* partial draw rect */
580 if (draw_rect->left || draw_rect->top
581 || draw_rect->right < target->resource.width
582 || draw_rect->bottom < target->resource.height)
583 return FALSE;
585 /* partial clear rect */
586 if (clear_rect && (clear_rect->left > 0 || clear_rect->top > 0
587 || clear_rect->right < target->resource.width
588 || clear_rect->bottom < target->resource.height))
589 return FALSE;
591 return TRUE;
594 static void prepare_ds_clear(struct wined3d_surface *ds, struct wined3d_context *context,
595 DWORD location, const RECT *draw_rect, UINT rect_count, const RECT *clear_rect, RECT *out_rect)
597 RECT current_rect, r;
599 if (ds->flags & location)
600 SetRect(&current_rect, 0, 0,
601 ds->ds_current_size.cx,
602 ds->ds_current_size.cy);
603 else
604 SetRectEmpty(&current_rect);
606 IntersectRect(&r, draw_rect, &current_rect);
607 if (EqualRect(&r, draw_rect))
609 /* current_rect ⊇ draw_rect, modify only. */
610 SetRect(out_rect, 0, 0, ds->ds_current_size.cx, ds->ds_current_size.cy);
611 return;
614 if (EqualRect(&r, &current_rect))
616 /* draw_rect ⊇ current_rect, test if we're doing a full clear. */
618 if (!clear_rect)
620 /* Full clear, modify only. */
621 *out_rect = *draw_rect;
622 return;
625 IntersectRect(&r, draw_rect, clear_rect);
626 if (EqualRect(&r, draw_rect))
628 /* clear_rect ⊇ draw_rect, modify only. */
629 *out_rect = *draw_rect;
630 return;
634 /* Full load. */
635 surface_load_ds_location(ds, context, location);
636 SetRect(out_rect, 0, 0, ds->ds_current_size.cx, ds->ds_current_size.cy);
639 /* Do not call while under the GL lock. */
640 HRESULT device_clear_render_targets(struct wined3d_device *device, UINT rt_count, const struct wined3d_fb_state *fb,
641 UINT rect_count, const RECT *rects, const RECT *draw_rect, DWORD flags, const struct wined3d_color *color,
642 float depth, DWORD stencil)
644 const RECT *clear_rect = (rect_count > 0 && rects) ? (const RECT *)rects : NULL;
645 struct wined3d_surface *target = rt_count ? fb->render_targets[0] : NULL;
646 UINT drawable_width, drawable_height;
647 struct wined3d_context *context;
648 GLbitfield clear_mask = 0;
649 BOOL render_offscreen;
650 unsigned int i;
651 RECT ds_rect;
653 /* When we're clearing parts of the drawable, make sure that the target surface is well up to date in the
654 * drawable. After the clear we'll mark the drawable up to date, so we have to make sure that this is true
655 * for the cleared parts, and the untouched parts.
657 * If we're clearing the whole target there is no need to copy it into the drawable, it will be overwritten
658 * anyway. If we're not clearing the color buffer we don't have to copy either since we're not going to set
659 * the drawable up to date. We have to check all settings that limit the clear area though. Do not bother
660 * checking all this if the dest surface is in the drawable anyway. */
661 if (flags & WINED3DCLEAR_TARGET && !is_full_clear(target, draw_rect, clear_rect))
663 for (i = 0; i < rt_count; ++i)
665 struct wined3d_surface *rt = fb->render_targets[i];
666 if (rt)
667 surface_load_location(rt, rt->draw_binding, NULL);
671 context = context_acquire(device, target);
672 if (!context->valid)
674 context_release(context);
675 WARN("Invalid context, skipping clear.\n");
676 return WINED3D_OK;
679 if (target)
681 render_offscreen = context->render_offscreen;
682 target->get_drawable_size(context, &drawable_width, &drawable_height);
684 else
686 render_offscreen = TRUE;
687 drawable_width = fb->depth_stencil->pow2Width;
688 drawable_height = fb->depth_stencil->pow2Height;
691 if (flags & WINED3DCLEAR_ZBUFFER)
693 DWORD location = render_offscreen ? fb->depth_stencil->draw_binding : SFLAG_INDRAWABLE;
695 if (!render_offscreen && fb->depth_stencil != device->onscreen_depth_stencil)
696 device_switch_onscreen_ds(device, context, fb->depth_stencil);
697 prepare_ds_clear(fb->depth_stencil, context, location,
698 draw_rect, rect_count, clear_rect, &ds_rect);
701 if (!context_apply_clear_state(context, device, rt_count, fb))
703 context_release(context);
704 WARN("Failed to apply clear state, skipping clear.\n");
705 return WINED3D_OK;
708 ENTER_GL();
710 /* Only set the values up once, as they are not changing. */
711 if (flags & WINED3DCLEAR_STENCIL)
713 if (context->gl_info->supported[EXT_STENCIL_TWO_SIDE])
715 glDisable(GL_STENCIL_TEST_TWO_SIDE_EXT);
716 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_TWOSIDEDSTENCILMODE));
718 glStencilMask(~0U);
719 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_STENCILWRITEMASK));
720 glClearStencil(stencil);
721 checkGLcall("glClearStencil");
722 clear_mask = clear_mask | GL_STENCIL_BUFFER_BIT;
725 if (flags & WINED3DCLEAR_ZBUFFER)
727 DWORD location = render_offscreen ? fb->depth_stencil->draw_binding : SFLAG_INDRAWABLE;
729 surface_modify_ds_location(fb->depth_stencil, location, ds_rect.right, ds_rect.bottom);
731 glDepthMask(GL_TRUE);
732 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ZWRITEENABLE));
733 glClearDepth(depth);
734 checkGLcall("glClearDepth");
735 clear_mask = clear_mask | GL_DEPTH_BUFFER_BIT;
738 if (flags & WINED3DCLEAR_TARGET)
740 for (i = 0; i < rt_count; ++i)
742 struct wined3d_surface *rt = fb->render_targets[i];
744 if (rt)
745 surface_modify_location(rt, rt->draw_binding, TRUE);
748 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
749 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE));
750 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE1));
751 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE2));
752 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE3));
753 glClearColor(color->r, color->g, color->b, color->a);
754 checkGLcall("glClearColor");
755 clear_mask = clear_mask | GL_COLOR_BUFFER_BIT;
758 if (!clear_rect)
760 if (render_offscreen)
762 glScissor(draw_rect->left, draw_rect->top,
763 draw_rect->right - draw_rect->left, draw_rect->bottom - draw_rect->top);
765 else
767 glScissor(draw_rect->left, drawable_height - draw_rect->bottom,
768 draw_rect->right - draw_rect->left, draw_rect->bottom - draw_rect->top);
770 checkGLcall("glScissor");
771 glClear(clear_mask);
772 checkGLcall("glClear");
774 else
776 RECT current_rect;
778 /* Now process each rect in turn. */
779 for (i = 0; i < rect_count; ++i)
781 /* Note that GL uses lower left, width/height. */
782 IntersectRect(&current_rect, draw_rect, &clear_rect[i]);
784 TRACE("clear_rect[%u] %s, current_rect %s.\n", i,
785 wine_dbgstr_rect(&clear_rect[i]),
786 wine_dbgstr_rect(&current_rect));
788 /* Tests show that rectangles where x1 > x2 or y1 > y2 are ignored silently.
789 * The rectangle is not cleared, no error is returned, but further rectangles are
790 * still cleared if they are valid. */
791 if (current_rect.left > current_rect.right || current_rect.top > current_rect.bottom)
793 TRACE("Rectangle with negative dimensions, ignoring.\n");
794 continue;
797 if (render_offscreen)
799 glScissor(current_rect.left, current_rect.top,
800 current_rect.right - current_rect.left, current_rect.bottom - current_rect.top);
802 else
804 glScissor(current_rect.left, drawable_height - current_rect.bottom,
805 current_rect.right - current_rect.left, current_rect.bottom - current_rect.top);
807 checkGLcall("glScissor");
809 glClear(clear_mask);
810 checkGLcall("glClear");
814 LEAVE_GL();
816 if (wined3d_settings.strict_draw_ordering || (flags & WINED3DCLEAR_TARGET
817 && target->container.type == WINED3D_CONTAINER_SWAPCHAIN
818 && target->container.u.swapchain->front_buffer == target))
819 wglFlush(); /* Flush to ensure ordering across contexts. */
821 context_release(context);
823 return WINED3D_OK;
826 ULONG CDECL wined3d_device_incref(struct wined3d_device *device)
828 ULONG refcount = InterlockedIncrement(&device->ref);
830 TRACE("%p increasing refcount to %u.\n", device, refcount);
832 return refcount;
835 ULONG CDECL wined3d_device_decref(struct wined3d_device *device)
837 ULONG refcount = InterlockedDecrement(&device->ref);
839 TRACE("%p decreasing refcount to %u.\n", device, refcount);
841 if (!refcount)
843 struct wined3d_stateblock *stateblock;
844 UINT i;
846 if (wined3d_stateblock_decref(device->updateStateBlock)
847 && device->updateStateBlock != device->stateBlock)
848 FIXME("Something's still holding the update stateblock.\n");
849 device->updateStateBlock = NULL;
851 stateblock = device->stateBlock;
852 device->stateBlock = NULL;
853 if (wined3d_stateblock_decref(stateblock))
854 FIXME("Something's still holding the stateblock.\n");
856 for (i = 0; i < sizeof(device->multistate_funcs) / sizeof(device->multistate_funcs[0]); ++i)
858 HeapFree(GetProcessHeap(), 0, device->multistate_funcs[i]);
859 device->multistate_funcs[i] = NULL;
862 if (!list_empty(&device->resources))
864 struct wined3d_resource *resource;
866 FIXME("Device released with resources still bound, acceptable but unexpected.\n");
868 LIST_FOR_EACH_ENTRY(resource, &device->resources, struct wined3d_resource, resource_list_entry)
870 FIXME("Leftover resource %p with type %s (%#x).\n",
871 resource, debug_d3dresourcetype(resource->type), resource->type);
875 if (device->contexts)
876 ERR("Context array not freed!\n");
877 if (device->hardwareCursor)
878 DestroyCursor(device->hardwareCursor);
879 device->hardwareCursor = 0;
881 wined3d_decref(device->wined3d);
882 device->wined3d = NULL;
883 HeapFree(GetProcessHeap(), 0, device);
884 TRACE("Freed device %p.\n", device);
887 return refcount;
890 UINT CDECL wined3d_device_get_swapchain_count(const struct wined3d_device *device)
892 TRACE("device %p.\n", device);
894 return device->swapchain_count;
897 HRESULT CDECL wined3d_device_get_swapchain(const struct wined3d_device *device,
898 UINT swapchain_idx, struct wined3d_swapchain **swapchain)
900 TRACE("device %p, swapchain_idx %u, swapchain %p.\n",
901 device, swapchain_idx, swapchain);
903 if (swapchain_idx >= device->swapchain_count)
905 WARN("swapchain_idx %u >= swapchain_count %u.\n",
906 swapchain_idx, device->swapchain_count);
907 *swapchain = NULL;
909 return WINED3DERR_INVALIDCALL;
912 *swapchain = device->swapchains[swapchain_idx];
913 wined3d_swapchain_incref(*swapchain);
914 TRACE("Returning %p.\n", *swapchain);
916 return WINED3D_OK;
919 static void device_load_logo(struct wined3d_device *device, const char *filename)
921 struct wined3d_color_key color_key;
922 HBITMAP hbm;
923 BITMAP bm;
924 HRESULT hr;
925 HDC dcb = NULL, dcs = NULL;
927 hbm = LoadImageA(NULL, filename, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE | LR_CREATEDIBSECTION);
928 if(hbm)
930 GetObjectA(hbm, sizeof(BITMAP), &bm);
931 dcb = CreateCompatibleDC(NULL);
932 if(!dcb) goto out;
933 SelectObject(dcb, hbm);
935 else
937 /* Create a 32x32 white surface to indicate that wined3d is used, but the specified image
938 * couldn't be loaded
940 memset(&bm, 0, sizeof(bm));
941 bm.bmWidth = 32;
942 bm.bmHeight = 32;
945 hr = wined3d_surface_create(device, bm.bmWidth, bm.bmHeight, WINED3DFMT_B5G6R5_UNORM, 0, 0,
946 WINED3D_POOL_DEFAULT, WINED3D_MULTISAMPLE_NONE, 0, WINED3D_SURFACE_TYPE_OPENGL, WINED3D_SURFACE_MAPPABLE,
947 NULL, &wined3d_null_parent_ops, &device->logo_surface);
948 if (FAILED(hr))
950 ERR("Wine logo requested, but failed to create surface, hr %#x.\n", hr);
951 goto out;
954 if (dcb)
956 if (FAILED(hr = wined3d_surface_getdc(device->logo_surface, &dcs)))
957 goto out;
958 BitBlt(dcs, 0, 0, bm.bmWidth, bm.bmHeight, dcb, 0, 0, SRCCOPY);
959 wined3d_surface_releasedc(device->logo_surface, dcs);
961 color_key.color_space_low_value = 0;
962 color_key.color_space_high_value = 0;
963 wined3d_surface_set_color_key(device->logo_surface, WINEDDCKEY_SRCBLT, &color_key);
965 else
967 const struct wined3d_color c = {1.0f, 1.0f, 1.0f, 1.0f};
968 /* Fill the surface with a white color to show that wined3d is there */
969 wined3d_device_color_fill(device, device->logo_surface, NULL, &c);
972 out:
973 if (dcb) DeleteDC(dcb);
974 if (hbm) DeleteObject(hbm);
977 /* Context activation is done by the caller. */
978 static void create_dummy_textures(struct wined3d_device *device, struct wined3d_context *context)
980 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
981 unsigned int i, j, count;
982 /* Under DirectX you can sample even if no texture is bound, whereas
983 * OpenGL will only allow that when a valid texture is bound.
984 * We emulate this by creating dummy textures and binding them
985 * to each texture stage when the currently set D3D texture is NULL. */
986 ENTER_GL();
988 if (gl_info->supported[APPLE_CLIENT_STORAGE])
990 /* The dummy texture does not have client storage backing */
991 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE);
992 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE)");
995 count = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers);
996 for (i = 0; i < count; ++i)
998 DWORD color = 0x000000ff;
1000 /* Make appropriate texture active */
1001 context_active_texture(context, gl_info, i);
1003 glGenTextures(1, &device->dummy_texture_2d[i]);
1004 checkGLcall("glGenTextures");
1005 TRACE("Dummy 2D texture %u given name %u.\n", i, device->dummy_texture_2d[i]);
1007 glBindTexture(GL_TEXTURE_2D, device->dummy_texture_2d[i]);
1008 checkGLcall("glBindTexture");
1010 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 1, 1, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, &color);
1011 checkGLcall("glTexImage2D");
1013 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1015 glGenTextures(1, &device->dummy_texture_rect[i]);
1016 checkGLcall("glGenTextures");
1017 TRACE("Dummy rectangle texture %u given name %u.\n", i, device->dummy_texture_rect[i]);
1019 glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_texture_rect[i]);
1020 checkGLcall("glBindTexture");
1022 glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGBA8, 1, 1, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, &color);
1023 checkGLcall("glTexImage2D");
1026 if (gl_info->supported[EXT_TEXTURE3D])
1028 glGenTextures(1, &device->dummy_texture_3d[i]);
1029 checkGLcall("glGenTextures");
1030 TRACE("Dummy 3D texture %u given name %u.\n", i, device->dummy_texture_3d[i]);
1032 glBindTexture(GL_TEXTURE_3D, device->dummy_texture_3d[i]);
1033 checkGLcall("glBindTexture");
1035 GL_EXTCALL(glTexImage3DEXT(GL_TEXTURE_3D, 0, GL_RGBA8, 1, 1, 1, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, &color));
1036 checkGLcall("glTexImage3D");
1039 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1041 glGenTextures(1, &device->dummy_texture_cube[i]);
1042 checkGLcall("glGenTextures");
1043 TRACE("Dummy cube texture %u given name %u.\n", i, device->dummy_texture_cube[i]);
1045 glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_texture_cube[i]);
1046 checkGLcall("glBindTexture");
1048 for (j = GL_TEXTURE_CUBE_MAP_POSITIVE_X; j <= GL_TEXTURE_CUBE_MAP_NEGATIVE_Z; ++j)
1050 glTexImage2D(j, 0, GL_RGBA8, 1, 1, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, &color);
1051 checkGLcall("glTexImage2D");
1056 if (gl_info->supported[APPLE_CLIENT_STORAGE])
1058 /* Reenable because if supported it is enabled by default */
1059 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
1060 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
1063 LEAVE_GL();
1066 /* Context activation is done by the caller. */
1067 static void destroy_dummy_textures(struct wined3d_device *device, const struct wined3d_gl_info *gl_info)
1069 unsigned int count = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers);
1071 ENTER_GL();
1072 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1074 glDeleteTextures(count, device->dummy_texture_cube);
1075 checkGLcall("glDeleteTextures(count, device->dummy_texture_cube)");
1078 if (gl_info->supported[EXT_TEXTURE3D])
1080 glDeleteTextures(count, device->dummy_texture_3d);
1081 checkGLcall("glDeleteTextures(count, device->dummy_texture_3d)");
1084 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1086 glDeleteTextures(count, device->dummy_texture_rect);
1087 checkGLcall("glDeleteTextures(count, device->dummy_texture_rect)");
1090 glDeleteTextures(count, device->dummy_texture_2d);
1091 checkGLcall("glDeleteTextures(count, device->dummy_texture_2d)");
1092 LEAVE_GL();
1094 memset(device->dummy_texture_cube, 0, gl_info->limits.textures * sizeof(*device->dummy_texture_cube));
1095 memset(device->dummy_texture_3d, 0, gl_info->limits.textures * sizeof(*device->dummy_texture_3d));
1096 memset(device->dummy_texture_rect, 0, gl_info->limits.textures * sizeof(*device->dummy_texture_rect));
1097 memset(device->dummy_texture_2d, 0, gl_info->limits.textures * sizeof(*device->dummy_texture_2d));
1100 static LONG fullscreen_style(LONG style)
1102 /* Make sure the window is managed, otherwise we won't get keyboard input. */
1103 style |= WS_POPUP | WS_SYSMENU;
1104 style &= ~(WS_CAPTION | WS_THICKFRAME);
1106 return style;
1109 static LONG fullscreen_exstyle(LONG exstyle)
1111 /* Filter out window decorations. */
1112 exstyle &= ~(WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE);
1114 return exstyle;
1117 void CDECL wined3d_device_setup_fullscreen_window(struct wined3d_device *device, HWND window, UINT w, UINT h)
1119 BOOL filter_messages;
1120 LONG style, exstyle;
1122 TRACE("Setting up window %p for fullscreen mode.\n", window);
1124 if (device->style || device->exStyle)
1126 ERR("Changing the window style for window %p, but another style (%08x, %08x) is already stored.\n",
1127 window, device->style, device->exStyle);
1130 device->style = GetWindowLongW(window, GWL_STYLE);
1131 device->exStyle = GetWindowLongW(window, GWL_EXSTYLE);
1133 style = fullscreen_style(device->style);
1134 exstyle = fullscreen_exstyle(device->exStyle);
1136 TRACE("Old style was %08x, %08x, setting to %08x, %08x.\n",
1137 device->style, device->exStyle, style, exstyle);
1139 filter_messages = device->filter_messages;
1140 device->filter_messages = TRUE;
1142 SetWindowLongW(window, GWL_STYLE, style);
1143 SetWindowLongW(window, GWL_EXSTYLE, exstyle);
1144 SetWindowPos(window, HWND_TOP, 0, 0, w, h, SWP_FRAMECHANGED | SWP_SHOWWINDOW | SWP_NOACTIVATE);
1146 device->filter_messages = filter_messages;
1149 void CDECL wined3d_device_restore_fullscreen_window(struct wined3d_device *device, HWND window)
1151 BOOL filter_messages;
1152 LONG style, exstyle;
1154 if (!device->style && !device->exStyle) return;
1156 TRACE("Restoring window style of window %p to %08x, %08x.\n",
1157 window, device->style, device->exStyle);
1159 style = GetWindowLongW(window, GWL_STYLE);
1160 exstyle = GetWindowLongW(window, GWL_EXSTYLE);
1162 filter_messages = device->filter_messages;
1163 device->filter_messages = TRUE;
1165 /* Only restore the style if the application didn't modify it during the
1166 * fullscreen phase. Some applications change it before calling Reset()
1167 * when switching between windowed and fullscreen modes (HL2), some
1168 * depend on the original style (Eve Online). */
1169 if (style == fullscreen_style(device->style) && exstyle == fullscreen_exstyle(device->exStyle))
1171 SetWindowLongW(window, GWL_STYLE, device->style);
1172 SetWindowLongW(window, GWL_EXSTYLE, device->exStyle);
1174 SetWindowPos(window, 0, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
1176 device->filter_messages = filter_messages;
1178 /* Delete the old values. */
1179 device->style = 0;
1180 device->exStyle = 0;
1183 HRESULT CDECL wined3d_device_acquire_focus_window(struct wined3d_device *device, HWND window)
1185 TRACE("device %p, window %p.\n", device, window);
1187 if (!wined3d_register_window(window, device))
1189 ERR("Failed to register window %p.\n", window);
1190 return E_FAIL;
1193 InterlockedExchangePointer((void **)&device->focus_window, window);
1194 SetWindowPos(window, 0, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
1196 return WINED3D_OK;
1199 void CDECL wined3d_device_release_focus_window(struct wined3d_device *device)
1201 TRACE("device %p.\n", device);
1203 if (device->focus_window) wined3d_unregister_window(device->focus_window);
1204 InterlockedExchangePointer((void **)&device->focus_window, NULL);
1207 HRESULT CDECL wined3d_device_init_3d(struct wined3d_device *device,
1208 struct wined3d_swapchain_desc *swapchain_desc)
1210 static const struct wined3d_color black = {0.0f, 0.0f, 0.0f, 0.0f};
1211 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1212 struct wined3d_swapchain *swapchain = NULL;
1213 struct wined3d_context *context;
1214 HRESULT hr;
1215 DWORD state;
1216 unsigned int i;
1218 TRACE("device %p, swapchain_desc %p.\n", device, swapchain_desc);
1220 if (device->d3d_initialized)
1221 return WINED3DERR_INVALIDCALL;
1222 if (!device->adapter->opengl)
1223 return WINED3DERR_INVALIDCALL;
1225 device->valid_rt_mask = 0;
1226 for (i = 0; i < gl_info->limits.buffers; ++i)
1227 device->valid_rt_mask |= (1 << i);
1228 device->fb.render_targets = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1229 sizeof(*device->fb.render_targets) * gl_info->limits.buffers);
1231 /* Initialize the texture unit mapping to a 1:1 mapping */
1232 for (state = 0; state < MAX_COMBINED_SAMPLERS; ++state)
1234 if (state < gl_info->limits.fragment_samplers)
1236 device->texUnitMap[state] = state;
1237 device->rev_tex_unit_map[state] = state;
1239 else
1241 device->texUnitMap[state] = WINED3D_UNMAPPED_STAGE;
1242 device->rev_tex_unit_map[state] = WINED3D_UNMAPPED_STAGE;
1246 /* Setup the implicit swapchain. This also initializes a context. */
1247 TRACE("Creating implicit swapchain\n");
1248 hr = device->device_parent->ops->create_swapchain(device->device_parent,
1249 swapchain_desc, &swapchain);
1250 if (FAILED(hr))
1252 WARN("Failed to create implicit swapchain\n");
1253 goto err_out;
1256 device->swapchain_count = 1;
1257 device->swapchains = HeapAlloc(GetProcessHeap(), 0, device->swapchain_count * sizeof(*device->swapchains));
1258 if (!device->swapchains)
1260 ERR("Out of memory!\n");
1261 goto err_out;
1263 device->swapchains[0] = swapchain;
1265 if (swapchain->back_buffers && swapchain->back_buffers[0])
1267 TRACE("Setting rendertarget to %p.\n", swapchain->back_buffers);
1268 device->fb.render_targets[0] = swapchain->back_buffers[0];
1270 else
1272 TRACE("Setting rendertarget to %p.\n", swapchain->front_buffer);
1273 device->fb.render_targets[0] = swapchain->front_buffer;
1275 wined3d_surface_incref(device->fb.render_targets[0]);
1277 /* Depth Stencil support */
1278 device->fb.depth_stencil = device->auto_depth_stencil;
1279 if (device->fb.depth_stencil)
1280 wined3d_surface_incref(device->fb.depth_stencil);
1282 hr = device->shader_backend->shader_alloc_private(device);
1283 if (FAILED(hr))
1285 TRACE("Shader private data couldn't be allocated\n");
1286 goto err_out;
1288 hr = device->frag_pipe->alloc_private(device);
1289 if (FAILED(hr))
1291 TRACE("Fragment pipeline private data couldn't be allocated\n");
1292 goto err_out;
1294 hr = device->blitter->alloc_private(device);
1295 if (FAILED(hr))
1297 TRACE("Blitter private data couldn't be allocated\n");
1298 goto err_out;
1301 /* Set up some starting GL setup */
1303 /* Setup all the devices defaults */
1304 stateblock_init_default_state(device->stateBlock);
1306 context = context_acquire(device, swapchain->front_buffer);
1308 create_dummy_textures(device, context);
1310 ENTER_GL();
1312 /* Initialize the current view state */
1313 device->view_ident = 1;
1314 device->contexts[0]->last_was_rhw = 0;
1316 switch (wined3d_settings.offscreen_rendering_mode)
1318 case ORM_FBO:
1319 device->offscreenBuffer = GL_COLOR_ATTACHMENT0;
1320 break;
1322 case ORM_BACKBUFFER:
1324 if (context_get_current()->aux_buffers > 0)
1326 TRACE("Using auxiliary buffer for offscreen rendering\n");
1327 device->offscreenBuffer = GL_AUX0;
1329 else
1331 TRACE("Using back buffer for offscreen rendering\n");
1332 device->offscreenBuffer = GL_BACK;
1337 TRACE("All defaults now set up, leaving 3D init.\n");
1338 LEAVE_GL();
1340 context_release(context);
1342 /* Clear the screen */
1343 wined3d_device_clear(device, 0, NULL, WINED3DCLEAR_TARGET
1344 | (swapchain_desc->enable_auto_depth_stencil ? WINED3DCLEAR_ZBUFFER | WINED3DCLEAR_STENCIL : 0),
1345 &black, 1.0f, 0);
1347 device->d3d_initialized = TRUE;
1349 if (wined3d_settings.logo)
1350 device_load_logo(device, wined3d_settings.logo);
1351 return WINED3D_OK;
1353 err_out:
1354 HeapFree(GetProcessHeap(), 0, device->fb.render_targets);
1355 HeapFree(GetProcessHeap(), 0, device->swapchains);
1356 device->swapchain_count = 0;
1357 if (swapchain)
1358 wined3d_swapchain_decref(swapchain);
1359 if (device->blit_priv)
1360 device->blitter->free_private(device);
1361 if (device->fragment_priv)
1362 device->frag_pipe->free_private(device);
1363 if (device->shader_priv)
1364 device->shader_backend->shader_free_private(device);
1366 return hr;
1369 HRESULT CDECL wined3d_device_init_gdi(struct wined3d_device *device,
1370 struct wined3d_swapchain_desc *swapchain_desc)
1372 struct wined3d_swapchain *swapchain = NULL;
1373 HRESULT hr;
1375 TRACE("device %p, swapchain_desc %p.\n", device, swapchain_desc);
1377 /* Setup the implicit swapchain */
1378 TRACE("Creating implicit swapchain\n");
1379 hr = device->device_parent->ops->create_swapchain(device->device_parent,
1380 swapchain_desc, &swapchain);
1381 if (FAILED(hr))
1383 WARN("Failed to create implicit swapchain\n");
1384 goto err_out;
1387 device->swapchain_count = 1;
1388 device->swapchains = HeapAlloc(GetProcessHeap(), 0, device->swapchain_count * sizeof(*device->swapchains));
1389 if (!device->swapchains)
1391 ERR("Out of memory!\n");
1392 goto err_out;
1394 device->swapchains[0] = swapchain;
1395 return WINED3D_OK;
1397 err_out:
1398 wined3d_swapchain_decref(swapchain);
1399 return hr;
1402 HRESULT CDECL wined3d_device_uninit_3d(struct wined3d_device *device)
1404 struct wined3d_resource *resource, *cursor;
1405 const struct wined3d_gl_info *gl_info;
1406 struct wined3d_context *context;
1407 struct wined3d_surface *surface;
1408 UINT i;
1410 TRACE("device %p.\n", device);
1412 if (!device->d3d_initialized)
1413 return WINED3DERR_INVALIDCALL;
1415 /* Force making the context current again, to verify it is still valid
1416 * (workaround for broken drivers) */
1417 context_set_current(NULL);
1418 /* I don't think that the interface guarantees that the device is destroyed from the same thread
1419 * it was created. Thus make sure a context is active for the glDelete* calls
1421 context = context_acquire(device, NULL);
1422 gl_info = context->gl_info;
1424 if (device->logo_surface)
1425 wined3d_surface_decref(device->logo_surface);
1427 stateblock_unbind_resources(device->stateBlock);
1429 /* Unload resources */
1430 LIST_FOR_EACH_ENTRY_SAFE(resource, cursor, &device->resources, struct wined3d_resource, resource_list_entry)
1432 TRACE("Unloading resource %p.\n", resource);
1434 resource->resource_ops->resource_unload(resource);
1437 TRACE("Deleting high order patches\n");
1438 for (i = 0; i < PATCHMAP_SIZE; ++i)
1440 struct wined3d_rect_patch *patch;
1441 struct list *e1, *e2;
1443 LIST_FOR_EACH_SAFE(e1, e2, &device->patches[i])
1445 patch = LIST_ENTRY(e1, struct wined3d_rect_patch, entry);
1446 wined3d_device_delete_patch(device, patch->Handle);
1450 /* Delete the mouse cursor texture */
1451 if (device->cursorTexture)
1453 ENTER_GL();
1454 glDeleteTextures(1, &device->cursorTexture);
1455 LEAVE_GL();
1456 device->cursorTexture = 0;
1459 /* Destroy the depth blt resources, they will be invalid after the reset. Also free shader
1460 * private data, it might contain opengl pointers
1462 if (device->depth_blt_texture)
1464 ENTER_GL();
1465 glDeleteTextures(1, &device->depth_blt_texture);
1466 LEAVE_GL();
1467 device->depth_blt_texture = 0;
1470 /* Destroy the shader backend. Note that this has to happen after all shaders are destroyed. */
1471 device->blitter->free_private(device);
1472 device->frag_pipe->free_private(device);
1473 device->shader_backend->shader_free_private(device);
1475 /* Release the buffers (with sanity checks)*/
1476 if (device->onscreen_depth_stencil)
1478 surface = device->onscreen_depth_stencil;
1479 device->onscreen_depth_stencil = NULL;
1480 wined3d_surface_decref(surface);
1483 if (device->fb.depth_stencil)
1485 surface = device->fb.depth_stencil;
1487 TRACE("Releasing depth/stencil buffer %p.\n", surface);
1489 device->fb.depth_stencil = NULL;
1490 wined3d_surface_decref(surface);
1493 if (device->auto_depth_stencil)
1495 surface = device->auto_depth_stencil;
1496 device->auto_depth_stencil = NULL;
1497 if (wined3d_surface_decref(surface))
1498 FIXME("Something's still holding the auto depth stencil buffer (%p).\n", surface);
1501 for (i = 1; i < gl_info->limits.buffers; ++i)
1503 wined3d_device_set_render_target(device, i, NULL, FALSE);
1506 surface = device->fb.render_targets[0];
1507 TRACE("Setting rendertarget 0 to NULL\n");
1508 device->fb.render_targets[0] = NULL;
1509 TRACE("Releasing the render target at %p\n", surface);
1510 wined3d_surface_decref(surface);
1512 context_release(context);
1514 for (i = 0; i < device->swapchain_count; ++i)
1516 TRACE("Releasing the implicit swapchain %u.\n", i);
1517 if (wined3d_swapchain_decref(device->swapchains[i]))
1518 FIXME("Something's still holding the implicit swapchain.\n");
1521 HeapFree(GetProcessHeap(), 0, device->swapchains);
1522 device->swapchains = NULL;
1523 device->swapchain_count = 0;
1525 HeapFree(GetProcessHeap(), 0, device->fb.render_targets);
1526 device->fb.render_targets = NULL;
1528 device->d3d_initialized = FALSE;
1530 return WINED3D_OK;
1533 HRESULT CDECL wined3d_device_uninit_gdi(struct wined3d_device *device)
1535 unsigned int i;
1537 for (i = 0; i < device->swapchain_count; ++i)
1539 TRACE("Releasing the implicit swapchain %u.\n", i);
1540 if (wined3d_swapchain_decref(device->swapchains[i]))
1541 FIXME("Something's still holding the implicit swapchain.\n");
1544 HeapFree(GetProcessHeap(), 0, device->swapchains);
1545 device->swapchains = NULL;
1546 device->swapchain_count = 0;
1547 return WINED3D_OK;
1550 /* Enables thread safety in the wined3d device and its resources. Called by DirectDraw
1551 * from SetCooperativeLevel if DDSCL_MULTITHREADED is specified, and by d3d8/9 from
1552 * CreateDevice if D3DCREATE_MULTITHREADED is passed.
1554 * There is no way to deactivate thread safety once it is enabled.
1556 void CDECL wined3d_device_set_multithreaded(struct wined3d_device *device)
1558 TRACE("device %p.\n", device);
1560 /* For now just store the flag (needed in case of ddraw). */
1561 device->create_parms.flags |= WINED3DCREATE_MULTITHREADED;
1564 HRESULT CDECL wined3d_device_set_display_mode(struct wined3d_device *device,
1565 UINT swapchain_idx, const struct wined3d_display_mode *mode)
1567 struct wined3d_adapter *adapter = device->adapter;
1568 const struct wined3d_format *format = wined3d_get_format(&adapter->gl_info, mode->format_id);
1569 DEVMODEW devmode;
1570 LONG ret;
1571 RECT clip_rc;
1573 TRACE("device %p, swapchain_idx %u, mode %p (%ux%u@%u %s).\n", device, swapchain_idx, mode,
1574 mode->width, mode->height, mode->refresh_rate, debug_d3dformat(mode->format_id));
1576 /* Resize the screen even without a window:
1577 * The app could have unset it with SetCooperativeLevel, but not called
1578 * RestoreDisplayMode first. Then the release will call RestoreDisplayMode,
1579 * but we don't have any hwnd
1582 memset(&devmode, 0, sizeof(devmode));
1583 devmode.dmSize = sizeof(devmode);
1584 devmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
1585 devmode.dmBitsPerPel = format->byte_count * CHAR_BIT;
1586 devmode.dmPelsWidth = mode->width;
1587 devmode.dmPelsHeight = mode->height;
1589 devmode.dmDisplayFrequency = mode->refresh_rate;
1590 if (mode->refresh_rate)
1591 devmode.dmFields |= DM_DISPLAYFREQUENCY;
1593 /* Only change the mode if necessary */
1594 if (adapter->screen_size.cx == mode->width && adapter->screen_size.cy == mode->height
1595 && adapter->screen_format == mode->format_id && !mode->refresh_rate)
1596 return WINED3D_OK;
1598 ret = ChangeDisplaySettingsExW(NULL, &devmode, NULL, CDS_FULLSCREEN, NULL);
1599 if (ret != DISP_CHANGE_SUCCESSFUL)
1601 if (devmode.dmDisplayFrequency)
1603 WARN("ChangeDisplaySettingsExW failed, trying without the refresh rate\n");
1604 devmode.dmFields &= ~DM_DISPLAYFREQUENCY;
1605 devmode.dmDisplayFrequency = 0;
1606 ret = ChangeDisplaySettingsExW(NULL, &devmode, NULL, CDS_FULLSCREEN, NULL) != DISP_CHANGE_SUCCESSFUL;
1608 if(ret != DISP_CHANGE_SUCCESSFUL) {
1609 return WINED3DERR_NOTAVAILABLE;
1613 /* Store the new values */
1614 adapter->screen_size.cx = mode->width;
1615 adapter->screen_size.cy = mode->height;
1616 adapter->screen_format = mode->format_id;
1618 /* And finally clip mouse to our screen */
1619 SetRect(&clip_rc, 0, 0, mode->width, mode->height);
1620 ClipCursor(&clip_rc);
1622 return WINED3D_OK;
1625 HRESULT CDECL wined3d_device_get_wined3d(const struct wined3d_device *device, struct wined3d **wined3d)
1627 TRACE("device %p, wined3d %p.\n", device, wined3d);
1629 *wined3d = device->wined3d;
1630 wined3d_incref(*wined3d);
1632 TRACE("Returning %p.\n", *wined3d);
1634 return WINED3D_OK;
1637 UINT CDECL wined3d_device_get_available_texture_mem(const struct wined3d_device *device)
1639 TRACE("device %p.\n", device);
1641 TRACE("Emulating %d MB, returning %d MB left.\n",
1642 device->adapter->TextureRam / (1024 * 1024),
1643 (device->adapter->TextureRam - device->adapter->UsedTextureRam) / (1024 * 1024));
1645 return device->adapter->TextureRam - device->adapter->UsedTextureRam;
1648 HRESULT CDECL wined3d_device_set_stream_source(struct wined3d_device *device, UINT stream_idx,
1649 struct wined3d_buffer *buffer, UINT offset, UINT stride)
1651 struct wined3d_stream_state *stream;
1652 struct wined3d_buffer *prev_buffer;
1654 TRACE("device %p, stream_idx %u, buffer %p, offset %u, stride %u.\n",
1655 device, stream_idx, buffer, offset, stride);
1657 if (stream_idx >= MAX_STREAMS)
1659 WARN("Stream index %u out of range.\n", stream_idx);
1660 return WINED3DERR_INVALIDCALL;
1662 else if (offset & 0x3)
1664 WARN("Offset %u is not 4 byte aligned.\n", offset);
1665 return WINED3DERR_INVALIDCALL;
1668 stream = &device->updateStateBlock->state.streams[stream_idx];
1669 prev_buffer = stream->buffer;
1671 device->updateStateBlock->changed.streamSource |= 1 << stream_idx;
1673 if (prev_buffer == buffer
1674 && stream->stride == stride
1675 && stream->offset == offset)
1677 TRACE("Application is setting the old values over, nothing to do.\n");
1678 return WINED3D_OK;
1681 stream->buffer = buffer;
1682 if (buffer)
1684 stream->stride = stride;
1685 stream->offset = offset;
1688 /* Handle recording of state blocks. */
1689 if (device->isRecordingState)
1691 TRACE("Recording... not performing anything.\n");
1692 if (buffer)
1693 wined3d_buffer_incref(buffer);
1694 if (prev_buffer)
1695 wined3d_buffer_decref(prev_buffer);
1696 return WINED3D_OK;
1699 if (buffer)
1701 InterlockedIncrement(&buffer->bind_count);
1702 wined3d_buffer_incref(buffer);
1704 if (prev_buffer)
1706 InterlockedDecrement(&prev_buffer->bind_count);
1707 wined3d_buffer_decref(prev_buffer);
1710 device_invalidate_state(device, STATE_STREAMSRC);
1712 return WINED3D_OK;
1715 HRESULT CDECL wined3d_device_get_stream_source(const struct wined3d_device *device,
1716 UINT stream_idx, struct wined3d_buffer **buffer, UINT *offset, UINT *stride)
1718 struct wined3d_stream_state *stream;
1720 TRACE("device %p, stream_idx %u, buffer %p, offset %p, stride %p.\n",
1721 device, stream_idx, buffer, offset, stride);
1723 if (stream_idx >= MAX_STREAMS)
1725 WARN("Stream index %u out of range.\n", stream_idx);
1726 return WINED3DERR_INVALIDCALL;
1729 stream = &device->stateBlock->state.streams[stream_idx];
1730 *buffer = stream->buffer;
1731 if (*buffer)
1732 wined3d_buffer_incref(*buffer);
1733 if (offset)
1734 *offset = stream->offset;
1735 *stride = stream->stride;
1737 return WINED3D_OK;
1740 HRESULT CDECL wined3d_device_set_stream_source_freq(struct wined3d_device *device, UINT stream_idx, UINT divider)
1742 struct wined3d_stream_state *stream;
1743 UINT old_flags, old_freq;
1745 TRACE("device %p, stream_idx %u, divider %#x.\n", device, stream_idx, divider);
1747 /* Verify input. At least in d3d9 this is invalid. */
1748 if ((divider & WINED3DSTREAMSOURCE_INSTANCEDATA) && (divider & WINED3DSTREAMSOURCE_INDEXEDDATA))
1750 WARN("INSTANCEDATA and INDEXEDDATA were set, returning D3DERR_INVALIDCALL.\n");
1751 return WINED3DERR_INVALIDCALL;
1753 if ((divider & WINED3DSTREAMSOURCE_INSTANCEDATA) && !stream_idx)
1755 WARN("INSTANCEDATA used on stream 0, returning D3DERR_INVALIDCALL.\n");
1756 return WINED3DERR_INVALIDCALL;
1758 if (!divider)
1760 WARN("Divider is 0, returning D3DERR_INVALIDCALL.\n");
1761 return WINED3DERR_INVALIDCALL;
1764 stream = &device->updateStateBlock->state.streams[stream_idx];
1765 old_flags = stream->flags;
1766 old_freq = stream->frequency;
1768 stream->flags = divider & (WINED3DSTREAMSOURCE_INSTANCEDATA | WINED3DSTREAMSOURCE_INDEXEDDATA);
1769 stream->frequency = divider & 0x7fffff;
1771 device->updateStateBlock->changed.streamFreq |= 1 << stream_idx;
1773 if (stream->frequency != old_freq || stream->flags != old_flags)
1774 device_invalidate_state(device, STATE_STREAMSRC);
1776 return WINED3D_OK;
1779 HRESULT CDECL wined3d_device_get_stream_source_freq(const struct wined3d_device *device,
1780 UINT stream_idx, UINT *divider)
1782 struct wined3d_stream_state *stream;
1784 TRACE("device %p, stream_idx %u, divider %p.\n", device, stream_idx, divider);
1786 stream = &device->updateStateBlock->state.streams[stream_idx];
1787 *divider = stream->flags | stream->frequency;
1789 TRACE("Returning %#x.\n", *divider);
1791 return WINED3D_OK;
1794 HRESULT CDECL wined3d_device_set_transform(struct wined3d_device *device,
1795 enum wined3d_transform_state d3dts, const struct wined3d_matrix *matrix)
1797 TRACE("device %p, state %s, matrix %p.\n",
1798 device, debug_d3dtstype(d3dts), matrix);
1800 /* Handle recording of state blocks. */
1801 if (device->isRecordingState)
1803 TRACE("Recording... not performing anything.\n");
1804 device->updateStateBlock->changed.transform[d3dts >> 5] |= 1 << (d3dts & 0x1f);
1805 device->updateStateBlock->state.transforms[d3dts] = *matrix;
1806 return WINED3D_OK;
1809 /* If the new matrix is the same as the current one,
1810 * we cut off any further processing. this seems to be a reasonable
1811 * optimization because as was noticed, some apps (warcraft3 for example)
1812 * tend towards setting the same matrix repeatedly for some reason.
1814 * From here on we assume that the new matrix is different, wherever it matters. */
1815 if (!memcmp(&device->stateBlock->state.transforms[d3dts].u.m[0][0], matrix, sizeof(*matrix)))
1817 TRACE("The application is setting the same matrix over again.\n");
1818 return WINED3D_OK;
1821 conv_mat(matrix, &device->stateBlock->state.transforms[d3dts].u.m[0][0]);
1823 /* ScreenCoord = ProjectionMat * ViewMat * WorldMat * ObjectCoord
1824 * where ViewMat = Camera space, WorldMat = world space.
1826 * In OpenGL, camera and world space is combined into GL_MODELVIEW
1827 * matrix. The Projection matrix stay projection matrix. */
1829 if (d3dts == WINED3D_TS_VIEW)
1830 device->view_ident = !memcmp(matrix, identity, 16 * sizeof(float));
1832 if (d3dts < WINED3D_TS_WORLD_MATRIX(device->adapter->gl_info.limits.blends))
1833 device_invalidate_state(device, STATE_TRANSFORM(d3dts));
1835 return WINED3D_OK;
1839 HRESULT CDECL wined3d_device_get_transform(const struct wined3d_device *device,
1840 enum wined3d_transform_state state, struct wined3d_matrix *matrix)
1842 TRACE("device %p, state %s, matrix %p.\n", device, debug_d3dtstype(state), matrix);
1844 *matrix = device->stateBlock->state.transforms[state];
1846 return WINED3D_OK;
1849 HRESULT CDECL wined3d_device_multiply_transform(struct wined3d_device *device,
1850 enum wined3d_transform_state state, const struct wined3d_matrix *matrix)
1852 const struct wined3d_matrix *mat = NULL;
1853 struct wined3d_matrix temp;
1855 TRACE("device %p, state %s, matrix %p.\n", device, debug_d3dtstype(state), matrix);
1857 /* Note: Using 'updateStateBlock' rather than 'stateblock' in the code
1858 * below means it will be recorded in a state block change, but it
1859 * works regardless where it is recorded.
1860 * If this is found to be wrong, change to StateBlock. */
1861 if (state > HIGHEST_TRANSFORMSTATE)
1863 WARN("Unhandled transform state %#x.\n", state);
1864 return WINED3D_OK;
1867 mat = &device->updateStateBlock->state.transforms[state];
1868 multiply_matrix(&temp, mat, matrix);
1870 /* Apply change via set transform - will reapply to eg. lights this way. */
1871 return wined3d_device_set_transform(device, state, &temp);
1874 /* Note lights are real special cases. Although the device caps state only
1875 * e.g. 8 are supported, you can reference any indexes you want as long as
1876 * that number max are enabled at any one point in time. Therefore since the
1877 * indices can be anything, we need a hashmap of them. However, this causes
1878 * stateblock problems. When capturing the state block, I duplicate the
1879 * hashmap, but when recording, just build a chain pretty much of commands to
1880 * be replayed. */
1881 HRESULT CDECL wined3d_device_set_light(struct wined3d_device *device,
1882 UINT light_idx, const struct wined3d_light *light)
1884 UINT hash_idx = LIGHTMAP_HASHFUNC(light_idx);
1885 struct wined3d_light_info *object = NULL;
1886 struct list *e;
1887 float rho;
1889 TRACE("device %p, light_idx %u, light %p.\n", device, light_idx, light);
1891 /* Check the parameter range. Need for speed most wanted sets junk lights
1892 * which confuse the GL driver. */
1893 if (!light)
1894 return WINED3DERR_INVALIDCALL;
1896 switch (light->type)
1898 case WINED3D_LIGHT_POINT:
1899 case WINED3D_LIGHT_SPOT:
1900 case WINED3D_LIGHT_PARALLELPOINT:
1901 case WINED3D_LIGHT_GLSPOT:
1902 /* Incorrect attenuation values can cause the gl driver to crash.
1903 * Happens with Need for speed most wanted. */
1904 if (light->attenuation0 < 0.0f || light->attenuation1 < 0.0f || light->attenuation2 < 0.0f)
1906 WARN("Attenuation is negative, returning WINED3DERR_INVALIDCALL.\n");
1907 return WINED3DERR_INVALIDCALL;
1909 break;
1911 case WINED3D_LIGHT_DIRECTIONAL:
1912 /* Ignores attenuation */
1913 break;
1915 default:
1916 WARN("Light type out of range, returning WINED3DERR_INVALIDCALL\n");
1917 return WINED3DERR_INVALIDCALL;
1920 LIST_FOR_EACH(e, &device->updateStateBlock->state.light_map[hash_idx])
1922 object = LIST_ENTRY(e, struct wined3d_light_info, entry);
1923 if (object->OriginalIndex == light_idx)
1924 break;
1925 object = NULL;
1928 if (!object)
1930 TRACE("Adding new light\n");
1931 object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
1932 if (!object)
1934 ERR("Out of memory error when allocating a light\n");
1935 return E_OUTOFMEMORY;
1937 list_add_head(&device->updateStateBlock->state.light_map[hash_idx], &object->entry);
1938 object->glIndex = -1;
1939 object->OriginalIndex = light_idx;
1942 /* Initialize the object. */
1943 TRACE("Light %d setting to type %d, Diffuse(%f,%f,%f,%f), Specular(%f,%f,%f,%f), Ambient(%f,%f,%f,%f)\n",
1944 light_idx, light->type,
1945 light->diffuse.r, light->diffuse.g, light->diffuse.b, light->diffuse.a,
1946 light->specular.r, light->specular.g, light->specular.b, light->specular.a,
1947 light->ambient.r, light->ambient.g, light->ambient.b, light->ambient.a);
1948 TRACE("... Pos(%f,%f,%f), Dir(%f,%f,%f)\n", light->position.x, light->position.y, light->position.z,
1949 light->direction.x, light->direction.y, light->direction.z);
1950 TRACE("... Range(%f), Falloff(%f), Theta(%f), Phi(%f)\n",
1951 light->range, light->falloff, light->theta, light->phi);
1953 /* Save away the information. */
1954 object->OriginalParms = *light;
1956 switch (light->type)
1958 case WINED3D_LIGHT_POINT:
1959 /* Position */
1960 object->lightPosn[0] = light->position.x;
1961 object->lightPosn[1] = light->position.y;
1962 object->lightPosn[2] = light->position.z;
1963 object->lightPosn[3] = 1.0f;
1964 object->cutoff = 180.0f;
1965 /* FIXME: Range */
1966 break;
1968 case WINED3D_LIGHT_DIRECTIONAL:
1969 /* Direction */
1970 object->lightPosn[0] = -light->direction.x;
1971 object->lightPosn[1] = -light->direction.y;
1972 object->lightPosn[2] = -light->direction.z;
1973 object->lightPosn[3] = 0.0f;
1974 object->exponent = 0.0f;
1975 object->cutoff = 180.0f;
1976 break;
1978 case WINED3D_LIGHT_SPOT:
1979 /* Position */
1980 object->lightPosn[0] = light->position.x;
1981 object->lightPosn[1] = light->position.y;
1982 object->lightPosn[2] = light->position.z;
1983 object->lightPosn[3] = 1.0f;
1985 /* Direction */
1986 object->lightDirn[0] = light->direction.x;
1987 object->lightDirn[1] = light->direction.y;
1988 object->lightDirn[2] = light->direction.z;
1989 object->lightDirn[3] = 1.0f;
1991 /* opengl-ish and d3d-ish spot lights use too different models
1992 * for the light "intensity" as a function of the angle towards
1993 * the main light direction, so we only can approximate very
1994 * roughly. However, spot lights are rather rarely used in games
1995 * (if ever used at all). Furthermore if still used, probably
1996 * nobody pays attention to such details. */
1997 if (!light->falloff)
1999 /* Falloff = 0 is easy, because d3d's and opengl's spot light
2000 * equations have the falloff resp. exponent parameter as an
2001 * exponent, so the spot light lighting will always be 1.0 for
2002 * both of them, and we don't have to care for the rest of the
2003 * rather complex calculation. */
2004 object->exponent = 0.0f;
2006 else
2008 rho = light->theta + (light->phi - light->theta) / (2 * light->falloff);
2009 if (rho < 0.0001f)
2010 rho = 0.0001f;
2011 object->exponent = -0.3f / logf(cosf(rho / 2));
2014 if (object->exponent > 128.0f)
2015 object->exponent = 128.0f;
2017 object->cutoff = (float)(light->phi * 90 / M_PI);
2018 /* FIXME: Range */
2019 break;
2021 default:
2022 FIXME("Unrecognized light type %#x.\n", light->type);
2025 /* Update the live definitions if the light is currently assigned a glIndex. */
2026 if (object->glIndex != -1 && !device->isRecordingState)
2027 device_invalidate_state(device, STATE_ACTIVELIGHT(object->glIndex));
2029 return WINED3D_OK;
2032 HRESULT CDECL wined3d_device_get_light(const struct wined3d_device *device,
2033 UINT light_idx, struct wined3d_light *light)
2035 UINT hash_idx = LIGHTMAP_HASHFUNC(light_idx);
2036 struct wined3d_light_info *light_info = NULL;
2037 struct list *e;
2039 TRACE("device %p, light_idx %u, light %p.\n", device, light_idx, light);
2041 LIST_FOR_EACH(e, &device->stateBlock->state.light_map[hash_idx])
2043 light_info = LIST_ENTRY(e, struct wined3d_light_info, entry);
2044 if (light_info->OriginalIndex == light_idx)
2045 break;
2046 light_info = NULL;
2049 if (!light_info)
2051 TRACE("Light information requested but light not defined\n");
2052 return WINED3DERR_INVALIDCALL;
2055 *light = light_info->OriginalParms;
2056 return WINED3D_OK;
2059 HRESULT CDECL wined3d_device_set_light_enable(struct wined3d_device *device, UINT light_idx, BOOL enable)
2061 UINT hash_idx = LIGHTMAP_HASHFUNC(light_idx);
2062 struct wined3d_light_info *light_info = NULL;
2063 struct list *e;
2065 TRACE("device %p, light_idx %u, enable %#x.\n", device, light_idx, enable);
2067 LIST_FOR_EACH(e, &device->updateStateBlock->state.light_map[hash_idx])
2069 light_info = LIST_ENTRY(e, struct wined3d_light_info, entry);
2070 if (light_info->OriginalIndex == light_idx)
2071 break;
2072 light_info = NULL;
2074 TRACE("Found light %p.\n", light_info);
2076 /* Special case - enabling an undefined light creates one with a strict set of parameters. */
2077 if (!light_info)
2079 TRACE("Light enabled requested but light not defined, so defining one!\n");
2080 wined3d_device_set_light(device, light_idx, &WINED3D_default_light);
2082 /* Search for it again! Should be fairly quick as near head of list. */
2083 LIST_FOR_EACH(e, &device->updateStateBlock->state.light_map[hash_idx])
2085 light_info = LIST_ENTRY(e, struct wined3d_light_info, entry);
2086 if (light_info->OriginalIndex == light_idx)
2087 break;
2088 light_info = NULL;
2090 if (!light_info)
2092 FIXME("Adding default lights has failed dismally\n");
2093 return WINED3DERR_INVALIDCALL;
2097 if (!enable)
2099 if (light_info->glIndex != -1)
2101 if (!device->isRecordingState)
2102 device_invalidate_state(device, STATE_ACTIVELIGHT(light_info->glIndex));
2104 device->updateStateBlock->state.lights[light_info->glIndex] = NULL;
2105 light_info->glIndex = -1;
2107 else
2109 TRACE("Light already disabled, nothing to do\n");
2111 light_info->enabled = FALSE;
2113 else
2115 light_info->enabled = TRUE;
2116 if (light_info->glIndex != -1)
2118 TRACE("Nothing to do as light was enabled\n");
2120 else
2122 unsigned int i;
2123 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
2124 /* Find a free GL light. */
2125 for (i = 0; i < gl_info->limits.lights; ++i)
2127 if (!device->updateStateBlock->state.lights[i])
2129 device->updateStateBlock->state.lights[i] = light_info;
2130 light_info->glIndex = i;
2131 break;
2134 if (light_info->glIndex == -1)
2136 /* Our tests show that Windows returns D3D_OK in this situation, even with
2137 * D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_PUREDEVICE devices. This
2138 * is consistent among ddraw, d3d8 and d3d9. GetLightEnable returns TRUE
2139 * as well for those lights.
2141 * TODO: Test how this affects rendering. */
2142 WARN("Too many concurrently active lights\n");
2143 return WINED3D_OK;
2146 /* i == light_info->glIndex */
2147 if (!device->isRecordingState)
2148 device_invalidate_state(device, STATE_ACTIVELIGHT(i));
2152 return WINED3D_OK;
2155 HRESULT CDECL wined3d_device_get_light_enable(const struct wined3d_device *device, UINT light_idx, BOOL *enable)
2157 UINT hash_idx = LIGHTMAP_HASHFUNC(light_idx);
2158 struct wined3d_light_info *light_info = NULL;
2159 struct list *e;
2161 TRACE("device %p, light_idx %u, enable %p.\n", device, light_idx, enable);
2163 LIST_FOR_EACH(e, &device->stateBlock->state.light_map[hash_idx])
2165 light_info = LIST_ENTRY(e, struct wined3d_light_info, entry);
2166 if (light_info->OriginalIndex == light_idx)
2167 break;
2168 light_info = NULL;
2171 if (!light_info)
2173 TRACE("Light enabled state requested but light not defined.\n");
2174 return WINED3DERR_INVALIDCALL;
2176 /* true is 128 according to SetLightEnable */
2177 *enable = light_info->enabled ? 128 : 0;
2178 return WINED3D_OK;
2181 HRESULT CDECL wined3d_device_set_clip_plane(struct wined3d_device *device, UINT plane_idx, const float *plane)
2183 TRACE("device %p, plane_idx %u, plane %p.\n", device, plane_idx, plane);
2185 /* Validate plane_idx. */
2186 if (plane_idx >= device->adapter->gl_info.limits.clipplanes)
2188 TRACE("Application has requested clipplane this device doesn't support.\n");
2189 return WINED3DERR_INVALIDCALL;
2192 device->updateStateBlock->changed.clipplane |= 1 << plane_idx;
2194 if (device->updateStateBlock->state.clip_planes[plane_idx][0] == plane[0]
2195 && device->updateStateBlock->state.clip_planes[plane_idx][1] == plane[1]
2196 && device->updateStateBlock->state.clip_planes[plane_idx][2] == plane[2]
2197 && device->updateStateBlock->state.clip_planes[plane_idx][3] == plane[3])
2199 TRACE("Application is setting old values over, nothing to do.\n");
2200 return WINED3D_OK;
2203 device->updateStateBlock->state.clip_planes[plane_idx][0] = plane[0];
2204 device->updateStateBlock->state.clip_planes[plane_idx][1] = plane[1];
2205 device->updateStateBlock->state.clip_planes[plane_idx][2] = plane[2];
2206 device->updateStateBlock->state.clip_planes[plane_idx][3] = plane[3];
2208 /* Handle recording of state blocks. */
2209 if (device->isRecordingState)
2211 TRACE("Recording... not performing anything.\n");
2212 return WINED3D_OK;
2215 device_invalidate_state(device, STATE_CLIPPLANE(plane_idx));
2217 return WINED3D_OK;
2220 HRESULT CDECL wined3d_device_get_clip_plane(const struct wined3d_device *device, UINT plane_idx, float *plane)
2222 TRACE("device %p, plane_idx %u, plane %p.\n", device, plane_idx, plane);
2224 /* Validate plane_idx. */
2225 if (plane_idx >= device->adapter->gl_info.limits.clipplanes)
2227 TRACE("Application has requested clipplane this device doesn't support.\n");
2228 return WINED3DERR_INVALIDCALL;
2231 plane[0] = (float)device->stateBlock->state.clip_planes[plane_idx][0];
2232 plane[1] = (float)device->stateBlock->state.clip_planes[plane_idx][1];
2233 plane[2] = (float)device->stateBlock->state.clip_planes[plane_idx][2];
2234 plane[3] = (float)device->stateBlock->state.clip_planes[plane_idx][3];
2236 return WINED3D_OK;
2239 HRESULT CDECL wined3d_device_set_clip_status(struct wined3d_device *device,
2240 const struct wined3d_clip_status *clip_status)
2242 FIXME("device %p, clip_status %p stub!\n", device, clip_status);
2244 if (!clip_status)
2245 return WINED3DERR_INVALIDCALL;
2247 return WINED3D_OK;
2250 HRESULT CDECL wined3d_device_get_clip_status(const struct wined3d_device *device,
2251 struct wined3d_clip_status *clip_status)
2253 FIXME("device %p, clip_status %p stub!\n", device, clip_status);
2255 if (!clip_status)
2256 return WINED3DERR_INVALIDCALL;
2258 return WINED3D_OK;
2261 HRESULT CDECL wined3d_device_set_material(struct wined3d_device *device, const struct wined3d_material *material)
2263 TRACE("device %p, material %p.\n", device, material);
2265 device->updateStateBlock->changed.material = TRUE;
2266 device->updateStateBlock->state.material = *material;
2268 /* Handle recording of state blocks */
2269 if (device->isRecordingState)
2271 TRACE("Recording... not performing anything.\n");
2272 return WINED3D_OK;
2275 device_invalidate_state(device, STATE_MATERIAL);
2277 return WINED3D_OK;
2280 HRESULT CDECL wined3d_device_get_material(const struct wined3d_device *device, struct wined3d_material *material)
2282 TRACE("device %p, material %p.\n", device, material);
2284 *material = device->updateStateBlock->state.material;
2286 TRACE("diffuse {%.8e, %.8e, %.8e, %.8e}\n",
2287 material->diffuse.r, material->diffuse.g,
2288 material->diffuse.b, material->diffuse.a);
2289 TRACE("ambient {%.8e, %.8e, %.8e, %.8e}\n",
2290 material->ambient.r, material->ambient.g,
2291 material->ambient.b, material->ambient.a);
2292 TRACE("specular {%.8e, %.8e, %.8e, %.8e}\n",
2293 material->specular.r, material->specular.g,
2294 material->specular.b, material->specular.a);
2295 TRACE("emissive {%.8e, %.8e, %.8e, %.8e}\n",
2296 material->emissive.r, material->emissive.g,
2297 material->emissive.b, material->emissive.a);
2298 TRACE("power %.8e.\n", material->power);
2300 return WINED3D_OK;
2303 HRESULT CDECL wined3d_device_set_index_buffer(struct wined3d_device *device,
2304 struct wined3d_buffer *buffer, enum wined3d_format_id format_id)
2306 struct wined3d_buffer *prev_buffer;
2308 TRACE("device %p, buffer %p, format %s.\n",
2309 device, buffer, debug_d3dformat(format_id));
2311 prev_buffer = device->updateStateBlock->state.index_buffer;
2313 device->updateStateBlock->changed.indices = TRUE;
2314 device->updateStateBlock->state.index_buffer = buffer;
2315 device->updateStateBlock->state.index_format = format_id;
2317 /* Handle recording of state blocks. */
2318 if (device->isRecordingState)
2320 TRACE("Recording... not performing anything.\n");
2321 if (buffer)
2322 wined3d_buffer_incref(buffer);
2323 if (prev_buffer)
2324 wined3d_buffer_decref(prev_buffer);
2325 return WINED3D_OK;
2328 if (prev_buffer != buffer)
2330 device_invalidate_state(device, STATE_INDEXBUFFER);
2331 if (buffer)
2333 InterlockedIncrement(&buffer->bind_count);
2334 wined3d_buffer_incref(buffer);
2336 if (prev_buffer)
2338 InterlockedDecrement(&prev_buffer->bind_count);
2339 wined3d_buffer_decref(prev_buffer);
2343 return WINED3D_OK;
2346 HRESULT CDECL wined3d_device_get_index_buffer(const struct wined3d_device *device, struct wined3d_buffer **buffer)
2348 TRACE("device %p, buffer %p.\n", device, buffer);
2350 *buffer = device->stateBlock->state.index_buffer;
2352 if (*buffer)
2353 wined3d_buffer_incref(*buffer);
2355 TRACE("Returning %p.\n", *buffer);
2357 return WINED3D_OK;
2360 /* Method to offer d3d9 a simple way to set the base vertex index without messing with the index buffer */
2361 HRESULT CDECL wined3d_device_set_base_vertex_index(struct wined3d_device *device, INT base_index)
2363 TRACE("device %p, base_index %d.\n", device, base_index);
2365 if (device->updateStateBlock->state.base_vertex_index == base_index)
2367 TRACE("Application is setting the old value over, nothing to do\n");
2368 return WINED3D_OK;
2371 device->updateStateBlock->state.base_vertex_index = base_index;
2373 if (device->isRecordingState)
2375 TRACE("Recording... not performing anything\n");
2376 return WINED3D_OK;
2378 return WINED3D_OK;
2381 INT CDECL wined3d_device_get_base_vertex_index(const struct wined3d_device *device)
2383 TRACE("device %p.\n", device);
2385 return device->stateBlock->state.base_vertex_index;
2388 HRESULT CDECL wined3d_device_set_viewport(struct wined3d_device *device, const struct wined3d_viewport *viewport)
2390 TRACE("device %p, viewport %p.\n", device, viewport);
2391 TRACE("x %u, y %u, w %u, h %u, min_z %.8e, max_z %.8e.\n",
2392 viewport->x, viewport->y, viewport->width, viewport->height, viewport->min_z, viewport->max_z);
2394 device->updateStateBlock->changed.viewport = TRUE;
2395 device->updateStateBlock->state.viewport = *viewport;
2397 /* Handle recording of state blocks */
2398 if (device->isRecordingState)
2400 TRACE("Recording... not performing anything\n");
2401 return WINED3D_OK;
2404 device_invalidate_state(device, STATE_VIEWPORT);
2406 return WINED3D_OK;
2409 HRESULT CDECL wined3d_device_get_viewport(const struct wined3d_device *device, struct wined3d_viewport *viewport)
2411 TRACE("device %p, viewport %p.\n", device, viewport);
2413 *viewport = device->stateBlock->state.viewport;
2415 return WINED3D_OK;
2418 HRESULT CDECL wined3d_device_set_render_state(struct wined3d_device *device,
2419 enum wined3d_render_state state, DWORD value)
2421 DWORD old_value = device->stateBlock->state.render_states[state];
2423 TRACE("device %p, state %s (%#x), value %#x.\n", device, debug_d3drenderstate(state), state, value);
2425 device->updateStateBlock->changed.renderState[state >> 5] |= 1 << (state & 0x1f);
2426 device->updateStateBlock->state.render_states[state] = value;
2428 /* Handle recording of state blocks. */
2429 if (device->isRecordingState)
2431 TRACE("Recording... not performing anything.\n");
2432 return WINED3D_OK;
2435 /* Compared here and not before the assignment to allow proper stateblock recording. */
2436 if (value == old_value)
2437 TRACE("Application is setting the old value over, nothing to do.\n");
2438 else
2439 device_invalidate_state(device, STATE_RENDER(state));
2441 return WINED3D_OK;
2444 HRESULT CDECL wined3d_device_get_render_state(const struct wined3d_device *device,
2445 enum wined3d_render_state state, DWORD *value)
2447 TRACE("device %p, state %s (%#x), value %p.\n", device, debug_d3drenderstate(state), state, value);
2449 *value = device->stateBlock->state.render_states[state];
2451 return WINED3D_OK;
2454 HRESULT CDECL wined3d_device_set_sampler_state(struct wined3d_device *device,
2455 UINT sampler_idx, enum wined3d_sampler_state state, DWORD value)
2457 DWORD old_value;
2459 TRACE("device %p, sampler_idx %u, state %s, value %#x.\n",
2460 device, sampler_idx, debug_d3dsamplerstate(state), value);
2462 if (sampler_idx >= WINED3DVERTEXTEXTURESAMPLER0 && sampler_idx <= WINED3DVERTEXTEXTURESAMPLER3)
2463 sampler_idx -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
2465 if (sampler_idx >= sizeof(device->stateBlock->state.sampler_states)
2466 / sizeof(*device->stateBlock->state.sampler_states))
2468 WARN("Invalid sampler %u.\n", sampler_idx);
2469 return WINED3D_OK; /* Windows accepts overflowing this array ... we do not. */
2472 old_value = device->stateBlock->state.sampler_states[sampler_idx][state];
2473 device->updateStateBlock->state.sampler_states[sampler_idx][state] = value;
2474 device->updateStateBlock->changed.samplerState[sampler_idx] |= 1 << state;
2476 /* Handle recording of state blocks. */
2477 if (device->isRecordingState)
2479 TRACE("Recording... not performing anything.\n");
2480 return WINED3D_OK;
2483 if (old_value == value)
2485 TRACE("Application is setting the old value over, nothing to do.\n");
2486 return WINED3D_OK;
2489 device_invalidate_state(device, STATE_SAMPLER(sampler_idx));
2491 return WINED3D_OK;
2494 HRESULT CDECL wined3d_device_get_sampler_state(const struct wined3d_device *device,
2495 UINT sampler_idx, enum wined3d_sampler_state state, DWORD *value)
2497 TRACE("device %p, sampler_idx %u, state %s, value %p.\n",
2498 device, sampler_idx, debug_d3dsamplerstate(state), value);
2500 if (sampler_idx >= WINED3DVERTEXTEXTURESAMPLER0 && sampler_idx <= WINED3DVERTEXTEXTURESAMPLER3)
2501 sampler_idx -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
2503 if (sampler_idx >= sizeof(device->stateBlock->state.sampler_states)
2504 / sizeof(*device->stateBlock->state.sampler_states))
2506 WARN("Invalid sampler %u.\n", sampler_idx);
2507 return WINED3D_OK; /* Windows accepts overflowing this array ... we do not. */
2510 *value = device->stateBlock->state.sampler_states[sampler_idx][state];
2511 TRACE("Returning %#x.\n", *value);
2513 return WINED3D_OK;
2516 HRESULT CDECL wined3d_device_set_scissor_rect(struct wined3d_device *device, const RECT *rect)
2518 TRACE("device %p, rect %s.\n", device, wine_dbgstr_rect(rect));
2520 device->updateStateBlock->changed.scissorRect = TRUE;
2521 if (EqualRect(&device->updateStateBlock->state.scissor_rect, rect))
2523 TRACE("App is setting the old scissor rectangle over, nothing to do.\n");
2524 return WINED3D_OK;
2526 CopyRect(&device->updateStateBlock->state.scissor_rect, rect);
2528 if (device->isRecordingState)
2530 TRACE("Recording... not performing anything.\n");
2531 return WINED3D_OK;
2534 device_invalidate_state(device, STATE_SCISSORRECT);
2536 return WINED3D_OK;
2539 HRESULT CDECL wined3d_device_get_scissor_rect(const struct wined3d_device *device, RECT *rect)
2541 TRACE("device %p, rect %p.\n", device, rect);
2543 *rect = device->updateStateBlock->state.scissor_rect;
2544 TRACE("Returning rect %s.\n", wine_dbgstr_rect(rect));
2546 return WINED3D_OK;
2549 HRESULT CDECL wined3d_device_set_vertex_declaration(struct wined3d_device *device,
2550 struct wined3d_vertex_declaration *declaration)
2552 struct wined3d_vertex_declaration *prev = device->updateStateBlock->state.vertex_declaration;
2554 TRACE("device %p, declaration %p.\n", device, declaration);
2556 if (declaration)
2557 wined3d_vertex_declaration_incref(declaration);
2558 if (prev)
2559 wined3d_vertex_declaration_decref(prev);
2561 device->updateStateBlock->state.vertex_declaration = declaration;
2562 device->updateStateBlock->changed.vertexDecl = TRUE;
2564 if (device->isRecordingState)
2566 TRACE("Recording... not performing anything.\n");
2567 return WINED3D_OK;
2569 else if (declaration == prev)
2571 /* Checked after the assignment to allow proper stateblock recording. */
2572 TRACE("Application is setting the old declaration over, nothing to do.\n");
2573 return WINED3D_OK;
2576 device_invalidate_state(device, STATE_VDECL);
2577 return WINED3D_OK;
2580 HRESULT CDECL wined3d_device_get_vertex_declaration(const struct wined3d_device *device,
2581 struct wined3d_vertex_declaration **declaration)
2583 TRACE("device %p, declaration %p.\n", device, declaration);
2585 *declaration = device->stateBlock->state.vertex_declaration;
2586 if (*declaration)
2587 wined3d_vertex_declaration_incref(*declaration);
2589 return WINED3D_OK;
2592 HRESULT CDECL wined3d_device_set_vertex_shader(struct wined3d_device *device, struct wined3d_shader *shader)
2594 struct wined3d_shader *prev = device->updateStateBlock->state.vertex_shader;
2596 TRACE("device %p, shader %p.\n", device, shader);
2598 device->updateStateBlock->state.vertex_shader = shader;
2599 device->updateStateBlock->changed.vertexShader = TRUE;
2601 if (device->isRecordingState)
2603 if (shader)
2604 wined3d_shader_incref(shader);
2605 if (prev)
2606 wined3d_shader_decref(prev);
2607 TRACE("Recording... not performing anything.\n");
2608 return WINED3D_OK;
2611 if (shader == prev)
2613 TRACE("Application is setting the old shader over, nothing to do.\n");
2614 return WINED3D_OK;
2617 if (shader)
2618 wined3d_shader_incref(shader);
2619 if (prev)
2620 wined3d_shader_decref(prev);
2622 device_invalidate_state(device, STATE_VSHADER);
2624 return WINED3D_OK;
2627 struct wined3d_shader * CDECL wined3d_device_get_vertex_shader(const struct wined3d_device *device)
2629 struct wined3d_shader *shader;
2631 TRACE("device %p.\n", device);
2633 shader = device->stateBlock->state.vertex_shader;
2634 if (shader)
2635 wined3d_shader_incref(shader);
2637 TRACE("Returning %p.\n", shader);
2638 return shader;
2641 HRESULT CDECL wined3d_device_set_vs_consts_b(struct wined3d_device *device,
2642 UINT start_register, const BOOL *constants, UINT bool_count)
2644 UINT count = min(bool_count, MAX_CONST_B - start_register);
2645 UINT i;
2647 TRACE("device %p, start_register %u, constants %p, bool_count %u.\n",
2648 device, start_register, constants, bool_count);
2650 if (!constants || start_register >= MAX_CONST_B)
2651 return WINED3DERR_INVALIDCALL;
2653 memcpy(&device->updateStateBlock->state.vs_consts_b[start_register], constants, count * sizeof(BOOL));
2654 for (i = 0; i < count; ++i)
2655 TRACE("Set BOOL constant %u to %s.\n", start_register + i, constants[i] ? "true" : "false");
2657 for (i = start_register; i < count + start_register; ++i)
2658 device->updateStateBlock->changed.vertexShaderConstantsB |= (1 << i);
2660 if (!device->isRecordingState)
2661 device_invalidate_state(device, STATE_VERTEXSHADERCONSTANT);
2663 return WINED3D_OK;
2666 HRESULT CDECL wined3d_device_get_vs_consts_b(const struct wined3d_device *device,
2667 UINT start_register, BOOL *constants, UINT bool_count)
2669 UINT count = min(bool_count, MAX_CONST_B - start_register);
2671 TRACE("device %p, start_register %u, constants %p, bool_count %u.\n",
2672 device, start_register, constants, bool_count);
2674 if (!constants || start_register >= MAX_CONST_B)
2675 return WINED3DERR_INVALIDCALL;
2677 memcpy(constants, &device->stateBlock->state.vs_consts_b[start_register], count * sizeof(BOOL));
2679 return WINED3D_OK;
2682 HRESULT CDECL wined3d_device_set_vs_consts_i(struct wined3d_device *device,
2683 UINT start_register, const int *constants, UINT vector4i_count)
2685 UINT count = min(vector4i_count, MAX_CONST_I - start_register);
2686 UINT i;
2688 TRACE("device %p, start_register %u, constants %p, vector4i_count %u.\n",
2689 device, start_register, constants, vector4i_count);
2691 if (!constants || start_register >= MAX_CONST_I)
2692 return WINED3DERR_INVALIDCALL;
2694 memcpy(&device->updateStateBlock->state.vs_consts_i[start_register * 4], constants, count * sizeof(int) * 4);
2695 for (i = 0; i < count; ++i)
2696 TRACE("Set INT constant %u to {%d, %d, %d, %d}.\n", start_register + i,
2697 constants[i * 4], constants[i * 4 + 1],
2698 constants[i * 4 + 2], constants[i * 4 + 3]);
2700 for (i = start_register; i < count + start_register; ++i)
2701 device->updateStateBlock->changed.vertexShaderConstantsI |= (1 << i);
2703 if (!device->isRecordingState)
2704 device_invalidate_state(device, STATE_VERTEXSHADERCONSTANT);
2706 return WINED3D_OK;
2709 HRESULT CDECL wined3d_device_get_vs_consts_i(const struct wined3d_device *device,
2710 UINT start_register, int *constants, UINT vector4i_count)
2712 UINT count = min(vector4i_count, MAX_CONST_I - start_register);
2714 TRACE("device %p, start_register %u, constants %p, vector4i_count %u.\n",
2715 device, start_register, constants, vector4i_count);
2717 if (!constants || start_register >= MAX_CONST_I)
2718 return WINED3DERR_INVALIDCALL;
2720 memcpy(constants, &device->stateBlock->state.vs_consts_i[start_register * 4], count * sizeof(int) * 4);
2721 return WINED3D_OK;
2724 HRESULT CDECL wined3d_device_set_vs_consts_f(struct wined3d_device *device,
2725 UINT start_register, const float *constants, UINT vector4f_count)
2727 UINT i;
2729 TRACE("device %p, start_register %u, constants %p, vector4f_count %u.\n",
2730 device, start_register, constants, vector4f_count);
2732 /* Specifically test start_register > limit to catch MAX_UINT overflows
2733 * when adding start_register + vector4f_count. */
2734 if (!constants
2735 || start_register + vector4f_count > device->d3d_vshader_constantF
2736 || start_register > device->d3d_vshader_constantF)
2737 return WINED3DERR_INVALIDCALL;
2739 memcpy(&device->updateStateBlock->state.vs_consts_f[start_register * 4],
2740 constants, vector4f_count * sizeof(float) * 4);
2741 if (TRACE_ON(d3d))
2743 for (i = 0; i < vector4f_count; ++i)
2744 TRACE("Set FLOAT constant %u to {%.8e, %.8e, %.8e, %.8e}.\n", start_register + i,
2745 constants[i * 4], constants[i * 4 + 1],
2746 constants[i * 4 + 2], constants[i * 4 + 3]);
2749 if (!device->isRecordingState)
2751 device->shader_backend->shader_update_float_vertex_constants(device, start_register, vector4f_count);
2752 device_invalidate_state(device, STATE_VERTEXSHADERCONSTANT);
2755 memset(device->updateStateBlock->changed.vertexShaderConstantsF + start_register, 1,
2756 sizeof(*device->updateStateBlock->changed.vertexShaderConstantsF) * vector4f_count);
2758 return WINED3D_OK;
2761 HRESULT CDECL wined3d_device_get_vs_consts_f(const struct wined3d_device *device,
2762 UINT start_register, float *constants, UINT vector4f_count)
2764 int count = min(vector4f_count, device->d3d_vshader_constantF - start_register);
2766 TRACE("device %p, start_register %u, constants %p, vector4f_count %u.\n",
2767 device, start_register, constants, vector4f_count);
2769 if (!constants || count < 0)
2770 return WINED3DERR_INVALIDCALL;
2772 memcpy(constants, &device->stateBlock->state.vs_consts_f[start_register * 4], count * sizeof(float) * 4);
2774 return WINED3D_OK;
2777 static void device_invalidate_texture_stage(const struct wined3d_device *device, DWORD stage)
2779 DWORD i;
2781 for (i = 0; i <= WINED3D_HIGHEST_TEXTURE_STATE; ++i)
2783 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, i));
2787 static void device_map_stage(struct wined3d_device *device, DWORD stage, DWORD unit)
2789 DWORD i = device->rev_tex_unit_map[unit];
2790 DWORD j = device->texUnitMap[stage];
2792 device->texUnitMap[stage] = unit;
2793 if (i != WINED3D_UNMAPPED_STAGE && i != stage)
2794 device->texUnitMap[i] = WINED3D_UNMAPPED_STAGE;
2796 device->rev_tex_unit_map[unit] = stage;
2797 if (j != WINED3D_UNMAPPED_STAGE && j != unit)
2798 device->rev_tex_unit_map[j] = WINED3D_UNMAPPED_STAGE;
2801 static void device_update_fixed_function_usage_map(struct wined3d_device *device)
2803 UINT i;
2805 device->fixed_function_usage_map = 0;
2806 for (i = 0; i < MAX_TEXTURES; ++i)
2808 const struct wined3d_state *state = &device->stateBlock->state;
2809 enum wined3d_texture_op color_op = state->texture_states[i][WINED3D_TSS_COLOR_OP];
2810 enum wined3d_texture_op alpha_op = state->texture_states[i][WINED3D_TSS_ALPHA_OP];
2811 DWORD color_arg1 = state->texture_states[i][WINED3D_TSS_COLOR_ARG1] & WINED3DTA_SELECTMASK;
2812 DWORD color_arg2 = state->texture_states[i][WINED3D_TSS_COLOR_ARG2] & WINED3DTA_SELECTMASK;
2813 DWORD color_arg3 = state->texture_states[i][WINED3D_TSS_COLOR_ARG0] & WINED3DTA_SELECTMASK;
2814 DWORD alpha_arg1 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG1] & WINED3DTA_SELECTMASK;
2815 DWORD alpha_arg2 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG2] & WINED3DTA_SELECTMASK;
2816 DWORD alpha_arg3 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG0] & WINED3DTA_SELECTMASK;
2818 /* Not used, and disable higher stages. */
2819 if (color_op == WINED3D_TOP_DISABLE)
2820 break;
2822 if (((color_arg1 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG2)
2823 || ((color_arg2 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG1)
2824 || ((color_arg3 == WINED3DTA_TEXTURE)
2825 && (color_op == WINED3D_TOP_MULTIPLY_ADD || color_op == WINED3D_TOP_LERP))
2826 || ((alpha_arg1 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG2)
2827 || ((alpha_arg2 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG1)
2828 || ((alpha_arg3 == WINED3DTA_TEXTURE)
2829 && (alpha_op == WINED3D_TOP_MULTIPLY_ADD || alpha_op == WINED3D_TOP_LERP)))
2830 device->fixed_function_usage_map |= (1 << i);
2832 if ((color_op == WINED3D_TOP_BUMPENVMAP || color_op == WINED3D_TOP_BUMPENVMAP_LUMINANCE)
2833 && i < MAX_TEXTURES - 1)
2834 device->fixed_function_usage_map |= (1 << (i + 1));
2838 static void device_map_fixed_function_samplers(struct wined3d_device *device, const struct wined3d_gl_info *gl_info)
2840 unsigned int i, tex;
2841 WORD ffu_map;
2843 device_update_fixed_function_usage_map(device);
2844 ffu_map = device->fixed_function_usage_map;
2846 if (device->max_ffp_textures == gl_info->limits.texture_stages
2847 || device->stateBlock->state.lowest_disabled_stage <= device->max_ffp_textures)
2849 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2851 if (!(ffu_map & 1)) continue;
2853 if (device->texUnitMap[i] != i)
2855 device_map_stage(device, i, i);
2856 device_invalidate_state(device, STATE_SAMPLER(i));
2857 device_invalidate_texture_stage(device, i);
2860 return;
2863 /* Now work out the mapping */
2864 tex = 0;
2865 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2867 if (!(ffu_map & 1)) continue;
2869 if (device->texUnitMap[i] != tex)
2871 device_map_stage(device, i, tex);
2872 device_invalidate_state(device, STATE_SAMPLER(i));
2873 device_invalidate_texture_stage(device, i);
2876 ++tex;
2880 static void device_map_psamplers(struct wined3d_device *device, const struct wined3d_gl_info *gl_info)
2882 const enum wined3d_sampler_texture_type *sampler_type =
2883 device->stateBlock->state.pixel_shader->reg_maps.sampler_type;
2884 unsigned int i;
2886 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
2888 if (sampler_type[i] && device->texUnitMap[i] != i)
2890 device_map_stage(device, i, i);
2891 device_invalidate_state(device, STATE_SAMPLER(i));
2892 if (i < gl_info->limits.texture_stages)
2893 device_invalidate_texture_stage(device, i);
2898 static BOOL device_unit_free_for_vs(const struct wined3d_device *device,
2899 const enum wined3d_sampler_texture_type *pshader_sampler_tokens,
2900 const enum wined3d_sampler_texture_type *vshader_sampler_tokens, DWORD unit)
2902 DWORD current_mapping = device->rev_tex_unit_map[unit];
2904 /* Not currently used */
2905 if (current_mapping == WINED3D_UNMAPPED_STAGE) return TRUE;
2907 if (current_mapping < MAX_FRAGMENT_SAMPLERS) {
2908 /* Used by a fragment sampler */
2910 if (!pshader_sampler_tokens) {
2911 /* No pixel shader, check fixed function */
2912 return current_mapping >= MAX_TEXTURES || !(device->fixed_function_usage_map & (1 << current_mapping));
2915 /* Pixel shader, check the shader's sampler map */
2916 return !pshader_sampler_tokens[current_mapping];
2919 /* Used by a vertex sampler */
2920 return !vshader_sampler_tokens[current_mapping - MAX_FRAGMENT_SAMPLERS];
2923 static void device_map_vsamplers(struct wined3d_device *device, BOOL ps, const struct wined3d_gl_info *gl_info)
2925 const enum wined3d_sampler_texture_type *vshader_sampler_type =
2926 device->stateBlock->state.vertex_shader->reg_maps.sampler_type;
2927 const enum wined3d_sampler_texture_type *pshader_sampler_type = NULL;
2928 int start = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers) - 1;
2929 int i;
2931 if (ps)
2933 /* Note that we only care if a sampler is sampled or not, not the sampler's specific type.
2934 * Otherwise we'd need to call shader_update_samplers() here for 1.x pixelshaders. */
2935 pshader_sampler_type = device->stateBlock->state.pixel_shader->reg_maps.sampler_type;
2938 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i) {
2939 DWORD vsampler_idx = i + MAX_FRAGMENT_SAMPLERS;
2940 if (vshader_sampler_type[i])
2942 if (device->texUnitMap[vsampler_idx] != WINED3D_UNMAPPED_STAGE)
2944 /* Already mapped somewhere */
2945 continue;
2948 while (start >= 0)
2950 if (device_unit_free_for_vs(device, pshader_sampler_type, vshader_sampler_type, start))
2952 device_map_stage(device, vsampler_idx, start);
2953 device_invalidate_state(device, STATE_SAMPLER(vsampler_idx));
2955 --start;
2956 break;
2959 --start;
2965 void device_update_tex_unit_map(struct wined3d_device *device)
2967 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
2968 const struct wined3d_state *state = &device->stateBlock->state;
2969 BOOL vs = use_vs(state);
2970 BOOL ps = use_ps(state);
2972 * Rules are:
2973 * -> Pixel shaders need a 1:1 map. In theory the shader input could be mapped too, but
2974 * that would be really messy and require shader recompilation
2975 * -> When the mapping of a stage is changed, sampler and ALL texture stage states have
2976 * to be reset. Because of that try to work with a 1:1 mapping as much as possible
2978 if (ps)
2979 device_map_psamplers(device, gl_info);
2980 else
2981 device_map_fixed_function_samplers(device, gl_info);
2983 if (vs)
2984 device_map_vsamplers(device, ps, gl_info);
2987 HRESULT CDECL wined3d_device_set_pixel_shader(struct wined3d_device *device, struct wined3d_shader *shader)
2989 struct wined3d_shader *prev = device->updateStateBlock->state.pixel_shader;
2991 TRACE("device %p, shader %p.\n", device, shader);
2993 device->updateStateBlock->state.pixel_shader = shader;
2994 device->updateStateBlock->changed.pixelShader = TRUE;
2996 if (device->isRecordingState)
2998 if (shader)
2999 wined3d_shader_incref(shader);
3000 if (prev)
3001 wined3d_shader_decref(prev);
3002 TRACE("Recording... not performing anything.\n");
3003 return WINED3D_OK;
3006 if (shader == prev)
3008 TRACE("Application is setting the old shader over, nothing to do.\n");
3009 return WINED3D_OK;
3012 if (shader)
3013 wined3d_shader_incref(shader);
3014 if (prev)
3015 wined3d_shader_decref(prev);
3017 device_invalidate_state(device, STATE_PIXELSHADER);
3019 return WINED3D_OK;
3022 struct wined3d_shader * CDECL wined3d_device_get_pixel_shader(const struct wined3d_device *device)
3024 struct wined3d_shader *shader;
3026 TRACE("device %p.\n", device);
3028 shader = device->stateBlock->state.pixel_shader;
3029 if (shader)
3030 wined3d_shader_incref(shader);
3032 TRACE("Returning %p.\n", shader);
3033 return shader;
3036 HRESULT CDECL wined3d_device_set_ps_consts_b(struct wined3d_device *device,
3037 UINT start_register, const BOOL *constants, UINT bool_count)
3039 UINT count = min(bool_count, MAX_CONST_B - start_register);
3040 UINT i;
3042 TRACE("device %p, start_register %u, constants %p, bool_count %u.\n",
3043 device, start_register, constants, bool_count);
3045 if (!constants || start_register >= MAX_CONST_B)
3046 return WINED3DERR_INVALIDCALL;
3048 memcpy(&device->updateStateBlock->state.ps_consts_b[start_register], constants, count * sizeof(BOOL));
3049 for (i = 0; i < count; ++i)
3050 TRACE("Set BOOL constant %u to %s.\n", start_register + i, constants[i] ? "true" : "false");
3052 for (i = start_register; i < count + start_register; ++i)
3053 device->updateStateBlock->changed.pixelShaderConstantsB |= (1 << i);
3055 if (!device->isRecordingState)
3056 device_invalidate_state(device, STATE_PIXELSHADERCONSTANT);
3058 return WINED3D_OK;
3061 HRESULT CDECL wined3d_device_get_ps_consts_b(const struct wined3d_device *device,
3062 UINT start_register, BOOL *constants, UINT bool_count)
3064 UINT count = min(bool_count, MAX_CONST_B - start_register);
3066 TRACE("device %p, start_register %u, constants %p, bool_count %u.\n",
3067 device, start_register, constants, bool_count);
3069 if (!constants || start_register >= MAX_CONST_B)
3070 return WINED3DERR_INVALIDCALL;
3072 memcpy(constants, &device->stateBlock->state.ps_consts_b[start_register], count * sizeof(BOOL));
3074 return WINED3D_OK;
3077 HRESULT CDECL wined3d_device_set_ps_consts_i(struct wined3d_device *device,
3078 UINT start_register, const int *constants, UINT vector4i_count)
3080 UINT count = min(vector4i_count, MAX_CONST_I - start_register);
3081 UINT i;
3083 TRACE("device %p, start_register %u, constants %p, vector4i_count %u.\n",
3084 device, start_register, constants, vector4i_count);
3086 if (!constants || start_register >= MAX_CONST_I)
3087 return WINED3DERR_INVALIDCALL;
3089 memcpy(&device->updateStateBlock->state.ps_consts_i[start_register * 4], constants, count * sizeof(int) * 4);
3090 for (i = 0; i < count; ++i)
3091 TRACE("Set INT constant %u to {%d, %d, %d, %d}.\n", start_register + i,
3092 constants[i * 4], constants[i * 4 + 1],
3093 constants[i * 4 + 2], constants[i * 4 + 3]);
3095 for (i = start_register; i < count + start_register; ++i)
3096 device->updateStateBlock->changed.pixelShaderConstantsI |= (1 << i);
3098 if (!device->isRecordingState)
3099 device_invalidate_state(device, STATE_PIXELSHADERCONSTANT);
3101 return WINED3D_OK;
3104 HRESULT CDECL wined3d_device_get_ps_consts_i(const struct wined3d_device *device,
3105 UINT start_register, int *constants, UINT vector4i_count)
3107 UINT count = min(vector4i_count, MAX_CONST_I - start_register);
3109 TRACE("device %p, start_register %u, constants %p, vector4i_count %u.\n",
3110 device, start_register, constants, vector4i_count);
3112 if (!constants || start_register >= MAX_CONST_I)
3113 return WINED3DERR_INVALIDCALL;
3115 memcpy(constants, &device->stateBlock->state.ps_consts_i[start_register * 4], count * sizeof(int) * 4);
3117 return WINED3D_OK;
3120 HRESULT CDECL wined3d_device_set_ps_consts_f(struct wined3d_device *device,
3121 UINT start_register, const float *constants, UINT vector4f_count)
3123 UINT i;
3125 TRACE("device %p, start_register %u, constants %p, vector4f_count %u.\n",
3126 device, start_register, constants, vector4f_count);
3128 /* Specifically test start_register > limit to catch MAX_UINT overflows
3129 * when adding start_register + vector4f_count. */
3130 if (!constants
3131 || start_register + vector4f_count > device->d3d_pshader_constantF
3132 || start_register > device->d3d_pshader_constantF)
3133 return WINED3DERR_INVALIDCALL;
3135 memcpy(&device->updateStateBlock->state.ps_consts_f[start_register * 4],
3136 constants, vector4f_count * sizeof(float) * 4);
3137 if (TRACE_ON(d3d))
3139 for (i = 0; i < vector4f_count; ++i)
3140 TRACE("Set FLOAT constant %u to {%.8e, %.8e, %.8e, %.8e}.\n", start_register + i,
3141 constants[i * 4], constants[i * 4 + 1],
3142 constants[i * 4 + 2], constants[i * 4 + 3]);
3145 if (!device->isRecordingState)
3147 device->shader_backend->shader_update_float_pixel_constants(device, start_register, vector4f_count);
3148 device_invalidate_state(device, STATE_PIXELSHADERCONSTANT);
3151 memset(device->updateStateBlock->changed.pixelShaderConstantsF + start_register, 1,
3152 sizeof(*device->updateStateBlock->changed.pixelShaderConstantsF) * vector4f_count);
3154 return WINED3D_OK;
3157 HRESULT CDECL wined3d_device_get_ps_consts_f(const struct wined3d_device *device,
3158 UINT start_register, float *constants, UINT vector4f_count)
3160 int count = min(vector4f_count, device->d3d_pshader_constantF - start_register);
3162 TRACE("device %p, start_register %u, constants %p, vector4f_count %u.\n",
3163 device, start_register, constants, vector4f_count);
3165 if (!constants || count < 0)
3166 return WINED3DERR_INVALIDCALL;
3168 memcpy(constants, &device->stateBlock->state.ps_consts_f[start_register * 4], count * sizeof(float) * 4);
3170 return WINED3D_OK;
3173 /* Context activation is done by the caller. */
3174 /* Do not call while under the GL lock. */
3175 #define copy_and_next(dest, src, size) memcpy(dest, src, size); dest += (size)
3176 static HRESULT process_vertices_strided(const struct wined3d_device *device, DWORD dwDestIndex, DWORD dwCount,
3177 const struct wined3d_stream_info *stream_info, struct wined3d_buffer *dest, DWORD flags,
3178 DWORD DestFVF)
3180 struct wined3d_matrix mat, proj_mat, view_mat, world_mat;
3181 struct wined3d_viewport vp;
3182 UINT vertex_size;
3183 unsigned int i;
3184 BYTE *dest_ptr;
3185 BOOL doClip;
3186 DWORD numTextures;
3187 HRESULT hr;
3189 if (stream_info->use_map & (1 << WINED3D_FFP_NORMAL))
3191 WARN(" lighting state not saved yet... Some strange stuff may happen !\n");
3194 if (!(stream_info->use_map & (1 << WINED3D_FFP_POSITION)))
3196 ERR("Source has no position mask\n");
3197 return WINED3DERR_INVALIDCALL;
3200 if (device->stateBlock->state.render_states[WINED3D_RS_CLIPPING])
3202 static BOOL warned = FALSE;
3204 * The clipping code is not quite correct. Some things need
3205 * to be checked against IDirect3DDevice3 (!), d3d8 and d3d9,
3206 * so disable clipping for now.
3207 * (The graphics in Half-Life are broken, and my processvertices
3208 * test crashes with IDirect3DDevice3)
3209 doClip = TRUE;
3211 doClip = FALSE;
3212 if(!warned) {
3213 warned = TRUE;
3214 FIXME("Clipping is broken and disabled for now\n");
3217 else
3218 doClip = FALSE;
3220 vertex_size = get_flexible_vertex_size(DestFVF);
3221 if (FAILED(hr = wined3d_buffer_map(dest, dwDestIndex * vertex_size, dwCount * vertex_size, &dest_ptr, 0)))
3223 WARN("Failed to map buffer, hr %#x.\n", hr);
3224 return hr;
3227 wined3d_device_get_transform(device, WINED3D_TS_VIEW, &view_mat);
3228 wined3d_device_get_transform(device, WINED3D_TS_PROJECTION, &proj_mat);
3229 wined3d_device_get_transform(device, WINED3D_TS_WORLD_MATRIX(0), &world_mat);
3231 TRACE("View mat:\n");
3232 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);
3233 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);
3234 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);
3235 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);
3237 TRACE("Proj mat:\n");
3238 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);
3239 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);
3240 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);
3241 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);
3243 TRACE("World mat:\n");
3244 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);
3245 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);
3246 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);
3247 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);
3249 /* Get the viewport */
3250 wined3d_device_get_viewport(device, &vp);
3251 TRACE("viewport x %u, y %u, width %u, height %u, min_z %.8e, max_z %.8e.\n",
3252 vp.x, vp.y, vp.width, vp.height, vp.min_z, vp.max_z);
3254 multiply_matrix(&mat,&view_mat,&world_mat);
3255 multiply_matrix(&mat,&proj_mat,&mat);
3257 numTextures = (DestFVF & WINED3DFVF_TEXCOUNT_MASK) >> WINED3DFVF_TEXCOUNT_SHIFT;
3259 for (i = 0; i < dwCount; i+= 1) {
3260 unsigned int tex_index;
3262 if ( ((DestFVF & WINED3DFVF_POSITION_MASK) == WINED3DFVF_XYZ ) ||
3263 ((DestFVF & WINED3DFVF_POSITION_MASK) == WINED3DFVF_XYZRHW ) ) {
3264 /* The position first */
3265 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_POSITION];
3266 const float *p = (const float *)(element->data.addr + i * element->stride);
3267 float x, y, z, rhw;
3268 TRACE("In: ( %06.2f %06.2f %06.2f )\n", p[0], p[1], p[2]);
3270 /* Multiplication with world, view and projection matrix */
3271 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);
3272 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);
3273 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);
3274 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);
3276 TRACE("x=%f y=%f z=%f rhw=%f\n", x, y, z, rhw);
3278 /* WARNING: The following things are taken from d3d7 and were not yet checked
3279 * against d3d8 or d3d9!
3282 /* Clipping conditions: From msdn
3284 * A vertex is clipped if it does not match the following requirements
3285 * -rhw < x <= rhw
3286 * -rhw < y <= rhw
3287 * 0 < z <= rhw
3288 * 0 < rhw ( Not in d3d7, but tested in d3d7)
3290 * If clipping is on is determined by the D3DVOP_CLIP flag in D3D7, and
3291 * by the D3DRS_CLIPPING in D3D9(according to the msdn, not checked)
3295 if( !doClip ||
3296 ( (-rhw -eps < x) && (-rhw -eps < y) && ( -eps < z) &&
3297 (x <= rhw + eps) && (y <= rhw + eps ) && (z <= rhw + eps) &&
3298 ( rhw > eps ) ) ) {
3300 /* "Normal" viewport transformation (not clipped)
3301 * 1) The values are divided by rhw
3302 * 2) The y axis is negative, so multiply it with -1
3303 * 3) Screen coordinates go from -(Width/2) to +(Width/2) and
3304 * -(Height/2) to +(Height/2). The z range is MinZ to MaxZ
3305 * 4) Multiply x with Width/2 and add Width/2
3306 * 5) The same for the height
3307 * 6) Add the viewpoint X and Y to the 2D coordinates and
3308 * The minimum Z value to z
3309 * 7) rhw = 1 / rhw Reciprocal of Homogeneous W....
3311 * Well, basically it's simply a linear transformation into viewport
3312 * coordinates
3315 x /= rhw;
3316 y /= rhw;
3317 z /= rhw;
3319 y *= -1;
3321 x *= vp.width / 2;
3322 y *= vp.height / 2;
3323 z *= vp.max_z - vp.min_z;
3325 x += vp.width / 2 + vp.x;
3326 y += vp.height / 2 + vp.y;
3327 z += vp.min_z;
3329 rhw = 1 / rhw;
3330 } else {
3331 /* That vertex got clipped
3332 * Contrary to OpenGL it is not dropped completely, it just
3333 * undergoes a different calculation.
3335 TRACE("Vertex got clipped\n");
3336 x += rhw;
3337 y += rhw;
3339 x /= 2;
3340 y /= 2;
3342 /* Msdn mentions that Direct3D9 keeps a list of clipped vertices
3343 * outside of the main vertex buffer memory. That needs some more
3344 * investigation...
3348 TRACE("Writing (%f %f %f) %f\n", x, y, z, rhw);
3351 ( (float *) dest_ptr)[0] = x;
3352 ( (float *) dest_ptr)[1] = y;
3353 ( (float *) dest_ptr)[2] = z;
3354 ( (float *) dest_ptr)[3] = rhw; /* SIC, see ddraw test! */
3356 dest_ptr += 3 * sizeof(float);
3358 if ((DestFVF & WINED3DFVF_POSITION_MASK) == WINED3DFVF_XYZRHW)
3359 dest_ptr += sizeof(float);
3362 if (DestFVF & WINED3DFVF_PSIZE)
3363 dest_ptr += sizeof(DWORD);
3365 if (DestFVF & WINED3DFVF_NORMAL)
3367 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_NORMAL];
3368 const float *normal = (const float *)(element->data.addr + i * element->stride);
3369 /* AFAIK this should go into the lighting information */
3370 FIXME("Didn't expect the destination to have a normal\n");
3371 copy_and_next(dest_ptr, normal, 3 * sizeof(float));
3374 if (DestFVF & WINED3DFVF_DIFFUSE)
3376 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_DIFFUSE];
3377 const DWORD *color_d = (const DWORD *)(element->data.addr + i * element->stride);
3378 if (!(stream_info->use_map & (1 << WINED3D_FFP_DIFFUSE)))
3380 static BOOL warned = FALSE;
3382 if(!warned) {
3383 ERR("No diffuse color in source, but destination has one\n");
3384 warned = TRUE;
3387 *( (DWORD *) dest_ptr) = 0xffffffff;
3388 dest_ptr += sizeof(DWORD);
3390 else
3392 copy_and_next(dest_ptr, color_d, sizeof(DWORD));
3396 if (DestFVF & WINED3DFVF_SPECULAR)
3398 /* What's the color value in the feedback buffer? */
3399 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_SPECULAR];
3400 const DWORD *color_s = (const DWORD *)(element->data.addr + i * element->stride);
3401 if (!(stream_info->use_map & (1 << WINED3D_FFP_SPECULAR)))
3403 static BOOL warned = FALSE;
3405 if(!warned) {
3406 ERR("No specular color in source, but destination has one\n");
3407 warned = TRUE;
3410 *( (DWORD *) dest_ptr) = 0xFF000000;
3411 dest_ptr += sizeof(DWORD);
3413 else
3415 copy_and_next(dest_ptr, color_s, sizeof(DWORD));
3419 for (tex_index = 0; tex_index < numTextures; ++tex_index)
3421 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_TEXCOORD0 + tex_index];
3422 const float *tex_coord = (const float *)(element->data.addr + i * element->stride);
3423 if (!(stream_info->use_map & (1 << (WINED3D_FFP_TEXCOORD0 + tex_index))))
3425 ERR("No source texture, but destination requests one\n");
3426 dest_ptr += GET_TEXCOORD_SIZE_FROM_FVF(DestFVF, tex_index) * sizeof(float);
3428 else
3430 copy_and_next(dest_ptr, tex_coord, GET_TEXCOORD_SIZE_FROM_FVF(DestFVF, tex_index) * sizeof(float));
3435 wined3d_buffer_unmap(dest);
3437 return WINED3D_OK;
3439 #undef copy_and_next
3441 /* Do not call while under the GL lock. */
3442 HRESULT CDECL wined3d_device_process_vertices(struct wined3d_device *device,
3443 UINT src_start_idx, UINT dst_idx, UINT vertex_count, struct wined3d_buffer *dst_buffer,
3444 const struct wined3d_vertex_declaration *declaration, DWORD flags, DWORD dst_fvf)
3446 struct wined3d_state *state = &device->stateBlock->state;
3447 struct wined3d_stream_info stream_info;
3448 const struct wined3d_gl_info *gl_info;
3449 BOOL streamWasUP = state->user_stream;
3450 struct wined3d_context *context;
3451 struct wined3d_shader *vs;
3452 unsigned int i;
3453 HRESULT hr;
3455 TRACE("device %p, src_start_idx %u, dst_idx %u, vertex_count %u, "
3456 "dst_buffer %p, declaration %p, flags %#x, dst_fvf %#x.\n",
3457 device, src_start_idx, dst_idx, vertex_count,
3458 dst_buffer, declaration, flags, dst_fvf);
3460 if (declaration)
3461 FIXME("Output vertex declaration not implemented yet.\n");
3463 /* Need any context to write to the vbo. */
3464 context = context_acquire(device, NULL);
3465 gl_info = context->gl_info;
3467 /* ProcessVertices reads from vertex buffers, which have to be assigned.
3468 * DrawPrimitive and DrawPrimitiveUP control the streamIsUP flag, thus
3469 * restore it afterwards. */
3470 vs = state->vertex_shader;
3471 state->vertex_shader = NULL;
3472 state->user_stream = FALSE;
3473 device_stream_info_from_declaration(device, &stream_info, NULL);
3474 state->user_stream = streamWasUP;
3475 state->vertex_shader = vs;
3477 /* We can't convert FROM a VBO, and vertex buffers used to source into
3478 * process_vertices() are unlikely to ever be used for drawing. Release
3479 * VBOs in those buffers and fix up the stream_info structure.
3481 * Also apply the start index. */
3482 for (i = 0; i < (sizeof(stream_info.elements) / sizeof(*stream_info.elements)); ++i)
3484 struct wined3d_stream_info_element *e;
3486 if (!(stream_info.use_map & (1 << i)))
3487 continue;
3489 e = &stream_info.elements[i];
3490 if (e->data.buffer_object)
3492 struct wined3d_buffer *vb = state->streams[e->stream_idx].buffer;
3493 e->data.buffer_object = 0;
3494 e->data.addr = (BYTE *)((ULONG_PTR)e->data.addr + (ULONG_PTR)buffer_get_sysmem(vb, gl_info));
3495 ENTER_GL();
3496 GL_EXTCALL(glDeleteBuffersARB(1, &vb->buffer_object));
3497 vb->buffer_object = 0;
3498 LEAVE_GL();
3500 if (e->data.addr)
3501 e->data.addr += e->stride * src_start_idx;
3504 hr = process_vertices_strided(device, dst_idx, vertex_count,
3505 &stream_info, dst_buffer, flags, dst_fvf);
3507 context_release(context);
3509 return hr;
3512 HRESULT CDECL wined3d_device_set_texture_stage_state(struct wined3d_device *device,
3513 UINT stage, enum wined3d_texture_stage_state state, DWORD value)
3515 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
3516 DWORD old_value;
3518 TRACE("device %p, stage %u, state %s, value %#x.\n",
3519 device, stage, debug_d3dtexturestate(state), value);
3521 if (state > WINED3D_HIGHEST_TEXTURE_STATE)
3523 WARN("Invalid state %#x passed.\n", state);
3524 return WINED3D_OK;
3527 if (stage >= gl_info->limits.texture_stages)
3529 WARN("Attempting to set stage %u which is higher than the max stage %u, ignoring.\n",
3530 stage, gl_info->limits.texture_stages - 1);
3531 return WINED3D_OK;
3534 old_value = device->updateStateBlock->state.texture_states[stage][state];
3535 device->updateStateBlock->changed.textureState[stage] |= 1 << state;
3536 device->updateStateBlock->state.texture_states[stage][state] = value;
3538 if (device->isRecordingState)
3540 TRACE("Recording... not performing anything.\n");
3541 return WINED3D_OK;
3544 /* Checked after the assignments to allow proper stateblock recording. */
3545 if (old_value == value)
3547 TRACE("Application is setting the old value over, nothing to do.\n");
3548 return WINED3D_OK;
3551 if (stage > device->stateBlock->state.lowest_disabled_stage
3552 && device->StateTable[STATE_TEXTURESTAGE(0, state)].representative
3553 == STATE_TEXTURESTAGE(0, WINED3D_TSS_COLOR_OP))
3555 /* Colorop change above lowest disabled stage? That won't change
3556 * anything in the GL setup. Changes in other states are important on
3557 * disabled stages too. */
3558 return WINED3D_OK;
3561 if (state == WINED3D_TSS_COLOR_OP)
3563 unsigned int i;
3565 if (value == WINED3D_TOP_DISABLE && old_value != WINED3D_TOP_DISABLE)
3567 /* Previously enabled stage disabled now. Make sure to dirtify
3568 * all enabled stages above stage, they have to be disabled.
3570 * The current stage is dirtified below. */
3571 for (i = stage + 1; i < device->stateBlock->state.lowest_disabled_stage; ++i)
3573 TRACE("Additionally dirtifying stage %u.\n", i);
3574 device_invalidate_state(device, STATE_TEXTURESTAGE(i, WINED3D_TSS_COLOR_OP));
3576 device->stateBlock->state.lowest_disabled_stage = stage;
3577 TRACE("New lowest disabled: %u.\n", stage);
3579 else if (value != WINED3D_TOP_DISABLE && old_value == WINED3D_TOP_DISABLE)
3581 /* Previously disabled stage enabled. Stages above it may need
3582 * enabling. Stage must be lowest_disabled_stage here, if it's
3583 * bigger success is returned above, and stages below the lowest
3584 * disabled stage can't be enabled (because they are enabled
3585 * already).
3587 * Again stage stage doesn't need to be dirtified here, it is
3588 * handled below. */
3589 for (i = stage + 1; i < gl_info->limits.texture_stages; ++i)
3591 if (device->updateStateBlock->state.texture_states[i][WINED3D_TSS_COLOR_OP] == WINED3D_TOP_DISABLE)
3592 break;
3593 TRACE("Additionally dirtifying stage %u due to enable.\n", i);
3594 device_invalidate_state(device, STATE_TEXTURESTAGE(i, WINED3D_TSS_COLOR_OP));
3596 device->stateBlock->state.lowest_disabled_stage = i;
3597 TRACE("New lowest disabled: %u.\n", i);
3601 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, state));
3603 return WINED3D_OK;
3606 HRESULT CDECL wined3d_device_get_texture_stage_state(const struct wined3d_device *device,
3607 UINT stage, enum wined3d_texture_stage_state state, DWORD *value)
3609 TRACE("device %p, stage %u, state %s, value %p.\n",
3610 device, stage, debug_d3dtexturestate(state), value);
3612 if (state > WINED3D_HIGHEST_TEXTURE_STATE)
3614 WARN("Invalid state %#x passed.\n", state);
3615 return WINED3D_OK;
3618 *value = device->updateStateBlock->state.texture_states[stage][state];
3619 TRACE("Returning %#x.\n", *value);
3621 return WINED3D_OK;
3624 HRESULT CDECL wined3d_device_set_texture(struct wined3d_device *device,
3625 UINT stage, struct wined3d_texture *texture)
3627 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
3628 struct wined3d_texture *prev;
3630 TRACE("device %p, stage %u, texture %p.\n", device, stage, texture);
3632 if (stage >= WINED3DVERTEXTEXTURESAMPLER0 && stage <= WINED3DVERTEXTEXTURESAMPLER3)
3633 stage -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
3635 /* Windows accepts overflowing this array... we do not. */
3636 if (stage >= sizeof(device->stateBlock->state.textures) / sizeof(*device->stateBlock->state.textures))
3638 WARN("Ignoring invalid stage %u.\n", stage);
3639 return WINED3D_OK;
3642 if (texture && texture->resource.pool == WINED3D_POOL_SCRATCH)
3644 WARN("Rejecting attempt to set scratch texture.\n");
3645 return WINED3DERR_INVALIDCALL;
3648 device->updateStateBlock->changed.textures |= 1 << stage;
3650 prev = device->updateStateBlock->state.textures[stage];
3651 TRACE("Previous texture %p.\n", prev);
3653 if (texture == prev)
3655 TRACE("App is setting the same texture again, nothing to do.\n");
3656 return WINED3D_OK;
3659 TRACE("Setting new texture to %p.\n", texture);
3660 device->updateStateBlock->state.textures[stage] = texture;
3662 if (device->isRecordingState)
3664 TRACE("Recording... not performing anything\n");
3666 if (texture) wined3d_texture_incref(texture);
3667 if (prev) wined3d_texture_decref(prev);
3669 return WINED3D_OK;
3672 if (texture)
3674 LONG bind_count = InterlockedIncrement(&texture->bind_count);
3676 wined3d_texture_incref(texture);
3678 if (!prev || texture->target != prev->target)
3679 device_invalidate_state(device, STATE_PIXELSHADER);
3681 if (!prev && stage < gl_info->limits.texture_stages)
3683 /* The source arguments for color and alpha ops have different
3684 * meanings when a NULL texture is bound, so the COLOR_OP and
3685 * ALPHA_OP have to be dirtified. */
3686 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, WINED3D_TSS_COLOR_OP));
3687 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, WINED3D_TSS_ALPHA_OP));
3690 if (bind_count == 1)
3691 texture->sampler = stage;
3694 if (prev)
3696 LONG bind_count = InterlockedDecrement(&prev->bind_count);
3698 wined3d_texture_decref(prev);
3700 if (!texture && stage < gl_info->limits.texture_stages)
3702 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, WINED3D_TSS_COLOR_OP));
3703 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, WINED3D_TSS_ALPHA_OP));
3706 if (bind_count && prev->sampler == stage)
3708 unsigned int i;
3710 /* Search for other stages the texture is bound to. Shouldn't
3711 * happen if applications bind textures to a single stage only. */
3712 TRACE("Searching for other stages the texture is bound to.\n");
3713 for (i = 0; i < MAX_COMBINED_SAMPLERS; ++i)
3715 if (device->updateStateBlock->state.textures[i] == prev)
3717 TRACE("Texture is also bound to stage %u.\n", i);
3718 prev->sampler = i;
3719 break;
3725 device_invalidate_state(device, STATE_SAMPLER(stage));
3727 return WINED3D_OK;
3730 HRESULT CDECL wined3d_device_get_texture(const struct wined3d_device *device,
3731 UINT stage, struct wined3d_texture **texture)
3733 TRACE("device %p, stage %u, texture %p.\n", device, stage, texture);
3735 if (stage >= WINED3DVERTEXTEXTURESAMPLER0 && stage <= WINED3DVERTEXTEXTURESAMPLER3)
3736 stage -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
3738 if (stage >= sizeof(device->stateBlock->state.textures) / sizeof(*device->stateBlock->state.textures))
3740 WARN("Ignoring invalid stage %u.\n", stage);
3741 return WINED3D_OK; /* Windows accepts overflowing this array ... we do not. */
3744 *texture = device->stateBlock->state.textures[stage];
3745 if (*texture)
3746 wined3d_texture_incref(*texture);
3748 TRACE("Returning %p.\n", *texture);
3750 return WINED3D_OK;
3753 HRESULT CDECL wined3d_device_get_back_buffer(const struct wined3d_device *device, UINT swapchain_idx,
3754 UINT backbuffer_idx, enum wined3d_backbuffer_type backbuffer_type, struct wined3d_surface **backbuffer)
3756 struct wined3d_swapchain *swapchain;
3757 HRESULT hr;
3759 TRACE("device %p, swapchain_idx %u, backbuffer_idx %u, backbuffer_type %#x, backbuffer %p.\n",
3760 device, swapchain_idx, backbuffer_idx, backbuffer_type, backbuffer);
3762 hr = wined3d_device_get_swapchain(device, swapchain_idx, &swapchain);
3763 if (FAILED(hr))
3765 WARN("Failed to get swapchain %u, hr %#x.\n", swapchain_idx, hr);
3766 return hr;
3769 hr = wined3d_swapchain_get_back_buffer(swapchain, backbuffer_idx, backbuffer_type, backbuffer);
3770 wined3d_swapchain_decref(swapchain);
3771 if (FAILED(hr))
3773 WARN("Failed to get backbuffer %u, hr %#x.\n", backbuffer_idx, hr);
3774 return hr;
3777 return WINED3D_OK;
3780 HRESULT CDECL wined3d_device_get_device_caps(const struct wined3d_device *device, WINED3DCAPS *caps)
3782 TRACE("device %p, caps %p.\n", device, caps);
3784 return wined3d_get_device_caps(device->wined3d, device->adapter->ordinal,
3785 device->create_parms.device_type, caps);
3788 HRESULT CDECL wined3d_device_get_display_mode(const struct wined3d_device *device,
3789 UINT swapchain_idx, struct wined3d_display_mode *mode)
3791 struct wined3d_swapchain *swapchain;
3792 HRESULT hr;
3794 TRACE("device %p, swapchain_idx %u, mode %p.\n", device, swapchain_idx, mode);
3796 if (swapchain_idx)
3798 hr = wined3d_device_get_swapchain(device, swapchain_idx, &swapchain);
3799 if (SUCCEEDED(hr))
3801 hr = wined3d_swapchain_get_display_mode(swapchain, mode);
3802 wined3d_swapchain_decref(swapchain);
3805 else
3807 const struct wined3d_adapter *adapter = device->adapter;
3809 /* Don't read the real display mode, but return the stored mode
3810 * instead. X11 can't change the color depth, and some apps are
3811 * pretty angry if they SetDisplayMode from 24 to 16 bpp and find out
3812 * that GetDisplayMode still returns 24 bpp.
3814 * Also don't relay to the swapchain because with ddraw it's possible
3815 * that there isn't a swapchain at all. */
3816 mode->width = adapter->screen_size.cx;
3817 mode->height = adapter->screen_size.cy;
3818 mode->format_id = adapter->screen_format;
3819 mode->refresh_rate = 0;
3820 hr = WINED3D_OK;
3823 return hr;
3826 HRESULT CDECL wined3d_device_begin_stateblock(struct wined3d_device *device)
3828 struct wined3d_stateblock *stateblock;
3829 HRESULT hr;
3831 TRACE("device %p.\n", device);
3833 if (device->isRecordingState)
3834 return WINED3DERR_INVALIDCALL;
3836 hr = wined3d_stateblock_create(device, WINED3D_SBT_RECORDED, &stateblock);
3837 if (FAILED(hr))
3838 return hr;
3840 wined3d_stateblock_decref(device->updateStateBlock);
3841 device->updateStateBlock = stateblock;
3842 device->isRecordingState = TRUE;
3844 TRACE("Recording stateblock %p.\n", stateblock);
3846 return WINED3D_OK;
3849 HRESULT CDECL wined3d_device_end_stateblock(struct wined3d_device *device,
3850 struct wined3d_stateblock **stateblock)
3852 struct wined3d_stateblock *object = device->updateStateBlock;
3854 TRACE("device %p, stateblock %p.\n", device, stateblock);
3856 if (!device->isRecordingState)
3858 WARN("Not recording.\n");
3859 *stateblock = NULL;
3860 return WINED3DERR_INVALIDCALL;
3863 stateblock_init_contained_states(object);
3865 *stateblock = object;
3866 device->isRecordingState = FALSE;
3867 device->updateStateBlock = device->stateBlock;
3868 wined3d_stateblock_incref(device->updateStateBlock);
3870 TRACE("Returning stateblock %p.\n", *stateblock);
3872 return WINED3D_OK;
3875 HRESULT CDECL wined3d_device_begin_scene(struct wined3d_device *device)
3877 /* At the moment we have no need for any functionality at the beginning
3878 * of a scene. */
3879 TRACE("device %p.\n", device);
3881 if (device->inScene)
3883 WARN("Already in scene, returning WINED3DERR_INVALIDCALL.\n");
3884 return WINED3DERR_INVALIDCALL;
3886 device->inScene = TRUE;
3887 return WINED3D_OK;
3890 HRESULT CDECL wined3d_device_end_scene(struct wined3d_device *device)
3892 struct wined3d_context *context;
3894 TRACE("device %p.\n", device);
3896 if (!device->inScene)
3898 WARN("Not in scene, returning WINED3DERR_INVALIDCALL.\n");
3899 return WINED3DERR_INVALIDCALL;
3902 context = context_acquire(device, NULL);
3903 /* We only have to do this if we need to read the, swapbuffers performs a flush for us */
3904 wglFlush();
3905 /* No checkGLcall here to avoid locking the lock just for checking a call that hardly ever
3906 * fails. */
3907 context_release(context);
3909 device->inScene = FALSE;
3910 return WINED3D_OK;
3913 HRESULT CDECL wined3d_device_present(const struct wined3d_device *device, const RECT *src_rect,
3914 const RECT *dst_rect, HWND dst_window_override, const RGNDATA *dirty_region)
3916 UINT i;
3918 TRACE("device %p, src_rect %s, dst_rect %s, dst_window_override %p, dirty_region %p.\n",
3919 device, wine_dbgstr_rect(src_rect), wine_dbgstr_rect(dst_rect),
3920 dst_window_override, dirty_region);
3922 for (i = 0; i < device->swapchain_count; ++i)
3924 wined3d_swapchain_present(device->swapchains[i], src_rect,
3925 dst_rect, dst_window_override, dirty_region, 0);
3928 return WINED3D_OK;
3931 /* Do not call while under the GL lock. */
3932 HRESULT CDECL wined3d_device_clear(struct wined3d_device *device, DWORD rect_count,
3933 const RECT *rects, DWORD flags, const struct wined3d_color *color, float depth, DWORD stencil)
3935 RECT draw_rect;
3937 TRACE("device %p, rect_count %u, rects %p, flags %#x, color {%.8e, %.8e, %.8e, %.8e}, depth %.8e, stencil %u.\n",
3938 device, rect_count, rects, flags, color->r, color->g, color->b, color->a, depth, stencil);
3940 if (flags & (WINED3DCLEAR_ZBUFFER | WINED3DCLEAR_STENCIL))
3942 struct wined3d_surface *ds = device->fb.depth_stencil;
3943 if (!ds)
3945 WARN("Clearing depth and/or stencil without a depth stencil buffer attached, returning WINED3DERR_INVALIDCALL\n");
3946 /* TODO: What about depth stencil buffers without stencil bits? */
3947 return WINED3DERR_INVALIDCALL;
3949 else if (flags & WINED3DCLEAR_TARGET)
3951 if (ds->resource.width < device->fb.render_targets[0]->resource.width
3952 || ds->resource.height < device->fb.render_targets[0]->resource.height)
3954 WARN("Silently ignoring depth and target clear with mismatching sizes\n");
3955 return WINED3D_OK;
3960 wined3d_get_draw_rect(&device->stateBlock->state, &draw_rect);
3962 return device_clear_render_targets(device, device->adapter->gl_info.limits.buffers,
3963 &device->fb, rect_count, rects,
3964 &draw_rect, flags, color, depth, stencil);
3967 void CDECL wined3d_device_set_primitive_type(struct wined3d_device *device,
3968 enum wined3d_primitive_type primitive_type)
3970 TRACE("device %p, primitive_type %s\n", device, debug_d3dprimitivetype(primitive_type));
3972 device->updateStateBlock->changed.primitive_type = TRUE;
3973 device->updateStateBlock->state.gl_primitive_type = gl_primitive_type_from_d3d(primitive_type);
3976 void CDECL wined3d_device_get_primitive_type(const struct wined3d_device *device,
3977 enum wined3d_primitive_type *primitive_type)
3979 TRACE("device %p, primitive_type %p\n", device, primitive_type);
3981 *primitive_type = d3d_primitive_type_from_gl(device->stateBlock->state.gl_primitive_type);
3983 TRACE("Returning %s\n", debug_d3dprimitivetype(*primitive_type));
3986 HRESULT CDECL wined3d_device_draw_primitive(struct wined3d_device *device, UINT start_vertex, UINT vertex_count)
3988 TRACE("device %p, start_vertex %u, vertex_count %u.\n", device, start_vertex, vertex_count);
3990 if (!device->stateBlock->state.vertex_declaration)
3992 WARN("Called without a valid vertex declaration set.\n");
3993 return WINED3DERR_INVALIDCALL;
3996 /* The index buffer is not needed here, but restore it, otherwise it is hell to keep track of */
3997 if (device->stateBlock->state.user_stream)
3999 device_invalidate_state(device, STATE_INDEXBUFFER);
4000 device->stateBlock->state.user_stream = FALSE;
4003 if (device->stateBlock->state.load_base_vertex_index)
4005 device->stateBlock->state.load_base_vertex_index = 0;
4006 device_invalidate_state(device, STATE_BASEVERTEXINDEX);
4009 /* Account for the loading offset due to index buffers. Instead of
4010 * reloading all sources correct it with the startvertex parameter. */
4011 drawPrimitive(device, vertex_count, start_vertex, 0, NULL);
4012 return WINED3D_OK;
4015 HRESULT CDECL wined3d_device_draw_indexed_primitive(struct wined3d_device *device, UINT start_idx, UINT index_count)
4017 struct wined3d_buffer *index_buffer;
4018 UINT index_size = 2;
4019 GLuint vbo;
4020 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4022 TRACE("device %p, start_idx %u, index_count %u.\n", device, start_idx, index_count);
4024 index_buffer = device->stateBlock->state.index_buffer;
4025 if (!index_buffer)
4027 /* D3D9 returns D3DERR_INVALIDCALL when DrawIndexedPrimitive is called
4028 * without an index buffer set. (The first time at least...)
4029 * D3D8 simply dies, but I doubt it can do much harm to return
4030 * D3DERR_INVALIDCALL there as well. */
4031 WARN("Called without a valid index buffer set, returning WINED3DERR_INVALIDCALL.\n");
4032 return WINED3DERR_INVALIDCALL;
4035 if (!device->stateBlock->state.vertex_declaration)
4037 WARN("Called without a valid vertex declaration set.\n");
4038 return WINED3DERR_INVALIDCALL;
4041 if (device->stateBlock->state.user_stream)
4043 device_invalidate_state(device, STATE_INDEXBUFFER);
4044 device->stateBlock->state.user_stream = FALSE;
4046 vbo = index_buffer->buffer_object;
4048 if (device->stateBlock->state.index_format == WINED3DFMT_R16_UINT)
4049 index_size = 2;
4050 else
4051 index_size = 4;
4053 if (!gl_info->supported[ARB_DRAW_ELEMENTS_BASE_VERTEX] &&
4054 device->stateBlock->state.load_base_vertex_index != device->stateBlock->state.base_vertex_index)
4056 device->stateBlock->state.load_base_vertex_index = device->stateBlock->state.base_vertex_index;
4057 device_invalidate_state(device, STATE_BASEVERTEXINDEX);
4060 drawPrimitive(device, index_count, start_idx, index_size,
4061 vbo ? NULL : index_buffer->resource.allocatedMemory);
4063 return WINED3D_OK;
4066 HRESULT CDECL wined3d_device_draw_primitive_up(struct wined3d_device *device, UINT vertex_count,
4067 const void *stream_data, UINT stream_stride)
4069 struct wined3d_stream_state *stream;
4070 struct wined3d_buffer *vb;
4072 TRACE("device %p, vertex count %u, stream_data %p, stream_stride %u.\n",
4073 device, vertex_count, stream_data, stream_stride);
4075 if (!device->stateBlock->state.vertex_declaration)
4077 WARN("Called without a valid vertex declaration set.\n");
4078 return WINED3DERR_INVALIDCALL;
4081 /* Note in the following, it's not this type, but that's the purpose of streamIsUP */
4082 stream = &device->stateBlock->state.streams[0];
4083 vb = stream->buffer;
4084 stream->buffer = (struct wined3d_buffer *)stream_data;
4085 if (vb)
4086 wined3d_buffer_decref(vb);
4087 stream->offset = 0;
4088 stream->stride = stream_stride;
4089 device->stateBlock->state.user_stream = TRUE;
4090 if (device->stateBlock->state.load_base_vertex_index)
4092 device->stateBlock->state.load_base_vertex_index = 0;
4093 device_invalidate_state(device, STATE_BASEVERTEXINDEX);
4096 /* TODO: Only mark dirty if drawing from a different UP address */
4097 device_invalidate_state(device, STATE_STREAMSRC);
4099 drawPrimitive(device, vertex_count, 0, 0, NULL);
4101 /* MSDN specifies stream zero settings must be set to NULL */
4102 stream->buffer = NULL;
4103 stream->stride = 0;
4105 /* stream zero settings set to null at end, as per the msdn. No need to
4106 * mark dirty here, the app has to set the new stream sources or use UP
4107 * drawing again. */
4108 return WINED3D_OK;
4111 HRESULT CDECL wined3d_device_draw_indexed_primitive_up(struct wined3d_device *device,
4112 UINT index_count, const void *index_data, enum wined3d_format_id index_data_format_id,
4113 const void *stream_data, UINT stream_stride)
4115 struct wined3d_stream_state *stream;
4116 struct wined3d_buffer *vb, *ib;
4117 UINT index_size;
4119 TRACE("device %p, index_count %u, index_data %p, index_data_format %s, stream_data %p, stream_stride %u.\n",
4120 device, index_count, index_data, debug_d3dformat(index_data_format_id), stream_data, stream_stride);
4122 if (!device->stateBlock->state.vertex_declaration)
4124 WARN("(%p) : Called without a valid vertex declaration set\n", device);
4125 return WINED3DERR_INVALIDCALL;
4128 if (index_data_format_id == WINED3DFMT_R16_UINT)
4129 index_size = 2;
4130 else
4131 index_size = 4;
4133 stream = &device->stateBlock->state.streams[0];
4134 vb = stream->buffer;
4135 stream->buffer = (struct wined3d_buffer *)stream_data;
4136 if (vb)
4137 wined3d_buffer_decref(vb);
4138 stream->offset = 0;
4139 stream->stride = stream_stride;
4140 device->stateBlock->state.user_stream = TRUE;
4142 /* Set to 0 as per msdn. Do it now due to the stream source loading during drawPrimitive */
4143 device->stateBlock->state.base_vertex_index = 0;
4144 if (device->stateBlock->state.load_base_vertex_index)
4146 device->stateBlock->state.load_base_vertex_index = 0;
4147 device_invalidate_state(device, STATE_BASEVERTEXINDEX);
4149 /* Invalidate the state until we have nicer tracking of the stream source pointers */
4150 device_invalidate_state(device, STATE_STREAMSRC);
4151 device_invalidate_state(device, STATE_INDEXBUFFER);
4153 drawPrimitive(device, index_count, 0, index_size, index_data);
4155 /* MSDN specifies stream zero settings and index buffer must be set to NULL */
4156 stream->buffer = NULL;
4157 stream->stride = 0;
4158 ib = device->stateBlock->state.index_buffer;
4159 if (ib)
4161 wined3d_buffer_decref(ib);
4162 device->stateBlock->state.index_buffer = NULL;
4164 /* No need to mark the stream source state dirty here. Either the app calls UP drawing again, or it has to call
4165 * SetStreamSource to specify a vertex buffer
4168 return WINED3D_OK;
4171 HRESULT CDECL wined3d_device_draw_primitive_strided(struct wined3d_device *device,
4172 UINT vertex_count, const struct wined3d_strided_data *strided_data)
4174 /* Mark the state dirty until we have nicer tracking. It's fine to change
4175 * baseVertexIndex because that call is only called by ddraw which does
4176 * not need that value. */
4177 device_invalidate_state(device, STATE_VDECL);
4178 device_invalidate_state(device, STATE_STREAMSRC);
4179 device_invalidate_state(device, STATE_INDEXBUFFER);
4181 device->stateBlock->state.base_vertex_index = 0;
4182 device->up_strided = strided_data;
4183 drawPrimitive(device, vertex_count, 0, 0, NULL);
4184 device->up_strided = NULL;
4186 /* Invalidate the states again to make sure the values from the stateblock
4187 * are properly applied in the next regular draw. Note that the application-
4188 * provided strided data has ovwritten pretty much the entire vertex and
4189 * and index stream related states */
4190 device_invalidate_state(device, STATE_VDECL);
4191 device_invalidate_state(device, STATE_STREAMSRC);
4192 device_invalidate_state(device, STATE_INDEXBUFFER);
4193 return WINED3D_OK;
4196 HRESULT CDECL wined3d_device_draw_indexed_primitive_strided(struct wined3d_device *device,
4197 UINT index_count, const struct wined3d_strided_data *strided_data,
4198 UINT vertex_count, const void *index_data, enum wined3d_format_id index_data_format_id)
4200 UINT index_size = index_data_format_id == WINED3DFMT_R32_UINT ? 4 : 2;
4202 /* Mark the state dirty until we have nicer tracking
4203 * its fine to change baseVertexIndex because that call is only called by ddraw which does not need
4204 * that value.
4206 device_invalidate_state(device, STATE_VDECL);
4207 device_invalidate_state(device, STATE_STREAMSRC);
4208 device_invalidate_state(device, STATE_INDEXBUFFER);
4210 device->stateBlock->state.user_stream = TRUE;
4211 device->stateBlock->state.base_vertex_index = 0;
4212 device->up_strided = strided_data;
4213 drawPrimitive(device, index_count, 0, index_size, index_data);
4214 device->up_strided = NULL;
4216 device_invalidate_state(device, STATE_VDECL);
4217 device_invalidate_state(device, STATE_STREAMSRC);
4218 device_invalidate_state(device, STATE_INDEXBUFFER);
4219 return WINED3D_OK;
4222 /* This is a helper function for UpdateTexture, there is no UpdateVolume method in D3D. */
4223 static HRESULT device_update_volume(struct wined3d_device *device,
4224 struct wined3d_volume *src_volume, struct wined3d_volume *dst_volume)
4226 struct wined3d_mapped_box src;
4227 struct wined3d_mapped_box dst;
4228 HRESULT hr;
4230 TRACE("device %p, src_volume %p, dst_volume %p.\n",
4231 device, src_volume, dst_volume);
4233 /* TODO: Implement direct loading into the gl volume instead of using
4234 * memcpy and dirtification to improve loading performance. */
4235 hr = wined3d_volume_map(src_volume, &src, NULL, WINED3DLOCK_READONLY);
4236 if (FAILED(hr)) return hr;
4237 hr = wined3d_volume_map(dst_volume, &dst, NULL, WINED3DLOCK_DISCARD);
4238 if (FAILED(hr))
4240 wined3d_volume_unmap(src_volume);
4241 return hr;
4244 memcpy(dst.data, src.data, dst_volume->resource.size);
4246 hr = wined3d_volume_unmap(dst_volume);
4247 if (FAILED(hr))
4248 wined3d_volume_unmap(src_volume);
4249 else
4250 hr = wined3d_volume_unmap(src_volume);
4252 return hr;
4255 HRESULT CDECL wined3d_device_update_texture(struct wined3d_device *device,
4256 struct wined3d_texture *src_texture, struct wined3d_texture *dst_texture)
4258 enum wined3d_resource_type type;
4259 unsigned int level_count, i;
4260 HRESULT hr;
4262 TRACE("device %p, src_texture %p, dst_texture %p.\n", device, src_texture, dst_texture);
4264 /* Verify that the source and destination textures are non-NULL. */
4265 if (!src_texture || !dst_texture)
4267 WARN("Source and destination textures must be non-NULL, returning WINED3DERR_INVALIDCALL.\n");
4268 return WINED3DERR_INVALIDCALL;
4271 if (src_texture == dst_texture)
4273 WARN("Source and destination are the same object, returning WINED3DERR_INVALIDCALL.\n");
4274 return WINED3DERR_INVALIDCALL;
4277 /* Verify that the source and destination textures are the same type. */
4278 type = src_texture->resource.type;
4279 if (dst_texture->resource.type != type)
4281 WARN("Source and destination have different types, returning WINED3DERR_INVALIDCALL.\n");
4282 return WINED3DERR_INVALIDCALL;
4285 /* Check that both textures have the identical numbers of levels. */
4286 level_count = wined3d_texture_get_level_count(src_texture);
4287 if (wined3d_texture_get_level_count(dst_texture) != level_count)
4289 WARN("Source and destination have different level counts, returning WINED3DERR_INVALIDCALL.\n");
4290 return WINED3DERR_INVALIDCALL;
4293 /* Make sure that the destination texture is loaded. */
4294 dst_texture->texture_ops->texture_preload(dst_texture, SRGB_RGB);
4296 /* Update every surface level of the texture. */
4297 switch (type)
4299 case WINED3D_RTYPE_TEXTURE:
4301 struct wined3d_surface *src_surface;
4302 struct wined3d_surface *dst_surface;
4304 for (i = 0; i < level_count; ++i)
4306 src_surface = surface_from_resource(wined3d_texture_get_sub_resource(src_texture, i));
4307 dst_surface = surface_from_resource(wined3d_texture_get_sub_resource(dst_texture, i));
4308 hr = wined3d_device_update_surface(device, src_surface, NULL, dst_surface, NULL);
4309 if (FAILED(hr))
4311 WARN("Failed to update surface, hr %#x.\n", hr);
4312 return hr;
4315 break;
4318 case WINED3D_RTYPE_CUBE_TEXTURE:
4320 struct wined3d_surface *src_surface;
4321 struct wined3d_surface *dst_surface;
4323 for (i = 0; i < level_count * 6; ++i)
4325 src_surface = surface_from_resource(wined3d_texture_get_sub_resource(src_texture, i));
4326 dst_surface = surface_from_resource(wined3d_texture_get_sub_resource(dst_texture, i));
4327 hr = wined3d_device_update_surface(device, src_surface, NULL, dst_surface, NULL);
4328 if (FAILED(hr))
4330 WARN("Failed to update surface, hr %#x.\n", hr);
4331 return hr;
4334 break;
4337 case WINED3D_RTYPE_VOLUME_TEXTURE:
4339 for (i = 0; i < level_count; ++i)
4341 hr = device_update_volume(device,
4342 volume_from_resource(wined3d_texture_get_sub_resource(src_texture, i)),
4343 volume_from_resource(wined3d_texture_get_sub_resource(dst_texture, i)));
4344 if (FAILED(hr))
4346 WARN("Failed to update volume, hr %#x.\n", hr);
4347 return hr;
4350 break;
4353 default:
4354 FIXME("Unsupported texture type %#x.\n", type);
4355 return WINED3DERR_INVALIDCALL;
4358 return WINED3D_OK;
4361 HRESULT CDECL wined3d_device_get_front_buffer_data(const struct wined3d_device *device,
4362 UINT swapchain_idx, struct wined3d_surface *dst_surface)
4364 struct wined3d_swapchain *swapchain;
4365 HRESULT hr;
4367 TRACE("device %p, swapchain_idx %u, dst_surface %p.\n", device, swapchain_idx, dst_surface);
4369 hr = wined3d_device_get_swapchain(device, swapchain_idx, &swapchain);
4370 if (FAILED(hr)) return hr;
4372 hr = wined3d_swapchain_get_front_buffer_data(swapchain, dst_surface);
4373 wined3d_swapchain_decref(swapchain);
4375 return hr;
4378 HRESULT CDECL wined3d_device_validate_device(const struct wined3d_device *device, DWORD *num_passes)
4380 const struct wined3d_state *state = &device->stateBlock->state;
4381 struct wined3d_texture *texture;
4382 DWORD i;
4384 TRACE("device %p, num_passes %p.\n", device, num_passes);
4386 for (i = 0; i < MAX_COMBINED_SAMPLERS; ++i)
4388 if (state->sampler_states[i][WINED3D_SAMP_MIN_FILTER] == WINED3D_TEXF_NONE)
4390 WARN("Sampler state %u has minfilter D3DTEXF_NONE, returning D3DERR_UNSUPPORTEDTEXTUREFILTER\n", i);
4391 return WINED3DERR_UNSUPPORTEDTEXTUREFILTER;
4393 if (state->sampler_states[i][WINED3D_SAMP_MAG_FILTER] == WINED3D_TEXF_NONE)
4395 WARN("Sampler state %u has magfilter D3DTEXF_NONE, returning D3DERR_UNSUPPORTEDTEXTUREFILTER\n", i);
4396 return WINED3DERR_UNSUPPORTEDTEXTUREFILTER;
4399 texture = state->textures[i];
4400 if (!texture || texture->resource.format->flags & WINED3DFMT_FLAG_FILTERING) continue;
4402 if (state->sampler_states[i][WINED3D_SAMP_MAG_FILTER] != WINED3D_TEXF_POINT)
4404 WARN("Non-filterable texture and mag filter enabled on samper %u, returning E_FAIL\n", i);
4405 return E_FAIL;
4407 if (state->sampler_states[i][WINED3D_SAMP_MIN_FILTER] != WINED3D_TEXF_POINT)
4409 WARN("Non-filterable texture and min filter enabled on samper %u, returning E_FAIL\n", i);
4410 return E_FAIL;
4412 if (state->sampler_states[i][WINED3D_SAMP_MIP_FILTER] != WINED3D_TEXF_NONE
4413 && state->sampler_states[i][WINED3D_SAMP_MIP_FILTER] != WINED3D_TEXF_POINT)
4415 WARN("Non-filterable texture and mip filter enabled on samper %u, returning E_FAIL\n", i);
4416 return E_FAIL;
4420 if (state->render_states[WINED3D_RS_ZENABLE] || state->render_states[WINED3D_RS_ZWRITEENABLE]
4421 || state->render_states[WINED3D_RS_STENCILENABLE])
4423 struct wined3d_surface *ds = device->fb.depth_stencil;
4424 struct wined3d_surface *target = device->fb.render_targets[0];
4426 if(ds && target
4427 && (ds->resource.width < target->resource.width || ds->resource.height < target->resource.height))
4429 WARN("Depth stencil is smaller than the color buffer, returning D3DERR_CONFLICTINGRENDERSTATE\n");
4430 return WINED3DERR_CONFLICTINGRENDERSTATE;
4434 /* return a sensible default */
4435 *num_passes = 1;
4437 TRACE("returning D3D_OK\n");
4438 return WINED3D_OK;
4441 HRESULT CDECL wined3d_device_set_software_vertex_processing(struct wined3d_device *device, BOOL software)
4443 static BOOL warned;
4445 TRACE("device %p, software %#x.\n", device, software);
4447 if (!warned)
4449 FIXME("device %p, software %#x stub!\n", device, software);
4450 warned = TRUE;
4453 device->softwareVertexProcessing = software;
4455 return WINED3D_OK;
4458 BOOL CDECL wined3d_device_get_software_vertex_processing(const struct wined3d_device *device)
4460 static BOOL warned;
4462 TRACE("device %p.\n", device);
4464 if (!warned)
4466 TRACE("device %p stub!\n", device);
4467 warned = TRUE;
4470 return device->softwareVertexProcessing;
4473 HRESULT CDECL wined3d_device_get_raster_status(const struct wined3d_device *device,
4474 UINT swapchain_idx, struct wined3d_raster_status *raster_status)
4476 struct wined3d_swapchain *swapchain;
4477 HRESULT hr;
4479 TRACE("device %p, swapchain_idx %u, raster_status %p.\n",
4480 device, swapchain_idx, raster_status);
4482 hr = wined3d_device_get_swapchain(device, swapchain_idx, &swapchain);
4483 if (FAILED(hr))
4485 WARN("Failed to get swapchain %u, hr %#x.\n", swapchain_idx, hr);
4486 return hr;
4489 hr = wined3d_swapchain_get_raster_status(swapchain, raster_status);
4490 wined3d_swapchain_decref(swapchain);
4491 if (FAILED(hr))
4493 WARN("Failed to get raster status, hr %#x.\n", hr);
4494 return hr;
4497 return WINED3D_OK;
4500 HRESULT CDECL wined3d_device_set_npatch_mode(struct wined3d_device *device, float segments)
4502 static BOOL warned;
4504 TRACE("device %p, segments %.8e.\n", device, segments);
4506 if (segments != 0.0f)
4508 if (!warned)
4510 FIXME("device %p, segments %.8e stub!\n", device, segments);
4511 warned = TRUE;
4515 return WINED3D_OK;
4518 float CDECL wined3d_device_get_npatch_mode(const struct wined3d_device *device)
4520 static BOOL warned;
4522 TRACE("device %p.\n", device);
4524 if (!warned)
4526 FIXME("device %p stub!\n", device);
4527 warned = TRUE;
4530 return 0.0f;
4533 HRESULT CDECL wined3d_device_update_surface(struct wined3d_device *device,
4534 struct wined3d_surface *src_surface, const RECT *src_rect,
4535 struct wined3d_surface *dst_surface, const POINT *dst_point)
4537 TRACE("device %p, src_surface %p, src_rect %s, dst_surface %p, dst_point %s.\n",
4538 device, src_surface, wine_dbgstr_rect(src_rect),
4539 dst_surface, wine_dbgstr_point(dst_point));
4541 if (src_surface->resource.pool != WINED3D_POOL_SYSTEM_MEM || dst_surface->resource.pool != WINED3D_POOL_DEFAULT)
4543 WARN("source %p must be SYSTEMMEM and dest %p must be DEFAULT, returning WINED3DERR_INVALIDCALL\n",
4544 src_surface, dst_surface);
4545 return WINED3DERR_INVALIDCALL;
4548 return surface_upload_from_surface(dst_surface, dst_point, src_surface, src_rect);
4551 HRESULT CDECL wined3d_device_draw_rect_patch(struct wined3d_device *device, UINT handle,
4552 const float *num_segs, const struct wined3d_rect_patch_info *rect_patch_info)
4554 struct wined3d_rect_patch *patch;
4555 GLenum old_primitive_type;
4556 unsigned int i;
4557 struct list *e;
4558 BOOL found;
4560 TRACE("device %p, handle %#x, num_segs %p, rect_patch_info %p.\n",
4561 device, handle, num_segs, rect_patch_info);
4563 if (!(handle || rect_patch_info))
4565 /* TODO: Write a test for the return value, thus the FIXME */
4566 FIXME("Both handle and rect_patch_info are NULL.\n");
4567 return WINED3DERR_INVALIDCALL;
4570 if (handle)
4572 i = PATCHMAP_HASHFUNC(handle);
4573 found = FALSE;
4574 LIST_FOR_EACH(e, &device->patches[i])
4576 patch = LIST_ENTRY(e, struct wined3d_rect_patch, entry);
4577 if (patch->Handle == handle)
4579 found = TRUE;
4580 break;
4584 if (!found)
4586 TRACE("Patch does not exist. Creating a new one\n");
4587 patch = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*patch));
4588 patch->Handle = handle;
4589 list_add_head(&device->patches[i], &patch->entry);
4590 } else {
4591 TRACE("Found existing patch %p\n", patch);
4594 else
4596 /* Since opengl does not load tesselated vertex attributes into numbered vertex
4597 * attributes we have to tesselate, read back, and draw. This needs a patch
4598 * management structure instance. Create one.
4600 * A possible improvement is to check if a vertex shader is used, and if not directly
4601 * draw the patch.
4603 FIXME("Drawing an uncached patch. This is slow\n");
4604 patch = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*patch));
4607 if (num_segs[0] != patch->numSegs[0] || num_segs[1] != patch->numSegs[1]
4608 || num_segs[2] != patch->numSegs[2] || num_segs[3] != patch->numSegs[3]
4609 || (rect_patch_info && memcmp(rect_patch_info, &patch->rect_patch_info, sizeof(*rect_patch_info))))
4611 HRESULT hr;
4612 TRACE("Tesselation density or patch info changed, retesselating\n");
4614 if (rect_patch_info)
4615 patch->rect_patch_info = *rect_patch_info;
4617 patch->numSegs[0] = num_segs[0];
4618 patch->numSegs[1] = num_segs[1];
4619 patch->numSegs[2] = num_segs[2];
4620 patch->numSegs[3] = num_segs[3];
4622 hr = tesselate_rectpatch(device, patch);
4623 if (FAILED(hr))
4625 WARN("Patch tesselation failed.\n");
4627 /* Do not release the handle to store the params of the patch */
4628 if (!handle)
4629 HeapFree(GetProcessHeap(), 0, patch);
4631 return hr;
4635 old_primitive_type = device->stateBlock->state.gl_primitive_type;
4636 device->stateBlock->state.gl_primitive_type = GL_TRIANGLES;
4637 wined3d_device_draw_primitive_strided(device, patch->numSegs[0] * patch->numSegs[1] * 2 * 3, &patch->strided);
4638 device->stateBlock->state.gl_primitive_type = old_primitive_type;
4640 /* Destroy uncached patches */
4641 if (!handle)
4643 HeapFree(GetProcessHeap(), 0, patch->mem);
4644 HeapFree(GetProcessHeap(), 0, patch);
4646 return WINED3D_OK;
4649 HRESULT CDECL wined3d_device_draw_tri_patch(struct wined3d_device *device, UINT handle,
4650 const float *segment_count, const struct wined3d_tri_patch_info *patch_info)
4652 FIXME("device %p, handle %#x, segment_count %p, patch_info %p stub!\n",
4653 device, handle, segment_count, patch_info);
4655 return WINED3D_OK;
4658 HRESULT CDECL wined3d_device_delete_patch(struct wined3d_device *device, UINT handle)
4660 struct wined3d_rect_patch *patch;
4661 struct list *e;
4662 int i;
4664 TRACE("device %p, handle %#x.\n", device, handle);
4666 i = PATCHMAP_HASHFUNC(handle);
4667 LIST_FOR_EACH(e, &device->patches[i])
4669 patch = LIST_ENTRY(e, struct wined3d_rect_patch, entry);
4670 if (patch->Handle == handle)
4672 TRACE("Deleting patch %p\n", patch);
4673 list_remove(&patch->entry);
4674 HeapFree(GetProcessHeap(), 0, patch->mem);
4675 HeapFree(GetProcessHeap(), 0, patch);
4676 return WINED3D_OK;
4680 /* TODO: Write a test for the return value */
4681 FIXME("Attempt to destroy nonexistent patch\n");
4682 return WINED3DERR_INVALIDCALL;
4685 /* Do not call while under the GL lock. */
4686 HRESULT CDECL wined3d_device_color_fill(struct wined3d_device *device,
4687 struct wined3d_surface *surface, const RECT *rect, const struct wined3d_color *color)
4689 RECT r;
4691 TRACE("device %p, surface %p, rect %s, color {%.8e, %.8e, %.8e, %.8e}.\n",
4692 device, surface, wine_dbgstr_rect(rect),
4693 color->r, color->g, color->b, color->a);
4695 if (surface->resource.pool != WINED3D_POOL_DEFAULT && surface->resource.pool != WINED3D_POOL_SYSTEM_MEM)
4697 WARN("Color-fill not allowed on %s surfaces.\n", debug_d3dpool(surface->resource.pool));
4698 return WINED3DERR_INVALIDCALL;
4701 if (!rect)
4703 SetRect(&r, 0, 0, surface->resource.width, surface->resource.height);
4704 rect = &r;
4707 return surface_color_fill(surface, rect, color);
4710 /* Do not call while under the GL lock. */
4711 void CDECL wined3d_device_clear_rendertarget_view(struct wined3d_device *device,
4712 struct wined3d_rendertarget_view *rendertarget_view, const struct wined3d_color *color)
4714 struct wined3d_resource *resource;
4715 HRESULT hr;
4716 RECT rect;
4718 resource = rendertarget_view->resource;
4719 if (resource->type != WINED3D_RTYPE_SURFACE)
4721 FIXME("Only supported on surface resources\n");
4722 return;
4725 SetRect(&rect, 0, 0, resource->width, resource->height);
4726 hr = surface_color_fill(surface_from_resource(resource), &rect, color);
4727 if (FAILED(hr)) ERR("Color fill failed, hr %#x.\n", hr);
4730 HRESULT CDECL wined3d_device_get_render_target(const struct wined3d_device *device,
4731 UINT render_target_idx, struct wined3d_surface **render_target)
4733 TRACE("device %p, render_target_idx %u, render_target %p.\n",
4734 device, render_target_idx, render_target);
4736 if (render_target_idx >= device->adapter->gl_info.limits.buffers)
4738 WARN("Only %u render targets are supported.\n", device->adapter->gl_info.limits.buffers);
4739 return WINED3DERR_INVALIDCALL;
4742 *render_target = device->fb.render_targets[render_target_idx];
4743 TRACE("Returning render target %p.\n", *render_target);
4745 if (!*render_target)
4746 return WINED3DERR_NOTFOUND;
4748 wined3d_surface_incref(*render_target);
4750 return WINED3D_OK;
4753 HRESULT CDECL wined3d_device_get_depth_stencil(const struct wined3d_device *device,
4754 struct wined3d_surface **depth_stencil)
4756 TRACE("device %p, depth_stencil %p.\n", device, depth_stencil);
4758 *depth_stencil = device->fb.depth_stencil;
4759 TRACE("Returning depth/stencil surface %p.\n", *depth_stencil);
4761 if (!*depth_stencil)
4762 return WINED3DERR_NOTFOUND;
4764 wined3d_surface_incref(*depth_stencil);
4766 return WINED3D_OK;
4769 HRESULT CDECL wined3d_device_set_render_target(struct wined3d_device *device,
4770 UINT render_target_idx, struct wined3d_surface *render_target, BOOL set_viewport)
4772 struct wined3d_surface *prev;
4774 TRACE("device %p, render_target_idx %u, render_target %p, set_viewport %#x.\n",
4775 device, render_target_idx, render_target, set_viewport);
4777 if (render_target_idx >= device->adapter->gl_info.limits.buffers)
4779 WARN("Only %u render targets are supported.\n", device->adapter->gl_info.limits.buffers);
4780 return WINED3DERR_INVALIDCALL;
4783 prev = device->fb.render_targets[render_target_idx];
4784 if (render_target == prev)
4786 TRACE("Trying to do a NOP SetRenderTarget operation.\n");
4787 return WINED3D_OK;
4790 /* Render target 0 can't be set to NULL. */
4791 if (!render_target && !render_target_idx)
4793 WARN("Trying to set render target 0 to NULL.\n");
4794 return WINED3DERR_INVALIDCALL;
4797 if (render_target && !(render_target->resource.usage & WINED3DUSAGE_RENDERTARGET))
4799 FIXME("Surface %p doesn't have render target usage.\n", render_target);
4800 return WINED3DERR_INVALIDCALL;
4803 if (render_target)
4804 wined3d_surface_incref(render_target);
4805 device->fb.render_targets[render_target_idx] = render_target;
4806 /* Release after the assignment, to prevent device_resource_released()
4807 * from seeing the surface as still in use. */
4808 if (prev)
4809 wined3d_surface_decref(prev);
4811 /* Render target 0 is special. */
4812 if (!render_target_idx && set_viewport)
4814 /* Set the viewport and scissor rectangles, if requested. Tests show
4815 * that stateblock recording is ignored, the change goes directly
4816 * into the primary stateblock. */
4817 device->stateBlock->state.viewport.height = device->fb.render_targets[0]->resource.height;
4818 device->stateBlock->state.viewport.width = device->fb.render_targets[0]->resource.width;
4819 device->stateBlock->state.viewport.x = 0;
4820 device->stateBlock->state.viewport.y = 0;
4821 device->stateBlock->state.viewport.max_z = 1.0f;
4822 device->stateBlock->state.viewport.min_z = 0.0f;
4823 device_invalidate_state(device, STATE_VIEWPORT);
4825 device->stateBlock->state.scissor_rect.top = 0;
4826 device->stateBlock->state.scissor_rect.left = 0;
4827 device->stateBlock->state.scissor_rect.right = device->stateBlock->state.viewport.width;
4828 device->stateBlock->state.scissor_rect.bottom = device->stateBlock->state.viewport.height;
4829 device_invalidate_state(device, STATE_SCISSORRECT);
4832 device_invalidate_state(device, STATE_FRAMEBUFFER);
4834 return WINED3D_OK;
4837 HRESULT CDECL wined3d_device_set_depth_stencil(struct wined3d_device *device, struct wined3d_surface *depth_stencil)
4839 struct wined3d_surface *prev = device->fb.depth_stencil;
4841 TRACE("device %p, depth_stencil %p, old depth_stencil %p.\n",
4842 device, depth_stencil, prev);
4844 if (prev == depth_stencil)
4846 TRACE("Trying to do a NOP SetRenderTarget operation.\n");
4847 return WINED3D_OK;
4850 if (prev)
4852 if (device->swapchains[0]->desc.flags & WINED3DPRESENTFLAG_DISCARD_DEPTHSTENCIL
4853 || prev->flags & SFLAG_DISCARD)
4855 surface_modify_ds_location(prev, SFLAG_DISCARDED,
4856 prev->resource.width, prev->resource.height);
4857 if (prev == device->onscreen_depth_stencil)
4859 wined3d_surface_decref(device->onscreen_depth_stencil);
4860 device->onscreen_depth_stencil = NULL;
4865 device->fb.depth_stencil = depth_stencil;
4866 if (depth_stencil)
4867 wined3d_surface_incref(depth_stencil);
4869 if (!prev != !depth_stencil)
4871 /* Swapping NULL / non NULL depth stencil affects the depth and tests */
4872 device_invalidate_state(device, STATE_RENDER(WINED3D_RS_ZENABLE));
4873 device_invalidate_state(device, STATE_RENDER(WINED3D_RS_STENCILENABLE));
4874 device_invalidate_state(device, STATE_RENDER(WINED3D_RS_STENCILWRITEMASK));
4875 device_invalidate_state(device, STATE_RENDER(WINED3D_RS_DEPTHBIAS));
4877 else if (prev && prev->resource.format->depth_size != depth_stencil->resource.format->depth_size)
4879 device_invalidate_state(device, STATE_RENDER(WINED3D_RS_DEPTHBIAS));
4881 if (prev)
4882 wined3d_surface_decref(prev);
4884 device_invalidate_state(device, STATE_FRAMEBUFFER);
4886 return WINED3D_OK;
4889 HRESULT CDECL wined3d_device_set_cursor_properties(struct wined3d_device *device,
4890 UINT x_hotspot, UINT y_hotspot, struct wined3d_surface *cursor_image)
4892 struct wined3d_mapped_rect mapped_rect;
4894 TRACE("device %p, x_hotspot %u, y_hotspot %u, cursor_image %p.\n",
4895 device, x_hotspot, y_hotspot, cursor_image);
4897 /* some basic validation checks */
4898 if (device->cursorTexture)
4900 struct wined3d_context *context = context_acquire(device, NULL);
4901 ENTER_GL();
4902 glDeleteTextures(1, &device->cursorTexture);
4903 LEAVE_GL();
4904 context_release(context);
4905 device->cursorTexture = 0;
4908 if (cursor_image)
4910 struct wined3d_mapped_rect rect;
4912 /* MSDN: Cursor must be A8R8G8B8 */
4913 if (cursor_image->resource.format->id != WINED3DFMT_B8G8R8A8_UNORM)
4915 WARN("surface %p has an invalid format.\n", cursor_image);
4916 return WINED3DERR_INVALIDCALL;
4919 /* MSDN: Cursor must be smaller than the display mode */
4920 if (cursor_image->resource.width > device->adapter->screen_size.cx
4921 || cursor_image->resource.height > device->adapter->screen_size.cy)
4923 WARN("Surface %p dimensions are %ux%u, but screen dimensions are %ux%u.\n",
4924 cursor_image, cursor_image->resource.width, cursor_image->resource.height,
4925 device->adapter->screen_size.cx, device->adapter->screen_size.cy);
4926 return WINED3DERR_INVALIDCALL;
4929 /* TODO: MSDN: Cursor sizes must be a power of 2 */
4931 /* Do not store the surface's pointer because the application may
4932 * release it after setting the cursor image. Windows doesn't
4933 * addref the set surface, so we can't do this either without
4934 * creating circular refcount dependencies. Copy out the gl texture
4935 * instead. */
4936 device->cursorWidth = cursor_image->resource.width;
4937 device->cursorHeight = cursor_image->resource.height;
4938 if (SUCCEEDED(wined3d_surface_map(cursor_image, &rect, NULL, WINED3DLOCK_READONLY)))
4940 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4941 const struct wined3d_format *format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
4942 struct wined3d_context *context;
4943 char *mem, *bits = rect.data;
4944 GLint intfmt = format->glInternal;
4945 GLint gl_format = format->glFormat;
4946 GLint type = format->glType;
4947 INT height = device->cursorHeight;
4948 INT width = device->cursorWidth;
4949 INT bpp = format->byte_count;
4950 INT i;
4952 /* Reformat the texture memory (pitch and width can be
4953 * different) */
4954 mem = HeapAlloc(GetProcessHeap(), 0, width * height * bpp);
4955 for(i = 0; i < height; i++)
4956 memcpy(&mem[width * bpp * i], &bits[rect.row_pitch * i], width * bpp);
4957 wined3d_surface_unmap(cursor_image);
4959 context = context_acquire(device, NULL);
4961 ENTER_GL();
4963 if (gl_info->supported[APPLE_CLIENT_STORAGE])
4965 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE);
4966 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE)");
4969 invalidate_active_texture(device, context);
4970 /* Create a new cursor texture */
4971 glGenTextures(1, &device->cursorTexture);
4972 checkGLcall("glGenTextures");
4973 context_bind_texture(context, GL_TEXTURE_2D, device->cursorTexture);
4974 /* Copy the bitmap memory into the cursor texture */
4975 glTexImage2D(GL_TEXTURE_2D, 0, intfmt, width, height, 0, gl_format, type, mem);
4976 checkGLcall("glTexImage2D");
4977 HeapFree(GetProcessHeap(), 0, mem);
4979 if (gl_info->supported[APPLE_CLIENT_STORAGE])
4981 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
4982 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
4985 LEAVE_GL();
4987 context_release(context);
4989 else
4991 FIXME("A cursor texture was not returned.\n");
4992 device->cursorTexture = 0;
4995 if (cursor_image->resource.width == 32 && cursor_image->resource.height == 32)
4997 UINT mask_size = cursor_image->resource.width * cursor_image->resource.height / 8;
4998 ICONINFO cursorInfo;
4999 DWORD *maskBits;
5000 HCURSOR cursor;
5002 /* 32-bit user32 cursors ignore the alpha channel if it's all
5003 * zeroes, and use the mask instead. Fill the mask with all ones
5004 * to ensure we still get a fully transparent cursor. */
5005 maskBits = HeapAlloc(GetProcessHeap(), 0, mask_size);
5006 memset(maskBits, 0xff, mask_size);
5007 wined3d_surface_map(cursor_image, &mapped_rect, NULL,
5008 WINED3DLOCK_NO_DIRTY_UPDATE | WINED3DLOCK_READONLY);
5009 TRACE("width: %u height: %u.\n", cursor_image->resource.width, cursor_image->resource.height);
5011 cursorInfo.fIcon = FALSE;
5012 cursorInfo.xHotspot = x_hotspot;
5013 cursorInfo.yHotspot = y_hotspot;
5014 cursorInfo.hbmMask = CreateBitmap(cursor_image->resource.width, cursor_image->resource.height,
5015 1, 1, maskBits);
5016 cursorInfo.hbmColor = CreateBitmap(cursor_image->resource.width, cursor_image->resource.height,
5017 1, 32, mapped_rect.data);
5018 wined3d_surface_unmap(cursor_image);
5019 /* Create our cursor and clean up. */
5020 cursor = CreateIconIndirect(&cursorInfo);
5021 if (cursorInfo.hbmMask) DeleteObject(cursorInfo.hbmMask);
5022 if (cursorInfo.hbmColor) DeleteObject(cursorInfo.hbmColor);
5023 if (device->hardwareCursor) DestroyCursor(device->hardwareCursor);
5024 device->hardwareCursor = cursor;
5025 if (device->bCursorVisible) SetCursor( cursor );
5026 HeapFree(GetProcessHeap(), 0, maskBits);
5030 device->xHotSpot = x_hotspot;
5031 device->yHotSpot = y_hotspot;
5032 return WINED3D_OK;
5035 void CDECL wined3d_device_set_cursor_position(struct wined3d_device *device,
5036 int x_screen_space, int y_screen_space, DWORD flags)
5038 TRACE("device %p, x %d, y %d, flags %#x.\n",
5039 device, x_screen_space, y_screen_space, flags);
5041 device->xScreenSpace = x_screen_space;
5042 device->yScreenSpace = y_screen_space;
5044 if (device->hardwareCursor)
5046 POINT pt;
5048 GetCursorPos( &pt );
5049 if (x_screen_space == pt.x && y_screen_space == pt.y)
5050 return;
5051 SetCursorPos( x_screen_space, y_screen_space );
5053 /* Switch to the software cursor if position diverges from the hardware one. */
5054 GetCursorPos( &pt );
5055 if (x_screen_space != pt.x || y_screen_space != pt.y)
5057 if (device->bCursorVisible) SetCursor( NULL );
5058 DestroyCursor( device->hardwareCursor );
5059 device->hardwareCursor = 0;
5064 BOOL CDECL wined3d_device_show_cursor(struct wined3d_device *device, BOOL show)
5066 BOOL oldVisible = device->bCursorVisible;
5068 TRACE("device %p, show %#x.\n", device, show);
5071 * When ShowCursor is first called it should make the cursor appear at the OS's last
5072 * known cursor position.
5074 if (show && !oldVisible)
5076 POINT pt;
5077 GetCursorPos(&pt);
5078 device->xScreenSpace = pt.x;
5079 device->yScreenSpace = pt.y;
5082 if (device->hardwareCursor)
5084 device->bCursorVisible = show;
5085 if (show)
5086 SetCursor(device->hardwareCursor);
5087 else
5088 SetCursor(NULL);
5090 else
5092 if (device->cursorTexture)
5093 device->bCursorVisible = show;
5096 return oldVisible;
5099 void CDECL wined3d_device_evict_managed_resources(struct wined3d_device *device)
5101 struct wined3d_resource *resource, *cursor;
5103 TRACE("device %p.\n", device);
5105 LIST_FOR_EACH_ENTRY_SAFE(resource, cursor, &device->resources, struct wined3d_resource, resource_list_entry)
5107 TRACE("Checking resource %p for eviction.\n", resource);
5109 if (resource->pool == WINED3D_POOL_MANAGED)
5111 TRACE("Evicting %p.\n", resource);
5112 resource->resource_ops->resource_unload(resource);
5116 /* Invalidate stream sources, the buffer(s) may have been evicted. */
5117 device_invalidate_state(device, STATE_STREAMSRC);
5120 static BOOL is_display_mode_supported(const struct wined3d_device *device,
5121 const struct wined3d_swapchain_desc *swapchain_desc)
5123 struct wined3d_display_mode m;
5124 UINT i, count;
5125 HRESULT hr;
5127 /* All Windowed modes are supported, as is leaving the current mode */
5128 if (swapchain_desc->windowed)
5129 return TRUE;
5130 if (!swapchain_desc->backbuffer_width)
5131 return TRUE;
5132 if (!swapchain_desc->backbuffer_height)
5133 return TRUE;
5135 count = wined3d_get_adapter_mode_count(device->wined3d, device->adapter->ordinal, WINED3DFMT_UNKNOWN);
5136 for (i = 0; i < count; ++i)
5138 memset(&m, 0, sizeof(m));
5139 hr = wined3d_enum_adapter_modes(device->wined3d, device->adapter->ordinal, WINED3DFMT_UNKNOWN, i, &m);
5140 if (FAILED(hr))
5141 ERR("Failed to enumerate adapter mode.\n");
5142 if (m.width == swapchain_desc->backbuffer_width && m.height == swapchain_desc->backbuffer_height)
5143 /* Mode found, it is supported. */
5144 return TRUE;
5146 /* Mode not found -> not supported */
5147 return FALSE;
5150 /* Do not call while under the GL lock. */
5151 static void delete_opengl_contexts(struct wined3d_device *device, struct wined3d_swapchain *swapchain)
5153 struct wined3d_resource *resource, *cursor;
5154 const struct wined3d_gl_info *gl_info;
5155 struct wined3d_context *context;
5156 struct wined3d_shader *shader;
5158 context = context_acquire(device, NULL);
5159 gl_info = context->gl_info;
5161 LIST_FOR_EACH_ENTRY_SAFE(resource, cursor, &device->resources, struct wined3d_resource, resource_list_entry)
5163 TRACE("Unloading resource %p.\n", resource);
5165 resource->resource_ops->resource_unload(resource);
5168 LIST_FOR_EACH_ENTRY(shader, &device->shaders, struct wined3d_shader, shader_list_entry)
5170 device->shader_backend->shader_destroy(shader);
5173 ENTER_GL();
5174 if (device->depth_blt_texture)
5176 glDeleteTextures(1, &device->depth_blt_texture);
5177 device->depth_blt_texture = 0;
5179 if (device->cursorTexture)
5181 glDeleteTextures(1, &device->cursorTexture);
5182 device->cursorTexture = 0;
5184 LEAVE_GL();
5186 device->blitter->free_private(device);
5187 device->frag_pipe->free_private(device);
5188 device->shader_backend->shader_free_private(device);
5189 destroy_dummy_textures(device, gl_info);
5191 context_release(context);
5193 while (device->context_count)
5195 swapchain_destroy_contexts(device->contexts[0]->swapchain);
5198 HeapFree(GetProcessHeap(), 0, swapchain->context);
5199 swapchain->context = NULL;
5202 /* Do not call while under the GL lock. */
5203 static HRESULT create_primary_opengl_context(struct wined3d_device *device, struct wined3d_swapchain *swapchain)
5205 struct wined3d_context *context;
5206 struct wined3d_surface *target;
5207 HRESULT hr;
5209 /* Recreate the primary swapchain's context */
5210 swapchain->context = HeapAlloc(GetProcessHeap(), 0, sizeof(*swapchain->context));
5211 if (!swapchain->context)
5213 ERR("Failed to allocate memory for swapchain context array.\n");
5214 return E_OUTOFMEMORY;
5217 target = swapchain->back_buffers ? swapchain->back_buffers[0] : swapchain->front_buffer;
5218 if (!(context = context_create(swapchain, target, swapchain->ds_format)))
5220 WARN("Failed to create context.\n");
5221 HeapFree(GetProcessHeap(), 0, swapchain->context);
5222 return E_FAIL;
5225 swapchain->context[0] = context;
5226 swapchain->num_contexts = 1;
5227 create_dummy_textures(device, context);
5228 context_release(context);
5230 hr = device->shader_backend->shader_alloc_private(device);
5231 if (FAILED(hr))
5233 ERR("Failed to allocate shader private data, hr %#x.\n", hr);
5234 goto err;
5237 hr = device->frag_pipe->alloc_private(device);
5238 if (FAILED(hr))
5240 ERR("Failed to allocate fragment pipe private data, hr %#x.\n", hr);
5241 device->shader_backend->shader_free_private(device);
5242 goto err;
5245 hr = device->blitter->alloc_private(device);
5246 if (FAILED(hr))
5248 ERR("Failed to allocate blitter private data, hr %#x.\n", hr);
5249 device->frag_pipe->free_private(device);
5250 device->shader_backend->shader_free_private(device);
5251 goto err;
5254 return WINED3D_OK;
5256 err:
5257 context_acquire(device, NULL);
5258 destroy_dummy_textures(device, context->gl_info);
5259 context_release(context);
5260 context_destroy(device, context);
5261 HeapFree(GetProcessHeap(), 0, swapchain->context);
5262 swapchain->num_contexts = 0;
5263 return hr;
5266 /* Do not call while under the GL lock. */
5267 HRESULT CDECL wined3d_device_reset(struct wined3d_device *device,
5268 const struct wined3d_swapchain_desc *swapchain_desc,
5269 wined3d_device_reset_cb callback)
5271 struct wined3d_resource *resource, *cursor;
5272 struct wined3d_swapchain *swapchain;
5273 struct wined3d_display_mode mode;
5274 BOOL DisplayModeChanged = FALSE;
5275 BOOL update_desc = FALSE;
5276 HRESULT hr;
5278 TRACE("device %p, swapchain_desc %p.\n", device, swapchain_desc);
5280 stateblock_unbind_resources(device->stateBlock);
5282 if (device->onscreen_depth_stencil)
5284 wined3d_surface_decref(device->onscreen_depth_stencil);
5285 device->onscreen_depth_stencil = NULL;
5288 LIST_FOR_EACH_ENTRY_SAFE(resource, cursor, &device->resources, struct wined3d_resource, resource_list_entry)
5290 TRACE("Enumerating resource %p.\n", resource);
5291 if (FAILED(hr = callback(resource)))
5292 return hr;
5295 hr = wined3d_device_get_swapchain(device, 0, &swapchain);
5296 if (FAILED(hr))
5298 ERR("Failed to get the first implicit swapchain\n");
5299 return hr;
5302 if (!is_display_mode_supported(device, swapchain_desc))
5304 WARN("Rejecting reset() call because the requested display mode is not supported.\n");
5305 WARN("Requested mode: %ux%u.\n",
5306 swapchain_desc->backbuffer_width,
5307 swapchain_desc->backbuffer_height);
5308 wined3d_swapchain_decref(swapchain);
5309 return WINED3DERR_INVALIDCALL;
5312 /* Is it necessary to recreate the gl context? Actually every setting can be changed
5313 * on an existing gl context, so there's no real need for recreation.
5315 * TODO: Figure out how Reset influences resources in D3DPOOL_DEFAULT, D3DPOOL_SYSTEMMEMORY and D3DPOOL_MANAGED
5317 * TODO: Figure out what happens to explicit swapchains, or if we have more than one implicit swapchain
5319 TRACE("New params:\n");
5320 TRACE("backbuffer_width %u\n", swapchain_desc->backbuffer_width);
5321 TRACE("backbuffer_height %u\n", swapchain_desc->backbuffer_height);
5322 TRACE("backbuffer_format %s\n", debug_d3dformat(swapchain_desc->backbuffer_format));
5323 TRACE("backbuffer_count %u\n", swapchain_desc->backbuffer_count);
5324 TRACE("multisample_type %#x\n", swapchain_desc->multisample_type);
5325 TRACE("multisample_quality %u\n", swapchain_desc->multisample_quality);
5326 TRACE("swap_effect %#x\n", swapchain_desc->swap_effect);
5327 TRACE("device_window %p\n", swapchain_desc->device_window);
5328 TRACE("windowed %#x\n", swapchain_desc->windowed);
5329 TRACE("enable_auto_depth_stencil %#x\n", swapchain_desc->enable_auto_depth_stencil);
5330 if (swapchain_desc->enable_auto_depth_stencil)
5331 TRACE("auto_depth_stencil_format %s\n", debug_d3dformat(swapchain_desc->auto_depth_stencil_format));
5332 TRACE("flags %#x\n", swapchain_desc->flags);
5333 TRACE("refresh_rate %u\n", swapchain_desc->refresh_rate);
5334 TRACE("swap_interval %u\n", swapchain_desc->swap_interval);
5335 TRACE("auto_restore_display_mode %#x\n", swapchain_desc->auto_restore_display_mode);
5337 /* No special treatment of these parameters. Just store them */
5338 swapchain->desc.swap_effect = swapchain_desc->swap_effect;
5339 swapchain->desc.flags = swapchain_desc->flags;
5340 swapchain->desc.swap_interval = swapchain_desc->swap_interval;
5341 swapchain->desc.refresh_rate = swapchain_desc->refresh_rate;
5343 /* What to do about these? */
5344 if (swapchain_desc->backbuffer_count
5345 && swapchain_desc->backbuffer_count != swapchain->desc.backbuffer_count)
5346 FIXME("Cannot change the back buffer count yet.\n");
5348 if (swapchain_desc->device_window
5349 && swapchain_desc->device_window != swapchain->desc.device_window)
5351 TRACE("Changing the device window from %p to %p.\n",
5352 swapchain->desc.device_window, swapchain_desc->device_window);
5353 swapchain->desc.device_window = swapchain_desc->device_window;
5354 swapchain->device_window = swapchain_desc->device_window;
5355 wined3d_swapchain_set_window(swapchain, NULL);
5358 if (swapchain_desc->enable_auto_depth_stencil && !device->auto_depth_stencil)
5360 HRESULT hrc;
5362 TRACE("Creating the depth stencil buffer\n");
5364 hrc = device->device_parent->ops->create_depth_stencil(device->device_parent,
5365 swapchain_desc->backbuffer_width,
5366 swapchain_desc->backbuffer_height,
5367 swapchain_desc->auto_depth_stencil_format,
5368 swapchain_desc->multisample_type,
5369 swapchain_desc->multisample_quality,
5370 FALSE,
5371 &device->auto_depth_stencil);
5372 if (FAILED(hrc))
5374 ERR("Failed to create the depth stencil buffer.\n");
5375 wined3d_swapchain_decref(swapchain);
5376 return WINED3DERR_INVALIDCALL;
5380 if (device->onscreen_depth_stencil)
5382 wined3d_surface_decref(device->onscreen_depth_stencil);
5383 device->onscreen_depth_stencil = NULL;
5386 /* Reset the depth stencil */
5387 if (swapchain_desc->enable_auto_depth_stencil)
5388 wined3d_device_set_depth_stencil(device, device->auto_depth_stencil);
5389 else
5390 wined3d_device_set_depth_stencil(device, NULL);
5392 TRACE("Resetting stateblock\n");
5393 wined3d_stateblock_decref(device->updateStateBlock);
5394 wined3d_stateblock_decref(device->stateBlock);
5396 if (swapchain_desc->windowed)
5398 mode.width = swapchain->orig_width;
5399 mode.height = swapchain->orig_height;
5400 mode.refresh_rate = 0;
5401 mode.format_id = swapchain->desc.backbuffer_format;
5403 else
5405 mode.width = swapchain_desc->backbuffer_width;
5406 mode.height = swapchain_desc->backbuffer_height;
5407 mode.refresh_rate = swapchain_desc->refresh_rate;
5408 mode.format_id = swapchain_desc->backbuffer_format;
5411 /* Should Width == 800 && Height == 0 set 800x600? */
5412 if (swapchain_desc->backbuffer_width && swapchain_desc->backbuffer_height
5413 && (swapchain_desc->backbuffer_width != swapchain->desc.backbuffer_width
5414 || swapchain_desc->backbuffer_height != swapchain->desc.backbuffer_height))
5416 if (!swapchain_desc->windowed)
5417 DisplayModeChanged = TRUE;
5419 swapchain->desc.backbuffer_width = swapchain_desc->backbuffer_width;
5420 swapchain->desc.backbuffer_height = swapchain_desc->backbuffer_height;
5421 update_desc = TRUE;
5424 if (swapchain_desc->backbuffer_format != WINED3DFMT_UNKNOWN
5425 && swapchain_desc->backbuffer_format != swapchain->desc.backbuffer_format)
5427 swapchain->desc.backbuffer_format = swapchain_desc->backbuffer_format;
5428 update_desc = TRUE;
5431 if (swapchain_desc->multisample_type != swapchain->desc.multisample_type
5432 || swapchain_desc->multisample_quality != swapchain->desc.multisample_quality)
5434 swapchain->desc.multisample_type = swapchain_desc->multisample_type;
5435 swapchain->desc.multisample_quality = swapchain_desc->multisample_quality;
5436 update_desc = TRUE;
5439 if (update_desc)
5441 UINT i;
5443 hr = wined3d_surface_update_desc(swapchain->front_buffer, swapchain->desc.backbuffer_width,
5444 swapchain->desc.backbuffer_height, swapchain->desc.backbuffer_format,
5445 swapchain->desc.multisample_type, swapchain->desc.multisample_quality);
5446 if (FAILED(hr))
5448 wined3d_swapchain_decref(swapchain);
5449 return hr;
5452 for (i = 0; i < swapchain->desc.backbuffer_count; ++i)
5454 hr = wined3d_surface_update_desc(swapchain->back_buffers[i], swapchain->desc.backbuffer_width,
5455 swapchain->desc.backbuffer_height, swapchain->desc.backbuffer_format,
5456 swapchain->desc.multisample_type, swapchain->desc.multisample_quality);
5457 if (FAILED(hr))
5459 wined3d_swapchain_decref(swapchain);
5460 return hr;
5463 if (device->auto_depth_stencil)
5465 hr = wined3d_surface_update_desc(device->auto_depth_stencil, swapchain->desc.backbuffer_width,
5466 swapchain->desc.backbuffer_height, device->auto_depth_stencil->resource.format->id,
5467 swapchain->desc.multisample_type, swapchain->desc.multisample_quality);
5468 if (FAILED(hr))
5470 wined3d_swapchain_decref(swapchain);
5471 return hr;
5476 if (device->d3d_initialized)
5477 delete_opengl_contexts(device, swapchain);
5479 if (!swapchain_desc->windowed != !swapchain->desc.windowed
5480 || DisplayModeChanged)
5482 wined3d_device_set_display_mode(device, 0, &mode);
5484 if (!swapchain_desc->windowed)
5486 if (swapchain->desc.windowed)
5488 HWND focus_window = device->create_parms.focus_window;
5489 if (!focus_window)
5490 focus_window = swapchain_desc->device_window;
5491 if (FAILED(hr = wined3d_device_acquire_focus_window(device, focus_window)))
5493 ERR("Failed to acquire focus window, hr %#x.\n", hr);
5494 wined3d_swapchain_decref(swapchain);
5495 return hr;
5498 /* switch from windowed to fs */
5499 wined3d_device_setup_fullscreen_window(device, swapchain->device_window,
5500 swapchain_desc->backbuffer_width,
5501 swapchain_desc->backbuffer_height);
5503 else
5505 /* Fullscreen -> fullscreen mode change */
5506 MoveWindow(swapchain->device_window, 0, 0,
5507 swapchain_desc->backbuffer_width,
5508 swapchain_desc->backbuffer_height,
5509 TRUE);
5512 else if (!swapchain->desc.windowed)
5514 /* Fullscreen -> windowed switch */
5515 wined3d_device_restore_fullscreen_window(device, swapchain->device_window);
5516 wined3d_device_release_focus_window(device);
5518 swapchain->desc.windowed = swapchain_desc->windowed;
5520 else if (!swapchain_desc->windowed)
5522 DWORD style = device->style;
5523 DWORD exStyle = device->exStyle;
5524 /* If we're in fullscreen, and the mode wasn't changed, we have to get the window back into
5525 * the right position. Some applications(Battlefield 2, Guild Wars) move it and then call
5526 * Reset to clear up their mess. Guild Wars also loses the device during that.
5528 device->style = 0;
5529 device->exStyle = 0;
5530 wined3d_device_setup_fullscreen_window(device, swapchain->device_window,
5531 swapchain_desc->backbuffer_width,
5532 swapchain_desc->backbuffer_height);
5533 device->style = style;
5534 device->exStyle = exStyle;
5537 /* Note: No parent needed for initial internal stateblock */
5538 hr = wined3d_stateblock_create(device, WINED3D_SBT_INIT, &device->stateBlock);
5539 if (FAILED(hr))
5540 ERR("Resetting the stateblock failed with error %#x.\n", hr);
5541 else
5542 TRACE("Created stateblock %p.\n", device->stateBlock);
5543 device->updateStateBlock = device->stateBlock;
5544 wined3d_stateblock_incref(device->updateStateBlock);
5546 stateblock_init_default_state(device->stateBlock);
5548 swapchain_update_render_to_fbo(swapchain);
5549 swapchain_update_draw_bindings(swapchain);
5551 if (device->d3d_initialized)
5552 hr = create_primary_opengl_context(device, swapchain);
5553 wined3d_swapchain_decref(swapchain);
5555 /* All done. There is no need to reload resources or shaders, this will happen automatically on the
5556 * first use
5558 return hr;
5561 HRESULT CDECL wined3d_device_set_dialog_box_mode(struct wined3d_device *device, BOOL enable_dialogs)
5563 TRACE("device %p, enable_dialogs %#x.\n", device, enable_dialogs);
5565 if (!enable_dialogs) FIXME("Dialogs cannot be disabled yet.\n");
5567 return WINED3D_OK;
5571 HRESULT CDECL wined3d_device_get_creation_parameters(const struct wined3d_device *device,
5572 struct wined3d_device_creation_parameters *parameters)
5574 TRACE("device %p, parameters %p.\n", device, parameters);
5576 *parameters = device->create_parms;
5577 return WINED3D_OK;
5580 void CDECL wined3d_device_set_gamma_ramp(const struct wined3d_device *device,
5581 UINT swapchain_idx, DWORD flags, const struct wined3d_gamma_ramp *ramp)
5583 struct wined3d_swapchain *swapchain;
5585 TRACE("device %p, swapchain_idx %u, flags %#x, ramp %p.\n",
5586 device, swapchain_idx, flags, ramp);
5588 if (SUCCEEDED(wined3d_device_get_swapchain(device, swapchain_idx, &swapchain)))
5590 wined3d_swapchain_set_gamma_ramp(swapchain, flags, ramp);
5591 wined3d_swapchain_decref(swapchain);
5595 void CDECL wined3d_device_get_gamma_ramp(const struct wined3d_device *device,
5596 UINT swapchain_idx, struct wined3d_gamma_ramp *ramp)
5598 struct wined3d_swapchain *swapchain;
5600 TRACE("device %p, swapchain_idx %u, ramp %p.\n",
5601 device, swapchain_idx, ramp);
5603 if (SUCCEEDED(wined3d_device_get_swapchain(device, swapchain_idx, &swapchain)))
5605 wined3d_swapchain_get_gamma_ramp(swapchain, ramp);
5606 wined3d_swapchain_decref(swapchain);
5610 void device_resource_add(struct wined3d_device *device, struct wined3d_resource *resource)
5612 TRACE("device %p, resource %p.\n", device, resource);
5614 list_add_head(&device->resources, &resource->resource_list_entry);
5617 static void device_resource_remove(struct wined3d_device *device, struct wined3d_resource *resource)
5619 TRACE("device %p, resource %p.\n", device, resource);
5621 list_remove(&resource->resource_list_entry);
5624 void device_resource_released(struct wined3d_device *device, struct wined3d_resource *resource)
5626 enum wined3d_resource_type type = resource->type;
5627 unsigned int i;
5629 TRACE("device %p, resource %p, type %s.\n", device, resource, debug_d3dresourcetype(type));
5631 context_resource_released(device, resource, type);
5633 switch (type)
5635 case WINED3D_RTYPE_SURFACE:
5637 struct wined3d_surface *surface = surface_from_resource(resource);
5639 if (!device->d3d_initialized) break;
5641 for (i = 0; i < device->adapter->gl_info.limits.buffers; ++i)
5643 if (device->fb.render_targets[i] == surface)
5645 ERR("Surface %p is still in use as render target %u.\n", surface, i);
5646 device->fb.render_targets[i] = NULL;
5650 if (device->fb.depth_stencil == surface)
5652 ERR("Surface %p is still in use as depth/stencil buffer.\n", surface);
5653 device->fb.depth_stencil = NULL;
5656 break;
5658 case WINED3D_RTYPE_TEXTURE:
5659 case WINED3D_RTYPE_CUBE_TEXTURE:
5660 case WINED3D_RTYPE_VOLUME_TEXTURE:
5661 for (i = 0; i < MAX_COMBINED_SAMPLERS; ++i)
5663 struct wined3d_texture *texture = wined3d_texture_from_resource(resource);
5665 if (device->stateBlock && device->stateBlock->state.textures[i] == texture)
5667 ERR("Texture %p is still in use by stateblock %p, stage %u.\n",
5668 texture, device->stateBlock, i);
5669 device->stateBlock->state.textures[i] = NULL;
5672 if (device->updateStateBlock != device->stateBlock
5673 && device->updateStateBlock->state.textures[i] == texture)
5675 ERR("Texture %p is still in use by stateblock %p, stage %u.\n",
5676 texture, device->updateStateBlock, i);
5677 device->updateStateBlock->state.textures[i] = NULL;
5680 break;
5682 case WINED3D_RTYPE_BUFFER:
5684 struct wined3d_buffer *buffer = buffer_from_resource(resource);
5686 for (i = 0; i < MAX_STREAMS; ++i)
5688 if (device->stateBlock && device->stateBlock->state.streams[i].buffer == buffer)
5690 ERR("Buffer %p is still in use by stateblock %p, stream %u.\n",
5691 buffer, device->stateBlock, i);
5692 device->stateBlock->state.streams[i].buffer = NULL;
5695 if (device->updateStateBlock != device->stateBlock
5696 && device->updateStateBlock->state.streams[i].buffer == buffer)
5698 ERR("Buffer %p is still in use by stateblock %p, stream %u.\n",
5699 buffer, device->updateStateBlock, i);
5700 device->updateStateBlock->state.streams[i].buffer = NULL;
5705 if (device->stateBlock && device->stateBlock->state.index_buffer == buffer)
5707 ERR("Buffer %p is still in use by stateblock %p as index buffer.\n",
5708 buffer, device->stateBlock);
5709 device->stateBlock->state.index_buffer = NULL;
5712 if (device->updateStateBlock != device->stateBlock
5713 && device->updateStateBlock->state.index_buffer == buffer)
5715 ERR("Buffer %p is still in use by stateblock %p as index buffer.\n",
5716 buffer, device->updateStateBlock);
5717 device->updateStateBlock->state.index_buffer = NULL;
5720 break;
5722 default:
5723 break;
5726 /* Remove the resource from the resourceStore */
5727 device_resource_remove(device, resource);
5729 TRACE("Resource released.\n");
5732 HRESULT CDECL wined3d_device_get_surface_from_dc(const struct wined3d_device *device,
5733 HDC dc, struct wined3d_surface **surface)
5735 struct wined3d_resource *resource;
5737 TRACE("device %p, dc %p, surface %p.\n", device, dc, surface);
5739 if (!dc)
5740 return WINED3DERR_INVALIDCALL;
5742 LIST_FOR_EACH_ENTRY(resource, &device->resources, struct wined3d_resource, resource_list_entry)
5744 if (resource->type == WINED3D_RTYPE_SURFACE)
5746 struct wined3d_surface *s = surface_from_resource(resource);
5748 if (s->hDC == dc)
5750 TRACE("Found surface %p for dc %p.\n", s, dc);
5751 *surface = s;
5752 return WINED3D_OK;
5757 return WINED3DERR_INVALIDCALL;
5760 HRESULT device_init(struct wined3d_device *device, struct wined3d *wined3d,
5761 UINT adapter_idx, enum wined3d_device_type device_type, HWND focus_window, DWORD flags,
5762 BYTE surface_alignment, struct wined3d_device_parent *device_parent)
5764 struct wined3d_adapter *adapter = &wined3d->adapters[adapter_idx];
5765 const struct fragment_pipeline *fragment_pipeline;
5766 struct wined3d_display_mode mode;
5767 struct shader_caps shader_caps;
5768 struct fragment_caps ffp_caps;
5769 unsigned int i;
5770 HRESULT hr;
5772 device->ref = 1;
5773 device->wined3d = wined3d;
5774 wined3d_incref(device->wined3d);
5775 device->adapter = wined3d->adapter_count ? adapter : NULL;
5776 device->device_parent = device_parent;
5777 list_init(&device->resources);
5778 list_init(&device->shaders);
5779 device->surface_alignment = surface_alignment;
5781 /* Get the initial screen setup for ddraw. */
5782 hr = wined3d_get_adapter_display_mode(wined3d, adapter_idx, &mode);
5783 if (FAILED(hr))
5785 ERR("Failed to get the adapter's display mode, hr %#x.\n", hr);
5786 wined3d_decref(device->wined3d);
5787 return hr;
5789 adapter->screen_size.cx = mode.width;
5790 adapter->screen_size.cy = mode.height;
5791 adapter->screen_format = mode.format_id;
5793 /* Save the creation parameters. */
5794 device->create_parms.adapter_idx = adapter_idx;
5795 device->create_parms.device_type = device_type;
5796 device->create_parms.focus_window = focus_window;
5797 device->create_parms.flags = flags;
5799 for (i = 0; i < PATCHMAP_SIZE; ++i) list_init(&device->patches[i]);
5801 select_shader_mode(&adapter->gl_info, &device->ps_selected_mode, &device->vs_selected_mode);
5802 device->shader_backend = adapter->shader_backend;
5804 if (device->shader_backend)
5806 device->shader_backend->shader_get_caps(&adapter->gl_info, &shader_caps);
5807 device->vshader_version = shader_caps.VertexShaderVersion;
5808 device->pshader_version = shader_caps.PixelShaderVersion;
5809 device->d3d_vshader_constantF = shader_caps.MaxVertexShaderConst;
5810 device->d3d_pshader_constantF = shader_caps.MaxPixelShaderConst;
5811 device->vs_clipping = shader_caps.VSClipping;
5813 fragment_pipeline = adapter->fragment_pipe;
5814 device->frag_pipe = fragment_pipeline;
5815 if (fragment_pipeline)
5817 fragment_pipeline->get_caps(&adapter->gl_info, &ffp_caps);
5818 device->max_ffp_textures = ffp_caps.MaxSimultaneousTextures;
5820 hr = compile_state_table(device->StateTable, device->multistate_funcs, &adapter->gl_info,
5821 ffp_vertexstate_template, fragment_pipeline, misc_state_template);
5822 if (FAILED(hr))
5824 ERR("Failed to compile state table, hr %#x.\n", hr);
5825 wined3d_decref(device->wined3d);
5826 return hr;
5829 device->blitter = adapter->blitter;
5831 hr = wined3d_stateblock_create(device, WINED3D_SBT_INIT, &device->stateBlock);
5832 if (FAILED(hr))
5834 WARN("Failed to create stateblock.\n");
5835 for (i = 0; i < sizeof(device->multistate_funcs) / sizeof(device->multistate_funcs[0]); ++i)
5837 HeapFree(GetProcessHeap(), 0, device->multistate_funcs[i]);
5839 wined3d_decref(device->wined3d);
5840 return hr;
5843 TRACE("Created stateblock %p.\n", device->stateBlock);
5844 device->updateStateBlock = device->stateBlock;
5845 wined3d_stateblock_incref(device->updateStateBlock);
5847 return WINED3D_OK;
5851 void device_invalidate_state(const struct wined3d_device *device, DWORD state)
5853 DWORD rep = device->StateTable[state].representative;
5854 struct wined3d_context *context;
5855 DWORD idx;
5856 BYTE shift;
5857 UINT i;
5859 for (i = 0; i < device->context_count; ++i)
5861 context = device->contexts[i];
5862 if(isStateDirty(context, rep)) continue;
5864 context->dirtyArray[context->numDirtyEntries++] = rep;
5865 idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
5866 shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
5867 context->isStateDirty[idx] |= (1 << shift);
5871 void get_drawable_size_fbo(const struct wined3d_context *context, UINT *width, UINT *height)
5873 /* The drawable size of a fbo target is the opengl texture size, which is the power of two size. */
5874 *width = context->current_rt->pow2Width;
5875 *height = context->current_rt->pow2Height;
5878 void get_drawable_size_backbuffer(const struct wined3d_context *context, UINT *width, UINT *height)
5880 const struct wined3d_swapchain *swapchain = context->swapchain;
5881 /* The drawable size of a backbuffer / aux buffer offscreen target is the size of the
5882 * current context's drawable, which is the size of the back buffer of the swapchain
5883 * the active context belongs to. */
5884 *width = swapchain->desc.backbuffer_width;
5885 *height = swapchain->desc.backbuffer_height;
5888 LRESULT device_process_message(struct wined3d_device *device, HWND window, BOOL unicode,
5889 UINT message, WPARAM wparam, LPARAM lparam, WNDPROC proc)
5891 if (device->filter_messages)
5893 TRACE("Filtering message: window %p, message %#x, wparam %#lx, lparam %#lx.\n",
5894 window, message, wparam, lparam);
5895 if (unicode)
5896 return DefWindowProcW(window, message, wparam, lparam);
5897 else
5898 return DefWindowProcA(window, message, wparam, lparam);
5901 if (message == WM_DESTROY)
5903 TRACE("unregister window %p.\n", window);
5904 wined3d_unregister_window(window);
5906 if (InterlockedCompareExchangePointer((void **)&device->focus_window, NULL, window) != window)
5907 ERR("Window %p is not the focus window for device %p.\n", window, device);
5909 else if (message == WM_DISPLAYCHANGE)
5911 device->device_parent->ops->mode_changed(device->device_parent);
5914 if (unicode)
5915 return CallWindowProcW(proc, window, message, wparam, lparam);
5916 else
5917 return CallWindowProcA(proc, window, message, wparam, lparam);