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