device9.c revision 0fc21ecfc0891d239f20bf7724e51bc75503570c
1/*
2 * Copyright 2011 Joakim Sindholt <opensource@zhasha.com>
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * on the rights to use, copy, modify, merge, publish, distribute, sub
8 * license, and/or sell copies of the Software, and to permit persons to whom
9 * the Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHOR(S) AND/OR THEIR SUPPLIERS BE LIABLE FOR ANY CLAIM,
19 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
20 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
21 * USE OR OTHER DEALINGS IN THE SOFTWARE. */
22
23#include "device9.h"
24#include "stateblock9.h"
25#include "surface9.h"
26#include "swapchain9.h"
27#include "swapchain9ex.h"
28#include "indexbuffer9.h"
29#include "vertexbuffer9.h"
30#include "vertexdeclaration9.h"
31#include "vertexshader9.h"
32#include "pixelshader9.h"
33#include "query9.h"
34#include "texture9.h"
35#include "cubetexture9.h"
36#include "volumetexture9.h"
37#include "nine_helpers.h"
38#include "nine_pipe.h"
39#include "nine_ff.h"
40#include "nine_dump.h"
41
42#include "pipe/p_screen.h"
43#include "pipe/p_context.h"
44#include "pipe/p_config.h"
45#include "util/u_math.h"
46#include "util/u_inlines.h"
47#include "util/u_hash_table.h"
48#include "util/u_format.h"
49#include "util/u_surface.h"
50#include "util/u_upload_mgr.h"
51#include "hud/hud_context.h"
52
53#include "cso_cache/cso_context.h"
54
55#define DBG_CHANNEL DBG_DEVICE
56
57#if defined(PIPE_CC_GCC) && (defined(PIPE_ARCH_X86) || defined(PIPE_ARCH_X86_64))
58
59#include <fpu_control.h>
60
61static void nine_setup_fpu()
62{
63    fpu_control_t c;
64
65    _FPU_GETCW(c);
66    /* clear the control word */
67    c &= _FPU_RESERVED;
68    /* d3d9 doc/wine tests: mask all exceptions, use single-precision
69     * and round to nearest */
70    c |= _FPU_MASK_IM | _FPU_MASK_DM | _FPU_MASK_ZM | _FPU_MASK_OM |
71         _FPU_MASK_UM | _FPU_MASK_PM | _FPU_SINGLE | _FPU_RC_NEAREST;
72    _FPU_SETCW(c);
73}
74
75#else
76
77static void nine_setup_fpu(void)
78{
79    WARN_ONCE("FPU setup not supported on non-x86 platforms\n");
80}
81
82#endif
83
84static void
85NineDevice9_SetDefaultState( struct NineDevice9 *This, boolean is_reset )
86{
87    struct NineSurface9 *refSurf = NULL;
88
89    DBG("This=%p is_reset=%d\n", This, (int) is_reset);
90
91    assert(!This->is_recording);
92
93    nine_state_set_defaults(This, &This->caps, is_reset);
94
95    This->state.viewport.X = 0;
96    This->state.viewport.Y = 0;
97    This->state.viewport.Width = 0;
98    This->state.viewport.Height = 0;
99
100    This->state.scissor.minx = 0;
101    This->state.scissor.miny = 0;
102    This->state.scissor.maxx = 0xffff;
103    This->state.scissor.maxy = 0xffff;
104
105    if (This->nswapchains && This->swapchains[0]->params.BackBufferCount)
106        refSurf = This->swapchains[0]->buffers[0];
107
108    if (refSurf) {
109        This->state.viewport.Width = refSurf->desc.Width;
110        This->state.viewport.Height = refSurf->desc.Height;
111        This->state.scissor.maxx = refSurf->desc.Width;
112        This->state.scissor.maxy = refSurf->desc.Height;
113    }
114
115    if (This->nswapchains && This->swapchains[0]->params.EnableAutoDepthStencil)
116        This->state.rs[D3DRS_ZENABLE] = TRUE;
117    if (This->state.rs[D3DRS_ZENABLE])
118        NineDevice9_SetDepthStencilSurface(
119            This, (IDirect3DSurface9 *)This->swapchains[0]->zsbuf);
120}
121
122#define GET_PCAP(n) pScreen->get_param(pScreen, PIPE_CAP_##n)
123HRESULT
124NineDevice9_ctor( struct NineDevice9 *This,
125                  struct NineUnknownParams *pParams,
126                  struct pipe_screen *pScreen,
127                  D3DDEVICE_CREATION_PARAMETERS *pCreationParameters,
128                  D3DCAPS9 *pCaps,
129                  D3DPRESENT_PARAMETERS *pPresentationParameters,
130                  IDirect3D9 *pD3D9,
131                  ID3DPresentGroup *pPresentationGroup,
132                  struct d3dadapter9_context *pCTX,
133                  boolean ex,
134                  D3DDISPLAYMODEEX *pFullscreenDisplayMode )
135{
136    unsigned i;
137    HRESULT hr = NineUnknown_ctor(&This->base, pParams);
138
139    DBG("This=%p pParams=%p pScreen=%p pCreationParameters=%p pCaps=%p pPresentationParameters=%p "
140        "pD3D9=%p pPresentationGroup=%p pCTX=%p ex=%d pFullscreenDisplayMode=%p\n",
141        This, pParams, pScreen, pCreationParameters, pCaps, pPresentationParameters, pD3D9,
142        pPresentationGroup, pCTX, (int) ex, pFullscreenDisplayMode);
143
144    if (FAILED(hr)) { return hr; }
145
146    list_inithead(&This->update_textures);
147    list_inithead(&This->managed_textures);
148
149    This->screen = pScreen;
150    This->caps = *pCaps;
151    This->d3d9 = pD3D9;
152    This->params = *pCreationParameters;
153    This->ex = ex;
154    This->present = pPresentationGroup;
155    IDirect3D9_AddRef(This->d3d9);
156    ID3DPresentGroup_AddRef(This->present);
157
158    if (!(This->params.BehaviorFlags & D3DCREATE_FPU_PRESERVE))
159        nine_setup_fpu();
160
161    if (This->params.BehaviorFlags & D3DCREATE_SOFTWARE_VERTEXPROCESSING)
162        DBG("Application asked full Software Vertex Processing. Ignoring.\n");
163    if (This->params.BehaviorFlags & D3DCREATE_MIXED_VERTEXPROCESSING)
164        DBG("Application asked mixed Software Vertex Processing. Ignoring.\n");
165
166    This->pipe = This->screen->context_create(This->screen, NULL, 0);
167    if (!This->pipe) { return E_OUTOFMEMORY; } /* guess */
168
169    This->cso = cso_create_context(This->pipe);
170    if (!This->cso) { return E_OUTOFMEMORY; } /* also a guess */
171
172    /* Create first, it messes up our state. */
173    This->hud = hud_create(This->pipe, This->cso); /* NULL result is fine */
174
175    /* create implicit swapchains */
176    This->nswapchains = ID3DPresentGroup_GetMultiheadCount(This->present);
177    This->swapchains = CALLOC(This->nswapchains,
178                              sizeof(struct NineSwapChain9 *));
179    if (!This->swapchains) { return E_OUTOFMEMORY; }
180
181    for (i = 0; i < This->nswapchains; ++i) {
182        ID3DPresent *present;
183
184        hr = ID3DPresentGroup_GetPresent(This->present, i, &present);
185        if (FAILED(hr))
186            return hr;
187
188        if (ex) {
189            D3DDISPLAYMODEEX *mode = NULL;
190            struct NineSwapChain9Ex **ret =
191                (struct NineSwapChain9Ex **)&This->swapchains[i];
192
193            if (pFullscreenDisplayMode) mode = &(pFullscreenDisplayMode[i]);
194            /* when this is a Device9Ex, it should create SwapChain9Exs */
195            hr = NineSwapChain9Ex_new(This, TRUE, present,
196                                      &pPresentationParameters[i], pCTX,
197                                      This->params.hFocusWindow, mode, ret);
198        } else {
199            hr = NineSwapChain9_new(This, TRUE, present,
200                                    &pPresentationParameters[i], pCTX,
201                                    This->params.hFocusWindow,
202                                    &This->swapchains[i]);
203        }
204
205        ID3DPresent_Release(present);
206        if (FAILED(hr))
207            return hr;
208        NineUnknown_ConvertRefToBind(NineUnknown(This->swapchains[i]));
209
210        hr = NineSwapChain9_GetBackBuffer(This->swapchains[i], 0,
211                                          D3DBACKBUFFER_TYPE_MONO,
212                                          (IDirect3DSurface9 **)
213                                          &This->state.rt[i]);
214        if (FAILED(hr))
215            return hr;
216        NineUnknown_ConvertRefToBind(NineUnknown(This->state.rt[i]));
217    }
218
219    /* Initialize a dummy VBO to be used when a a vertex declaration does not
220     * specify all the inputs needed by vertex shader, on win default behavior
221     * is to pass 0,0,0,0 to the shader */
222    {
223        struct pipe_transfer *transfer;
224        struct pipe_resource tmpl;
225        struct pipe_box box;
226        unsigned char *data;
227
228        tmpl.target = PIPE_BUFFER;
229        tmpl.format = PIPE_FORMAT_R8_UNORM;
230        tmpl.width0 = 16; /* 4 floats */
231        tmpl.height0 = 1;
232        tmpl.depth0 = 1;
233        tmpl.array_size = 1;
234        tmpl.last_level = 0;
235        tmpl.nr_samples = 0;
236        tmpl.usage = PIPE_USAGE_DEFAULT;
237        tmpl.bind = PIPE_BIND_VERTEX_BUFFER | PIPE_BIND_TRANSFER_WRITE;
238        tmpl.flags = 0;
239        This->dummy_vbo = pScreen->resource_create(pScreen, &tmpl);
240
241        if (!This->dummy_vbo)
242            return D3DERR_OUTOFVIDEOMEMORY;
243
244        u_box_1d(0, 16, &box);
245        data = This->pipe->transfer_map(This->pipe, This->dummy_vbo, 0,
246                                        PIPE_TRANSFER_WRITE |
247                                        PIPE_TRANSFER_DISCARD_WHOLE_RESOURCE,
248                                        &box, &transfer);
249        assert(data);
250        assert(transfer);
251        memset(data, 0, 16);
252        This->pipe->transfer_unmap(This->pipe, transfer);
253    }
254
255    This->cursor.software = FALSE;
256    This->cursor.hotspot.x = -1;
257    This->cursor.hotspot.y = -1;
258    {
259        struct pipe_resource tmpl;
260        tmpl.target = PIPE_TEXTURE_2D;
261        tmpl.format = PIPE_FORMAT_R8G8B8A8_UNORM;
262        tmpl.width0 = 64;
263        tmpl.height0 = 64;
264        tmpl.depth0 = 1;
265        tmpl.array_size = 1;
266        tmpl.last_level = 0;
267        tmpl.nr_samples = 0;
268        tmpl.usage = PIPE_USAGE_DEFAULT;
269        tmpl.bind = PIPE_BIND_CURSOR | PIPE_BIND_SAMPLER_VIEW;
270        tmpl.flags = 0;
271
272        This->cursor.image = pScreen->resource_create(pScreen, &tmpl);
273        if (!This->cursor.image)
274            return D3DERR_OUTOFVIDEOMEMORY;
275    }
276
277    /* Create constant buffers. */
278    {
279        struct pipe_resource tmpl;
280        unsigned max_const_vs, max_const_ps;
281
282        /* vs 3.0: >= 256 float constants, but for cards with exactly 256 slots,
283         * we have to take in some more slots for int and bool*/
284        max_const_vs = _min(pScreen->get_shader_param(pScreen, PIPE_SHADER_VERTEX,
285                                PIPE_SHADER_CAP_MAX_CONST_BUFFER_SIZE) /
286                                sizeof(float[4]),
287                            NINE_MAX_CONST_ALL);
288        /* ps 3.0: 224 float constants. All cards supported support at least
289         * 256 constants for ps */
290        max_const_ps = NINE_MAX_CONST_F_PS3 + (NINE_MAX_CONST_I + NINE_MAX_CONST_B / 4);
291
292        This->max_vs_const_f = max_const_vs -
293                               (NINE_MAX_CONST_I + NINE_MAX_CONST_B / 4);
294        This->max_ps_const_f = max_const_ps -
295                               (NINE_MAX_CONST_I + NINE_MAX_CONST_B / 4);
296
297        This->vs_const_size = max_const_vs * sizeof(float[4]);
298        This->ps_const_size = max_const_ps * sizeof(float[4]);
299        /* Include space for I,B constants for user constbuf. */
300        This->state.vs_const_f = CALLOC(This->vs_const_size, 1);
301        This->state.ps_const_f = CALLOC(This->ps_const_size, 1);
302        This->state.vs_lconstf_temp = CALLOC(This->vs_const_size,1);
303        This->state.ps_lconstf_temp = CALLOC(This->ps_const_size,1);
304        if (!This->state.vs_const_f || !This->state.ps_const_f ||
305            !This->state.vs_lconstf_temp || !This->state.ps_lconstf_temp)
306            return E_OUTOFMEMORY;
307
308        if (strstr(pScreen->get_name(pScreen), "AMD") ||
309            strstr(pScreen->get_name(pScreen), "ATI")) {
310            This->driver_bugs.buggy_barycentrics = TRUE;
311        }
312
313        /* Disable NV path for now, needs some fixes */
314        This->prefer_user_constbuf = TRUE;
315
316        tmpl.target = PIPE_BUFFER;
317        tmpl.format = PIPE_FORMAT_R8_UNORM;
318        tmpl.height0 = 1;
319        tmpl.depth0 = 1;
320        tmpl.array_size = 1;
321        tmpl.last_level = 0;
322        tmpl.nr_samples = 0;
323        tmpl.usage = PIPE_USAGE_DYNAMIC;
324        tmpl.bind = PIPE_BIND_CONSTANT_BUFFER;
325        tmpl.flags = 0;
326
327        tmpl.width0 = This->vs_const_size;
328        This->constbuf_vs = pScreen->resource_create(pScreen, &tmpl);
329
330        tmpl.width0 = This->ps_const_size;
331        This->constbuf_ps = pScreen->resource_create(pScreen, &tmpl);
332
333        if (!This->constbuf_vs || !This->constbuf_ps)
334            return E_OUTOFMEMORY;
335    }
336
337    /* allocate dummy texture/sampler for when there are missing ones bound */
338    {
339        struct pipe_resource tmplt;
340        struct pipe_sampler_view templ;
341        struct pipe_sampler_state samp;
342        memset(&samp, 0, sizeof(samp));
343
344        tmplt.target = PIPE_TEXTURE_2D;
345        tmplt.width0 = 1;
346        tmplt.height0 = 1;
347        tmplt.depth0 = 1;
348        tmplt.last_level = 0;
349        tmplt.array_size = 1;
350        tmplt.usage = PIPE_USAGE_DEFAULT;
351        tmplt.flags = 0;
352        tmplt.format = PIPE_FORMAT_B8G8R8A8_UNORM;
353        tmplt.bind = PIPE_BIND_SAMPLER_VIEW;
354        tmplt.nr_samples = 0;
355
356        This->dummy_texture = This->screen->resource_create(This->screen, &tmplt);
357        if (!This->dummy_texture)
358            return D3DERR_DRIVERINTERNALERROR;
359
360        templ.format = PIPE_FORMAT_B8G8R8A8_UNORM;
361        templ.u.tex.first_layer = 0;
362        templ.u.tex.last_layer = 0;
363        templ.u.tex.first_level = 0;
364        templ.u.tex.last_level = 0;
365        templ.swizzle_r = PIPE_SWIZZLE_ZERO;
366        templ.swizzle_g = PIPE_SWIZZLE_ZERO;
367        templ.swizzle_b = PIPE_SWIZZLE_ZERO;
368        templ.swizzle_a = PIPE_SWIZZLE_ONE;
369        templ.target = This->dummy_texture->target;
370
371        This->dummy_sampler_view = This->pipe->create_sampler_view(This->pipe, This->dummy_texture, &templ);
372        if (!This->dummy_sampler_view)
373            return D3DERR_DRIVERINTERNALERROR;
374
375        samp.min_mip_filter = PIPE_TEX_MIPFILTER_NONE;
376        samp.max_lod = 15.0f;
377        samp.wrap_s = PIPE_TEX_WRAP_CLAMP_TO_EDGE;
378        samp.wrap_t = PIPE_TEX_WRAP_CLAMP_TO_EDGE;
379        samp.wrap_r = PIPE_TEX_WRAP_CLAMP_TO_EDGE;
380        samp.min_img_filter = PIPE_TEX_FILTER_NEAREST;
381        samp.mag_img_filter = PIPE_TEX_FILTER_NEAREST;
382        samp.compare_mode = PIPE_TEX_COMPARE_NONE;
383        samp.compare_func = PIPE_FUNC_LEQUAL;
384        samp.normalized_coords = 1;
385        samp.seamless_cube_map = 1;
386        This->dummy_sampler_state = samp;
387    }
388
389    /* Allocate upload helper for drivers that suck (from st pov ;). */
390
391    This->driver_caps.user_vbufs = GET_PCAP(USER_VERTEX_BUFFERS);
392    This->driver_caps.user_ibufs = GET_PCAP(USER_INDEX_BUFFERS);
393    This->driver_caps.user_cbufs = GET_PCAP(USER_CONSTANT_BUFFERS);
394
395    if (!This->driver_caps.user_vbufs)
396        This->vertex_uploader = u_upload_create(This->pipe, 65536, 4, PIPE_BIND_VERTEX_BUFFER);
397    if (!This->driver_caps.user_ibufs)
398        This->index_uploader = u_upload_create(This->pipe, 128 * 1024, 4, PIPE_BIND_INDEX_BUFFER);
399    if (!This->driver_caps.user_cbufs) {
400        unsigned alignment = GET_PCAP(CONSTANT_BUFFER_OFFSET_ALIGNMENT);
401
402        This->constbuf_uploader = u_upload_create(This->pipe, This->vs_const_size,
403                                                  alignment, PIPE_BIND_CONSTANT_BUFFER);
404    }
405
406    This->driver_caps.window_space_position_support = GET_PCAP(TGSI_VS_WINDOW_SPACE_POSITION);
407    This->driver_caps.vs_integer = pScreen->get_shader_param(pScreen, PIPE_SHADER_VERTEX, PIPE_SHADER_CAP_INTEGERS);
408    This->driver_caps.ps_integer = pScreen->get_shader_param(pScreen, PIPE_SHADER_FRAGMENT, PIPE_SHADER_CAP_INTEGERS);
409
410    nine_ff_init(This); /* initialize fixed function code */
411
412    NineDevice9_SetDefaultState(This, FALSE);
413
414    {
415        struct pipe_poly_stipple stipple;
416        memset(&stipple, ~0, sizeof(stipple));
417        This->pipe->set_polygon_stipple(This->pipe, &stipple);
418    }
419
420    This->update = &This->state;
421    nine_update_state(This);
422
423    ID3DPresentGroup_Release(This->present);
424
425    return D3D_OK;
426}
427#undef GET_PCAP
428
429void
430NineDevice9_dtor( struct NineDevice9 *This )
431{
432    unsigned i;
433
434    DBG("This=%p\n", This);
435
436    if (This->pipe && This->cso)
437        nine_pipe_context_clear(This);
438    nine_ff_fini(This);
439    nine_state_clear(&This->state, TRUE);
440
441    if (This->vertex_uploader)
442        u_upload_destroy(This->vertex_uploader);
443    if (This->index_uploader)
444        u_upload_destroy(This->index_uploader);
445    if (This->constbuf_uploader)
446        u_upload_destroy(This->constbuf_uploader);
447
448    nine_bind(&This->record, NULL);
449
450    pipe_sampler_view_reference(&This->dummy_sampler_view, NULL);
451    pipe_resource_reference(&This->dummy_texture, NULL);
452    pipe_resource_reference(&This->constbuf_vs, NULL);
453    pipe_resource_reference(&This->constbuf_ps, NULL);
454    pipe_resource_reference(&This->dummy_vbo, NULL);
455    FREE(This->state.vs_const_f);
456    FREE(This->state.ps_const_f);
457    FREE(This->state.vs_lconstf_temp);
458    FREE(This->state.ps_lconstf_temp);
459
460    if (This->swapchains) {
461        for (i = 0; i < This->nswapchains; ++i)
462            NineUnknown_Unbind(NineUnknown(This->swapchains[i]));
463        FREE(This->swapchains);
464    }
465
466    /* state stuff */
467    if (This->pipe) {
468        if (This->cso) {
469            cso_destroy_context(This->cso);
470        }
471        if (This->pipe->destroy) { This->pipe->destroy(This->pipe); }
472    }
473
474    if (This->present) { ID3DPresentGroup_Release(This->present); }
475    if (This->d3d9) { IDirect3D9_Release(This->d3d9); }
476
477    NineUnknown_dtor(&This->base);
478}
479
480struct pipe_screen *
481NineDevice9_GetScreen( struct NineDevice9 *This )
482{
483    return This->screen;
484}
485
486struct pipe_context *
487NineDevice9_GetPipe( struct NineDevice9 *This )
488{
489    return This->pipe;
490}
491
492struct cso_context *
493NineDevice9_GetCSO( struct NineDevice9 *This )
494{
495    return This->cso;
496}
497
498const D3DCAPS9 *
499NineDevice9_GetCaps( struct NineDevice9 *This )
500{
501    return &This->caps;
502}
503
504static inline void
505NineDevice9_PauseRecording( struct NineDevice9 *This )
506{
507    if (This->record) {
508        This->update = &This->state;
509        This->is_recording = FALSE;
510    }
511}
512
513static inline void
514NineDevice9_ResumeRecording( struct NineDevice9 *This )
515{
516    if (This->record) {
517        This->update = &This->record->state;
518        This->is_recording = TRUE;
519    }
520}
521
522HRESULT WINAPI
523NineDevice9_TestCooperativeLevel( struct NineDevice9 *This )
524{
525    return D3D_OK; /* TODO */
526}
527
528UINT WINAPI
529NineDevice9_GetAvailableTextureMem( struct NineDevice9 *This )
530{
531   const unsigned mem = This->screen->get_param(This->screen, PIPE_CAP_VIDEO_MEMORY);
532   if (mem < 4096)
533      return mem << 20;
534   else
535      return UINT_MAX;
536}
537
538HRESULT WINAPI
539NineDevice9_EvictManagedResources( struct NineDevice9 *This )
540{
541    struct NineBaseTexture9 *tex;
542
543    DBG("This=%p\n", This);
544    LIST_FOR_EACH_ENTRY(tex, &This->managed_textures, list2) {
545        NineBaseTexture9_UnLoad(tex);
546    }
547
548    return D3D_OK;
549}
550
551HRESULT WINAPI
552NineDevice9_GetDirect3D( struct NineDevice9 *This,
553                         IDirect3D9 **ppD3D9 )
554{
555    user_assert(ppD3D9 != NULL, E_POINTER);
556    IDirect3D9_AddRef(This->d3d9);
557    *ppD3D9 = This->d3d9;
558    return D3D_OK;
559}
560
561HRESULT WINAPI
562NineDevice9_GetDeviceCaps( struct NineDevice9 *This,
563                           D3DCAPS9 *pCaps )
564{
565    user_assert(pCaps != NULL, D3DERR_INVALIDCALL);
566    *pCaps = This->caps;
567    return D3D_OK;
568}
569
570HRESULT WINAPI
571NineDevice9_GetDisplayMode( struct NineDevice9 *This,
572                            UINT iSwapChain,
573                            D3DDISPLAYMODE *pMode )
574{
575    DBG("This=%p iSwapChain=%u pMode=%p\n", This, iSwapChain, pMode);
576
577    user_assert(iSwapChain < This->nswapchains, D3DERR_INVALIDCALL);
578
579    return NineSwapChain9_GetDisplayMode(This->swapchains[iSwapChain], pMode);
580}
581
582HRESULT WINAPI
583NineDevice9_GetCreationParameters( struct NineDevice9 *This,
584                                   D3DDEVICE_CREATION_PARAMETERS *pParameters )
585{
586    user_assert(pParameters != NULL, D3DERR_INVALIDCALL);
587    *pParameters = This->params;
588    return D3D_OK;
589}
590
591HRESULT WINAPI
592NineDevice9_SetCursorProperties( struct NineDevice9 *This,
593                                 UINT XHotSpot,
594                                 UINT YHotSpot,
595                                 IDirect3DSurface9 *pCursorBitmap )
596{
597    struct NineSurface9 *surf = NineSurface9(pCursorBitmap);
598    struct pipe_context *pipe = This->pipe;
599    struct pipe_box box;
600    struct pipe_transfer *transfer;
601    BOOL hw_cursor;
602    void *ptr;
603
604    DBG_FLAG(DBG_SWAPCHAIN, "This=%p XHotSpot=%u YHotSpot=%u "
605             "pCursorBitmap=%p\n", This, XHotSpot, YHotSpot, pCursorBitmap);
606
607    user_assert(pCursorBitmap, D3DERR_INVALIDCALL);
608
609    if (This->swapchains[0]->params.Windowed) {
610        This->cursor.w = MIN2(surf->desc.Width, 32);
611        This->cursor.h = MIN2(surf->desc.Height, 32);
612        hw_cursor = 1; /* always use hw cursor for windowed mode */
613    } else {
614        This->cursor.w = MIN2(surf->desc.Width, This->cursor.image->width0);
615        This->cursor.h = MIN2(surf->desc.Height, This->cursor.image->height0);
616        hw_cursor = This->cursor.w == 32 && This->cursor.h == 32;
617    }
618
619    u_box_origin_2d(This->cursor.w, This->cursor.h, &box);
620
621    ptr = pipe->transfer_map(pipe, This->cursor.image, 0,
622                             PIPE_TRANSFER_WRITE |
623                             PIPE_TRANSFER_DISCARD_WHOLE_RESOURCE,
624                             &box, &transfer);
625    if (!ptr)
626        ret_err("Failed to update cursor image.\n", D3DERR_DRIVERINTERNALERROR);
627
628    This->cursor.hotspot.x = XHotSpot;
629    This->cursor.hotspot.y = YHotSpot;
630
631    /* Copy cursor image to internal storage. */
632    {
633        D3DLOCKED_RECT lock;
634        HRESULT hr;
635        const struct util_format_description *sfmt =
636            util_format_description(surf->base.info.format);
637        assert(sfmt);
638
639        hr = NineSurface9_LockRect(surf, &lock, NULL, D3DLOCK_READONLY);
640        if (FAILED(hr))
641            ret_err("Failed to map cursor source image.\n",
642                    D3DERR_DRIVERINTERNALERROR);
643
644        sfmt->unpack_rgba_8unorm(ptr, transfer->stride,
645                                 lock.pBits, lock.Pitch,
646                                 This->cursor.w, This->cursor.h);
647
648        if (hw_cursor)
649            hw_cursor = ID3DPresent_SetCursor(This->swapchains[0]->present,
650                                              lock.pBits,
651                                              &This->cursor.hotspot,
652                                              This->cursor.visible) == D3D_OK;
653
654        NineSurface9_UnlockRect(surf);
655    }
656    pipe->transfer_unmap(pipe, transfer);
657
658    /* hide cursor if we emulate it */
659    if (!hw_cursor)
660        ID3DPresent_SetCursor(This->swapchains[0]->present, NULL, NULL, FALSE);
661    This->cursor.software = !hw_cursor;
662
663    return D3D_OK;
664}
665
666void WINAPI
667NineDevice9_SetCursorPosition( struct NineDevice9 *This,
668                               int X,
669                               int Y,
670                               DWORD Flags )
671{
672    struct NineSwapChain9 *swap = This->swapchains[0];
673
674    DBG("This=%p X=%d Y=%d Flags=%d\n", This, X, Y, Flags);
675
676    This->cursor.pos.x = X;
677    This->cursor.pos.y = Y;
678
679    if (!This->cursor.software)
680        This->cursor.software = ID3DPresent_SetCursorPos(swap->present, &This->cursor.pos) != D3D_OK;
681}
682
683BOOL WINAPI
684NineDevice9_ShowCursor( struct NineDevice9 *This,
685                        BOOL bShow )
686{
687    BOOL old = This->cursor.visible;
688
689    DBG("This=%p bShow=%d\n", This, (int) bShow);
690
691    This->cursor.visible = bShow && (This->cursor.hotspot.x != -1);
692    if (!This->cursor.software)
693        This->cursor.software = ID3DPresent_SetCursor(This->swapchains[0]->present, NULL, NULL, bShow) != D3D_OK;
694
695    return old;
696}
697
698HRESULT WINAPI
699NineDevice9_CreateAdditionalSwapChain( struct NineDevice9 *This,
700                                       D3DPRESENT_PARAMETERS *pPresentationParameters,
701                                       IDirect3DSwapChain9 **pSwapChain )
702{
703    struct NineSwapChain9 *swapchain, *tmplt = This->swapchains[0];
704    ID3DPresent *present;
705    HRESULT hr;
706
707    DBG("This=%p pPresentationParameters=%p pSwapChain=%p\n",
708        This, pPresentationParameters, pSwapChain);
709
710    user_assert(pPresentationParameters, D3DERR_INVALIDCALL);
711
712    hr = ID3DPresentGroup_CreateAdditionalPresent(This->present, pPresentationParameters, &present);
713
714    if (FAILED(hr))
715        return hr;
716
717    hr = NineSwapChain9_new(This, FALSE, present, pPresentationParameters,
718                            tmplt->actx,
719                            tmplt->params.hDeviceWindow,
720                            &swapchain);
721    if (FAILED(hr))
722        return hr;
723
724    *pSwapChain = (IDirect3DSwapChain9 *)swapchain;
725    return D3D_OK;
726}
727
728HRESULT WINAPI
729NineDevice9_GetSwapChain( struct NineDevice9 *This,
730                          UINT iSwapChain,
731                          IDirect3DSwapChain9 **pSwapChain )
732{
733    user_assert(pSwapChain != NULL, D3DERR_INVALIDCALL);
734
735    *pSwapChain = NULL;
736    user_assert(iSwapChain < This->nswapchains, D3DERR_INVALIDCALL);
737
738    NineUnknown_AddRef(NineUnknown(This->swapchains[iSwapChain]));
739    *pSwapChain = (IDirect3DSwapChain9 *)This->swapchains[iSwapChain];
740
741    return D3D_OK;
742}
743
744UINT WINAPI
745NineDevice9_GetNumberOfSwapChains( struct NineDevice9 *This )
746{
747    return This->nswapchains;
748}
749
750HRESULT WINAPI
751NineDevice9_Reset( struct NineDevice9 *This,
752                   D3DPRESENT_PARAMETERS *pPresentationParameters )
753{
754    HRESULT hr = D3D_OK;
755    unsigned i;
756
757    DBG("This=%p pPresentationParameters=%p\n", This, pPresentationParameters);
758
759    for (i = 0; i < This->nswapchains; ++i) {
760        D3DPRESENT_PARAMETERS *params = &pPresentationParameters[i];
761        hr = NineSwapChain9_Resize(This->swapchains[i], params, NULL);
762        if (hr != D3D_OK)
763            return hr;
764    }
765
766    nine_pipe_context_clear(This);
767    nine_state_clear(&This->state, TRUE);
768
769    NineDevice9_SetDefaultState(This, TRUE);
770    NineDevice9_SetRenderTarget(
771        This, 0, (IDirect3DSurface9 *)This->swapchains[0]->buffers[0]);
772    /* XXX: better use GetBackBuffer here ? */
773
774    return hr;
775}
776
777HRESULT WINAPI
778NineDevice9_Present( struct NineDevice9 *This,
779                     const RECT *pSourceRect,
780                     const RECT *pDestRect,
781                     HWND hDestWindowOverride,
782                     const RGNDATA *pDirtyRegion )
783{
784    unsigned i;
785    HRESULT hr;
786
787    DBG("This=%p pSourceRect=%p pDestRect=%p hDestWindowOverride=%p pDirtyRegion=%p\n",
788        This, pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion);
789
790    /* XXX is this right? */
791    for (i = 0; i < This->nswapchains; ++i) {
792        hr = NineSwapChain9_Present(This->swapchains[i], pSourceRect, pDestRect,
793                                    hDestWindowOverride, pDirtyRegion, 0);
794        if (FAILED(hr)) { return hr; }
795    }
796
797    return D3D_OK;
798}
799
800HRESULT WINAPI
801NineDevice9_GetBackBuffer( struct NineDevice9 *This,
802                           UINT iSwapChain,
803                           UINT iBackBuffer,
804                           D3DBACKBUFFER_TYPE Type,
805                           IDirect3DSurface9 **ppBackBuffer )
806{
807    user_assert(ppBackBuffer != NULL, D3DERR_INVALIDCALL);
808    user_assert(iSwapChain < This->nswapchains, D3DERR_INVALIDCALL);
809
810    return NineSwapChain9_GetBackBuffer(This->swapchains[iSwapChain],
811                                        iBackBuffer, Type, ppBackBuffer);
812}
813
814HRESULT WINAPI
815NineDevice9_GetRasterStatus( struct NineDevice9 *This,
816                             UINT iSwapChain,
817                             D3DRASTER_STATUS *pRasterStatus )
818{
819    user_assert(pRasterStatus != NULL, D3DERR_INVALIDCALL);
820    user_assert(iSwapChain < This->nswapchains, D3DERR_INVALIDCALL);
821
822    return NineSwapChain9_GetRasterStatus(This->swapchains[iSwapChain],
823                                          pRasterStatus);
824}
825
826HRESULT WINAPI
827NineDevice9_SetDialogBoxMode( struct NineDevice9 *This,
828                              BOOL bEnableDialogs )
829{
830    STUB(D3DERR_INVALIDCALL);
831}
832
833void WINAPI
834NineDevice9_SetGammaRamp( struct NineDevice9 *This,
835                          UINT iSwapChain,
836                          DWORD Flags,
837                          const D3DGAMMARAMP *pRamp )
838{
839    DBG("This=%p iSwapChain=%u Flags=%x pRamp=%p\n", This,
840        iSwapChain, Flags, pRamp);
841
842    user_warn(iSwapChain >= This->nswapchains);
843    user_warn(!pRamp);
844
845    if (pRamp && (iSwapChain < This->nswapchains)) {
846        struct NineSwapChain9 *swap = This->swapchains[iSwapChain];
847        swap->gamma = *pRamp;
848        ID3DPresent_SetGammaRamp(swap->present, pRamp, swap->params.hDeviceWindow);
849    }
850}
851
852void WINAPI
853NineDevice9_GetGammaRamp( struct NineDevice9 *This,
854                          UINT iSwapChain,
855                          D3DGAMMARAMP *pRamp )
856{
857    DBG("This=%p iSwapChain=%u pRamp=%p\n", This, iSwapChain, pRamp);
858
859    user_warn(iSwapChain >= This->nswapchains);
860    user_warn(!pRamp);
861
862    if (pRamp && (iSwapChain < This->nswapchains))
863        *pRamp = This->swapchains[iSwapChain]->gamma;
864}
865
866HRESULT WINAPI
867NineDevice9_CreateTexture( struct NineDevice9 *This,
868                           UINT Width,
869                           UINT Height,
870                           UINT Levels,
871                           DWORD Usage,
872                           D3DFORMAT Format,
873                           D3DPOOL Pool,
874                           IDirect3DTexture9 **ppTexture,
875                           HANDLE *pSharedHandle )
876{
877    struct NineTexture9 *tex;
878    HRESULT hr;
879
880    DBG("This=%p Width=%u Height=%u Levels=%u Usage=%s Format=%s Pool=%s "
881        "ppOut=%p pSharedHandle=%p\n", This, Width, Height, Levels,
882        nine_D3DUSAGE_to_str(Usage), d3dformat_to_string(Format),
883        nine_D3DPOOL_to_str(Pool), ppTexture, pSharedHandle);
884
885    Usage &= D3DUSAGE_AUTOGENMIPMAP | D3DUSAGE_DEPTHSTENCIL | D3DUSAGE_DMAP |
886             D3DUSAGE_DYNAMIC | D3DUSAGE_NONSECURE | D3DUSAGE_RENDERTARGET |
887             D3DUSAGE_SOFTWAREPROCESSING | D3DUSAGE_TEXTAPI;
888
889    *ppTexture = NULL;
890    user_assert(Width && Height, D3DERR_INVALIDCALL);
891    user_assert(!pSharedHandle || This->ex, D3DERR_INVALIDCALL);
892    /* When is used shared handle, Pool must be
893     * SYSTEMMEM with Levels 1 or DEFAULT with any Levels */
894    user_assert(!pSharedHandle || Pool != D3DPOOL_SYSTEMMEM || Levels == 1,
895                D3DERR_INVALIDCALL);
896    user_assert(!pSharedHandle || Pool == D3DPOOL_SYSTEMMEM || Pool == D3DPOOL_DEFAULT,
897                D3DERR_INVALIDCALL);
898    user_assert((Usage != D3DUSAGE_AUTOGENMIPMAP || Levels <= 1), D3DERR_INVALIDCALL);
899
900    hr = NineTexture9_new(This, Width, Height, Levels, Usage, Format, Pool,
901                          &tex, pSharedHandle);
902    if (SUCCEEDED(hr))
903        *ppTexture = (IDirect3DTexture9 *)tex;
904
905    return hr;
906}
907
908HRESULT WINAPI
909NineDevice9_CreateVolumeTexture( struct NineDevice9 *This,
910                                 UINT Width,
911                                 UINT Height,
912                                 UINT Depth,
913                                 UINT Levels,
914                                 DWORD Usage,
915                                 D3DFORMAT Format,
916                                 D3DPOOL Pool,
917                                 IDirect3DVolumeTexture9 **ppVolumeTexture,
918                                 HANDLE *pSharedHandle )
919{
920    struct NineVolumeTexture9 *tex;
921    HRESULT hr;
922
923    DBG("This=%p Width=%u Height=%u Depth=%u Levels=%u Usage=%s Format=%s Pool=%s "
924        "ppOut=%p pSharedHandle=%p\n", This, Width, Height, Depth, Levels,
925        nine_D3DUSAGE_to_str(Usage), d3dformat_to_string(Format),
926        nine_D3DPOOL_to_str(Pool), ppVolumeTexture, pSharedHandle);
927
928    Usage &= D3DUSAGE_DYNAMIC | D3DUSAGE_NONSECURE |
929             D3DUSAGE_SOFTWAREPROCESSING;
930
931    *ppVolumeTexture = NULL;
932    user_assert(Width && Height && Depth, D3DERR_INVALIDCALL);
933    user_assert(!pSharedHandle || Pool == D3DPOOL_DEFAULT, D3DERR_INVALIDCALL);
934
935    hr = NineVolumeTexture9_new(This, Width, Height, Depth, Levels,
936                                Usage, Format, Pool, &tex, pSharedHandle);
937    if (SUCCEEDED(hr))
938        *ppVolumeTexture = (IDirect3DVolumeTexture9 *)tex;
939
940    return hr;
941}
942
943HRESULT WINAPI
944NineDevice9_CreateCubeTexture( struct NineDevice9 *This,
945                               UINT EdgeLength,
946                               UINT Levels,
947                               DWORD Usage,
948                               D3DFORMAT Format,
949                               D3DPOOL Pool,
950                               IDirect3DCubeTexture9 **ppCubeTexture,
951                               HANDLE *pSharedHandle )
952{
953    struct NineCubeTexture9 *tex;
954    HRESULT hr;
955
956    DBG("This=%p EdgeLength=%u Levels=%u Usage=%s Format=%s Pool=%s ppOut=%p "
957        "pSharedHandle=%p\n", This, EdgeLength, Levels,
958        nine_D3DUSAGE_to_str(Usage), d3dformat_to_string(Format),
959        nine_D3DPOOL_to_str(Pool), ppCubeTexture, pSharedHandle);
960
961    Usage &= D3DUSAGE_AUTOGENMIPMAP | D3DUSAGE_DEPTHSTENCIL | D3DUSAGE_DYNAMIC |
962             D3DUSAGE_NONSECURE | D3DUSAGE_RENDERTARGET |
963             D3DUSAGE_SOFTWAREPROCESSING;
964
965    *ppCubeTexture = NULL;
966    user_assert(EdgeLength, D3DERR_INVALIDCALL);
967    user_assert(!pSharedHandle || Pool == D3DPOOL_DEFAULT, D3DERR_INVALIDCALL);
968
969    hr = NineCubeTexture9_new(This, EdgeLength, Levels, Usage, Format, Pool,
970                              &tex, pSharedHandle);
971    if (SUCCEEDED(hr))
972        *ppCubeTexture = (IDirect3DCubeTexture9 *)tex;
973
974    return hr;
975}
976
977HRESULT WINAPI
978NineDevice9_CreateVertexBuffer( struct NineDevice9 *This,
979                                UINT Length,
980                                DWORD Usage,
981                                DWORD FVF,
982                                D3DPOOL Pool,
983                                IDirect3DVertexBuffer9 **ppVertexBuffer,
984                                HANDLE *pSharedHandle )
985{
986    struct NineVertexBuffer9 *buf;
987    HRESULT hr;
988    D3DVERTEXBUFFER_DESC desc;
989
990    DBG("This=%p Length=%u Usage=%x FVF=%x Pool=%u ppOut=%p pSharedHandle=%p\n",
991        This, Length, Usage, FVF, Pool, ppVertexBuffer, pSharedHandle);
992
993    user_assert(!pSharedHandle || Pool == D3DPOOL_DEFAULT, D3DERR_NOTAVAILABLE);
994
995    desc.Format = D3DFMT_VERTEXDATA;
996    desc.Type = D3DRTYPE_VERTEXBUFFER;
997    desc.Usage = Usage &
998        (D3DUSAGE_DONOTCLIP | D3DUSAGE_DYNAMIC | D3DUSAGE_NONSECURE |
999         D3DUSAGE_NPATCHES | D3DUSAGE_POINTS | D3DUSAGE_RTPATCHES |
1000         D3DUSAGE_SOFTWAREPROCESSING | D3DUSAGE_TEXTAPI |
1001         D3DUSAGE_WRITEONLY);
1002    desc.Pool = Pool;
1003    desc.Size = Length;
1004    desc.FVF = FVF;
1005
1006    user_assert(!pSharedHandle || Pool == D3DPOOL_DEFAULT, D3DERR_INVALIDCALL);
1007    user_assert(desc.Usage == Usage, D3DERR_INVALIDCALL);
1008
1009    hr = NineVertexBuffer9_new(This, &desc, &buf);
1010    if (SUCCEEDED(hr))
1011        *ppVertexBuffer = (IDirect3DVertexBuffer9 *)buf;
1012    return hr;
1013}
1014
1015HRESULT WINAPI
1016NineDevice9_CreateIndexBuffer( struct NineDevice9 *This,
1017                               UINT Length,
1018                               DWORD Usage,
1019                               D3DFORMAT Format,
1020                               D3DPOOL Pool,
1021                               IDirect3DIndexBuffer9 **ppIndexBuffer,
1022                               HANDLE *pSharedHandle )
1023{
1024    struct NineIndexBuffer9 *buf;
1025    HRESULT hr;
1026    D3DINDEXBUFFER_DESC desc;
1027
1028    DBG("This=%p Length=%u Usage=%x Format=%s Pool=%u ppOut=%p "
1029        "pSharedHandle=%p\n", This, Length, Usage,
1030        d3dformat_to_string(Format), Pool, ppIndexBuffer, pSharedHandle);
1031
1032    user_assert(!pSharedHandle || Pool == D3DPOOL_DEFAULT, D3DERR_NOTAVAILABLE);
1033
1034    desc.Format = Format;
1035    desc.Type = D3DRTYPE_INDEXBUFFER;
1036    desc.Usage = Usage &
1037        (D3DUSAGE_DONOTCLIP | D3DUSAGE_DYNAMIC | D3DUSAGE_NONSECURE |
1038         D3DUSAGE_NPATCHES | D3DUSAGE_POINTS | D3DUSAGE_RTPATCHES |
1039         D3DUSAGE_SOFTWAREPROCESSING | D3DUSAGE_WRITEONLY);
1040    desc.Pool = Pool;
1041    desc.Size = Length;
1042
1043    user_assert(!pSharedHandle || Pool == D3DPOOL_DEFAULT, D3DERR_INVALIDCALL);
1044    user_assert(desc.Usage == Usage, D3DERR_INVALIDCALL);
1045
1046    hr = NineIndexBuffer9_new(This, &desc, &buf);
1047    if (SUCCEEDED(hr))
1048        *ppIndexBuffer = (IDirect3DIndexBuffer9 *)buf;
1049    return hr;
1050}
1051
1052static HRESULT
1053create_zs_or_rt_surface(struct NineDevice9 *This,
1054                        unsigned type, /* 0 = RT, 1 = ZS, 2 = plain */
1055                        D3DPOOL Pool,
1056                        UINT Width, UINT Height,
1057                        D3DFORMAT Format,
1058                        D3DMULTISAMPLE_TYPE MultiSample,
1059                        DWORD MultisampleQuality,
1060                        BOOL Discard_or_Lockable,
1061                        IDirect3DSurface9 **ppSurface,
1062                        HANDLE *pSharedHandle)
1063{
1064    struct NineSurface9 *surface;
1065    struct pipe_screen *screen = This->screen;
1066    struct pipe_resource *resource = NULL;
1067    HRESULT hr;
1068    D3DSURFACE_DESC desc;
1069    struct pipe_resource templ;
1070
1071    DBG("This=%p type=%u Pool=%s Width=%u Height=%u Format=%s MS=%u Quality=%u "
1072        "Discard_or_Lockable=%i ppSurface=%p pSharedHandle=%p\n",
1073        This, type, nine_D3DPOOL_to_str(Pool), Width, Height,
1074        d3dformat_to_string(Format), MultiSample, MultisampleQuality,
1075        Discard_or_Lockable, ppSurface, pSharedHandle);
1076
1077    if (pSharedHandle)
1078      DBG("FIXME Used shared handle! This option isn't probably handled correctly!\n");
1079
1080    user_assert(Width && Height, D3DERR_INVALIDCALL);
1081    user_assert(Pool != D3DPOOL_MANAGED, D3DERR_INVALIDCALL);
1082
1083    templ.target = PIPE_TEXTURE_2D;
1084    templ.width0 = Width;
1085    templ.height0 = Height;
1086    templ.depth0 = 1;
1087    templ.array_size = 1;
1088    templ.last_level = 0;
1089    templ.nr_samples = (unsigned)MultiSample;
1090    templ.usage = PIPE_USAGE_DEFAULT;
1091    templ.flags = 0;
1092    templ.bind = PIPE_BIND_SAMPLER_VIEW; /* StretchRect */
1093    switch (type) {
1094    case 0: templ.bind |= PIPE_BIND_RENDER_TARGET; break;
1095    case 1: templ.bind = d3d9_get_pipe_depth_format_bindings(Format); break;
1096    default:
1097        assert(type == 2);
1098        break;
1099    }
1100    templ.format = d3d9_to_pipe_format_checked(screen, Format, templ.target,
1101                                               templ.nr_samples, templ.bind,
1102                                               FALSE);
1103
1104    desc.Format = Format;
1105    desc.Type = D3DRTYPE_SURFACE;
1106    desc.Usage = 0;
1107    desc.Pool = Pool;
1108    desc.MultiSampleType = MultiSample;
1109    desc.MultiSampleQuality = MultisampleQuality;
1110    desc.Width = Width;
1111    desc.Height = Height;
1112    switch (type) {
1113    case 0: desc.Usage = D3DUSAGE_RENDERTARGET; break;
1114    case 1: desc.Usage = D3DUSAGE_DEPTHSTENCIL; break;
1115    default: break;
1116    }
1117
1118    if (compressed_format(Format)) {
1119        const unsigned w = util_format_get_blockwidth(templ.format);
1120        const unsigned h = util_format_get_blockheight(templ.format);
1121
1122        user_assert(!(Width % w) && !(Height % h), D3DERR_INVALIDCALL);
1123    }
1124
1125    if (Pool == D3DPOOL_DEFAULT && Format != D3DFMT_NULL) {
1126        /* resource_create doesn't return an error code, so check format here */
1127        user_assert(templ.format != PIPE_FORMAT_NONE, D3DERR_INVALIDCALL);
1128        resource = screen->resource_create(screen, &templ);
1129        user_assert(resource, D3DERR_OUTOFVIDEOMEMORY);
1130        if (Discard_or_Lockable && (desc.Usage & D3DUSAGE_RENDERTARGET))
1131            resource->flags |= NINE_RESOURCE_FLAG_LOCKABLE;
1132    } else {
1133        resource = NULL;
1134    }
1135    hr = NineSurface9_new(This, NULL, resource, NULL, 0, 0, 0, &desc, &surface);
1136    pipe_resource_reference(&resource, NULL);
1137
1138    if (SUCCEEDED(hr))
1139        *ppSurface = (IDirect3DSurface9 *)surface;
1140    return hr;
1141}
1142
1143HRESULT WINAPI
1144NineDevice9_CreateRenderTarget( struct NineDevice9 *This,
1145                                UINT Width,
1146                                UINT Height,
1147                                D3DFORMAT Format,
1148                                D3DMULTISAMPLE_TYPE MultiSample,
1149                                DWORD MultisampleQuality,
1150                                BOOL Lockable,
1151                                IDirect3DSurface9 **ppSurface,
1152                                HANDLE *pSharedHandle )
1153{
1154    *ppSurface = NULL;
1155    return create_zs_or_rt_surface(This, 0, D3DPOOL_DEFAULT,
1156                                   Width, Height, Format,
1157                                   MultiSample, MultisampleQuality,
1158                                   Lockable, ppSurface, pSharedHandle);
1159}
1160
1161HRESULT WINAPI
1162NineDevice9_CreateDepthStencilSurface( struct NineDevice9 *This,
1163                                       UINT Width,
1164                                       UINT Height,
1165                                       D3DFORMAT Format,
1166                                       D3DMULTISAMPLE_TYPE MultiSample,
1167                                       DWORD MultisampleQuality,
1168                                       BOOL Discard,
1169                                       IDirect3DSurface9 **ppSurface,
1170                                       HANDLE *pSharedHandle )
1171{
1172    *ppSurface = NULL;
1173    if (!depth_stencil_format(Format))
1174        return D3DERR_NOTAVAILABLE;
1175    return create_zs_or_rt_surface(This, 1, D3DPOOL_DEFAULT,
1176                                   Width, Height, Format,
1177                                   MultiSample, MultisampleQuality,
1178                                   Discard, ppSurface, pSharedHandle);
1179}
1180
1181HRESULT WINAPI
1182NineDevice9_UpdateSurface( struct NineDevice9 *This,
1183                           IDirect3DSurface9 *pSourceSurface,
1184                           const RECT *pSourceRect,
1185                           IDirect3DSurface9 *pDestinationSurface,
1186                           const POINT *pDestPoint )
1187{
1188    struct NineSurface9 *dst = NineSurface9(pDestinationSurface);
1189    struct NineSurface9 *src = NineSurface9(pSourceSurface);
1190    int copy_width, copy_height;
1191    RECT destRect;
1192
1193    DBG("This=%p pSourceSurface=%p pDestinationSurface=%p "
1194        "pSourceRect=%p pDestPoint=%p\n", This,
1195        pSourceSurface, pDestinationSurface, pSourceRect, pDestPoint);
1196    if (pSourceRect)
1197        DBG("pSourceRect = (%u,%u)-(%u,%u)\n",
1198            pSourceRect->left, pSourceRect->top,
1199            pSourceRect->right, pSourceRect->bottom);
1200    if (pDestPoint)
1201        DBG("pDestPoint = (%u,%u)\n", pDestPoint->x, pDestPoint->y);
1202
1203    user_assert(dst && src, D3DERR_INVALIDCALL);
1204
1205    user_assert(dst->base.pool == D3DPOOL_DEFAULT, D3DERR_INVALIDCALL);
1206    user_assert(src->base.pool == D3DPOOL_SYSTEMMEM, D3DERR_INVALIDCALL);
1207
1208    user_assert(dst->desc.MultiSampleType == D3DMULTISAMPLE_NONE, D3DERR_INVALIDCALL);
1209    user_assert(src->desc.MultiSampleType == D3DMULTISAMPLE_NONE, D3DERR_INVALIDCALL);
1210
1211    user_assert(!src->lock_count, D3DERR_INVALIDCALL);
1212    user_assert(!dst->lock_count, D3DERR_INVALIDCALL);
1213
1214    user_assert(dst->desc.Format == src->desc.Format, D3DERR_INVALIDCALL);
1215    user_assert(!depth_stencil_format(dst->desc.Format), D3DERR_INVALIDCALL);
1216
1217    if (pSourceRect) {
1218        copy_width = pSourceRect->right - pSourceRect->left;
1219        copy_height = pSourceRect->bottom - pSourceRect->top;
1220
1221        user_assert(pSourceRect->left >= 0 &&
1222                    copy_width > 0 &&
1223                    pSourceRect->right <= src->desc.Width &&
1224                    pSourceRect->top >= 0 &&
1225                    copy_height > 0 &&
1226                    pSourceRect->bottom <= src->desc.Height,
1227                    D3DERR_INVALIDCALL);
1228    } else {
1229        copy_width = src->desc.Width;
1230        copy_height = src->desc.Height;
1231    }
1232
1233    destRect.right = copy_width;
1234    destRect.bottom = copy_height;
1235
1236    if (pDestPoint) {
1237        user_assert(pDestPoint->x >= 0 && pDestPoint->y >= 0,
1238                    D3DERR_INVALIDCALL);
1239        destRect.right += pDestPoint->x;
1240        destRect.bottom += pDestPoint->y;
1241    }
1242
1243    user_assert(destRect.right <= dst->desc.Width &&
1244                destRect.bottom <= dst->desc.Height,
1245                D3DERR_INVALIDCALL);
1246
1247    if (compressed_format(dst->desc.Format)) {
1248        const unsigned w = util_format_get_blockwidth(dst->base.info.format);
1249        const unsigned h = util_format_get_blockheight(dst->base.info.format);
1250
1251        if (pDestPoint) {
1252            user_assert(!(pDestPoint->x % w) && !(pDestPoint->y % h),
1253                        D3DERR_INVALIDCALL);
1254        }
1255
1256        if (pSourceRect) {
1257            user_assert(!(pSourceRect->left % w) && !(pSourceRect->top % h),
1258                        D3DERR_INVALIDCALL);
1259        }
1260        if (!(copy_width == src->desc.Width &&
1261              copy_width == dst->desc.Width &&
1262              copy_height == src->desc.Height &&
1263              copy_height == dst->desc.Height)) {
1264            user_assert(!(copy_width  % w) && !(copy_height % h),
1265                        D3DERR_INVALIDCALL);
1266        }
1267    }
1268
1269    NineSurface9_CopyMemToDefault(dst, src, pDestPoint, pSourceRect);
1270
1271    return D3D_OK;
1272}
1273
1274HRESULT WINAPI
1275NineDevice9_UpdateTexture( struct NineDevice9 *This,
1276                           IDirect3DBaseTexture9 *pSourceTexture,
1277                           IDirect3DBaseTexture9 *pDestinationTexture )
1278{
1279    struct NineBaseTexture9 *dstb = NineBaseTexture9(pDestinationTexture);
1280    struct NineBaseTexture9 *srcb = NineBaseTexture9(pSourceTexture);
1281    unsigned l, m;
1282    unsigned last_level = dstb->base.info.last_level;
1283    RECT rect;
1284
1285    DBG("This=%p pSourceTexture=%p pDestinationTexture=%p\n", This,
1286        pSourceTexture, pDestinationTexture);
1287
1288    user_assert(pSourceTexture != pDestinationTexture, D3DERR_INVALIDCALL);
1289
1290    user_assert(dstb->base.pool == D3DPOOL_DEFAULT, D3DERR_INVALIDCALL);
1291    user_assert(srcb->base.pool == D3DPOOL_SYSTEMMEM, D3DERR_INVALIDCALL);
1292
1293    if (dstb->base.usage & D3DUSAGE_AUTOGENMIPMAP) {
1294        /* Only the first level is updated, the others regenerated. */
1295        last_level = 0;
1296        /* if the source has D3DUSAGE_AUTOGENMIPMAP, we have to ignore
1297         * the sublevels, thus level 0 has to match */
1298        user_assert(!(srcb->base.usage & D3DUSAGE_AUTOGENMIPMAP) ||
1299                    (srcb->base.info.width0 == dstb->base.info.width0 &&
1300                     srcb->base.info.height0 == dstb->base.info.height0 &&
1301                     srcb->base.info.depth0 == dstb->base.info.depth0),
1302                    D3DERR_INVALIDCALL);
1303    } else {
1304        user_assert(!(srcb->base.usage & D3DUSAGE_AUTOGENMIPMAP), D3DERR_INVALIDCALL);
1305    }
1306
1307    user_assert(dstb->base.type == srcb->base.type, D3DERR_INVALIDCALL);
1308
1309    /* Find src level that matches dst level 0: */
1310    user_assert(srcb->base.info.width0 >= dstb->base.info.width0 &&
1311                srcb->base.info.height0 >= dstb->base.info.height0 &&
1312                srcb->base.info.depth0 >= dstb->base.info.depth0,
1313                D3DERR_INVALIDCALL);
1314    for (m = 0; m <= srcb->base.info.last_level; ++m) {
1315        unsigned w = u_minify(srcb->base.info.width0, m);
1316        unsigned h = u_minify(srcb->base.info.height0, m);
1317        unsigned d = u_minify(srcb->base.info.depth0, m);
1318
1319        if (w == dstb->base.info.width0 &&
1320            h == dstb->base.info.height0 &&
1321            d == dstb->base.info.depth0)
1322            break;
1323    }
1324    user_assert(m <= srcb->base.info.last_level, D3DERR_INVALIDCALL);
1325
1326    last_level = MIN2(last_level, srcb->base.info.last_level - m);
1327
1328    if (dstb->base.type == D3DRTYPE_TEXTURE) {
1329        struct NineTexture9 *dst = NineTexture9(dstb);
1330        struct NineTexture9 *src = NineTexture9(srcb);
1331
1332        if (src->dirty_rect.width == 0)
1333            return D3D_OK;
1334
1335        pipe_box_to_rect(&rect, &src->dirty_rect);
1336        for (l = 0; l < m; ++l)
1337            rect_minify_inclusive(&rect);
1338
1339        for (l = 0; l <= last_level; ++l, ++m) {
1340            fit_rect_format_inclusive(dst->base.base.info.format,
1341                                      &rect,
1342                                      dst->surfaces[l]->desc.Width,
1343                                      dst->surfaces[l]->desc.Height);
1344            NineSurface9_CopyMemToDefault(dst->surfaces[l],
1345                                          src->surfaces[m],
1346                                          (POINT *)&rect,
1347                                          &rect);
1348            rect_minify_inclusive(&rect);
1349        }
1350        u_box_origin_2d(0, 0, &src->dirty_rect);
1351    } else
1352    if (dstb->base.type == D3DRTYPE_CUBETEXTURE) {
1353        struct NineCubeTexture9 *dst = NineCubeTexture9(dstb);
1354        struct NineCubeTexture9 *src = NineCubeTexture9(srcb);
1355        unsigned z;
1356
1357        /* GPUs usually have them stored as arrays of mip-mapped 2D textures. */
1358        for (z = 0; z < 6; ++z) {
1359            if (src->dirty_rect[z].width == 0)
1360                continue;
1361
1362            pipe_box_to_rect(&rect, &src->dirty_rect[z]);
1363            for (l = 0; l < m; ++l)
1364                rect_minify_inclusive(&rect);
1365
1366            for (l = 0; l <= last_level; ++l, ++m) {
1367                fit_rect_format_inclusive(dst->base.base.info.format,
1368                                          &rect,
1369                                          dst->surfaces[l * 6 + z]->desc.Width,
1370                                          dst->surfaces[l * 6 + z]->desc.Height);
1371                NineSurface9_CopyMemToDefault(dst->surfaces[l * 6 + z],
1372                                              src->surfaces[m * 6 + z],
1373                                              (POINT *)&rect,
1374                                              &rect);
1375                rect_minify_inclusive(&rect);
1376            }
1377            u_box_origin_2d(0, 0, &src->dirty_rect[z]);
1378            m -= l;
1379        }
1380    } else
1381    if (dstb->base.type == D3DRTYPE_VOLUMETEXTURE) {
1382        struct NineVolumeTexture9 *dst = NineVolumeTexture9(dstb);
1383        struct NineVolumeTexture9 *src = NineVolumeTexture9(srcb);
1384
1385        if (src->dirty_box.width == 0)
1386            return D3D_OK;
1387        for (l = 0; l <= last_level; ++l, ++m)
1388            NineVolume9_CopyMemToDefault(dst->volumes[l],
1389                                         src->volumes[m], 0, 0, 0, NULL);
1390        u_box_3d(0, 0, 0, 0, 0, 0, &src->dirty_box);
1391    } else{
1392        assert(!"invalid texture type");
1393    }
1394
1395    if (dstb->base.usage & D3DUSAGE_AUTOGENMIPMAP) {
1396        dstb->dirty_mip = TRUE;
1397        NineBaseTexture9_GenerateMipSubLevels(dstb);
1398    }
1399
1400    return D3D_OK;
1401}
1402
1403HRESULT WINAPI
1404NineDevice9_GetRenderTargetData( struct NineDevice9 *This,
1405                                 IDirect3DSurface9 *pRenderTarget,
1406                                 IDirect3DSurface9 *pDestSurface )
1407{
1408    struct NineSurface9 *dst = NineSurface9(pDestSurface);
1409    struct NineSurface9 *src = NineSurface9(pRenderTarget);
1410
1411    DBG("This=%p pRenderTarget=%p pDestSurface=%p\n",
1412        This, pRenderTarget, pDestSurface);
1413
1414    user_assert(dst->desc.Pool == D3DPOOL_SYSTEMMEM, D3DERR_INVALIDCALL);
1415    user_assert(src->desc.Pool == D3DPOOL_DEFAULT, D3DERR_INVALIDCALL);
1416
1417    user_assert(dst->desc.MultiSampleType < 2, D3DERR_INVALIDCALL);
1418    user_assert(src->desc.MultiSampleType < 2, D3DERR_INVALIDCALL);
1419
1420    user_assert(src->desc.Width == dst->desc.Width, D3DERR_INVALIDCALL);
1421    user_assert(src->desc.Height == dst->desc.Height, D3DERR_INVALIDCALL);
1422
1423    NineSurface9_CopyDefaultToMem(dst, src);
1424
1425    return D3D_OK;
1426}
1427
1428HRESULT WINAPI
1429NineDevice9_GetFrontBufferData( struct NineDevice9 *This,
1430                                UINT iSwapChain,
1431                                IDirect3DSurface9 *pDestSurface )
1432{
1433    DBG("This=%p iSwapChain=%u pDestSurface=%p\n", This,
1434        iSwapChain, pDestSurface);
1435
1436    user_assert(pDestSurface != NULL, D3DERR_INVALIDCALL);
1437    user_assert(iSwapChain < This->nswapchains, D3DERR_INVALIDCALL);
1438
1439    return NineSwapChain9_GetFrontBufferData(This->swapchains[iSwapChain],
1440                                             pDestSurface);
1441}
1442
1443HRESULT WINAPI
1444NineDevice9_StretchRect( struct NineDevice9 *This,
1445                         IDirect3DSurface9 *pSourceSurface,
1446                         const RECT *pSourceRect,
1447                         IDirect3DSurface9 *pDestSurface,
1448                         const RECT *pDestRect,
1449                         D3DTEXTUREFILTERTYPE Filter )
1450{
1451    struct pipe_screen *screen = This->screen;
1452    struct pipe_context *pipe = This->pipe;
1453    struct NineSurface9 *dst = NineSurface9(pDestSurface);
1454    struct NineSurface9 *src = NineSurface9(pSourceSurface);
1455    struct pipe_resource *dst_res = NineSurface9_GetResource(dst);
1456    struct pipe_resource *src_res = NineSurface9_GetResource(src);
1457    const boolean zs = util_format_is_depth_or_stencil(dst_res->format);
1458    struct pipe_blit_info blit;
1459    boolean scaled, clamped, ms, flip_x = FALSE, flip_y = FALSE;
1460
1461    DBG("This=%p pSourceSurface=%p pSourceRect=%p pDestSurface=%p "
1462        "pDestRect=%p Filter=%u\n",
1463        This, pSourceSurface, pSourceRect, pDestSurface, pDestRect, Filter);
1464    if (pSourceRect)
1465        DBG("pSourceRect=(%u,%u)-(%u,%u)\n",
1466            pSourceRect->left, pSourceRect->top,
1467            pSourceRect->right, pSourceRect->bottom);
1468    if (pDestRect)
1469        DBG("pDestRect=(%u,%u)-(%u,%u)\n", pDestRect->left, pDestRect->top,
1470            pDestRect->right, pDestRect->bottom);
1471
1472    user_assert(!zs || !This->in_scene, D3DERR_INVALIDCALL);
1473    user_assert(!zs || !pSourceRect ||
1474                (pSourceRect->left == 0 &&
1475                 pSourceRect->top == 0 &&
1476                 pSourceRect->right == src->desc.Width &&
1477                 pSourceRect->bottom == src->desc.Height), D3DERR_INVALIDCALL);
1478    user_assert(!zs || !pDestRect ||
1479                (pDestRect->left == 0 &&
1480                 pDestRect->top == 0 &&
1481                 pDestRect->right == dst->desc.Width &&
1482                 pDestRect->bottom == dst->desc.Height), D3DERR_INVALIDCALL);
1483    user_assert(!zs ||
1484                (dst->desc.Width == src->desc.Width &&
1485                 dst->desc.Height == src->desc.Height), D3DERR_INVALIDCALL);
1486    user_assert(zs || !util_format_is_depth_or_stencil(src_res->format),
1487                D3DERR_INVALIDCALL);
1488    user_assert(!zs || dst->desc.Format == src->desc.Format,
1489                D3DERR_INVALIDCALL);
1490    user_assert(screen->is_format_supported(screen, src_res->format,
1491                                            src_res->target,
1492                                            src_res->nr_samples,
1493                                            PIPE_BIND_SAMPLER_VIEW),
1494                D3DERR_INVALIDCALL);
1495    user_assert(dst->base.pool == D3DPOOL_DEFAULT &&
1496                src->base.pool == D3DPOOL_DEFAULT, D3DERR_INVALIDCALL);
1497
1498    /* We might want to permit these, but wine thinks we shouldn't. */
1499    user_assert(!pDestRect ||
1500                (pDestRect->left <= pDestRect->right &&
1501                 pDestRect->top <= pDestRect->bottom), D3DERR_INVALIDCALL);
1502    user_assert(!pSourceRect ||
1503                (pSourceRect->left <= pSourceRect->right &&
1504                 pSourceRect->top <= pSourceRect->bottom), D3DERR_INVALIDCALL);
1505
1506    memset(&blit, 0, sizeof(blit));
1507    blit.dst.resource = dst_res;
1508    blit.dst.level = dst->level;
1509    blit.dst.box.z = dst->layer;
1510    blit.dst.box.depth = 1;
1511    blit.dst.format = dst_res->format;
1512    if (pDestRect) {
1513        flip_x = pDestRect->left > pDestRect->right;
1514        if (flip_x) {
1515            blit.dst.box.x = pDestRect->right;
1516            blit.dst.box.width = pDestRect->left - pDestRect->right;
1517        } else {
1518            blit.dst.box.x = pDestRect->left;
1519            blit.dst.box.width = pDestRect->right - pDestRect->left;
1520        }
1521        flip_y = pDestRect->top > pDestRect->bottom;
1522        if (flip_y) {
1523            blit.dst.box.y = pDestRect->bottom;
1524            blit.dst.box.height = pDestRect->top - pDestRect->bottom;
1525        } else {
1526            blit.dst.box.y = pDestRect->top;
1527            blit.dst.box.height = pDestRect->bottom - pDestRect->top;
1528        }
1529    } else {
1530        blit.dst.box.x = 0;
1531        blit.dst.box.y = 0;
1532        blit.dst.box.width = dst->desc.Width;
1533        blit.dst.box.height = dst->desc.Height;
1534    }
1535    blit.src.resource = src_res;
1536    blit.src.level = src->level;
1537    blit.src.box.z = src->layer;
1538    blit.src.box.depth = 1;
1539    blit.src.format = src_res->format;
1540    if (pSourceRect) {
1541        if (flip_x ^ (pSourceRect->left > pSourceRect->right)) {
1542            blit.src.box.x = pSourceRect->right;
1543            blit.src.box.width = pSourceRect->left - pSourceRect->right;
1544        } else {
1545            blit.src.box.x = pSourceRect->left;
1546            blit.src.box.width = pSourceRect->right - pSourceRect->left;
1547        }
1548        if (flip_y ^ (pSourceRect->top > pSourceRect->bottom)) {
1549            blit.src.box.y = pSourceRect->bottom;
1550            blit.src.box.height = pSourceRect->top - pSourceRect->bottom;
1551        } else {
1552            blit.src.box.y = pSourceRect->top;
1553            blit.src.box.height = pSourceRect->bottom - pSourceRect->top;
1554        }
1555    } else {
1556        blit.src.box.x = flip_x ? src->desc.Width : 0;
1557        blit.src.box.y = flip_y ? src->desc.Height : 0;
1558        blit.src.box.width = flip_x ? -src->desc.Width : src->desc.Width;
1559        blit.src.box.height = flip_y ? -src->desc.Height : src->desc.Height;
1560    }
1561    blit.mask = zs ? PIPE_MASK_ZS : PIPE_MASK_RGBA;
1562    blit.filter = Filter == D3DTEXF_LINEAR ?
1563       PIPE_TEX_FILTER_LINEAR : PIPE_TEX_FILTER_NEAREST;
1564    blit.scissor_enable = FALSE;
1565    blit.alpha_blend = FALSE;
1566
1567    /* If both of a src and dst dimension are negative, flip them. */
1568    if (blit.dst.box.width < 0 && blit.src.box.width < 0) {
1569        blit.dst.box.width = -blit.dst.box.width;
1570        blit.src.box.width = -blit.src.box.width;
1571    }
1572    if (blit.dst.box.height < 0 && blit.src.box.height < 0) {
1573        blit.dst.box.height = -blit.dst.box.height;
1574        blit.src.box.height = -blit.src.box.height;
1575    }
1576    scaled =
1577        blit.dst.box.width != blit.src.box.width ||
1578        blit.dst.box.height != blit.src.box.height;
1579
1580    user_assert(!scaled || dst != src, D3DERR_INVALIDCALL);
1581    user_assert(!scaled ||
1582                !NineSurface9_IsOffscreenPlain(dst), D3DERR_INVALIDCALL);
1583    user_assert(!NineSurface9_IsOffscreenPlain(dst) ||
1584                NineSurface9_IsOffscreenPlain(src), D3DERR_INVALIDCALL);
1585    user_assert(NineSurface9_IsOffscreenPlain(dst) ||
1586                dst->desc.Usage & (D3DUSAGE_RENDERTARGET | D3DUSAGE_DEPTHSTENCIL),
1587                D3DERR_INVALIDCALL);
1588    user_assert(!scaled ||
1589                (!util_format_is_compressed(dst->base.info.format) &&
1590                 !util_format_is_compressed(src->base.info.format)),
1591                D3DERR_INVALIDCALL);
1592
1593    user_warn(src == dst &&
1594              u_box_test_intersection_2d(&blit.src.box, &blit.dst.box));
1595
1596    /* Check for clipping/clamping: */
1597    {
1598        struct pipe_box box;
1599        int xy;
1600
1601        xy = u_box_clip_2d(&box, &blit.dst.box,
1602                           dst->desc.Width, dst->desc.Height);
1603        if (xy < 0)
1604            return D3D_OK;
1605        if (xy == 0)
1606            xy = u_box_clip_2d(&box, &blit.src.box,
1607                               src->desc.Width, src->desc.Height);
1608        clamped = !!xy;
1609    }
1610
1611    ms = (dst->desc.MultiSampleType | 1) != (src->desc.MultiSampleType | 1);
1612
1613    if (clamped || scaled || (blit.dst.format != blit.src.format) || ms) {
1614        DBG("using pipe->blit()\n");
1615        /* TODO: software scaling */
1616        user_assert(screen->is_format_supported(screen, dst_res->format,
1617                                                dst_res->target,
1618                                                dst_res->nr_samples,
1619                                                zs ? PIPE_BIND_DEPTH_STENCIL :
1620                                                PIPE_BIND_RENDER_TARGET),
1621                    D3DERR_INVALIDCALL);
1622
1623        pipe->blit(pipe, &blit);
1624    } else {
1625        assert(blit.dst.box.x >= 0 && blit.dst.box.y >= 0 &&
1626               blit.src.box.x >= 0 && blit.src.box.y >= 0 &&
1627               blit.dst.box.x + blit.dst.box.width <= dst->desc.Width &&
1628               blit.src.box.x + blit.src.box.width <= src->desc.Width &&
1629               blit.dst.box.y + blit.dst.box.height <= dst->desc.Height &&
1630               blit.src.box.y + blit.src.box.height <= src->desc.Height);
1631        /* Or drivers might crash ... */
1632        DBG("Using resource_copy_region.\n");
1633        pipe->resource_copy_region(pipe,
1634            blit.dst.resource, blit.dst.level,
1635            blit.dst.box.x, blit.dst.box.y, blit.dst.box.z,
1636            blit.src.resource, blit.src.level,
1637            &blit.src.box);
1638    }
1639
1640    /* Communicate the container it needs to update sublevels - if apply */
1641    NineSurface9_MarkContainerDirty(dst);
1642
1643    return D3D_OK;
1644}
1645
1646HRESULT WINAPI
1647NineDevice9_ColorFill( struct NineDevice9 *This,
1648                       IDirect3DSurface9 *pSurface,
1649                       const RECT *pRect,
1650                       D3DCOLOR color )
1651{
1652    struct pipe_context *pipe = This->pipe;
1653    struct NineSurface9 *surf = NineSurface9(pSurface);
1654    struct pipe_surface *psurf;
1655    unsigned x, y, w, h;
1656    union pipe_color_union rgba;
1657    boolean fallback;
1658
1659    DBG("This=%p pSurface=%p pRect=%p color=%08x\n", This,
1660        pSurface, pRect, color);
1661    if (pRect)
1662        DBG("pRect=(%u,%u)-(%u,%u)\n", pRect->left, pRect->top,
1663            pRect->right, pRect->bottom);
1664
1665    user_assert(surf->base.pool == D3DPOOL_DEFAULT, D3DERR_INVALIDCALL);
1666
1667    user_assert((surf->base.usage & D3DUSAGE_RENDERTARGET) ||
1668                NineSurface9_IsOffscreenPlain(surf), D3DERR_INVALIDCALL);
1669
1670    if (pRect) {
1671        x = pRect->left;
1672        y = pRect->top;
1673        w = pRect->right - pRect->left;
1674        h = pRect->bottom - pRect->top;
1675    } else{
1676        x = 0;
1677        y = 0;
1678        w = surf->desc.Width;
1679        h = surf->desc.Height;
1680    }
1681    d3dcolor_to_pipe_color_union(&rgba, color);
1682
1683    fallback = !(surf->base.info.bind & PIPE_BIND_RENDER_TARGET);
1684
1685    if (!fallback) {
1686        psurf = NineSurface9_GetSurface(surf, 0);
1687        if (!psurf)
1688            fallback = TRUE;
1689    }
1690
1691    if (!fallback) {
1692        pipe->clear_render_target(pipe, psurf, &rgba, x, y, w, h);
1693    } else {
1694        D3DLOCKED_RECT lock;
1695        union util_color uc;
1696        HRESULT hr;
1697        /* XXX: lock pRect and fix util_fill_rect */
1698        hr = NineSurface9_LockRect(surf, &lock, NULL, 0);
1699        if (FAILED(hr))
1700            return hr;
1701        util_pack_color_ub(color >> 16, color >> 8, color >> 0, color >> 24,
1702                           surf->base.info.format, &uc);
1703        util_fill_rect(lock.pBits, surf->base.info.format,lock.Pitch,
1704                       x, y, w, h, &uc);
1705        NineSurface9_UnlockRect(surf);
1706    }
1707
1708    return D3D_OK;
1709}
1710
1711HRESULT WINAPI
1712NineDevice9_CreateOffscreenPlainSurface( struct NineDevice9 *This,
1713                                         UINT Width,
1714                                         UINT Height,
1715                                         D3DFORMAT Format,
1716                                         D3DPOOL Pool,
1717                                         IDirect3DSurface9 **ppSurface,
1718                                         HANDLE *pSharedHandle )
1719{
1720    HRESULT hr;
1721
1722    DBG("This=%p Width=%u Height=%u Format=%s(0x%x) Pool=%u "
1723        "ppSurface=%p pSharedHandle=%p\n", This,
1724        Width, Height, d3dformat_to_string(Format), Format, Pool,
1725        ppSurface, pSharedHandle);
1726
1727    *ppSurface = NULL;
1728    user_assert(!pSharedHandle || Pool == D3DPOOL_DEFAULT
1729                               || Pool == D3DPOOL_SYSTEMMEM, D3DERR_INVALIDCALL);
1730    user_assert(Pool != D3DPOOL_MANAGED, D3DERR_INVALIDCALL);
1731
1732    /* Can be used with StretchRect and ColorFill. It's also always lockable.
1733     */
1734    hr = create_zs_or_rt_surface(This, 2, Pool, Width, Height,
1735                                 Format,
1736                                 D3DMULTISAMPLE_NONE, 0,
1737                                 TRUE,
1738                                 ppSurface, pSharedHandle);
1739    if (FAILED(hr))
1740        DBG("Failed to create surface.\n");
1741    return hr;
1742}
1743
1744HRESULT WINAPI
1745NineDevice9_SetRenderTarget( struct NineDevice9 *This,
1746                             DWORD RenderTargetIndex,
1747                             IDirect3DSurface9 *pRenderTarget )
1748{
1749    struct NineSurface9 *rt = NineSurface9(pRenderTarget);
1750    const unsigned i = RenderTargetIndex;
1751
1752    DBG("This=%p RenderTargetIndex=%u pRenderTarget=%p\n", This,
1753        RenderTargetIndex, pRenderTarget);
1754
1755    user_assert(i < This->caps.NumSimultaneousRTs, D3DERR_INVALIDCALL);
1756    user_assert(i != 0 || pRenderTarget, D3DERR_INVALIDCALL);
1757    user_assert(!pRenderTarget ||
1758                rt->desc.Usage & D3DUSAGE_RENDERTARGET, D3DERR_INVALIDCALL);
1759
1760    if (i == 0) {
1761        This->state.viewport.X = 0;
1762        This->state.viewport.Y = 0;
1763        This->state.viewport.Width = rt->desc.Width;
1764        This->state.viewport.Height = rt->desc.Height;
1765        This->state.viewport.MinZ = 0.0f;
1766        This->state.viewport.MaxZ = 1.0f;
1767
1768        This->state.scissor.minx = 0;
1769        This->state.scissor.miny = 0;
1770        This->state.scissor.maxx = rt->desc.Width;
1771        This->state.scissor.maxy = rt->desc.Height;
1772
1773        This->state.changed.group |= NINE_STATE_VIEWPORT | NINE_STATE_SCISSOR;
1774    }
1775
1776    if (This->state.rt[i] != NineSurface9(pRenderTarget)) {
1777       nine_bind(&This->state.rt[i], pRenderTarget);
1778       This->state.changed.group |= NINE_STATE_FB;
1779    }
1780    return D3D_OK;
1781}
1782
1783HRESULT WINAPI
1784NineDevice9_GetRenderTarget( struct NineDevice9 *This,
1785                             DWORD RenderTargetIndex,
1786                             IDirect3DSurface9 **ppRenderTarget )
1787{
1788    const unsigned i = RenderTargetIndex;
1789
1790    user_assert(i < This->caps.NumSimultaneousRTs, D3DERR_INVALIDCALL);
1791    user_assert(ppRenderTarget, D3DERR_INVALIDCALL);
1792
1793    *ppRenderTarget = (IDirect3DSurface9 *)This->state.rt[i];
1794    if (!This->state.rt[i])
1795        return D3DERR_NOTFOUND;
1796
1797    NineUnknown_AddRef(NineUnknown(This->state.rt[i]));
1798    return D3D_OK;
1799}
1800
1801HRESULT WINAPI
1802NineDevice9_SetDepthStencilSurface( struct NineDevice9 *This,
1803                                    IDirect3DSurface9 *pNewZStencil )
1804{
1805    DBG("This=%p pNewZStencil=%p\n", This, pNewZStencil);
1806
1807    if (This->state.ds != NineSurface9(pNewZStencil)) {
1808        nine_bind(&This->state.ds, pNewZStencil);
1809        This->state.changed.group |= NINE_STATE_FB;
1810    }
1811    return D3D_OK;
1812}
1813
1814HRESULT WINAPI
1815NineDevice9_GetDepthStencilSurface( struct NineDevice9 *This,
1816                                    IDirect3DSurface9 **ppZStencilSurface )
1817{
1818    user_assert(ppZStencilSurface, D3DERR_INVALIDCALL);
1819
1820    *ppZStencilSurface = (IDirect3DSurface9 *)This->state.ds;
1821    if (!This->state.ds)
1822        return D3DERR_NOTFOUND;
1823
1824    NineUnknown_AddRef(NineUnknown(This->state.ds));
1825    return D3D_OK;
1826}
1827
1828HRESULT WINAPI
1829NineDevice9_BeginScene( struct NineDevice9 *This )
1830{
1831    DBG("This=%p\n", This);
1832    user_assert(!This->in_scene, D3DERR_INVALIDCALL);
1833    This->in_scene = TRUE;
1834    /* Do we want to do anything else here ? */
1835    return D3D_OK;
1836}
1837
1838HRESULT WINAPI
1839NineDevice9_EndScene( struct NineDevice9 *This )
1840{
1841    DBG("This=%p\n", This);
1842    user_assert(This->in_scene, D3DERR_INVALIDCALL);
1843    This->in_scene = FALSE;
1844    return D3D_OK;
1845}
1846
1847HRESULT WINAPI
1848NineDevice9_Clear( struct NineDevice9 *This,
1849                   DWORD Count,
1850                   const D3DRECT *pRects,
1851                   DWORD Flags,
1852                   D3DCOLOR Color,
1853                   float Z,
1854                   DWORD Stencil )
1855{
1856    const int sRGB = This->state.rs[D3DRS_SRGBWRITEENABLE] ? 1 : 0;
1857    struct pipe_surface *cbuf, *zsbuf;
1858    struct pipe_context *pipe = This->pipe;
1859    struct NineSurface9 *zsbuf_surf = This->state.ds;
1860    struct NineSurface9 *rt;
1861    unsigned bufs = 0;
1862    unsigned r, i;
1863    union pipe_color_union rgba;
1864    unsigned rt_mask = 0;
1865    D3DRECT rect;
1866
1867    DBG("This=%p Count=%u pRects=%p Flags=%x Color=%08x Z=%f Stencil=%x\n",
1868        This, Count, pRects, Flags, Color, Z, Stencil);
1869
1870    user_assert(This->state.ds || !(Flags & NINED3DCLEAR_DEPTHSTENCIL),
1871                D3DERR_INVALIDCALL);
1872    user_assert(!(Flags & D3DCLEAR_STENCIL) ||
1873                (zsbuf_surf &&
1874                 util_format_is_depth_and_stencil(zsbuf_surf->base.info.format)),
1875                D3DERR_INVALIDCALL);
1876#ifdef NINE_STRICT
1877    user_assert((Count && pRects) || (!Count && !pRects), D3DERR_INVALIDCALL);
1878#else
1879    user_warn((pRects && !Count) || (!pRects && Count));
1880    if (pRects && !Count)
1881        return D3D_OK;
1882    if (!pRects)
1883        Count = 0;
1884#endif
1885
1886    if (Flags & D3DCLEAR_TARGET) bufs |= PIPE_CLEAR_COLOR;
1887    if (Flags & D3DCLEAR_ZBUFFER) bufs |= PIPE_CLEAR_DEPTH;
1888    if (Flags & D3DCLEAR_STENCIL) bufs |= PIPE_CLEAR_STENCIL;
1889    if (!bufs)
1890        return D3D_OK;
1891    d3dcolor_to_pipe_color_union(&rgba, Color);
1892
1893    nine_update_state_framebuffer(This);
1894
1895    rect.x1 = This->state.viewport.X;
1896    rect.y1 = This->state.viewport.Y;
1897    rect.x2 = This->state.viewport.Width + rect.x1;
1898    rect.y2 = This->state.viewport.Height + rect.y1;
1899
1900    /* Both rectangles apply, which is weird, but that's D3D9. */
1901    if (This->state.rs[D3DRS_SCISSORTESTENABLE]) {
1902        rect.x1 = MAX2(rect.x1, This->state.scissor.minx);
1903        rect.y1 = MAX2(rect.y1, This->state.scissor.miny);
1904        rect.x2 = MIN2(rect.x2, This->state.scissor.maxx);
1905        rect.y2 = MIN2(rect.y2, This->state.scissor.maxy);
1906    }
1907
1908    if (Count) {
1909        /* Maybe apps like to specify a large rect ? */
1910        if (pRects[0].x1 <= rect.x1 && pRects[0].x2 >= rect.x2 &&
1911            pRects[0].y1 <= rect.y1 && pRects[0].y2 >= rect.y2) {
1912            DBG("First rect covers viewport.\n");
1913            Count = 0;
1914            pRects = NULL;
1915        }
1916    }
1917
1918    if (rect.x1 >= This->state.fb.width || rect.y1 >= This->state.fb.height)
1919        return D3D_OK;
1920
1921    for (i = 0; i < This->caps.NumSimultaneousRTs; ++i) {
1922        if (This->state.rt[i] && This->state.rt[i]->desc.Format != D3DFMT_NULL)
1923            rt_mask |= 1 << i;
1924    }
1925
1926    /* fast path, clears everything at once */
1927    if (!Count &&
1928        (!(bufs & PIPE_CLEAR_COLOR) || (rt_mask == This->state.rt_mask)) &&
1929        rect.x1 == 0 && rect.y1 == 0 &&
1930        /* Case we clear only render target. Check clear region vs rt. */
1931        ((!(bufs & (PIPE_CLEAR_DEPTH | PIPE_CLEAR_STENCIL)) &&
1932         rect.x2 >= This->state.fb.width &&
1933         rect.y2 >= This->state.fb.height) ||
1934        /* Case we clear depth buffer (and eventually rt too).
1935         * depth buffer size is always >= rt size. Compare to clear region */
1936        ((bufs & (PIPE_CLEAR_DEPTH | PIPE_CLEAR_STENCIL)) &&
1937         This->state.fb.zsbuf != NULL &&
1938         rect.x2 >= zsbuf_surf->desc.Width &&
1939         rect.y2 >= zsbuf_surf->desc.Height))) {
1940        DBG("Clear fast path\n");
1941        pipe->clear(pipe, bufs, &rgba, Z, Stencil);
1942        return D3D_OK;
1943    }
1944
1945    if (!Count) {
1946        Count = 1;
1947        pRects = &rect;
1948    }
1949
1950    for (i = 0; i < This->caps.NumSimultaneousRTs; ++i) {
1951        rt = This->state.rt[i];
1952        if (!rt || rt->desc.Format == D3DFMT_NULL ||
1953            !(Flags & D3DCLEAR_TARGET))
1954            continue; /* save space, compiler should hoist this */
1955        cbuf = NineSurface9_GetSurface(rt, sRGB);
1956        for (r = 0; r < Count; ++r) {
1957            /* Don't trust users to pass these in the right order. */
1958            unsigned x1 = MIN2(pRects[r].x1, pRects[r].x2);
1959            unsigned y1 = MIN2(pRects[r].y1, pRects[r].y2);
1960            unsigned x2 = MAX2(pRects[r].x1, pRects[r].x2);
1961            unsigned y2 = MAX2(pRects[r].y1, pRects[r].y2);
1962#ifndef NINE_LAX
1963            /* Drop negative rectangles (like wine expects). */
1964            if (pRects[r].x1 > pRects[r].x2) continue;
1965            if (pRects[r].y1 > pRects[r].y2) continue;
1966#endif
1967
1968            x1 = MAX2(x1, rect.x1);
1969            y1 = MAX2(y1, rect.y1);
1970            x2 = MIN3(x2, rect.x2, rt->desc.Width);
1971            y2 = MIN3(y2, rect.y2, rt->desc.Height);
1972
1973            DBG("Clearing (%u..%u)x(%u..%u)\n", x1, x2, y1, y2);
1974            pipe->clear_render_target(pipe, cbuf, &rgba,
1975                                      x1, y1, x2 - x1, y2 - y1);
1976        }
1977    }
1978    if (!(Flags & NINED3DCLEAR_DEPTHSTENCIL))
1979        return D3D_OK;
1980
1981    bufs &= PIPE_CLEAR_DEPTHSTENCIL;
1982
1983    for (r = 0; r < Count; ++r) {
1984        unsigned x1 = MIN2(pRects[r].x1, pRects[r].x2);
1985        unsigned y1 = MIN2(pRects[r].y1, pRects[r].y2);
1986        unsigned x2 = MAX2(pRects[r].x1, pRects[r].x2);
1987        unsigned y2 = MAX2(pRects[r].y1, pRects[r].y2);
1988#ifndef NINE_LAX
1989        /* Drop negative rectangles. */
1990        if (pRects[r].x1 > pRects[r].x2) continue;
1991        if (pRects[r].y1 > pRects[r].y2) continue;
1992#endif
1993
1994        x1 = MIN2(x1, rect.x1);
1995        y1 = MIN2(y1, rect.y1);
1996        x2 = MIN3(x2, rect.x2, zsbuf_surf->desc.Width);
1997        y2 = MIN3(y2, rect.y2, zsbuf_surf->desc.Height);
1998
1999        zsbuf = NineSurface9_GetSurface(zsbuf_surf, 0);
2000        assert(zsbuf);
2001        pipe->clear_depth_stencil(pipe, zsbuf, bufs, Z, Stencil,
2002                                  x1, y1, x2 - x1, y2 - y1);
2003    }
2004    return D3D_OK;
2005}
2006
2007HRESULT WINAPI
2008NineDevice9_SetTransform( struct NineDevice9 *This,
2009                          D3DTRANSFORMSTATETYPE State,
2010                          const D3DMATRIX *pMatrix )
2011{
2012    struct nine_state *state = This->update;
2013    D3DMATRIX *M = nine_state_access_transform(state, State, TRUE);
2014
2015    DBG("This=%p State=%d pMatrix=%p\n", This, State, pMatrix);
2016
2017    user_assert(M, D3DERR_INVALIDCALL);
2018
2019    *M = *pMatrix;
2020    state->ff.changed.transform[State / 32] |= 1 << (State % 32);
2021    state->changed.group |= NINE_STATE_FF;
2022
2023    return D3D_OK;
2024}
2025
2026HRESULT WINAPI
2027NineDevice9_GetTransform( struct NineDevice9 *This,
2028                          D3DTRANSFORMSTATETYPE State,
2029                          D3DMATRIX *pMatrix )
2030{
2031    D3DMATRIX *M = nine_state_access_transform(&This->state, State, FALSE);
2032    user_assert(M, D3DERR_INVALIDCALL);
2033    *pMatrix = *M;
2034    return D3D_OK;
2035}
2036
2037HRESULT WINAPI
2038NineDevice9_MultiplyTransform( struct NineDevice9 *This,
2039                               D3DTRANSFORMSTATETYPE State,
2040                               const D3DMATRIX *pMatrix )
2041{
2042    struct nine_state *state = This->update;
2043    D3DMATRIX T;
2044    D3DMATRIX *M = nine_state_access_transform(state, State, TRUE);
2045
2046    DBG("This=%p State=%d pMatrix=%p\n", This, State, pMatrix);
2047
2048    user_assert(M, D3DERR_INVALIDCALL);
2049
2050    nine_d3d_matrix_matrix_mul(&T, pMatrix, M);
2051    return NineDevice9_SetTransform(This, State, &T);
2052}
2053
2054HRESULT WINAPI
2055NineDevice9_SetViewport( struct NineDevice9 *This,
2056                         const D3DVIEWPORT9 *pViewport )
2057{
2058    struct nine_state *state = This->update;
2059
2060    DBG("X=%u Y=%u W=%u H=%u MinZ=%f MaxZ=%f\n",
2061        pViewport->X, pViewport->Y, pViewport->Width, pViewport->Height,
2062        pViewport->MinZ, pViewport->MaxZ);
2063
2064    state->viewport = *pViewport;
2065    state->changed.group |= NINE_STATE_VIEWPORT;
2066
2067    return D3D_OK;
2068}
2069
2070HRESULT WINAPI
2071NineDevice9_GetViewport( struct NineDevice9 *This,
2072                         D3DVIEWPORT9 *pViewport )
2073{
2074    *pViewport = This->state.viewport;
2075    return D3D_OK;
2076}
2077
2078HRESULT WINAPI
2079NineDevice9_SetMaterial( struct NineDevice9 *This,
2080                         const D3DMATERIAL9 *pMaterial )
2081{
2082    struct nine_state *state = This->update;
2083
2084    DBG("This=%p pMaterial=%p\n", This, pMaterial);
2085    if (pMaterial)
2086        nine_dump_D3DMATERIAL9(DBG_FF, pMaterial);
2087
2088    user_assert(pMaterial, E_POINTER);
2089
2090    state->ff.material = *pMaterial;
2091    state->changed.group |= NINE_STATE_FF_MATERIAL;
2092
2093    return D3D_OK;
2094}
2095
2096HRESULT WINAPI
2097NineDevice9_GetMaterial( struct NineDevice9 *This,
2098                         D3DMATERIAL9 *pMaterial )
2099{
2100    user_assert(pMaterial, E_POINTER);
2101    *pMaterial = This->state.ff.material;
2102    return D3D_OK;
2103}
2104
2105HRESULT WINAPI
2106NineDevice9_SetLight( struct NineDevice9 *This,
2107                      DWORD Index,
2108                      const D3DLIGHT9 *pLight )
2109{
2110    struct nine_state *state = This->update;
2111
2112    DBG("This=%p Index=%u pLight=%p\n", This, Index, pLight);
2113    if (pLight)
2114        nine_dump_D3DLIGHT9(DBG_FF, pLight);
2115
2116    user_assert(pLight, D3DERR_INVALIDCALL);
2117    user_assert(pLight->Type < NINED3DLIGHT_INVALID, D3DERR_INVALIDCALL);
2118
2119    user_assert(Index < NINE_MAX_LIGHTS, D3DERR_INVALIDCALL); /* sanity */
2120
2121    if (Index >= state->ff.num_lights) {
2122        unsigned n = state->ff.num_lights;
2123        unsigned N = Index + 1;
2124
2125        state->ff.light = REALLOC(state->ff.light, n * sizeof(D3DLIGHT9),
2126                                                   N * sizeof(D3DLIGHT9));
2127        if (!state->ff.light)
2128            return E_OUTOFMEMORY;
2129        state->ff.num_lights = N;
2130
2131        for (; n < Index; ++n) {
2132            memset(&state->ff.light[n], 0, sizeof(D3DLIGHT9));
2133            state->ff.light[n].Type = (D3DLIGHTTYPE)NINED3DLIGHT_INVALID;
2134        }
2135    }
2136    state->ff.light[Index] = *pLight;
2137
2138    if (pLight->Type == D3DLIGHT_SPOT && pLight->Theta >= pLight->Phi) {
2139        DBG("Warning: clamping D3DLIGHT9.Theta\n");
2140        state->ff.light[Index].Theta = state->ff.light[Index].Phi;
2141    }
2142    if (pLight->Type != D3DLIGHT_DIRECTIONAL &&
2143        pLight->Attenuation0 == 0.0f &&
2144        pLight->Attenuation1 == 0.0f &&
2145        pLight->Attenuation2 == 0.0f) {
2146        DBG("Warning: all D3DLIGHT9.Attenuation[i] are 0\n");
2147    }
2148
2149    state->changed.group |= NINE_STATE_FF_LIGHTING;
2150
2151    return D3D_OK;
2152}
2153
2154HRESULT WINAPI
2155NineDevice9_GetLight( struct NineDevice9 *This,
2156                      DWORD Index,
2157                      D3DLIGHT9 *pLight )
2158{
2159    const struct nine_state *state = &This->state;
2160
2161    user_assert(pLight, D3DERR_INVALIDCALL);
2162    user_assert(Index < state->ff.num_lights, D3DERR_INVALIDCALL);
2163    user_assert(state->ff.light[Index].Type < NINED3DLIGHT_INVALID,
2164                D3DERR_INVALIDCALL);
2165
2166    *pLight = state->ff.light[Index];
2167
2168    return D3D_OK;
2169}
2170
2171HRESULT WINAPI
2172NineDevice9_LightEnable( struct NineDevice9 *This,
2173                         DWORD Index,
2174                         BOOL Enable )
2175{
2176    struct nine_state *state = This->update;
2177    unsigned i;
2178
2179    DBG("This=%p Index=%u Enable=%i\n", This, Index, Enable);
2180
2181    if (Index >= state->ff.num_lights ||
2182        state->ff.light[Index].Type == NINED3DLIGHT_INVALID) {
2183        /* This should create a default light. */
2184        D3DLIGHT9 light;
2185        memset(&light, 0, sizeof(light));
2186        light.Type = D3DLIGHT_DIRECTIONAL;
2187        light.Diffuse.r = 1.0f;
2188        light.Diffuse.g = 1.0f;
2189        light.Diffuse.b = 1.0f;
2190        light.Direction.z = 1.0f;
2191        NineDevice9_SetLight(This, Index, &light);
2192    }
2193    user_assert(Index < state->ff.num_lights, D3DERR_INVALIDCALL);
2194
2195    for (i = 0; i < state->ff.num_lights_active; ++i) {
2196        if (state->ff.active_light[i] == Index)
2197            break;
2198    }
2199
2200    if (Enable) {
2201        if (i < state->ff.num_lights_active)
2202            return D3D_OK;
2203        /* XXX wine thinks this should still succeed:
2204         */
2205        user_assert(i < NINE_MAX_LIGHTS_ACTIVE, D3DERR_INVALIDCALL);
2206
2207        state->ff.active_light[i] = Index;
2208        state->ff.num_lights_active++;
2209    } else {
2210        if (i == state->ff.num_lights_active)
2211            return D3D_OK;
2212        --state->ff.num_lights_active;
2213        for (; i < state->ff.num_lights_active; ++i)
2214            state->ff.active_light[i] = state->ff.active_light[i + 1];
2215    }
2216    state->changed.group |= NINE_STATE_FF_LIGHTING;
2217
2218    return D3D_OK;
2219}
2220
2221HRESULT WINAPI
2222NineDevice9_GetLightEnable( struct NineDevice9 *This,
2223                            DWORD Index,
2224                            BOOL *pEnable )
2225{
2226    const struct nine_state *state = &This->state;
2227    unsigned i;
2228
2229    user_assert(Index < state->ff.num_lights, D3DERR_INVALIDCALL);
2230    user_assert(state->ff.light[Index].Type < NINED3DLIGHT_INVALID,
2231                D3DERR_INVALIDCALL);
2232
2233    for (i = 0; i < state->ff.num_lights_active; ++i)
2234        if (state->ff.active_light[i] == Index)
2235            break;
2236
2237    *pEnable = i != state->ff.num_lights_active ? 128 : 0; // Taken from wine
2238
2239    return D3D_OK;
2240}
2241
2242HRESULT WINAPI
2243NineDevice9_SetClipPlane( struct NineDevice9 *This,
2244                          DWORD Index,
2245                          const float *pPlane )
2246{
2247    struct nine_state *state = This->update;
2248
2249    user_assert(pPlane, D3DERR_INVALIDCALL);
2250
2251    DBG("This=%p Index=%u pPlane=%f %f %f %f\n", This, Index,
2252        pPlane[0], pPlane[1],
2253        pPlane[2], pPlane[3]);
2254
2255    user_assert(Index < PIPE_MAX_CLIP_PLANES, D3DERR_INVALIDCALL);
2256
2257    memcpy(&state->clip.ucp[Index][0], pPlane, sizeof(state->clip.ucp[0]));
2258    state->changed.ucp |= 1 << Index;
2259
2260    return D3D_OK;
2261}
2262
2263HRESULT WINAPI
2264NineDevice9_GetClipPlane( struct NineDevice9 *This,
2265                          DWORD Index,
2266                          float *pPlane )
2267{
2268    const struct nine_state *state = &This->state;
2269
2270    user_assert(Index < PIPE_MAX_CLIP_PLANES, D3DERR_INVALIDCALL);
2271
2272    memcpy(pPlane, &state->clip.ucp[Index][0], sizeof(state->clip.ucp[0]));
2273    return D3D_OK;
2274}
2275
2276#define RESZ_CODE 0x7fa05000
2277
2278static HRESULT
2279NineDevice9_ResolveZ( struct NineDevice9 *This )
2280{
2281    struct nine_state *state = &This->state;
2282    const struct util_format_description *desc;
2283    struct NineSurface9 *source = state->ds;
2284    struct NineBaseTexture9 *destination = state->texture[0];
2285    struct pipe_resource *src, *dst;
2286    struct pipe_blit_info blit;
2287
2288    DBG("RESZ resolve\n");
2289
2290    user_assert(source && destination &&
2291                destination->base.type == D3DRTYPE_TEXTURE, D3DERR_INVALIDCALL);
2292
2293    src = source->base.resource;
2294    dst = destination->base.resource;
2295
2296    user_assert(src && dst, D3DERR_INVALIDCALL);
2297
2298    /* check dst is depth format. we know already for src */
2299    desc = util_format_description(dst->format);
2300    user_assert(desc->colorspace == UTIL_FORMAT_COLORSPACE_ZS, D3DERR_INVALIDCALL);
2301
2302    memset(&blit, 0, sizeof(blit));
2303    blit.src.resource = src;
2304    blit.src.level = 0;
2305    blit.src.format = src->format;
2306    blit.src.box.z = 0;
2307    blit.src.box.depth = 1;
2308    blit.src.box.x = 0;
2309    blit.src.box.y = 0;
2310    blit.src.box.width = src->width0;
2311    blit.src.box.height = src->height0;
2312
2313    blit.dst.resource = dst;
2314    blit.dst.level = 0;
2315    blit.dst.format = dst->format;
2316    blit.dst.box.z = 0;
2317    blit.dst.box.depth = 1;
2318    blit.dst.box.x = 0;
2319    blit.dst.box.y = 0;
2320    blit.dst.box.width = dst->width0;
2321    blit.dst.box.height = dst->height0;
2322
2323    blit.mask = PIPE_MASK_ZS;
2324    blit.filter = PIPE_TEX_FILTER_NEAREST;
2325    blit.scissor_enable = FALSE;
2326
2327    This->pipe->blit(This->pipe, &blit);
2328    return D3D_OK;
2329}
2330
2331#define ALPHA_TO_COVERAGE_ENABLE   MAKEFOURCC('A', '2', 'M', '1')
2332#define ALPHA_TO_COVERAGE_DISABLE  MAKEFOURCC('A', '2', 'M', '0')
2333
2334HRESULT WINAPI
2335NineDevice9_SetRenderState( struct NineDevice9 *This,
2336                            D3DRENDERSTATETYPE State,
2337                            DWORD Value )
2338{
2339    struct nine_state *state = This->update;
2340
2341    DBG("This=%p State=%u(%s) Value=%08x\n", This,
2342        State, nine_d3drs_to_string(State), Value);
2343
2344    /* Amd hacks (equivalent to GL extensions) */
2345    if (State == D3DRS_POINTSIZE) {
2346        if (Value == RESZ_CODE)
2347            return NineDevice9_ResolveZ(This);
2348
2349        if (Value == ALPHA_TO_COVERAGE_ENABLE ||
2350            Value == ALPHA_TO_COVERAGE_DISABLE) {
2351            state->rs[NINED3DRS_ALPHACOVERAGE] = (Value == ALPHA_TO_COVERAGE_ENABLE);
2352            state->changed.group |= NINE_STATE_BLEND;
2353            return D3D_OK;
2354        }
2355    }
2356
2357    /* NV hack */
2358    if (State == D3DRS_ADAPTIVETESS_Y &&
2359        (Value == D3DFMT_ATOC || (Value == D3DFMT_UNKNOWN && state->rs[NINED3DRS_ALPHACOVERAGE]))) {
2360            state->rs[NINED3DRS_ALPHACOVERAGE] = (Value == D3DFMT_ATOC);
2361            state->changed.group |= NINE_STATE_BLEND;
2362            return D3D_OK;
2363    }
2364
2365    user_assert(State < Elements(state->rs), D3DERR_INVALIDCALL);
2366
2367    if (likely(state->rs[State] != Value) || unlikely(This->is_recording)) {
2368        state->rs[State] = Value;
2369        state->changed.rs[State / 32] |= 1 << (State % 32);
2370        state->changed.group |= nine_render_state_group[State];
2371    }
2372
2373    return D3D_OK;
2374}
2375
2376HRESULT WINAPI
2377NineDevice9_GetRenderState( struct NineDevice9 *This,
2378                            D3DRENDERSTATETYPE State,
2379                            DWORD *pValue )
2380{
2381    user_assert(State < Elements(This->state.rs), D3DERR_INVALIDCALL);
2382
2383    *pValue = This->state.rs[State];
2384    return D3D_OK;
2385}
2386
2387HRESULT WINAPI
2388NineDevice9_CreateStateBlock( struct NineDevice9 *This,
2389                              D3DSTATEBLOCKTYPE Type,
2390                              IDirect3DStateBlock9 **ppSB )
2391{
2392    struct NineStateBlock9 *nsb;
2393    struct nine_state *dst;
2394    HRESULT hr;
2395    enum nine_stateblock_type type;
2396    unsigned s;
2397
2398    DBG("This=%p Type=%u ppSB=%p\n", This, Type, ppSB);
2399
2400    user_assert(Type == D3DSBT_ALL ||
2401                Type == D3DSBT_VERTEXSTATE ||
2402                Type == D3DSBT_PIXELSTATE, D3DERR_INVALIDCALL);
2403
2404    switch (Type) {
2405    case D3DSBT_VERTEXSTATE: type = NINESBT_VERTEXSTATE; break;
2406    case D3DSBT_PIXELSTATE:  type = NINESBT_PIXELSTATE; break;
2407    default:
2408       type = NINESBT_ALL;
2409       break;
2410    }
2411
2412    hr = NineStateBlock9_new(This, &nsb, type);
2413    if (FAILED(hr))
2414       return hr;
2415    *ppSB = (IDirect3DStateBlock9 *)nsb;
2416    dst = &nsb->state;
2417
2418    dst->changed.group =
2419       NINE_STATE_TEXTURE |
2420       NINE_STATE_SAMPLER;
2421
2422    if (Type == D3DSBT_ALL || Type == D3DSBT_VERTEXSTATE) {
2423       dst->changed.group |=
2424           NINE_STATE_FF_LIGHTING |
2425           NINE_STATE_VS | NINE_STATE_VS_CONST |
2426           NINE_STATE_VDECL;
2427       /* TODO: texture/sampler state */
2428       memcpy(dst->changed.rs,
2429              nine_render_states_vertex, sizeof(dst->changed.rs));
2430       nine_ranges_insert(&dst->changed.vs_const_f, 0, This->max_vs_const_f,
2431                          &This->range_pool);
2432       dst->changed.vs_const_i = 0xffff;
2433       dst->changed.vs_const_b = 0xffff;
2434       for (s = 0; s < NINE_MAX_SAMPLERS; ++s)
2435           dst->changed.sampler[s] |= 1 << D3DSAMP_DMAPOFFSET;
2436       if (This->state.ff.num_lights) {
2437           dst->ff.num_lights = This->state.ff.num_lights;
2438           /* zero'd -> light type won't be NINED3DLIGHT_INVALID, so
2439            * all currently existing lights will be captured
2440            */
2441           dst->ff.light = CALLOC(This->state.ff.num_lights,
2442                                  sizeof(D3DLIGHT9));
2443           if (!dst->ff.light) {
2444               nine_bind(ppSB, NULL);
2445               return E_OUTOFMEMORY;
2446           }
2447       }
2448    }
2449    if (Type == D3DSBT_ALL || Type == D3DSBT_PIXELSTATE) {
2450       dst->changed.group |=
2451          NINE_STATE_PS | NINE_STATE_PS_CONST;
2452       /* TODO: texture/sampler state */
2453       memcpy(dst->changed.rs,
2454              nine_render_states_pixel, sizeof(dst->changed.rs));
2455       nine_ranges_insert(&dst->changed.ps_const_f, 0, This->max_ps_const_f,
2456                          &This->range_pool);
2457       dst->changed.ps_const_i = 0xffff;
2458       dst->changed.ps_const_b = 0xffff;
2459       for (s = 0; s < NINE_MAX_SAMPLERS; ++s)
2460           dst->changed.sampler[s] |= 0x1ffe;
2461    }
2462    if (Type == D3DSBT_ALL) {
2463       dst->changed.group |=
2464          NINE_STATE_VIEWPORT |
2465          NINE_STATE_SCISSOR |
2466          NINE_STATE_RASTERIZER |
2467          NINE_STATE_BLEND |
2468          NINE_STATE_DSA |
2469          NINE_STATE_IDXBUF |
2470          NINE_STATE_MATERIAL |
2471          NINE_STATE_BLEND_COLOR |
2472          NINE_STATE_SAMPLE_MASK;
2473       memset(dst->changed.rs, ~0, (D3DRS_COUNT / 32) * sizeof(uint32_t));
2474       dst->changed.rs[D3DRS_LAST / 32] |= (1 << (D3DRS_COUNT % 32)) - 1;
2475       dst->changed.vtxbuf = (1ULL << This->caps.MaxStreams) - 1;
2476       dst->changed.stream_freq = dst->changed.vtxbuf;
2477       dst->changed.ucp = (1 << PIPE_MAX_CLIP_PLANES) - 1;
2478       dst->changed.texture = (1 << NINE_MAX_SAMPLERS) - 1;
2479    }
2480    NineStateBlock9_Capture(NineStateBlock9(*ppSB));
2481
2482    /* TODO: fixed function state */
2483
2484    return D3D_OK;
2485}
2486
2487HRESULT WINAPI
2488NineDevice9_BeginStateBlock( struct NineDevice9 *This )
2489{
2490    HRESULT hr;
2491
2492    DBG("This=%p\n", This);
2493
2494    user_assert(!This->record, D3DERR_INVALIDCALL);
2495
2496    hr = NineStateBlock9_new(This, &This->record, NINESBT_CUSTOM);
2497    if (FAILED(hr))
2498        return hr;
2499    NineUnknown_ConvertRefToBind(NineUnknown(This->record));
2500
2501    This->update = &This->record->state;
2502    This->is_recording = TRUE;
2503
2504    return D3D_OK;
2505}
2506
2507HRESULT WINAPI
2508NineDevice9_EndStateBlock( struct NineDevice9 *This,
2509                           IDirect3DStateBlock9 **ppSB )
2510{
2511    DBG("This=%p ppSB=%p\n", This, ppSB);
2512
2513    user_assert(This->record, D3DERR_INVALIDCALL);
2514
2515    This->update = &This->state;
2516    This->is_recording = FALSE;
2517
2518    NineUnknown_AddRef(NineUnknown(This->record));
2519    *ppSB = (IDirect3DStateBlock9 *)This->record;
2520    NineUnknown_Unbind(NineUnknown(This->record));
2521    This->record = NULL;
2522
2523    return D3D_OK;
2524}
2525
2526HRESULT WINAPI
2527NineDevice9_SetClipStatus( struct NineDevice9 *This,
2528                           const D3DCLIPSTATUS9 *pClipStatus )
2529{
2530    STUB(D3DERR_INVALIDCALL);
2531}
2532
2533HRESULT WINAPI
2534NineDevice9_GetClipStatus( struct NineDevice9 *This,
2535                           D3DCLIPSTATUS9 *pClipStatus )
2536{
2537    STUB(D3DERR_INVALIDCALL);
2538}
2539
2540HRESULT WINAPI
2541NineDevice9_GetTexture( struct NineDevice9 *This,
2542                        DWORD Stage,
2543                        IDirect3DBaseTexture9 **ppTexture )
2544{
2545    user_assert(Stage < This->caps.MaxSimultaneousTextures ||
2546                Stage == D3DDMAPSAMPLER ||
2547                (Stage >= D3DVERTEXTEXTURESAMPLER0 &&
2548                 Stage <= D3DVERTEXTEXTURESAMPLER3), D3DERR_INVALIDCALL);
2549    user_assert(ppTexture, D3DERR_INVALIDCALL);
2550
2551    if (Stage >= D3DDMAPSAMPLER)
2552        Stage = Stage - D3DDMAPSAMPLER + NINE_MAX_SAMPLERS_PS;
2553
2554    *ppTexture = (IDirect3DBaseTexture9 *)This->state.texture[Stage];
2555
2556    if (This->state.texture[Stage])
2557        NineUnknown_AddRef(NineUnknown(This->state.texture[Stage]));
2558    return D3D_OK;
2559}
2560
2561HRESULT WINAPI
2562NineDevice9_SetTexture( struct NineDevice9 *This,
2563                        DWORD Stage,
2564                        IDirect3DBaseTexture9 *pTexture )
2565{
2566    struct nine_state *state = This->update;
2567    struct NineBaseTexture9 *tex = NineBaseTexture9(pTexture);
2568
2569    DBG("This=%p Stage=%u pTexture=%p\n", This, Stage, pTexture);
2570
2571    user_assert(Stage < This->caps.MaxSimultaneousTextures ||
2572                Stage == D3DDMAPSAMPLER ||
2573                (Stage >= D3DVERTEXTEXTURESAMPLER0 &&
2574                 Stage <= D3DVERTEXTEXTURESAMPLER3), D3DERR_INVALIDCALL);
2575    user_assert(!tex || (tex->base.pool != D3DPOOL_SCRATCH &&
2576                tex->base.pool != D3DPOOL_SYSTEMMEM), D3DERR_INVALIDCALL);
2577
2578    if (Stage >= D3DDMAPSAMPLER)
2579        Stage = Stage - D3DDMAPSAMPLER + NINE_MAX_SAMPLERS_PS;
2580
2581    if (!This->is_recording) {
2582        struct NineBaseTexture9 *old = state->texture[Stage];
2583        if (old == tex)
2584            return D3D_OK;
2585
2586        state->samplers_shadow &= ~(1 << Stage);
2587        if (tex) {
2588            state->samplers_shadow |= tex->shadow << Stage;
2589
2590            if ((tex->managed.dirty | tex->dirty_mip) && LIST_IS_EMPTY(&tex->list))
2591                list_add(&tex->list, &This->update_textures);
2592
2593            tex->bind_count++;
2594        }
2595        if (old)
2596            old->bind_count--;
2597    }
2598    nine_bind(&state->texture[Stage], pTexture);
2599
2600    state->changed.texture |= 1 << Stage;
2601    state->changed.group |= NINE_STATE_TEXTURE;
2602
2603    return D3D_OK;
2604}
2605
2606HRESULT WINAPI
2607NineDevice9_GetTextureStageState( struct NineDevice9 *This,
2608                                  DWORD Stage,
2609                                  D3DTEXTURESTAGESTATETYPE Type,
2610                                  DWORD *pValue )
2611{
2612    const struct nine_state *state = &This->state;
2613
2614    user_assert(Stage < Elements(state->ff.tex_stage), D3DERR_INVALIDCALL);
2615    user_assert(Type < Elements(state->ff.tex_stage[0]), D3DERR_INVALIDCALL);
2616
2617    *pValue = state->ff.tex_stage[Stage][Type];
2618
2619    return D3D_OK;
2620}
2621
2622HRESULT WINAPI
2623NineDevice9_SetTextureStageState( struct NineDevice9 *This,
2624                                  DWORD Stage,
2625                                  D3DTEXTURESTAGESTATETYPE Type,
2626                                  DWORD Value )
2627{
2628    struct nine_state *state = This->update;
2629    int bumpmap_index = -1;
2630
2631    DBG("Stage=%u Type=%u Value=%08x\n", Stage, Type, Value);
2632    nine_dump_D3DTSS_value(DBG_FF, Type, Value);
2633
2634    user_assert(Stage < Elements(state->ff.tex_stage), D3DERR_INVALIDCALL);
2635    user_assert(Type < Elements(state->ff.tex_stage[0]), D3DERR_INVALIDCALL);
2636
2637    state->ff.tex_stage[Stage][Type] = Value;
2638    switch (Type) {
2639    case D3DTSS_BUMPENVMAT00:
2640        bumpmap_index = 4 * Stage;
2641        break;
2642    case D3DTSS_BUMPENVMAT10:
2643        bumpmap_index = 4 * Stage + 1;
2644        break;
2645    case D3DTSS_BUMPENVMAT01:
2646        bumpmap_index = 4 * Stage + 2;
2647        break;
2648    case D3DTSS_BUMPENVMAT11:
2649        bumpmap_index = 4 * Stage + 3;
2650        break;
2651    case D3DTSS_BUMPENVLSCALE:
2652        bumpmap_index = 4 * 8 + 2 * Stage;
2653        break;
2654    case D3DTSS_BUMPENVLOFFSET:
2655        bumpmap_index = 4 * 8 + 2 * Stage + 1;
2656        break;
2657    case D3DTSS_TEXTURETRANSFORMFLAGS:
2658        state->changed.group |= NINE_STATE_PS1X_SHADER;
2659        break;
2660    default:
2661        break;
2662    }
2663
2664    if (bumpmap_index >= 0) {
2665        state->bumpmap_vars[bumpmap_index] = Value;
2666        state->changed.group |= NINE_STATE_PS_CONST;
2667    }
2668
2669    state->changed.group |= NINE_STATE_FF_PSSTAGES;
2670    state->ff.changed.tex_stage[Stage][Type / 32] |= 1 << (Type % 32);
2671
2672    return D3D_OK;
2673}
2674
2675HRESULT WINAPI
2676NineDevice9_GetSamplerState( struct NineDevice9 *This,
2677                             DWORD Sampler,
2678                             D3DSAMPLERSTATETYPE Type,
2679                             DWORD *pValue )
2680{
2681    user_assert(Sampler < This->caps.MaxSimultaneousTextures ||
2682                Sampler == D3DDMAPSAMPLER ||
2683                (Sampler >= D3DVERTEXTEXTURESAMPLER0 &&
2684                 Sampler <= D3DVERTEXTEXTURESAMPLER3), D3DERR_INVALIDCALL);
2685
2686    if (Sampler >= D3DDMAPSAMPLER)
2687        Sampler = Sampler - D3DDMAPSAMPLER + NINE_MAX_SAMPLERS_PS;
2688
2689    *pValue = This->state.samp[Sampler][Type];
2690    return D3D_OK;
2691}
2692
2693HRESULT WINAPI
2694NineDevice9_SetSamplerState( struct NineDevice9 *This,
2695                             DWORD Sampler,
2696                             D3DSAMPLERSTATETYPE Type,
2697                             DWORD Value )
2698{
2699    struct nine_state *state = This->update;
2700
2701    DBG("This=%p Sampler=%u Type=%s Value=%08x\n", This,
2702        Sampler, nine_D3DSAMP_to_str(Type), Value);
2703
2704    user_assert(Sampler < This->caps.MaxSimultaneousTextures ||
2705                Sampler == D3DDMAPSAMPLER ||
2706                (Sampler >= D3DVERTEXTEXTURESAMPLER0 &&
2707                 Sampler <= D3DVERTEXTEXTURESAMPLER3), D3DERR_INVALIDCALL);
2708
2709    if (Sampler >= D3DDMAPSAMPLER)
2710        Sampler = Sampler - D3DDMAPSAMPLER + NINE_MAX_SAMPLERS_PS;
2711
2712    if (state->samp[Sampler][Type] != Value || unlikely(This->is_recording)) {
2713        state->samp[Sampler][Type] = Value;
2714        state->changed.group |= NINE_STATE_SAMPLER;
2715        state->changed.sampler[Sampler] |= 1 << Type;
2716    }
2717
2718    return D3D_OK;
2719}
2720
2721HRESULT WINAPI
2722NineDevice9_ValidateDevice( struct NineDevice9 *This,
2723                            DWORD *pNumPasses )
2724{
2725    const struct nine_state *state = &This->state;
2726    unsigned i;
2727    unsigned w = 0, h = 0;
2728
2729    DBG("This=%p pNumPasses=%p\n", This, pNumPasses);
2730
2731    for (i = 0; i < Elements(state->samp); ++i) {
2732        if (state->samp[i][D3DSAMP_MINFILTER] == D3DTEXF_NONE ||
2733            state->samp[i][D3DSAMP_MAGFILTER] == D3DTEXF_NONE)
2734            return D3DERR_UNSUPPORTEDTEXTUREFILTER;
2735    }
2736
2737    for (i = 0; i < This->caps.NumSimultaneousRTs; ++i) {
2738        if (!state->rt[i])
2739            continue;
2740        if (w == 0) {
2741            w = state->rt[i]->desc.Width;
2742            h = state->rt[i]->desc.Height;
2743        } else
2744        if (state->rt[i]->desc.Width != w || state->rt[i]->desc.Height != h) {
2745            return D3DERR_CONFLICTINGRENDERSTATE;
2746        }
2747    }
2748    if (state->ds &&
2749        (state->rs[D3DRS_ZENABLE] || state->rs[D3DRS_STENCILENABLE])) {
2750        if (w != 0 &&
2751            (state->ds->desc.Width != w || state->ds->desc.Height != h))
2752            return D3DERR_CONFLICTINGRENDERSTATE;
2753    }
2754
2755    if (pNumPasses)
2756        *pNumPasses = 1;
2757
2758    return D3D_OK;
2759}
2760
2761HRESULT WINAPI
2762NineDevice9_SetPaletteEntries( struct NineDevice9 *This,
2763                               UINT PaletteNumber,
2764                               const PALETTEENTRY *pEntries )
2765{
2766    STUB(D3D_OK); /* like wine */
2767}
2768
2769HRESULT WINAPI
2770NineDevice9_GetPaletteEntries( struct NineDevice9 *This,
2771                               UINT PaletteNumber,
2772                               PALETTEENTRY *pEntries )
2773{
2774    STUB(D3DERR_INVALIDCALL);
2775}
2776
2777HRESULT WINAPI
2778NineDevice9_SetCurrentTexturePalette( struct NineDevice9 *This,
2779                                      UINT PaletteNumber )
2780{
2781    STUB(D3D_OK); /* like wine */
2782}
2783
2784HRESULT WINAPI
2785NineDevice9_GetCurrentTexturePalette( struct NineDevice9 *This,
2786                                      UINT *PaletteNumber )
2787{
2788    STUB(D3DERR_INVALIDCALL);
2789}
2790
2791HRESULT WINAPI
2792NineDevice9_SetScissorRect( struct NineDevice9 *This,
2793                            const RECT *pRect )
2794{
2795    struct nine_state *state = This->update;
2796
2797    DBG("x=(%u..%u) y=(%u..%u)\n",
2798        pRect->left, pRect->top, pRect->right, pRect->bottom);
2799
2800    state->scissor.minx = pRect->left;
2801    state->scissor.miny = pRect->top;
2802    state->scissor.maxx = pRect->right;
2803    state->scissor.maxy = pRect->bottom;
2804
2805    state->changed.group |= NINE_STATE_SCISSOR;
2806
2807    return D3D_OK;
2808}
2809
2810HRESULT WINAPI
2811NineDevice9_GetScissorRect( struct NineDevice9 *This,
2812                            RECT *pRect )
2813{
2814    pRect->left   = This->state.scissor.minx;
2815    pRect->top    = This->state.scissor.miny;
2816    pRect->right  = This->state.scissor.maxx;
2817    pRect->bottom = This->state.scissor.maxy;
2818
2819    return D3D_OK;
2820}
2821
2822HRESULT WINAPI
2823NineDevice9_SetSoftwareVertexProcessing( struct NineDevice9 *This,
2824                                         BOOL bSoftware )
2825{
2826    STUB(D3DERR_INVALIDCALL);
2827}
2828
2829BOOL WINAPI
2830NineDevice9_GetSoftwareVertexProcessing( struct NineDevice9 *This )
2831{
2832    return !!(This->params.BehaviorFlags & D3DCREATE_SOFTWARE_VERTEXPROCESSING);
2833}
2834
2835HRESULT WINAPI
2836NineDevice9_SetNPatchMode( struct NineDevice9 *This,
2837                           float nSegments )
2838{
2839    STUB(D3DERR_INVALIDCALL);
2840}
2841
2842float WINAPI
2843NineDevice9_GetNPatchMode( struct NineDevice9 *This )
2844{
2845    STUB(0);
2846}
2847
2848static inline void
2849init_draw_info(struct pipe_draw_info *info,
2850               struct NineDevice9 *dev, D3DPRIMITIVETYPE type, UINT count)
2851{
2852    info->mode = d3dprimitivetype_to_pipe_prim(type);
2853    info->count = prim_count_to_vertex_count(type, count);
2854    info->start_instance = 0;
2855    info->instance_count = 1;
2856    if (dev->state.stream_instancedata_mask & dev->state.stream_usage_mask)
2857        info->instance_count = MAX2(dev->state.stream_freq[0] & 0x7FFFFF, 1);
2858    info->primitive_restart = FALSE;
2859    info->restart_index = 0;
2860    info->count_from_stream_output = NULL;
2861    info->indirect = NULL;
2862}
2863
2864HRESULT WINAPI
2865NineDevice9_DrawPrimitive( struct NineDevice9 *This,
2866                           D3DPRIMITIVETYPE PrimitiveType,
2867                           UINT StartVertex,
2868                           UINT PrimitiveCount )
2869{
2870    struct pipe_draw_info info;
2871
2872    DBG("iface %p, PrimitiveType %u, StartVertex %u, PrimitiveCount %u\n",
2873        This, PrimitiveType, StartVertex, PrimitiveCount);
2874
2875    nine_update_state(This);
2876
2877    init_draw_info(&info, This, PrimitiveType, PrimitiveCount);
2878    info.indexed = FALSE;
2879    info.start = StartVertex;
2880    info.index_bias = 0;
2881    info.min_index = info.start;
2882    info.max_index = info.count - 1;
2883
2884    This->pipe->draw_vbo(This->pipe, &info);
2885
2886    return D3D_OK;
2887}
2888
2889HRESULT WINAPI
2890NineDevice9_DrawIndexedPrimitive( struct NineDevice9 *This,
2891                                  D3DPRIMITIVETYPE PrimitiveType,
2892                                  INT BaseVertexIndex,
2893                                  UINT MinVertexIndex,
2894                                  UINT NumVertices,
2895                                  UINT StartIndex,
2896                                  UINT PrimitiveCount )
2897{
2898    struct pipe_draw_info info;
2899
2900    DBG("iface %p, PrimitiveType %u, BaseVertexIndex %u, MinVertexIndex %u "
2901        "NumVertices %u, StartIndex %u, PrimitiveCount %u\n",
2902        This, PrimitiveType, BaseVertexIndex, MinVertexIndex, NumVertices,
2903        StartIndex, PrimitiveCount);
2904
2905    user_assert(This->state.idxbuf, D3DERR_INVALIDCALL);
2906    user_assert(This->state.vdecl, D3DERR_INVALIDCALL);
2907
2908    nine_update_state(This);
2909
2910    init_draw_info(&info, This, PrimitiveType, PrimitiveCount);
2911    info.indexed = TRUE;
2912    info.start = StartIndex;
2913    info.index_bias = BaseVertexIndex;
2914    /* These don't include index bias: */
2915    info.min_index = MinVertexIndex;
2916    info.max_index = MinVertexIndex + NumVertices - 1;
2917
2918    This->pipe->draw_vbo(This->pipe, &info);
2919
2920    return D3D_OK;
2921}
2922
2923HRESULT WINAPI
2924NineDevice9_DrawPrimitiveUP( struct NineDevice9 *This,
2925                             D3DPRIMITIVETYPE PrimitiveType,
2926                             UINT PrimitiveCount,
2927                             const void *pVertexStreamZeroData,
2928                             UINT VertexStreamZeroStride )
2929{
2930    struct pipe_vertex_buffer vtxbuf;
2931    struct pipe_draw_info info;
2932
2933    DBG("iface %p, PrimitiveType %u, PrimitiveCount %u, data %p, stride %u\n",
2934        This, PrimitiveType, PrimitiveCount,
2935        pVertexStreamZeroData, VertexStreamZeroStride);
2936
2937    user_assert(pVertexStreamZeroData && VertexStreamZeroStride,
2938                D3DERR_INVALIDCALL);
2939
2940    nine_update_state(This);
2941
2942    init_draw_info(&info, This, PrimitiveType, PrimitiveCount);
2943    info.indexed = FALSE;
2944    info.start = 0;
2945    info.index_bias = 0;
2946    info.min_index = 0;
2947    info.max_index = info.count - 1;
2948
2949    vtxbuf.stride = VertexStreamZeroStride;
2950    vtxbuf.buffer_offset = 0;
2951    vtxbuf.buffer = NULL;
2952    vtxbuf.user_buffer = pVertexStreamZeroData;
2953
2954    if (!This->driver_caps.user_vbufs) {
2955        u_upload_data(This->vertex_uploader,
2956                      0,
2957                      (info.max_index + 1) * VertexStreamZeroStride, /* XXX */
2958                      vtxbuf.user_buffer,
2959                      &vtxbuf.buffer_offset,
2960                      &vtxbuf.buffer);
2961        u_upload_unmap(This->vertex_uploader);
2962        vtxbuf.user_buffer = NULL;
2963    }
2964
2965    This->pipe->set_vertex_buffers(This->pipe, 0, 1, &vtxbuf);
2966
2967    This->pipe->draw_vbo(This->pipe, &info);
2968
2969    NineDevice9_PauseRecording(This);
2970    NineDevice9_SetStreamSource(This, 0, NULL, 0, 0);
2971    NineDevice9_ResumeRecording(This);
2972
2973    pipe_resource_reference(&vtxbuf.buffer, NULL);
2974
2975    return D3D_OK;
2976}
2977
2978HRESULT WINAPI
2979NineDevice9_DrawIndexedPrimitiveUP( struct NineDevice9 *This,
2980                                    D3DPRIMITIVETYPE PrimitiveType,
2981                                    UINT MinVertexIndex,
2982                                    UINT NumVertices,
2983                                    UINT PrimitiveCount,
2984                                    const void *pIndexData,
2985                                    D3DFORMAT IndexDataFormat,
2986                                    const void *pVertexStreamZeroData,
2987                                    UINT VertexStreamZeroStride )
2988{
2989    struct pipe_draw_info info;
2990    struct pipe_vertex_buffer vbuf;
2991    struct pipe_index_buffer ibuf;
2992
2993    DBG("iface %p, PrimitiveType %u, MinVertexIndex %u, NumVertices %u "
2994        "PrimitiveCount %u, pIndexData %p, IndexDataFormat %u "
2995        "pVertexStreamZeroData %p, VertexStreamZeroStride %u\n",
2996        This, PrimitiveType, MinVertexIndex, NumVertices, PrimitiveCount,
2997        pIndexData, IndexDataFormat,
2998        pVertexStreamZeroData, VertexStreamZeroStride);
2999
3000    user_assert(pIndexData && pVertexStreamZeroData, D3DERR_INVALIDCALL);
3001    user_assert(VertexStreamZeroStride, D3DERR_INVALIDCALL);
3002    user_assert(IndexDataFormat == D3DFMT_INDEX16 ||
3003                IndexDataFormat == D3DFMT_INDEX32, D3DERR_INVALIDCALL);
3004
3005    nine_update_state(This);
3006
3007    init_draw_info(&info, This, PrimitiveType, PrimitiveCount);
3008    info.indexed = TRUE;
3009    info.start = 0;
3010    info.index_bias = 0;
3011    info.min_index = MinVertexIndex;
3012    info.max_index = MinVertexIndex + NumVertices - 1;
3013
3014    vbuf.stride = VertexStreamZeroStride;
3015    vbuf.buffer_offset = 0;
3016    vbuf.buffer = NULL;
3017    vbuf.user_buffer = pVertexStreamZeroData;
3018
3019    ibuf.index_size = (IndexDataFormat == D3DFMT_INDEX16) ? 2 : 4;
3020    ibuf.offset = 0;
3021    ibuf.buffer = NULL;
3022    ibuf.user_buffer = pIndexData;
3023
3024    if (!This->driver_caps.user_vbufs) {
3025        const unsigned base = info.min_index * VertexStreamZeroStride;
3026        u_upload_data(This->vertex_uploader,
3027                      base,
3028                      (info.max_index -
3029                       info.min_index + 1) * VertexStreamZeroStride, /* XXX */
3030                      (const uint8_t *)vbuf.user_buffer + base,
3031                      &vbuf.buffer_offset,
3032                      &vbuf.buffer);
3033        u_upload_unmap(This->vertex_uploader);
3034        /* Won't be used: */
3035        vbuf.buffer_offset -= base;
3036        vbuf.user_buffer = NULL;
3037    }
3038    if (!This->driver_caps.user_ibufs) {
3039        u_upload_data(This->index_uploader,
3040                      0,
3041                      info.count * ibuf.index_size,
3042                      ibuf.user_buffer,
3043                      &ibuf.offset,
3044                      &ibuf.buffer);
3045        u_upload_unmap(This->index_uploader);
3046        ibuf.user_buffer = NULL;
3047    }
3048
3049    This->pipe->set_vertex_buffers(This->pipe, 0, 1, &vbuf);
3050    This->pipe->set_index_buffer(This->pipe, &ibuf);
3051
3052    This->pipe->draw_vbo(This->pipe, &info);
3053
3054    pipe_resource_reference(&vbuf.buffer, NULL);
3055    pipe_resource_reference(&ibuf.buffer, NULL);
3056
3057    NineDevice9_PauseRecording(This);
3058    NineDevice9_SetIndices(This, NULL);
3059    NineDevice9_SetStreamSource(This, 0, NULL, 0, 0);
3060    NineDevice9_ResumeRecording(This);
3061
3062    return D3D_OK;
3063}
3064
3065/* TODO: Write to pDestBuffer directly if vertex declaration contains
3066 * only f32 formats.
3067 */
3068HRESULT WINAPI
3069NineDevice9_ProcessVertices( struct NineDevice9 *This,
3070                             UINT SrcStartIndex,
3071                             UINT DestIndex,
3072                             UINT VertexCount,
3073                             IDirect3DVertexBuffer9 *pDestBuffer,
3074                             IDirect3DVertexDeclaration9 *pVertexDecl,
3075                             DWORD Flags )
3076{
3077    struct pipe_screen *screen = This->screen;
3078    struct NineVertexDeclaration9 *vdecl = NineVertexDeclaration9(pVertexDecl);
3079    struct NineVertexShader9 *vs;
3080    struct pipe_resource *resource;
3081    struct pipe_stream_output_target *target;
3082    struct pipe_draw_info draw;
3083    HRESULT hr;
3084    unsigned buffer_offset, buffer_size;
3085
3086    DBG("This=%p SrcStartIndex=%u DestIndex=%u VertexCount=%u "
3087        "pDestBuffer=%p pVertexDecl=%p Flags=%d\n",
3088        This, SrcStartIndex, DestIndex, VertexCount, pDestBuffer,
3089        pVertexDecl, Flags);
3090
3091    if (!screen->get_param(screen, PIPE_CAP_MAX_STREAM_OUTPUT_BUFFERS))
3092        STUB(D3DERR_INVALIDCALL);
3093
3094    nine_update_state(This);
3095
3096    /* TODO: Create shader with stream output. */
3097    STUB(D3DERR_INVALIDCALL);
3098    struct NineVertexBuffer9 *dst = NineVertexBuffer9(pDestBuffer);
3099
3100    vs = This->state.vs ? This->state.vs : This->ff.vs;
3101
3102    buffer_size = VertexCount * vs->so->stride[0];
3103    if (1) {
3104        struct pipe_resource templ;
3105
3106        templ.target = PIPE_BUFFER;
3107        templ.format = PIPE_FORMAT_R8_UNORM;
3108        templ.width0 = buffer_size;
3109        templ.flags = 0;
3110        templ.bind = PIPE_BIND_STREAM_OUTPUT;
3111        templ.usage = PIPE_USAGE_STREAM;
3112        templ.height0 = templ.depth0 = templ.array_size = 1;
3113        templ.last_level = templ.nr_samples = 0;
3114
3115        resource = This->screen->resource_create(This->screen, &templ);
3116        if (!resource)
3117            return E_OUTOFMEMORY;
3118        buffer_offset = 0;
3119    } else {
3120        /* SO matches vertex declaration */
3121        resource = dst->base.resource;
3122        buffer_offset = DestIndex * vs->so->stride[0];
3123    }
3124    target = This->pipe->create_stream_output_target(This->pipe, resource,
3125                                                     buffer_offset,
3126                                                     buffer_size);
3127    if (!target) {
3128        pipe_resource_reference(&resource, NULL);
3129        return D3DERR_DRIVERINTERNALERROR;
3130    }
3131
3132    if (!vdecl) {
3133        hr = NineVertexDeclaration9_new_from_fvf(This, dst->desc.FVF, &vdecl);
3134        if (FAILED(hr))
3135            goto out;
3136    }
3137
3138    init_draw_info(&draw, This, D3DPT_POINTLIST, VertexCount);
3139    draw.instance_count = 1;
3140    draw.indexed = FALSE;
3141    draw.start = SrcStartIndex;
3142    draw.index_bias = 0;
3143    draw.min_index = SrcStartIndex;
3144    draw.max_index = SrcStartIndex + VertexCount - 1;
3145
3146    This->pipe->set_stream_output_targets(This->pipe, 1, &target, 0);
3147    This->pipe->draw_vbo(This->pipe, &draw);
3148    This->pipe->set_stream_output_targets(This->pipe, 0, NULL, 0);
3149    This->pipe->stream_output_target_destroy(This->pipe, target);
3150
3151    hr = NineVertexDeclaration9_ConvertStreamOutput(vdecl,
3152                                                    dst, DestIndex, VertexCount,
3153                                                    resource, vs->so);
3154out:
3155    pipe_resource_reference(&resource, NULL);
3156    if (!pVertexDecl)
3157        NineUnknown_Release(NineUnknown(vdecl));
3158    return hr;
3159}
3160
3161HRESULT WINAPI
3162NineDevice9_CreateVertexDeclaration( struct NineDevice9 *This,
3163                                     const D3DVERTEXELEMENT9 *pVertexElements,
3164                                     IDirect3DVertexDeclaration9 **ppDecl )
3165{
3166    struct NineVertexDeclaration9 *vdecl;
3167
3168    DBG("This=%p pVertexElements=%p ppDecl=%p\n",
3169        This, pVertexElements, ppDecl);
3170
3171    HRESULT hr = NineVertexDeclaration9_new(This, pVertexElements, &vdecl);
3172    if (SUCCEEDED(hr))
3173        *ppDecl = (IDirect3DVertexDeclaration9 *)vdecl;
3174
3175    return hr;
3176}
3177
3178HRESULT WINAPI
3179NineDevice9_SetVertexDeclaration( struct NineDevice9 *This,
3180                                  IDirect3DVertexDeclaration9 *pDecl )
3181{
3182    struct nine_state *state = This->update;
3183
3184    DBG("This=%p pDecl=%p\n", This, pDecl);
3185
3186    if (likely(!This->is_recording) && state->vdecl == NineVertexDeclaration9(pDecl))
3187        return D3D_OK;
3188    nine_bind(&state->vdecl, pDecl);
3189
3190    state->changed.group |= NINE_STATE_VDECL;
3191
3192    return D3D_OK;
3193}
3194
3195HRESULT WINAPI
3196NineDevice9_GetVertexDeclaration( struct NineDevice9 *This,
3197                                  IDirect3DVertexDeclaration9 **ppDecl )
3198{
3199    user_assert(ppDecl, D3DERR_INVALIDCALL);
3200
3201    *ppDecl = (IDirect3DVertexDeclaration9 *)This->state.vdecl;
3202    if (*ppDecl)
3203        NineUnknown_AddRef(NineUnknown(*ppDecl));
3204    return D3D_OK;
3205}
3206
3207HRESULT WINAPI
3208NineDevice9_SetFVF( struct NineDevice9 *This,
3209                    DWORD FVF )
3210{
3211    struct NineVertexDeclaration9 *vdecl;
3212    HRESULT hr;
3213
3214    DBG("FVF = %08x\n", FVF);
3215    if (!FVF)
3216        return D3D_OK; /* like wine */
3217
3218    vdecl = util_hash_table_get(This->ff.ht_fvf, &FVF);
3219    if (!vdecl) {
3220        hr = NineVertexDeclaration9_new_from_fvf(This, FVF, &vdecl);
3221        if (FAILED(hr))
3222            return hr;
3223        vdecl->fvf = FVF;
3224        util_hash_table_set(This->ff.ht_fvf, &vdecl->fvf, vdecl);
3225        NineUnknown_ConvertRefToBind(NineUnknown(vdecl));
3226    }
3227    return NineDevice9_SetVertexDeclaration(
3228        This, (IDirect3DVertexDeclaration9 *)vdecl);
3229}
3230
3231HRESULT WINAPI
3232NineDevice9_GetFVF( struct NineDevice9 *This,
3233                    DWORD *pFVF )
3234{
3235    *pFVF = This->state.vdecl ? This->state.vdecl->fvf : 0;
3236    return D3D_OK;
3237}
3238
3239HRESULT WINAPI
3240NineDevice9_CreateVertexShader( struct NineDevice9 *This,
3241                                const DWORD *pFunction,
3242                                IDirect3DVertexShader9 **ppShader )
3243{
3244    struct NineVertexShader9 *vs;
3245    HRESULT hr;
3246
3247    DBG("This=%p pFunction=%p ppShader=%p\n", This, pFunction, ppShader);
3248
3249    hr = NineVertexShader9_new(This, &vs, pFunction, NULL);
3250    if (FAILED(hr))
3251        return hr;
3252    *ppShader = (IDirect3DVertexShader9 *)vs;
3253    return D3D_OK;
3254}
3255
3256HRESULT WINAPI
3257NineDevice9_SetVertexShader( struct NineDevice9 *This,
3258                             IDirect3DVertexShader9 *pShader )
3259{
3260    struct nine_state *state = This->update;
3261
3262    DBG("This=%p pShader=%p\n", This, pShader);
3263
3264    if (!This->is_recording && state->vs == (struct NineVertexShader9*)pShader)
3265      return D3D_OK;
3266
3267    /* ff -> non-ff: commit back non-ff constants */
3268    if (!state->vs && pShader)
3269        state->commit |= NINE_STATE_COMMIT_CONST_VS;
3270
3271    nine_bind(&state->vs, pShader);
3272
3273    state->changed.group |= NINE_STATE_VS;
3274
3275    return D3D_OK;
3276}
3277
3278HRESULT WINAPI
3279NineDevice9_GetVertexShader( struct NineDevice9 *This,
3280                             IDirect3DVertexShader9 **ppShader )
3281{
3282    user_assert(ppShader, D3DERR_INVALIDCALL);
3283    nine_reference_set(ppShader, This->state.vs);
3284    return D3D_OK;
3285}
3286
3287HRESULT WINAPI
3288NineDevice9_SetVertexShaderConstantF( struct NineDevice9 *This,
3289                                      UINT StartRegister,
3290                                      const float *pConstantData,
3291                                      UINT Vector4fCount )
3292{
3293    struct nine_state *state = This->update;
3294
3295    DBG("This=%p StartRegister=%u pConstantData=%p Vector4fCount=%u\n",
3296        This, StartRegister, pConstantData, Vector4fCount);
3297
3298    user_assert(StartRegister                  < This->caps.MaxVertexShaderConst, D3DERR_INVALIDCALL);
3299    user_assert(StartRegister + Vector4fCount <= This->caps.MaxVertexShaderConst, D3DERR_INVALIDCALL);
3300
3301    if (!Vector4fCount)
3302       return D3D_OK;
3303    user_assert(pConstantData, D3DERR_INVALIDCALL);
3304
3305    if (!This->is_recording) {
3306        if (!memcmp(&state->vs_const_f[StartRegister * 4], pConstantData,
3307                    Vector4fCount * 4 * sizeof(state->vs_const_f[0])))
3308            return D3D_OK;
3309    }
3310
3311    memcpy(&state->vs_const_f[StartRegister * 4],
3312           pConstantData,
3313           Vector4fCount * 4 * sizeof(state->vs_const_f[0]));
3314
3315    nine_ranges_insert(&state->changed.vs_const_f,
3316                       StartRegister, StartRegister + Vector4fCount,
3317                       &This->range_pool);
3318
3319    state->changed.group |= NINE_STATE_VS_CONST;
3320
3321    return D3D_OK;
3322}
3323
3324HRESULT WINAPI
3325NineDevice9_GetVertexShaderConstantF( struct NineDevice9 *This,
3326                                      UINT StartRegister,
3327                                      float *pConstantData,
3328                                      UINT Vector4fCount )
3329{
3330    const struct nine_state *state = &This->state;
3331
3332    user_assert(StartRegister                  < This->caps.MaxVertexShaderConst, D3DERR_INVALIDCALL);
3333    user_assert(StartRegister + Vector4fCount <= This->caps.MaxVertexShaderConst, D3DERR_INVALIDCALL);
3334    user_assert(pConstantData, D3DERR_INVALIDCALL);
3335
3336    memcpy(pConstantData,
3337           &state->vs_const_f[StartRegister * 4],
3338           Vector4fCount * 4 * sizeof(state->vs_const_f[0]));
3339
3340    return D3D_OK;
3341}
3342
3343HRESULT WINAPI
3344NineDevice9_SetVertexShaderConstantI( struct NineDevice9 *This,
3345                                      UINT StartRegister,
3346                                      const int *pConstantData,
3347                                      UINT Vector4iCount )
3348{
3349    struct nine_state *state = This->update;
3350    int i;
3351
3352    DBG("This=%p StartRegister=%u pConstantData=%p Vector4iCount=%u\n",
3353        This, StartRegister, pConstantData, Vector4iCount);
3354
3355    user_assert(StartRegister                  < NINE_MAX_CONST_I, D3DERR_INVALIDCALL);
3356    user_assert(StartRegister + Vector4iCount <= NINE_MAX_CONST_I, D3DERR_INVALIDCALL);
3357    user_assert(pConstantData, D3DERR_INVALIDCALL);
3358
3359    if (This->driver_caps.vs_integer) {
3360        if (!This->is_recording) {
3361            if (!memcmp(&state->vs_const_i[StartRegister][0], pConstantData,
3362                        Vector4iCount * sizeof(state->vs_const_i[0])))
3363                return D3D_OK;
3364        }
3365        memcpy(&state->vs_const_i[StartRegister][0],
3366               pConstantData,
3367               Vector4iCount * sizeof(state->vs_const_i[0]));
3368    } else {
3369        for (i = 0; i < Vector4iCount; i++) {
3370            state->vs_const_i[StartRegister+i][0] = fui((float)(pConstantData[4*i]));
3371            state->vs_const_i[StartRegister+i][1] = fui((float)(pConstantData[4*i+1]));
3372            state->vs_const_i[StartRegister+i][2] = fui((float)(pConstantData[4*i+2]));
3373            state->vs_const_i[StartRegister+i][3] = fui((float)(pConstantData[4*i+3]));
3374        }
3375    }
3376
3377    state->changed.vs_const_i |= ((1 << Vector4iCount) - 1) << StartRegister;
3378    state->changed.group |= NINE_STATE_VS_CONST;
3379
3380    return D3D_OK;
3381}
3382
3383HRESULT WINAPI
3384NineDevice9_GetVertexShaderConstantI( struct NineDevice9 *This,
3385                                      UINT StartRegister,
3386                                      int *pConstantData,
3387                                      UINT Vector4iCount )
3388{
3389    const struct nine_state *state = &This->state;
3390    int i;
3391
3392    user_assert(StartRegister                  < NINE_MAX_CONST_I, D3DERR_INVALIDCALL);
3393    user_assert(StartRegister + Vector4iCount <= NINE_MAX_CONST_I, D3DERR_INVALIDCALL);
3394    user_assert(pConstantData, D3DERR_INVALIDCALL);
3395
3396    if (This->driver_caps.vs_integer) {
3397        memcpy(pConstantData,
3398               &state->vs_const_i[StartRegister][0],
3399               Vector4iCount * sizeof(state->vs_const_i[0]));
3400    } else {
3401        for (i = 0; i < Vector4iCount; i++) {
3402            pConstantData[4*i] = (int32_t) uif(state->vs_const_i[StartRegister+i][0]);
3403            pConstantData[4*i+1] = (int32_t) uif(state->vs_const_i[StartRegister+i][1]);
3404            pConstantData[4*i+2] = (int32_t) uif(state->vs_const_i[StartRegister+i][2]);
3405            pConstantData[4*i+3] = (int32_t) uif(state->vs_const_i[StartRegister+i][3]);
3406        }
3407    }
3408
3409    return D3D_OK;
3410}
3411
3412HRESULT WINAPI
3413NineDevice9_SetVertexShaderConstantB( struct NineDevice9 *This,
3414                                      UINT StartRegister,
3415                                      const BOOL *pConstantData,
3416                                      UINT BoolCount )
3417{
3418    struct nine_state *state = This->update;
3419    int i;
3420    uint32_t bool_true = This->driver_caps.vs_integer ? 0xFFFFFFFF : fui(1.0f);
3421
3422    DBG("This=%p StartRegister=%u pConstantData=%p BoolCount=%u\n",
3423        This, StartRegister, pConstantData, BoolCount);
3424
3425    user_assert(StartRegister              < NINE_MAX_CONST_B, D3DERR_INVALIDCALL);
3426    user_assert(StartRegister + BoolCount <= NINE_MAX_CONST_B, D3DERR_INVALIDCALL);
3427    user_assert(pConstantData, D3DERR_INVALIDCALL);
3428
3429    if (!This->is_recording) {
3430        bool noChange = true;
3431        for (i = 0; i < BoolCount; i++) {
3432            if (!!state->vs_const_b[StartRegister + i] != !!pConstantData[i])
3433              noChange = false;
3434        }
3435        if (noChange)
3436            return D3D_OK;
3437    }
3438
3439    for (i = 0; i < BoolCount; i++)
3440        state->vs_const_b[StartRegister + i] = pConstantData[i] ? bool_true : 0;
3441
3442    state->changed.vs_const_b |= ((1 << BoolCount) - 1) << StartRegister;
3443    state->changed.group |= NINE_STATE_VS_CONST;
3444
3445    return D3D_OK;
3446}
3447
3448HRESULT WINAPI
3449NineDevice9_GetVertexShaderConstantB( struct NineDevice9 *This,
3450                                      UINT StartRegister,
3451                                      BOOL *pConstantData,
3452                                      UINT BoolCount )
3453{
3454    const struct nine_state *state = &This->state;
3455    int i;
3456
3457    user_assert(StartRegister              < NINE_MAX_CONST_B, D3DERR_INVALIDCALL);
3458    user_assert(StartRegister + BoolCount <= NINE_MAX_CONST_B, D3DERR_INVALIDCALL);
3459    user_assert(pConstantData, D3DERR_INVALIDCALL);
3460
3461    for (i = 0; i < BoolCount; i++)
3462        pConstantData[i] = state->vs_const_b[StartRegister + i] != 0 ? TRUE : FALSE;
3463
3464    return D3D_OK;
3465}
3466
3467HRESULT WINAPI
3468NineDevice9_SetStreamSource( struct NineDevice9 *This,
3469                             UINT StreamNumber,
3470                             IDirect3DVertexBuffer9 *pStreamData,
3471                             UINT OffsetInBytes,
3472                             UINT Stride )
3473{
3474    struct nine_state *state = This->update;
3475    struct NineVertexBuffer9 *pVBuf9 = NineVertexBuffer9(pStreamData);
3476    const unsigned i = StreamNumber;
3477
3478    DBG("This=%p StreamNumber=%u pStreamData=%p OffsetInBytes=%u Stride=%u\n",
3479        This, StreamNumber, pStreamData, OffsetInBytes, Stride);
3480
3481    user_assert(StreamNumber < This->caps.MaxStreams, D3DERR_INVALIDCALL);
3482    user_assert(Stride <= This->caps.MaxStreamStride, D3DERR_INVALIDCALL);
3483
3484    if (likely(!This->is_recording)) {
3485        if (state->stream[i] == NineVertexBuffer9(pStreamData) &&
3486            state->vtxbuf[i].stride == Stride &&
3487            state->vtxbuf[i].buffer_offset == OffsetInBytes)
3488            return D3D_OK;
3489    }
3490    nine_bind(&state->stream[i], pStreamData);
3491
3492    state->changed.vtxbuf |= 1 << StreamNumber;
3493
3494    if (pStreamData) {
3495        state->vtxbuf[i].stride = Stride;
3496        state->vtxbuf[i].buffer_offset = OffsetInBytes;
3497    }
3498    state->vtxbuf[i].buffer = pStreamData ? pVBuf9->base.resource : NULL;
3499
3500    return D3D_OK;
3501}
3502
3503HRESULT WINAPI
3504NineDevice9_GetStreamSource( struct NineDevice9 *This,
3505                             UINT StreamNumber,
3506                             IDirect3DVertexBuffer9 **ppStreamData,
3507                             UINT *pOffsetInBytes,
3508                             UINT *pStride )
3509{
3510    const struct nine_state *state = &This->state;
3511    const unsigned i = StreamNumber;
3512
3513    user_assert(StreamNumber < This->caps.MaxStreams, D3DERR_INVALIDCALL);
3514    user_assert(ppStreamData, D3DERR_INVALIDCALL);
3515
3516    nine_reference_set(ppStreamData, state->stream[i]);
3517    *pStride = state->vtxbuf[i].stride;
3518    *pOffsetInBytes = state->vtxbuf[i].buffer_offset;
3519
3520    return D3D_OK;
3521}
3522
3523HRESULT WINAPI
3524NineDevice9_SetStreamSourceFreq( struct NineDevice9 *This,
3525                                 UINT StreamNumber,
3526                                 UINT Setting )
3527{
3528    struct nine_state *state = This->update;
3529    /* const UINT freq = Setting & 0x7FFFFF; */
3530
3531    DBG("This=%p StreamNumber=%u FrequencyParameter=0x%x\n", This,
3532        StreamNumber, Setting);
3533
3534    user_assert(StreamNumber < This->caps.MaxStreams, D3DERR_INVALIDCALL);
3535    user_assert(StreamNumber != 0 || !(Setting & D3DSTREAMSOURCE_INSTANCEDATA),
3536                D3DERR_INVALIDCALL);
3537    user_assert(!((Setting & D3DSTREAMSOURCE_INSTANCEDATA) &&
3538                  (Setting & D3DSTREAMSOURCE_INDEXEDDATA)), D3DERR_INVALIDCALL);
3539    user_assert(Setting, D3DERR_INVALIDCALL);
3540
3541    state->stream_freq[StreamNumber] = Setting;
3542
3543    if (Setting & D3DSTREAMSOURCE_INSTANCEDATA)
3544        state->stream_instancedata_mask |= 1 << StreamNumber;
3545    else
3546        state->stream_instancedata_mask &= ~(1 << StreamNumber);
3547
3548    state->changed.stream_freq |= 1 << StreamNumber;
3549    return D3D_OK;
3550}
3551
3552HRESULT WINAPI
3553NineDevice9_GetStreamSourceFreq( struct NineDevice9 *This,
3554                                 UINT StreamNumber,
3555                                 UINT *pSetting )
3556{
3557    user_assert(StreamNumber < This->caps.MaxStreams, D3DERR_INVALIDCALL);
3558    *pSetting = This->state.stream_freq[StreamNumber];
3559    return D3D_OK;
3560}
3561
3562HRESULT WINAPI
3563NineDevice9_SetIndices( struct NineDevice9 *This,
3564                        IDirect3DIndexBuffer9 *pIndexData )
3565{
3566    struct nine_state *state = This->update;
3567
3568    DBG("This=%p pIndexData=%p\n", This, pIndexData);
3569
3570    if (likely(!This->is_recording))
3571        if (state->idxbuf == NineIndexBuffer9(pIndexData))
3572            return D3D_OK;
3573    nine_bind(&state->idxbuf, pIndexData);
3574
3575    state->changed.group |= NINE_STATE_IDXBUF;
3576
3577    return D3D_OK;
3578}
3579
3580/* XXX: wine/d3d9 doesn't have pBaseVertexIndex, and it doesn't make sense
3581 * here because it's an argument passed to the Draw calls.
3582 */
3583HRESULT WINAPI
3584NineDevice9_GetIndices( struct NineDevice9 *This,
3585                        IDirect3DIndexBuffer9 **ppIndexData /*,
3586                        UINT *pBaseVertexIndex */ )
3587{
3588    user_assert(ppIndexData, D3DERR_INVALIDCALL);
3589    nine_reference_set(ppIndexData, This->state.idxbuf);
3590    return D3D_OK;
3591}
3592
3593HRESULT WINAPI
3594NineDevice9_CreatePixelShader( struct NineDevice9 *This,
3595                               const DWORD *pFunction,
3596                               IDirect3DPixelShader9 **ppShader )
3597{
3598    struct NinePixelShader9 *ps;
3599    HRESULT hr;
3600
3601    DBG("This=%p pFunction=%p ppShader=%p\n", This, pFunction, ppShader);
3602
3603    hr = NinePixelShader9_new(This, &ps, pFunction, NULL);
3604    if (FAILED(hr))
3605        return hr;
3606    *ppShader = (IDirect3DPixelShader9 *)ps;
3607    return D3D_OK;
3608}
3609
3610HRESULT WINAPI
3611NineDevice9_SetPixelShader( struct NineDevice9 *This,
3612                            IDirect3DPixelShader9 *pShader )
3613{
3614    struct nine_state *state = This->update;
3615    unsigned old_mask = state->ps ? state->ps->rt_mask : 1;
3616    unsigned mask;
3617
3618    DBG("This=%p pShader=%p\n", This, pShader);
3619
3620    if (!This->is_recording && state->ps == (struct NinePixelShader9*)pShader)
3621      return D3D_OK;
3622
3623    /* ff -> non-ff: commit back non-ff constants */
3624    if (!state->ps && pShader)
3625        state->commit |= NINE_STATE_COMMIT_CONST_PS;
3626
3627    nine_bind(&state->ps, pShader);
3628
3629    state->changed.group |= NINE_STATE_PS;
3630
3631    mask = state->ps ? state->ps->rt_mask : 1;
3632    /* We need to update cbufs if the pixel shader would
3633     * write to different render targets */
3634    if (mask != old_mask)
3635        state->changed.group |= NINE_STATE_FB;
3636
3637    return D3D_OK;
3638}
3639
3640HRESULT WINAPI
3641NineDevice9_GetPixelShader( struct NineDevice9 *This,
3642                            IDirect3DPixelShader9 **ppShader )
3643{
3644    user_assert(ppShader, D3DERR_INVALIDCALL);
3645    nine_reference_set(ppShader, This->state.ps);
3646    return D3D_OK;
3647}
3648
3649HRESULT WINAPI
3650NineDevice9_SetPixelShaderConstantF( struct NineDevice9 *This,
3651                                     UINT StartRegister,
3652                                     const float *pConstantData,
3653                                     UINT Vector4fCount )
3654{
3655    struct nine_state *state = This->update;
3656
3657    DBG("This=%p StartRegister=%u pConstantData=%p Vector4fCount=%u\n",
3658        This, StartRegister, pConstantData, Vector4fCount);
3659
3660    user_assert(StartRegister                  < NINE_MAX_CONST_F_PS3, D3DERR_INVALIDCALL);
3661    user_assert(StartRegister + Vector4fCount <= NINE_MAX_CONST_F_PS3, D3DERR_INVALIDCALL);
3662
3663    if (!Vector4fCount)
3664       return D3D_OK;
3665    user_assert(pConstantData, D3DERR_INVALIDCALL);
3666
3667    if (!This->is_recording) {
3668        if (!memcmp(&state->ps_const_f[StartRegister * 4], pConstantData,
3669                    Vector4fCount * 4 * sizeof(state->ps_const_f[0])))
3670            return D3D_OK;
3671    }
3672
3673    memcpy(&state->ps_const_f[StartRegister * 4],
3674           pConstantData,
3675           Vector4fCount * 4 * sizeof(state->ps_const_f[0]));
3676
3677    nine_ranges_insert(&state->changed.ps_const_f,
3678                       StartRegister, StartRegister + Vector4fCount,
3679                       &This->range_pool);
3680
3681    state->changed.group |= NINE_STATE_PS_CONST;
3682
3683    return D3D_OK;
3684}
3685
3686HRESULT WINAPI
3687NineDevice9_GetPixelShaderConstantF( struct NineDevice9 *This,
3688                                     UINT StartRegister,
3689                                     float *pConstantData,
3690                                     UINT Vector4fCount )
3691{
3692    const struct nine_state *state = &This->state;
3693
3694    user_assert(StartRegister                  < NINE_MAX_CONST_F_PS3, D3DERR_INVALIDCALL);
3695    user_assert(StartRegister + Vector4fCount <= NINE_MAX_CONST_F_PS3, D3DERR_INVALIDCALL);
3696    user_assert(pConstantData, D3DERR_INVALIDCALL);
3697
3698    memcpy(pConstantData,
3699           &state->ps_const_f[StartRegister * 4],
3700           Vector4fCount * 4 * sizeof(state->ps_const_f[0]));
3701
3702    return D3D_OK;
3703}
3704
3705HRESULT WINAPI
3706NineDevice9_SetPixelShaderConstantI( struct NineDevice9 *This,
3707                                     UINT StartRegister,
3708                                     const int *pConstantData,
3709                                     UINT Vector4iCount )
3710{
3711    struct nine_state *state = This->update;
3712    int i;
3713
3714    DBG("This=%p StartRegister=%u pConstantData=%p Vector4iCount=%u\n",
3715        This, StartRegister, pConstantData, Vector4iCount);
3716
3717    user_assert(StartRegister                  < NINE_MAX_CONST_I, D3DERR_INVALIDCALL);
3718    user_assert(StartRegister + Vector4iCount <= NINE_MAX_CONST_I, D3DERR_INVALIDCALL);
3719    user_assert(pConstantData, D3DERR_INVALIDCALL);
3720
3721    if (This->driver_caps.ps_integer) {
3722        if (!This->is_recording) {
3723            if (!memcmp(&state->ps_const_i[StartRegister][0], pConstantData,
3724                        Vector4iCount * sizeof(state->ps_const_i[0])))
3725                return D3D_OK;
3726        }
3727        memcpy(&state->ps_const_i[StartRegister][0],
3728               pConstantData,
3729               Vector4iCount * sizeof(state->ps_const_i[0]));
3730    } else {
3731        for (i = 0; i < Vector4iCount; i++) {
3732            state->ps_const_i[StartRegister+i][0] = fui((float)(pConstantData[4*i]));
3733            state->ps_const_i[StartRegister+i][1] = fui((float)(pConstantData[4*i+1]));
3734            state->ps_const_i[StartRegister+i][2] = fui((float)(pConstantData[4*i+2]));
3735            state->ps_const_i[StartRegister+i][3] = fui((float)(pConstantData[4*i+3]));
3736        }
3737    }
3738    state->changed.ps_const_i |= ((1 << Vector4iCount) - 1) << StartRegister;
3739    state->changed.group |= NINE_STATE_PS_CONST;
3740
3741    return D3D_OK;
3742}
3743
3744HRESULT WINAPI
3745NineDevice9_GetPixelShaderConstantI( struct NineDevice9 *This,
3746                                     UINT StartRegister,
3747                                     int *pConstantData,
3748                                     UINT Vector4iCount )
3749{
3750    const struct nine_state *state = &This->state;
3751    int i;
3752
3753    user_assert(StartRegister                  < NINE_MAX_CONST_I, D3DERR_INVALIDCALL);
3754    user_assert(StartRegister + Vector4iCount <= NINE_MAX_CONST_I, D3DERR_INVALIDCALL);
3755    user_assert(pConstantData, D3DERR_INVALIDCALL);
3756
3757    if (This->driver_caps.ps_integer) {
3758        memcpy(pConstantData,
3759               &state->ps_const_i[StartRegister][0],
3760               Vector4iCount * sizeof(state->ps_const_i[0]));
3761    } else {
3762        for (i = 0; i < Vector4iCount; i++) {
3763            pConstantData[4*i] = (int32_t) uif(state->ps_const_i[StartRegister+i][0]);
3764            pConstantData[4*i+1] = (int32_t) uif(state->ps_const_i[StartRegister+i][1]);
3765            pConstantData[4*i+2] = (int32_t) uif(state->ps_const_i[StartRegister+i][2]);
3766            pConstantData[4*i+3] = (int32_t) uif(state->ps_const_i[StartRegister+i][3]);
3767        }
3768    }
3769
3770    return D3D_OK;
3771}
3772
3773HRESULT WINAPI
3774NineDevice9_SetPixelShaderConstantB( struct NineDevice9 *This,
3775                                     UINT StartRegister,
3776                                     const BOOL *pConstantData,
3777                                     UINT BoolCount )
3778{
3779    struct nine_state *state = This->update;
3780    int i;
3781    uint32_t bool_true = This->driver_caps.ps_integer ? 0xFFFFFFFF : fui(1.0f);
3782
3783    DBG("This=%p StartRegister=%u pConstantData=%p BoolCount=%u\n",
3784        This, StartRegister, pConstantData, BoolCount);
3785
3786    user_assert(StartRegister              < NINE_MAX_CONST_B, D3DERR_INVALIDCALL);
3787    user_assert(StartRegister + BoolCount <= NINE_MAX_CONST_B, D3DERR_INVALIDCALL);
3788    user_assert(pConstantData, D3DERR_INVALIDCALL);
3789
3790    if (!This->is_recording) {
3791        bool noChange = true;
3792        for (i = 0; i < BoolCount; i++) {
3793            if (!!state->ps_const_b[StartRegister + i] != !!pConstantData[i])
3794              noChange = false;
3795        }
3796        if (noChange)
3797            return D3D_OK;
3798    }
3799
3800    for (i = 0; i < BoolCount; i++)
3801        state->ps_const_b[StartRegister + i] = pConstantData[i] ? bool_true : 0;
3802
3803    state->changed.ps_const_b |= ((1 << BoolCount) - 1) << StartRegister;
3804    state->changed.group |= NINE_STATE_PS_CONST;
3805
3806    return D3D_OK;
3807}
3808
3809HRESULT WINAPI
3810NineDevice9_GetPixelShaderConstantB( struct NineDevice9 *This,
3811                                     UINT StartRegister,
3812                                     BOOL *pConstantData,
3813                                     UINT BoolCount )
3814{
3815    const struct nine_state *state = &This->state;
3816    int i;
3817
3818    user_assert(StartRegister              < NINE_MAX_CONST_B, D3DERR_INVALIDCALL);
3819    user_assert(StartRegister + BoolCount <= NINE_MAX_CONST_B, D3DERR_INVALIDCALL);
3820    user_assert(pConstantData, D3DERR_INVALIDCALL);
3821
3822    for (i = 0; i < BoolCount; i++)
3823        pConstantData[i] = state->ps_const_b[StartRegister + i] ? TRUE : FALSE;
3824
3825    return D3D_OK;
3826}
3827
3828HRESULT WINAPI
3829NineDevice9_DrawRectPatch( struct NineDevice9 *This,
3830                           UINT Handle,
3831                           const float *pNumSegs,
3832                           const D3DRECTPATCH_INFO *pRectPatchInfo )
3833{
3834    STUB(D3DERR_INVALIDCALL);
3835}
3836
3837HRESULT WINAPI
3838NineDevice9_DrawTriPatch( struct NineDevice9 *This,
3839                          UINT Handle,
3840                          const float *pNumSegs,
3841                          const D3DTRIPATCH_INFO *pTriPatchInfo )
3842{
3843    STUB(D3DERR_INVALIDCALL);
3844}
3845
3846HRESULT WINAPI
3847NineDevice9_DeletePatch( struct NineDevice9 *This,
3848                         UINT Handle )
3849{
3850    STUB(D3DERR_INVALIDCALL);
3851}
3852
3853HRESULT WINAPI
3854NineDevice9_CreateQuery( struct NineDevice9 *This,
3855                         D3DQUERYTYPE Type,
3856                         IDirect3DQuery9 **ppQuery )
3857{
3858    struct NineQuery9 *query;
3859    HRESULT hr;
3860
3861    DBG("This=%p Type=%d ppQuery=%p\n", This, Type, ppQuery);
3862
3863    hr = nine_is_query_supported(This->screen, Type);
3864    if (!ppQuery || hr != D3D_OK)
3865        return hr;
3866
3867    hr = NineQuery9_new(This, &query, Type);
3868    if (FAILED(hr))
3869        return hr;
3870    *ppQuery = (IDirect3DQuery9 *)query;
3871    return D3D_OK;
3872}
3873
3874IDirect3DDevice9Vtbl NineDevice9_vtable = {
3875    (void *)NineUnknown_QueryInterface,
3876    (void *)NineUnknown_AddRef,
3877    (void *)NineUnknown_Release,
3878    (void *)NineDevice9_TestCooperativeLevel,
3879    (void *)NineDevice9_GetAvailableTextureMem,
3880    (void *)NineDevice9_EvictManagedResources,
3881    (void *)NineDevice9_GetDirect3D,
3882    (void *)NineDevice9_GetDeviceCaps,
3883    (void *)NineDevice9_GetDisplayMode,
3884    (void *)NineDevice9_GetCreationParameters,
3885    (void *)NineDevice9_SetCursorProperties,
3886    (void *)NineDevice9_SetCursorPosition,
3887    (void *)NineDevice9_ShowCursor,
3888    (void *)NineDevice9_CreateAdditionalSwapChain,
3889    (void *)NineDevice9_GetSwapChain,
3890    (void *)NineDevice9_GetNumberOfSwapChains,
3891    (void *)NineDevice9_Reset,
3892    (void *)NineDevice9_Present,
3893    (void *)NineDevice9_GetBackBuffer,
3894    (void *)NineDevice9_GetRasterStatus,
3895    (void *)NineDevice9_SetDialogBoxMode,
3896    (void *)NineDevice9_SetGammaRamp,
3897    (void *)NineDevice9_GetGammaRamp,
3898    (void *)NineDevice9_CreateTexture,
3899    (void *)NineDevice9_CreateVolumeTexture,
3900    (void *)NineDevice9_CreateCubeTexture,
3901    (void *)NineDevice9_CreateVertexBuffer,
3902    (void *)NineDevice9_CreateIndexBuffer,
3903    (void *)NineDevice9_CreateRenderTarget,
3904    (void *)NineDevice9_CreateDepthStencilSurface,
3905    (void *)NineDevice9_UpdateSurface,
3906    (void *)NineDevice9_UpdateTexture,
3907    (void *)NineDevice9_GetRenderTargetData,
3908    (void *)NineDevice9_GetFrontBufferData,
3909    (void *)NineDevice9_StretchRect,
3910    (void *)NineDevice9_ColorFill,
3911    (void *)NineDevice9_CreateOffscreenPlainSurface,
3912    (void *)NineDevice9_SetRenderTarget,
3913    (void *)NineDevice9_GetRenderTarget,
3914    (void *)NineDevice9_SetDepthStencilSurface,
3915    (void *)NineDevice9_GetDepthStencilSurface,
3916    (void *)NineDevice9_BeginScene,
3917    (void *)NineDevice9_EndScene,
3918    (void *)NineDevice9_Clear,
3919    (void *)NineDevice9_SetTransform,
3920    (void *)NineDevice9_GetTransform,
3921    (void *)NineDevice9_MultiplyTransform,
3922    (void *)NineDevice9_SetViewport,
3923    (void *)NineDevice9_GetViewport,
3924    (void *)NineDevice9_SetMaterial,
3925    (void *)NineDevice9_GetMaterial,
3926    (void *)NineDevice9_SetLight,
3927    (void *)NineDevice9_GetLight,
3928    (void *)NineDevice9_LightEnable,
3929    (void *)NineDevice9_GetLightEnable,
3930    (void *)NineDevice9_SetClipPlane,
3931    (void *)NineDevice9_GetClipPlane,
3932    (void *)NineDevice9_SetRenderState,
3933    (void *)NineDevice9_GetRenderState,
3934    (void *)NineDevice9_CreateStateBlock,
3935    (void *)NineDevice9_BeginStateBlock,
3936    (void *)NineDevice9_EndStateBlock,
3937    (void *)NineDevice9_SetClipStatus,
3938    (void *)NineDevice9_GetClipStatus,
3939    (void *)NineDevice9_GetTexture,
3940    (void *)NineDevice9_SetTexture,
3941    (void *)NineDevice9_GetTextureStageState,
3942    (void *)NineDevice9_SetTextureStageState,
3943    (void *)NineDevice9_GetSamplerState,
3944    (void *)NineDevice9_SetSamplerState,
3945    (void *)NineDevice9_ValidateDevice,
3946    (void *)NineDevice9_SetPaletteEntries,
3947    (void *)NineDevice9_GetPaletteEntries,
3948    (void *)NineDevice9_SetCurrentTexturePalette,
3949    (void *)NineDevice9_GetCurrentTexturePalette,
3950    (void *)NineDevice9_SetScissorRect,
3951    (void *)NineDevice9_GetScissorRect,
3952    (void *)NineDevice9_SetSoftwareVertexProcessing,
3953    (void *)NineDevice9_GetSoftwareVertexProcessing,
3954    (void *)NineDevice9_SetNPatchMode,
3955    (void *)NineDevice9_GetNPatchMode,
3956    (void *)NineDevice9_DrawPrimitive,
3957    (void *)NineDevice9_DrawIndexedPrimitive,
3958    (void *)NineDevice9_DrawPrimitiveUP,
3959    (void *)NineDevice9_DrawIndexedPrimitiveUP,
3960    (void *)NineDevice9_ProcessVertices,
3961    (void *)NineDevice9_CreateVertexDeclaration,
3962    (void *)NineDevice9_SetVertexDeclaration,
3963    (void *)NineDevice9_GetVertexDeclaration,
3964    (void *)NineDevice9_SetFVF,
3965    (void *)NineDevice9_GetFVF,
3966    (void *)NineDevice9_CreateVertexShader,
3967    (void *)NineDevice9_SetVertexShader,
3968    (void *)NineDevice9_GetVertexShader,
3969    (void *)NineDevice9_SetVertexShaderConstantF,
3970    (void *)NineDevice9_GetVertexShaderConstantF,
3971    (void *)NineDevice9_SetVertexShaderConstantI,
3972    (void *)NineDevice9_GetVertexShaderConstantI,
3973    (void *)NineDevice9_SetVertexShaderConstantB,
3974    (void *)NineDevice9_GetVertexShaderConstantB,
3975    (void *)NineDevice9_SetStreamSource,
3976    (void *)NineDevice9_GetStreamSource,
3977    (void *)NineDevice9_SetStreamSourceFreq,
3978    (void *)NineDevice9_GetStreamSourceFreq,
3979    (void *)NineDevice9_SetIndices,
3980    (void *)NineDevice9_GetIndices,
3981    (void *)NineDevice9_CreatePixelShader,
3982    (void *)NineDevice9_SetPixelShader,
3983    (void *)NineDevice9_GetPixelShader,
3984    (void *)NineDevice9_SetPixelShaderConstantF,
3985    (void *)NineDevice9_GetPixelShaderConstantF,
3986    (void *)NineDevice9_SetPixelShaderConstantI,
3987    (void *)NineDevice9_GetPixelShaderConstantI,
3988    (void *)NineDevice9_SetPixelShaderConstantB,
3989    (void *)NineDevice9_GetPixelShaderConstantB,
3990    (void *)NineDevice9_DrawRectPatch,
3991    (void *)NineDevice9_DrawTriPatch,
3992    (void *)NineDevice9_DeletePatch,
3993    (void *)NineDevice9_CreateQuery
3994};
3995
3996static const GUID *NineDevice9_IIDs[] = {
3997    &IID_IDirect3DDevice9,
3998    &IID_IUnknown,
3999    NULL
4000};
4001
4002HRESULT
4003NineDevice9_new( struct pipe_screen *pScreen,
4004                 D3DDEVICE_CREATION_PARAMETERS *pCreationParameters,
4005                 D3DCAPS9 *pCaps,
4006                 D3DPRESENT_PARAMETERS *pPresentationParameters,
4007                 IDirect3D9 *pD3D9,
4008                 ID3DPresentGroup *pPresentationGroup,
4009                 struct d3dadapter9_context *pCTX,
4010                 boolean ex,
4011                 D3DDISPLAYMODEEX *pFullscreenDisplayMode,
4012                 struct NineDevice9 **ppOut )
4013{
4014    BOOL lock;
4015    lock = !!(pCreationParameters->BehaviorFlags & D3DCREATE_MULTITHREADED);
4016
4017    NINE_NEW(Device9, ppOut, lock, /* args */
4018             pScreen, pCreationParameters, pCaps,
4019             pPresentationParameters, pD3D9, pPresentationGroup, pCTX,
4020             ex, pFullscreenDisplayMode);
4021}
4022