dsound: Add support for 24/32 bits input sound buffers.
[wine] / dlls / wined3d / vertexbuffer.c
1 /*
2  * IWineD3DVertexBuffer Implementation
3  *
4  * Copyright 2002-2005 Jason Edmeades
5  *                     Raphael Junqueira
6  * Copyright 2004 Christian Costa
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  */
22
23 #include "config.h"
24 #include "wined3d_private.h"
25
26 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
27 #define GLINFO_LOCATION This->resource.wineD3DDevice->adapter->gl_info
28
29 #define VB_MAXDECLCHANGES     100     /* After that number we stop converting */
30 #define VB_RESETDECLCHANGE    1000    /* Reset the changecount after that number of draws */
31
32 /* *******************************************
33    IWineD3DVertexBuffer IUnknown parts follow
34    ******************************************* */
35 static HRESULT WINAPI IWineD3DVertexBufferImpl_QueryInterface(IWineD3DVertexBuffer *iface, REFIID riid, LPVOID *ppobj)
36 {
37     IWineD3DVertexBufferImpl *This = (IWineD3DVertexBufferImpl *)iface;
38     TRACE("(%p)->(%s,%p)\n",This,debugstr_guid(riid),ppobj);
39     if (IsEqualGUID(riid, &IID_IUnknown)
40         || IsEqualGUID(riid, &IID_IWineD3DBase)
41         || IsEqualGUID(riid, &IID_IWineD3DResource)
42         || IsEqualGUID(riid, &IID_IWineD3DVertexBuffer)){
43         IUnknown_AddRef(iface);
44         *ppobj = This;
45         return S_OK;
46     }
47     *ppobj = NULL;
48     return E_NOINTERFACE;
49 }
50
51 static ULONG WINAPI IWineD3DVertexBufferImpl_AddRef(IWineD3DVertexBuffer *iface) {
52     IWineD3DVertexBufferImpl *This = (IWineD3DVertexBufferImpl *)iface;
53     ULONG ref = InterlockedIncrement(&This->resource.ref);
54     TRACE("(%p) : AddRef increasing from %d\n", This, ref - 1);
55     return ref;
56 }
57
58 static ULONG WINAPI IWineD3DVertexBufferImpl_Release(IWineD3DVertexBuffer *iface) {
59     IWineD3DVertexBufferImpl *This = (IWineD3DVertexBufferImpl *)iface;
60     ULONG ref = InterlockedDecrement(&This->resource.ref);
61     TRACE("(%p) : Releasing from %d\n", This, ref + 1);
62     if (ref == 0) {
63
64         if(This->vbo) {
65             IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
66
67             ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
68             ENTER_GL();
69             GL_EXTCALL(glDeleteBuffersARB(1, &This->vbo));
70             checkGLcall("glDeleteBuffersARB");
71             LEAVE_GL();
72         }
73
74         IWineD3DResourceImpl_CleanUp((IWineD3DResource *)iface);
75         HeapFree(GetProcessHeap(), 0, This);
76     }
77     return ref;
78 }
79
80 /* ****************************************************
81    IWineD3DVertexBuffer IWineD3DResource parts follow
82    **************************************************** */
83 static HRESULT WINAPI IWineD3DVertexBufferImpl_GetDevice(IWineD3DVertexBuffer *iface, IWineD3DDevice** ppDevice) {
84     return IWineD3DResourceImpl_GetDevice((IWineD3DResource *)iface, ppDevice);
85 }
86
87 static HRESULT WINAPI IWineD3DVertexBufferImpl_SetPrivateData(IWineD3DVertexBuffer *iface, REFGUID refguid, CONST void* pData, DWORD SizeOfData, DWORD Flags) {
88     return IWineD3DResourceImpl_SetPrivateData((IWineD3DResource *)iface, refguid, pData, SizeOfData, Flags);
89 }
90
91 static HRESULT WINAPI IWineD3DVertexBufferImpl_GetPrivateData(IWineD3DVertexBuffer *iface, REFGUID refguid, void* pData, DWORD* pSizeOfData) {
92     return IWineD3DResourceImpl_GetPrivateData((IWineD3DResource *)iface, refguid, pData, pSizeOfData);
93 }
94
95 static HRESULT WINAPI IWineD3DVertexBufferImpl_FreePrivateData(IWineD3DVertexBuffer *iface, REFGUID refguid) {
96     return IWineD3DResourceImpl_FreePrivateData((IWineD3DResource *)iface, refguid);
97 }
98
99 static DWORD    WINAPI IWineD3DVertexBufferImpl_SetPriority(IWineD3DVertexBuffer *iface, DWORD PriorityNew) {
100     return IWineD3DResourceImpl_SetPriority((IWineD3DResource *)iface, PriorityNew);
101 }
102
103 static DWORD    WINAPI IWineD3DVertexBufferImpl_GetPriority(IWineD3DVertexBuffer *iface) {
104     return IWineD3DResourceImpl_GetPriority((IWineD3DResource *)iface);
105 }
106
107 static void fixup_vertices(
108         BYTE *src, BYTE *dst,
109         int stride,
110         int num,
111         int pos, BOOL haspos,
112         int diffuse, BOOL hasdiffuse,
113         int specular, BOOL hasspecular
114 ) {
115     int i;
116     float x, y, z, w;
117
118     for(i = num - 1; i >= 0; i--) {
119         if(haspos) {
120             float *p = (float *) ((src + pos) + i * stride);
121
122             /* rhw conversion like in drawStridedSlow */
123             if(p[3] == 1.0 || ((p[3] < eps) && (p[3] > -eps))) {
124                 x = p[0];
125                 y = p[1];
126                 z = p[2];
127                 w = 1.0;
128             } else {
129                 w = 1.0 / p[3];
130                 x = p[0] * w;
131                 y = p[1] * w;
132                 z = p[2] * w;
133             }
134             p = (float *) (dst + i * stride + pos);
135             p[0] = x;
136             p[1] = y;
137             p[2] = z;
138             p[3] = w;
139         }
140         if(hasdiffuse) {
141             DWORD srcColor, *dstColor = (DWORD *) (dst + i * stride + diffuse);
142             srcColor = * (DWORD *) ( (src + diffuse) + i * stride);
143
144             /* Color conversion like in drawStridedSlow. watch out for little endianity
145             * If we want that stuff to work on big endian machines too we have to consider more things
146             *
147             * 0xff000000: Alpha mask
148             * 0x00ff0000: Blue mask
149             * 0x0000ff00: Green mask
150             * 0x000000ff: Red mask
151             */
152
153             *dstColor = 0;
154             *dstColor |= (srcColor & 0xff00ff00)      ;   /* Alpha Green */
155             *dstColor |= (srcColor & 0x00ff0000) >> 16;   /* Red */
156             *dstColor |= (srcColor & 0x000000ff) << 16;   /* Blue */
157         }
158         if(hasspecular) {
159             DWORD srcColor, *dstColor = (DWORD *) (dst + i * stride + specular);
160             srcColor = * (DWORD *) ( (src + specular) + i * stride);
161
162             /* Similar to diffuse
163              * TODO: Write the alpha value out for fog coords
164              */
165             *dstColor = 0;
166             *dstColor |= (srcColor & 0xff00ff00)      ;   /* Alpha Green */
167             *dstColor |= (srcColor & 0x00ff0000) >> 16;   /* Red */
168             *dstColor |= (srcColor & 0x000000ff) << 16;   /* Blue */
169         }
170     }
171 }
172
173 inline BOOL WINAPI IWineD3DVertexBufferImpl_FindDecl(IWineD3DVertexBufferImpl *This)
174 {
175     WineDirect3DVertexStridedData strided;
176     IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
177
178     /* In d3d7 the vertex buffer declaration NEVER changes because it is stored in the d3d7 vertex buffer.
179      * Once we have our declaration there is no need to look it up again.
180      */
181     if(((IWineD3DImpl *)device->wineD3D)->dxVersion == 7 && This->Flags & VBFLAG_HASDESC) {
182         return FALSE;
183     }
184
185     /* There are certain vertex data types that need to be fixed up. The Vertex Buffers FVF doesn't
186      * help finding them, only the vertex declaration or the device FVF can determine that at drawPrim
187      * time. Rules are as follows:
188      *
189      * -> No modification when Vertex Shaders are used
190      * -> Fix up position1 and position 2 if they are XYZRHW
191      * -> Fix up diffuse color
192      * -> Fix up specular color
193      *
194      * The Declaration is only known at drawing time, and it can change from draw to draw. If any converted values
195      * are changed, the whole buffer has to be reconverted and reloaded. (Converting is SLOW, so if this happens too
196      * often PreLoad stops converting entirely and falls back to drawStridedSlow).
197      *
198      * Reconvert if:
199      * -> New semantics that have to be converted appear
200      * -> The position of semantics that have to be converted changes
201      * -> The stride of the vertex changed AND there is stuff that needs conversion
202      * -> (If a vertex shader is bound and in use assume that nothing that needs conversion is there)
203      *
204      * Return values:
205      *  TRUE: Reload is needed
206      *  FALSE: otherwise
207      */
208
209     if (use_vs(device)) {
210         /* Assume no conversion */
211         memset(&strided, 0, sizeof(strided));
212     } else {
213         /* we need a copy because we modify some params */
214         memcpy(&strided, &device->strided_streams, sizeof(strided));
215
216         /* Filter out data that does not come from this VBO */
217         if(strided.u.s.position.VBO != This->vbo)    memset(&strided.u.s.position, 0, sizeof(strided.u.s.position));
218         if(strided.u.s.diffuse.VBO != This->vbo)     memset(&strided.u.s.diffuse, 0, sizeof(strided.u.s.diffuse));
219         if(strided.u.s.specular.VBO != This->vbo)    memset(&strided.u.s.specular, 0, sizeof(strided.u.s.specular));
220         if(strided.u.s.position2.VBO != This->vbo)   memset(&strided.u.s.position2, 0, sizeof(strided.u.s.position2));
221     }
222
223     /* We have a declaration now in the buffer */
224     This->Flags |= VBFLAG_HASDESC;
225
226     /* Find out if reload is needed
227      * Position of the semantic in the vertex and the stride must be equal to the stored type. Don't mind if only unconverted stuff changed.
228      *
229      * If some stuff does not exist in the buffer, then lpData, dwStride and dwType are memsetted to 0. So if the semantic didn't exist before
230      * and does not exist now all 3 values will be equal(=0).
231      *
232      * Checking the lpData field alone is not enough, because data may appear at offset 0 in the buffer. This is the same location as nonexistent
233      * data uses, so we have to check the type and stride too. Colors can be at offset 0 too, because it is perfectly fine to render from 2 or more
234      * buffers at the same time and get the position from one and the color from the other buffer.
235      */
236     if( /* Position transformed vs untransformed */
237         ((This->strided.u.s.position_transformed || strided.u.s.position_transformed) &&
238           (This->strided.u.s.position.lpData != strided.u.s.position.lpData ||
239            This->strided.u.s.position.dwType != strided.u.s.position.dwType)) ||
240         /* Diffuse position and data type */
241         This->strided.u.s.diffuse.lpData != strided.u.s.diffuse.lpData || This->strided.u.s.diffuse.dwStride != strided.u.s.diffuse.dwStride ||
242          This->strided.u.s.diffuse.dwType != strided.u.s.diffuse.dwType ||
243         /* Specular position and data type */
244         This->strided.u.s.specular.lpData != strided.u.s.specular.lpData || This->strided.u.s.specular.dwStride != strided.u.s.specular.dwStride ||
245          This->strided.u.s.specular.dwType != strided.u.s.specular.dwType) {
246
247         TRACE("Declaration changed, reloading buffer\n");
248         /* Set the new description */
249         memcpy(&This->strided, &strided, sizeof(strided));
250         return TRUE;
251     }
252
253     return FALSE;
254 }
255
256 static void     WINAPI IWineD3DVertexBufferImpl_PreLoad(IWineD3DVertexBuffer *iface) {
257     IWineD3DVertexBufferImpl *This = (IWineD3DVertexBufferImpl *) iface;
258     IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
259     BYTE *data;
260     UINT start = 0, end = 0, stride = 0;
261     BOOL declChanged = FALSE;
262     TRACE("(%p)->()\n", This);
263
264     if(This->Flags & VBFLAG_LOAD) {
265         return; /* Already doing that stuff */
266     }
267
268     if(!This->vbo) {
269         /* TODO: Make converting independent from VBOs */
270         return; /* Not doing any conversion */
271     }
272
273     /* Reading the declaration makes only sense if the stateblock is finalized and the buffer bound to a stream */
274     if(device->isInDraw && This->bindCount > 0) {
275         declChanged = IWineD3DVertexBufferImpl_FindDecl(This);
276     } else if(This->Flags & VBFLAG_HASDESC) {
277         /* Reuse the declaration stored in the buffer. It will most likely not change, and if it does
278          * the stream source state handler will call PreLoad again and the change will be cought
279          */
280     } else {
281         /* Cannot get a declaration, and no declaration is stored in the buffer. It is pointless to preload
282          * now. When the buffer is used, PreLoad will be called by the stream source state handler and a valid
283          * declaration for the buffer can be found
284          */
285         return;
286     }
287
288     /* If applications change the declaration over and over, reconverting all the time is a huge
289      * performance hit. So count the declaration changes and release the VBO if there are too much
290      * of them(and thus stop converting)
291      */
292     if(declChanged) {
293         This->declChanges++;
294         This->draws = 0;
295
296         if(This->declChanges > VB_MAXDECLCHANGES) {
297             FIXME("Too much declaration changes, stopping converting\n");
298             ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
299             ENTER_GL();
300             GL_EXTCALL(glDeleteBuffersARB(1, &This->vbo));
301             checkGLcall("glDeleteBuffersARB");
302             LEAVE_GL();
303             This->vbo = 0;
304
305             /* The stream source state handler might have read the memory of the vertex buffer already
306              * and got the memory in the vbo which is not valid any longer. Dirtify the stream source
307              * to force a reload. This happens only once per changed vertexbuffer and should occur rather
308              * rarely
309              */
310             IWineD3DDeviceImpl_MarkStateDirty(device, STATE_STREAMSRC);
311
312             return;
313         }
314     } else {
315         /* However, it is perfectly fine to change the declaration every now and then. We don't want a game that
316          * changes it every minute drop the VBO after VB_MAX_DECL_CHANGES minutes. So count draws without
317          * decl changes and reset the decl change count after a specific number of them
318          */
319         This->draws++;
320         if(This->draws > VB_RESETDECLCHANGE) This->declChanges = 0;
321     }
322
323     if(declChanged) {
324         /* The declaration changed, reload the whole buffer */
325         WARN("Reloading buffer because of decl change\n");
326         start = 0;
327         end = This->resource.size;
328     } else if(This->Flags & VBFLAG_DIRTY) {
329         /* No decl change, but dirty data, reload the changed stuff */
330         start = This->dirtystart;
331         end = This->dirtyend;
332     } else {
333         /* Desc not changed, buffer not dirty, nothing to do :-) */
334         return;
335     }
336
337     /* Mark the buffer clean */
338     This->Flags &= ~VBFLAG_DIRTY;
339     This->dirtystart = 0;
340     This->dirtyend = 0;
341
342     if     (This->strided.u.s.position.dwStride) stride = This->strided.u.s.position.dwStride;
343     else if(This->strided.u.s.specular.dwStride) stride = This->strided.u.s.specular.dwStride;
344     else if(This->strided.u.s.diffuse.dwStride)  stride = This->strided.u.s.diffuse.dwStride;
345     else {
346         /* That means that there is nothing to fixup. Just upload from This->resource.allocatedMemory
347          * directly into the vbo. Do not free the system memory copy because drawPrimitive may need it if
348          * the stride is 0, for instancing emulation, vertex blending emulation or shader emulation.
349          */
350         TRACE("No conversion needed, locking directly into the VBO in future\n");
351
352         if(!device->isInDraw) {
353             ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
354         }
355         ENTER_GL();
356         GL_EXTCALL(glBindBufferARB(GL_ARRAY_BUFFER_ARB, This->vbo));
357         checkGLcall("glBindBufferARB");
358         GL_EXTCALL(glBufferSubDataARB(GL_ARRAY_BUFFER_ARB, start, end-start, This->resource.allocatedMemory + start));
359         checkGLcall("glBufferSubDataARB");
360         LEAVE_GL();
361         return;
362     }
363
364     /* OK, we have the original data from the app, the description of the buffer and the dirty area.
365      * so convert the stuff
366      */
367     data = HeapAlloc(GetProcessHeap(), 0, end-start);
368     if(!data) {
369         ERR("Out of memory\n");
370         return;
371     }
372     memcpy(data, This->resource.allocatedMemory + start, end - start);
373
374     fixup_vertices(data, data, stride, ( end - start) / stride,
375                    /* Position */
376                    (int)This->strided.u.s.position.lpData, /* Data location */
377                    This->strided.u.s.position_transformed, /* Do convert? */
378                    /* Diffuse color */
379                    (int)This->strided.u.s.diffuse.lpData, /* Location */
380                    This->strided.u.s.diffuse.dwType == WINED3DDECLTYPE_SHORT4 || This->strided.u.s.diffuse.dwType == WINED3DDECLTYPE_D3DCOLOR, /* Convert? */
381                    /* specular color */
382                    (int)This->strided.u.s.specular.lpData, /* location */
383                    This->strided.u.s.specular.dwType == WINED3DDECLTYPE_SHORT4 || This->strided.u.s.specular.dwType == WINED3DDECLTYPE_D3DCOLOR);
384
385     if(!device->isInDraw) {
386         ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
387     }
388     ENTER_GL();
389     GL_EXTCALL(glBindBufferARB(GL_ARRAY_BUFFER_ARB, This->vbo));
390     checkGLcall("glBindBufferARB");
391     GL_EXTCALL(glBufferSubDataARB(GL_ARRAY_BUFFER_ARB, start, end - start, data));
392     checkGLcall("glBufferSubDataARB");
393     LEAVE_GL();
394
395     HeapFree(GetProcessHeap(), 0, data);
396 }
397
398 static WINED3DRESOURCETYPE WINAPI IWineD3DVertexBufferImpl_GetType(IWineD3DVertexBuffer *iface) {
399     return IWineD3DResourceImpl_GetType((IWineD3DResource *)iface);
400 }
401
402 static HRESULT WINAPI IWineD3DVertexBufferImpl_GetParent(IWineD3DVertexBuffer *iface, IUnknown **pParent) {
403     return IWineD3DResourceImpl_GetParent((IWineD3DResource *)iface, pParent);
404 }
405
406 /* ******************************************************
407    IWineD3DVertexBuffer IWineD3DVertexBuffer parts follow
408    ****************************************************** */
409 static HRESULT  WINAPI IWineD3DVertexBufferImpl_Lock(IWineD3DVertexBuffer *iface, UINT OffsetToLock, UINT SizeToLock, BYTE** ppbData, DWORD Flags) {
410     IWineD3DVertexBufferImpl *This = (IWineD3DVertexBufferImpl *)iface;
411     BYTE *data;
412     TRACE("(%p)->%d, %d, %p, %08x\n", This, OffsetToLock, SizeToLock, ppbData, Flags);
413
414     InterlockedIncrement(&This->lockcount);
415
416     if(This->Flags & VBFLAG_DIRTY) {
417         if(This->dirtystart > OffsetToLock) This->dirtystart = OffsetToLock;
418         if(SizeToLock) {
419             if(This->dirtyend < OffsetToLock + SizeToLock) This->dirtyend = OffsetToLock + SizeToLock;
420         } else {
421             This->dirtyend = This->resource.size;
422         }
423     } else {
424         This->dirtystart = OffsetToLock;
425         if(SizeToLock)
426             This->dirtyend = OffsetToLock + SizeToLock;
427         else
428             This->dirtyend = This->resource.size;
429     }
430
431     data = This->resource.allocatedMemory;
432     This->Flags |= VBFLAG_DIRTY;
433     *ppbData = data + OffsetToLock;
434
435     TRACE("(%p) : returning memory of %p (base:%p,offset:%u)\n", This, data + OffsetToLock, data, OffsetToLock);
436     /* TODO: check Flags compatibility with This->currentDesc.Usage (see MSDN) */
437     return WINED3D_OK;
438 }
439 HRESULT  WINAPI IWineD3DVertexBufferImpl_Unlock(IWineD3DVertexBuffer *iface) {
440     IWineD3DVertexBufferImpl *This = (IWineD3DVertexBufferImpl *) iface;
441     LONG lockcount;
442     TRACE("(%p)\n", This);
443
444     lockcount = InterlockedDecrement(&This->lockcount);
445     if(lockcount > 0) {
446         /* Delay loading the buffer until everything is unlocked */
447         TRACE("Ignoring the unlock\n");
448         return WINED3D_OK;
449     }
450
451     if(This->Flags & VBFLAG_HASDESC) {
452         IWineD3DVertexBufferImpl_PreLoad(iface);
453     }
454     return WINED3D_OK;
455 }
456 static HRESULT  WINAPI IWineD3DVertexBufferImpl_GetDesc(IWineD3DVertexBuffer *iface, WINED3DVERTEXBUFFER_DESC *pDesc) {
457     IWineD3DVertexBufferImpl *This = (IWineD3DVertexBufferImpl *)iface;
458
459     TRACE("(%p)\n", This);
460     pDesc->Format = This->resource.format;
461     pDesc->Type   = This->resource.resourceType;
462     pDesc->Usage  = This->resource.usage;
463     pDesc->Pool   = This->resource.pool;
464     pDesc->Size   = This->resource.size;
465     pDesc->FVF    = This->fvf;
466     return WINED3D_OK;
467 }
468
469 const IWineD3DVertexBufferVtbl IWineD3DVertexBuffer_Vtbl =
470 {
471     /* IUnknown */
472     IWineD3DVertexBufferImpl_QueryInterface,
473     IWineD3DVertexBufferImpl_AddRef,
474     IWineD3DVertexBufferImpl_Release,
475     /* IWineD3DResource */
476     IWineD3DVertexBufferImpl_GetParent,
477     IWineD3DVertexBufferImpl_GetDevice,
478     IWineD3DVertexBufferImpl_SetPrivateData,
479     IWineD3DVertexBufferImpl_GetPrivateData,
480     IWineD3DVertexBufferImpl_FreePrivateData,
481     IWineD3DVertexBufferImpl_SetPriority,
482     IWineD3DVertexBufferImpl_GetPriority,
483     IWineD3DVertexBufferImpl_PreLoad,
484     IWineD3DVertexBufferImpl_GetType,
485     /* IWineD3DVertexBuffer */
486     IWineD3DVertexBufferImpl_Lock,
487     IWineD3DVertexBufferImpl_Unlock,
488     IWineD3DVertexBufferImpl_GetDesc
489 };
490
491 BYTE* WINAPI IWineD3DVertexBufferImpl_GetMemory(IWineD3DVertexBuffer* iface, DWORD iOffset, GLint *vbo) {
492     IWineD3DVertexBufferImpl *This = (IWineD3DVertexBufferImpl *)iface;
493
494     *vbo = This->vbo;
495     if(This->vbo == 0) {
496         return This->resource.allocatedMemory + iOffset;
497     } else {
498         return (BYTE *) iOffset;
499     }
500 }
501
502 HRESULT WINAPI IWineD3DVertexBufferImpl_ReleaseMemory(IWineD3DVertexBuffer* iface) {
503   return WINED3D_OK;
504 }