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