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