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