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