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