wined3d: Reset render target bindings in wined3d_device_reset().
[wine] / dlls / wined3d / device.c
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
11  *
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.
16  *
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.
21  *
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
25  */
26
27 #include "config.h"
28 #include "wine/port.h"
29
30 #include <stdio.h>
31 #ifdef HAVE_FLOAT_H
32 # include <float.h>
33 #endif
34
35 #include "wined3d_private.h"
36
37 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
38
39 /* Define the default light parameters as specified by MSDN. */
40 const struct wined3d_light WINED3D_default_light =
41 {
42     WINED3D_LIGHT_DIRECTIONAL,  /* Type */
43     { 1.0f, 1.0f, 1.0f, 0.0f }, /* Diffuse r,g,b,a */
44     { 0.0f, 0.0f, 0.0f, 0.0f }, /* Specular r,g,b,a */
45     { 0.0f, 0.0f, 0.0f, 0.0f }, /* Ambient r,g,b,a, */
46     { 0.0f, 0.0f, 0.0f },       /* Position x,y,z */
47     { 0.0f, 0.0f, 1.0f },       /* Direction x,y,z */
48     0.0f,                       /* Range */
49     0.0f,                       /* Falloff */
50     0.0f, 0.0f, 0.0f,           /* Attenuation 0,1,2 */
51     0.0f,                       /* Theta */
52     0.0f                        /* Phi */
53 };
54
55 /**********************************************************
56  * Global variable / Constants follow
57  **********************************************************/
58 const struct wined3d_matrix identity =
59 {{{
60     1.0f, 0.0f, 0.0f, 0.0f,
61     0.0f, 1.0f, 0.0f, 0.0f,
62     0.0f, 0.0f, 1.0f, 0.0f,
63     0.0f, 0.0f, 0.0f, 1.0f,
64 }}};  /* When needed for comparisons */
65
66 /* Note that except for WINED3DPT_POINTLIST and WINED3DPT_LINELIST these
67  * actually have the same values in GL and D3D. */
68 static GLenum gl_primitive_type_from_d3d(enum wined3d_primitive_type primitive_type)
69 {
70     switch(primitive_type)
71     {
72         case WINED3D_PT_POINTLIST:
73             return GL_POINTS;
74
75         case WINED3D_PT_LINELIST:
76             return GL_LINES;
77
78         case WINED3D_PT_LINESTRIP:
79             return GL_LINE_STRIP;
80
81         case WINED3D_PT_TRIANGLELIST:
82             return GL_TRIANGLES;
83
84         case WINED3D_PT_TRIANGLESTRIP:
85             return GL_TRIANGLE_STRIP;
86
87         case WINED3D_PT_TRIANGLEFAN:
88             return GL_TRIANGLE_FAN;
89
90         case WINED3D_PT_LINELIST_ADJ:
91             return GL_LINES_ADJACENCY_ARB;
92
93         case WINED3D_PT_LINESTRIP_ADJ:
94             return GL_LINE_STRIP_ADJACENCY_ARB;
95
96         case WINED3D_PT_TRIANGLELIST_ADJ:
97             return GL_TRIANGLES_ADJACENCY_ARB;
98
99         case WINED3D_PT_TRIANGLESTRIP_ADJ:
100             return GL_TRIANGLE_STRIP_ADJACENCY_ARB;
101
102         default:
103             FIXME("Unhandled primitive type %s\n", debug_d3dprimitivetype(primitive_type));
104             return GL_NONE;
105     }
106 }
107
108 static enum wined3d_primitive_type d3d_primitive_type_from_gl(GLenum primitive_type)
109 {
110     switch(primitive_type)
111     {
112         case GL_POINTS:
113             return WINED3D_PT_POINTLIST;
114
115         case GL_LINES:
116             return WINED3D_PT_LINELIST;
117
118         case GL_LINE_STRIP:
119             return WINED3D_PT_LINESTRIP;
120
121         case GL_TRIANGLES:
122             return WINED3D_PT_TRIANGLELIST;
123
124         case GL_TRIANGLE_STRIP:
125             return WINED3D_PT_TRIANGLESTRIP;
126
127         case GL_TRIANGLE_FAN:
128             return WINED3D_PT_TRIANGLEFAN;
129
130         case GL_LINES_ADJACENCY_ARB:
131             return WINED3D_PT_LINELIST_ADJ;
132
133         case GL_LINE_STRIP_ADJACENCY_ARB:
134             return WINED3D_PT_LINESTRIP_ADJ;
135
136         case GL_TRIANGLES_ADJACENCY_ARB:
137             return WINED3D_PT_TRIANGLELIST_ADJ;
138
139         case GL_TRIANGLE_STRIP_ADJACENCY_ARB:
140             return WINED3D_PT_TRIANGLESTRIP_ADJ;
141
142         default:
143             FIXME("Unhandled primitive type %s\n", debug_d3dprimitivetype(primitive_type));
144             return WINED3D_PT_UNDEFINED;
145     }
146 }
147
148 static BOOL fixed_get_input(BYTE usage, BYTE usage_idx, unsigned int *regnum)
149 {
150     if ((usage == WINED3D_DECL_USAGE_POSITION || usage == WINED3D_DECL_USAGE_POSITIONT) && !usage_idx)
151         *regnum = WINED3D_FFP_POSITION;
152     else if (usage == WINED3D_DECL_USAGE_BLEND_WEIGHT && !usage_idx)
153         *regnum = WINED3D_FFP_BLENDWEIGHT;
154     else if (usage == WINED3D_DECL_USAGE_BLEND_INDICES && !usage_idx)
155         *regnum = WINED3D_FFP_BLENDINDICES;
156     else if (usage == WINED3D_DECL_USAGE_NORMAL && !usage_idx)
157         *regnum = WINED3D_FFP_NORMAL;
158     else if (usage == WINED3D_DECL_USAGE_PSIZE && !usage_idx)
159         *regnum = WINED3D_FFP_PSIZE;
160     else if (usage == WINED3D_DECL_USAGE_COLOR && !usage_idx)
161         *regnum = WINED3D_FFP_DIFFUSE;
162     else if (usage == WINED3D_DECL_USAGE_COLOR && usage_idx == 1)
163         *regnum = WINED3D_FFP_SPECULAR;
164     else if (usage == WINED3D_DECL_USAGE_TEXCOORD && usage_idx < WINED3DDP_MAXTEXCOORD)
165         *regnum = WINED3D_FFP_TEXCOORD0 + usage_idx;
166     else
167     {
168         FIXME("Unsupported input stream [usage=%s, usage_idx=%u]\n", debug_d3ddeclusage(usage), usage_idx);
169         *regnum = ~0U;
170         return FALSE;
171     }
172
173     return TRUE;
174 }
175
176 /* Context activation is done by the caller. */
177 void device_stream_info_from_declaration(struct wined3d_device *device, struct wined3d_stream_info *stream_info)
178 {
179     const struct wined3d_state *state = &device->stateBlock->state;
180     /* We need to deal with frequency data! */
181     struct wined3d_vertex_declaration *declaration = state->vertex_declaration;
182     BOOL use_vshader;
183     unsigned int i;
184
185     stream_info->use_map = 0;
186     stream_info->swizzle_map = 0;
187
188     /* Check for transformed vertices, disable vertex shader if present. */
189     stream_info->position_transformed = declaration->position_transformed;
190     use_vshader = state->vertex_shader && !declaration->position_transformed;
191
192     /* Translate the declaration into strided data. */
193     for (i = 0; i < declaration->element_count; ++i)
194     {
195         const struct wined3d_vertex_declaration_element *element = &declaration->elements[i];
196         const struct wined3d_stream_state *stream = &state->streams[element->input_slot];
197         struct wined3d_buffer *buffer = stream->buffer;
198         struct wined3d_bo_address data;
199         BOOL stride_used;
200         unsigned int idx;
201         DWORD stride;
202
203         TRACE("%p Element %p (%u of %u)\n", declaration->elements,
204                 element, i + 1, declaration->element_count);
205
206         if (!buffer) continue;
207
208         data.buffer_object = 0;
209         data.addr = NULL;
210
211         stride = stream->stride;
212         if (state->user_stream)
213         {
214             TRACE("Stream %u is UP, %p\n", element->input_slot, buffer);
215             data.buffer_object = 0;
216             data.addr = (BYTE *)buffer;
217         }
218         else
219         {
220             TRACE("Stream %u isn't UP, %p\n", element->input_slot, buffer);
221             buffer_get_memory(buffer, &device->adapter->gl_info, &data);
222
223             /* Can't use vbo's if the base vertex index is negative. OpenGL doesn't accept negative offsets
224              * (or rather offsets bigger than the vbo, because the pointer is unsigned), so use system memory
225              * sources. In most sane cases the pointer - offset will still be > 0, otherwise it will wrap
226              * around to some big value. Hope that with the indices, the driver wraps it back internally. If
227              * not, drawStridedSlow is needed, including a vertex buffer path. */
228             if (state->load_base_vertex_index < 0)
229             {
230                 WARN("load_base_vertex_index is < 0 (%d), not using VBOs.\n",
231                         state->load_base_vertex_index);
232                 data.buffer_object = 0;
233                 data.addr = buffer_get_sysmem(buffer, &device->adapter->gl_info);
234                 if ((UINT_PTR)data.addr < -state->load_base_vertex_index * stride)
235                 {
236                     FIXME("System memory vertex data load offset is negative!\n");
237                 }
238             }
239         }
240         data.addr += element->offset;
241
242         TRACE("offset %u input_slot %u usage_idx %d\n", element->offset, element->input_slot, element->usage_idx);
243
244         if (use_vshader)
245         {
246             if (element->output_slot == ~0U)
247             {
248                 /* TODO: Assuming vertexdeclarations are usually used with the
249                  * same or a similar shader, it might be worth it to store the
250                  * last used output slot and try that one first. */
251                 stride_used = vshader_get_input(state->vertex_shader,
252                         element->usage, element->usage_idx, &idx);
253             }
254             else
255             {
256                 idx = element->output_slot;
257                 stride_used = TRUE;
258             }
259         }
260         else
261         {
262             if (!element->ffp_valid)
263             {
264                 WARN("Skipping unsupported fixed function element of format %s and usage %s\n",
265                         debug_d3dformat(element->format->id), debug_d3ddeclusage(element->usage));
266                 stride_used = FALSE;
267             }
268             else
269             {
270                 stride_used = fixed_get_input(element->usage, element->usage_idx, &idx);
271             }
272         }
273
274         if (stride_used)
275         {
276             TRACE("Load %s array %u [usage %s, usage_idx %u, "
277                     "input_slot %u, offset %u, stride %u, format %s, buffer_object %u]\n",
278                     use_vshader ? "shader": "fixed function", idx,
279                     debug_d3ddeclusage(element->usage), element->usage_idx, element->input_slot,
280                     element->offset, stride, debug_d3dformat(element->format->id), data.buffer_object);
281
282             data.addr += stream->offset;
283
284             stream_info->elements[idx].format = element->format;
285             stream_info->elements[idx].data = data;
286             stream_info->elements[idx].stride = stride;
287             stream_info->elements[idx].stream_idx = element->input_slot;
288
289             if (!device->adapter->gl_info.supported[ARB_VERTEX_ARRAY_BGRA]
290                     && element->format->id == WINED3DFMT_B8G8R8A8_UNORM)
291             {
292                 stream_info->swizzle_map |= 1 << idx;
293             }
294             stream_info->use_map |= 1 << idx;
295         }
296     }
297
298     device->num_buffer_queries = 0;
299     if (!state->user_stream)
300     {
301         WORD map = stream_info->use_map;
302         stream_info->all_vbo = 1;
303
304         /* PreLoad all the vertex buffers. */
305         for (i = 0; map; map >>= 1, ++i)
306         {
307             struct wined3d_stream_info_element *element;
308             struct wined3d_buffer *buffer;
309
310             if (!(map & 1)) continue;
311
312             element = &stream_info->elements[i];
313             buffer = state->streams[element->stream_idx].buffer;
314             wined3d_buffer_preload(buffer);
315
316             /* If the preload dropped the buffer object, update the stream info. */
317             if (buffer->buffer_object != element->data.buffer_object)
318             {
319                 element->data.buffer_object = 0;
320                 element->data.addr = buffer_get_sysmem(buffer, &device->adapter->gl_info)
321                         + (ptrdiff_t)element->data.addr;
322             }
323
324             if (!buffer->buffer_object)
325                 stream_info->all_vbo = 0;
326
327             if (buffer->query)
328                 device->buffer_queries[device->num_buffer_queries++] = buffer->query;
329         }
330     }
331     else
332     {
333         stream_info->all_vbo = 0;
334     }
335 }
336
337 static void stream_info_element_from_strided(const struct wined3d_gl_info *gl_info,
338         const struct wined3d_strided_element *strided, struct wined3d_stream_info_element *e)
339 {
340     e->data.addr = strided->data;
341     e->data.buffer_object = 0;
342     e->format = wined3d_get_format(gl_info, strided->format);
343     e->stride = strided->stride;
344     e->stream_idx = 0;
345 }
346
347 static void device_stream_info_from_strided(const struct wined3d_gl_info *gl_info,
348         const struct wined3d_strided_data *strided, struct wined3d_stream_info *stream_info)
349 {
350     unsigned int i;
351
352     memset(stream_info, 0, sizeof(*stream_info));
353
354     if (strided->position.data)
355         stream_info_element_from_strided(gl_info, &strided->position, &stream_info->elements[WINED3D_FFP_POSITION]);
356     if (strided->normal.data)
357         stream_info_element_from_strided(gl_info, &strided->normal, &stream_info->elements[WINED3D_FFP_NORMAL]);
358     if (strided->diffuse.data)
359         stream_info_element_from_strided(gl_info, &strided->diffuse, &stream_info->elements[WINED3D_FFP_DIFFUSE]);
360     if (strided->specular.data)
361         stream_info_element_from_strided(gl_info, &strided->specular, &stream_info->elements[WINED3D_FFP_SPECULAR]);
362
363     for (i = 0; i < WINED3DDP_MAXTEXCOORD; ++i)
364     {
365         if (strided->tex_coords[i].data)
366             stream_info_element_from_strided(gl_info, &strided->tex_coords[i],
367                     &stream_info->elements[WINED3D_FFP_TEXCOORD0 + i]);
368     }
369
370     stream_info->position_transformed = strided->position_transformed;
371
372     for (i = 0; i < sizeof(stream_info->elements) / sizeof(*stream_info->elements); ++i)
373     {
374         if (!stream_info->elements[i].format) continue;
375
376         if (!gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
377                 && stream_info->elements[i].format->id == WINED3DFMT_B8G8R8A8_UNORM)
378         {
379             stream_info->swizzle_map |= 1 << i;
380         }
381         stream_info->use_map |= 1 << i;
382     }
383 }
384
385 static void device_trace_strided_stream_info(const struct wined3d_stream_info *stream_info)
386 {
387     TRACE("Strided Data:\n");
388     TRACE_STRIDED(stream_info, WINED3D_FFP_POSITION);
389     TRACE_STRIDED(stream_info, WINED3D_FFP_BLENDWEIGHT);
390     TRACE_STRIDED(stream_info, WINED3D_FFP_BLENDINDICES);
391     TRACE_STRIDED(stream_info, WINED3D_FFP_NORMAL);
392     TRACE_STRIDED(stream_info, WINED3D_FFP_PSIZE);
393     TRACE_STRIDED(stream_info, WINED3D_FFP_DIFFUSE);
394     TRACE_STRIDED(stream_info, WINED3D_FFP_SPECULAR);
395     TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD0);
396     TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD1);
397     TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD2);
398     TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD3);
399     TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD4);
400     TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD5);
401     TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD6);
402     TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD7);
403 }
404
405 /* Context activation is done by the caller. */
406 void device_update_stream_info(struct wined3d_device *device, const struct wined3d_gl_info *gl_info)
407 {
408     struct wined3d_stream_info *stream_info = &device->strided_streams;
409     const struct wined3d_state *state = &device->stateBlock->state;
410     DWORD prev_all_vbo = stream_info->all_vbo;
411
412     if (device->up_strided)
413     {
414         /* Note: this is a ddraw fixed-function code path. */
415         TRACE("=============================== Strided Input ================================\n");
416         device_stream_info_from_strided(gl_info, device->up_strided, stream_info);
417         if (TRACE_ON(d3d)) device_trace_strided_stream_info(stream_info);
418     }
419     else
420     {
421         TRACE("============================= Vertex Declaration =============================\n");
422         device_stream_info_from_declaration(device, stream_info);
423     }
424
425     if (state->vertex_shader && !stream_info->position_transformed)
426     {
427         if (state->vertex_declaration->half_float_conv_needed && !stream_info->all_vbo)
428         {
429             TRACE("Using drawStridedSlow with vertex shaders for FLOAT16 conversion.\n");
430             device->useDrawStridedSlow = TRUE;
431         }
432         else
433         {
434             device->useDrawStridedSlow = FALSE;
435         }
436     }
437     else
438     {
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));
442
443         if ((stream_info->position_transformed || (stream_info->use_map & slow_mask)) && !stream_info->all_vbo)
444         {
445             device->useDrawStridedSlow = TRUE;
446         }
447         else
448         {
449             device->useDrawStridedSlow = FALSE;
450         }
451     }
452
453     if (prev_all_vbo != stream_info->all_vbo)
454         device_invalidate_state(device, STATE_INDEXBUFFER);
455 }
456
457 static void device_preload_texture(const struct wined3d_state *state, unsigned int idx)
458 {
459     struct wined3d_texture *texture;
460     enum WINED3DSRGB srgb;
461
462     if (!(texture = state->textures[idx])) return;
463     srgb = state->sampler_states[idx][WINED3D_SAMP_SRGB_TEXTURE] ? SRGB_SRGB : SRGB_RGB;
464     texture->texture_ops->texture_preload(texture, srgb);
465 }
466
467 void device_preload_textures(const struct wined3d_device *device)
468 {
469     const struct wined3d_state *state = &device->stateBlock->state;
470     unsigned int i;
471
472     if (use_vs(state))
473     {
474         for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
475         {
476             if (state->vertex_shader->reg_maps.sampler_type[i])
477                 device_preload_texture(state, MAX_FRAGMENT_SAMPLERS + i);
478         }
479     }
480
481     if (use_ps(state))
482     {
483         for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
484         {
485             if (state->pixel_shader->reg_maps.sampler_type[i])
486                 device_preload_texture(state, i);
487         }
488     }
489     else
490     {
491         WORD ffu_map = device->fixed_function_usage_map;
492
493         for (i = 0; ffu_map; ffu_map >>= 1, ++i)
494         {
495             if (ffu_map & 1)
496                 device_preload_texture(state, i);
497         }
498     }
499 }
500
501 BOOL device_context_add(struct wined3d_device *device, struct wined3d_context *context)
502 {
503     struct wined3d_context **new_array;
504
505     TRACE("Adding context %p.\n", context);
506
507     if (!device->contexts) new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*new_array));
508     else new_array = HeapReAlloc(GetProcessHeap(), 0, device->contexts,
509             sizeof(*new_array) * (device->context_count + 1));
510
511     if (!new_array)
512     {
513         ERR("Failed to grow the context array.\n");
514         return FALSE;
515     }
516
517     new_array[device->context_count++] = context;
518     device->contexts = new_array;
519     return TRUE;
520 }
521
522 void device_context_remove(struct wined3d_device *device, struct wined3d_context *context)
523 {
524     struct wined3d_context **new_array;
525     BOOL found = FALSE;
526     UINT i;
527
528     TRACE("Removing context %p.\n", context);
529
530     for (i = 0; i < device->context_count; ++i)
531     {
532         if (device->contexts[i] == context)
533         {
534             found = TRUE;
535             break;
536         }
537     }
538
539     if (!found)
540     {
541         ERR("Context %p doesn't exist in context array.\n", context);
542         return;
543     }
544
545     if (!--device->context_count)
546     {
547         HeapFree(GetProcessHeap(), 0, device->contexts);
548         device->contexts = NULL;
549         return;
550     }
551
552     memmove(&device->contexts[i], &device->contexts[i + 1], (device->context_count - i) * sizeof(*device->contexts));
553     new_array = HeapReAlloc(GetProcessHeap(), 0, device->contexts, device->context_count * sizeof(*device->contexts));
554     if (!new_array)
555     {
556         ERR("Failed to shrink context array. Oh well.\n");
557         return;
558     }
559
560     device->contexts = new_array;
561 }
562
563 /* Do not call while under the GL lock. */
564 void device_switch_onscreen_ds(struct wined3d_device *device,
565         struct wined3d_context *context, struct wined3d_surface *depth_stencil)
566 {
567     if (device->onscreen_depth_stencil)
568     {
569         surface_load_ds_location(device->onscreen_depth_stencil, context, SFLAG_INTEXTURE);
570
571         surface_modify_ds_location(device->onscreen_depth_stencil, SFLAG_INTEXTURE,
572                 device->onscreen_depth_stencil->ds_current_size.cx,
573                 device->onscreen_depth_stencil->ds_current_size.cy);
574         wined3d_surface_decref(device->onscreen_depth_stencil);
575     }
576     device->onscreen_depth_stencil = depth_stencil;
577     wined3d_surface_incref(device->onscreen_depth_stencil);
578 }
579
580 static BOOL is_full_clear(const struct wined3d_surface *target, const RECT *draw_rect, const RECT *clear_rect)
581 {
582     /* partial draw rect */
583     if (draw_rect->left || draw_rect->top
584             || draw_rect->right < target->resource.width
585             || draw_rect->bottom < target->resource.height)
586         return FALSE;
587
588     /* partial clear rect */
589     if (clear_rect && (clear_rect->left > 0 || clear_rect->top > 0
590             || clear_rect->right < target->resource.width
591             || clear_rect->bottom < target->resource.height))
592         return FALSE;
593
594     return TRUE;
595 }
596
597 static void prepare_ds_clear(struct wined3d_surface *ds, struct wined3d_context *context,
598         DWORD location, const RECT *draw_rect, UINT rect_count, const RECT *clear_rect, RECT *out_rect)
599 {
600     RECT current_rect, r;
601
602     if (ds->flags & location)
603         SetRect(&current_rect, 0, 0,
604                 ds->ds_current_size.cx,
605                 ds->ds_current_size.cy);
606     else
607         SetRectEmpty(&current_rect);
608
609     IntersectRect(&r, draw_rect, &current_rect);
610     if (EqualRect(&r, draw_rect))
611     {
612         /* current_rect âŠ‡ draw_rect, modify only. */
613         SetRect(out_rect, 0, 0, ds->ds_current_size.cx, ds->ds_current_size.cy);
614         return;
615     }
616
617     if (EqualRect(&r, &current_rect))
618     {
619         /* draw_rect âŠ‡ current_rect, test if we're doing a full clear. */
620
621         if (!clear_rect)
622         {
623             /* Full clear, modify only. */
624             *out_rect = *draw_rect;
625             return;
626         }
627
628         IntersectRect(&r, draw_rect, clear_rect);
629         if (EqualRect(&r, draw_rect))
630         {
631             /* clear_rect âŠ‡ draw_rect, modify only. */
632             *out_rect = *draw_rect;
633             return;
634         }
635     }
636
637     /* Full load. */
638     surface_load_ds_location(ds, context, location);
639     SetRect(out_rect, 0, 0, ds->ds_current_size.cx, ds->ds_current_size.cy);
640 }
641
642 /* Do not call while under the GL lock. */
643 void device_clear_render_targets(struct wined3d_device *device, UINT rt_count, const struct wined3d_fb_state *fb,
644         UINT rect_count, const RECT *rects, const RECT *draw_rect, DWORD flags, const struct wined3d_color *color,
645         float depth, DWORD stencil)
646 {
647     const RECT *clear_rect = (rect_count > 0 && rects) ? (const RECT *)rects : NULL;
648     struct wined3d_surface *target = rt_count ? fb->render_targets[0] : NULL;
649     UINT drawable_width, drawable_height;
650     struct wined3d_context *context;
651     GLbitfield clear_mask = 0;
652     BOOL render_offscreen;
653     unsigned int i;
654     RECT ds_rect;
655
656     /* When we're clearing parts of the drawable, make sure that the target surface is well up to date in the
657      * drawable. After the clear we'll mark the drawable up to date, so we have to make sure that this is true
658      * for the cleared parts, and the untouched parts.
659      *
660      * If we're clearing the whole target there is no need to copy it into the drawable, it will be overwritten
661      * anyway. If we're not clearing the color buffer we don't have to copy either since we're not going to set
662      * the drawable up to date. We have to check all settings that limit the clear area though. Do not bother
663      * checking all this if the dest surface is in the drawable anyway. */
664     if (flags & WINED3DCLEAR_TARGET && !is_full_clear(target, draw_rect, clear_rect))
665     {
666         for (i = 0; i < rt_count; ++i)
667         {
668             struct wined3d_surface *rt = fb->render_targets[i];
669             if (rt)
670                 surface_load_location(rt, rt->draw_binding, NULL);
671         }
672     }
673
674     context = context_acquire(device, target);
675     if (!context->valid)
676     {
677         context_release(context);
678         WARN("Invalid context, skipping clear.\n");
679         return;
680     }
681
682     if (target)
683     {
684         render_offscreen = context->render_offscreen;
685         target->get_drawable_size(context, &drawable_width, &drawable_height);
686     }
687     else
688     {
689         render_offscreen = TRUE;
690         drawable_width = fb->depth_stencil->pow2Width;
691         drawable_height = fb->depth_stencil->pow2Height;
692     }
693
694     if (flags & WINED3DCLEAR_ZBUFFER)
695     {
696         DWORD location = render_offscreen ? fb->depth_stencil->draw_binding : SFLAG_INDRAWABLE;
697
698         if (!render_offscreen && fb->depth_stencil != device->onscreen_depth_stencil)
699             device_switch_onscreen_ds(device, context, fb->depth_stencil);
700         prepare_ds_clear(fb->depth_stencil, context, location,
701                 draw_rect, rect_count, clear_rect, &ds_rect);
702     }
703
704     if (!context_apply_clear_state(context, device, rt_count, fb))
705     {
706         context_release(context);
707         WARN("Failed to apply clear state, skipping clear.\n");
708         return;
709     }
710
711     ENTER_GL();
712
713     /* Only set the values up once, as they are not changing. */
714     if (flags & WINED3DCLEAR_STENCIL)
715     {
716         if (context->gl_info->supported[EXT_STENCIL_TWO_SIDE])
717         {
718             glDisable(GL_STENCIL_TEST_TWO_SIDE_EXT);
719             context_invalidate_state(context, STATE_RENDER(WINED3D_RS_TWOSIDEDSTENCILMODE));
720         }
721         glStencilMask(~0U);
722         context_invalidate_state(context, STATE_RENDER(WINED3D_RS_STENCILWRITEMASK));
723         glClearStencil(stencil);
724         checkGLcall("glClearStencil");
725         clear_mask = clear_mask | GL_STENCIL_BUFFER_BIT;
726     }
727
728     if (flags & WINED3DCLEAR_ZBUFFER)
729     {
730         DWORD location = render_offscreen ? fb->depth_stencil->draw_binding : SFLAG_INDRAWABLE;
731
732         surface_modify_ds_location(fb->depth_stencil, location, ds_rect.right, ds_rect.bottom);
733
734         glDepthMask(GL_TRUE);
735         context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ZWRITEENABLE));
736         glClearDepth(depth);
737         checkGLcall("glClearDepth");
738         clear_mask = clear_mask | GL_DEPTH_BUFFER_BIT;
739     }
740
741     if (flags & WINED3DCLEAR_TARGET)
742     {
743         for (i = 0; i < rt_count; ++i)
744         {
745             struct wined3d_surface *rt = fb->render_targets[i];
746
747             if (rt)
748                 surface_modify_location(rt, rt->draw_binding, TRUE);
749         }
750
751         glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
752         context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE));
753         context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE1));
754         context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE2));
755         context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE3));
756         glClearColor(color->r, color->g, color->b, color->a);
757         checkGLcall("glClearColor");
758         clear_mask = clear_mask | GL_COLOR_BUFFER_BIT;
759     }
760
761     if (!clear_rect)
762     {
763         if (render_offscreen)
764         {
765             glScissor(draw_rect->left, draw_rect->top,
766                     draw_rect->right - draw_rect->left, draw_rect->bottom - draw_rect->top);
767         }
768         else
769         {
770             glScissor(draw_rect->left, drawable_height - draw_rect->bottom,
771                         draw_rect->right - draw_rect->left, draw_rect->bottom - draw_rect->top);
772         }
773         checkGLcall("glScissor");
774         glClear(clear_mask);
775         checkGLcall("glClear");
776     }
777     else
778     {
779         RECT current_rect;
780
781         /* Now process each rect in turn. */
782         for (i = 0; i < rect_count; ++i)
783         {
784             /* Note that GL uses lower left, width/height. */
785             IntersectRect(&current_rect, draw_rect, &clear_rect[i]);
786
787             TRACE("clear_rect[%u] %s, current_rect %s.\n", i,
788                     wine_dbgstr_rect(&clear_rect[i]),
789                     wine_dbgstr_rect(&current_rect));
790
791             /* Tests show that rectangles where x1 > x2 or y1 > y2 are ignored silently.
792              * The rectangle is not cleared, no error is returned, but further rectangles are
793              * still cleared if they are valid. */
794             if (current_rect.left > current_rect.right || current_rect.top > current_rect.bottom)
795             {
796                 TRACE("Rectangle with negative dimensions, ignoring.\n");
797                 continue;
798             }
799
800             if (render_offscreen)
801             {
802                 glScissor(current_rect.left, current_rect.top,
803                         current_rect.right - current_rect.left, current_rect.bottom - current_rect.top);
804             }
805             else
806             {
807                 glScissor(current_rect.left, drawable_height - current_rect.bottom,
808                           current_rect.right - current_rect.left, current_rect.bottom - current_rect.top);
809             }
810             checkGLcall("glScissor");
811
812             glClear(clear_mask);
813             checkGLcall("glClear");
814         }
815     }
816
817     LEAVE_GL();
818
819     if (wined3d_settings.strict_draw_ordering || (flags & WINED3DCLEAR_TARGET
820             && target->container.type == WINED3D_CONTAINER_SWAPCHAIN
821             && target->container.u.swapchain->front_buffer == target))
822         wglFlush(); /* Flush to ensure ordering across contexts. */
823
824     context_release(context);
825 }
826
827 ULONG CDECL wined3d_device_incref(struct wined3d_device *device)
828 {
829     ULONG refcount = InterlockedIncrement(&device->ref);
830
831     TRACE("%p increasing refcount to %u.\n", device, refcount);
832
833     return refcount;
834 }
835
836 ULONG CDECL wined3d_device_decref(struct wined3d_device *device)
837 {
838     ULONG refcount = InterlockedDecrement(&device->ref);
839
840     TRACE("%p decreasing refcount to %u.\n", device, refcount);
841
842     if (!refcount)
843     {
844         struct wined3d_stateblock *stateblock;
845         UINT i;
846
847         if (wined3d_stateblock_decref(device->updateStateBlock)
848                 && device->updateStateBlock != device->stateBlock)
849             FIXME("Something's still holding the update stateblock.\n");
850         device->updateStateBlock = NULL;
851
852         stateblock = device->stateBlock;
853         device->stateBlock = NULL;
854         if (wined3d_stateblock_decref(stateblock))
855             FIXME("Something's still holding the stateblock.\n");
856
857         for (i = 0; i < sizeof(device->multistate_funcs) / sizeof(device->multistate_funcs[0]); ++i)
858         {
859             HeapFree(GetProcessHeap(), 0, device->multistate_funcs[i]);
860             device->multistate_funcs[i] = NULL;
861         }
862
863         if (!list_empty(&device->resources))
864         {
865             struct wined3d_resource *resource;
866
867             FIXME("Device released with resources still bound, acceptable but unexpected.\n");
868
869             LIST_FOR_EACH_ENTRY(resource, &device->resources, struct wined3d_resource, resource_list_entry)
870             {
871                 FIXME("Leftover resource %p with type %s (%#x).\n",
872                         resource, debug_d3dresourcetype(resource->type), resource->type);
873             }
874         }
875
876         if (device->contexts)
877             ERR("Context array not freed!\n");
878         if (device->hardwareCursor)
879             DestroyCursor(device->hardwareCursor);
880         device->hardwareCursor = 0;
881
882         wined3d_decref(device->wined3d);
883         device->wined3d = NULL;
884         HeapFree(GetProcessHeap(), 0, device);
885         TRACE("Freed device %p.\n", device);
886     }
887
888     return refcount;
889 }
890
891 UINT CDECL wined3d_device_get_swapchain_count(const struct wined3d_device *device)
892 {
893     TRACE("device %p.\n", device);
894
895     return device->swapchain_count;
896 }
897
898 HRESULT CDECL wined3d_device_get_swapchain(const struct wined3d_device *device,
899         UINT swapchain_idx, struct wined3d_swapchain **swapchain)
900 {
901     TRACE("device %p, swapchain_idx %u, swapchain %p.\n",
902             device, swapchain_idx, swapchain);
903
904     if (swapchain_idx >= device->swapchain_count)
905     {
906         WARN("swapchain_idx %u >= swapchain_count %u.\n",
907                 swapchain_idx, device->swapchain_count);
908         *swapchain = NULL;
909
910         return WINED3DERR_INVALIDCALL;
911     }
912
913     *swapchain = device->swapchains[swapchain_idx];
914     wined3d_swapchain_incref(*swapchain);
915     TRACE("Returning %p.\n", *swapchain);
916
917     return WINED3D_OK;
918 }
919
920 static void device_load_logo(struct wined3d_device *device, const char *filename)
921 {
922     struct wined3d_color_key color_key;
923     HBITMAP hbm;
924     BITMAP bm;
925     HRESULT hr;
926     HDC dcb = NULL, dcs = NULL;
927
928     hbm = LoadImageA(NULL, filename, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE | LR_CREATEDIBSECTION);
929     if(hbm)
930     {
931         GetObjectA(hbm, sizeof(BITMAP), &bm);
932         dcb = CreateCompatibleDC(NULL);
933         if(!dcb) goto out;
934         SelectObject(dcb, hbm);
935     }
936     else
937     {
938         /* Create a 32x32 white surface to indicate that wined3d is used, but the specified image
939          * couldn't be loaded
940          */
941         memset(&bm, 0, sizeof(bm));
942         bm.bmWidth = 32;
943         bm.bmHeight = 32;
944     }
945
946     hr = wined3d_surface_create(device, bm.bmWidth, bm.bmHeight, WINED3DFMT_B5G6R5_UNORM, 0, 0,
947             WINED3D_POOL_DEFAULT, WINED3D_MULTISAMPLE_NONE, 0, WINED3D_SURFACE_TYPE_OPENGL, WINED3D_SURFACE_MAPPABLE,
948             NULL, &wined3d_null_parent_ops, &device->logo_surface);
949     if (FAILED(hr))
950     {
951         ERR("Wine logo requested, but failed to create surface, hr %#x.\n", hr);
952         goto out;
953     }
954
955     if (dcb)
956     {
957         if (FAILED(hr = wined3d_surface_getdc(device->logo_surface, &dcs)))
958             goto out;
959         BitBlt(dcs, 0, 0, bm.bmWidth, bm.bmHeight, dcb, 0, 0, SRCCOPY);
960         wined3d_surface_releasedc(device->logo_surface, dcs);
961
962         color_key.color_space_low_value = 0;
963         color_key.color_space_high_value = 0;
964         wined3d_surface_set_color_key(device->logo_surface, WINEDDCKEY_SRCBLT, &color_key);
965     }
966     else
967     {
968         const struct wined3d_color c = {1.0f, 1.0f, 1.0f, 1.0f};
969         /* Fill the surface with a white color to show that wined3d is there */
970         wined3d_device_color_fill(device, device->logo_surface, NULL, &c);
971     }
972
973 out:
974     if (dcb) DeleteDC(dcb);
975     if (hbm) DeleteObject(hbm);
976 }
977
978 /* Context activation is done by the caller. */
979 static void create_dummy_textures(struct wined3d_device *device, struct wined3d_context *context)
980 {
981     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
982     unsigned int i, j, count;
983     /* Under DirectX you can sample even if no texture is bound, whereas
984      * OpenGL will only allow that when a valid texture is bound.
985      * We emulate this by creating dummy textures and binding them
986      * to each texture stage when the currently set D3D texture is NULL. */
987     ENTER_GL();
988
989     if (gl_info->supported[APPLE_CLIENT_STORAGE])
990     {
991         /* The dummy texture does not have client storage backing */
992         glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE);
993         checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE)");
994     }
995
996     count = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers);
997     for (i = 0; i < count; ++i)
998     {
999         DWORD color = 0x000000ff;
1000
1001         /* Make appropriate texture active */
1002         context_active_texture(context, gl_info, i);
1003
1004         glGenTextures(1, &device->dummy_texture_2d[i]);
1005         checkGLcall("glGenTextures");
1006         TRACE("Dummy 2D texture %u given name %u.\n", i, device->dummy_texture_2d[i]);
1007
1008         glBindTexture(GL_TEXTURE_2D, device->dummy_texture_2d[i]);
1009         checkGLcall("glBindTexture");
1010
1011         glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 1, 1, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, &color);
1012         checkGLcall("glTexImage2D");
1013
1014         if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1015         {
1016             glGenTextures(1, &device->dummy_texture_rect[i]);
1017             checkGLcall("glGenTextures");
1018             TRACE("Dummy rectangle texture %u given name %u.\n", i, device->dummy_texture_rect[i]);
1019
1020             glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_texture_rect[i]);
1021             checkGLcall("glBindTexture");
1022
1023             glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGBA8, 1, 1, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, &color);
1024             checkGLcall("glTexImage2D");
1025         }
1026
1027         if (gl_info->supported[EXT_TEXTURE3D])
1028         {
1029             glGenTextures(1, &device->dummy_texture_3d[i]);
1030             checkGLcall("glGenTextures");
1031             TRACE("Dummy 3D texture %u given name %u.\n", i, device->dummy_texture_3d[i]);
1032
1033             glBindTexture(GL_TEXTURE_3D, device->dummy_texture_3d[i]);
1034             checkGLcall("glBindTexture");
1035
1036             GL_EXTCALL(glTexImage3DEXT(GL_TEXTURE_3D, 0, GL_RGBA8, 1, 1, 1, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, &color));
1037             checkGLcall("glTexImage3D");
1038         }
1039
1040         if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1041         {
1042             glGenTextures(1, &device->dummy_texture_cube[i]);
1043             checkGLcall("glGenTextures");
1044             TRACE("Dummy cube texture %u given name %u.\n", i, device->dummy_texture_cube[i]);
1045
1046             glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_texture_cube[i]);
1047             checkGLcall("glBindTexture");
1048
1049             for (j = GL_TEXTURE_CUBE_MAP_POSITIVE_X; j <= GL_TEXTURE_CUBE_MAP_NEGATIVE_Z; ++j)
1050             {
1051                 glTexImage2D(j, 0, GL_RGBA8, 1, 1, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, &color);
1052                 checkGLcall("glTexImage2D");
1053             }
1054         }
1055     }
1056
1057     if (gl_info->supported[APPLE_CLIENT_STORAGE])
1058     {
1059         /* Re-enable because if supported it is enabled by default */
1060         glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
1061         checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
1062     }
1063
1064     LEAVE_GL();
1065 }
1066
1067 /* Context activation is done by the caller. */
1068 static void destroy_dummy_textures(struct wined3d_device *device, const struct wined3d_gl_info *gl_info)
1069 {
1070     unsigned int count = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers);
1071
1072     ENTER_GL();
1073     if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1074     {
1075         glDeleteTextures(count, device->dummy_texture_cube);
1076         checkGLcall("glDeleteTextures(count, device->dummy_texture_cube)");
1077     }
1078
1079     if (gl_info->supported[EXT_TEXTURE3D])
1080     {
1081         glDeleteTextures(count, device->dummy_texture_3d);
1082         checkGLcall("glDeleteTextures(count, device->dummy_texture_3d)");
1083     }
1084
1085     if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1086     {
1087         glDeleteTextures(count, device->dummy_texture_rect);
1088         checkGLcall("glDeleteTextures(count, device->dummy_texture_rect)");
1089     }
1090
1091     glDeleteTextures(count, device->dummy_texture_2d);
1092     checkGLcall("glDeleteTextures(count, device->dummy_texture_2d)");
1093     LEAVE_GL();
1094
1095     memset(device->dummy_texture_cube, 0, gl_info->limits.textures * sizeof(*device->dummy_texture_cube));
1096     memset(device->dummy_texture_3d, 0, gl_info->limits.textures * sizeof(*device->dummy_texture_3d));
1097     memset(device->dummy_texture_rect, 0, gl_info->limits.textures * sizeof(*device->dummy_texture_rect));
1098     memset(device->dummy_texture_2d, 0, gl_info->limits.textures * sizeof(*device->dummy_texture_2d));
1099 }
1100
1101 static LONG fullscreen_style(LONG style)
1102 {
1103     /* Make sure the window is managed, otherwise we won't get keyboard input. */
1104     style |= WS_POPUP | WS_SYSMENU;
1105     style &= ~(WS_CAPTION | WS_THICKFRAME);
1106
1107     return style;
1108 }
1109
1110 static LONG fullscreen_exstyle(LONG exstyle)
1111 {
1112     /* Filter out window decorations. */
1113     exstyle &= ~(WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE);
1114
1115     return exstyle;
1116 }
1117
1118 void CDECL wined3d_device_setup_fullscreen_window(struct wined3d_device *device, HWND window, UINT w, UINT h)
1119 {
1120     BOOL filter_messages;
1121     LONG style, exstyle;
1122
1123     TRACE("Setting up window %p for fullscreen mode.\n", window);
1124
1125     if (device->style || device->exStyle)
1126     {
1127         ERR("Changing the window style for window %p, but another style (%08x, %08x) is already stored.\n",
1128                 window, device->style, device->exStyle);
1129     }
1130
1131     device->style = GetWindowLongW(window, GWL_STYLE);
1132     device->exStyle = GetWindowLongW(window, GWL_EXSTYLE);
1133
1134     style = fullscreen_style(device->style);
1135     exstyle = fullscreen_exstyle(device->exStyle);
1136
1137     TRACE("Old style was %08x, %08x, setting to %08x, %08x.\n",
1138             device->style, device->exStyle, style, exstyle);
1139
1140     filter_messages = device->filter_messages;
1141     device->filter_messages = TRUE;
1142
1143     SetWindowLongW(window, GWL_STYLE, style);
1144     SetWindowLongW(window, GWL_EXSTYLE, exstyle);
1145     SetWindowPos(window, HWND_TOP, 0, 0, w, h, SWP_FRAMECHANGED | SWP_SHOWWINDOW | SWP_NOACTIVATE);
1146
1147     device->filter_messages = filter_messages;
1148 }
1149
1150 void CDECL wined3d_device_restore_fullscreen_window(struct wined3d_device *device, HWND window)
1151 {
1152     BOOL filter_messages;
1153     LONG style, exstyle;
1154
1155     if (!device->style && !device->exStyle) return;
1156
1157     TRACE("Restoring window style of window %p to %08x, %08x.\n",
1158             window, device->style, device->exStyle);
1159
1160     style = GetWindowLongW(window, GWL_STYLE);
1161     exstyle = GetWindowLongW(window, GWL_EXSTYLE);
1162
1163     filter_messages = device->filter_messages;
1164     device->filter_messages = TRUE;
1165
1166     /* Only restore the style if the application didn't modify it during the
1167      * fullscreen phase. Some applications change it before calling Reset()
1168      * when switching between windowed and fullscreen modes (HL2), some
1169      * depend on the original style (Eve Online). */
1170     if (style == fullscreen_style(device->style) && exstyle == fullscreen_exstyle(device->exStyle))
1171     {
1172         SetWindowLongW(window, GWL_STYLE, device->style);
1173         SetWindowLongW(window, GWL_EXSTYLE, device->exStyle);
1174     }
1175     SetWindowPos(window, 0, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
1176
1177     device->filter_messages = filter_messages;
1178
1179     /* Delete the old values. */
1180     device->style = 0;
1181     device->exStyle = 0;
1182 }
1183
1184 HRESULT CDECL wined3d_device_acquire_focus_window(struct wined3d_device *device, HWND window)
1185 {
1186     TRACE("device %p, window %p.\n", device, window);
1187
1188     if (!wined3d_register_window(window, device))
1189     {
1190         ERR("Failed to register window %p.\n", window);
1191         return E_FAIL;
1192     }
1193
1194     InterlockedExchangePointer((void **)&device->focus_window, window);
1195     SetWindowPos(window, 0, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
1196
1197     return WINED3D_OK;
1198 }
1199
1200 void CDECL wined3d_device_release_focus_window(struct wined3d_device *device)
1201 {
1202     TRACE("device %p.\n", device);
1203
1204     if (device->focus_window) wined3d_unregister_window(device->focus_window);
1205     InterlockedExchangePointer((void **)&device->focus_window, NULL);
1206 }
1207
1208 HRESULT CDECL wined3d_device_init_3d(struct wined3d_device *device,
1209         struct wined3d_swapchain_desc *swapchain_desc)
1210 {
1211     static const struct wined3d_color black = {0.0f, 0.0f, 0.0f, 0.0f};
1212     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1213     struct wined3d_swapchain *swapchain = NULL;
1214     struct wined3d_context *context;
1215     HRESULT hr;
1216     DWORD state;
1217     unsigned int i;
1218
1219     TRACE("device %p, swapchain_desc %p.\n", device, swapchain_desc);
1220
1221     if (device->d3d_initialized)
1222         return WINED3DERR_INVALIDCALL;
1223     if (!device->adapter->opengl)
1224         return WINED3DERR_INVALIDCALL;
1225
1226     device->valid_rt_mask = 0;
1227     for (i = 0; i < gl_info->limits.buffers; ++i)
1228         device->valid_rt_mask |= (1 << i);
1229     device->fb.render_targets = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1230             sizeof(*device->fb.render_targets) * gl_info->limits.buffers);
1231
1232     /* Initialize the texture unit mapping to a 1:1 mapping */
1233     for (state = 0; state < MAX_COMBINED_SAMPLERS; ++state)
1234     {
1235         if (state < gl_info->limits.fragment_samplers)
1236         {
1237             device->texUnitMap[state] = state;
1238             device->rev_tex_unit_map[state] = state;
1239         }
1240         else
1241         {
1242             device->texUnitMap[state] = WINED3D_UNMAPPED_STAGE;
1243             device->rev_tex_unit_map[state] = WINED3D_UNMAPPED_STAGE;
1244         }
1245     }
1246
1247     /* Setup the implicit swapchain. This also initializes a context. */
1248     TRACE("Creating implicit swapchain\n");
1249     hr = device->device_parent->ops->create_swapchain(device->device_parent,
1250             swapchain_desc, &swapchain);
1251     if (FAILED(hr))
1252     {
1253         WARN("Failed to create implicit swapchain\n");
1254         goto err_out;
1255     }
1256
1257     device->swapchain_count = 1;
1258     device->swapchains = HeapAlloc(GetProcessHeap(), 0, device->swapchain_count * sizeof(*device->swapchains));
1259     if (!device->swapchains)
1260     {
1261         ERR("Out of memory!\n");
1262         goto err_out;
1263     }
1264     device->swapchains[0] = swapchain;
1265
1266     if (swapchain->back_buffers && swapchain->back_buffers[0])
1267     {
1268         TRACE("Setting rendertarget to %p.\n", swapchain->back_buffers);
1269         device->fb.render_targets[0] = swapchain->back_buffers[0];
1270     }
1271     else
1272     {
1273         TRACE("Setting rendertarget to %p.\n", swapchain->front_buffer);
1274         device->fb.render_targets[0] = swapchain->front_buffer;
1275     }
1276     wined3d_surface_incref(device->fb.render_targets[0]);
1277
1278     /* Depth Stencil support */
1279     device->fb.depth_stencil = device->auto_depth_stencil;
1280     if (device->fb.depth_stencil)
1281         wined3d_surface_incref(device->fb.depth_stencil);
1282
1283     hr = device->shader_backend->shader_alloc_private(device);
1284     if (FAILED(hr))
1285     {
1286         TRACE("Shader private data couldn't be allocated\n");
1287         goto err_out;
1288     }
1289     hr = device->frag_pipe->alloc_private(device);
1290     if (FAILED(hr))
1291     {
1292         TRACE("Fragment pipeline private data couldn't be allocated\n");
1293         goto err_out;
1294     }
1295     hr = device->blitter->alloc_private(device);
1296     if (FAILED(hr))
1297     {
1298         TRACE("Blitter private data couldn't be allocated\n");
1299         goto err_out;
1300     }
1301
1302     /* Set up some starting GL setup */
1303
1304     /* Setup all the devices defaults */
1305     stateblock_init_default_state(device->stateBlock);
1306
1307     context = context_acquire(device, swapchain->front_buffer);
1308
1309     create_dummy_textures(device, context);
1310
1311     ENTER_GL();
1312
1313     /* Initialize the current view state */
1314     device->view_ident = 1;
1315     device->contexts[0]->last_was_rhw = 0;
1316
1317     switch (wined3d_settings.offscreen_rendering_mode)
1318     {
1319         case ORM_FBO:
1320             device->offscreenBuffer = GL_COLOR_ATTACHMENT0;
1321             break;
1322
1323         case ORM_BACKBUFFER:
1324         {
1325             if (context_get_current()->aux_buffers > 0)
1326             {
1327                 TRACE("Using auxiliary buffer for offscreen rendering\n");
1328                 device->offscreenBuffer = GL_AUX0;
1329             }
1330             else
1331             {
1332                 TRACE("Using back buffer for offscreen rendering\n");
1333                 device->offscreenBuffer = GL_BACK;
1334             }
1335         }
1336     }
1337
1338     TRACE("All defaults now set up, leaving 3D init.\n");
1339     LEAVE_GL();
1340
1341     context_release(context);
1342
1343     /* Clear the screen */
1344     wined3d_device_clear(device, 0, NULL, WINED3DCLEAR_TARGET
1345             | (swapchain_desc->enable_auto_depth_stencil ? WINED3DCLEAR_ZBUFFER | WINED3DCLEAR_STENCIL : 0),
1346             &black, 1.0f, 0);
1347
1348     device->d3d_initialized = TRUE;
1349
1350     if (wined3d_settings.logo)
1351         device_load_logo(device, wined3d_settings.logo);
1352     return WINED3D_OK;
1353
1354 err_out:
1355     HeapFree(GetProcessHeap(), 0, device->fb.render_targets);
1356     HeapFree(GetProcessHeap(), 0, device->swapchains);
1357     device->swapchain_count = 0;
1358     if (swapchain)
1359         wined3d_swapchain_decref(swapchain);
1360     if (device->blit_priv)
1361         device->blitter->free_private(device);
1362     if (device->fragment_priv)
1363         device->frag_pipe->free_private(device);
1364     if (device->shader_priv)
1365         device->shader_backend->shader_free_private(device);
1366
1367     return hr;
1368 }
1369
1370 HRESULT CDECL wined3d_device_init_gdi(struct wined3d_device *device,
1371         struct wined3d_swapchain_desc *swapchain_desc)
1372 {
1373     struct wined3d_swapchain *swapchain = NULL;
1374     HRESULT hr;
1375
1376     TRACE("device %p, swapchain_desc %p.\n", device, swapchain_desc);
1377
1378     /* Setup the implicit swapchain */
1379     TRACE("Creating implicit swapchain\n");
1380     hr = device->device_parent->ops->create_swapchain(device->device_parent,
1381             swapchain_desc, &swapchain);
1382     if (FAILED(hr))
1383     {
1384         WARN("Failed to create implicit swapchain\n");
1385         goto err_out;
1386     }
1387
1388     device->swapchain_count = 1;
1389     device->swapchains = HeapAlloc(GetProcessHeap(), 0, device->swapchain_count * sizeof(*device->swapchains));
1390     if (!device->swapchains)
1391     {
1392         ERR("Out of memory!\n");
1393         goto err_out;
1394     }
1395     device->swapchains[0] = swapchain;
1396     return WINED3D_OK;
1397
1398 err_out:
1399     wined3d_swapchain_decref(swapchain);
1400     return hr;
1401 }
1402
1403 HRESULT CDECL wined3d_device_uninit_3d(struct wined3d_device *device)
1404 {
1405     struct wined3d_resource *resource, *cursor;
1406     const struct wined3d_gl_info *gl_info;
1407     struct wined3d_context *context;
1408     struct wined3d_surface *surface;
1409     UINT i;
1410
1411     TRACE("device %p.\n", device);
1412
1413     if (!device->d3d_initialized)
1414         return WINED3DERR_INVALIDCALL;
1415
1416     /* Force making the context current again, to verify it is still valid
1417      * (workaround for broken drivers) */
1418     context_set_current(NULL);
1419     /* I don't think that the interface guarantees that the device is destroyed from the same thread
1420      * it was created. Thus make sure a context is active for the glDelete* calls
1421      */
1422     context = context_acquire(device, NULL);
1423     gl_info = context->gl_info;
1424
1425     if (device->logo_surface)
1426         wined3d_surface_decref(device->logo_surface);
1427
1428     stateblock_unbind_resources(device->stateBlock);
1429
1430     /* Unload resources */
1431     LIST_FOR_EACH_ENTRY_SAFE(resource, cursor, &device->resources, struct wined3d_resource, resource_list_entry)
1432     {
1433         TRACE("Unloading resource %p.\n", resource);
1434
1435         resource->resource_ops->resource_unload(resource);
1436     }
1437
1438     TRACE("Deleting high order patches\n");
1439     for (i = 0; i < PATCHMAP_SIZE; ++i)
1440     {
1441         struct wined3d_rect_patch *patch;
1442         struct list *e1, *e2;
1443
1444         LIST_FOR_EACH_SAFE(e1, e2, &device->patches[i])
1445         {
1446             patch = LIST_ENTRY(e1, struct wined3d_rect_patch, entry);
1447             wined3d_device_delete_patch(device, patch->Handle);
1448         }
1449     }
1450
1451     /* Delete the mouse cursor texture */
1452     if (device->cursorTexture)
1453     {
1454         ENTER_GL();
1455         glDeleteTextures(1, &device->cursorTexture);
1456         LEAVE_GL();
1457         device->cursorTexture = 0;
1458     }
1459
1460     /* Destroy the depth blt resources, they will be invalid after the reset. Also free shader
1461      * private data, it might contain opengl pointers
1462      */
1463     if (device->depth_blt_texture)
1464     {
1465         ENTER_GL();
1466         glDeleteTextures(1, &device->depth_blt_texture);
1467         LEAVE_GL();
1468         device->depth_blt_texture = 0;
1469     }
1470
1471     /* Destroy the shader backend. Note that this has to happen after all shaders are destroyed. */
1472     device->blitter->free_private(device);
1473     device->frag_pipe->free_private(device);
1474     device->shader_backend->shader_free_private(device);
1475
1476     /* Release the buffers (with sanity checks)*/
1477     if (device->onscreen_depth_stencil)
1478     {
1479         surface = device->onscreen_depth_stencil;
1480         device->onscreen_depth_stencil = NULL;
1481         wined3d_surface_decref(surface);
1482     }
1483
1484     if (device->fb.depth_stencil)
1485     {
1486         surface = device->fb.depth_stencil;
1487
1488         TRACE("Releasing depth/stencil buffer %p.\n", surface);
1489
1490         device->fb.depth_stencil = NULL;
1491         wined3d_surface_decref(surface);
1492     }
1493
1494     if (device->auto_depth_stencil)
1495     {
1496         surface = device->auto_depth_stencil;
1497         device->auto_depth_stencil = NULL;
1498         if (wined3d_surface_decref(surface))
1499             FIXME("Something's still holding the auto depth stencil buffer (%p).\n", surface);
1500     }
1501
1502     for (i = 1; i < gl_info->limits.buffers; ++i)
1503     {
1504         wined3d_device_set_render_target(device, i, NULL, FALSE);
1505     }
1506
1507     surface = device->fb.render_targets[0];
1508     TRACE("Setting rendertarget 0 to NULL\n");
1509     device->fb.render_targets[0] = NULL;
1510     TRACE("Releasing the render target at %p\n", surface);
1511     wined3d_surface_decref(surface);
1512
1513     context_release(context);
1514
1515     for (i = 0; i < device->swapchain_count; ++i)
1516     {
1517         TRACE("Releasing the implicit swapchain %u.\n", i);
1518         if (wined3d_swapchain_decref(device->swapchains[i]))
1519             FIXME("Something's still holding the implicit swapchain.\n");
1520     }
1521
1522     HeapFree(GetProcessHeap(), 0, device->swapchains);
1523     device->swapchains = NULL;
1524     device->swapchain_count = 0;
1525
1526     HeapFree(GetProcessHeap(), 0, device->fb.render_targets);
1527     device->fb.render_targets = NULL;
1528
1529     device->d3d_initialized = FALSE;
1530
1531     return WINED3D_OK;
1532 }
1533
1534 HRESULT CDECL wined3d_device_uninit_gdi(struct wined3d_device *device)
1535 {
1536     unsigned int i;
1537
1538     for (i = 0; i < device->swapchain_count; ++i)
1539     {
1540         TRACE("Releasing the implicit swapchain %u.\n", i);
1541         if (wined3d_swapchain_decref(device->swapchains[i]))
1542             FIXME("Something's still holding the implicit swapchain.\n");
1543     }
1544
1545     HeapFree(GetProcessHeap(), 0, device->swapchains);
1546     device->swapchains = NULL;
1547     device->swapchain_count = 0;
1548     return WINED3D_OK;
1549 }
1550
1551 /* Enables thread safety in the wined3d device and its resources. Called by DirectDraw
1552  * from SetCooperativeLevel if DDSCL_MULTITHREADED is specified, and by d3d8/9 from
1553  * CreateDevice if D3DCREATE_MULTITHREADED is passed.
1554  *
1555  * There is no way to deactivate thread safety once it is enabled.
1556  */
1557 void CDECL wined3d_device_set_multithreaded(struct wined3d_device *device)
1558 {
1559     TRACE("device %p.\n", device);
1560
1561     /* For now just store the flag (needed in case of ddraw). */
1562     device->create_parms.flags |= WINED3DCREATE_MULTITHREADED;
1563 }
1564
1565 HRESULT CDECL wined3d_device_set_display_mode(struct wined3d_device *device,
1566         UINT swapchain_idx, const struct wined3d_display_mode *mode)
1567 {
1568     struct wined3d_adapter *adapter = device->adapter;
1569     const struct wined3d_format *format = wined3d_get_format(&adapter->gl_info, mode->format_id);
1570     DEVMODEW devmode;
1571     LONG ret;
1572     RECT clip_rc;
1573
1574     TRACE("device %p, swapchain_idx %u, mode %p (%ux%u@%u %s).\n", device, swapchain_idx, mode,
1575             mode->width, mode->height, mode->refresh_rate, debug_d3dformat(mode->format_id));
1576
1577     /* Resize the screen even without a window:
1578      * The app could have unset it with SetCooperativeLevel, but not called
1579      * RestoreDisplayMode first. Then the release will call RestoreDisplayMode,
1580      * but we don't have any hwnd
1581      */
1582
1583     memset(&devmode, 0, sizeof(devmode));
1584     devmode.dmSize = sizeof(devmode);
1585     devmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
1586     devmode.dmBitsPerPel = format->byte_count * CHAR_BIT;
1587     devmode.dmPelsWidth = mode->width;
1588     devmode.dmPelsHeight = mode->height;
1589
1590     devmode.dmDisplayFrequency = mode->refresh_rate;
1591     if (mode->refresh_rate)
1592         devmode.dmFields |= DM_DISPLAYFREQUENCY;
1593
1594     /* Only change the mode if necessary */
1595     if (adapter->screen_size.cx == mode->width && adapter->screen_size.cy == mode->height
1596             && adapter->screen_format == mode->format_id && !mode->refresh_rate)
1597         return WINED3D_OK;
1598
1599     ret = ChangeDisplaySettingsExW(NULL, &devmode, NULL, CDS_FULLSCREEN, NULL);
1600     if (ret != DISP_CHANGE_SUCCESSFUL)
1601     {
1602         if (devmode.dmDisplayFrequency)
1603         {
1604             WARN("ChangeDisplaySettingsExW failed, trying without the refresh rate\n");
1605             devmode.dmFields &= ~DM_DISPLAYFREQUENCY;
1606             devmode.dmDisplayFrequency = 0;
1607             ret = ChangeDisplaySettingsExW(NULL, &devmode, NULL, CDS_FULLSCREEN, NULL) != DISP_CHANGE_SUCCESSFUL;
1608         }
1609         if(ret != DISP_CHANGE_SUCCESSFUL) {
1610             return WINED3DERR_NOTAVAILABLE;
1611         }
1612     }
1613
1614     /* Store the new values */
1615     adapter->screen_size.cx = mode->width;
1616     adapter->screen_size.cy = mode->height;
1617     adapter->screen_format = mode->format_id;
1618
1619     /* And finally clip mouse to our screen */
1620     SetRect(&clip_rc, 0, 0, mode->width, mode->height);
1621     ClipCursor(&clip_rc);
1622
1623     return WINED3D_OK;
1624 }
1625
1626 HRESULT CDECL wined3d_device_get_wined3d(const struct wined3d_device *device, struct wined3d **wined3d)
1627 {
1628     TRACE("device %p, wined3d %p.\n", device, wined3d);
1629
1630     *wined3d = device->wined3d;
1631     wined3d_incref(*wined3d);
1632
1633     TRACE("Returning %p.\n", *wined3d);
1634
1635     return WINED3D_OK;
1636 }
1637
1638 UINT CDECL wined3d_device_get_available_texture_mem(const struct wined3d_device *device)
1639 {
1640     TRACE("device %p.\n", device);
1641
1642     TRACE("Emulating %d MB, returning %d MB left.\n",
1643             device->adapter->TextureRam / (1024 * 1024),
1644             (device->adapter->TextureRam - device->adapter->UsedTextureRam) / (1024 * 1024));
1645
1646     return device->adapter->TextureRam - device->adapter->UsedTextureRam;
1647 }
1648
1649 HRESULT CDECL wined3d_device_set_stream_source(struct wined3d_device *device, UINT stream_idx,
1650         struct wined3d_buffer *buffer, UINT offset, UINT stride)
1651 {
1652     struct wined3d_stream_state *stream;
1653     struct wined3d_buffer *prev_buffer;
1654
1655     TRACE("device %p, stream_idx %u, buffer %p, offset %u, stride %u.\n",
1656             device, stream_idx, buffer, offset, stride);
1657
1658     if (stream_idx >= MAX_STREAMS)
1659     {
1660         WARN("Stream index %u out of range.\n", stream_idx);
1661         return WINED3DERR_INVALIDCALL;
1662     }
1663     else if (offset & 0x3)
1664     {
1665         WARN("Offset %u is not 4 byte aligned.\n", offset);
1666         return WINED3DERR_INVALIDCALL;
1667     }
1668
1669     stream = &device->updateStateBlock->state.streams[stream_idx];
1670     prev_buffer = stream->buffer;
1671
1672     device->updateStateBlock->changed.streamSource |= 1 << stream_idx;
1673
1674     if (prev_buffer == buffer
1675             && stream->stride == stride
1676             && stream->offset == offset)
1677     {
1678        TRACE("Application is setting the old values over, nothing to do.\n");
1679        return WINED3D_OK;
1680     }
1681
1682     stream->buffer = buffer;
1683     if (buffer)
1684     {
1685         stream->stride = stride;
1686         stream->offset = offset;
1687     }
1688
1689     /* Handle recording of state blocks. */
1690     if (device->isRecordingState)
1691     {
1692         TRACE("Recording... not performing anything.\n");
1693         if (buffer)
1694             wined3d_buffer_incref(buffer);
1695         if (prev_buffer)
1696             wined3d_buffer_decref(prev_buffer);
1697         return WINED3D_OK;
1698     }
1699
1700     if (buffer)
1701     {
1702         InterlockedIncrement(&buffer->resource.bind_count);
1703         wined3d_buffer_incref(buffer);
1704     }
1705     if (prev_buffer)
1706     {
1707         InterlockedDecrement(&prev_buffer->resource.bind_count);
1708         wined3d_buffer_decref(prev_buffer);
1709     }
1710
1711     device_invalidate_state(device, STATE_STREAMSRC);
1712
1713     return WINED3D_OK;
1714 }
1715
1716 HRESULT CDECL wined3d_device_get_stream_source(const struct wined3d_device *device,
1717         UINT stream_idx, struct wined3d_buffer **buffer, UINT *offset, UINT *stride)
1718 {
1719     struct wined3d_stream_state *stream;
1720
1721     TRACE("device %p, stream_idx %u, buffer %p, offset %p, stride %p.\n",
1722             device, stream_idx, buffer, offset, stride);
1723
1724     if (stream_idx >= MAX_STREAMS)
1725     {
1726         WARN("Stream index %u out of range.\n", stream_idx);
1727         return WINED3DERR_INVALIDCALL;
1728     }
1729
1730     stream = &device->stateBlock->state.streams[stream_idx];
1731     *buffer = stream->buffer;
1732     if (*buffer)
1733         wined3d_buffer_incref(*buffer);
1734     if (offset)
1735         *offset = stream->offset;
1736     *stride = stream->stride;
1737
1738     return WINED3D_OK;
1739 }
1740
1741 HRESULT CDECL wined3d_device_set_stream_source_freq(struct wined3d_device *device, UINT stream_idx, UINT divider)
1742 {
1743     struct wined3d_stream_state *stream;
1744     UINT old_flags, old_freq;
1745
1746     TRACE("device %p, stream_idx %u, divider %#x.\n", device, stream_idx, divider);
1747
1748     /* Verify input. At least in d3d9 this is invalid. */
1749     if ((divider & WINED3DSTREAMSOURCE_INSTANCEDATA) && (divider & WINED3DSTREAMSOURCE_INDEXEDDATA))
1750     {
1751         WARN("INSTANCEDATA and INDEXEDDATA were set, returning D3DERR_INVALIDCALL.\n");
1752         return WINED3DERR_INVALIDCALL;
1753     }
1754     if ((divider & WINED3DSTREAMSOURCE_INSTANCEDATA) && !stream_idx)
1755     {
1756         WARN("INSTANCEDATA used on stream 0, returning D3DERR_INVALIDCALL.\n");
1757         return WINED3DERR_INVALIDCALL;
1758     }
1759     if (!divider)
1760     {
1761         WARN("Divider is 0, returning D3DERR_INVALIDCALL.\n");
1762         return WINED3DERR_INVALIDCALL;
1763     }
1764
1765     stream = &device->updateStateBlock->state.streams[stream_idx];
1766     old_flags = stream->flags;
1767     old_freq = stream->frequency;
1768
1769     stream->flags = divider & (WINED3DSTREAMSOURCE_INSTANCEDATA | WINED3DSTREAMSOURCE_INDEXEDDATA);
1770     stream->frequency = divider & 0x7fffff;
1771
1772     device->updateStateBlock->changed.streamFreq |= 1 << stream_idx;
1773
1774     if (stream->frequency != old_freq || stream->flags != old_flags)
1775         device_invalidate_state(device, STATE_STREAMSRC);
1776
1777     return WINED3D_OK;
1778 }
1779
1780 HRESULT CDECL wined3d_device_get_stream_source_freq(const struct wined3d_device *device,
1781         UINT stream_idx, UINT *divider)
1782 {
1783     struct wined3d_stream_state *stream;
1784
1785     TRACE("device %p, stream_idx %u, divider %p.\n", device, stream_idx, divider);
1786
1787     stream = &device->updateStateBlock->state.streams[stream_idx];
1788     *divider = stream->flags | stream->frequency;
1789
1790     TRACE("Returning %#x.\n", *divider);
1791
1792     return WINED3D_OK;
1793 }
1794
1795 HRESULT CDECL wined3d_device_set_transform(struct wined3d_device *device,
1796         enum wined3d_transform_state d3dts, const struct wined3d_matrix *matrix)
1797 {
1798     TRACE("device %p, state %s, matrix %p.\n",
1799             device, debug_d3dtstype(d3dts), matrix);
1800     TRACE("%.8e %.8e %.8e %.8e\n", matrix->u.s._11, matrix->u.s._12, matrix->u.s._13, matrix->u.s._14);
1801     TRACE("%.8e %.8e %.8e %.8e\n", matrix->u.s._21, matrix->u.s._22, matrix->u.s._23, matrix->u.s._24);
1802     TRACE("%.8e %.8e %.8e %.8e\n", matrix->u.s._31, matrix->u.s._32, matrix->u.s._33, matrix->u.s._34);
1803     TRACE("%.8e %.8e %.8e %.8e\n", matrix->u.s._41, matrix->u.s._42, matrix->u.s._43, matrix->u.s._44);
1804
1805     /* Handle recording of state blocks. */
1806     if (device->isRecordingState)
1807     {
1808         TRACE("Recording... not performing anything.\n");
1809         device->updateStateBlock->changed.transform[d3dts >> 5] |= 1 << (d3dts & 0x1f);
1810         device->updateStateBlock->state.transforms[d3dts] = *matrix;
1811         return WINED3D_OK;
1812     }
1813
1814     /* If the new matrix is the same as the current one,
1815      * we cut off any further processing. this seems to be a reasonable
1816      * optimization because as was noticed, some apps (warcraft3 for example)
1817      * tend towards setting the same matrix repeatedly for some reason.
1818      *
1819      * From here on we assume that the new matrix is different, wherever it matters. */
1820     if (!memcmp(&device->stateBlock->state.transforms[d3dts].u.m[0][0], matrix, sizeof(*matrix)))
1821     {
1822         TRACE("The application is setting the same matrix over again.\n");
1823         return WINED3D_OK;
1824     }
1825
1826     device->stateBlock->state.transforms[d3dts] = *matrix;
1827     if (d3dts == WINED3D_TS_VIEW)
1828         device->view_ident = !memcmp(matrix, &identity, sizeof(identity));
1829
1830     if (d3dts < WINED3D_TS_WORLD_MATRIX(device->adapter->gl_info.limits.blends))
1831         device_invalidate_state(device, STATE_TRANSFORM(d3dts));
1832
1833     return WINED3D_OK;
1834
1835 }
1836
1837 HRESULT CDECL wined3d_device_get_transform(const struct wined3d_device *device,
1838         enum wined3d_transform_state state, struct wined3d_matrix *matrix)
1839 {
1840     TRACE("device %p, state %s, matrix %p.\n", device, debug_d3dtstype(state), matrix);
1841
1842     *matrix = device->stateBlock->state.transforms[state];
1843
1844     return WINED3D_OK;
1845 }
1846
1847 HRESULT CDECL wined3d_device_multiply_transform(struct wined3d_device *device,
1848         enum wined3d_transform_state state, const struct wined3d_matrix *matrix)
1849 {
1850     const struct wined3d_matrix *mat = NULL;
1851     struct wined3d_matrix temp;
1852
1853     TRACE("device %p, state %s, matrix %p.\n", device, debug_d3dtstype(state), matrix);
1854
1855     /* Note: Using 'updateStateBlock' rather than 'stateblock' in the code
1856      * below means it will be recorded in a state block change, but it
1857      * works regardless where it is recorded.
1858      * If this is found to be wrong, change to StateBlock. */
1859     if (state > HIGHEST_TRANSFORMSTATE)
1860     {
1861         WARN("Unhandled transform state %#x.\n", state);
1862         return WINED3D_OK;
1863     }
1864
1865     mat = &device->updateStateBlock->state.transforms[state];
1866     multiply_matrix(&temp, mat, matrix);
1867
1868     /* Apply change via set transform - will reapply to eg. lights this way. */
1869     return wined3d_device_set_transform(device, state, &temp);
1870 }
1871
1872 /* Note lights are real special cases. Although the device caps state only
1873  * e.g. 8 are supported, you can reference any indexes you want as long as
1874  * that number max are enabled at any one point in time. Therefore since the
1875  * indices can be anything, we need a hashmap of them. However, this causes
1876  * stateblock problems. When capturing the state block, I duplicate the
1877  * hashmap, but when recording, just build a chain pretty much of commands to
1878  * be replayed. */
1879 HRESULT CDECL wined3d_device_set_light(struct wined3d_device *device,
1880         UINT light_idx, const struct wined3d_light *light)
1881 {
1882     UINT hash_idx = LIGHTMAP_HASHFUNC(light_idx);
1883     struct wined3d_light_info *object = NULL;
1884     struct list *e;
1885     float rho;
1886
1887     TRACE("device %p, light_idx %u, light %p.\n", device, light_idx, light);
1888
1889     /* Check the parameter range. Need for speed most wanted sets junk lights
1890      * which confuse the GL driver. */
1891     if (!light)
1892         return WINED3DERR_INVALIDCALL;
1893
1894     switch (light->type)
1895     {
1896         case WINED3D_LIGHT_POINT:
1897         case WINED3D_LIGHT_SPOT:
1898         case WINED3D_LIGHT_PARALLELPOINT:
1899         case WINED3D_LIGHT_GLSPOT:
1900             /* Incorrect attenuation values can cause the gl driver to crash.
1901              * Happens with Need for speed most wanted. */
1902             if (light->attenuation0 < 0.0f || light->attenuation1 < 0.0f || light->attenuation2 < 0.0f)
1903             {
1904                 WARN("Attenuation is negative, returning WINED3DERR_INVALIDCALL.\n");
1905                 return WINED3DERR_INVALIDCALL;
1906             }
1907             break;
1908
1909         case WINED3D_LIGHT_DIRECTIONAL:
1910             /* Ignores attenuation */
1911             break;
1912
1913         default:
1914         WARN("Light type out of range, returning WINED3DERR_INVALIDCALL\n");
1915         return WINED3DERR_INVALIDCALL;
1916     }
1917
1918     LIST_FOR_EACH(e, &device->updateStateBlock->state.light_map[hash_idx])
1919     {
1920         object = LIST_ENTRY(e, struct wined3d_light_info, entry);
1921         if (object->OriginalIndex == light_idx)
1922             break;
1923         object = NULL;
1924     }
1925
1926     if (!object)
1927     {
1928         TRACE("Adding new light\n");
1929         object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
1930         if (!object)
1931         {
1932             ERR("Out of memory error when allocating a light\n");
1933             return E_OUTOFMEMORY;
1934         }
1935         list_add_head(&device->updateStateBlock->state.light_map[hash_idx], &object->entry);
1936         object->glIndex = -1;
1937         object->OriginalIndex = light_idx;
1938     }
1939
1940     /* Initialize the object. */
1941     TRACE("Light %d setting to type %d, Diffuse(%f,%f,%f,%f), Specular(%f,%f,%f,%f), Ambient(%f,%f,%f,%f)\n",
1942             light_idx, light->type,
1943             light->diffuse.r, light->diffuse.g, light->diffuse.b, light->diffuse.a,
1944             light->specular.r, light->specular.g, light->specular.b, light->specular.a,
1945             light->ambient.r, light->ambient.g, light->ambient.b, light->ambient.a);
1946     TRACE("... Pos(%f,%f,%f), Dir(%f,%f,%f)\n", light->position.x, light->position.y, light->position.z,
1947             light->direction.x, light->direction.y, light->direction.z);
1948     TRACE("... Range(%f), Falloff(%f), Theta(%f), Phi(%f)\n",
1949             light->range, light->falloff, light->theta, light->phi);
1950
1951     /* Save away the information. */
1952     object->OriginalParms = *light;
1953
1954     switch (light->type)
1955     {
1956         case WINED3D_LIGHT_POINT:
1957             /* Position */
1958             object->lightPosn[0] = light->position.x;
1959             object->lightPosn[1] = light->position.y;
1960             object->lightPosn[2] = light->position.z;
1961             object->lightPosn[3] = 1.0f;
1962             object->cutoff = 180.0f;
1963             /* FIXME: Range */
1964             break;
1965
1966         case WINED3D_LIGHT_DIRECTIONAL:
1967             /* Direction */
1968             object->lightPosn[0] = -light->direction.x;
1969             object->lightPosn[1] = -light->direction.y;
1970             object->lightPosn[2] = -light->direction.z;
1971             object->lightPosn[3] = 0.0f;
1972             object->exponent = 0.0f;
1973             object->cutoff = 180.0f;
1974             break;
1975
1976         case WINED3D_LIGHT_SPOT:
1977             /* Position */
1978             object->lightPosn[0] = light->position.x;
1979             object->lightPosn[1] = light->position.y;
1980             object->lightPosn[2] = light->position.z;
1981             object->lightPosn[3] = 1.0f;
1982
1983             /* Direction */
1984             object->lightDirn[0] = light->direction.x;
1985             object->lightDirn[1] = light->direction.y;
1986             object->lightDirn[2] = light->direction.z;
1987             object->lightDirn[3] = 1.0f;
1988
1989             /* opengl-ish and d3d-ish spot lights use too different models
1990              * for the light "intensity" as a function of the angle towards
1991              * the main light direction, so we only can approximate very
1992              * roughly. However, spot lights are rather rarely used in games
1993              * (if ever used at all). Furthermore if still used, probably
1994              * nobody pays attention to such details. */
1995             if (!light->falloff)
1996             {
1997                 /* Falloff = 0 is easy, because d3d's and opengl's spot light
1998                  * equations have the falloff resp. exponent parameter as an
1999                  * exponent, so the spot light lighting will always be 1.0 for
2000                  * both of them, and we don't have to care for the rest of the
2001                  * rather complex calculation. */
2002                 object->exponent = 0.0f;
2003             }
2004             else
2005             {
2006                 rho = light->theta + (light->phi - light->theta) / (2 * light->falloff);
2007                 if (rho < 0.0001f)
2008                     rho = 0.0001f;
2009                 object->exponent = -0.3f / logf(cosf(rho / 2));
2010             }
2011
2012             if (object->exponent > 128.0f)
2013                 object->exponent = 128.0f;
2014
2015             object->cutoff = (float)(light->phi * 90 / M_PI);
2016             /* FIXME: Range */
2017             break;
2018
2019         default:
2020             FIXME("Unrecognized light type %#x.\n", light->type);
2021     }
2022
2023     /* Update the live definitions if the light is currently assigned a glIndex. */
2024     if (object->glIndex != -1 && !device->isRecordingState)
2025         device_invalidate_state(device, STATE_ACTIVELIGHT(object->glIndex));
2026
2027     return WINED3D_OK;
2028 }
2029
2030 HRESULT CDECL wined3d_device_get_light(const struct wined3d_device *device,
2031         UINT light_idx, struct wined3d_light *light)
2032 {
2033     UINT hash_idx = LIGHTMAP_HASHFUNC(light_idx);
2034     struct wined3d_light_info *light_info = NULL;
2035     struct list *e;
2036
2037     TRACE("device %p, light_idx %u, light %p.\n", device, light_idx, light);
2038
2039     LIST_FOR_EACH(e, &device->stateBlock->state.light_map[hash_idx])
2040     {
2041         light_info = LIST_ENTRY(e, struct wined3d_light_info, entry);
2042         if (light_info->OriginalIndex == light_idx)
2043             break;
2044         light_info = NULL;
2045     }
2046
2047     if (!light_info)
2048     {
2049         TRACE("Light information requested but light not defined\n");
2050         return WINED3DERR_INVALIDCALL;
2051     }
2052
2053     *light = light_info->OriginalParms;
2054     return WINED3D_OK;
2055 }
2056
2057 HRESULT CDECL wined3d_device_set_light_enable(struct wined3d_device *device, UINT light_idx, BOOL enable)
2058 {
2059     UINT hash_idx = LIGHTMAP_HASHFUNC(light_idx);
2060     struct wined3d_light_info *light_info = NULL;
2061     struct list *e;
2062
2063     TRACE("device %p, light_idx %u, enable %#x.\n", device, light_idx, enable);
2064
2065     LIST_FOR_EACH(e, &device->updateStateBlock->state.light_map[hash_idx])
2066     {
2067         light_info = LIST_ENTRY(e, struct wined3d_light_info, entry);
2068         if (light_info->OriginalIndex == light_idx)
2069             break;
2070         light_info = NULL;
2071     }
2072     TRACE("Found light %p.\n", light_info);
2073
2074     /* Special case - enabling an undefined light creates one with a strict set of parameters. */
2075     if (!light_info)
2076     {
2077         TRACE("Light enabled requested but light not defined, so defining one!\n");
2078         wined3d_device_set_light(device, light_idx, &WINED3D_default_light);
2079
2080         /* Search for it again! Should be fairly quick as near head of list. */
2081         LIST_FOR_EACH(e, &device->updateStateBlock->state.light_map[hash_idx])
2082         {
2083             light_info = LIST_ENTRY(e, struct wined3d_light_info, entry);
2084             if (light_info->OriginalIndex == light_idx)
2085                 break;
2086             light_info = NULL;
2087         }
2088         if (!light_info)
2089         {
2090             FIXME("Adding default lights has failed dismally\n");
2091             return WINED3DERR_INVALIDCALL;
2092         }
2093     }
2094
2095     if (!enable)
2096     {
2097         if (light_info->glIndex != -1)
2098         {
2099             if (!device->isRecordingState)
2100                 device_invalidate_state(device, STATE_ACTIVELIGHT(light_info->glIndex));
2101
2102             device->updateStateBlock->state.lights[light_info->glIndex] = NULL;
2103             light_info->glIndex = -1;
2104         }
2105         else
2106         {
2107             TRACE("Light already disabled, nothing to do\n");
2108         }
2109         light_info->enabled = FALSE;
2110     }
2111     else
2112     {
2113         light_info->enabled = TRUE;
2114         if (light_info->glIndex != -1)
2115         {
2116             TRACE("Nothing to do as light was enabled\n");
2117         }
2118         else
2119         {
2120             unsigned int i;
2121             const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
2122             /* Find a free GL light. */
2123             for (i = 0; i < gl_info->limits.lights; ++i)
2124             {
2125                 if (!device->updateStateBlock->state.lights[i])
2126                 {
2127                     device->updateStateBlock->state.lights[i] = light_info;
2128                     light_info->glIndex = i;
2129                     break;
2130                 }
2131             }
2132             if (light_info->glIndex == -1)
2133             {
2134                 /* Our tests show that Windows returns D3D_OK in this situation, even with
2135                  * D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_PUREDEVICE devices. This
2136                  * is consistent among ddraw, d3d8 and d3d9. GetLightEnable returns TRUE
2137                  * as well for those lights.
2138                  *
2139                  * TODO: Test how this affects rendering. */
2140                 WARN("Too many concurrently active lights\n");
2141                 return WINED3D_OK;
2142             }
2143
2144             /* i == light_info->glIndex */
2145             if (!device->isRecordingState)
2146                 device_invalidate_state(device, STATE_ACTIVELIGHT(i));
2147         }
2148     }
2149
2150     return WINED3D_OK;
2151 }
2152
2153 HRESULT CDECL wined3d_device_get_light_enable(const struct wined3d_device *device, UINT light_idx, BOOL *enable)
2154 {
2155     UINT hash_idx = LIGHTMAP_HASHFUNC(light_idx);
2156     struct wined3d_light_info *light_info = NULL;
2157     struct list *e;
2158
2159     TRACE("device %p, light_idx %u, enable %p.\n", device, light_idx, enable);
2160
2161     LIST_FOR_EACH(e, &device->stateBlock->state.light_map[hash_idx])
2162     {
2163         light_info = LIST_ENTRY(e, struct wined3d_light_info, entry);
2164         if (light_info->OriginalIndex == light_idx)
2165             break;
2166         light_info = NULL;
2167     }
2168
2169     if (!light_info)
2170     {
2171         TRACE("Light enabled state requested but light not defined.\n");
2172         return WINED3DERR_INVALIDCALL;
2173     }
2174     /* true is 128 according to SetLightEnable */
2175     *enable = light_info->enabled ? 128 : 0;
2176     return WINED3D_OK;
2177 }
2178
2179 HRESULT CDECL wined3d_device_set_clip_plane(struct wined3d_device *device,
2180         UINT plane_idx, const struct wined3d_vec4 *plane)
2181 {
2182     TRACE("device %p, plane_idx %u, plane %p.\n", device, plane_idx, plane);
2183
2184     /* Validate plane_idx. */
2185     if (plane_idx >= device->adapter->gl_info.limits.clipplanes)
2186     {
2187         TRACE("Application has requested clipplane this device doesn't support.\n");
2188         return WINED3DERR_INVALIDCALL;
2189     }
2190
2191     device->updateStateBlock->changed.clipplane |= 1 << plane_idx;
2192
2193     if (!memcmp(&device->updateStateBlock->state.clip_planes[plane_idx], plane, sizeof(*plane)))
2194     {
2195         TRACE("Application is setting old values over, nothing to do.\n");
2196         return WINED3D_OK;
2197     }
2198
2199     device->updateStateBlock->state.clip_planes[plane_idx] = *plane;
2200
2201     /* Handle recording of state blocks. */
2202     if (device->isRecordingState)
2203     {
2204         TRACE("Recording... not performing anything.\n");
2205         return WINED3D_OK;
2206     }
2207
2208     device_invalidate_state(device, STATE_CLIPPLANE(plane_idx));
2209
2210     return WINED3D_OK;
2211 }
2212
2213 HRESULT CDECL wined3d_device_get_clip_plane(const struct wined3d_device *device,
2214         UINT plane_idx, struct wined3d_vec4 *plane)
2215 {
2216     TRACE("device %p, plane_idx %u, plane %p.\n", device, plane_idx, plane);
2217
2218     /* Validate plane_idx. */
2219     if (plane_idx >= device->adapter->gl_info.limits.clipplanes)
2220     {
2221         TRACE("Application has requested clipplane this device doesn't support.\n");
2222         return WINED3DERR_INVALIDCALL;
2223     }
2224
2225     *plane = device->stateBlock->state.clip_planes[plane_idx];
2226
2227     return WINED3D_OK;
2228 }
2229
2230 HRESULT CDECL wined3d_device_set_clip_status(struct wined3d_device *device,
2231         const struct wined3d_clip_status *clip_status)
2232 {
2233     FIXME("device %p, clip_status %p stub!\n", device, clip_status);
2234
2235     if (!clip_status)
2236         return WINED3DERR_INVALIDCALL;
2237
2238     return WINED3D_OK;
2239 }
2240
2241 HRESULT CDECL wined3d_device_get_clip_status(const struct wined3d_device *device,
2242         struct wined3d_clip_status *clip_status)
2243 {
2244     FIXME("device %p, clip_status %p stub!\n", device, clip_status);
2245
2246     if (!clip_status)
2247         return WINED3DERR_INVALIDCALL;
2248
2249     return WINED3D_OK;
2250 }
2251
2252 HRESULT CDECL wined3d_device_set_material(struct wined3d_device *device, const struct wined3d_material *material)
2253 {
2254     TRACE("device %p, material %p.\n", device, material);
2255
2256     device->updateStateBlock->changed.material = TRUE;
2257     device->updateStateBlock->state.material = *material;
2258
2259     /* Handle recording of state blocks */
2260     if (device->isRecordingState)
2261     {
2262         TRACE("Recording... not performing anything.\n");
2263         return WINED3D_OK;
2264     }
2265
2266     device_invalidate_state(device, STATE_MATERIAL);
2267
2268     return WINED3D_OK;
2269 }
2270
2271 HRESULT CDECL wined3d_device_get_material(const struct wined3d_device *device, struct wined3d_material *material)
2272 {
2273     TRACE("device %p, material %p.\n", device, material);
2274
2275     *material = device->updateStateBlock->state.material;
2276
2277     TRACE("diffuse {%.8e, %.8e, %.8e, %.8e}\n",
2278             material->diffuse.r, material->diffuse.g,
2279             material->diffuse.b, material->diffuse.a);
2280     TRACE("ambient {%.8e, %.8e, %.8e, %.8e}\n",
2281             material->ambient.r, material->ambient.g,
2282             material->ambient.b, material->ambient.a);
2283     TRACE("specular {%.8e, %.8e, %.8e, %.8e}\n",
2284             material->specular.r, material->specular.g,
2285             material->specular.b, material->specular.a);
2286     TRACE("emissive {%.8e, %.8e, %.8e, %.8e}\n",
2287             material->emissive.r, material->emissive.g,
2288             material->emissive.b, material->emissive.a);
2289     TRACE("power %.8e.\n", material->power);
2290
2291     return WINED3D_OK;
2292 }
2293
2294 HRESULT CDECL wined3d_device_set_index_buffer(struct wined3d_device *device,
2295         struct wined3d_buffer *buffer, enum wined3d_format_id format_id)
2296 {
2297     struct wined3d_buffer *prev_buffer;
2298
2299     TRACE("device %p, buffer %p, format %s.\n",
2300             device, buffer, debug_d3dformat(format_id));
2301
2302     prev_buffer = device->updateStateBlock->state.index_buffer;
2303
2304     device->updateStateBlock->changed.indices = TRUE;
2305     device->updateStateBlock->state.index_buffer = buffer;
2306     device->updateStateBlock->state.index_format = format_id;
2307
2308     /* Handle recording of state blocks. */
2309     if (device->isRecordingState)
2310     {
2311         TRACE("Recording... not performing anything.\n");
2312         if (buffer)
2313             wined3d_buffer_incref(buffer);
2314         if (prev_buffer)
2315             wined3d_buffer_decref(prev_buffer);
2316         return WINED3D_OK;
2317     }
2318
2319     if (prev_buffer != buffer)
2320     {
2321         device_invalidate_state(device, STATE_INDEXBUFFER);
2322         if (buffer)
2323         {
2324             InterlockedIncrement(&buffer->resource.bind_count);
2325             wined3d_buffer_incref(buffer);
2326         }
2327         if (prev_buffer)
2328         {
2329             InterlockedDecrement(&prev_buffer->resource.bind_count);
2330             wined3d_buffer_decref(prev_buffer);
2331         }
2332     }
2333
2334     return WINED3D_OK;
2335 }
2336
2337 HRESULT CDECL wined3d_device_get_index_buffer(const struct wined3d_device *device, struct wined3d_buffer **buffer)
2338 {
2339     TRACE("device %p, buffer %p.\n", device, buffer);
2340
2341     *buffer = device->stateBlock->state.index_buffer;
2342
2343     if (*buffer)
2344         wined3d_buffer_incref(*buffer);
2345
2346     TRACE("Returning %p.\n", *buffer);
2347
2348     return WINED3D_OK;
2349 }
2350
2351 /* Method to offer d3d9 a simple way to set the base vertex index without messing with the index buffer */
2352 HRESULT CDECL wined3d_device_set_base_vertex_index(struct wined3d_device *device, INT base_index)
2353 {
2354     TRACE("device %p, base_index %d.\n", device, base_index);
2355
2356     if (device->updateStateBlock->state.base_vertex_index == base_index)
2357     {
2358         TRACE("Application is setting the old value over, nothing to do\n");
2359         return WINED3D_OK;
2360     }
2361
2362     device->updateStateBlock->state.base_vertex_index = base_index;
2363
2364     if (device->isRecordingState)
2365     {
2366         TRACE("Recording... not performing anything\n");
2367         return WINED3D_OK;
2368     }
2369     return WINED3D_OK;
2370 }
2371
2372 INT CDECL wined3d_device_get_base_vertex_index(const struct wined3d_device *device)
2373 {
2374     TRACE("device %p.\n", device);
2375
2376     return device->stateBlock->state.base_vertex_index;
2377 }
2378
2379 HRESULT CDECL wined3d_device_set_viewport(struct wined3d_device *device, const struct wined3d_viewport *viewport)
2380 {
2381     TRACE("device %p, viewport %p.\n", device, viewport);
2382     TRACE("x %u, y %u, w %u, h %u, min_z %.8e, max_z %.8e.\n",
2383           viewport->x, viewport->y, viewport->width, viewport->height, viewport->min_z, viewport->max_z);
2384
2385     device->updateStateBlock->changed.viewport = TRUE;
2386     device->updateStateBlock->state.viewport = *viewport;
2387
2388     /* Handle recording of state blocks */
2389     if (device->isRecordingState)
2390     {
2391         TRACE("Recording... not performing anything\n");
2392         return WINED3D_OK;
2393     }
2394
2395     device_invalidate_state(device, STATE_VIEWPORT);
2396
2397     return WINED3D_OK;
2398 }
2399
2400 HRESULT CDECL wined3d_device_get_viewport(const struct wined3d_device *device, struct wined3d_viewport *viewport)
2401 {
2402     TRACE("device %p, viewport %p.\n", device, viewport);
2403
2404     *viewport = device->stateBlock->state.viewport;
2405
2406     return WINED3D_OK;
2407 }
2408
2409 HRESULT CDECL wined3d_device_set_render_state(struct wined3d_device *device,
2410         enum wined3d_render_state state, DWORD value)
2411 {
2412     DWORD old_value = device->stateBlock->state.render_states[state];
2413
2414     TRACE("device %p, state %s (%#x), value %#x.\n", device, debug_d3drenderstate(state), state, value);
2415
2416     device->updateStateBlock->changed.renderState[state >> 5] |= 1 << (state & 0x1f);
2417     device->updateStateBlock->state.render_states[state] = value;
2418
2419     /* Handle recording of state blocks. */
2420     if (device->isRecordingState)
2421     {
2422         TRACE("Recording... not performing anything.\n");
2423         return WINED3D_OK;
2424     }
2425
2426     /* Compared here and not before the assignment to allow proper stateblock recording. */
2427     if (value == old_value)
2428         TRACE("Application is setting the old value over, nothing to do.\n");
2429     else
2430         device_invalidate_state(device, STATE_RENDER(state));
2431
2432     return WINED3D_OK;
2433 }
2434
2435 HRESULT CDECL wined3d_device_get_render_state(const struct wined3d_device *device,
2436         enum wined3d_render_state state, DWORD *value)
2437 {
2438     TRACE("device %p, state %s (%#x), value %p.\n", device, debug_d3drenderstate(state), state, value);
2439
2440     *value = device->stateBlock->state.render_states[state];
2441
2442     return WINED3D_OK;
2443 }
2444
2445 HRESULT CDECL wined3d_device_set_sampler_state(struct wined3d_device *device,
2446         UINT sampler_idx, enum wined3d_sampler_state state, DWORD value)
2447 {
2448     DWORD old_value;
2449
2450     TRACE("device %p, sampler_idx %u, state %s, value %#x.\n",
2451             device, sampler_idx, debug_d3dsamplerstate(state), value);
2452
2453     if (sampler_idx >= WINED3DVERTEXTEXTURESAMPLER0 && sampler_idx <= WINED3DVERTEXTEXTURESAMPLER3)
2454         sampler_idx -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
2455
2456     if (sampler_idx >= sizeof(device->stateBlock->state.sampler_states)
2457             / sizeof(*device->stateBlock->state.sampler_states))
2458     {
2459         WARN("Invalid sampler %u.\n", sampler_idx);
2460         return WINED3D_OK; /* Windows accepts overflowing this array ... we do not. */
2461     }
2462
2463     old_value = device->stateBlock->state.sampler_states[sampler_idx][state];
2464     device->updateStateBlock->state.sampler_states[sampler_idx][state] = value;
2465     device->updateStateBlock->changed.samplerState[sampler_idx] |= 1 << state;
2466
2467     /* Handle recording of state blocks. */
2468     if (device->isRecordingState)
2469     {
2470         TRACE("Recording... not performing anything.\n");
2471         return WINED3D_OK;
2472     }
2473
2474     if (old_value == value)
2475     {
2476         TRACE("Application is setting the old value over, nothing to do.\n");
2477         return WINED3D_OK;
2478     }
2479
2480     device_invalidate_state(device, STATE_SAMPLER(sampler_idx));
2481
2482     return WINED3D_OK;
2483 }
2484
2485 HRESULT CDECL wined3d_device_get_sampler_state(const struct wined3d_device *device,
2486         UINT sampler_idx, enum wined3d_sampler_state state, DWORD *value)
2487 {
2488     TRACE("device %p, sampler_idx %u, state %s, value %p.\n",
2489             device, sampler_idx, debug_d3dsamplerstate(state), value);
2490
2491     if (sampler_idx >= WINED3DVERTEXTEXTURESAMPLER0 && sampler_idx <= WINED3DVERTEXTEXTURESAMPLER3)
2492         sampler_idx -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
2493
2494     if (sampler_idx >= sizeof(device->stateBlock->state.sampler_states)
2495             / sizeof(*device->stateBlock->state.sampler_states))
2496     {
2497         WARN("Invalid sampler %u.\n", sampler_idx);
2498         return WINED3D_OK; /* Windows accepts overflowing this array ... we do not. */
2499     }
2500
2501     *value = device->stateBlock->state.sampler_states[sampler_idx][state];
2502     TRACE("Returning %#x.\n", *value);
2503
2504     return WINED3D_OK;
2505 }
2506
2507 HRESULT CDECL wined3d_device_set_scissor_rect(struct wined3d_device *device, const RECT *rect)
2508 {
2509     TRACE("device %p, rect %s.\n", device, wine_dbgstr_rect(rect));
2510
2511     device->updateStateBlock->changed.scissorRect = TRUE;
2512     if (EqualRect(&device->updateStateBlock->state.scissor_rect, rect))
2513     {
2514         TRACE("App is setting the old scissor rectangle over, nothing to do.\n");
2515         return WINED3D_OK;
2516     }
2517     CopyRect(&device->updateStateBlock->state.scissor_rect, rect);
2518
2519     if (device->isRecordingState)
2520     {
2521         TRACE("Recording... not performing anything.\n");
2522         return WINED3D_OK;
2523     }
2524
2525     device_invalidate_state(device, STATE_SCISSORRECT);
2526
2527     return WINED3D_OK;
2528 }
2529
2530 HRESULT CDECL wined3d_device_get_scissor_rect(const struct wined3d_device *device, RECT *rect)
2531 {
2532     TRACE("device %p, rect %p.\n", device, rect);
2533
2534     *rect = device->updateStateBlock->state.scissor_rect;
2535     TRACE("Returning rect %s.\n", wine_dbgstr_rect(rect));
2536
2537     return WINED3D_OK;
2538 }
2539
2540 HRESULT CDECL wined3d_device_set_vertex_declaration(struct wined3d_device *device,
2541         struct wined3d_vertex_declaration *declaration)
2542 {
2543     struct wined3d_vertex_declaration *prev = device->updateStateBlock->state.vertex_declaration;
2544
2545     TRACE("device %p, declaration %p.\n", device, declaration);
2546
2547     if (declaration)
2548         wined3d_vertex_declaration_incref(declaration);
2549     if (prev)
2550         wined3d_vertex_declaration_decref(prev);
2551
2552     device->updateStateBlock->state.vertex_declaration = declaration;
2553     device->updateStateBlock->changed.vertexDecl = TRUE;
2554
2555     if (device->isRecordingState)
2556     {
2557         TRACE("Recording... not performing anything.\n");
2558         return WINED3D_OK;
2559     }
2560     else if (declaration == prev)
2561     {
2562         /* Checked after the assignment to allow proper stateblock recording. */
2563         TRACE("Application is setting the old declaration over, nothing to do.\n");
2564         return WINED3D_OK;
2565     }
2566
2567     device_invalidate_state(device, STATE_VDECL);
2568     return WINED3D_OK;
2569 }
2570
2571 HRESULT CDECL wined3d_device_get_vertex_declaration(const struct wined3d_device *device,
2572         struct wined3d_vertex_declaration **declaration)
2573 {
2574     TRACE("device %p, declaration %p.\n", device, declaration);
2575
2576     *declaration = device->stateBlock->state.vertex_declaration;
2577     if (*declaration)
2578         wined3d_vertex_declaration_incref(*declaration);
2579
2580     return WINED3D_OK;
2581 }
2582
2583 HRESULT CDECL wined3d_device_set_vertex_shader(struct wined3d_device *device, struct wined3d_shader *shader)
2584 {
2585     struct wined3d_shader *prev = device->updateStateBlock->state.vertex_shader;
2586
2587     TRACE("device %p, shader %p.\n", device, shader);
2588
2589     device->updateStateBlock->state.vertex_shader = shader;
2590     device->updateStateBlock->changed.vertexShader = TRUE;
2591
2592     if (device->isRecordingState)
2593     {
2594         if (shader)
2595             wined3d_shader_incref(shader);
2596         if (prev)
2597             wined3d_shader_decref(prev);
2598         TRACE("Recording... not performing anything.\n");
2599         return WINED3D_OK;
2600     }
2601
2602     if (shader == prev)
2603     {
2604         TRACE("Application is setting the old shader over, nothing to do.\n");
2605         return WINED3D_OK;
2606     }
2607
2608     if (shader)
2609         wined3d_shader_incref(shader);
2610     if (prev)
2611         wined3d_shader_decref(prev);
2612
2613     device_invalidate_state(device, STATE_VSHADER);
2614
2615     return WINED3D_OK;
2616 }
2617
2618 struct wined3d_shader * CDECL wined3d_device_get_vertex_shader(const struct wined3d_device *device)
2619 {
2620     struct wined3d_shader *shader;
2621
2622     TRACE("device %p.\n", device);
2623
2624     shader = device->stateBlock->state.vertex_shader;
2625     if (shader)
2626         wined3d_shader_incref(shader);
2627
2628     TRACE("Returning %p.\n", shader);
2629     return shader;
2630 }
2631
2632 HRESULT CDECL wined3d_device_set_vs_consts_b(struct wined3d_device *device,
2633         UINT start_register, const BOOL *constants, UINT bool_count)
2634 {
2635     UINT count = min(bool_count, MAX_CONST_B - start_register);
2636     UINT i;
2637
2638     TRACE("device %p, start_register %u, constants %p, bool_count %u.\n",
2639             device, start_register, constants, bool_count);
2640
2641     if (!constants || start_register >= MAX_CONST_B)
2642         return WINED3DERR_INVALIDCALL;
2643
2644     memcpy(&device->updateStateBlock->state.vs_consts_b[start_register], constants, count * sizeof(BOOL));
2645     for (i = 0; i < count; ++i)
2646         TRACE("Set BOOL constant %u to %s.\n", start_register + i, constants[i] ? "true" : "false");
2647
2648     for (i = start_register; i < count + start_register; ++i)
2649         device->updateStateBlock->changed.vertexShaderConstantsB |= (1 << i);
2650
2651     if (!device->isRecordingState)
2652         device_invalidate_state(device, STATE_VERTEXSHADERCONSTANT);
2653
2654     return WINED3D_OK;
2655 }
2656
2657 HRESULT CDECL wined3d_device_get_vs_consts_b(const struct wined3d_device *device,
2658         UINT start_register, BOOL *constants, UINT bool_count)
2659 {
2660     UINT count = min(bool_count, MAX_CONST_B - start_register);
2661
2662     TRACE("device %p, start_register %u, constants %p, bool_count %u.\n",
2663             device, start_register, constants, bool_count);
2664
2665     if (!constants || start_register >= MAX_CONST_B)
2666         return WINED3DERR_INVALIDCALL;
2667
2668     memcpy(constants, &device->stateBlock->state.vs_consts_b[start_register], count * sizeof(BOOL));
2669
2670     return WINED3D_OK;
2671 }
2672
2673 HRESULT CDECL wined3d_device_set_vs_consts_i(struct wined3d_device *device,
2674         UINT start_register, const int *constants, UINT vector4i_count)
2675 {
2676     UINT count = min(vector4i_count, MAX_CONST_I - start_register);
2677     UINT i;
2678
2679     TRACE("device %p, start_register %u, constants %p, vector4i_count %u.\n",
2680             device, start_register, constants, vector4i_count);
2681
2682     if (!constants || start_register >= MAX_CONST_I)
2683         return WINED3DERR_INVALIDCALL;
2684
2685     memcpy(&device->updateStateBlock->state.vs_consts_i[start_register * 4], constants, count * sizeof(int) * 4);
2686     for (i = 0; i < count; ++i)
2687         TRACE("Set INT constant %u to {%d, %d, %d, %d}.\n", start_register + i,
2688                 constants[i * 4], constants[i * 4 + 1],
2689                 constants[i * 4 + 2], constants[i * 4 + 3]);
2690
2691     for (i = start_register; i < count + start_register; ++i)
2692         device->updateStateBlock->changed.vertexShaderConstantsI |= (1 << i);
2693
2694     if (!device->isRecordingState)
2695         device_invalidate_state(device, STATE_VERTEXSHADERCONSTANT);
2696
2697     return WINED3D_OK;
2698 }
2699
2700 HRESULT CDECL wined3d_device_get_vs_consts_i(const struct wined3d_device *device,
2701         UINT start_register, int *constants, UINT vector4i_count)
2702 {
2703     UINT count = min(vector4i_count, MAX_CONST_I - start_register);
2704
2705     TRACE("device %p, start_register %u, constants %p, vector4i_count %u.\n",
2706             device, start_register, constants, vector4i_count);
2707
2708     if (!constants || start_register >= MAX_CONST_I)
2709         return WINED3DERR_INVALIDCALL;
2710
2711     memcpy(constants, &device->stateBlock->state.vs_consts_i[start_register * 4], count * sizeof(int) * 4);
2712     return WINED3D_OK;
2713 }
2714
2715 HRESULT CDECL wined3d_device_set_vs_consts_f(struct wined3d_device *device,
2716         UINT start_register, const float *constants, UINT vector4f_count)
2717 {
2718     UINT i;
2719
2720     TRACE("device %p, start_register %u, constants %p, vector4f_count %u.\n",
2721             device, start_register, constants, vector4f_count);
2722
2723     /* Specifically test start_register > limit to catch MAX_UINT overflows
2724      * when adding start_register + vector4f_count. */
2725     if (!constants
2726             || start_register + vector4f_count > device->d3d_vshader_constantF
2727             || start_register > device->d3d_vshader_constantF)
2728         return WINED3DERR_INVALIDCALL;
2729
2730     memcpy(&device->updateStateBlock->state.vs_consts_f[start_register * 4],
2731             constants, vector4f_count * sizeof(float) * 4);
2732     if (TRACE_ON(d3d))
2733     {
2734         for (i = 0; i < vector4f_count; ++i)
2735             TRACE("Set FLOAT constant %u to {%.8e, %.8e, %.8e, %.8e}.\n", start_register + i,
2736                     constants[i * 4], constants[i * 4 + 1],
2737                     constants[i * 4 + 2], constants[i * 4 + 3]);
2738     }
2739
2740     if (!device->isRecordingState)
2741     {
2742         device->shader_backend->shader_update_float_vertex_constants(device, start_register, vector4f_count);
2743         device_invalidate_state(device, STATE_VERTEXSHADERCONSTANT);
2744     }
2745
2746     memset(device->updateStateBlock->changed.vertexShaderConstantsF + start_register, 1,
2747             sizeof(*device->updateStateBlock->changed.vertexShaderConstantsF) * vector4f_count);
2748
2749     return WINED3D_OK;
2750 }
2751
2752 HRESULT CDECL wined3d_device_get_vs_consts_f(const struct wined3d_device *device,
2753         UINT start_register, float *constants, UINT vector4f_count)
2754 {
2755     int count = min(vector4f_count, device->d3d_vshader_constantF - start_register);
2756
2757     TRACE("device %p, start_register %u, constants %p, vector4f_count %u.\n",
2758             device, start_register, constants, vector4f_count);
2759
2760     if (!constants || count < 0)
2761         return WINED3DERR_INVALIDCALL;
2762
2763     memcpy(constants, &device->stateBlock->state.vs_consts_f[start_register * 4], count * sizeof(float) * 4);
2764
2765     return WINED3D_OK;
2766 }
2767
2768 static void device_invalidate_texture_stage(const struct wined3d_device *device, DWORD stage)
2769 {
2770     DWORD i;
2771
2772     for (i = 0; i <= WINED3D_HIGHEST_TEXTURE_STATE; ++i)
2773     {
2774         device_invalidate_state(device, STATE_TEXTURESTAGE(stage, i));
2775     }
2776 }
2777
2778 static void device_map_stage(struct wined3d_device *device, DWORD stage, DWORD unit)
2779 {
2780     DWORD i = device->rev_tex_unit_map[unit];
2781     DWORD j = device->texUnitMap[stage];
2782
2783     device->texUnitMap[stage] = unit;
2784     if (i != WINED3D_UNMAPPED_STAGE && i != stage)
2785         device->texUnitMap[i] = WINED3D_UNMAPPED_STAGE;
2786
2787     device->rev_tex_unit_map[unit] = stage;
2788     if (j != WINED3D_UNMAPPED_STAGE && j != unit)
2789         device->rev_tex_unit_map[j] = WINED3D_UNMAPPED_STAGE;
2790 }
2791
2792 static void device_update_fixed_function_usage_map(struct wined3d_device *device)
2793 {
2794     UINT i;
2795
2796     device->fixed_function_usage_map = 0;
2797     for (i = 0; i < MAX_TEXTURES; ++i)
2798     {
2799         const struct wined3d_state *state = &device->stateBlock->state;
2800         enum wined3d_texture_op color_op = state->texture_states[i][WINED3D_TSS_COLOR_OP];
2801         enum wined3d_texture_op alpha_op = state->texture_states[i][WINED3D_TSS_ALPHA_OP];
2802         DWORD color_arg1 = state->texture_states[i][WINED3D_TSS_COLOR_ARG1] & WINED3DTA_SELECTMASK;
2803         DWORD color_arg2 = state->texture_states[i][WINED3D_TSS_COLOR_ARG2] & WINED3DTA_SELECTMASK;
2804         DWORD color_arg3 = state->texture_states[i][WINED3D_TSS_COLOR_ARG0] & WINED3DTA_SELECTMASK;
2805         DWORD alpha_arg1 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG1] & WINED3DTA_SELECTMASK;
2806         DWORD alpha_arg2 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG2] & WINED3DTA_SELECTMASK;
2807         DWORD alpha_arg3 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG0] & WINED3DTA_SELECTMASK;
2808
2809         /* Not used, and disable higher stages. */
2810         if (color_op == WINED3D_TOP_DISABLE)
2811             break;
2812
2813         if (((color_arg1 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG2)
2814                 || ((color_arg2 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG1)
2815                 || ((color_arg3 == WINED3DTA_TEXTURE)
2816                     && (color_op == WINED3D_TOP_MULTIPLY_ADD || color_op == WINED3D_TOP_LERP))
2817                 || ((alpha_arg1 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG2)
2818                 || ((alpha_arg2 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG1)
2819                 || ((alpha_arg3 == WINED3DTA_TEXTURE)
2820                     && (alpha_op == WINED3D_TOP_MULTIPLY_ADD || alpha_op == WINED3D_TOP_LERP)))
2821             device->fixed_function_usage_map |= (1 << i);
2822
2823         if ((color_op == WINED3D_TOP_BUMPENVMAP || color_op == WINED3D_TOP_BUMPENVMAP_LUMINANCE)
2824                 && i < MAX_TEXTURES - 1)
2825             device->fixed_function_usage_map |= (1 << (i + 1));
2826     }
2827 }
2828
2829 static void device_map_fixed_function_samplers(struct wined3d_device *device, const struct wined3d_gl_info *gl_info)
2830 {
2831     unsigned int i, tex;
2832     WORD ffu_map;
2833
2834     device_update_fixed_function_usage_map(device);
2835     ffu_map = device->fixed_function_usage_map;
2836
2837     if (device->max_ffp_textures == gl_info->limits.texture_stages
2838             || device->stateBlock->state.lowest_disabled_stage <= device->max_ffp_textures)
2839     {
2840         for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2841         {
2842             if (!(ffu_map & 1)) continue;
2843
2844             if (device->texUnitMap[i] != i)
2845             {
2846                 device_map_stage(device, i, i);
2847                 device_invalidate_state(device, STATE_SAMPLER(i));
2848                 device_invalidate_texture_stage(device, i);
2849             }
2850         }
2851         return;
2852     }
2853
2854     /* Now work out the mapping */
2855     tex = 0;
2856     for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2857     {
2858         if (!(ffu_map & 1)) continue;
2859
2860         if (device->texUnitMap[i] != tex)
2861         {
2862             device_map_stage(device, i, tex);
2863             device_invalidate_state(device, STATE_SAMPLER(i));
2864             device_invalidate_texture_stage(device, i);
2865         }
2866
2867         ++tex;
2868     }
2869 }
2870
2871 static void device_map_psamplers(struct wined3d_device *device, const struct wined3d_gl_info *gl_info)
2872 {
2873     const enum wined3d_sampler_texture_type *sampler_type =
2874             device->stateBlock->state.pixel_shader->reg_maps.sampler_type;
2875     unsigned int i;
2876
2877     for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
2878     {
2879         if (sampler_type[i] && device->texUnitMap[i] != i)
2880         {
2881             device_map_stage(device, i, i);
2882             device_invalidate_state(device, STATE_SAMPLER(i));
2883             if (i < gl_info->limits.texture_stages)
2884                 device_invalidate_texture_stage(device, i);
2885         }
2886     }
2887 }
2888
2889 static BOOL device_unit_free_for_vs(const struct wined3d_device *device,
2890         const enum wined3d_sampler_texture_type *pshader_sampler_tokens,
2891         const enum wined3d_sampler_texture_type *vshader_sampler_tokens, DWORD unit)
2892 {
2893     DWORD current_mapping = device->rev_tex_unit_map[unit];
2894
2895     /* Not currently used */
2896     if (current_mapping == WINED3D_UNMAPPED_STAGE) return TRUE;
2897
2898     if (current_mapping < MAX_FRAGMENT_SAMPLERS) {
2899         /* Used by a fragment sampler */
2900
2901         if (!pshader_sampler_tokens) {
2902             /* No pixel shader, check fixed function */
2903             return current_mapping >= MAX_TEXTURES || !(device->fixed_function_usage_map & (1 << current_mapping));
2904         }
2905
2906         /* Pixel shader, check the shader's sampler map */
2907         return !pshader_sampler_tokens[current_mapping];
2908     }
2909
2910     /* Used by a vertex sampler */
2911     return !vshader_sampler_tokens[current_mapping - MAX_FRAGMENT_SAMPLERS];
2912 }
2913
2914 static void device_map_vsamplers(struct wined3d_device *device, BOOL ps, const struct wined3d_gl_info *gl_info)
2915 {
2916     const enum wined3d_sampler_texture_type *vshader_sampler_type =
2917             device->stateBlock->state.vertex_shader->reg_maps.sampler_type;
2918     const enum wined3d_sampler_texture_type *pshader_sampler_type = NULL;
2919     int start = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers) - 1;
2920     int i;
2921
2922     if (ps)
2923     {
2924         /* Note that we only care if a sampler is sampled or not, not the sampler's specific type.
2925          * Otherwise we'd need to call shader_update_samplers() here for 1.x pixelshaders. */
2926         pshader_sampler_type = device->stateBlock->state.pixel_shader->reg_maps.sampler_type;
2927     }
2928
2929     for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i) {
2930         DWORD vsampler_idx = i + MAX_FRAGMENT_SAMPLERS;
2931         if (vshader_sampler_type[i])
2932         {
2933             if (device->texUnitMap[vsampler_idx] != WINED3D_UNMAPPED_STAGE)
2934             {
2935                 /* Already mapped somewhere */
2936                 continue;
2937             }
2938
2939             while (start >= 0)
2940             {
2941                 if (device_unit_free_for_vs(device, pshader_sampler_type, vshader_sampler_type, start))
2942                 {
2943                     device_map_stage(device, vsampler_idx, start);
2944                     device_invalidate_state(device, STATE_SAMPLER(vsampler_idx));
2945
2946                     --start;
2947                     break;
2948                 }
2949
2950                 --start;
2951             }
2952         }
2953     }
2954 }
2955
2956 void device_update_tex_unit_map(struct wined3d_device *device)
2957 {
2958     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
2959     const struct wined3d_state *state = &device->stateBlock->state;
2960     BOOL vs = use_vs(state);
2961     BOOL ps = use_ps(state);
2962     /*
2963      * Rules are:
2964      * -> Pixel shaders need a 1:1 map. In theory the shader input could be mapped too, but
2965      * that would be really messy and require shader recompilation
2966      * -> When the mapping of a stage is changed, sampler and ALL texture stage states have
2967      * to be reset. Because of that try to work with a 1:1 mapping as much as possible
2968      */
2969     if (ps)
2970         device_map_psamplers(device, gl_info);
2971     else
2972         device_map_fixed_function_samplers(device, gl_info);
2973
2974     if (vs)
2975         device_map_vsamplers(device, ps, gl_info);
2976 }
2977
2978 HRESULT CDECL wined3d_device_set_pixel_shader(struct wined3d_device *device, struct wined3d_shader *shader)
2979 {
2980     struct wined3d_shader *prev = device->updateStateBlock->state.pixel_shader;
2981
2982     TRACE("device %p, shader %p.\n", device, shader);
2983
2984     device->updateStateBlock->state.pixel_shader = shader;
2985     device->updateStateBlock->changed.pixelShader = TRUE;
2986
2987     if (device->isRecordingState)
2988     {
2989         if (shader)
2990             wined3d_shader_incref(shader);
2991         if (prev)
2992             wined3d_shader_decref(prev);
2993         TRACE("Recording... not performing anything.\n");
2994         return WINED3D_OK;
2995     }
2996
2997     if (shader == prev)
2998     {
2999         TRACE("Application is setting the old shader over, nothing to do.\n");
3000         return WINED3D_OK;
3001     }
3002
3003     if (shader)
3004         wined3d_shader_incref(shader);
3005     if (prev)
3006         wined3d_shader_decref(prev);
3007
3008     device_invalidate_state(device, STATE_PIXELSHADER);
3009
3010     return WINED3D_OK;
3011 }
3012
3013 struct wined3d_shader * CDECL wined3d_device_get_pixel_shader(const struct wined3d_device *device)
3014 {
3015     struct wined3d_shader *shader;
3016
3017     TRACE("device %p.\n", device);
3018
3019     shader = device->stateBlock->state.pixel_shader;
3020     if (shader)
3021         wined3d_shader_incref(shader);
3022
3023     TRACE("Returning %p.\n", shader);
3024     return shader;
3025 }
3026
3027 HRESULT CDECL wined3d_device_set_ps_consts_b(struct wined3d_device *device,
3028         UINT start_register, const BOOL *constants, UINT bool_count)
3029 {
3030     UINT count = min(bool_count, MAX_CONST_B - start_register);
3031     UINT i;
3032
3033     TRACE("device %p, start_register %u, constants %p, bool_count %u.\n",
3034             device, start_register, constants, bool_count);
3035
3036     if (!constants || start_register >= MAX_CONST_B)
3037         return WINED3DERR_INVALIDCALL;
3038
3039     memcpy(&device->updateStateBlock->state.ps_consts_b[start_register], constants, count * sizeof(BOOL));
3040     for (i = 0; i < count; ++i)
3041         TRACE("Set BOOL constant %u to %s.\n", start_register + i, constants[i] ? "true" : "false");
3042
3043     for (i = start_register; i < count + start_register; ++i)
3044         device->updateStateBlock->changed.pixelShaderConstantsB |= (1 << i);
3045
3046     if (!device->isRecordingState)
3047         device_invalidate_state(device, STATE_PIXELSHADERCONSTANT);
3048
3049     return WINED3D_OK;
3050 }
3051
3052 HRESULT CDECL wined3d_device_get_ps_consts_b(const struct wined3d_device *device,
3053         UINT start_register, BOOL *constants, UINT bool_count)
3054 {
3055     UINT count = min(bool_count, MAX_CONST_B - start_register);
3056
3057     TRACE("device %p, start_register %u, constants %p, bool_count %u.\n",
3058             device, start_register, constants, bool_count);
3059
3060     if (!constants || start_register >= MAX_CONST_B)
3061         return WINED3DERR_INVALIDCALL;
3062
3063     memcpy(constants, &device->stateBlock->state.ps_consts_b[start_register], count * sizeof(BOOL));
3064
3065     return WINED3D_OK;
3066 }
3067
3068 HRESULT CDECL wined3d_device_set_ps_consts_i(struct wined3d_device *device,
3069         UINT start_register, const int *constants, UINT vector4i_count)
3070 {
3071     UINT count = min(vector4i_count, MAX_CONST_I - start_register);
3072     UINT i;
3073
3074     TRACE("device %p, start_register %u, constants %p, vector4i_count %u.\n",
3075             device, start_register, constants, vector4i_count);
3076
3077     if (!constants || start_register >= MAX_CONST_I)
3078         return WINED3DERR_INVALIDCALL;
3079
3080     memcpy(&device->updateStateBlock->state.ps_consts_i[start_register * 4], constants, count * sizeof(int) * 4);
3081     for (i = 0; i < count; ++i)
3082         TRACE("Set INT constant %u to {%d, %d, %d, %d}.\n", start_register + i,
3083                 constants[i * 4], constants[i * 4 + 1],
3084                 constants[i * 4 + 2], constants[i * 4 + 3]);
3085
3086     for (i = start_register; i < count + start_register; ++i)
3087         device->updateStateBlock->changed.pixelShaderConstantsI |= (1 << i);
3088
3089     if (!device->isRecordingState)
3090         device_invalidate_state(device, STATE_PIXELSHADERCONSTANT);
3091
3092     return WINED3D_OK;
3093 }
3094
3095 HRESULT CDECL wined3d_device_get_ps_consts_i(const struct wined3d_device *device,
3096         UINT start_register, int *constants, UINT vector4i_count)
3097 {
3098     UINT count = min(vector4i_count, MAX_CONST_I - start_register);
3099
3100     TRACE("device %p, start_register %u, constants %p, vector4i_count %u.\n",
3101             device, start_register, constants, vector4i_count);
3102
3103     if (!constants || start_register >= MAX_CONST_I)
3104         return WINED3DERR_INVALIDCALL;
3105
3106     memcpy(constants, &device->stateBlock->state.ps_consts_i[start_register * 4], count * sizeof(int) * 4);
3107
3108     return WINED3D_OK;
3109 }
3110
3111 HRESULT CDECL wined3d_device_set_ps_consts_f(struct wined3d_device *device,
3112         UINT start_register, const float *constants, UINT vector4f_count)
3113 {
3114     UINT i;
3115
3116     TRACE("device %p, start_register %u, constants %p, vector4f_count %u.\n",
3117             device, start_register, constants, vector4f_count);
3118
3119     /* Specifically test start_register > limit to catch MAX_UINT overflows
3120      * when adding start_register + vector4f_count. */
3121     if (!constants
3122             || start_register + vector4f_count > device->d3d_pshader_constantF
3123             || start_register > device->d3d_pshader_constantF)
3124         return WINED3DERR_INVALIDCALL;
3125
3126     memcpy(&device->updateStateBlock->state.ps_consts_f[start_register * 4],
3127             constants, vector4f_count * sizeof(float) * 4);
3128     if (TRACE_ON(d3d))
3129     {
3130         for (i = 0; i < vector4f_count; ++i)
3131             TRACE("Set FLOAT constant %u to {%.8e, %.8e, %.8e, %.8e}.\n", start_register + i,
3132                     constants[i * 4], constants[i * 4 + 1],
3133                     constants[i * 4 + 2], constants[i * 4 + 3]);
3134     }
3135
3136     if (!device->isRecordingState)
3137     {
3138         device->shader_backend->shader_update_float_pixel_constants(device, start_register, vector4f_count);
3139         device_invalidate_state(device, STATE_PIXELSHADERCONSTANT);
3140     }
3141
3142     memset(device->updateStateBlock->changed.pixelShaderConstantsF + start_register, 1,
3143             sizeof(*device->updateStateBlock->changed.pixelShaderConstantsF) * vector4f_count);
3144
3145     return WINED3D_OK;
3146 }
3147
3148 HRESULT CDECL wined3d_device_get_ps_consts_f(const struct wined3d_device *device,
3149         UINT start_register, float *constants, UINT vector4f_count)
3150 {
3151     int count = min(vector4f_count, device->d3d_pshader_constantF - start_register);
3152
3153     TRACE("device %p, start_register %u, constants %p, vector4f_count %u.\n",
3154             device, start_register, constants, vector4f_count);
3155
3156     if (!constants || count < 0)
3157         return WINED3DERR_INVALIDCALL;
3158
3159     memcpy(constants, &device->stateBlock->state.ps_consts_f[start_register * 4], count * sizeof(float) * 4);
3160
3161     return WINED3D_OK;
3162 }
3163
3164 /* Context activation is done by the caller. */
3165 /* Do not call while under the GL lock. */
3166 #define copy_and_next(dest, src, size) memcpy(dest, src, size); dest += (size)
3167 static HRESULT process_vertices_strided(const struct wined3d_device *device, DWORD dwDestIndex, DWORD dwCount,
3168         const struct wined3d_stream_info *stream_info, struct wined3d_buffer *dest, DWORD flags,
3169         DWORD DestFVF)
3170 {
3171     struct wined3d_matrix mat, proj_mat, view_mat, world_mat;
3172     struct wined3d_viewport vp;
3173     UINT vertex_size;
3174     unsigned int i;
3175     BYTE *dest_ptr;
3176     BOOL doClip;
3177     DWORD numTextures;
3178     HRESULT hr;
3179
3180     if (stream_info->use_map & (1 << WINED3D_FFP_NORMAL))
3181     {
3182         WARN(" lighting state not saved yet... Some strange stuff may happen !\n");
3183     }
3184
3185     if (!(stream_info->use_map & (1 << WINED3D_FFP_POSITION)))
3186     {
3187         ERR("Source has no position mask\n");
3188         return WINED3DERR_INVALIDCALL;
3189     }
3190
3191     if (device->stateBlock->state.render_states[WINED3D_RS_CLIPPING])
3192     {
3193         static BOOL warned = FALSE;
3194         /*
3195          * The clipping code is not quite correct. Some things need
3196          * to be checked against IDirect3DDevice3 (!), d3d8 and d3d9,
3197          * so disable clipping for now.
3198          * (The graphics in Half-Life are broken, and my processvertices
3199          *  test crashes with IDirect3DDevice3)
3200         doClip = TRUE;
3201          */
3202         doClip = FALSE;
3203         if(!warned) {
3204            warned = TRUE;
3205            FIXME("Clipping is broken and disabled for now\n");
3206         }
3207     }
3208     else
3209         doClip = FALSE;
3210
3211     vertex_size = get_flexible_vertex_size(DestFVF);
3212     if (FAILED(hr = wined3d_buffer_map(dest, dwDestIndex * vertex_size, dwCount * vertex_size, &dest_ptr, 0)))
3213     {
3214         WARN("Failed to map buffer, hr %#x.\n", hr);
3215         return hr;
3216     }
3217
3218     wined3d_device_get_transform(device, WINED3D_TS_VIEW, &view_mat);
3219     wined3d_device_get_transform(device, WINED3D_TS_PROJECTION, &proj_mat);
3220     wined3d_device_get_transform(device, WINED3D_TS_WORLD_MATRIX(0), &world_mat);
3221
3222     TRACE("View mat:\n");
3223     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);
3224     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);
3225     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);
3226     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);
3227
3228     TRACE("Proj mat:\n");
3229     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);
3230     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);
3231     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);
3232     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);
3233
3234     TRACE("World mat:\n");
3235     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);
3236     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);
3237     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);
3238     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);
3239
3240     /* Get the viewport */
3241     wined3d_device_get_viewport(device, &vp);
3242     TRACE("viewport  x %u, y %u, width %u, height %u, min_z %.8e, max_z %.8e.\n",
3243           vp.x, vp.y, vp.width, vp.height, vp.min_z, vp.max_z);
3244
3245     multiply_matrix(&mat,&view_mat,&world_mat);
3246     multiply_matrix(&mat,&proj_mat,&mat);
3247
3248     numTextures = (DestFVF & WINED3DFVF_TEXCOUNT_MASK) >> WINED3DFVF_TEXCOUNT_SHIFT;
3249
3250     for (i = 0; i < dwCount; i+= 1) {
3251         unsigned int tex_index;
3252
3253         if ( ((DestFVF & WINED3DFVF_POSITION_MASK) == WINED3DFVF_XYZ ) ||
3254              ((DestFVF & WINED3DFVF_POSITION_MASK) == WINED3DFVF_XYZRHW ) ) {
3255             /* The position first */
3256             const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_POSITION];
3257             const float *p = (const float *)(element->data.addr + i * element->stride);
3258             float x, y, z, rhw;
3259             TRACE("In: ( %06.2f %06.2f %06.2f )\n", p[0], p[1], p[2]);
3260
3261             /* Multiplication with world, view and projection matrix */
3262             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);
3263             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);
3264             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);
3265             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);
3266
3267             TRACE("x=%f y=%f z=%f rhw=%f\n", x, y, z, rhw);
3268
3269             /* WARNING: The following things are taken from d3d7 and were not yet checked
3270              * against d3d8 or d3d9!
3271              */
3272
3273             /* Clipping conditions: From msdn
3274              *
3275              * A vertex is clipped if it does not match the following requirements
3276              * -rhw < x <= rhw
3277              * -rhw < y <= rhw
3278              *    0 < z <= rhw
3279              *    0 < rhw ( Not in d3d7, but tested in d3d7)
3280              *
3281              * If clipping is on is determined by the D3DVOP_CLIP flag in D3D7, and
3282              * by the D3DRS_CLIPPING in D3D9(according to the msdn, not checked)
3283              *
3284              */
3285
3286             if( !doClip ||
3287                 ( (-rhw -eps < x) && (-rhw -eps < y) && ( -eps < z) &&
3288                   (x <= rhw + eps) && (y <= rhw + eps ) && (z <= rhw + eps) &&
3289                   ( rhw > eps ) ) ) {
3290
3291                 /* "Normal" viewport transformation (not clipped)
3292                  * 1) The values are divided by rhw
3293                  * 2) The y axis is negative, so multiply it with -1
3294                  * 3) Screen coordinates go from -(Width/2) to +(Width/2) and
3295                  *    -(Height/2) to +(Height/2). The z range is MinZ to MaxZ
3296                  * 4) Multiply x with Width/2 and add Width/2
3297                  * 5) The same for the height
3298                  * 6) Add the viewpoint X and Y to the 2D coordinates and
3299                  *    The minimum Z value to z
3300                  * 7) rhw = 1 / rhw Reciprocal of Homogeneous W....
3301                  *
3302                  * Well, basically it's simply a linear transformation into viewport
3303                  * coordinates
3304                  */
3305
3306                 x /= rhw;
3307                 y /= rhw;
3308                 z /= rhw;
3309
3310                 y *= -1;
3311
3312                 x *= vp.width / 2;
3313                 y *= vp.height / 2;
3314                 z *= vp.max_z - vp.min_z;
3315
3316                 x += vp.width / 2 + vp.x;
3317                 y += vp.height / 2 + vp.y;
3318                 z += vp.min_z;
3319
3320                 rhw = 1 / rhw;
3321             } else {
3322                 /* That vertex got clipped
3323                  * Contrary to OpenGL it is not dropped completely, it just
3324                  * undergoes a different calculation.
3325                  */
3326                 TRACE("Vertex got clipped\n");
3327                 x += rhw;
3328                 y += rhw;
3329
3330                 x  /= 2;
3331                 y  /= 2;
3332
3333                 /* Msdn mentions that Direct3D9 keeps a list of clipped vertices
3334                  * outside of the main vertex buffer memory. That needs some more
3335                  * investigation...
3336                  */
3337             }
3338
3339             TRACE("Writing (%f %f %f) %f\n", x, y, z, rhw);
3340
3341
3342             ( (float *) dest_ptr)[0] = x;
3343             ( (float *) dest_ptr)[1] = y;
3344             ( (float *) dest_ptr)[2] = z;
3345             ( (float *) dest_ptr)[3] = rhw; /* SIC, see ddraw test! */
3346
3347             dest_ptr += 3 * sizeof(float);
3348
3349             if ((DestFVF & WINED3DFVF_POSITION_MASK) == WINED3DFVF_XYZRHW)
3350                 dest_ptr += sizeof(float);
3351         }
3352
3353         if (DestFVF & WINED3DFVF_PSIZE)
3354             dest_ptr += sizeof(DWORD);
3355
3356         if (DestFVF & WINED3DFVF_NORMAL)
3357         {
3358             const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_NORMAL];
3359             const float *normal = (const float *)(element->data.addr + i * element->stride);
3360             /* AFAIK this should go into the lighting information */
3361             FIXME("Didn't expect the destination to have a normal\n");
3362             copy_and_next(dest_ptr, normal, 3 * sizeof(float));
3363         }
3364
3365         if (DestFVF & WINED3DFVF_DIFFUSE)
3366         {
3367             const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_DIFFUSE];
3368             const DWORD *color_d = (const DWORD *)(element->data.addr + i * element->stride);
3369             if (!(stream_info->use_map & (1 << WINED3D_FFP_DIFFUSE)))
3370             {
3371                 static BOOL warned = FALSE;
3372
3373                 if(!warned) {
3374                     ERR("No diffuse color in source, but destination has one\n");
3375                     warned = TRUE;
3376                 }
3377
3378                 *( (DWORD *) dest_ptr) = 0xffffffff;
3379                 dest_ptr += sizeof(DWORD);
3380             }
3381             else
3382             {
3383                 copy_and_next(dest_ptr, color_d, sizeof(DWORD));
3384             }
3385         }
3386
3387         if (DestFVF & WINED3DFVF_SPECULAR)
3388         {
3389             /* What's the color value in the feedback buffer? */
3390             const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_SPECULAR];
3391             const DWORD *color_s = (const DWORD *)(element->data.addr + i * element->stride);
3392             if (!(stream_info->use_map & (1 << WINED3D_FFP_SPECULAR)))
3393             {
3394                 static BOOL warned = FALSE;
3395
3396                 if(!warned) {
3397                     ERR("No specular color in source, but destination has one\n");
3398                     warned = TRUE;
3399                 }
3400
3401                 *( (DWORD *) dest_ptr) = 0xFF000000;
3402                 dest_ptr += sizeof(DWORD);
3403             }
3404             else
3405             {
3406                 copy_and_next(dest_ptr, color_s, sizeof(DWORD));
3407             }
3408         }
3409
3410         for (tex_index = 0; tex_index < numTextures; ++tex_index)
3411         {
3412             const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_TEXCOORD0 + tex_index];
3413             const float *tex_coord = (const float *)(element->data.addr + i * element->stride);
3414             if (!(stream_info->use_map & (1 << (WINED3D_FFP_TEXCOORD0 + tex_index))))
3415             {
3416                 ERR("No source texture, but destination requests one\n");
3417                 dest_ptr += GET_TEXCOORD_SIZE_FROM_FVF(DestFVF, tex_index) * sizeof(float);
3418             }
3419             else
3420             {
3421                 copy_and_next(dest_ptr, tex_coord, GET_TEXCOORD_SIZE_FROM_FVF(DestFVF, tex_index) * sizeof(float));
3422             }
3423         }
3424     }
3425
3426     wined3d_buffer_unmap(dest);
3427
3428     return WINED3D_OK;
3429 }
3430 #undef copy_and_next
3431
3432 /* Do not call while under the GL lock. */
3433 HRESULT CDECL wined3d_device_process_vertices(struct wined3d_device *device,
3434         UINT src_start_idx, UINT dst_idx, UINT vertex_count, struct wined3d_buffer *dst_buffer,
3435         const struct wined3d_vertex_declaration *declaration, DWORD flags, DWORD dst_fvf)
3436 {
3437     struct wined3d_state *state = &device->stateBlock->state;
3438     struct wined3d_stream_info stream_info;
3439     const struct wined3d_gl_info *gl_info;
3440     BOOL streamWasUP = state->user_stream;
3441     struct wined3d_context *context;
3442     struct wined3d_shader *vs;
3443     unsigned int i;
3444     HRESULT hr;
3445
3446     TRACE("device %p, src_start_idx %u, dst_idx %u, vertex_count %u, "
3447             "dst_buffer %p, declaration %p, flags %#x, dst_fvf %#x.\n",
3448             device, src_start_idx, dst_idx, vertex_count,
3449             dst_buffer, declaration, flags, dst_fvf);
3450
3451     if (declaration)
3452         FIXME("Output vertex declaration not implemented yet.\n");
3453
3454     /* Need any context to write to the vbo. */
3455     context = context_acquire(device, NULL);
3456     gl_info = context->gl_info;
3457
3458     /* ProcessVertices reads from vertex buffers, which have to be assigned.
3459      * DrawPrimitive and DrawPrimitiveUP control the streamIsUP flag, thus
3460      * restore it afterwards. */
3461     vs = state->vertex_shader;
3462     state->vertex_shader = NULL;
3463     state->user_stream = FALSE;
3464     device_stream_info_from_declaration(device, &stream_info);
3465     state->user_stream = streamWasUP;
3466     state->vertex_shader = vs;
3467
3468     /* We can't convert FROM a VBO, and vertex buffers used to source into
3469      * process_vertices() are unlikely to ever be used for drawing. Release
3470      * VBOs in those buffers and fix up the stream_info structure.
3471      *
3472      * Also apply the start index. */
3473     for (i = 0; i < (sizeof(stream_info.elements) / sizeof(*stream_info.elements)); ++i)
3474     {
3475         struct wined3d_stream_info_element *e;
3476
3477         if (!(stream_info.use_map & (1 << i)))
3478             continue;
3479
3480         e = &stream_info.elements[i];
3481         if (e->data.buffer_object)
3482         {
3483             struct wined3d_buffer *vb = state->streams[e->stream_idx].buffer;
3484             e->data.buffer_object = 0;
3485             e->data.addr = (BYTE *)((ULONG_PTR)e->data.addr + (ULONG_PTR)buffer_get_sysmem(vb, gl_info));
3486             ENTER_GL();
3487             GL_EXTCALL(glDeleteBuffersARB(1, &vb->buffer_object));
3488             vb->buffer_object = 0;
3489             LEAVE_GL();
3490         }
3491         if (e->data.addr)
3492             e->data.addr += e->stride * src_start_idx;
3493     }
3494
3495     hr = process_vertices_strided(device, dst_idx, vertex_count,
3496             &stream_info, dst_buffer, flags, dst_fvf);
3497
3498     context_release(context);
3499
3500     return hr;
3501 }
3502
3503 HRESULT CDECL wined3d_device_set_texture_stage_state(struct wined3d_device *device,
3504         UINT stage, enum wined3d_texture_stage_state state, DWORD value)
3505 {
3506     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
3507     DWORD old_value;
3508
3509     TRACE("device %p, stage %u, state %s, value %#x.\n",
3510             device, stage, debug_d3dtexturestate(state), value);
3511
3512     if (state > WINED3D_HIGHEST_TEXTURE_STATE)
3513     {
3514         WARN("Invalid state %#x passed.\n", state);
3515         return WINED3D_OK;
3516     }
3517
3518     if (stage >= gl_info->limits.texture_stages)
3519     {
3520         WARN("Attempting to set stage %u which is higher than the max stage %u, ignoring.\n",
3521                 stage, gl_info->limits.texture_stages - 1);
3522         return WINED3D_OK;
3523     }
3524
3525     old_value = device->updateStateBlock->state.texture_states[stage][state];
3526     device->updateStateBlock->changed.textureState[stage] |= 1 << state;
3527     device->updateStateBlock->state.texture_states[stage][state] = value;
3528
3529     if (device->isRecordingState)
3530     {
3531         TRACE("Recording... not performing anything.\n");
3532         return WINED3D_OK;
3533     }
3534
3535     /* Checked after the assignments to allow proper stateblock recording. */
3536     if (old_value == value)
3537     {
3538         TRACE("Application is setting the old value over, nothing to do.\n");
3539         return WINED3D_OK;
3540     }
3541
3542     if (stage > device->stateBlock->state.lowest_disabled_stage
3543             && device->StateTable[STATE_TEXTURESTAGE(0, state)].representative
3544             == STATE_TEXTURESTAGE(0, WINED3D_TSS_COLOR_OP))
3545     {
3546         /* Colorop change above lowest disabled stage? That won't change
3547          * anything in the GL setup. Changes in other states are important on
3548          * disabled stages too. */
3549         return WINED3D_OK;
3550     }
3551
3552     if (state == WINED3D_TSS_COLOR_OP)
3553     {
3554         unsigned int i;
3555
3556         if (value == WINED3D_TOP_DISABLE && old_value != WINED3D_TOP_DISABLE)
3557         {
3558             /* Previously enabled stage disabled now. Make sure to dirtify
3559              * all enabled stages above stage, they have to be disabled.
3560              *
3561              * The current stage is dirtified below. */
3562             for (i = stage + 1; i < device->stateBlock->state.lowest_disabled_stage; ++i)
3563             {
3564                 TRACE("Additionally dirtifying stage %u.\n", i);
3565                 device_invalidate_state(device, STATE_TEXTURESTAGE(i, WINED3D_TSS_COLOR_OP));
3566             }
3567             device->stateBlock->state.lowest_disabled_stage = stage;
3568             TRACE("New lowest disabled: %u.\n", stage);
3569         }
3570         else if (value != WINED3D_TOP_DISABLE && old_value == WINED3D_TOP_DISABLE)
3571         {
3572             /* Previously disabled stage enabled. Stages above it may need
3573              * enabling. Stage must be lowest_disabled_stage here, if it's
3574              * bigger success is returned above, and stages below the lowest
3575              * disabled stage can't be enabled (because they are enabled
3576              * already).
3577              *
3578              * Again stage stage doesn't need to be dirtified here, it is
3579              * handled below. */
3580             for (i = stage + 1; i < gl_info->limits.texture_stages; ++i)
3581             {
3582                 if (device->updateStateBlock->state.texture_states[i][WINED3D_TSS_COLOR_OP] == WINED3D_TOP_DISABLE)
3583                     break;
3584                 TRACE("Additionally dirtifying stage %u due to enable.\n", i);
3585                 device_invalidate_state(device, STATE_TEXTURESTAGE(i, WINED3D_TSS_COLOR_OP));
3586             }
3587             device->stateBlock->state.lowest_disabled_stage = i;
3588             TRACE("New lowest disabled: %u.\n", i);
3589         }
3590     }
3591
3592     device_invalidate_state(device, STATE_TEXTURESTAGE(stage, state));
3593
3594     return WINED3D_OK;
3595 }
3596
3597 HRESULT CDECL wined3d_device_get_texture_stage_state(const struct wined3d_device *device,
3598         UINT stage, enum wined3d_texture_stage_state state, DWORD *value)
3599 {
3600     TRACE("device %p, stage %u, state %s, value %p.\n",
3601             device, stage, debug_d3dtexturestate(state), value);
3602
3603     if (state > WINED3D_HIGHEST_TEXTURE_STATE)
3604     {
3605         WARN("Invalid state %#x passed.\n", state);
3606         return WINED3D_OK;
3607     }
3608
3609     *value = device->updateStateBlock->state.texture_states[stage][state];
3610     TRACE("Returning %#x.\n", *value);
3611
3612     return WINED3D_OK;
3613 }
3614
3615 HRESULT CDECL wined3d_device_set_texture(struct wined3d_device *device,
3616         UINT stage, struct wined3d_texture *texture)
3617 {
3618     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
3619     struct wined3d_texture *prev;
3620
3621     TRACE("device %p, stage %u, texture %p.\n", device, stage, texture);
3622
3623     if (stage >= WINED3DVERTEXTEXTURESAMPLER0 && stage <= WINED3DVERTEXTEXTURESAMPLER3)
3624         stage -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
3625
3626     /* Windows accepts overflowing this array... we do not. */
3627     if (stage >= sizeof(device->stateBlock->state.textures) / sizeof(*device->stateBlock->state.textures))
3628     {
3629         WARN("Ignoring invalid stage %u.\n", stage);
3630         return WINED3D_OK;
3631     }
3632
3633     if (texture && texture->resource.pool == WINED3D_POOL_SCRATCH)
3634     {
3635         WARN("Rejecting attempt to set scratch texture.\n");
3636         return WINED3DERR_INVALIDCALL;
3637     }
3638
3639     device->updateStateBlock->changed.textures |= 1 << stage;
3640
3641     prev = device->updateStateBlock->state.textures[stage];
3642     TRACE("Previous texture %p.\n", prev);
3643
3644     if (texture == prev)
3645     {
3646         TRACE("App is setting the same texture again, nothing to do.\n");
3647         return WINED3D_OK;
3648     }
3649
3650     TRACE("Setting new texture to %p.\n", texture);
3651     device->updateStateBlock->state.textures[stage] = texture;
3652
3653     if (device->isRecordingState)
3654     {
3655         TRACE("Recording... not performing anything\n");
3656
3657         if (texture) wined3d_texture_incref(texture);
3658         if (prev) wined3d_texture_decref(prev);
3659
3660         return WINED3D_OK;
3661     }
3662
3663     if (texture)
3664     {
3665         LONG bind_count = InterlockedIncrement(&texture->resource.bind_count);
3666
3667         wined3d_texture_incref(texture);
3668
3669         if (!prev || texture->target != prev->target)
3670             device_invalidate_state(device, STATE_PIXELSHADER);
3671
3672         if (!prev && stage < gl_info->limits.texture_stages)
3673         {
3674             /* The source arguments for color and alpha ops have different
3675              * meanings when a NULL texture is bound, so the COLOR_OP and
3676              * ALPHA_OP have to be dirtified. */
3677             device_invalidate_state(device, STATE_TEXTURESTAGE(stage, WINED3D_TSS_COLOR_OP));
3678             device_invalidate_state(device, STATE_TEXTURESTAGE(stage, WINED3D_TSS_ALPHA_OP));
3679         }
3680
3681         if (bind_count == 1)
3682             texture->sampler = stage;
3683     }
3684
3685     if (prev)
3686     {
3687         LONG bind_count = InterlockedDecrement(&prev->resource.bind_count);
3688
3689         wined3d_texture_decref(prev);
3690
3691         if (!texture && stage < gl_info->limits.texture_stages)
3692         {
3693             device_invalidate_state(device, STATE_TEXTURESTAGE(stage, WINED3D_TSS_COLOR_OP));
3694             device_invalidate_state(device, STATE_TEXTURESTAGE(stage, WINED3D_TSS_ALPHA_OP));
3695         }
3696
3697         if (bind_count && prev->sampler == stage)
3698         {
3699             unsigned int i;
3700
3701             /* Search for other stages the texture is bound to. Shouldn't
3702              * happen if applications bind textures to a single stage only. */
3703             TRACE("Searching for other stages the texture is bound to.\n");
3704             for (i = 0; i < MAX_COMBINED_SAMPLERS; ++i)
3705             {
3706                 if (device->updateStateBlock->state.textures[i] == prev)
3707                 {
3708                     TRACE("Texture is also bound to stage %u.\n", i);
3709                     prev->sampler = i;
3710                     break;
3711                 }
3712             }
3713         }
3714     }
3715
3716     device_invalidate_state(device, STATE_SAMPLER(stage));
3717
3718     return WINED3D_OK;
3719 }
3720
3721 HRESULT CDECL wined3d_device_get_texture(const struct wined3d_device *device,
3722         UINT stage, struct wined3d_texture **texture)
3723 {
3724     TRACE("device %p, stage %u, texture %p.\n", device, stage, texture);
3725
3726     if (stage >= WINED3DVERTEXTEXTURESAMPLER0 && stage <= WINED3DVERTEXTEXTURESAMPLER3)
3727         stage -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
3728
3729     if (stage >= sizeof(device->stateBlock->state.textures) / sizeof(*device->stateBlock->state.textures))
3730     {
3731         WARN("Ignoring invalid stage %u.\n", stage);
3732         return WINED3D_OK; /* Windows accepts overflowing this array ... we do not. */
3733     }
3734
3735     *texture = device->stateBlock->state.textures[stage];
3736     if (*texture)
3737         wined3d_texture_incref(*texture);
3738
3739     TRACE("Returning %p.\n", *texture);
3740
3741     return WINED3D_OK;
3742 }
3743
3744 HRESULT CDECL wined3d_device_get_back_buffer(const struct wined3d_device *device, UINT swapchain_idx,
3745         UINT backbuffer_idx, enum wined3d_backbuffer_type backbuffer_type, struct wined3d_surface **backbuffer)
3746 {
3747     struct wined3d_swapchain *swapchain;
3748     HRESULT hr;
3749
3750     TRACE("device %p, swapchain_idx %u, backbuffer_idx %u, backbuffer_type %#x, backbuffer %p.\n",
3751             device, swapchain_idx, backbuffer_idx, backbuffer_type, backbuffer);
3752
3753     hr = wined3d_device_get_swapchain(device, swapchain_idx, &swapchain);
3754     if (FAILED(hr))
3755     {
3756         WARN("Failed to get swapchain %u, hr %#x.\n", swapchain_idx, hr);
3757         return hr;
3758     }
3759
3760     hr = wined3d_swapchain_get_back_buffer(swapchain, backbuffer_idx, backbuffer_type, backbuffer);
3761     wined3d_swapchain_decref(swapchain);
3762     if (FAILED(hr))
3763     {
3764         WARN("Failed to get backbuffer %u, hr %#x.\n", backbuffer_idx, hr);
3765         return hr;
3766     }
3767
3768     return WINED3D_OK;
3769 }
3770
3771 HRESULT CDECL wined3d_device_get_device_caps(const struct wined3d_device *device, WINED3DCAPS *caps)
3772 {
3773     TRACE("device %p, caps %p.\n", device, caps);
3774
3775     return wined3d_get_device_caps(device->wined3d, device->adapter->ordinal,
3776             device->create_parms.device_type, caps);
3777 }
3778
3779 HRESULT CDECL wined3d_device_get_display_mode(const struct wined3d_device *device,
3780         UINT swapchain_idx, struct wined3d_display_mode *mode)
3781 {
3782     struct wined3d_swapchain *swapchain;
3783     HRESULT hr;
3784
3785     TRACE("device %p, swapchain_idx %u, mode %p.\n", device, swapchain_idx, mode);
3786
3787     if (swapchain_idx)
3788     {
3789         hr = wined3d_device_get_swapchain(device, swapchain_idx, &swapchain);
3790         if (SUCCEEDED(hr))
3791         {
3792             hr = wined3d_swapchain_get_display_mode(swapchain, mode);
3793             wined3d_swapchain_decref(swapchain);
3794         }
3795     }
3796     else
3797     {
3798         const struct wined3d_adapter *adapter = device->adapter;
3799
3800         /* Don't read the real display mode, but return the stored mode
3801          * instead. X11 can't change the color depth, and some apps are
3802          * pretty angry if they SetDisplayMode from 24 to 16 bpp and find out
3803          * that GetDisplayMode still returns 24 bpp.
3804          *
3805          * Also don't relay to the swapchain because with ddraw it's possible
3806          * that there isn't a swapchain at all. */
3807         mode->width = adapter->screen_size.cx;
3808         mode->height = adapter->screen_size.cy;
3809         mode->format_id = adapter->screen_format;
3810         mode->refresh_rate = 0;
3811         hr = WINED3D_OK;
3812     }
3813
3814     return hr;
3815 }
3816
3817 HRESULT CDECL wined3d_device_begin_stateblock(struct wined3d_device *device)
3818 {
3819     struct wined3d_stateblock *stateblock;
3820     HRESULT hr;
3821
3822     TRACE("device %p.\n", device);
3823
3824     if (device->isRecordingState)
3825         return WINED3DERR_INVALIDCALL;
3826
3827     hr = wined3d_stateblock_create(device, WINED3D_SBT_RECORDED, &stateblock);
3828     if (FAILED(hr))
3829         return hr;
3830
3831     wined3d_stateblock_decref(device->updateStateBlock);
3832     device->updateStateBlock = stateblock;
3833     device->isRecordingState = TRUE;
3834
3835     TRACE("Recording stateblock %p.\n", stateblock);
3836
3837     return WINED3D_OK;
3838 }
3839
3840 HRESULT CDECL wined3d_device_end_stateblock(struct wined3d_device *device,
3841         struct wined3d_stateblock **stateblock)
3842 {
3843     struct wined3d_stateblock *object = device->updateStateBlock;
3844
3845     TRACE("device %p, stateblock %p.\n", device, stateblock);
3846
3847     if (!device->isRecordingState)
3848     {
3849         WARN("Not recording.\n");
3850         *stateblock = NULL;
3851         return WINED3DERR_INVALIDCALL;
3852     }
3853
3854     stateblock_init_contained_states(object);
3855
3856     *stateblock = object;
3857     device->isRecordingState = FALSE;
3858     device->updateStateBlock = device->stateBlock;
3859     wined3d_stateblock_incref(device->updateStateBlock);
3860
3861     TRACE("Returning stateblock %p.\n", *stateblock);
3862
3863     return WINED3D_OK;
3864 }
3865
3866 HRESULT CDECL wined3d_device_begin_scene(struct wined3d_device *device)
3867 {
3868     /* At the moment we have no need for any functionality at the beginning
3869      * of a scene. */
3870     TRACE("device %p.\n", device);
3871
3872     if (device->inScene)
3873     {
3874         WARN("Already in scene, returning WINED3DERR_INVALIDCALL.\n");
3875         return WINED3DERR_INVALIDCALL;
3876     }
3877     device->inScene = TRUE;
3878     return WINED3D_OK;
3879 }
3880
3881 HRESULT CDECL wined3d_device_end_scene(struct wined3d_device *device)
3882 {
3883     struct wined3d_context *context;
3884
3885     TRACE("device %p.\n", device);
3886
3887     if (!device->inScene)
3888     {
3889         WARN("Not in scene, returning WINED3DERR_INVALIDCALL.\n");
3890         return WINED3DERR_INVALIDCALL;
3891     }
3892
3893     context = context_acquire(device, NULL);
3894     /* We only have to do this if we need to read the, swapbuffers performs a flush for us */
3895     wglFlush();
3896     /* No checkGLcall here to avoid locking the lock just for checking a call that hardly ever
3897      * fails. */
3898     context_release(context);
3899
3900     device->inScene = FALSE;
3901     return WINED3D_OK;
3902 }
3903
3904 HRESULT CDECL wined3d_device_present(const struct wined3d_device *device, const RECT *src_rect,
3905         const RECT *dst_rect, HWND dst_window_override, const RGNDATA *dirty_region)
3906 {
3907     UINT i;
3908
3909     TRACE("device %p, src_rect %s, dst_rect %s, dst_window_override %p, dirty_region %p.\n",
3910             device, wine_dbgstr_rect(src_rect), wine_dbgstr_rect(dst_rect),
3911             dst_window_override, dirty_region);
3912
3913     for (i = 0; i < device->swapchain_count; ++i)
3914     {
3915         wined3d_swapchain_present(device->swapchains[i], src_rect,
3916                 dst_rect, dst_window_override, dirty_region, 0);
3917     }
3918
3919     return WINED3D_OK;
3920 }
3921
3922 /* Do not call while under the GL lock. */
3923 HRESULT CDECL wined3d_device_clear(struct wined3d_device *device, DWORD rect_count,
3924         const RECT *rects, DWORD flags, const struct wined3d_color *color, float depth, DWORD stencil)
3925 {
3926     RECT draw_rect;
3927
3928     TRACE("device %p, rect_count %u, rects %p, flags %#x, color {%.8e, %.8e, %.8e, %.8e}, depth %.8e, stencil %u.\n",
3929             device, rect_count, rects, flags, color->r, color->g, color->b, color->a, depth, stencil);
3930
3931     if (flags & (WINED3DCLEAR_ZBUFFER | WINED3DCLEAR_STENCIL))
3932     {
3933         struct wined3d_surface *ds = device->fb.depth_stencil;
3934         if (!ds)
3935         {
3936             WARN("Clearing depth and/or stencil without a depth stencil buffer attached, returning WINED3DERR_INVALIDCALL\n");
3937             /* TODO: What about depth stencil buffers without stencil bits? */
3938             return WINED3DERR_INVALIDCALL;
3939         }
3940         else if (flags & WINED3DCLEAR_TARGET)
3941         {
3942             if (ds->resource.width < device->fb.render_targets[0]->resource.width
3943                     || ds->resource.height < device->fb.render_targets[0]->resource.height)
3944             {
3945                 WARN("Silently ignoring depth and target clear with mismatching sizes\n");
3946                 return WINED3D_OK;
3947             }
3948         }
3949     }
3950
3951     wined3d_get_draw_rect(&device->stateBlock->state, &draw_rect);
3952     device_clear_render_targets(device, device->adapter->gl_info.limits.buffers,
3953             &device->fb, rect_count, rects, &draw_rect, flags, color, depth, stencil);
3954
3955     return WINED3D_OK;
3956 }
3957
3958 void CDECL wined3d_device_set_primitive_type(struct wined3d_device *device,
3959         enum wined3d_primitive_type primitive_type)
3960 {
3961     TRACE("device %p, primitive_type %s\n", device, debug_d3dprimitivetype(primitive_type));
3962
3963     device->updateStateBlock->changed.primitive_type = TRUE;
3964     device->updateStateBlock->state.gl_primitive_type = gl_primitive_type_from_d3d(primitive_type);
3965 }
3966
3967 void CDECL wined3d_device_get_primitive_type(const struct wined3d_device *device,
3968         enum wined3d_primitive_type *primitive_type)
3969 {
3970     TRACE("device %p, primitive_type %p\n", device, primitive_type);
3971
3972     *primitive_type = d3d_primitive_type_from_gl(device->stateBlock->state.gl_primitive_type);
3973
3974     TRACE("Returning %s\n", debug_d3dprimitivetype(*primitive_type));
3975 }
3976
3977 HRESULT CDECL wined3d_device_draw_primitive(struct wined3d_device *device, UINT start_vertex, UINT vertex_count)
3978 {
3979     TRACE("device %p, start_vertex %u, vertex_count %u.\n", device, start_vertex, vertex_count);
3980
3981     if (!device->stateBlock->state.vertex_declaration)
3982     {
3983         WARN("Called without a valid vertex declaration set.\n");
3984         return WINED3DERR_INVALIDCALL;
3985     }
3986
3987     /* The index buffer is not needed here, but restore it, otherwise it is hell to keep track of */
3988     if (device->stateBlock->state.user_stream)
3989     {
3990         device_invalidate_state(device, STATE_INDEXBUFFER);
3991         device->stateBlock->state.user_stream = FALSE;
3992     }
3993
3994     if (device->stateBlock->state.load_base_vertex_index)
3995     {
3996         device->stateBlock->state.load_base_vertex_index = 0;
3997         device_invalidate_state(device, STATE_BASEVERTEXINDEX);
3998     }
3999
4000     /* Account for the loading offset due to index buffers. Instead of
4001      * reloading all sources correct it with the startvertex parameter. */
4002     drawPrimitive(device, vertex_count, start_vertex, FALSE, NULL);
4003     return WINED3D_OK;
4004 }
4005
4006 HRESULT CDECL wined3d_device_draw_indexed_primitive(struct wined3d_device *device, UINT start_idx, UINT index_count)
4007 {
4008     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4009
4010     TRACE("device %p, start_idx %u, index_count %u.\n", device, start_idx, index_count);
4011
4012     if (!device->stateBlock->state.index_buffer)
4013     {
4014         /* D3D9 returns D3DERR_INVALIDCALL when DrawIndexedPrimitive is called
4015          * without an index buffer set. (The first time at least...)
4016          * D3D8 simply dies, but I doubt it can do much harm to return
4017          * D3DERR_INVALIDCALL there as well. */
4018         WARN("Called without a valid index buffer set, returning WINED3DERR_INVALIDCALL.\n");
4019         return WINED3DERR_INVALIDCALL;
4020     }
4021
4022     if (!device->stateBlock->state.vertex_declaration)
4023     {
4024         WARN("Called without a valid vertex declaration set.\n");
4025         return WINED3DERR_INVALIDCALL;
4026     }
4027
4028     if (device->stateBlock->state.user_stream)
4029     {
4030         device_invalidate_state(device, STATE_INDEXBUFFER);
4031         device->stateBlock->state.user_stream = FALSE;
4032     }
4033
4034     if (!gl_info->supported[ARB_DRAW_ELEMENTS_BASE_VERTEX] &&
4035         device->stateBlock->state.load_base_vertex_index != device->stateBlock->state.base_vertex_index)
4036     {
4037         device->stateBlock->state.load_base_vertex_index = device->stateBlock->state.base_vertex_index;
4038         device_invalidate_state(device, STATE_BASEVERTEXINDEX);
4039     }
4040
4041     drawPrimitive(device, index_count, start_idx, TRUE, NULL);
4042
4043     return WINED3D_OK;
4044 }
4045
4046 HRESULT CDECL wined3d_device_draw_primitive_up(struct wined3d_device *device, UINT vertex_count,
4047         const void *stream_data, UINT stream_stride)
4048 {
4049     struct wined3d_stream_state *stream;
4050     struct wined3d_buffer *vb;
4051
4052     TRACE("device %p, vertex count %u, stream_data %p, stream_stride %u.\n",
4053             device, vertex_count, stream_data, stream_stride);
4054
4055     if (!device->stateBlock->state.vertex_declaration)
4056     {
4057         WARN("Called without a valid vertex declaration set.\n");
4058         return WINED3DERR_INVALIDCALL;
4059     }
4060
4061     /* Note in the following, it's not this type, but that's the purpose of streamIsUP */
4062     stream = &device->stateBlock->state.streams[0];
4063     vb = stream->buffer;
4064     stream->buffer = (struct wined3d_buffer *)stream_data;
4065     if (vb)
4066         wined3d_buffer_decref(vb);
4067     stream->offset = 0;
4068     stream->stride = stream_stride;
4069     device->stateBlock->state.user_stream = TRUE;
4070     if (device->stateBlock->state.load_base_vertex_index)
4071     {
4072         device->stateBlock->state.load_base_vertex_index = 0;
4073         device_invalidate_state(device, STATE_BASEVERTEXINDEX);
4074     }
4075
4076     /* TODO: Only mark dirty if drawing from a different UP address */
4077     device_invalidate_state(device, STATE_STREAMSRC);
4078
4079     drawPrimitive(device, vertex_count, 0, FALSE, NULL);
4080
4081     /* MSDN specifies stream zero settings must be set to NULL */
4082     stream->buffer = NULL;
4083     stream->stride = 0;
4084
4085     /* stream zero settings set to null at end, as per the msdn. No need to
4086      * mark dirty here, the app has to set the new stream sources or use UP
4087      * drawing again. */
4088     return WINED3D_OK;
4089 }
4090
4091 HRESULT CDECL wined3d_device_draw_indexed_primitive_up(struct wined3d_device *device,
4092         UINT index_count, const void *index_data, enum wined3d_format_id index_data_format_id,
4093         const void *stream_data, UINT stream_stride)
4094 {
4095     struct wined3d_stream_state *stream;
4096     struct wined3d_buffer *vb, *ib;
4097
4098     TRACE("device %p, index_count %u, index_data %p, index_data_format %s, stream_data %p, stream_stride %u.\n",
4099             device, index_count, index_data, debug_d3dformat(index_data_format_id), stream_data, stream_stride);
4100
4101     if (!device->stateBlock->state.vertex_declaration)
4102     {
4103         WARN("(%p) : Called without a valid vertex declaration set\n", device);
4104         return WINED3DERR_INVALIDCALL;
4105     }
4106
4107     stream = &device->stateBlock->state.streams[0];
4108     vb = stream->buffer;
4109     stream->buffer = (struct wined3d_buffer *)stream_data;
4110     if (vb)
4111         wined3d_buffer_decref(vb);
4112     stream->offset = 0;
4113     stream->stride = stream_stride;
4114     device->stateBlock->state.user_stream = TRUE;
4115     device->stateBlock->state.index_format = index_data_format_id;
4116
4117     /* Set to 0 as per msdn. Do it now due to the stream source loading during drawPrimitive */
4118     device->stateBlock->state.base_vertex_index = 0;
4119     if (device->stateBlock->state.load_base_vertex_index)
4120     {
4121         device->stateBlock->state.load_base_vertex_index = 0;
4122         device_invalidate_state(device, STATE_BASEVERTEXINDEX);
4123     }
4124     /* Invalidate the state until we have nicer tracking of the stream source pointers */
4125     device_invalidate_state(device, STATE_STREAMSRC);
4126     device_invalidate_state(device, STATE_INDEXBUFFER);
4127
4128     drawPrimitive(device, index_count, 0, TRUE, index_data);
4129
4130     /* MSDN specifies stream zero settings and index buffer must be set to NULL */
4131     stream->buffer = NULL;
4132     stream->stride = 0;
4133     ib = device->stateBlock->state.index_buffer;
4134     if (ib)
4135     {
4136         wined3d_buffer_decref(ib);
4137         device->stateBlock->state.index_buffer = NULL;
4138     }
4139     /* No need to mark the stream source state dirty here. Either the app calls UP drawing again, or it has to call
4140      * SetStreamSource to specify a vertex buffer
4141      */
4142
4143     return WINED3D_OK;
4144 }
4145
4146 HRESULT CDECL wined3d_device_draw_primitive_strided(struct wined3d_device *device,
4147         UINT vertex_count, const struct wined3d_strided_data *strided_data)
4148 {
4149     /* Mark the state dirty until we have nicer tracking. It's fine to change
4150      * baseVertexIndex because that call is only called by ddraw which does
4151      * not need that value. */
4152     device_invalidate_state(device, STATE_VDECL);
4153     device_invalidate_state(device, STATE_STREAMSRC);
4154     device_invalidate_state(device, STATE_INDEXBUFFER);
4155
4156     device->stateBlock->state.base_vertex_index = 0;
4157     device->up_strided = strided_data;
4158     drawPrimitive(device, vertex_count, 0, FALSE, NULL);
4159     device->up_strided = NULL;
4160
4161     /* Invalidate the states again to make sure the values from the stateblock
4162      * are properly applied in the next regular draw. Note that the application-
4163      * provided strided data has ovwritten pretty much the entire vertex and
4164      * and index stream related states */
4165     device_invalidate_state(device, STATE_VDECL);
4166     device_invalidate_state(device, STATE_STREAMSRC);
4167     device_invalidate_state(device, STATE_INDEXBUFFER);
4168     return WINED3D_OK;
4169 }
4170
4171 HRESULT CDECL wined3d_device_draw_indexed_primitive_strided(struct wined3d_device *device,
4172         UINT index_count, const struct wined3d_strided_data *strided_data,
4173         UINT vertex_count, const void *index_data, enum wined3d_format_id index_data_format_id)
4174 {
4175     enum wined3d_format_id prev_idx_format;
4176
4177     /* Mark the state dirty until we have nicer tracking
4178      * its fine to change baseVertexIndex because that call is only called by ddraw which does not need
4179      * that value.
4180      */
4181     device_invalidate_state(device, STATE_VDECL);
4182     device_invalidate_state(device, STATE_STREAMSRC);
4183     device_invalidate_state(device, STATE_INDEXBUFFER);
4184
4185     prev_idx_format = device->stateBlock->state.index_format;
4186     device->stateBlock->state.index_format = index_data_format_id;
4187     device->stateBlock->state.user_stream = TRUE;
4188     device->stateBlock->state.base_vertex_index = 0;
4189     device->up_strided = strided_data;
4190     drawPrimitive(device, index_count, 0, TRUE, index_data);
4191     device->up_strided = NULL;
4192     device->stateBlock->state.index_format = prev_idx_format;
4193
4194     device_invalidate_state(device, STATE_VDECL);
4195     device_invalidate_state(device, STATE_STREAMSRC);
4196     device_invalidate_state(device, STATE_INDEXBUFFER);
4197     return WINED3D_OK;
4198 }
4199
4200 /* This is a helper function for UpdateTexture, there is no UpdateVolume method in D3D. */
4201 static HRESULT device_update_volume(struct wined3d_device *device,
4202         struct wined3d_volume *src_volume, struct wined3d_volume *dst_volume)
4203 {
4204     struct wined3d_map_desc src;
4205     struct wined3d_map_desc dst;
4206     HRESULT hr;
4207
4208     TRACE("device %p, src_volume %p, dst_volume %p.\n",
4209             device, src_volume, dst_volume);
4210
4211     /* TODO: Implement direct loading into the gl volume instead of using
4212      * memcpy and dirtification to improve loading performance. */
4213     hr = wined3d_volume_map(src_volume, &src, NULL, WINED3DLOCK_READONLY);
4214     if (FAILED(hr)) return hr;
4215     hr = wined3d_volume_map(dst_volume, &dst, NULL, WINED3DLOCK_DISCARD);
4216     if (FAILED(hr))
4217     {
4218         wined3d_volume_unmap(src_volume);
4219         return hr;
4220     }
4221
4222     memcpy(dst.data, src.data, dst_volume->resource.size);
4223
4224     hr = wined3d_volume_unmap(dst_volume);
4225     if (FAILED(hr))
4226         wined3d_volume_unmap(src_volume);
4227     else
4228         hr = wined3d_volume_unmap(src_volume);
4229
4230     return hr;
4231 }
4232
4233 HRESULT CDECL wined3d_device_update_texture(struct wined3d_device *device,
4234         struct wined3d_texture *src_texture, struct wined3d_texture *dst_texture)
4235 {
4236     enum wined3d_resource_type type;
4237     unsigned int level_count, i;
4238     HRESULT hr;
4239
4240     TRACE("device %p, src_texture %p, dst_texture %p.\n", device, src_texture, dst_texture);
4241
4242     /* Verify that the source and destination textures are non-NULL. */
4243     if (!src_texture || !dst_texture)
4244     {
4245         WARN("Source and destination textures must be non-NULL, returning WINED3DERR_INVALIDCALL.\n");
4246         return WINED3DERR_INVALIDCALL;
4247     }
4248
4249     if (src_texture == dst_texture)
4250     {
4251         WARN("Source and destination are the same object, returning WINED3DERR_INVALIDCALL.\n");
4252         return WINED3DERR_INVALIDCALL;
4253     }
4254
4255     /* Verify that the source and destination textures are the same type. */
4256     type = src_texture->resource.type;
4257     if (dst_texture->resource.type != type)
4258     {
4259         WARN("Source and destination have different types, returning WINED3DERR_INVALIDCALL.\n");
4260         return WINED3DERR_INVALIDCALL;
4261     }
4262
4263     /* Check that both textures have the identical numbers of levels. */
4264     level_count = wined3d_texture_get_level_count(src_texture);
4265     if (wined3d_texture_get_level_count(dst_texture) != level_count)
4266     {
4267         WARN("Source and destination have different level counts, returning WINED3DERR_INVALIDCALL.\n");
4268         return WINED3DERR_INVALIDCALL;
4269     }
4270
4271     /* Make sure that the destination texture is loaded. */
4272     dst_texture->texture_ops->texture_preload(dst_texture, SRGB_RGB);
4273
4274     /* Update every surface level of the texture. */
4275     switch (type)
4276     {
4277         case WINED3D_RTYPE_TEXTURE:
4278         {
4279             struct wined3d_surface *src_surface;
4280             struct wined3d_surface *dst_surface;
4281
4282             for (i = 0; i < level_count; ++i)
4283             {
4284                 src_surface = surface_from_resource(wined3d_texture_get_sub_resource(src_texture, i));
4285                 dst_surface = surface_from_resource(wined3d_texture_get_sub_resource(dst_texture, i));
4286                 hr = wined3d_device_update_surface(device, src_surface, NULL, dst_surface, NULL);
4287                 if (FAILED(hr))
4288                 {
4289                     WARN("Failed to update surface, hr %#x.\n", hr);
4290                     return hr;
4291                 }
4292             }
4293             break;
4294         }
4295
4296         case WINED3D_RTYPE_CUBE_TEXTURE:
4297         {
4298             struct wined3d_surface *src_surface;
4299             struct wined3d_surface *dst_surface;
4300
4301             for (i = 0; i < level_count * 6; ++i)
4302             {
4303                 src_surface = surface_from_resource(wined3d_texture_get_sub_resource(src_texture, i));
4304                 dst_surface = surface_from_resource(wined3d_texture_get_sub_resource(dst_texture, i));
4305                 hr = wined3d_device_update_surface(device, src_surface, NULL, dst_surface, NULL);
4306                 if (FAILED(hr))
4307                 {
4308                     WARN("Failed to update surface, hr %#x.\n", hr);
4309                     return hr;
4310                 }
4311             }
4312             break;
4313         }
4314
4315         case WINED3D_RTYPE_VOLUME_TEXTURE:
4316         {
4317             for (i = 0; i < level_count; ++i)
4318             {
4319                 hr = device_update_volume(device,
4320                         volume_from_resource(wined3d_texture_get_sub_resource(src_texture, i)),
4321                         volume_from_resource(wined3d_texture_get_sub_resource(dst_texture, i)));
4322                 if (FAILED(hr))
4323                 {
4324                     WARN("Failed to update volume, hr %#x.\n", hr);
4325                     return hr;
4326                 }
4327             }
4328             break;
4329         }
4330
4331         default:
4332             FIXME("Unsupported texture type %#x.\n", type);
4333             return WINED3DERR_INVALIDCALL;
4334     }
4335
4336     return WINED3D_OK;
4337 }
4338
4339 HRESULT CDECL wined3d_device_get_front_buffer_data(const struct wined3d_device *device,
4340         UINT swapchain_idx, struct wined3d_surface *dst_surface)
4341 {
4342     struct wined3d_swapchain *swapchain;
4343     HRESULT hr;
4344
4345     TRACE("device %p, swapchain_idx %u, dst_surface %p.\n", device, swapchain_idx, dst_surface);
4346
4347     hr = wined3d_device_get_swapchain(device, swapchain_idx, &swapchain);
4348     if (FAILED(hr)) return hr;
4349
4350     hr = wined3d_swapchain_get_front_buffer_data(swapchain, dst_surface);
4351     wined3d_swapchain_decref(swapchain);
4352
4353     return hr;
4354 }
4355
4356 HRESULT CDECL wined3d_device_validate_device(const struct wined3d_device *device, DWORD *num_passes)
4357 {
4358     const struct wined3d_state *state = &device->stateBlock->state;
4359     struct wined3d_texture *texture;
4360     DWORD i;
4361
4362     TRACE("device %p, num_passes %p.\n", device, num_passes);
4363
4364     for (i = 0; i < MAX_COMBINED_SAMPLERS; ++i)
4365     {
4366         if (state->sampler_states[i][WINED3D_SAMP_MIN_FILTER] == WINED3D_TEXF_NONE)
4367         {
4368             WARN("Sampler state %u has minfilter D3DTEXF_NONE, returning D3DERR_UNSUPPORTEDTEXTUREFILTER\n", i);
4369             return WINED3DERR_UNSUPPORTEDTEXTUREFILTER;
4370         }
4371         if (state->sampler_states[i][WINED3D_SAMP_MAG_FILTER] == WINED3D_TEXF_NONE)
4372         {
4373             WARN("Sampler state %u has magfilter D3DTEXF_NONE, returning D3DERR_UNSUPPORTEDTEXTUREFILTER\n", i);
4374             return WINED3DERR_UNSUPPORTEDTEXTUREFILTER;
4375         }
4376
4377         texture = state->textures[i];
4378         if (!texture || texture->resource.format->flags & WINED3DFMT_FLAG_FILTERING) continue;
4379
4380         if (state->sampler_states[i][WINED3D_SAMP_MAG_FILTER] != WINED3D_TEXF_POINT)
4381         {
4382             WARN("Non-filterable texture and mag filter enabled on samper %u, returning E_FAIL\n", i);
4383             return E_FAIL;
4384         }
4385         if (state->sampler_states[i][WINED3D_SAMP_MIN_FILTER] != WINED3D_TEXF_POINT)
4386         {
4387             WARN("Non-filterable texture and min filter enabled on samper %u, returning E_FAIL\n", i);
4388             return E_FAIL;
4389         }
4390         if (state->sampler_states[i][WINED3D_SAMP_MIP_FILTER] != WINED3D_TEXF_NONE
4391                 && state->sampler_states[i][WINED3D_SAMP_MIP_FILTER] != WINED3D_TEXF_POINT)
4392         {
4393             WARN("Non-filterable texture and mip filter enabled on samper %u, returning E_FAIL\n", i);
4394             return E_FAIL;
4395         }
4396     }
4397
4398     if (state->render_states[WINED3D_RS_ZENABLE] || state->render_states[WINED3D_RS_ZWRITEENABLE]
4399             || state->render_states[WINED3D_RS_STENCILENABLE])
4400     {
4401         struct wined3d_surface *ds = device->fb.depth_stencil;
4402         struct wined3d_surface *target = device->fb.render_targets[0];
4403
4404         if(ds && target
4405                 && (ds->resource.width < target->resource.width || ds->resource.height < target->resource.height))
4406         {
4407             WARN("Depth stencil is smaller than the color buffer, returning D3DERR_CONFLICTINGRENDERSTATE\n");
4408             return WINED3DERR_CONFLICTINGRENDERSTATE;
4409         }
4410     }
4411
4412     /* return a sensible default */
4413     *num_passes = 1;
4414
4415     TRACE("returning D3D_OK\n");
4416     return WINED3D_OK;
4417 }
4418
4419 HRESULT CDECL wined3d_device_set_software_vertex_processing(struct wined3d_device *device, BOOL software)
4420 {
4421     static BOOL warned;
4422
4423     TRACE("device %p, software %#x.\n", device, software);
4424
4425     if (!warned)
4426     {
4427         FIXME("device %p, software %#x stub!\n", device, software);
4428         warned = TRUE;
4429     }
4430
4431     device->softwareVertexProcessing = software;
4432
4433     return WINED3D_OK;
4434 }
4435
4436 BOOL CDECL wined3d_device_get_software_vertex_processing(const struct wined3d_device *device)
4437 {
4438     static BOOL warned;
4439
4440     TRACE("device %p.\n", device);
4441
4442     if (!warned)
4443     {
4444         TRACE("device %p stub!\n", device);
4445         warned = TRUE;
4446     }
4447
4448     return device->softwareVertexProcessing;
4449 }
4450
4451 HRESULT CDECL wined3d_device_get_raster_status(const struct wined3d_device *device,
4452         UINT swapchain_idx, struct wined3d_raster_status *raster_status)
4453 {
4454     struct wined3d_swapchain *swapchain;
4455     HRESULT hr;
4456
4457     TRACE("device %p, swapchain_idx %u, raster_status %p.\n",
4458             device, swapchain_idx, raster_status);
4459
4460     hr = wined3d_device_get_swapchain(device, swapchain_idx, &swapchain);
4461     if (FAILED(hr))
4462     {
4463         WARN("Failed to get swapchain %u, hr %#x.\n", swapchain_idx, hr);
4464         return hr;
4465     }
4466
4467     hr = wined3d_swapchain_get_raster_status(swapchain, raster_status);
4468     wined3d_swapchain_decref(swapchain);
4469     if (FAILED(hr))
4470     {
4471         WARN("Failed to get raster status, hr %#x.\n", hr);
4472         return hr;
4473     }
4474
4475     return WINED3D_OK;
4476 }
4477
4478 HRESULT CDECL wined3d_device_set_npatch_mode(struct wined3d_device *device, float segments)
4479 {
4480     static BOOL warned;
4481
4482     TRACE("device %p, segments %.8e.\n", device, segments);
4483
4484     if (segments != 0.0f)
4485     {
4486         if (!warned)
4487         {
4488             FIXME("device %p, segments %.8e stub!\n", device, segments);
4489             warned = TRUE;
4490         }
4491     }
4492
4493     return WINED3D_OK;
4494 }
4495
4496 float CDECL wined3d_device_get_npatch_mode(const struct wined3d_device *device)
4497 {
4498     static BOOL warned;
4499
4500     TRACE("device %p.\n", device);
4501
4502     if (!warned)
4503     {
4504         FIXME("device %p stub!\n", device);
4505         warned = TRUE;
4506     }
4507
4508     return 0.0f;
4509 }
4510
4511 HRESULT CDECL wined3d_device_update_surface(struct wined3d_device *device,
4512         struct wined3d_surface *src_surface, const RECT *src_rect,
4513         struct wined3d_surface *dst_surface, const POINT *dst_point)
4514 {
4515     TRACE("device %p, src_surface %p, src_rect %s, dst_surface %p, dst_point %s.\n",
4516             device, src_surface, wine_dbgstr_rect(src_rect),
4517             dst_surface, wine_dbgstr_point(dst_point));
4518
4519     if (src_surface->resource.pool != WINED3D_POOL_SYSTEM_MEM || dst_surface->resource.pool != WINED3D_POOL_DEFAULT)
4520     {
4521         WARN("source %p must be SYSTEMMEM and dest %p must be DEFAULT, returning WINED3DERR_INVALIDCALL\n",
4522                 src_surface, dst_surface);
4523         return WINED3DERR_INVALIDCALL;
4524     }
4525
4526     return surface_upload_from_surface(dst_surface, dst_point, src_surface, src_rect);
4527 }
4528
4529 HRESULT CDECL wined3d_device_draw_rect_patch(struct wined3d_device *device, UINT handle,
4530         const float *num_segs, const struct wined3d_rect_patch_info *rect_patch_info)
4531 {
4532     struct wined3d_rect_patch *patch;
4533     GLenum old_primitive_type;
4534     unsigned int i;
4535     struct list *e;
4536     BOOL found;
4537
4538     TRACE("device %p, handle %#x, num_segs %p, rect_patch_info %p.\n",
4539             device, handle, num_segs, rect_patch_info);
4540
4541     if (!(handle || rect_patch_info))
4542     {
4543         /* TODO: Write a test for the return value, thus the FIXME */
4544         FIXME("Both handle and rect_patch_info are NULL.\n");
4545         return WINED3DERR_INVALIDCALL;
4546     }
4547
4548     if (handle)
4549     {
4550         i = PATCHMAP_HASHFUNC(handle);
4551         found = FALSE;
4552         LIST_FOR_EACH(e, &device->patches[i])
4553         {
4554             patch = LIST_ENTRY(e, struct wined3d_rect_patch, entry);
4555             if (patch->Handle == handle)
4556             {
4557                 found = TRUE;
4558                 break;
4559             }
4560         }
4561
4562         if (!found)
4563         {
4564             TRACE("Patch does not exist. Creating a new one\n");
4565             patch = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*patch));
4566             patch->Handle = handle;
4567             list_add_head(&device->patches[i], &patch->entry);
4568         } else {
4569             TRACE("Found existing patch %p\n", patch);
4570         }
4571     }
4572     else
4573     {
4574         /* Since opengl does not load tesselated vertex attributes into numbered vertex
4575          * attributes we have to tesselate, read back, and draw. This needs a patch
4576          * management structure instance. Create one.
4577          *
4578          * A possible improvement is to check if a vertex shader is used, and if not directly
4579          * draw the patch.
4580          */
4581         FIXME("Drawing an uncached patch. This is slow\n");
4582         patch = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*patch));
4583     }
4584
4585     if (num_segs[0] != patch->numSegs[0] || num_segs[1] != patch->numSegs[1]
4586             || num_segs[2] != patch->numSegs[2] || num_segs[3] != patch->numSegs[3]
4587             || (rect_patch_info && memcmp(rect_patch_info, &patch->rect_patch_info, sizeof(*rect_patch_info))))
4588     {
4589         HRESULT hr;
4590         TRACE("Tesselation density or patch info changed, retesselating\n");
4591
4592         if (rect_patch_info)
4593             patch->rect_patch_info = *rect_patch_info;
4594
4595         patch->numSegs[0] = num_segs[0];
4596         patch->numSegs[1] = num_segs[1];
4597         patch->numSegs[2] = num_segs[2];
4598         patch->numSegs[3] = num_segs[3];
4599
4600         hr = tesselate_rectpatch(device, patch);
4601         if (FAILED(hr))
4602         {
4603             WARN("Patch tesselation failed.\n");
4604
4605             /* Do not release the handle to store the params of the patch */
4606             if (!handle)
4607                 HeapFree(GetProcessHeap(), 0, patch);
4608
4609             return hr;
4610         }
4611     }
4612
4613     old_primitive_type = device->stateBlock->state.gl_primitive_type;
4614     device->stateBlock->state.gl_primitive_type = GL_TRIANGLES;
4615     wined3d_device_draw_primitive_strided(device, patch->numSegs[0] * patch->numSegs[1] * 2 * 3, &patch->strided);
4616     device->stateBlock->state.gl_primitive_type = old_primitive_type;
4617
4618     /* Destroy uncached patches */
4619     if (!handle)
4620     {
4621         HeapFree(GetProcessHeap(), 0, patch->mem);
4622         HeapFree(GetProcessHeap(), 0, patch);
4623     }
4624     return WINED3D_OK;
4625 }
4626
4627 HRESULT CDECL wined3d_device_draw_tri_patch(struct wined3d_device *device, UINT handle,
4628         const float *segment_count, const struct wined3d_tri_patch_info *patch_info)
4629 {
4630     FIXME("device %p, handle %#x, segment_count %p, patch_info %p stub!\n",
4631             device, handle, segment_count, patch_info);
4632
4633     return WINED3D_OK;
4634 }
4635
4636 HRESULT CDECL wined3d_device_delete_patch(struct wined3d_device *device, UINT handle)
4637 {
4638     struct wined3d_rect_patch *patch;
4639     struct list *e;
4640     int i;
4641
4642     TRACE("device %p, handle %#x.\n", device, handle);
4643
4644     i = PATCHMAP_HASHFUNC(handle);
4645     LIST_FOR_EACH(e, &device->patches[i])
4646     {
4647         patch = LIST_ENTRY(e, struct wined3d_rect_patch, entry);
4648         if (patch->Handle == handle)
4649         {
4650             TRACE("Deleting patch %p\n", patch);
4651             list_remove(&patch->entry);
4652             HeapFree(GetProcessHeap(), 0, patch->mem);
4653             HeapFree(GetProcessHeap(), 0, patch);
4654             return WINED3D_OK;
4655         }
4656     }
4657
4658     /* TODO: Write a test for the return value */
4659     FIXME("Attempt to destroy nonexistent patch\n");
4660     return WINED3DERR_INVALIDCALL;
4661 }
4662
4663 /* Do not call while under the GL lock. */
4664 HRESULT CDECL wined3d_device_color_fill(struct wined3d_device *device,
4665         struct wined3d_surface *surface, const RECT *rect, const struct wined3d_color *color)
4666 {
4667     RECT r;
4668
4669     TRACE("device %p, surface %p, rect %s, color {%.8e, %.8e, %.8e, %.8e}.\n",
4670             device, surface, wine_dbgstr_rect(rect),
4671             color->r, color->g, color->b, color->a);
4672
4673     if (surface->resource.pool != WINED3D_POOL_DEFAULT && surface->resource.pool != WINED3D_POOL_SYSTEM_MEM)
4674     {
4675         WARN("Color-fill not allowed on %s surfaces.\n", debug_d3dpool(surface->resource.pool));
4676         return WINED3DERR_INVALIDCALL;
4677     }
4678
4679     if (!rect)
4680     {
4681         SetRect(&r, 0, 0, surface->resource.width, surface->resource.height);
4682         rect = &r;
4683     }
4684
4685     return surface_color_fill(surface, rect, color);
4686 }
4687
4688 /* Do not call while under the GL lock. */
4689 void CDECL wined3d_device_clear_rendertarget_view(struct wined3d_device *device,
4690         struct wined3d_rendertarget_view *rendertarget_view, const struct wined3d_color *color)
4691 {
4692     struct wined3d_resource *resource;
4693     HRESULT hr;
4694     RECT rect;
4695
4696     resource = rendertarget_view->resource;
4697     if (resource->type != WINED3D_RTYPE_SURFACE)
4698     {
4699         FIXME("Only supported on surface resources\n");
4700         return;
4701     }
4702
4703     SetRect(&rect, 0, 0, resource->width, resource->height);
4704     hr = surface_color_fill(surface_from_resource(resource), &rect, color);
4705     if (FAILED(hr)) ERR("Color fill failed, hr %#x.\n", hr);
4706 }
4707
4708 HRESULT CDECL wined3d_device_get_render_target(const struct wined3d_device *device,
4709         UINT render_target_idx, struct wined3d_surface **render_target)
4710 {
4711     TRACE("device %p, render_target_idx %u, render_target %p.\n",
4712             device, render_target_idx, render_target);
4713
4714     if (render_target_idx >= device->adapter->gl_info.limits.buffers)
4715     {
4716         WARN("Only %u render targets are supported.\n", device->adapter->gl_info.limits.buffers);
4717         return WINED3DERR_INVALIDCALL;
4718     }
4719
4720     *render_target = device->fb.render_targets[render_target_idx];
4721     TRACE("Returning render target %p.\n", *render_target);
4722
4723     if (!*render_target)
4724         return WINED3DERR_NOTFOUND;
4725
4726     wined3d_surface_incref(*render_target);
4727
4728     return WINED3D_OK;
4729 }
4730
4731 HRESULT CDECL wined3d_device_get_depth_stencil(const struct wined3d_device *device,
4732         struct wined3d_surface **depth_stencil)
4733 {
4734     TRACE("device %p, depth_stencil %p.\n", device, depth_stencil);
4735
4736     *depth_stencil = device->fb.depth_stencil;
4737     TRACE("Returning depth/stencil surface %p.\n", *depth_stencil);
4738
4739     if (!*depth_stencil)
4740         return WINED3DERR_NOTFOUND;
4741
4742     wined3d_surface_incref(*depth_stencil);
4743
4744     return WINED3D_OK;
4745 }
4746
4747 HRESULT CDECL wined3d_device_set_render_target(struct wined3d_device *device,
4748         UINT render_target_idx, struct wined3d_surface *render_target, BOOL set_viewport)
4749 {
4750     struct wined3d_surface *prev;
4751
4752     TRACE("device %p, render_target_idx %u, render_target %p, set_viewport %#x.\n",
4753             device, render_target_idx, render_target, set_viewport);
4754
4755     if (render_target_idx >= device->adapter->gl_info.limits.buffers)
4756     {
4757         WARN("Only %u render targets are supported.\n", device->adapter->gl_info.limits.buffers);
4758         return WINED3DERR_INVALIDCALL;
4759     }
4760
4761     prev = device->fb.render_targets[render_target_idx];
4762     if (render_target == prev)
4763     {
4764         TRACE("Trying to do a NOP SetRenderTarget operation.\n");
4765         return WINED3D_OK;
4766     }
4767
4768     /* Render target 0 can't be set to NULL. */
4769     if (!render_target && !render_target_idx)
4770     {
4771         WARN("Trying to set render target 0 to NULL.\n");
4772         return WINED3DERR_INVALIDCALL;
4773     }
4774
4775     if (render_target && !(render_target->resource.usage & WINED3DUSAGE_RENDERTARGET))
4776     {
4777         FIXME("Surface %p doesn't have render target usage.\n", render_target);
4778         return WINED3DERR_INVALIDCALL;
4779     }
4780
4781     if (render_target)
4782         wined3d_surface_incref(render_target);
4783     device->fb.render_targets[render_target_idx] = render_target;
4784     /* Release after the assignment, to prevent device_resource_released()
4785      * from seeing the surface as still in use. */
4786     if (prev)
4787         wined3d_surface_decref(prev);
4788
4789     /* Render target 0 is special. */
4790     if (!render_target_idx && set_viewport)
4791     {
4792         /* Set the viewport and scissor rectangles, if requested. Tests show
4793          * that stateblock recording is ignored, the change goes directly
4794          * into the primary stateblock. */
4795         device->stateBlock->state.viewport.height = device->fb.render_targets[0]->resource.height;
4796         device->stateBlock->state.viewport.width  = device->fb.render_targets[0]->resource.width;
4797         device->stateBlock->state.viewport.x      = 0;
4798         device->stateBlock->state.viewport.y      = 0;
4799         device->stateBlock->state.viewport.max_z  = 1.0f;
4800         device->stateBlock->state.viewport.min_z  = 0.0f;
4801         device_invalidate_state(device, STATE_VIEWPORT);
4802
4803         device->stateBlock->state.scissor_rect.top = 0;
4804         device->stateBlock->state.scissor_rect.left = 0;
4805         device->stateBlock->state.scissor_rect.right = device->stateBlock->state.viewport.width;
4806         device->stateBlock->state.scissor_rect.bottom = device->stateBlock->state.viewport.height;
4807         device_invalidate_state(device, STATE_SCISSORRECT);
4808     }
4809
4810     device_invalidate_state(device, STATE_FRAMEBUFFER);
4811
4812     return WINED3D_OK;
4813 }
4814
4815 HRESULT CDECL wined3d_device_set_depth_stencil(struct wined3d_device *device, struct wined3d_surface *depth_stencil)
4816 {
4817     struct wined3d_surface *prev = device->fb.depth_stencil;
4818
4819     TRACE("device %p, depth_stencil %p, old depth_stencil %p.\n",
4820             device, depth_stencil, prev);
4821
4822     if (prev == depth_stencil)
4823     {
4824         TRACE("Trying to do a NOP SetRenderTarget operation.\n");
4825         return WINED3D_OK;
4826     }
4827
4828     if (prev)
4829     {
4830         if (device->swapchains[0]->desc.flags & WINED3DPRESENTFLAG_DISCARD_DEPTHSTENCIL
4831                 || prev->flags & SFLAG_DISCARD)
4832         {
4833             surface_modify_ds_location(prev, SFLAG_DISCARDED,
4834                     prev->resource.width, prev->resource.height);
4835             if (prev == device->onscreen_depth_stencil)
4836             {
4837                 wined3d_surface_decref(device->onscreen_depth_stencil);
4838                 device->onscreen_depth_stencil = NULL;
4839             }
4840         }
4841     }
4842
4843     device->fb.depth_stencil = depth_stencil;
4844     if (depth_stencil)
4845         wined3d_surface_incref(depth_stencil);
4846
4847     if (!prev != !depth_stencil)
4848     {
4849         /* Swapping NULL / non NULL depth stencil affects the depth and tests */
4850         device_invalidate_state(device, STATE_RENDER(WINED3D_RS_ZENABLE));
4851         device_invalidate_state(device, STATE_RENDER(WINED3D_RS_STENCILENABLE));
4852         device_invalidate_state(device, STATE_RENDER(WINED3D_RS_STENCILWRITEMASK));
4853         device_invalidate_state(device, STATE_RENDER(WINED3D_RS_DEPTHBIAS));
4854     }
4855     else if (prev && prev->resource.format->depth_size != depth_stencil->resource.format->depth_size)
4856     {
4857         device_invalidate_state(device, STATE_RENDER(WINED3D_RS_DEPTHBIAS));
4858     }
4859     if (prev)
4860         wined3d_surface_decref(prev);
4861
4862     device_invalidate_state(device, STATE_FRAMEBUFFER);
4863
4864     return WINED3D_OK;
4865 }
4866
4867 HRESULT CDECL wined3d_device_set_cursor_properties(struct wined3d_device *device,
4868         UINT x_hotspot, UINT y_hotspot, struct wined3d_surface *cursor_image)
4869 {
4870     TRACE("device %p, x_hotspot %u, y_hotspot %u, cursor_image %p.\n",
4871             device, x_hotspot, y_hotspot, cursor_image);
4872
4873     /* some basic validation checks */
4874     if (device->cursorTexture)
4875     {
4876         struct wined3d_context *context = context_acquire(device, NULL);
4877         ENTER_GL();
4878         glDeleteTextures(1, &device->cursorTexture);
4879         LEAVE_GL();
4880         context_release(context);
4881         device->cursorTexture = 0;
4882     }
4883
4884     if (cursor_image)
4885     {
4886         struct wined3d_map_desc map_desc;
4887
4888         /* MSDN: Cursor must be A8R8G8B8 */
4889         if (cursor_image->resource.format->id != WINED3DFMT_B8G8R8A8_UNORM)
4890         {
4891             WARN("surface %p has an invalid format.\n", cursor_image);
4892             return WINED3DERR_INVALIDCALL;
4893         }
4894
4895         /* MSDN: Cursor must be smaller than the display mode */
4896         if (cursor_image->resource.width > device->adapter->screen_size.cx
4897                 || cursor_image->resource.height > device->adapter->screen_size.cy)
4898         {
4899             WARN("Surface %p dimensions are %ux%u, but screen dimensions are %ux%u.\n",
4900                     cursor_image, cursor_image->resource.width, cursor_image->resource.height,
4901                     device->adapter->screen_size.cx, device->adapter->screen_size.cy);
4902             return WINED3DERR_INVALIDCALL;
4903         }
4904
4905         /* TODO: MSDN: Cursor sizes must be a power of 2 */
4906
4907         /* Do not store the surface's pointer because the application may
4908          * release it after setting the cursor image. Windows doesn't
4909          * addref the set surface, so we can't do this either without
4910          * creating circular refcount dependencies. Copy out the gl texture
4911          * instead. */
4912         device->cursorWidth = cursor_image->resource.width;
4913         device->cursorHeight = cursor_image->resource.height;
4914         if (SUCCEEDED(wined3d_surface_map(cursor_image, &map_desc, NULL, WINED3DLOCK_READONLY)))
4915         {
4916             const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4917             const struct wined3d_format *format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
4918             struct wined3d_context *context;
4919             char *mem, *bits = map_desc.data;
4920             GLint intfmt = format->glInternal;
4921             GLint gl_format = format->glFormat;
4922             GLint type = format->glType;
4923             INT height = device->cursorHeight;
4924             INT width = device->cursorWidth;
4925             INT bpp = format->byte_count;
4926             INT i;
4927
4928             /* Reformat the texture memory (pitch and width can be
4929              * different) */
4930             mem = HeapAlloc(GetProcessHeap(), 0, width * height * bpp);
4931             for (i = 0; i < height; ++i)
4932                 memcpy(&mem[width * bpp * i], &bits[map_desc.row_pitch * i], width * bpp);
4933             wined3d_surface_unmap(cursor_image);
4934
4935             context = context_acquire(device, NULL);
4936
4937             ENTER_GL();
4938
4939             if (gl_info->supported[APPLE_CLIENT_STORAGE])
4940             {
4941                 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE);
4942                 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE)");
4943             }
4944
4945             invalidate_active_texture(device, context);
4946             /* Create a new cursor texture */
4947             glGenTextures(1, &device->cursorTexture);
4948             checkGLcall("glGenTextures");
4949             context_bind_texture(context, GL_TEXTURE_2D, device->cursorTexture);
4950             /* Copy the bitmap memory into the cursor texture */
4951             glTexImage2D(GL_TEXTURE_2D, 0, intfmt, width, height, 0, gl_format, type, mem);
4952             checkGLcall("glTexImage2D");
4953             HeapFree(GetProcessHeap(), 0, mem);
4954
4955             if (gl_info->supported[APPLE_CLIENT_STORAGE])
4956             {
4957                 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
4958                 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
4959             }
4960
4961             LEAVE_GL();
4962
4963             context_release(context);
4964         }
4965         else
4966         {
4967             FIXME("A cursor texture was not returned.\n");
4968             device->cursorTexture = 0;
4969         }
4970
4971         if (cursor_image->resource.width == 32 && cursor_image->resource.height == 32)
4972         {
4973             UINT mask_size = cursor_image->resource.width * cursor_image->resource.height / 8;
4974             ICONINFO cursorInfo;
4975             DWORD *maskBits;
4976             HCURSOR cursor;
4977
4978             /* 32-bit user32 cursors ignore the alpha channel if it's all
4979              * zeroes, and use the mask instead. Fill the mask with all ones
4980              * to ensure we still get a fully transparent cursor. */
4981             maskBits = HeapAlloc(GetProcessHeap(), 0, mask_size);
4982             memset(maskBits, 0xff, mask_size);
4983             wined3d_surface_map(cursor_image, &map_desc, NULL,
4984                     WINED3DLOCK_NO_DIRTY_UPDATE | WINED3DLOCK_READONLY);
4985             TRACE("width: %u height: %u.\n", cursor_image->resource.width, cursor_image->resource.height);
4986
4987             cursorInfo.fIcon = FALSE;
4988             cursorInfo.xHotspot = x_hotspot;
4989             cursorInfo.yHotspot = y_hotspot;
4990             cursorInfo.hbmMask = CreateBitmap(cursor_image->resource.width, cursor_image->resource.height,
4991                     1, 1, maskBits);
4992             cursorInfo.hbmColor = CreateBitmap(cursor_image->resource.width, cursor_image->resource.height,
4993                     1, 32, map_desc.data);
4994             wined3d_surface_unmap(cursor_image);
4995             /* Create our cursor and clean up. */
4996             cursor = CreateIconIndirect(&cursorInfo);
4997             if (cursorInfo.hbmMask) DeleteObject(cursorInfo.hbmMask);
4998             if (cursorInfo.hbmColor) DeleteObject(cursorInfo.hbmColor);
4999             if (device->hardwareCursor) DestroyCursor(device->hardwareCursor);
5000             device->hardwareCursor = cursor;
5001             if (device->bCursorVisible) SetCursor( cursor );
5002             HeapFree(GetProcessHeap(), 0, maskBits);
5003         }
5004     }
5005
5006     device->xHotSpot = x_hotspot;
5007     device->yHotSpot = y_hotspot;
5008     return WINED3D_OK;
5009 }
5010
5011 void CDECL wined3d_device_set_cursor_position(struct wined3d_device *device,
5012         int x_screen_space, int y_screen_space, DWORD flags)
5013 {
5014     TRACE("device %p, x %d, y %d, flags %#x.\n",
5015             device, x_screen_space, y_screen_space, flags);
5016
5017     device->xScreenSpace = x_screen_space;
5018     device->yScreenSpace = y_screen_space;
5019
5020     if (device->hardwareCursor)
5021     {
5022         POINT pt;
5023
5024         GetCursorPos( &pt );
5025         if (x_screen_space == pt.x && y_screen_space == pt.y)
5026             return;
5027         SetCursorPos( x_screen_space, y_screen_space );
5028
5029         /* Switch to the software cursor if position diverges from the hardware one. */
5030         GetCursorPos( &pt );
5031         if (x_screen_space != pt.x || y_screen_space != pt.y)
5032         {
5033             if (device->bCursorVisible) SetCursor( NULL );
5034             DestroyCursor( device->hardwareCursor );
5035             device->hardwareCursor = 0;
5036         }
5037     }
5038 }
5039
5040 BOOL CDECL wined3d_device_show_cursor(struct wined3d_device *device, BOOL show)
5041 {
5042     BOOL oldVisible = device->bCursorVisible;
5043
5044     TRACE("device %p, show %#x.\n", device, show);
5045
5046     /*
5047      * When ShowCursor is first called it should make the cursor appear at the OS's last
5048      * known cursor position.
5049      */
5050     if (show && !oldVisible)
5051     {
5052         POINT pt;
5053         GetCursorPos(&pt);
5054         device->xScreenSpace = pt.x;
5055         device->yScreenSpace = pt.y;
5056     }
5057
5058     if (device->hardwareCursor)
5059     {
5060         device->bCursorVisible = show;
5061         if (show)
5062             SetCursor(device->hardwareCursor);
5063         else
5064             SetCursor(NULL);
5065     }
5066     else
5067     {
5068         if (device->cursorTexture)
5069             device->bCursorVisible = show;
5070     }
5071
5072     return oldVisible;
5073 }
5074
5075 void CDECL wined3d_device_evict_managed_resources(struct wined3d_device *device)
5076 {
5077     struct wined3d_resource *resource, *cursor;
5078
5079     TRACE("device %p.\n", device);
5080
5081     LIST_FOR_EACH_ENTRY_SAFE(resource, cursor, &device->resources, struct wined3d_resource, resource_list_entry)
5082     {
5083         TRACE("Checking resource %p for eviction.\n", resource);
5084
5085         if (resource->pool == WINED3D_POOL_MANAGED && !resource->map_count)
5086         {
5087             TRACE("Evicting %p.\n", resource);
5088             resource->resource_ops->resource_unload(resource);
5089         }
5090     }
5091
5092     /* Invalidate stream sources, the buffer(s) may have been evicted. */
5093     device_invalidate_state(device, STATE_STREAMSRC);
5094 }
5095
5096 static BOOL is_display_mode_supported(const struct wined3d_device *device,
5097         const struct wined3d_swapchain_desc *swapchain_desc)
5098 {
5099     struct wined3d_display_mode m;
5100     UINT i, count;
5101     HRESULT hr;
5102
5103     /* All Windowed modes are supported, as is leaving the current mode */
5104     if (swapchain_desc->windowed)
5105         return TRUE;
5106     if (!swapchain_desc->backbuffer_width)
5107         return TRUE;
5108     if (!swapchain_desc->backbuffer_height)
5109         return TRUE;
5110
5111     count = wined3d_get_adapter_mode_count(device->wined3d, device->adapter->ordinal, WINED3DFMT_UNKNOWN);
5112     for (i = 0; i < count; ++i)
5113     {
5114         memset(&m, 0, sizeof(m));
5115         hr = wined3d_enum_adapter_modes(device->wined3d, device->adapter->ordinal, WINED3DFMT_UNKNOWN, i, &m);
5116         if (FAILED(hr))
5117             ERR("Failed to enumerate adapter mode.\n");
5118         if (m.width == swapchain_desc->backbuffer_width && m.height == swapchain_desc->backbuffer_height)
5119             /* Mode found, it is supported. */
5120             return TRUE;
5121     }
5122     /* Mode not found -> not supported */
5123     return FALSE;
5124 }
5125
5126 /* Do not call while under the GL lock. */
5127 static void delete_opengl_contexts(struct wined3d_device *device, struct wined3d_swapchain *swapchain)
5128 {
5129     struct wined3d_resource *resource, *cursor;
5130     const struct wined3d_gl_info *gl_info;
5131     struct wined3d_context *context;
5132     struct wined3d_shader *shader;
5133
5134     context = context_acquire(device, NULL);
5135     gl_info = context->gl_info;
5136
5137     LIST_FOR_EACH_ENTRY_SAFE(resource, cursor, &device->resources, struct wined3d_resource, resource_list_entry)
5138     {
5139         TRACE("Unloading resource %p.\n", resource);
5140
5141         resource->resource_ops->resource_unload(resource);
5142     }
5143
5144     LIST_FOR_EACH_ENTRY(shader, &device->shaders, struct wined3d_shader, shader_list_entry)
5145     {
5146         device->shader_backend->shader_destroy(shader);
5147     }
5148
5149     ENTER_GL();
5150     if (device->depth_blt_texture)
5151     {
5152         glDeleteTextures(1, &device->depth_blt_texture);
5153         device->depth_blt_texture = 0;
5154     }
5155     if (device->cursorTexture)
5156     {
5157         glDeleteTextures(1, &device->cursorTexture);
5158         device->cursorTexture = 0;
5159     }
5160     LEAVE_GL();
5161
5162     device->blitter->free_private(device);
5163     device->frag_pipe->free_private(device);
5164     device->shader_backend->shader_free_private(device);
5165     destroy_dummy_textures(device, gl_info);
5166
5167     context_release(context);
5168
5169     while (device->context_count)
5170     {
5171         swapchain_destroy_contexts(device->contexts[0]->swapchain);
5172     }
5173
5174     HeapFree(GetProcessHeap(), 0, swapchain->context);
5175     swapchain->context = NULL;
5176 }
5177
5178 /* Do not call while under the GL lock. */
5179 static HRESULT create_primary_opengl_context(struct wined3d_device *device, struct wined3d_swapchain *swapchain)
5180 {
5181     struct wined3d_context *context;
5182     struct wined3d_surface *target;
5183     HRESULT hr;
5184
5185     /* Recreate the primary swapchain's context */
5186     swapchain->context = HeapAlloc(GetProcessHeap(), 0, sizeof(*swapchain->context));
5187     if (!swapchain->context)
5188     {
5189         ERR("Failed to allocate memory for swapchain context array.\n");
5190         return E_OUTOFMEMORY;
5191     }
5192
5193     target = swapchain->back_buffers ? swapchain->back_buffers[0] : swapchain->front_buffer;
5194     if (!(context = context_create(swapchain, target, swapchain->ds_format)))
5195     {
5196         WARN("Failed to create context.\n");
5197         HeapFree(GetProcessHeap(), 0, swapchain->context);
5198         return E_FAIL;
5199     }
5200
5201     swapchain->context[0] = context;
5202     swapchain->num_contexts = 1;
5203     create_dummy_textures(device, context);
5204     context_release(context);
5205
5206     hr = device->shader_backend->shader_alloc_private(device);
5207     if (FAILED(hr))
5208     {
5209         ERR("Failed to allocate shader private data, hr %#x.\n", hr);
5210         goto err;
5211     }
5212
5213     hr = device->frag_pipe->alloc_private(device);
5214     if (FAILED(hr))
5215     {
5216         ERR("Failed to allocate fragment pipe private data, hr %#x.\n", hr);
5217         device->shader_backend->shader_free_private(device);
5218         goto err;
5219     }
5220
5221     hr = device->blitter->alloc_private(device);
5222     if (FAILED(hr))
5223     {
5224         ERR("Failed to allocate blitter private data, hr %#x.\n", hr);
5225         device->frag_pipe->free_private(device);
5226         device->shader_backend->shader_free_private(device);
5227         goto err;
5228     }
5229
5230     return WINED3D_OK;
5231
5232 err:
5233     context_acquire(device, NULL);
5234     destroy_dummy_textures(device, context->gl_info);
5235     context_release(context);
5236     context_destroy(device, context);
5237     HeapFree(GetProcessHeap(), 0, swapchain->context);
5238     swapchain->num_contexts = 0;
5239     return hr;
5240 }
5241
5242 /* Do not call while under the GL lock. */
5243 HRESULT CDECL wined3d_device_reset(struct wined3d_device *device,
5244         const struct wined3d_swapchain_desc *swapchain_desc,
5245         wined3d_device_reset_cb callback)
5246 {
5247     struct wined3d_resource *resource, *cursor;
5248     struct wined3d_swapchain *swapchain;
5249     struct wined3d_display_mode mode;
5250     BOOL DisplayModeChanged = FALSE;
5251     BOOL update_desc = FALSE;
5252     unsigned int i;
5253     HRESULT hr;
5254
5255     TRACE("device %p, swapchain_desc %p.\n", device, swapchain_desc);
5256
5257     if (FAILED(hr = wined3d_device_get_swapchain(device, 0, &swapchain)))
5258     {
5259         ERR("Failed to get the first implicit swapchain.\n");
5260         return hr;
5261     }
5262
5263     stateblock_unbind_resources(device->stateBlock);
5264     if (swapchain->back_buffers && swapchain->back_buffers[0])
5265         wined3d_device_set_render_target(device, 0, swapchain->back_buffers[0], FALSE);
5266     else
5267         wined3d_device_set_render_target(device, 0, swapchain->front_buffer, FALSE);
5268     for (i = 1; i < device->adapter->gl_info.limits.buffers; ++i)
5269     {
5270         wined3d_device_set_render_target(device, i, NULL, FALSE);
5271     }
5272     wined3d_device_set_depth_stencil(device, NULL);
5273
5274     if (device->onscreen_depth_stencil)
5275     {
5276         wined3d_surface_decref(device->onscreen_depth_stencil);
5277         device->onscreen_depth_stencil = NULL;
5278     }
5279
5280     LIST_FOR_EACH_ENTRY_SAFE(resource, cursor, &device->resources, struct wined3d_resource, resource_list_entry)
5281     {
5282         TRACE("Enumerating resource %p.\n", resource);
5283         if (FAILED(hr = callback(resource)))
5284         {
5285             wined3d_swapchain_decref(swapchain);
5286             return hr;
5287         }
5288     }
5289
5290     if (!is_display_mode_supported(device, swapchain_desc))
5291     {
5292         WARN("Rejecting reset() call because the requested display mode is not supported.\n");
5293         WARN("Requested mode: %ux%u.\n",
5294                 swapchain_desc->backbuffer_width,
5295                 swapchain_desc->backbuffer_height);
5296         wined3d_swapchain_decref(swapchain);
5297         return WINED3DERR_INVALIDCALL;
5298     }
5299
5300     /* Is it necessary to recreate the gl context? Actually every setting can be changed
5301      * on an existing gl context, so there's no real need for recreation.
5302      *
5303      * TODO: Figure out how Reset influences resources in D3DPOOL_DEFAULT, D3DPOOL_SYSTEMMEMORY and D3DPOOL_MANAGED
5304      *
5305      * TODO: Figure out what happens to explicit swapchains, or if we have more than one implicit swapchain
5306      */
5307     TRACE("New params:\n");
5308     TRACE("backbuffer_width %u\n", swapchain_desc->backbuffer_width);
5309     TRACE("backbuffer_height %u\n", swapchain_desc->backbuffer_height);
5310     TRACE("backbuffer_format %s\n", debug_d3dformat(swapchain_desc->backbuffer_format));
5311     TRACE("backbuffer_count %u\n", swapchain_desc->backbuffer_count);
5312     TRACE("multisample_type %#x\n", swapchain_desc->multisample_type);
5313     TRACE("multisample_quality %u\n", swapchain_desc->multisample_quality);
5314     TRACE("swap_effect %#x\n", swapchain_desc->swap_effect);
5315     TRACE("device_window %p\n", swapchain_desc->device_window);
5316     TRACE("windowed %#x\n", swapchain_desc->windowed);
5317     TRACE("enable_auto_depth_stencil %#x\n", swapchain_desc->enable_auto_depth_stencil);
5318     if (swapchain_desc->enable_auto_depth_stencil)
5319         TRACE("auto_depth_stencil_format %s\n", debug_d3dformat(swapchain_desc->auto_depth_stencil_format));
5320     TRACE("flags %#x\n", swapchain_desc->flags);
5321     TRACE("refresh_rate %u\n", swapchain_desc->refresh_rate);
5322     TRACE("swap_interval %u\n", swapchain_desc->swap_interval);
5323     TRACE("auto_restore_display_mode %#x\n", swapchain_desc->auto_restore_display_mode);
5324
5325     /* No special treatment of these parameters. Just store them */
5326     swapchain->desc.swap_effect = swapchain_desc->swap_effect;
5327     swapchain->desc.flags = swapchain_desc->flags;
5328     swapchain->desc.swap_interval = swapchain_desc->swap_interval;
5329     swapchain->desc.refresh_rate = swapchain_desc->refresh_rate;
5330
5331     /* What to do about these? */
5332     if (swapchain_desc->backbuffer_count
5333             && swapchain_desc->backbuffer_count != swapchain->desc.backbuffer_count)
5334         FIXME("Cannot change the back buffer count yet.\n");
5335
5336     if (swapchain_desc->device_window
5337             && swapchain_desc->device_window != swapchain->desc.device_window)
5338     {
5339         TRACE("Changing the device window from %p to %p.\n",
5340                 swapchain->desc.device_window, swapchain_desc->device_window);
5341         swapchain->desc.device_window = swapchain_desc->device_window;
5342         swapchain->device_window = swapchain_desc->device_window;
5343         wined3d_swapchain_set_window(swapchain, NULL);
5344     }
5345
5346     if (swapchain_desc->enable_auto_depth_stencil && !device->auto_depth_stencil)
5347     {
5348         HRESULT hrc;
5349
5350         TRACE("Creating the depth stencil buffer\n");
5351
5352         hrc = device->device_parent->ops->create_depth_stencil(device->device_parent,
5353                 swapchain_desc->backbuffer_width,
5354                 swapchain_desc->backbuffer_height,
5355                 swapchain_desc->auto_depth_stencil_format,
5356                 swapchain_desc->multisample_type,
5357                 swapchain_desc->multisample_quality,
5358                 FALSE,
5359                 &device->auto_depth_stencil);
5360         if (FAILED(hrc))
5361         {
5362             ERR("Failed to create the depth stencil buffer.\n");
5363             wined3d_swapchain_decref(swapchain);
5364             return WINED3DERR_INVALIDCALL;
5365         }
5366     }
5367
5368     if (device->onscreen_depth_stencil)
5369     {
5370         wined3d_surface_decref(device->onscreen_depth_stencil);
5371         device->onscreen_depth_stencil = NULL;
5372     }
5373
5374     /* Reset the depth stencil */
5375     if (swapchain_desc->enable_auto_depth_stencil)
5376         wined3d_device_set_depth_stencil(device, device->auto_depth_stencil);
5377
5378     TRACE("Resetting stateblock\n");
5379     wined3d_stateblock_decref(device->updateStateBlock);
5380     wined3d_stateblock_decref(device->stateBlock);
5381
5382     if (swapchain_desc->windowed)
5383     {
5384         mode.width = swapchain->orig_width;
5385         mode.height = swapchain->orig_height;
5386         mode.refresh_rate = 0;
5387         mode.format_id = swapchain->desc.backbuffer_format;
5388     }
5389     else
5390     {
5391         mode.width = swapchain_desc->backbuffer_width;
5392         mode.height = swapchain_desc->backbuffer_height;
5393         mode.refresh_rate = swapchain_desc->refresh_rate;
5394         mode.format_id = swapchain_desc->backbuffer_format;
5395     }
5396
5397     /* Should Width == 800 && Height == 0 set 800x600? */
5398     if (swapchain_desc->backbuffer_width && swapchain_desc->backbuffer_height
5399             && (swapchain_desc->backbuffer_width != swapchain->desc.backbuffer_width
5400             || swapchain_desc->backbuffer_height != swapchain->desc.backbuffer_height))
5401     {
5402         if (!swapchain_desc->windowed)
5403             DisplayModeChanged = TRUE;
5404
5405         swapchain->desc.backbuffer_width = swapchain_desc->backbuffer_width;
5406         swapchain->desc.backbuffer_height = swapchain_desc->backbuffer_height;
5407         update_desc = TRUE;
5408     }
5409
5410     if (swapchain_desc->backbuffer_format != WINED3DFMT_UNKNOWN
5411             && swapchain_desc->backbuffer_format != swapchain->desc.backbuffer_format)
5412     {
5413         swapchain->desc.backbuffer_format = swapchain_desc->backbuffer_format;
5414         update_desc = TRUE;
5415     }
5416
5417     if (swapchain_desc->multisample_type != swapchain->desc.multisample_type
5418             || swapchain_desc->multisample_quality != swapchain->desc.multisample_quality)
5419     {
5420         swapchain->desc.multisample_type = swapchain_desc->multisample_type;
5421         swapchain->desc.multisample_quality = swapchain_desc->multisample_quality;
5422         update_desc = TRUE;
5423     }
5424
5425     if (update_desc)
5426     {
5427         UINT i;
5428
5429         hr = wined3d_surface_update_desc(swapchain->front_buffer, swapchain->desc.backbuffer_width,
5430                 swapchain->desc.backbuffer_height, swapchain->desc.backbuffer_format,
5431                 swapchain->desc.multisample_type, swapchain->desc.multisample_quality);
5432         if (FAILED(hr))
5433         {
5434             wined3d_swapchain_decref(swapchain);
5435             return hr;
5436         }
5437
5438         for (i = 0; i < swapchain->desc.backbuffer_count; ++i)
5439         {
5440             hr = wined3d_surface_update_desc(swapchain->back_buffers[i], swapchain->desc.backbuffer_width,
5441                     swapchain->desc.backbuffer_height, swapchain->desc.backbuffer_format,
5442                     swapchain->desc.multisample_type, swapchain->desc.multisample_quality);
5443             if (FAILED(hr))
5444             {
5445                 wined3d_swapchain_decref(swapchain);
5446                 return hr;
5447             }
5448         }
5449         if (device->auto_depth_stencil)
5450         {
5451             hr = wined3d_surface_update_desc(device->auto_depth_stencil, swapchain->desc.backbuffer_width,
5452                     swapchain->desc.backbuffer_height, device->auto_depth_stencil->resource.format->id,
5453                     swapchain->desc.multisample_type, swapchain->desc.multisample_quality);
5454             if (FAILED(hr))
5455             {
5456                 wined3d_swapchain_decref(swapchain);
5457                 return hr;
5458             }
5459         }
5460     }
5461
5462     if (device->d3d_initialized)
5463         delete_opengl_contexts(device, swapchain);
5464
5465     if (!swapchain_desc->windowed != !swapchain->desc.windowed
5466             || DisplayModeChanged)
5467     {
5468         wined3d_device_set_display_mode(device, 0, &mode);
5469
5470         if (!swapchain_desc->windowed)
5471         {
5472             if (swapchain->desc.windowed)
5473             {
5474                 HWND focus_window = device->create_parms.focus_window;
5475                 if (!focus_window)
5476                     focus_window = swapchain_desc->device_window;
5477                 if (FAILED(hr = wined3d_device_acquire_focus_window(device, focus_window)))
5478                 {
5479                     ERR("Failed to acquire focus window, hr %#x.\n", hr);
5480                     wined3d_swapchain_decref(swapchain);
5481                     return hr;
5482                 }
5483
5484                 /* switch from windowed to fs */
5485                 wined3d_device_setup_fullscreen_window(device, swapchain->device_window,
5486                         swapchain_desc->backbuffer_width,
5487                         swapchain_desc->backbuffer_height);
5488             }
5489             else
5490             {
5491                 /* Fullscreen -> fullscreen mode change */
5492                 MoveWindow(swapchain->device_window, 0, 0,
5493                         swapchain_desc->backbuffer_width,
5494                         swapchain_desc->backbuffer_height,
5495                         TRUE);
5496             }
5497         }
5498         else if (!swapchain->desc.windowed)
5499         {
5500             /* Fullscreen -> windowed switch */
5501             wined3d_device_restore_fullscreen_window(device, swapchain->device_window);
5502             wined3d_device_release_focus_window(device);
5503         }
5504         swapchain->desc.windowed = swapchain_desc->windowed;
5505     }
5506     else if (!swapchain_desc->windowed)
5507     {
5508         DWORD style = device->style;
5509         DWORD exStyle = device->exStyle;
5510         /* If we're in fullscreen, and the mode wasn't changed, we have to get the window back into
5511          * the right position. Some applications(Battlefield 2, Guild Wars) move it and then call
5512          * Reset to clear up their mess. Guild Wars also loses the device during that.
5513          */
5514         device->style = 0;
5515         device->exStyle = 0;
5516         wined3d_device_setup_fullscreen_window(device, swapchain->device_window,
5517                 swapchain_desc->backbuffer_width,
5518                 swapchain_desc->backbuffer_height);
5519         device->style = style;
5520         device->exStyle = exStyle;
5521     }
5522
5523     /* Note: No parent needed for initial internal stateblock */
5524     hr = wined3d_stateblock_create(device, WINED3D_SBT_INIT, &device->stateBlock);
5525     if (FAILED(hr))
5526         ERR("Resetting the stateblock failed with error %#x.\n", hr);
5527     else
5528         TRACE("Created stateblock %p.\n", device->stateBlock);
5529     device->updateStateBlock = device->stateBlock;
5530     wined3d_stateblock_incref(device->updateStateBlock);
5531
5532     stateblock_init_default_state(device->stateBlock);
5533
5534     swapchain_update_render_to_fbo(swapchain);
5535     swapchain_update_draw_bindings(swapchain);
5536
5537     if (device->d3d_initialized)
5538         hr = create_primary_opengl_context(device, swapchain);
5539     wined3d_swapchain_decref(swapchain);
5540
5541     /* All done. There is no need to reload resources or shaders, this will happen automatically on the
5542      * first use
5543      */
5544     return hr;
5545 }
5546
5547 HRESULT CDECL wined3d_device_set_dialog_box_mode(struct wined3d_device *device, BOOL enable_dialogs)
5548 {
5549     TRACE("device %p, enable_dialogs %#x.\n", device, enable_dialogs);
5550
5551     if (!enable_dialogs) FIXME("Dialogs cannot be disabled yet.\n");
5552
5553     return WINED3D_OK;
5554 }
5555
5556
5557 HRESULT CDECL wined3d_device_get_creation_parameters(const struct wined3d_device *device,
5558         struct wined3d_device_creation_parameters *parameters)
5559 {
5560     TRACE("device %p, parameters %p.\n", device, parameters);
5561
5562     *parameters = device->create_parms;
5563     return WINED3D_OK;
5564 }
5565
5566 void CDECL wined3d_device_set_gamma_ramp(const struct wined3d_device *device,
5567         UINT swapchain_idx, DWORD flags, const struct wined3d_gamma_ramp *ramp)
5568 {
5569     struct wined3d_swapchain *swapchain;
5570
5571     TRACE("device %p, swapchain_idx %u, flags %#x, ramp %p.\n",
5572             device, swapchain_idx, flags, ramp);
5573
5574     if (SUCCEEDED(wined3d_device_get_swapchain(device, swapchain_idx, &swapchain)))
5575     {
5576         wined3d_swapchain_set_gamma_ramp(swapchain, flags, ramp);
5577         wined3d_swapchain_decref(swapchain);
5578     }
5579 }
5580
5581 void CDECL wined3d_device_get_gamma_ramp(const struct wined3d_device *device,
5582         UINT swapchain_idx, struct wined3d_gamma_ramp *ramp)
5583 {
5584     struct wined3d_swapchain *swapchain;
5585
5586     TRACE("device %p, swapchain_idx %u, ramp %p.\n",
5587             device, swapchain_idx, ramp);
5588
5589     if (SUCCEEDED(wined3d_device_get_swapchain(device, swapchain_idx, &swapchain)))
5590     {
5591         wined3d_swapchain_get_gamma_ramp(swapchain, ramp);
5592         wined3d_swapchain_decref(swapchain);
5593     }
5594 }
5595
5596 void device_resource_add(struct wined3d_device *device, struct wined3d_resource *resource)
5597 {
5598     TRACE("device %p, resource %p.\n", device, resource);
5599
5600     list_add_head(&device->resources, &resource->resource_list_entry);
5601 }
5602
5603 static void device_resource_remove(struct wined3d_device *device, struct wined3d_resource *resource)
5604 {
5605     TRACE("device %p, resource %p.\n", device, resource);
5606
5607     list_remove(&resource->resource_list_entry);
5608 }
5609
5610 void device_resource_released(struct wined3d_device *device, struct wined3d_resource *resource)
5611 {
5612     enum wined3d_resource_type type = resource->type;
5613     unsigned int i;
5614
5615     TRACE("device %p, resource %p, type %s.\n", device, resource, debug_d3dresourcetype(type));
5616
5617     context_resource_released(device, resource, type);
5618
5619     switch (type)
5620     {
5621         case WINED3D_RTYPE_SURFACE:
5622             {
5623                 struct wined3d_surface *surface = surface_from_resource(resource);
5624
5625                 if (!device->d3d_initialized) break;
5626
5627                 for (i = 0; i < device->adapter->gl_info.limits.buffers; ++i)
5628                 {
5629                     if (device->fb.render_targets[i] == surface)
5630                     {
5631                         ERR("Surface %p is still in use as render target %u.\n", surface, i);
5632                         device->fb.render_targets[i] = NULL;
5633                     }
5634                 }
5635
5636                 if (device->fb.depth_stencil == surface)
5637                 {
5638                     ERR("Surface %p is still in use as depth/stencil buffer.\n", surface);
5639                     device->fb.depth_stencil = NULL;
5640                 }
5641             }
5642             break;
5643
5644         case WINED3D_RTYPE_TEXTURE:
5645         case WINED3D_RTYPE_CUBE_TEXTURE:
5646         case WINED3D_RTYPE_VOLUME_TEXTURE:
5647             for (i = 0; i < MAX_COMBINED_SAMPLERS; ++i)
5648             {
5649                 struct wined3d_texture *texture = wined3d_texture_from_resource(resource);
5650
5651                 if (device->stateBlock && device->stateBlock->state.textures[i] == texture)
5652                 {
5653                     ERR("Texture %p is still in use by stateblock %p, stage %u.\n",
5654                             texture, device->stateBlock, i);
5655                     device->stateBlock->state.textures[i] = NULL;
5656                 }
5657
5658                 if (device->updateStateBlock != device->stateBlock
5659                         && device->updateStateBlock->state.textures[i] == texture)
5660                 {
5661                     ERR("Texture %p is still in use by stateblock %p, stage %u.\n",
5662                             texture, device->updateStateBlock, i);
5663                     device->updateStateBlock->state.textures[i] = NULL;
5664                 }
5665             }
5666             break;
5667
5668         case WINED3D_RTYPE_BUFFER:
5669             {
5670                 struct wined3d_buffer *buffer = buffer_from_resource(resource);
5671
5672                 for (i = 0; i < MAX_STREAMS; ++i)
5673                 {
5674                     if (device->stateBlock && device->stateBlock->state.streams[i].buffer == buffer)
5675                     {
5676                         ERR("Buffer %p is still in use by stateblock %p, stream %u.\n",
5677                                 buffer, device->stateBlock, i);
5678                         device->stateBlock->state.streams[i].buffer = NULL;
5679                     }
5680
5681                     if (device->updateStateBlock != device->stateBlock
5682                             && device->updateStateBlock->state.streams[i].buffer == buffer)
5683                     {
5684                         ERR("Buffer %p is still in use by stateblock %p, stream %u.\n",
5685                                 buffer, device->updateStateBlock, i);
5686                         device->updateStateBlock->state.streams[i].buffer = NULL;
5687                     }
5688
5689                 }
5690
5691                 if (device->stateBlock && device->stateBlock->state.index_buffer == buffer)
5692                 {
5693                     ERR("Buffer %p is still in use by stateblock %p as index buffer.\n",
5694                             buffer, device->stateBlock);
5695                     device->stateBlock->state.index_buffer =  NULL;
5696                 }
5697
5698                 if (device->updateStateBlock != device->stateBlock
5699                         && device->updateStateBlock->state.index_buffer == buffer)
5700                 {
5701                     ERR("Buffer %p is still in use by stateblock %p as index buffer.\n",
5702                             buffer, device->updateStateBlock);
5703                     device->updateStateBlock->state.index_buffer =  NULL;
5704                 }
5705             }
5706             break;
5707
5708         default:
5709             break;
5710     }
5711
5712     /* Remove the resource from the resourceStore */
5713     device_resource_remove(device, resource);
5714
5715     TRACE("Resource released.\n");
5716 }
5717
5718 HRESULT CDECL wined3d_device_get_surface_from_dc(const struct wined3d_device *device,
5719         HDC dc, struct wined3d_surface **surface)
5720 {
5721     struct wined3d_resource *resource;
5722
5723     TRACE("device %p, dc %p, surface %p.\n", device, dc, surface);
5724
5725     if (!dc)
5726         return WINED3DERR_INVALIDCALL;
5727
5728     LIST_FOR_EACH_ENTRY(resource, &device->resources, struct wined3d_resource, resource_list_entry)
5729     {
5730         if (resource->type == WINED3D_RTYPE_SURFACE)
5731         {
5732             struct wined3d_surface *s = surface_from_resource(resource);
5733
5734             if (s->hDC == dc)
5735             {
5736                 TRACE("Found surface %p for dc %p.\n", s, dc);
5737                 *surface = s;
5738                 return WINED3D_OK;
5739             }
5740         }
5741     }
5742
5743     return WINED3DERR_INVALIDCALL;
5744 }
5745
5746 HRESULT device_init(struct wined3d_device *device, struct wined3d *wined3d,
5747         UINT adapter_idx, enum wined3d_device_type device_type, HWND focus_window, DWORD flags,
5748         BYTE surface_alignment, struct wined3d_device_parent *device_parent)
5749 {
5750     struct wined3d_adapter *adapter = &wined3d->adapters[adapter_idx];
5751     const struct fragment_pipeline *fragment_pipeline;
5752     struct wined3d_display_mode mode;
5753     struct shader_caps shader_caps;
5754     struct fragment_caps ffp_caps;
5755     unsigned int i;
5756     HRESULT hr;
5757
5758     device->ref = 1;
5759     device->wined3d = wined3d;
5760     wined3d_incref(device->wined3d);
5761     device->adapter = wined3d->adapter_count ? adapter : NULL;
5762     device->device_parent = device_parent;
5763     list_init(&device->resources);
5764     list_init(&device->shaders);
5765     device->surface_alignment = surface_alignment;
5766
5767     /* Get the initial screen setup for ddraw. */
5768     hr = wined3d_get_adapter_display_mode(wined3d, adapter_idx, &mode);
5769     if (FAILED(hr))
5770     {
5771         ERR("Failed to get the adapter's display mode, hr %#x.\n", hr);
5772         wined3d_decref(device->wined3d);
5773         return hr;
5774     }
5775     adapter->screen_size.cx = mode.width;
5776     adapter->screen_size.cy = mode.height;
5777     adapter->screen_format = mode.format_id;
5778
5779     /* Save the creation parameters. */
5780     device->create_parms.adapter_idx = adapter_idx;
5781     device->create_parms.device_type = device_type;
5782     device->create_parms.focus_window = focus_window;
5783     device->create_parms.flags = flags;
5784
5785     for (i = 0; i < PATCHMAP_SIZE; ++i) list_init(&device->patches[i]);
5786
5787     select_shader_mode(&adapter->gl_info, &device->ps_selected_mode, &device->vs_selected_mode);
5788     device->shader_backend = adapter->shader_backend;
5789
5790     if (device->shader_backend)
5791     {
5792         device->shader_backend->shader_get_caps(&adapter->gl_info, &shader_caps);
5793         device->vshader_version = shader_caps.VertexShaderVersion;
5794         device->pshader_version = shader_caps.PixelShaderVersion;
5795         device->d3d_vshader_constantF = shader_caps.MaxVertexShaderConst;
5796         device->d3d_pshader_constantF = shader_caps.MaxPixelShaderConst;
5797         device->vs_clipping = shader_caps.VSClipping;
5798     }
5799     fragment_pipeline = adapter->fragment_pipe;
5800     device->frag_pipe = fragment_pipeline;
5801     if (fragment_pipeline)
5802     {
5803         fragment_pipeline->get_caps(&adapter->gl_info, &ffp_caps);
5804         device->max_ffp_textures = ffp_caps.MaxSimultaneousTextures;
5805
5806         hr = compile_state_table(device->StateTable, device->multistate_funcs, &adapter->gl_info,
5807                                  ffp_vertexstate_template, fragment_pipeline, misc_state_template);
5808         if (FAILED(hr))
5809         {
5810             ERR("Failed to compile state table, hr %#x.\n", hr);
5811             wined3d_decref(device->wined3d);
5812             return hr;
5813         }
5814     }
5815     device->blitter = adapter->blitter;
5816
5817     hr = wined3d_stateblock_create(device, WINED3D_SBT_INIT, &device->stateBlock);
5818     if (FAILED(hr))
5819     {
5820         WARN("Failed to create stateblock.\n");
5821         for (i = 0; i < sizeof(device->multistate_funcs) / sizeof(device->multistate_funcs[0]); ++i)
5822         {
5823             HeapFree(GetProcessHeap(), 0, device->multistate_funcs[i]);
5824         }
5825         wined3d_decref(device->wined3d);
5826         return hr;
5827     }
5828
5829     TRACE("Created stateblock %p.\n", device->stateBlock);
5830     device->updateStateBlock = device->stateBlock;
5831     wined3d_stateblock_incref(device->updateStateBlock);
5832
5833     return WINED3D_OK;
5834 }
5835
5836
5837 void device_invalidate_state(const struct wined3d_device *device, DWORD state)
5838 {
5839     DWORD rep = device->StateTable[state].representative;
5840     struct wined3d_context *context;
5841     DWORD idx;
5842     BYTE shift;
5843     UINT i;
5844
5845     for (i = 0; i < device->context_count; ++i)
5846     {
5847         context = device->contexts[i];
5848         if(isStateDirty(context, rep)) continue;
5849
5850         context->dirtyArray[context->numDirtyEntries++] = rep;
5851         idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
5852         shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
5853         context->isStateDirty[idx] |= (1 << shift);
5854     }
5855 }
5856
5857 void get_drawable_size_fbo(const struct wined3d_context *context, UINT *width, UINT *height)
5858 {
5859     /* The drawable size of a fbo target is the opengl texture size, which is the power of two size. */
5860     *width = context->current_rt->pow2Width;
5861     *height = context->current_rt->pow2Height;
5862 }
5863
5864 void get_drawable_size_backbuffer(const struct wined3d_context *context, UINT *width, UINT *height)
5865 {
5866     const struct wined3d_swapchain *swapchain = context->swapchain;
5867     /* The drawable size of a backbuffer / aux buffer offscreen target is the size of the
5868      * current context's drawable, which is the size of the back buffer of the swapchain
5869      * the active context belongs to. */
5870     *width = swapchain->desc.backbuffer_width;
5871     *height = swapchain->desc.backbuffer_height;
5872 }
5873
5874 LRESULT device_process_message(struct wined3d_device *device, HWND window, BOOL unicode,
5875         UINT message, WPARAM wparam, LPARAM lparam, WNDPROC proc)
5876 {
5877     if (device->filter_messages)
5878     {
5879         TRACE("Filtering message: window %p, message %#x, wparam %#lx, lparam %#lx.\n",
5880                 window, message, wparam, lparam);
5881         if (unicode)
5882             return DefWindowProcW(window, message, wparam, lparam);
5883         else
5884             return DefWindowProcA(window, message, wparam, lparam);
5885     }
5886
5887     if (message == WM_DESTROY)
5888     {
5889         TRACE("unregister window %p.\n", window);
5890         wined3d_unregister_window(window);
5891
5892         if (InterlockedCompareExchangePointer((void **)&device->focus_window, NULL, window) != window)
5893             ERR("Window %p is not the focus window for device %p.\n", window, device);
5894     }
5895     else if (message == WM_DISPLAYCHANGE)
5896     {
5897         device->device_parent->ops->mode_changed(device->device_parent);
5898     }
5899
5900     if (unicode)
5901         return CallWindowProcW(proc, window, message, wparam, lparam);
5902     else
5903         return CallWindowProcA(proc, window, message, wparam, lparam);
5904 }