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 "c99_alloca.h"
24
25#include "device9.h"
26#include "surface9.h"
27#include "texture9.h"
28#include "nine_helpers.h"
29#include "nine_memory_helper.h"
30#include "nine_pipe.h"
31#include "nine_dump.h"
32
33#include "pipe/p_state.h"
34#include "pipe/p_context.h"
35#include "pipe/p_screen.h"
36#include "util/u_inlines.h"
37#include "util/u_resource.h"
38
39#define DBG_CHANNEL DBG_TEXTURE
40
41static HRESULT
42NineTexture9_ctor( struct NineTexture9 *This,
43                   struct NineUnknownParams *pParams,
44                   UINT Width, UINT Height, UINT Levels,
45                   DWORD Usage,
46                   D3DFORMAT Format,
47                   D3DPOOL Pool,
48                   HANDLE *pSharedHandle )
49{
50    struct pipe_screen *screen = pParams->device->screen;
51    struct pipe_resource *info = &This->base.base.info;
52    enum pipe_format pf;
53    unsigned *level_offsets = NULL;
54    unsigned l;
55    D3DSURFACE_DESC sfdesc;
56    HRESULT hr;
57    struct nine_allocation *user_buffer = NULL, *user_buffer_for_level;
58
59    This->base.base.base.device = pParams->device; /* Early fill this field in case of failure */
60
61    DBG("(%p) Width=%u Height=%u Levels=%u Usage=%s Format=%s Pool=%s "
62        "pSharedHandle=%p\n", This, Width, Height, Levels,
63        nine_D3DUSAGE_to_str(Usage),
64        d3dformat_to_string(Format), nine_D3DPOOL_to_str(Pool), pSharedHandle);
65
66    user_assert(Width && Height, D3DERR_INVALIDCALL);
67
68    /* pSharedHandle: can be non-null for ex only.
69     * D3DPOOL_SYSTEMMEM: Levels must be 1
70     * D3DPOOL_DEFAULT: no restriction for Levels
71     * Other Pools are forbidden. */
72    user_assert(!pSharedHandle || pParams->device->ex, D3DERR_INVALIDCALL);
73    user_assert(!pSharedHandle ||
74                (Pool == D3DPOOL_SYSTEMMEM && Levels == 1) ||
75                Pool == D3DPOOL_DEFAULT, D3DERR_INVALIDCALL);
76
77    user_assert(!(Usage & D3DUSAGE_AUTOGENMIPMAP) ||
78                (Pool != D3DPOOL_SYSTEMMEM && Pool != D3DPOOL_SCRATCH && Levels <= 1),
79                D3DERR_INVALIDCALL);
80
81    /* TODO: implement pSharedHandle for D3DPOOL_DEFAULT (cross process
82     * buffer sharing).
83     *
84     * Gem names may have fit but they're depreciated and won't work on render-nodes.
85     * One solution is to use shm buffers. We would use a /dev/shm file, fill the first
86     * values to tell it is a nine buffer, the size, which function created it, etc,
87     * and then it would contain the data. The handle would be a number, corresponding to
88     * the file to read (/dev/shm/nine-share-4 for example would be 4).
89     *
90     * Wine just ignores the argument, which works only if the app creates the handle
91     * and won't use it. Instead of failing, we support that situation by putting an
92     * invalid handle, that we would fail to import. Please note that we don't advertise
93     * the flag indicating the support for that feature, but apps seem to not care.
94     */
95
96    if (pSharedHandle && Pool == D3DPOOL_DEFAULT) {
97        if (!*pSharedHandle) {
98            DBG("Creating Texture with invalid handle. Importing will fail\n.");
99            *pSharedHandle = (HANDLE)1; /* Wine would keep it NULL */
100            pSharedHandle = NULL;
101        } else {
102            ERR("Application tries to use cross-process sharing feature. Nine "
103                "doesn't support it");
104            return D3DERR_INVALIDCALL;
105        }
106    }
107
108    if (Usage & D3DUSAGE_AUTOGENMIPMAP)
109        Levels = 0;
110
111    pf = d3d9_to_pipe_format_checked(screen, Format, PIPE_TEXTURE_2D, 0,
112                                     PIPE_BIND_SAMPLER_VIEW, FALSE,
113                                     Pool == D3DPOOL_SCRATCH);
114
115    if (Format != D3DFMT_NULL && pf == PIPE_FORMAT_NONE)
116        return D3DERR_INVALIDCALL;
117
118    if (compressed_format(Format)) {
119        const unsigned w = util_format_get_blockwidth(pf);
120        const unsigned h = util_format_get_blockheight(pf);
121
122        user_assert(!(Width % w) && !(Height % h), D3DERR_INVALIDCALL);
123    }
124
125    info->screen = screen;
126    info->target = PIPE_TEXTURE_2D;
127    info->format = pf;
128    info->width0 = Width;
129    info->height0 = Height;
130    info->depth0 = 1;
131    if (Levels)
132        info->last_level = Levels - 1;
133    else
134        info->last_level = util_logbase2(MAX2(Width, Height));
135    info->array_size = 1;
136    info->nr_samples = 0;
137    info->nr_storage_samples = 0;
138    info->bind = PIPE_BIND_SAMPLER_VIEW;
139    info->usage = PIPE_USAGE_DEFAULT;
140    info->flags = 0;
141
142    if (Usage & D3DUSAGE_RENDERTARGET)
143        info->bind |= PIPE_BIND_RENDER_TARGET;
144    if (Usage & D3DUSAGE_DEPTHSTENCIL)
145        info->bind |= PIPE_BIND_DEPTH_STENCIL;
146
147    if (Usage & D3DUSAGE_DYNAMIC) {
148        info->usage = PIPE_USAGE_DYNAMIC;
149    }
150
151    if (Usage & D3DUSAGE_SOFTWAREPROCESSING)
152        DBG("Application asked for Software Vertex Processing, "
153            "but this is unimplemented\n");
154
155    hr = NineBaseTexture9_ctor(&This->base, pParams, NULL, D3DRTYPE_TEXTURE, Format, Pool, Usage);
156    if (FAILED(hr))
157        return hr;
158    This->base.pstype = (Height == 1) ? 1 : 0;
159
160    if (pSharedHandle && *pSharedHandle) { /* Pool == D3DPOOL_SYSTEMMEM */
161        user_buffer = nine_wrap_external_pointer(pParams->device->allocator, (void *)*pSharedHandle);
162        level_offsets = alloca(sizeof(unsigned) * This->base.level_count);
163        (void) nine_format_get_size_and_offsets(pf, level_offsets,
164                                                Width, Height,
165                                                This->base.level_count-1);
166    } else if (Pool != D3DPOOL_DEFAULT) {
167        level_offsets = alloca(sizeof(unsigned) * This->base.level_count);
168        user_buffer = nine_allocate(pParams->device->allocator,
169            nine_format_get_size_and_offsets(pf, level_offsets,
170                                             Width, Height,
171                                             This->base.level_count-1));
172        This->managed_buffer = user_buffer;
173        if (!This->managed_buffer)
174            return E_OUTOFMEMORY;
175    }
176
177    This->surfaces = CALLOC(This->base.level_count, sizeof(*This->surfaces));
178    if (!This->surfaces)
179        return E_OUTOFMEMORY;
180
181    /* Create all the surfaces right away.
182     * They manage backing storage, and transfers (LockRect) are deferred
183     * to them.
184     */
185    sfdesc.Format = Format;
186    sfdesc.Type = D3DRTYPE_SURFACE;
187    sfdesc.Usage = Usage;
188    sfdesc.Pool = Pool;
189    sfdesc.MultiSampleType = D3DMULTISAMPLE_NONE;
190    sfdesc.MultiSampleQuality = 0;
191
192    for (l = 0; l < This->base.level_count; ++l) {
193        sfdesc.Width = u_minify(Width, l);
194        sfdesc.Height = u_minify(Height, l);
195        /* Some apps expect the memory to be allocated in
196         * continous blocks */
197        user_buffer_for_level = user_buffer ?
198            nine_suballocate(pParams->device->allocator, user_buffer, level_offsets[l]) : NULL;
199
200        hr = NineSurface9_new(This->base.base.base.device, NineUnknown(This),
201                              This->base.base.resource, user_buffer_for_level,
202                              D3DRTYPE_TEXTURE, l, 0,
203                              &sfdesc, &This->surfaces[l]);
204        if (FAILED(hr))
205            return hr;
206    }
207
208    /* Textures start initially dirty */
209    This->dirty_rect.width = Width;
210    This->dirty_rect.height = Height;
211    This->dirty_rect.depth = 1; /* widht == 0 means empty, depth stays 1 */
212
213    if (pSharedHandle && !*pSharedHandle) {/* Pool == D3DPOOL_SYSTEMMEM */
214        *pSharedHandle = This->surfaces[0]->data;
215    }
216
217    return D3D_OK;
218}
219
220static void
221NineTexture9_dtor( struct NineTexture9 *This )
222{
223    bool is_worker = nine_context_is_worker(This->base.base.base.device);
224    unsigned l;
225
226    DBG("This=%p\n", This);
227
228    if (This->surfaces) {
229        /* The surfaces should have 0 references and be unbound now. */
230        for (l = 0; l < This->base.level_count; ++l)
231            if (This->surfaces[l])
232                NineUnknown_Destroy(&This->surfaces[l]->base.base);
233        FREE(This->surfaces);
234    }
235
236    if (This->managed_buffer) {
237        if (is_worker)
238            nine_free_worker(This->base.base.base.device->allocator, This->managed_buffer);
239        else
240            nine_free(This->base.base.base.device->allocator, This->managed_buffer);
241    }
242
243    NineBaseTexture9_dtor(&This->base);
244}
245
246HRESULT NINE_WINAPI
247NineTexture9_GetLevelDesc( struct NineTexture9 *This,
248                           UINT Level,
249                           D3DSURFACE_DESC *pDesc )
250{
251    DBG("This=%p Level=%d pDesc=%p\n", This, Level, pDesc);
252
253    user_assert(Level < This->base.level_count, D3DERR_INVALIDCALL);
254    user_assert(pDesc, D3DERR_INVALIDCALL);
255
256    *pDesc = This->surfaces[Level]->desc;
257
258    return D3D_OK;
259}
260
261HRESULT NINE_WINAPI
262NineTexture9_GetSurfaceLevel( struct NineTexture9 *This,
263                              UINT Level,
264                              IDirect3DSurface9 **ppSurfaceLevel )
265{
266    DBG("This=%p Level=%d ppSurfaceLevel=%p\n", This, Level, ppSurfaceLevel);
267
268    user_assert(Level < This->base.level_count, D3DERR_INVALIDCALL);
269    user_assert(ppSurfaceLevel, D3DERR_INVALIDCALL);
270
271    NineUnknown_AddRef(NineUnknown(This->surfaces[Level]));
272    *ppSurfaceLevel = (IDirect3DSurface9 *)This->surfaces[Level];
273
274    return D3D_OK;
275}
276
277HRESULT NINE_WINAPI
278NineTexture9_LockRect( struct NineTexture9 *This,
279                       UINT Level,
280                       D3DLOCKED_RECT *pLockedRect,
281                       const RECT *pRect,
282                       DWORD Flags )
283{
284    DBG("This=%p Level=%u pLockedRect=%p pRect=%p Flags=%d\n",
285        This, Level, pLockedRect, pRect, Flags);
286
287    user_assert(Level < This->base.level_count, D3DERR_INVALIDCALL);
288
289    return NineSurface9_LockRect(This->surfaces[Level], pLockedRect,
290                                 pRect, Flags);
291}
292
293HRESULT NINE_WINAPI
294NineTexture9_UnlockRect( struct NineTexture9 *This,
295                         UINT Level )
296{
297    DBG("This=%p Level=%u\n", This, Level);
298
299    user_assert(Level < This->base.level_count, D3DERR_INVALIDCALL);
300
301    return NineSurface9_UnlockRect(This->surfaces[Level]);
302}
303
304HRESULT NINE_WINAPI
305NineTexture9_AddDirtyRect( struct NineTexture9 *This,
306                           const RECT *pDirtyRect )
307{
308    DBG("This=%p pDirtyRect=%p[(%u,%u)-(%u,%u)]\n", This, pDirtyRect,
309        pDirtyRect ? pDirtyRect->left : 0, pDirtyRect ? pDirtyRect->top : 0,
310        pDirtyRect ? pDirtyRect->right : 0, pDirtyRect ? pDirtyRect->bottom : 0);
311
312    /* Tracking dirty regions on DEFAULT resources is pointless,
313     * because we always write to the final storage. Just marked it dirty in
314     * case we need to generate mip maps.
315     */
316    if (This->base.base.pool == D3DPOOL_DEFAULT) {
317        if (This->base.base.usage & D3DUSAGE_AUTOGENMIPMAP) {
318            This->base.dirty_mip = TRUE;
319            BASETEX_REGISTER_UPDATE(&This->base);
320        }
321        return D3D_OK;
322    }
323
324    if (This->base.base.pool == D3DPOOL_MANAGED) {
325        This->base.managed.dirty = TRUE;
326        BASETEX_REGISTER_UPDATE(&This->base);
327    }
328
329    if (!pDirtyRect) {
330        u_box_origin_2d(This->base.base.info.width0,
331                        This->base.base.info.height0, &This->dirty_rect);
332    } else {
333        if (This->dirty_rect.width == 0) {
334            rect_to_pipe_box_clamp(&This->dirty_rect, pDirtyRect);
335        } else {
336            struct pipe_box box;
337            rect_to_pipe_box_clamp(&box, pDirtyRect);
338            u_box_union_2d(&This->dirty_rect, &This->dirty_rect, &box);
339        }
340        (void) u_box_clip_2d(&This->dirty_rect, &This->dirty_rect,
341                             This->base.base.info.width0,
342                             This->base.base.info.height0);
343    }
344    return D3D_OK;
345}
346
347IDirect3DTexture9Vtbl NineTexture9_vtable = {
348    (void *)NineUnknown_QueryInterface,
349    (void *)NineUnknown_AddRef,
350    (void *)NineUnknown_Release,
351    (void *)NineUnknown_GetDevice, /* actually part of Resource9 iface */
352    (void *)NineUnknown_SetPrivateData,
353    (void *)NineUnknown_GetPrivateData,
354    (void *)NineUnknown_FreePrivateData,
355    (void *)NineResource9_SetPriority,
356    (void *)NineResource9_GetPriority,
357    (void *)NineBaseTexture9_PreLoad,
358    (void *)NineResource9_GetType,
359    (void *)NineBaseTexture9_SetLOD,
360    (void *)NineBaseTexture9_GetLOD,
361    (void *)NineBaseTexture9_GetLevelCount,
362    (void *)NineBaseTexture9_SetAutoGenFilterType,
363    (void *)NineBaseTexture9_GetAutoGenFilterType,
364    (void *)NineBaseTexture9_GenerateMipSubLevels,
365    (void *)NineTexture9_GetLevelDesc,
366    (void *)NineTexture9_GetSurfaceLevel,
367    (void *)NineTexture9_LockRect,
368    (void *)NineTexture9_UnlockRect,
369    (void *)NineTexture9_AddDirtyRect
370};
371
372static const GUID *NineTexture9_IIDs[] = {
373    &IID_IDirect3DTexture9,
374    &IID_IDirect3DBaseTexture9,
375    &IID_IDirect3DResource9,
376    &IID_IUnknown,
377    NULL
378};
379
380HRESULT
381NineTexture9_new( struct NineDevice9 *pDevice,
382                  UINT Width, UINT Height, UINT Levels,
383                  DWORD Usage,
384                  D3DFORMAT Format,
385                  D3DPOOL Pool,
386                  struct NineTexture9 **ppOut,
387                  HANDLE *pSharedHandle )
388{
389    NINE_DEVICE_CHILD_NEW(Texture9, ppOut, pDevice,
390                          Width, Height, Levels,
391                          Usage, Format, Pool, pSharedHandle);
392}
393