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