wined3d: Add more debug code to CheckDeviceFormat.
[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 inline void fixup_d3dcolor(DWORD *pos) {
108     DWORD srcColor = *pos;
109
110     /* Color conversion like in drawStridedSlow. watch out for little endianity
111      * If we want that stuff to work on big endian machines too we have to consider more things
112      *
113      * 0xff000000: Alpha mask
114      * 0x00ff0000: Blue mask
115      * 0x0000ff00: Green mask
116      * 0x000000ff: Red mask
117      */
118     *pos = 0;
119     *pos |= (srcColor & 0xff00ff00)      ;   /* Alpha Green */
120     *pos |= (srcColor & 0x00ff0000) >> 16;   /* Red */
121     *pos |= (srcColor & 0x000000ff) << 16;   /* Blue */
122 }
123
124 static inline void fixup_transformed_pos(float *p) {
125     float x, y, z, w;
126
127     /* rhw conversion like in drawStridedSlow */
128     if(p[3] == 1.0 || ((p[3] < eps) && (p[3] > -eps))) {
129         x = p[0];
130         y = p[1];
131         z = p[2];
132         w = 1.0;
133     } else {
134         w = 1.0 / p[3];
135         x = p[0] * w;
136         y = p[1] * w;
137         z = p[2] * w;
138     }
139     p[0] = x;
140     p[1] = y;
141     p[2] = z;
142     p[3] = w;
143 }
144
145 DWORD *find_conversion_shift(IWineD3DVertexBufferImpl *This, WineDirect3DVertexStridedData *strided, DWORD stride) {
146     DWORD *ret, i, shift, j, type;
147     DWORD orig_type_size;
148
149     if(!stride) {
150         TRACE("No shift\n");
151         return NULL;
152     }
153
154     This->conv_stride = stride;
155     ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(DWORD) * stride);
156     for(i = 0; i < MAX_ATTRIBS; i++) {
157         if(strided->u.input[i].VBO != This->vbo) continue;
158
159         type = strided->u.input[i].dwType;
160         if(type == WINED3DDECLTYPE_FLOAT16_2) {
161             shift = 4;
162         } else if(type == WINED3DDECLTYPE_FLOAT16_4) {
163             shift = 8;
164             /* Pre-shift the last 4 bytes in the FLOAT16_4 by 4 bytes - this makes FLOAT16_2 and FLOAT16_4 conversions
165              * compatible
166              */
167             for(j = 4; j < 8; j++) {
168                 ret[(DWORD_PTR) strided->u.input[i].lpData + j ] += 4;
169             }
170         } else {
171             shift = 0;
172         }
173         This->conv_stride += shift;
174
175         if(shift) {
176             orig_type_size = WINED3D_ATR_TYPESIZE(type) * WINED3D_ATR_SIZE(type);
177             for(j = (DWORD_PTR) strided->u.input[i].lpData + orig_type_size; j < stride; j++) {
178                 ret[j] += shift;
179             }
180         }
181     }
182
183     if(TRACE_ON(d3d)) {
184         TRACE("Dumping conversion shift:\n");
185         for(i = 0; i < stride; i++) {
186             TRACE("[%d]", ret[i]);
187         }
188         TRACE("\n");
189     }
190     return ret;
191 }
192
193 static inline BOOL process_converted_attribute(IWineD3DVertexBufferImpl *This,
194                                                const enum vbo_conversion_type conv_type,
195                                                const WineDirect3DStridedData *attrib,
196                                                DWORD *stride_this_run, const DWORD type) {
197     DWORD attrib_size;
198     BOOL ret = FALSE;
199     int i;
200     DWORD offset = This->resource.wineD3DDevice->stateBlock->streamOffset[attrib->streamNo];
201     DWORD_PTR data;
202
203     /* Check for some valid situations which cause us pain. One is if the buffer is used for
204      * constant attributes(stride = 0), the other one is if the buffer is used on two streams
205      * with different strides. In the 2nd case we might have to drop conversion entirely,
206      * it is possible that the same bytes are once read as FLOAT2 and once as UBYTE4N.
207      */
208     if(attrib->dwStride == 0) {
209         FIXME("%s used with stride 0, let's hope we get the vertex stride from somewhere else\n",
210                 debug_d3ddecltype(type));
211     } else if(attrib->dwStride != *stride_this_run &&
212                 *stride_this_run) {
213         FIXME("Got two concurrent strides, %d and %d\n", attrib->dwStride, *stride_this_run);
214     } else {
215         *stride_this_run = attrib->dwStride;
216         if(This->stride != *stride_this_run) {
217             /* We rely that this happens only on the first converted attribute that is found,
218              * if at all. See above check
219              */
220             TRACE("Reconverting because converted attributes occur, and the stride changed\n");
221             This->stride = *stride_this_run;
222             HeapFree(GetProcessHeap(), HEAP_ZERO_MEMORY, This->conv_map);
223             This->conv_map = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*This->conv_map) * This->stride);
224             ret = TRUE;
225         }
226     }
227
228     data = (((DWORD_PTR) attrib->lpData) + offset) % This->stride;
229     attrib_size = WINED3D_ATR_SIZE(type) * WINED3D_ATR_TYPESIZE(type);
230     for(i = 0; i < attrib_size; i++) {
231         if(This->conv_map[data + i] != conv_type) {
232             TRACE("Byte %ld in vertex changed\n", i + data);
233             TRACE("It was type %d, is %d now\n", This->conv_map[data + i], conv_type);
234             ret = TRUE;
235             This->conv_map[data + i] = conv_type;
236         }
237     }
238     return ret;
239 }
240
241 static inline BOOL check_attribute(IWineD3DVertexBufferImpl *This, const WineDirect3DStridedData *attrib,
242                                    const BOOL check_d3dcolor, const BOOL is_ffp_position, const BOOL is_ffp_color,
243                                    DWORD *stride_this_run, BOOL *float16_used) {
244     BOOL ret = FALSE;
245     DWORD type;
246
247     /* Ignore attributes that do not have our vbo. After that check we can be sure that the attribute is
248      * there, on nonexistent attribs the vbo is 0.
249      */
250     if(attrib->VBO != This->vbo) return FALSE;
251
252     type = attrib->dwType;
253     /* Look for newly appeared conversion */
254     if(!GL_SUPPORT(NV_HALF_FLOAT) && (
255        type == WINED3DDECLTYPE_FLOAT16_2 ||
256        type == WINED3DDECLTYPE_FLOAT16_4)) {
257
258         ret = process_converted_attribute(This, CONV_FLOAT16_2, attrib, stride_this_run, type);
259
260         if(is_ffp_position) {
261             FIXME("Test FLOAT16 fixed function processing positions\n");
262         } else if(is_ffp_color) {
263             FIXME("test FLOAT16 fixed function processing colors\n");
264         }
265         *float16_used = TRUE;
266     } else if(check_d3dcolor && type == WINED3DDECLTYPE_D3DCOLOR) {
267
268         ret = process_converted_attribute(This, CONV_D3DCOLOR, attrib, stride_this_run, WINED3DDECLTYPE_D3DCOLOR);
269
270         if(!is_ffp_color) {
271             FIXME("Test for non-color fixed function D3DCOLOR type\n");
272         }
273     } else if(is_ffp_position && type == WINED3DDECLTYPE_FLOAT4) {
274         ret = process_converted_attribute(This, CONV_POSITIONT, attrib, stride_this_run, WINED3DDECLTYPE_FLOAT4);
275     } else if(This->conv_map) {
276         ret = process_converted_attribute(This, CONV_NONE, attrib, stride_this_run, type);
277     }
278     return ret;
279 }
280
281 inline BOOL WINAPI IWineD3DVertexBufferImpl_FindDecl(IWineD3DVertexBufferImpl *This)
282 {
283     IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
284     BOOL ret = FALSE;
285     int i;
286     DWORD stride_this_run = 0;
287     BOOL float16_used = FALSE;
288
289     /* In d3d7 the vertex buffer declaration NEVER changes because it is stored in the d3d7 vertex buffer.
290      * Once we have our declaration there is no need to look it up again.
291      */
292     if(((IWineD3DImpl *)device->wineD3D)->dxVersion == 7 && This->Flags & VBFLAG_HASDESC) {
293         return FALSE;
294     }
295
296     TRACE("Finding vertex buffer conversion information\n");
297     /* Certain declaration types need some fixups before we can pass them to opengl. This means D3DCOLOR attributes with fixed
298      * function vertex processing, FLOAT4 POSITIONT with fixed function, and FLOAT16 if GL_NV_half_float is not supported.
299      *
300      * The vertex buffer FVF doesn't help with finding them, we have to use the decoded vertex declaration and pick the things
301      * that concern the current buffer. A problem with this is that this can change between draws, so we have to validate
302      * the information and reprocess the buffer if it changes, and avoid false positives for performance reasons.
303      *
304      * We have to distinguish between vertex shaders and fixed function to pick the way we access the
305      * strided vertex information.
306      *
307      * This code sets up a per-byte array with the size of the detected stride of the arrays in the
308      * buffer. For each byte we have a field that marks the conversion needed on this byte. For example,
309      * the following declaration with fixed function vertex processing:
310      *
311      *      POSITIONT, FLOAT4
312      *      NORMAL, FLOAT3
313      *      DIFFUSE, FLOAT16_4
314      *      SPECULAR, D3DCOLOR
315      *
316      * Will result in
317      * {                 POSITIONT                    }{             NORMAL                }{    DIFFUSE          }{SPECULAR }
318      * [P][P][P][P][P][P][P][P][P][P][P][P][P][P][P][P][0][0][0][0][0][0][0][0][0][0][0][0][F][F][F][F][F][F][F][F][C][C][C][C]
319      *
320      * Where in this example map P means 4 component position conversion, 0 means no conversion, F means FLOAT16_2 conversion
321      * and C means D3DCOLOR conversion(red / blue swizzle).
322      *
323      * If we're doing conversion and the stride changes we have to reconvert the whole buffer. Note that we do not mind if the
324      * semantic changes, we only care for the conversion type. So if the NORMAL is replaced with a TEXCOORD, nothing has to be
325      * done, or if the DIFFUSE is replaced with a D3DCOLOR BLENDWEIGHT we can happily dismiss the change. Some conversion types
326      * depend on the semantic as well, for example a FLOAT4 texcoord needs no conversion while a FLOAT4 positiont needs one
327      */
328     if(use_vs(device)) {
329         TRACE("vhsader\n");
330         /* If the current vertex declaration is marked for no half float conversion don't bother to
331          * analyse the strided streams in depth, just set them up for no conversion. Return decl changed
332          * if we used conversion before
333          */
334         if(!((IWineD3DVertexDeclarationImpl *) device->stateBlock->vertexDecl)->half_float_conv_needed) {
335             if(This->conv_map) {
336                 TRACE("Now using shaders without conversion, but conversion used before\n");
337                 HeapFree(GetProcessHeap(), 0, This->conv_map);
338                 HeapFree(GetProcessHeap(), 0, This->conv_shift);
339                 This->conv_map = NULL;
340                 This->stride = 0;
341                 This->conv_shift = NULL;
342                 This->conv_stride = 0;
343                 return TRUE;
344             } else {
345                 return FALSE;
346             }
347         }
348         for(i = 0; i < MAX_ATTRIBS; i++) {
349             ret = check_attribute(This, &device->strided_streams.u.input[i], FALSE, FALSE, FALSE, &stride_this_run, &float16_used) || ret;
350         }
351
352         /* Recalculate the conversion shift map if the declaration has changed,
353          * and we're using float16 conversion or used it on the last run
354          */
355         if(ret && (float16_used || This->conv_map)) {
356             HeapFree(GetProcessHeap(), 0, This->conv_shift);
357             This->conv_shift = find_conversion_shift(This, &device->strided_streams, This->stride);
358         }
359     } else {
360         /* Fixed function is a bit trickier. We have to take care for D3DCOLOR types, FLOAT4 positions and of course
361          * FLOAT16s if not supported. Also, we can't iterate over the array, so use macros to generate code for all
362          * the attributes that our current fixed function pipeline implementation cares for.
363          */
364         ret = check_attribute(This, &device->strided_streams.u.s.position,     TRUE, TRUE,  FALSE, &stride_this_run, &float16_used) || ret;
365         ret = check_attribute(This, &device->strided_streams.u.s.normal,       TRUE, FALSE, FALSE, &stride_this_run, &float16_used) || ret;
366         ret = check_attribute(This, &device->strided_streams.u.s.diffuse,      TRUE, FALSE, TRUE,  &stride_this_run, &float16_used) || ret;
367         ret = check_attribute(This, &device->strided_streams.u.s.specular,     TRUE, FALSE, TRUE,  &stride_this_run, &float16_used) || ret;
368         ret = check_attribute(This, &device->strided_streams.u.s.texCoords[0], TRUE, FALSE, FALSE, &stride_this_run, &float16_used) || ret;
369         ret = check_attribute(This, &device->strided_streams.u.s.texCoords[1], TRUE, FALSE, FALSE, &stride_this_run, &float16_used) || ret;
370         ret = check_attribute(This, &device->strided_streams.u.s.texCoords[2], TRUE, FALSE, FALSE, &stride_this_run, &float16_used) || ret;
371         ret = check_attribute(This, &device->strided_streams.u.s.texCoords[3], TRUE, FALSE, FALSE, &stride_this_run, &float16_used) || ret;
372         ret = check_attribute(This, &device->strided_streams.u.s.texCoords[4], TRUE, FALSE, FALSE, &stride_this_run, &float16_used) || ret;
373         ret = check_attribute(This, &device->strided_streams.u.s.texCoords[5], TRUE, FALSE, FALSE, &stride_this_run, &float16_used) || ret;
374         ret = check_attribute(This, &device->strided_streams.u.s.texCoords[6], TRUE, FALSE, FALSE, &stride_this_run, &float16_used) || ret;
375         ret = check_attribute(This, &device->strided_streams.u.s.texCoords[7], TRUE, FALSE, FALSE, &stride_this_run, &float16_used) || ret;
376
377         if(float16_used) FIXME("Float16 conversion used with fixed function vertex processing\n");
378     }
379
380     if(stride_this_run == 0 && This->conv_map) {
381         /* Sanity test */
382         if(ret == FALSE) {
383             ERR("no converted attributes found, old conversion map exists, and no declaration change???\n");
384         }
385         HeapFree(GetProcessHeap(), 0, This->conv_map);
386         This->conv_map = NULL;
387         This->stride = 0;
388     }
389     This->Flags |= VBFLAG_HASDESC;
390
391     if(ret) TRACE("Conversion information changed\n");
392     return ret;
393 }
394
395 static void check_vbo_size(IWineD3DVertexBufferImpl *This) {
396     DWORD size = This->conv_stride ? This->conv_stride * (This->resource.size / This->stride) : This->resource.size;
397     if(This->vbo_size != size) {
398         TRACE("Old size %d, creating new size %d\n", This->vbo_size, size);
399         ENTER_GL();
400         GL_EXTCALL(glBindBufferARB(GL_ARRAY_BUFFER_ARB, This->vbo));
401         checkGLcall("glBindBufferARB");
402         GL_EXTCALL(glBufferDataARB(GL_ARRAY_BUFFER_ARB, size, NULL, This->vbo_usage));
403         This->vbo_size = size;
404         checkGLcall("glBufferDataARB");
405         LEAVE_GL();
406     }
407 }
408
409 static void CreateVBO(IWineD3DVertexBufferImpl *This) {
410     GLenum error, glUsage;
411     DWORD vboUsage = This->resource.usage;
412     IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
413
414     TRACE("Creating an OpenGL vertex buffer object for IWineD3DVertexBuffer %p  Usage(%s)\n", This, debug_d3dusage(vboUsage));
415
416     /* Make sure that a context is there. Needed in a multithreaded environment. Otherwise this call is a nop */
417     ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
418     ENTER_GL();
419
420     /* Make sure that the gl error is cleared. Do not use checkGLcall
421     * here because checkGLcall just prints a fixme and continues. However,
422     * if an error during VBO creation occurs we can fall back to non-vbo operation
423     * with full functionality(but performance loss)
424     */
425     while(glGetError() != GL_NO_ERROR);
426
427     /* Basically the FVF parameter passed to CreateVertexBuffer is no good
428     * It is the FVF set with IWineD3DDevice::SetFVF or the Vertex Declaration set with
429     * IWineD3DDevice::SetVertexDeclaration that decides how the vertices in the buffer
430     * look like. This means that on each DrawPrimitive call the vertex buffer has to be verified
431     * to check if the rhw and color values are in the correct format.
432     */
433
434     GL_EXTCALL(glGenBuffersARB(1, &This->vbo));
435     error = glGetError();
436     if(This->vbo == 0 || error != GL_NO_ERROR) {
437         WARN("Failed to create a VBO with error %s (%#x)\n", debug_glerror(error), error);
438         goto error;
439     }
440
441     GL_EXTCALL(glBindBufferARB(GL_ARRAY_BUFFER_ARB, This->vbo));
442     error = glGetError();
443     if(error != GL_NO_ERROR) {
444         WARN("Failed to bind the VBO with error %s (%#x)\n", debug_glerror(error), error);
445         goto error;
446     }
447
448     /* Don't use static, because dx apps tend to update the buffer
449     * quite often even if they specify 0 usage. Because we always keep the local copy
450     * we never read from the vbo and can create a write only opengl buffer.
451     */
452     switch(vboUsage & (WINED3DUSAGE_WRITEONLY | WINED3DUSAGE_DYNAMIC) ) {
453         case WINED3DUSAGE_WRITEONLY | WINED3DUSAGE_DYNAMIC:
454         case WINED3DUSAGE_DYNAMIC:
455             TRACE("Gl usage = GL_STREAM_DRAW\n");
456             glUsage = GL_STREAM_DRAW_ARB;
457             break;
458         case WINED3DUSAGE_WRITEONLY:
459         default:
460             TRACE("Gl usage = GL_DYNAMIC_DRAW\n");
461             glUsage = GL_DYNAMIC_DRAW_ARB;
462             break;
463     }
464
465     /* Reserve memory for the buffer. The amount of data won't change
466     * so we are safe with calling glBufferData once with a NULL ptr and
467     * calling glBufferSubData on updates
468     */
469     GL_EXTCALL(glBufferDataARB(GL_ARRAY_BUFFER_ARB, This->resource.size, NULL, glUsage));
470     error = glGetError();
471     if(error != GL_NO_ERROR) {
472         WARN("glBufferDataARB failed with error %s (%#x)\n", debug_glerror(error), error);
473         goto error;
474     }
475     This->vbo_size = This->resource.size;
476     This->vbo_usage = glUsage;
477     This->dirtystart = 0;
478     This->dirtyend = This->resource.size;
479     This->Flags |= VBFLAG_DIRTY;
480
481     LEAVE_GL();
482
483     return;
484     error:
485             /* Clean up all vbo init, but continue because we can work without a vbo :-) */
486             FIXME("Failed to create a vertex buffer object. Continuing, but performance issues can occur\n");
487     if(This->vbo) GL_EXTCALL(glDeleteBuffersARB(1, &This->vbo));
488     This->vbo = 0;
489     LEAVE_GL();
490     return;
491 }
492
493 static void     WINAPI IWineD3DVertexBufferImpl_PreLoad(IWineD3DVertexBuffer *iface) {
494     IWineD3DVertexBufferImpl *This = (IWineD3DVertexBufferImpl *) iface;
495     IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
496     BYTE *data;
497     UINT start = 0, end = 0, vertices;
498     BOOL declChanged = FALSE;
499     int i, j;
500     TRACE("(%p)->()\n", This);
501
502     if(!This->vbo) {
503         /* TODO: Make converting independent from VBOs */
504         if(This->Flags & VBFLAG_CREATEVBO) {
505             CreateVBO(This);
506             This->Flags &= ~VBFLAG_CREATEVBO;
507         } else {
508             return; /* Not doing any conversion */
509         }
510     }
511
512     /* Reading the declaration makes only sense if the stateblock is finalized and the buffer bound to a stream */
513     if(device->isInDraw && This->bindCount > 0) {
514         declChanged = IWineD3DVertexBufferImpl_FindDecl(This);
515     } else if(This->Flags & VBFLAG_HASDESC) {
516         /* Reuse the declaration stored in the buffer. It will most likely not change, and if it does
517          * the stream source state handler will call PreLoad again and the change will be caught
518          */
519     } else {
520         /* Cannot get a declaration, and no declaration is stored in the buffer. It is pointless to preload
521          * now. When the buffer is used, PreLoad will be called by the stream source state handler and a valid
522          * declaration for the buffer can be found
523          */
524         return;
525     }
526
527     /* If applications change the declaration over and over, reconverting all the time is a huge
528      * performance hit. So count the declaration changes and release the VBO if there are too many
529      * of them (and thus stop converting)
530      */
531     if(declChanged) {
532         This->declChanges++;
533         This->draws = 0;
534
535         if(This->declChanges > VB_MAXDECLCHANGES) {
536             FIXME("Too many declaration changes, stopping converting\n");
537             ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
538             ENTER_GL();
539             GL_EXTCALL(glDeleteBuffersARB(1, &This->vbo));
540             checkGLcall("glDeleteBuffersARB");
541             LEAVE_GL();
542             This->vbo = 0;
543             HeapFree(GetProcessHeap(), 0, This->conv_shift);
544
545             /* The stream source state handler might have read the memory of the vertex buffer already
546              * and got the memory in the vbo which is not valid any longer. Dirtify the stream source
547              * to force a reload. This happens only once per changed vertexbuffer and should occur rather
548              * rarely
549              */
550             IWineD3DDeviceImpl_MarkStateDirty(device, STATE_STREAMSRC);
551
552             return;
553         }
554         check_vbo_size(This);
555     } else {
556         /* However, it is perfectly fine to change the declaration every now and then. We don't want a game that
557          * changes it every minute drop the VBO after VB_MAX_DECL_CHANGES minutes. So count draws without
558          * decl changes and reset the decl change count after a specific number of them
559          */
560         This->draws++;
561         if(This->draws > VB_RESETDECLCHANGE) This->declChanges = 0;
562     }
563
564     if(declChanged) {
565         /* The declaration changed, reload the whole buffer */
566         WARN("Reloading buffer because of decl change\n");
567         start = 0;
568         end = This->resource.size;
569     } else if(This->Flags & VBFLAG_DIRTY) {
570         /* No decl change, but dirty data, reload the changed stuff */
571         if(This->conv_shift) {
572             if(This->dirtystart != 0 || This->dirtyend != 0) {
573                 FIXME("Implement partial buffer loading with shifted conversion\n");
574             }
575         }
576         start = This->dirtystart;
577         end = This->dirtyend;
578     } else {
579         /* Desc not changed, buffer not dirty, nothing to do :-) */
580         return;
581     }
582
583     /* Mark the buffer clean */
584     This->Flags &= ~VBFLAG_DIRTY;
585     This->dirtystart = 0;
586     This->dirtyend = 0;
587
588     if(!This->conv_map) {
589         /* That means that there is nothing to fixup. Just upload from This->resource.allocatedMemory
590          * directly into the vbo. Do not free the system memory copy because drawPrimitive may need it if
591          * the stride is 0, for instancing emulation, vertex blending emulation or shader emulation.
592          */
593         TRACE("No conversion needed\n");
594
595         if(!device->isInDraw) {
596             ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
597         }
598         ENTER_GL();
599         GL_EXTCALL(glBindBufferARB(GL_ARRAY_BUFFER_ARB, This->vbo));
600         checkGLcall("glBindBufferARB");
601         GL_EXTCALL(glBufferSubDataARB(GL_ARRAY_BUFFER_ARB, start, end-start, This->resource.allocatedMemory + start));
602         checkGLcall("glBufferSubDataARB");
603         LEAVE_GL();
604         return;
605     }
606
607     /* Now for each vertex in the buffer that needs conversion */
608     vertices = This->resource.size / This->stride;
609
610     if(This->conv_shift) {
611         TRACE("Shifted conversion\n");
612         data = HeapAlloc(GetProcessHeap(), 0, vertices * This->conv_stride);
613
614         for(i = start / This->stride; i < min((end / This->stride) + 1, vertices); i++) {
615             for(j = 0; j < This->stride; j++) {
616                 switch(This->conv_map[j]) {
617                     case CONV_NONE:
618                         data[This->conv_stride * i + j + This->conv_shift[j]] = This->resource.allocatedMemory[This->stride * i + j];
619                         break;
620
621                     case CONV_FLOAT16_2:
622                     {
623                         float *out = (float *) (&data[This->conv_stride * i + j + This->conv_shift[j]]);
624                         WORD *in = (WORD *) (&This->resource.allocatedMemory[i * This->stride + j]);
625
626                         out[1] = float_16_to_32(in + 1);
627                         out[0] = float_16_to_32(in + 0);
628                         j += 3;    /* Skip 3 additional bytes,as a FLOAT16_2 has 4 bytes */
629                         break;
630                     }
631
632                     default:
633                         FIXME("Unimplemented conversion %d in shifted conversion\n", This->conv_map[j]);
634                 }
635             }
636         }
637
638         ENTER_GL();
639         GL_EXTCALL(glBindBufferARB(GL_ARRAY_BUFFER_ARB, This->vbo));
640         checkGLcall("glBindBufferARB");
641         GL_EXTCALL(glBufferSubDataARB(GL_ARRAY_BUFFER_ARB, 0, vertices * This->conv_stride, data));
642         checkGLcall("glBufferSubDataARB");
643         LEAVE_GL();
644
645     } else {
646         data = HeapAlloc(GetProcessHeap(), 0, This->resource.size);
647         memcpy(data + start, This->resource.allocatedMemory + start, end - start);
648         for(i = start / This->stride; i < min((end / This->stride) + 1, vertices); i++) {
649             for(j = 0; j < This->stride; j++) {
650                 switch(This->conv_map[j]) {
651                     case CONV_NONE:
652                         /* Done already */
653                         j += 3;
654                         break;
655                     case CONV_D3DCOLOR:
656                         fixup_d3dcolor((DWORD *) (data + i * This->stride + j));
657                         j += 3;
658                         break;
659
660                     case CONV_POSITIONT:
661                         fixup_transformed_pos((float *) (data + i * This->stride + j));
662                         j += 15;
663                         break;
664
665                     case CONV_FLOAT16_2:
666                         ERR("Did not expect FLOAT16 conversion in unshifted conversion\n");
667                     default:
668                         FIXME("Unimplemented conversion %d in shifted conversion\n", This->conv_map[j]);
669                 }
670             }
671         }
672
673         ENTER_GL();
674         GL_EXTCALL(glBindBufferARB(GL_ARRAY_BUFFER_ARB, This->vbo));
675         checkGLcall("glBindBufferARB");
676         GL_EXTCALL(glBufferSubDataARB(GL_ARRAY_BUFFER_ARB, start, end - start, data + start));
677         checkGLcall("glBufferSubDataARB");
678         LEAVE_GL();
679     }
680
681     HeapFree(GetProcessHeap(), 0, data);
682 }
683
684 static void WINAPI IWineD3DVertexBufferImpl_UnLoad(IWineD3DVertexBuffer *iface) {
685     IWineD3DVertexBufferImpl *This = (IWineD3DVertexBufferImpl *) iface;
686     IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
687     TRACE("(%p)\n", This);
688
689     /* This is easy: The whole content is shadowed in This->resource.allocatedMemory,
690      * so we only have to destroy the vbo. Only do it if we have a vbo, which implies
691      * that vbos are supported
692      */
693     if(This->vbo) {
694         ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
695         ENTER_GL();
696         GL_EXTCALL(glDeleteBuffersARB(1, &This->vbo));
697         checkGLcall("glDeleteBuffersARB");
698         LEAVE_GL();
699         This->vbo = 0;
700         This->Flags |= VBFLAG_CREATEVBO; /* Recreate the VBO next load */
701     }
702 }
703
704 static WINED3DRESOURCETYPE WINAPI IWineD3DVertexBufferImpl_GetType(IWineD3DVertexBuffer *iface) {
705     return IWineD3DResourceImpl_GetType((IWineD3DResource *)iface);
706 }
707
708 static HRESULT WINAPI IWineD3DVertexBufferImpl_GetParent(IWineD3DVertexBuffer *iface, IUnknown **pParent) {
709     return IWineD3DResourceImpl_GetParent((IWineD3DResource *)iface, pParent);
710 }
711
712 /* ******************************************************
713    IWineD3DVertexBuffer IWineD3DVertexBuffer parts follow
714    ****************************************************** */
715 static HRESULT  WINAPI IWineD3DVertexBufferImpl_Lock(IWineD3DVertexBuffer *iface, UINT OffsetToLock, UINT SizeToLock, BYTE** ppbData, DWORD Flags) {
716     IWineD3DVertexBufferImpl *This = (IWineD3DVertexBufferImpl *)iface;
717     BYTE *data;
718     TRACE("(%p)->%d, %d, %p, %08x\n", This, OffsetToLock, SizeToLock, ppbData, Flags);
719
720     InterlockedIncrement(&This->lockcount);
721
722     if(This->Flags & VBFLAG_DIRTY) {
723         if(This->dirtystart > OffsetToLock) This->dirtystart = OffsetToLock;
724         if(SizeToLock) {
725             if(This->dirtyend < OffsetToLock + SizeToLock) This->dirtyend = OffsetToLock + SizeToLock;
726         } else {
727             This->dirtyend = This->resource.size;
728         }
729     } else {
730         This->dirtystart = OffsetToLock;
731         if(SizeToLock)
732             This->dirtyend = OffsetToLock + SizeToLock;
733         else
734             This->dirtyend = This->resource.size;
735     }
736
737     data = This->resource.allocatedMemory;
738     This->Flags |= VBFLAG_DIRTY;
739     *ppbData = data + OffsetToLock;
740
741     TRACE("(%p) : returning memory of %p (base:%p,offset:%u)\n", This, data + OffsetToLock, data, OffsetToLock);
742     /* TODO: check Flags compatibility with This->currentDesc.Usage (see MSDN) */
743     return WINED3D_OK;
744 }
745 HRESULT  WINAPI IWineD3DVertexBufferImpl_Unlock(IWineD3DVertexBuffer *iface) {
746     IWineD3DVertexBufferImpl *This = (IWineD3DVertexBufferImpl *) iface;
747     LONG lockcount;
748     TRACE("(%p)\n", This);
749
750     lockcount = InterlockedDecrement(&This->lockcount);
751     if(lockcount > 0) {
752         /* Delay loading the buffer until everything is unlocked */
753         TRACE("Ignoring the unlock\n");
754         return WINED3D_OK;
755     }
756
757     if(This->Flags & VBFLAG_HASDESC) {
758         IWineD3DVertexBufferImpl_PreLoad(iface);
759     }
760     return WINED3D_OK;
761 }
762 static HRESULT  WINAPI IWineD3DVertexBufferImpl_GetDesc(IWineD3DVertexBuffer *iface, WINED3DVERTEXBUFFER_DESC *pDesc) {
763     IWineD3DVertexBufferImpl *This = (IWineD3DVertexBufferImpl *)iface;
764
765     TRACE("(%p)\n", This);
766     pDesc->Format = This->resource.format;
767     pDesc->Type   = This->resource.resourceType;
768     pDesc->Usage  = This->resource.usage;
769     pDesc->Pool   = This->resource.pool;
770     pDesc->Size   = This->resource.size;
771     pDesc->FVF    = This->fvf;
772     return WINED3D_OK;
773 }
774
775 const IWineD3DVertexBufferVtbl IWineD3DVertexBuffer_Vtbl =
776 {
777     /* IUnknown */
778     IWineD3DVertexBufferImpl_QueryInterface,
779     IWineD3DVertexBufferImpl_AddRef,
780     IWineD3DVertexBufferImpl_Release,
781     /* IWineD3DResource */
782     IWineD3DVertexBufferImpl_GetParent,
783     IWineD3DVertexBufferImpl_GetDevice,
784     IWineD3DVertexBufferImpl_SetPrivateData,
785     IWineD3DVertexBufferImpl_GetPrivateData,
786     IWineD3DVertexBufferImpl_FreePrivateData,
787     IWineD3DVertexBufferImpl_SetPriority,
788     IWineD3DVertexBufferImpl_GetPriority,
789     IWineD3DVertexBufferImpl_PreLoad,
790     IWineD3DVertexBufferImpl_UnLoad,
791     IWineD3DVertexBufferImpl_GetType,
792     /* IWineD3DVertexBuffer */
793     IWineD3DVertexBufferImpl_Lock,
794     IWineD3DVertexBufferImpl_Unlock,
795     IWineD3DVertexBufferImpl_GetDesc
796 };
797
798 BYTE* WINAPI IWineD3DVertexBufferImpl_GetMemory(IWineD3DVertexBuffer* iface, DWORD iOffset, GLint *vbo) {
799     IWineD3DVertexBufferImpl *This = (IWineD3DVertexBufferImpl *)iface;
800
801     *vbo = This->vbo;
802     if(This->vbo == 0) {
803         if(This->Flags & VBFLAG_CREATEVBO) {
804             CreateVBO(This);
805             This->Flags &= ~VBFLAG_CREATEVBO;
806             if(This->vbo) {
807                 *vbo = This->vbo;
808                 return (BYTE *) iOffset;
809             }
810         }
811         return This->resource.allocatedMemory + iOffset;
812     } else {
813         return (BYTE *) iOffset;
814     }
815 }
816
817 HRESULT WINAPI IWineD3DVertexBufferImpl_ReleaseMemory(IWineD3DVertexBuffer* iface) {
818   return WINED3D_OK;
819 }