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