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