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