wined3d: Rename the device "strided_streams" field to "stream_info".
[wine] / dlls / wined3d / buffer.c
1 /*
2  * Copyright 2002-2005 Jason Edmeades
3  * Copyright 2002-2005 Raphael Junqueira
4  * Copyright 2004 Christian Costa
5  * Copyright 2005 Oliver Stieber
6  * Copyright 2007-2010 Stefan Dösinger for CodeWeavers
7  * Copyright 2009-2010 Henri Verbeet for CodeWeavers
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22  *
23  */
24
25 #include "config.h"
26 #include "wine/port.h"
27
28 #include "wined3d_private.h"
29
30 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
31
32 #define VB_MAXDECLCHANGES     100     /* After that number of decl changes we stop converting */
33 #define VB_RESETDECLCHANGE    1000    /* Reset the decl changecount after that number of draws */
34 #define VB_MAXFULLCONVERSIONS 5       /* Number of full conversions before we stop converting */
35 #define VB_RESETFULLCONVS     20      /* Reset full conversion counts after that number of draws */
36
37 static inline BOOL buffer_add_dirty_area(struct wined3d_buffer *This, UINT offset, UINT size)
38 {
39     if (!This->buffer_object) return TRUE;
40
41     if (This->maps_size <= This->modified_areas)
42     {
43         void *new = HeapReAlloc(GetProcessHeap(), 0, This->maps,
44                                 This->maps_size * 2 * sizeof(*This->maps));
45         if (!new)
46         {
47             ERR("Out of memory\n");
48             return FALSE;
49         }
50         else
51         {
52             This->maps = new;
53             This->maps_size *= 2;
54         }
55     }
56
57     if(offset > This->resource.size || offset + size > This->resource.size)
58     {
59         WARN("Invalid range dirtified, marking entire buffer dirty\n");
60         offset = 0;
61         size = This->resource.size;
62     }
63     else if(!offset && !size)
64     {
65         size = This->resource.size;
66     }
67
68     This->maps[This->modified_areas].offset = offset;
69     This->maps[This->modified_areas].size = size;
70     This->modified_areas++;
71     return TRUE;
72 }
73
74 static inline void buffer_clear_dirty_areas(struct wined3d_buffer *This)
75 {
76     This->modified_areas = 0;
77 }
78
79 static BOOL buffer_is_dirty(const struct wined3d_buffer *buffer)
80 {
81     return !!buffer->modified_areas;
82 }
83
84 static BOOL buffer_is_fully_dirty(const struct wined3d_buffer *buffer)
85 {
86     unsigned int i;
87
88     for (i = 0; i < buffer->modified_areas; ++i)
89     {
90         if (!buffer->maps[i].offset && buffer->maps[i].size == buffer->resource.size)
91             return TRUE;
92     }
93     return FALSE;
94 }
95
96 /* Context activation is done by the caller */
97 static void delete_gl_buffer(struct wined3d_buffer *This, const struct wined3d_gl_info *gl_info)
98 {
99     if(!This->buffer_object) return;
100
101     GL_EXTCALL(glDeleteBuffersARB(1, &This->buffer_object));
102     checkGLcall("glDeleteBuffersARB");
103     This->buffer_object = 0;
104
105     if(This->query)
106     {
107         wined3d_event_query_destroy(This->query);
108         This->query = NULL;
109     }
110     This->flags &= ~WINED3D_BUFFER_APPLESYNC;
111 }
112
113 /* Context activation is done by the caller. */
114 static void buffer_create_buffer_object(struct wined3d_buffer *This, const struct wined3d_gl_info *gl_info)
115 {
116     GLenum gl_usage = GL_STATIC_DRAW_ARB;
117     GLenum error;
118
119     TRACE("Creating an OpenGL vertex buffer object for wined3d_buffer %p with usage %s.\n",
120             This, debug_d3dusage(This->resource.usage));
121
122     /* Make sure that the gl error is cleared. Do not use checkGLcall
123     * here because checkGLcall just prints a fixme and continues. However,
124     * if an error during VBO creation occurs we can fall back to non-vbo operation
125     * with full functionality(but performance loss)
126     */
127     while (gl_info->gl_ops.gl.p_glGetError() != GL_NO_ERROR);
128
129     /* Basically the FVF parameter passed to CreateVertexBuffer is no good.
130      * The vertex declaration from the device determines how the data in the
131      * buffer is interpreted. This means that on each draw call the buffer has
132      * to be verified to check if the rhw and color values are in the correct
133      * format. */
134
135     GL_EXTCALL(glGenBuffersARB(1, &This->buffer_object));
136     error = gl_info->gl_ops.gl.p_glGetError();
137     if (!This->buffer_object || error != GL_NO_ERROR)
138     {
139         ERR("Failed to create a VBO with error %s (%#x)\n", debug_glerror(error), error);
140         goto fail;
141     }
142
143     if (This->buffer_type_hint == GL_ELEMENT_ARRAY_BUFFER_ARB)
144         device_invalidate_state(This->resource.device, STATE_INDEXBUFFER);
145     GL_EXTCALL(glBindBufferARB(This->buffer_type_hint, This->buffer_object));
146     error = gl_info->gl_ops.gl.p_glGetError();
147     if (error != GL_NO_ERROR)
148     {
149         ERR("Failed to bind the VBO with error %s (%#x)\n", debug_glerror(error), error);
150         goto fail;
151     }
152
153     if (This->resource.usage & WINED3DUSAGE_DYNAMIC)
154     {
155         TRACE("Buffer has WINED3DUSAGE_DYNAMIC set.\n");
156         gl_usage = GL_STREAM_DRAW_ARB;
157
158         if(gl_info->supported[APPLE_FLUSH_BUFFER_RANGE])
159         {
160             GL_EXTCALL(glBufferParameteriAPPLE(This->buffer_type_hint, GL_BUFFER_FLUSHING_UNMAP_APPLE, GL_FALSE));
161             checkGLcall("glBufferParameteriAPPLE(This->buffer_type_hint, GL_BUFFER_FLUSHING_UNMAP_APPLE, GL_FALSE)");
162             This->flags |= WINED3D_BUFFER_FLUSH;
163
164             GL_EXTCALL(glBufferParameteriAPPLE(This->buffer_type_hint, GL_BUFFER_SERIALIZED_MODIFY_APPLE, GL_FALSE));
165             checkGLcall("glBufferParameteriAPPLE(This->buffer_type_hint, GL_BUFFER_SERIALIZED_MODIFY_APPLE, GL_FALSE)");
166             This->flags |= WINED3D_BUFFER_APPLESYNC;
167         }
168         /* No setup is needed here for GL_ARB_map_buffer_range */
169     }
170
171     /* Reserve memory for the buffer. The amount of data won't change
172      * so we are safe with calling glBufferData once and
173      * calling glBufferSubData on updates. Upload the actual data in case
174      * we're not double buffering, so we can release the heap mem afterwards
175      */
176     GL_EXTCALL(glBufferDataARB(This->buffer_type_hint, This->resource.size, This->resource.allocatedMemory, gl_usage));
177     error = gl_info->gl_ops.gl.p_glGetError();
178     if (error != GL_NO_ERROR)
179     {
180         ERR("glBufferDataARB failed with error %s (%#x)\n", debug_glerror(error), error);
181         goto fail;
182     }
183
184     This->buffer_object_size = This->resource.size;
185     This->buffer_object_usage = gl_usage;
186
187     if(This->flags & WINED3D_BUFFER_DOUBLEBUFFER)
188     {
189         if(!buffer_add_dirty_area(This, 0, 0))
190         {
191             ERR("buffer_add_dirty_area failed, this is not expected\n");
192             goto fail;
193         }
194     }
195     else
196     {
197         HeapFree(GetProcessHeap(), 0, This->resource.heapMemory);
198         This->resource.allocatedMemory = NULL;
199         This->resource.heapMemory = NULL;
200     }
201
202     return;
203
204 fail:
205     /* Clean up all vbo init, but continue because we can work without a vbo :-) */
206     ERR("Failed to create a vertex buffer object. Continuing, but performance issues may occur\n");
207     delete_gl_buffer(This, gl_info);
208     buffer_clear_dirty_areas(This);
209 }
210
211 static BOOL buffer_process_converted_attribute(struct wined3d_buffer *This,
212         const enum wined3d_buffer_conversion_type conversion_type,
213         const struct wined3d_stream_info_element *attrib, DWORD *stride_this_run)
214 {
215     DWORD attrib_size;
216     BOOL ret = FALSE;
217     unsigned int i;
218     DWORD_PTR data;
219
220     /* Check for some valid situations which cause us pain. One is if the buffer is used for
221      * constant attributes(stride = 0), the other one is if the buffer is used on two streams
222      * with different strides. In the 2nd case we might have to drop conversion entirely,
223      * it is possible that the same bytes are once read as FLOAT2 and once as UBYTE4N.
224      */
225     if (!attrib->stride)
226     {
227         FIXME("%s used with stride 0, let's hope we get the vertex stride from somewhere else\n",
228                 debug_d3dformat(attrib->format->id));
229     }
230     else if(attrib->stride != *stride_this_run && *stride_this_run)
231     {
232         FIXME("Got two concurrent strides, %d and %d\n", attrib->stride, *stride_this_run);
233     }
234     else
235     {
236         *stride_this_run = attrib->stride;
237         if (This->stride != *stride_this_run)
238         {
239             /* We rely that this happens only on the first converted attribute that is found,
240              * if at all. See above check
241              */
242             TRACE("Reconverting because converted attributes occur, and the stride changed\n");
243             This->stride = *stride_this_run;
244             HeapFree(GetProcessHeap(), HEAP_ZERO_MEMORY, This->conversion_map);
245             This->conversion_map = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
246                     sizeof(*This->conversion_map) * This->stride);
247             ret = TRUE;
248         }
249     }
250
251     data = ((DWORD_PTR)attrib->data.addr) % This->stride;
252     attrib_size = attrib->format->component_count * attrib->format->component_size;
253     for (i = 0; i < attrib_size; ++i)
254     {
255         DWORD_PTR idx = (data + i) % This->stride;
256         if (This->conversion_map[idx] != conversion_type)
257         {
258             TRACE("Byte %ld in vertex changed\n", idx);
259             TRACE("It was type %d, is %d now\n", This->conversion_map[idx], conversion_type);
260             ret = TRUE;
261             This->conversion_map[idx] = conversion_type;
262         }
263     }
264
265     return ret;
266 }
267
268 static BOOL buffer_check_attribute(struct wined3d_buffer *This, const struct wined3d_stream_info *si,
269         UINT attrib_idx, const BOOL check_d3dcolor, const BOOL is_ffp_position, const BOOL is_ffp_color,
270         DWORD *stride_this_run)
271 {
272     const struct wined3d_stream_info_element *attrib = &si->elements[attrib_idx];
273     enum wined3d_format_id format;
274     BOOL ret = FALSE;
275
276     /* Ignore attributes that do not have our vbo. After that check we can be sure that the attribute is
277      * there, on nonexistent attribs the vbo is 0.
278      */
279     if (!(si->use_map & (1 << attrib_idx))
280             || attrib->data.buffer_object != This->buffer_object)
281         return FALSE;
282
283     format = attrib->format->id;
284     /* Look for newly appeared conversion */
285     if (check_d3dcolor && format == WINED3DFMT_B8G8R8A8_UNORM)
286     {
287         ret = buffer_process_converted_attribute(This, CONV_D3DCOLOR, attrib, stride_this_run);
288
289         if (!is_ffp_color) FIXME("Test for non-color fixed function WINED3DFMT_B8G8R8A8_UNORM format\n");
290     }
291     else if (is_ffp_position && si->position_transformed)
292     {
293         if (format != WINED3DFMT_R32G32B32A32_FLOAT)
294         {
295             FIXME("Unexpected format %s for transformed position.\n", debug_d3dformat(format));
296             return FALSE;
297         }
298
299         ret = buffer_process_converted_attribute(This, CONV_POSITIONT, attrib, stride_this_run);
300     }
301     else if (This->conversion_map)
302     {
303         ret = buffer_process_converted_attribute(This, CONV_NONE, attrib, stride_this_run);
304     }
305
306     return ret;
307 }
308
309 static BOOL buffer_find_decl(struct wined3d_buffer *This)
310 {
311     struct wined3d_device *device = This->resource.device;
312     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
313     const struct wined3d_stream_info *si = &device->stream_info;
314     const struct wined3d_state *state = &device->stateBlock->state;
315     UINT stride_this_run = 0;
316     BOOL ret = FALSE;
317     BOOL support_d3dcolor = gl_info->supported[ARB_VERTEX_ARRAY_BGRA];
318
319     /* In d3d7 the vertex buffer declaration NEVER changes because it is stored in the d3d7 vertex buffer.
320      * Once we have our declaration there is no need to look it up again. Index buffers also never need
321      * conversion, so once the (empty) conversion structure is created don't bother checking again
322      */
323     if (This->flags & WINED3D_BUFFER_HASDESC)
324     {
325         if(This->resource.usage & WINED3DUSAGE_STATICDECL) return FALSE;
326     }
327
328     if (use_vs(state))
329     {
330         TRACE("Vertex shaders used, no VBO conversion is needed\n");
331         if(This->conversion_map)
332         {
333             HeapFree(GetProcessHeap(), 0, This->conversion_map);
334             This->conversion_map = NULL;
335             This->stride = 0;
336             return TRUE;
337         }
338
339         return FALSE;
340     }
341
342     TRACE("Finding vertex buffer conversion information\n");
343     /* Certain declaration types need some fixups before we can pass them to
344      * opengl. This means D3DCOLOR attributes with fixed function vertex
345      * processing, FLOAT4 POSITIONT with fixed function, and FLOAT16 if
346      * GL_ARB_half_float_vertex is not supported.
347      *
348      * Note for d3d8 and d3d9:
349      * The vertex buffer FVF doesn't help with finding them, we have to use
350      * the decoded vertex declaration and pick the things that concern the
351      * current buffer. A problem with this is that this can change between
352      * draws, so we have to validate the information and reprocess the buffer
353      * if it changes, and avoid false positives for performance reasons.
354      * WineD3D doesn't even know the vertex buffer any more, it is managed
355      * by the client libraries and passed to SetStreamSource and ProcessVertices
356      * as needed.
357      *
358      * We have to distinguish between vertex shaders and fixed function to
359      * pick the way we access the strided vertex information.
360      *
361      * This code sets up a per-byte array with the size of the detected
362      * stride of the arrays in the buffer. For each byte we have a field
363      * that marks the conversion needed on this byte. For example, the
364      * following declaration with fixed function vertex processing:
365      *
366      *      POSITIONT, FLOAT4
367      *      NORMAL, FLOAT3
368      *      DIFFUSE, FLOAT16_4
369      *      SPECULAR, D3DCOLOR
370      *
371      * Will result in
372      * {                 POSITIONT                    }{             NORMAL                }{    DIFFUSE          }{SPECULAR }
373      * [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]
374      *
375      * Where in this example map P means 4 component position conversion, 0
376      * means no conversion, F means FLOAT16_2 conversion and C means D3DCOLOR
377      * conversion (red / blue swizzle).
378      *
379      * If we're doing conversion and the stride changes we have to reconvert
380      * the whole buffer. Note that we do not mind if the semantic changes,
381      * we only care for the conversion type. So if the NORMAL is replaced
382      * with a TEXCOORD, nothing has to be done, or if the DIFFUSE is replaced
383      * with a D3DCOLOR BLENDWEIGHT we can happily dismiss the change. Some
384      * conversion types depend on the semantic as well, for example a FLOAT4
385      * texcoord needs no conversion while a FLOAT4 positiont needs one
386      */
387
388     ret = buffer_check_attribute(This, si, WINED3D_FFP_POSITION,
389             TRUE, TRUE,  FALSE, &stride_this_run) || ret;
390     ret = buffer_check_attribute(This, si, WINED3D_FFP_NORMAL,
391             TRUE, FALSE, FALSE, &stride_this_run) || ret;
392     ret = buffer_check_attribute(This, si, WINED3D_FFP_DIFFUSE,
393             !support_d3dcolor, FALSE, TRUE,  &stride_this_run) || ret;
394     ret = buffer_check_attribute(This, si, WINED3D_FFP_SPECULAR,
395             !support_d3dcolor, FALSE, TRUE,  &stride_this_run) || ret;
396     ret = buffer_check_attribute(This, si, WINED3D_FFP_TEXCOORD0,
397             TRUE, FALSE, FALSE, &stride_this_run) || ret;
398     ret = buffer_check_attribute(This, si, WINED3D_FFP_TEXCOORD1,
399             TRUE, FALSE, FALSE, &stride_this_run) || ret;
400     ret = buffer_check_attribute(This, si, WINED3D_FFP_TEXCOORD2,
401             TRUE, FALSE, FALSE, &stride_this_run) || ret;
402     ret = buffer_check_attribute(This, si, WINED3D_FFP_TEXCOORD3,
403             TRUE, FALSE, FALSE, &stride_this_run) || ret;
404     ret = buffer_check_attribute(This, si, WINED3D_FFP_TEXCOORD4,
405             TRUE, FALSE, FALSE, &stride_this_run) || ret;
406     ret = buffer_check_attribute(This, si, WINED3D_FFP_TEXCOORD5,
407             TRUE, FALSE, FALSE, &stride_this_run) || ret;
408     ret = buffer_check_attribute(This, si, WINED3D_FFP_TEXCOORD6,
409             TRUE, FALSE, FALSE, &stride_this_run) || ret;
410     ret = buffer_check_attribute(This, si, WINED3D_FFP_TEXCOORD7,
411             TRUE, FALSE, FALSE, &stride_this_run) || ret;
412
413     if (!stride_this_run && This->conversion_map)
414     {
415         /* Sanity test */
416         if (!ret) ERR("no converted attributes found, old conversion map exists, and no declaration change?\n");
417         HeapFree(GetProcessHeap(), 0, This->conversion_map);
418         This->conversion_map = NULL;
419         This->stride = 0;
420     }
421
422     if (ret) TRACE("Conversion information changed\n");
423
424     return ret;
425 }
426
427 static inline void fixup_d3dcolor(DWORD *dst_color)
428 {
429     DWORD src_color = *dst_color;
430
431     /* Color conversion like in drawStridedSlow. watch out for little endianity
432      * If we want that stuff to work on big endian machines too we have to consider more things
433      *
434      * 0xff000000: Alpha mask
435      * 0x00ff0000: Blue mask
436      * 0x0000ff00: Green mask
437      * 0x000000ff: Red mask
438      */
439     *dst_color = 0;
440     *dst_color |= (src_color & 0xff00ff00);         /* Alpha Green */
441     *dst_color |= (src_color & 0x00ff0000) >> 16;   /* Red */
442     *dst_color |= (src_color & 0x000000ff) << 16;   /* Blue */
443 }
444
445 static inline void fixup_transformed_pos(float *p)
446 {
447     /* rhw conversion like in position_float4(). */
448     if (p[3] != 1.0f && p[3] != 0.0f)
449     {
450         float w = 1.0f / p[3];
451         p[0] *= w;
452         p[1] *= w;
453         p[2] *= w;
454         p[3] = w;
455     }
456 }
457
458 /* Context activation is done by the caller. */
459 void buffer_get_memory(struct wined3d_buffer *buffer, const struct wined3d_gl_info *gl_info,
460         struct wined3d_bo_address *data)
461 {
462     data->buffer_object = buffer->buffer_object;
463     if (!buffer->buffer_object)
464     {
465         if ((buffer->flags & WINED3D_BUFFER_CREATEBO) && !buffer->resource.map_count)
466         {
467             buffer_create_buffer_object(buffer, gl_info);
468             buffer->flags &= ~WINED3D_BUFFER_CREATEBO;
469             if (buffer->buffer_object)
470             {
471                 data->buffer_object = buffer->buffer_object;
472                 data->addr = NULL;
473                 return;
474             }
475         }
476         data->addr = buffer->resource.allocatedMemory;
477     }
478     else
479     {
480         data->addr = NULL;
481     }
482 }
483
484 ULONG CDECL wined3d_buffer_incref(struct wined3d_buffer *buffer)
485 {
486     ULONG refcount = InterlockedIncrement(&buffer->resource.ref);
487
488     TRACE("%p increasing refcount to %u.\n", buffer, refcount);
489
490     return refcount;
491 }
492
493 /* Context activation is done by the caller. */
494 BYTE *buffer_get_sysmem(struct wined3d_buffer *This, const struct wined3d_gl_info *gl_info)
495 {
496     /* AllocatedMemory exists if the buffer is double buffered or has no buffer object at all */
497     if(This->resource.allocatedMemory) return This->resource.allocatedMemory;
498
499     This->resource.heapMemory = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, This->resource.size + RESOURCE_ALIGNMENT);
500     This->resource.allocatedMemory = (BYTE *)(((ULONG_PTR)This->resource.heapMemory + (RESOURCE_ALIGNMENT - 1)) & ~(RESOURCE_ALIGNMENT - 1));
501
502     if (This->buffer_type_hint == GL_ELEMENT_ARRAY_BUFFER_ARB)
503         device_invalidate_state(This->resource.device, STATE_INDEXBUFFER);
504
505     GL_EXTCALL(glBindBufferARB(This->buffer_type_hint, This->buffer_object));
506     GL_EXTCALL(glGetBufferSubDataARB(This->buffer_type_hint, 0, This->resource.size, This->resource.allocatedMemory));
507     This->flags |= WINED3D_BUFFER_DOUBLEBUFFER;
508
509     return This->resource.allocatedMemory;
510 }
511
512 /* Do not call while under the GL lock. */
513 static void buffer_unload(struct wined3d_resource *resource)
514 {
515     struct wined3d_buffer *buffer = buffer_from_resource(resource);
516
517     TRACE("buffer %p.\n", buffer);
518
519     if (buffer->buffer_object)
520     {
521         struct wined3d_device *device = resource->device;
522         struct wined3d_context *context;
523
524         context = context_acquire(device, NULL);
525
526         /* Download the buffer, but don't permanently enable double buffering */
527         if (!(buffer->flags & WINED3D_BUFFER_DOUBLEBUFFER))
528         {
529             buffer_get_sysmem(buffer, context->gl_info);
530             buffer->flags &= ~WINED3D_BUFFER_DOUBLEBUFFER;
531         }
532
533         delete_gl_buffer(buffer, context->gl_info);
534         buffer->flags |= WINED3D_BUFFER_CREATEBO; /* Recreate the buffer object next load */
535         buffer_clear_dirty_areas(buffer);
536
537         context_release(context);
538
539         HeapFree(GetProcessHeap(), 0, buffer->conversion_map);
540         buffer->conversion_map = NULL;
541         buffer->stride = 0;
542         buffer->conversion_stride = 0;
543         buffer->flags &= ~WINED3D_BUFFER_HASDESC;
544     }
545
546     resource_unload(resource);
547 }
548
549 /* Do not call while under the GL lock. */
550 ULONG CDECL wined3d_buffer_decref(struct wined3d_buffer *buffer)
551 {
552     ULONG refcount = InterlockedDecrement(&buffer->resource.ref);
553
554     TRACE("%p decreasing refcount to %u.\n", buffer, refcount);
555
556     if (!refcount)
557     {
558         buffer_unload(&buffer->resource);
559         resource_cleanup(&buffer->resource);
560         buffer->resource.parent_ops->wined3d_object_destroyed(buffer->resource.parent);
561         HeapFree(GetProcessHeap(), 0, buffer->maps);
562         HeapFree(GetProcessHeap(), 0, buffer);
563     }
564
565     return refcount;
566 }
567
568 void * CDECL wined3d_buffer_get_parent(const struct wined3d_buffer *buffer)
569 {
570     TRACE("buffer %p.\n", buffer);
571
572     return buffer->resource.parent;
573 }
574
575 DWORD CDECL wined3d_buffer_set_priority(struct wined3d_buffer *buffer, DWORD priority)
576 {
577     return resource_set_priority(&buffer->resource, priority);
578 }
579
580 DWORD CDECL wined3d_buffer_get_priority(const struct wined3d_buffer *buffer)
581 {
582     return resource_get_priority(&buffer->resource);
583 }
584
585 /* The caller provides a context and binds the buffer */
586 static void buffer_sync_apple(struct wined3d_buffer *This, DWORD flags, const struct wined3d_gl_info *gl_info)
587 {
588     enum wined3d_event_query_result ret;
589
590     /* No fencing needs to be done if the app promises not to overwrite
591      * existing data. */
592     if (flags & WINED3D_MAP_NOOVERWRITE)
593         return;
594
595     if (flags & WINED3D_MAP_DISCARD)
596     {
597         GL_EXTCALL(glBufferDataARB(This->buffer_type_hint, This->resource.size, NULL, This->buffer_object_usage));
598         checkGLcall("glBufferDataARB\n");
599         return;
600     }
601
602     if(!This->query)
603     {
604         TRACE("Creating event query for buffer %p\n", This);
605
606         if (!wined3d_event_query_supported(gl_info))
607         {
608             FIXME("Event queries not supported, dropping async buffer locks.\n");
609             goto drop_query;
610         }
611
612         This->query = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*This->query));
613         if (!This->query)
614         {
615             ERR("Failed to allocate event query memory, dropping async buffer locks.\n");
616             goto drop_query;
617         }
618
619         /* Since we don't know about old draws a glFinish is needed once */
620         gl_info->gl_ops.gl.p_glFinish();
621         return;
622     }
623     TRACE("Synchronizing buffer %p\n", This);
624     ret = wined3d_event_query_finish(This->query, This->resource.device);
625     switch(ret)
626     {
627         case WINED3D_EVENT_QUERY_NOT_STARTED:
628         case WINED3D_EVENT_QUERY_OK:
629             /* All done */
630             return;
631
632         case WINED3D_EVENT_QUERY_WRONG_THREAD:
633             WARN("Cannot synchronize buffer lock due to a thread conflict\n");
634             goto drop_query;
635
636         default:
637             ERR("wined3d_event_query_finish returned %u, dropping async buffer locks\n", ret);
638             goto drop_query;
639     }
640
641 drop_query:
642     if(This->query)
643     {
644         wined3d_event_query_destroy(This->query);
645         This->query = NULL;
646     }
647
648     gl_info->gl_ops.gl.p_glFinish();
649     GL_EXTCALL(glBufferParameteriAPPLE(This->buffer_type_hint, GL_BUFFER_SERIALIZED_MODIFY_APPLE, GL_TRUE));
650     checkGLcall("glBufferParameteriAPPLE(This->buffer_type_hint, GL_BUFFER_SERIALIZED_MODIFY_APPLE, GL_TRUE)");
651     This->flags &= ~WINED3D_BUFFER_APPLESYNC;
652 }
653
654 /* The caller provides a GL context */
655 static void buffer_direct_upload(struct wined3d_buffer *This, const struct wined3d_gl_info *gl_info, DWORD flags)
656 {
657     BYTE *map;
658     UINT start = 0, len = 0;
659
660     /* This potentially invalidates the element array buffer binding, but the
661      * caller always takes care of this. */
662     GL_EXTCALL(glBindBufferARB(This->buffer_type_hint, This->buffer_object));
663     checkGLcall("glBindBufferARB");
664     if (gl_info->supported[ARB_MAP_BUFFER_RANGE])
665     {
666         GLbitfield mapflags;
667         mapflags = GL_MAP_WRITE_BIT | GL_MAP_FLUSH_EXPLICIT_BIT;
668         if (flags & WINED3D_BUFFER_DISCARD)
669             mapflags |= GL_MAP_INVALIDATE_BUFFER_BIT;
670         if (flags & WINED3D_BUFFER_NOSYNC)
671             mapflags |= GL_MAP_UNSYNCHRONIZED_BIT;
672         map = GL_EXTCALL(glMapBufferRange(This->buffer_type_hint, 0,
673                     This->resource.size, mapflags));
674         checkGLcall("glMapBufferRange");
675     }
676     else
677     {
678         if (This->flags & WINED3D_BUFFER_APPLESYNC)
679         {
680             DWORD syncflags = 0;
681             if (flags & WINED3D_BUFFER_DISCARD)
682                 syncflags |= WINED3D_MAP_DISCARD;
683             if (flags & WINED3D_BUFFER_NOSYNC)
684                 syncflags |= WINED3D_MAP_NOOVERWRITE;
685             buffer_sync_apple(This, syncflags, gl_info);
686         }
687         map = GL_EXTCALL(glMapBufferARB(This->buffer_type_hint, GL_WRITE_ONLY_ARB));
688         checkGLcall("glMapBufferARB");
689     }
690     if (!map)
691     {
692         ERR("Failed to map opengl buffer\n");
693         return;
694     }
695
696     while (This->modified_areas)
697     {
698         This->modified_areas--;
699         start = This->maps[This->modified_areas].offset;
700         len = This->maps[This->modified_areas].size;
701
702         memcpy(map + start, This->resource.allocatedMemory + start, len);
703
704         if (gl_info->supported[ARB_MAP_BUFFER_RANGE])
705         {
706             GL_EXTCALL(glFlushMappedBufferRange(This->buffer_type_hint, start, len));
707             checkGLcall("glFlushMappedBufferRange");
708         }
709         else if (This->flags & WINED3D_BUFFER_FLUSH)
710         {
711             GL_EXTCALL(glFlushMappedBufferRangeAPPLE(This->buffer_type_hint, start, len));
712             checkGLcall("glFlushMappedBufferRangeAPPLE");
713         }
714     }
715     GL_EXTCALL(glUnmapBufferARB(This->buffer_type_hint));
716     checkGLcall("glUnmapBufferARB");
717 }
718
719 /* Do not call while under the GL lock. */
720 void CDECL wined3d_buffer_preload(struct wined3d_buffer *buffer)
721 {
722     DWORD flags = buffer->flags & (WINED3D_BUFFER_NOSYNC | WINED3D_BUFFER_DISCARD);
723     struct wined3d_device *device = buffer->resource.device;
724     UINT start = 0, end = 0, len = 0, vertices;
725     const struct wined3d_gl_info *gl_info;
726     struct wined3d_context *context;
727     BOOL decl_changed = FALSE;
728     unsigned int i, j;
729     BYTE *data;
730
731     TRACE("buffer %p.\n", buffer);
732
733     if (buffer->resource.map_count)
734     {
735         WARN("Buffer is mapped, skipping preload.\n");
736         return;
737     }
738
739     buffer->flags &= ~(WINED3D_BUFFER_NOSYNC | WINED3D_BUFFER_DISCARD);
740
741     if (!buffer->buffer_object)
742     {
743         /* TODO: Make converting independent from VBOs */
744         if (buffer->flags & WINED3D_BUFFER_CREATEBO)
745         {
746             context = context_acquire(device, NULL);
747             buffer_create_buffer_object(buffer, context->gl_info);
748             context_release(context);
749             buffer->flags &= ~WINED3D_BUFFER_CREATEBO;
750         }
751         else
752         {
753             /* Not doing any conversion */
754             return;
755         }
756     }
757
758     /* Reading the declaration makes only sense if the stateblock is finalized and the buffer bound to a stream */
759     if (device->isInDraw && buffer->resource.bind_count > 0)
760     {
761         decl_changed = buffer_find_decl(buffer);
762         buffer->flags |= WINED3D_BUFFER_HASDESC;
763     }
764
765     if (!decl_changed && !(buffer->flags & WINED3D_BUFFER_HASDESC && buffer_is_dirty(buffer)))
766     {
767         ++buffer->draw_count;
768         if (buffer->draw_count > VB_RESETDECLCHANGE)
769             buffer->decl_change_count = 0;
770         if (buffer->draw_count > VB_RESETFULLCONVS)
771             buffer->full_conversion_count = 0;
772         return;
773     }
774
775     /* If applications change the declaration over and over, reconverting all the time is a huge
776      * performance hit. So count the declaration changes and release the VBO if there are too many
777      * of them (and thus stop converting)
778      */
779     if (decl_changed)
780     {
781         ++buffer->decl_change_count;
782         buffer->draw_count = 0;
783
784         if (buffer->decl_change_count > VB_MAXDECLCHANGES
785                 || (buffer->conversion_map && (buffer->resource.usage & WINED3DUSAGE_DYNAMIC)))
786         {
787             FIXME("Too many declaration changes or converting dynamic buffer, stopping converting\n");
788
789             buffer_unload(&buffer->resource);
790             buffer->flags &= ~WINED3D_BUFFER_CREATEBO;
791
792             /* The stream source state handler might have read the memory of
793              * the vertex buffer already and got the memory in the vbo which
794              * is not valid any longer. Dirtify the stream source to force a
795              * reload. This happens only once per changed vertexbuffer and
796              * should occur rather rarely. */
797             device_invalidate_state(device, STATE_STREAMSRC);
798             return;
799         }
800
801         /* The declaration changed, reload the whole buffer */
802         WARN("Reloading buffer because of decl change\n");
803         buffer_clear_dirty_areas(buffer);
804         if (!buffer_add_dirty_area(buffer, 0, 0))
805         {
806             ERR("buffer_add_dirty_area failed, this is not expected\n");
807             return;
808         }
809         /* Avoid unfenced updates, we might overwrite more areas of the buffer than the application
810          * cleared for unsynchronized updates
811          */
812         flags = 0;
813     }
814     else
815     {
816         /* However, it is perfectly fine to change the declaration every now and then. We don't want a game that
817          * changes it every minute drop the VBO after VB_MAX_DECL_CHANGES minutes. So count draws without
818          * decl changes and reset the decl change count after a specific number of them
819          */
820         if (buffer->conversion_map && buffer_is_fully_dirty(buffer))
821         {
822             ++buffer->full_conversion_count;
823             if (buffer->full_conversion_count > VB_MAXFULLCONVERSIONS)
824             {
825                 FIXME("Too many full buffer conversions, stopping converting.\n");
826                 buffer_unload(&buffer->resource);
827                 buffer->flags &= ~WINED3D_BUFFER_CREATEBO;
828                 if (buffer->resource.bind_count)
829                     device_invalidate_state(device, STATE_STREAMSRC);
830                 return;
831             }
832         }
833         else
834         {
835             ++buffer->draw_count;
836             if (buffer->draw_count > VB_RESETDECLCHANGE)
837                 buffer->decl_change_count = 0;
838             if (buffer->draw_count > VB_RESETFULLCONVS)
839                 buffer->full_conversion_count = 0;
840         }
841     }
842
843     if (buffer->buffer_type_hint == GL_ELEMENT_ARRAY_BUFFER_ARB)
844         device_invalidate_state(device, STATE_INDEXBUFFER);
845
846     if (!buffer->conversion_map)
847     {
848         /* That means that there is nothing to fixup. Just upload from
849          * buffer->resource.allocatedMemory directly into the vbo. Do not
850          * free the system memory copy because drawPrimitive may need it if
851          * the stride is 0, for instancing emulation, vertex blending
852          * emulation or shader emulation. */
853         TRACE("No conversion needed.\n");
854
855         /* Nothing to do because we locked directly into the vbo */
856         if (!(buffer->flags & WINED3D_BUFFER_DOUBLEBUFFER))
857         {
858             return;
859         }
860
861         context = context_acquire(device, NULL);
862         buffer_direct_upload(buffer, context->gl_info, flags);
863
864         context_release(context);
865         return;
866     }
867
868     context = context_acquire(device, NULL);
869     gl_info = context->gl_info;
870
871     if(!(buffer->flags & WINED3D_BUFFER_DOUBLEBUFFER))
872     {
873         buffer_get_sysmem(buffer, gl_info);
874     }
875
876     /* Now for each vertex in the buffer that needs conversion */
877     vertices = buffer->resource.size / buffer->stride;
878
879     data = HeapAlloc(GetProcessHeap(), 0, buffer->resource.size);
880
881     while(buffer->modified_areas)
882     {
883         buffer->modified_areas--;
884         start = buffer->maps[buffer->modified_areas].offset;
885         len = buffer->maps[buffer->modified_areas].size;
886         end = start + len;
887
888         memcpy(data + start, buffer->resource.allocatedMemory + start, end - start);
889         for (i = start / buffer->stride; i < min((end / buffer->stride) + 1, vertices); ++i)
890         {
891             for (j = 0; j < buffer->stride; ++j)
892             {
893                 switch (buffer->conversion_map[j])
894                 {
895                     case CONV_NONE:
896                         /* Done already */
897                         j += 3;
898                         break;
899                     case CONV_D3DCOLOR:
900                         fixup_d3dcolor((DWORD *) (data + i * buffer->stride + j));
901                         j += 3;
902                         break;
903
904                     case CONV_POSITIONT:
905                         fixup_transformed_pos((float *) (data + i * buffer->stride + j));
906                         j += 15;
907                         break;
908                     default:
909                         FIXME("Unimplemented conversion %d in shifted conversion\n", buffer->conversion_map[j]);
910                 }
911             }
912         }
913
914         GL_EXTCALL(glBindBufferARB(buffer->buffer_type_hint, buffer->buffer_object));
915         checkGLcall("glBindBufferARB");
916         GL_EXTCALL(glBufferSubDataARB(buffer->buffer_type_hint, start, len, data + start));
917         checkGLcall("glBufferSubDataARB");
918     }
919
920     HeapFree(GetProcessHeap(), 0, data);
921     context_release(context);
922 }
923
924 static DWORD buffer_sanitize_flags(const struct wined3d_buffer *buffer, DWORD flags)
925 {
926     /* Not all flags make sense together, but Windows never returns an error.
927      * Catch the cases that could cause issues. */
928     if (flags & WINED3D_MAP_READONLY)
929     {
930         if (flags & WINED3D_MAP_DISCARD)
931         {
932             WARN("WINED3D_MAP_READONLY combined with WINED3D_MAP_DISCARD, ignoring flags.\n");
933             return 0;
934         }
935         if (flags & WINED3D_MAP_NOOVERWRITE)
936         {
937             WARN("WINED3D_MAP_READONLY combined with WINED3D_MAP_NOOVERWRITE, ignoring flags.\n");
938             return 0;
939         }
940     }
941     else if ((flags & (WINED3D_MAP_DISCARD | WINED3D_MAP_NOOVERWRITE))
942             == (WINED3D_MAP_DISCARD | WINED3D_MAP_NOOVERWRITE))
943     {
944         WARN("WINED3D_MAP_DISCARD and WINED3D_MAP_NOOVERWRITE used together, ignoring.\n");
945         return 0;
946     }
947     else if (flags & (WINED3D_MAP_DISCARD | WINED3D_MAP_NOOVERWRITE)
948             && !(buffer->resource.usage & WINED3DUSAGE_DYNAMIC))
949     {
950         WARN("DISCARD or NOOVERWRITE map on non-dynamic buffer, ignoring.\n");
951         return 0;
952     }
953
954     return flags;
955 }
956
957 static GLbitfield buffer_gl_map_flags(DWORD d3d_flags)
958 {
959     GLbitfield ret = 0;
960
961     if (!(d3d_flags & WINED3D_MAP_READONLY))
962         ret |= GL_MAP_WRITE_BIT | GL_MAP_FLUSH_EXPLICIT_BIT;
963     if (!(d3d_flags & (WINED3D_MAP_DISCARD | WINED3D_MAP_NOOVERWRITE)))
964         ret |= GL_MAP_READ_BIT;
965
966     if (d3d_flags & WINED3D_MAP_DISCARD)
967         ret |= GL_MAP_INVALIDATE_BUFFER_BIT;
968     if (d3d_flags & WINED3D_MAP_NOOVERWRITE)
969         ret |= GL_MAP_UNSYNCHRONIZED_BIT;
970
971     return ret;
972 }
973
974 struct wined3d_resource * CDECL wined3d_buffer_get_resource(struct wined3d_buffer *buffer)
975 {
976     TRACE("buffer %p.\n", buffer);
977
978     return &buffer->resource;
979 }
980
981 HRESULT CDECL wined3d_buffer_map(struct wined3d_buffer *buffer, UINT offset, UINT size, BYTE **data, DWORD flags)
982 {
983     BOOL dirty = buffer_is_dirty(buffer);
984     LONG count;
985
986     TRACE("buffer %p, offset %u, size %u, data %p, flags %#x\n", buffer, offset, size, data, flags);
987
988     flags = buffer_sanitize_flags(buffer, flags);
989     if (flags & WINED3D_MAP_DISCARD)
990     {
991         /* DISCARD invalidates the entire buffer, regardless of the specified
992          * offset and size. Some applications also depend on the entire buffer
993          * being uploaded in that case. Two such applications are Port Royale
994          * and Darkstar One. */
995         if (!buffer_add_dirty_area(buffer, 0, 0))
996             return E_OUTOFMEMORY;
997     }
998     else if (!(flags & WINED3D_MAP_READONLY))
999     {
1000         if (!buffer_add_dirty_area(buffer, offset, size))
1001             return E_OUTOFMEMORY;
1002     }
1003
1004     count = ++buffer->resource.map_count;
1005
1006     if (buffer->buffer_object)
1007     {
1008         if (!(buffer->flags & WINED3D_BUFFER_DOUBLEBUFFER))
1009         {
1010             if (count == 1)
1011             {
1012                 struct wined3d_device *device = buffer->resource.device;
1013                 struct wined3d_context *context;
1014                 const struct wined3d_gl_info *gl_info;
1015
1016                 context = context_acquire(device, NULL);
1017                 gl_info = context->gl_info;
1018
1019                 if (buffer->buffer_type_hint == GL_ELEMENT_ARRAY_BUFFER_ARB)
1020                     context_invalidate_state(context, STATE_INDEXBUFFER);
1021                 GL_EXTCALL(glBindBufferARB(buffer->buffer_type_hint, buffer->buffer_object));
1022
1023                 if (gl_info->supported[ARB_MAP_BUFFER_RANGE])
1024                 {
1025                     GLbitfield mapflags = buffer_gl_map_flags(flags);
1026                     buffer->resource.allocatedMemory = GL_EXTCALL(glMapBufferRange(buffer->buffer_type_hint,
1027                             0, buffer->resource.size, mapflags));
1028                     checkGLcall("glMapBufferRange");
1029                 }
1030                 else
1031                 {
1032                     if (buffer->flags & WINED3D_BUFFER_APPLESYNC)
1033                         buffer_sync_apple(buffer, flags, gl_info);
1034                     buffer->resource.allocatedMemory = GL_EXTCALL(glMapBufferARB(buffer->buffer_type_hint,
1035                             GL_READ_WRITE_ARB));
1036                     checkGLcall("glMapBufferARB");
1037                 }
1038
1039                 if (((DWORD_PTR)buffer->resource.allocatedMemory) & (RESOURCE_ALIGNMENT - 1))
1040                 {
1041                     WARN("Pointer %p is not %u byte aligned.\n", buffer->resource.allocatedMemory, RESOURCE_ALIGNMENT);
1042
1043                     GL_EXTCALL(glUnmapBufferARB(buffer->buffer_type_hint));
1044                     checkGLcall("glUnmapBufferARB");
1045                     buffer->resource.allocatedMemory = NULL;
1046
1047                     if (buffer->resource.usage & WINED3DUSAGE_DYNAMIC)
1048                     {
1049                         /* The extra copy is more expensive than not using VBOs at
1050                          * all on the Nvidia Linux driver, which is the only driver
1051                          * that returns unaligned pointers
1052                          */
1053                         TRACE("Dynamic buffer, dropping VBO\n");
1054                         buffer_unload(&buffer->resource);
1055                         buffer->flags &= ~WINED3D_BUFFER_CREATEBO;
1056                         if (buffer->resource.bind_count)
1057                             device_invalidate_state(device, STATE_STREAMSRC);
1058                     }
1059                     else
1060                     {
1061                         TRACE("Falling back to doublebuffered operation\n");
1062                         buffer_get_sysmem(buffer, gl_info);
1063                     }
1064                     TRACE("New pointer is %p.\n", buffer->resource.allocatedMemory);
1065                 }
1066                 context_release(context);
1067             }
1068         }
1069         else
1070         {
1071             if (dirty)
1072             {
1073                 if (buffer->flags & WINED3D_BUFFER_NOSYNC && !(flags & WINED3D_MAP_NOOVERWRITE))
1074                 {
1075                     buffer->flags &= ~WINED3D_BUFFER_NOSYNC;
1076                 }
1077             }
1078             else if(flags & WINED3D_MAP_NOOVERWRITE)
1079             {
1080                 buffer->flags |= WINED3D_BUFFER_NOSYNC;
1081             }
1082
1083             if (flags & WINED3D_MAP_DISCARD)
1084             {
1085                 buffer->flags |= WINED3D_BUFFER_DISCARD;
1086             }
1087         }
1088     }
1089
1090     *data = buffer->resource.allocatedMemory + offset;
1091
1092     TRACE("Returning memory at %p (base %p, offset %u).\n", *data, buffer->resource.allocatedMemory, offset);
1093     /* TODO: check Flags compatibility with buffer->currentDesc.Usage (see MSDN) */
1094
1095     return WINED3D_OK;
1096 }
1097
1098 void CDECL wined3d_buffer_unmap(struct wined3d_buffer *buffer)
1099 {
1100     ULONG i;
1101
1102     TRACE("buffer %p.\n", buffer);
1103
1104     /* In the case that the number of Unmap calls > the
1105      * number of Map calls, d3d returns always D3D_OK.
1106      * This is also needed to prevent Map from returning garbage on
1107      * the next call (this will happen if the lock_count is < 0). */
1108     if (!buffer->resource.map_count)
1109     {
1110         WARN("Unmap called without a previous map call.\n");
1111         return;
1112     }
1113
1114     if (--buffer->resource.map_count)
1115     {
1116         /* Delay loading the buffer until everything is unlocked */
1117         TRACE("Ignoring unmap.\n");
1118         return;
1119     }
1120
1121     if (!(buffer->flags & WINED3D_BUFFER_DOUBLEBUFFER) && buffer->buffer_object)
1122     {
1123         struct wined3d_device *device = buffer->resource.device;
1124         const struct wined3d_gl_info *gl_info;
1125         struct wined3d_context *context;
1126
1127         context = context_acquire(device, NULL);
1128         gl_info = context->gl_info;
1129
1130         if (buffer->buffer_type_hint == GL_ELEMENT_ARRAY_BUFFER_ARB)
1131             context_invalidate_state(context, STATE_INDEXBUFFER);
1132         GL_EXTCALL(glBindBufferARB(buffer->buffer_type_hint, buffer->buffer_object));
1133
1134         if (gl_info->supported[ARB_MAP_BUFFER_RANGE])
1135         {
1136             for (i = 0; i < buffer->modified_areas; ++i)
1137             {
1138                 GL_EXTCALL(glFlushMappedBufferRange(buffer->buffer_type_hint,
1139                         buffer->maps[i].offset, buffer->maps[i].size));
1140                 checkGLcall("glFlushMappedBufferRange");
1141             }
1142         }
1143         else if (buffer->flags & WINED3D_BUFFER_FLUSH)
1144         {
1145             for (i = 0; i < buffer->modified_areas; ++i)
1146             {
1147                 GL_EXTCALL(glFlushMappedBufferRangeAPPLE(buffer->buffer_type_hint,
1148                         buffer->maps[i].offset, buffer->maps[i].size));
1149                 checkGLcall("glFlushMappedBufferRangeAPPLE");
1150             }
1151         }
1152
1153         GL_EXTCALL(glUnmapBufferARB(buffer->buffer_type_hint));
1154         if (wined3d_settings.strict_draw_ordering)
1155             gl_info->gl_ops.gl.p_glFlush(); /* Flush to ensure ordering across contexts. */
1156         context_release(context);
1157
1158         buffer->resource.allocatedMemory = NULL;
1159         buffer_clear_dirty_areas(buffer);
1160     }
1161     else if (buffer->flags & WINED3D_BUFFER_HASDESC)
1162     {
1163         wined3d_buffer_preload(buffer);
1164     }
1165 }
1166
1167 static const struct wined3d_resource_ops buffer_resource_ops =
1168 {
1169     buffer_unload,
1170 };
1171
1172 static HRESULT buffer_init(struct wined3d_buffer *buffer, struct wined3d_device *device,
1173         UINT size, DWORD usage, enum wined3d_format_id format_id, enum wined3d_pool pool, GLenum bind_hint,
1174         const char *data, void *parent, const struct wined3d_parent_ops *parent_ops)
1175 {
1176     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1177     const struct wined3d_format *format = wined3d_get_format(gl_info, format_id);
1178     HRESULT hr;
1179     BOOL dynamic_buffer_ok;
1180
1181     if (!size)
1182     {
1183         WARN("Size 0 requested, returning WINED3DERR_INVALIDCALL\n");
1184         return WINED3DERR_INVALIDCALL;
1185     }
1186
1187     hr = resource_init(&buffer->resource, device, WINED3D_RTYPE_BUFFER, format,
1188             WINED3D_MULTISAMPLE_NONE, 0, usage, pool, size, 1, 1, size,
1189             parent, parent_ops, &buffer_resource_ops);
1190     if (FAILED(hr))
1191     {
1192         WARN("Failed to initialize resource, hr %#x\n", hr);
1193         return hr;
1194     }
1195     buffer->buffer_type_hint = bind_hint;
1196
1197     TRACE("size %#x, usage %#x, format %s, memory @ %p, iface @ %p.\n", buffer->resource.size, buffer->resource.usage,
1198             debug_d3dformat(buffer->resource.format->id), buffer->resource.allocatedMemory, buffer);
1199
1200     if (device->create_parms.flags & WINED3DCREATE_SOFTWARE_VERTEXPROCESSING)
1201     {
1202         /* SWvp always returns the same pointer in buffer maps and retains data in DISCARD maps.
1203          * Keep a system memory copy of the buffer to provide the same behavior to the application.
1204          * Still use a VBO to support OpenGL 3 core contexts. */
1205         TRACE("Using doublebuffer mode because of software vertex processing\n");
1206         buffer->flags |= WINED3D_BUFFER_DOUBLEBUFFER;
1207     }
1208
1209     dynamic_buffer_ok = gl_info->supported[APPLE_FLUSH_BUFFER_RANGE] || gl_info->supported[ARB_MAP_BUFFER_RANGE];
1210
1211     /* Observations show that drawStridedSlow is faster on dynamic VBs than converting +
1212      * drawStridedFast (half-life 2 and others).
1213      *
1214      * Basically converting the vertices in the buffer is quite expensive, and observations
1215      * show that drawStridedSlow is faster than converting + uploading + drawStridedFast.
1216      * Therefore do not create a VBO for WINED3DUSAGE_DYNAMIC buffers.
1217      */
1218     if (!gl_info->supported[ARB_VERTEX_BUFFER_OBJECT])
1219     {
1220         TRACE("Not creating a vbo because GL_ARB_vertex_buffer is not supported\n");
1221     }
1222     else if(buffer->resource.pool == WINED3D_POOL_SYSTEM_MEM)
1223     {
1224         TRACE("Not creating a vbo because the vertex buffer is in system memory\n");
1225     }
1226     else if(!dynamic_buffer_ok && (buffer->resource.usage & WINED3DUSAGE_DYNAMIC))
1227     {
1228         TRACE("Not creating a vbo because the buffer has dynamic usage and no GL support\n");
1229     }
1230     else
1231     {
1232         buffer->flags |= WINED3D_BUFFER_CREATEBO;
1233     }
1234
1235     if (data)
1236     {
1237         BYTE *ptr;
1238
1239         hr = wined3d_buffer_map(buffer, 0, size, &ptr, 0);
1240         if (FAILED(hr))
1241         {
1242             ERR("Failed to map buffer, hr %#x\n", hr);
1243             buffer_unload(&buffer->resource);
1244             resource_cleanup(&buffer->resource);
1245             return hr;
1246         }
1247
1248         memcpy(ptr, data, size);
1249
1250         wined3d_buffer_unmap(buffer);
1251     }
1252
1253     buffer->maps = HeapAlloc(GetProcessHeap(), 0, sizeof(*buffer->maps));
1254     if (!buffer->maps)
1255     {
1256         ERR("Out of memory\n");
1257         buffer_unload(&buffer->resource);
1258         resource_cleanup(&buffer->resource);
1259         return E_OUTOFMEMORY;
1260     }
1261     buffer->maps_size = 1;
1262
1263     return WINED3D_OK;
1264 }
1265
1266 HRESULT CDECL wined3d_buffer_create(struct wined3d_device *device, struct wined3d_buffer_desc *desc, const void *data,
1267         void *parent, const struct wined3d_parent_ops *parent_ops, struct wined3d_buffer **buffer)
1268 {
1269     struct wined3d_buffer *object;
1270     HRESULT hr;
1271
1272     TRACE("device %p, desc %p, data %p, parent %p, buffer %p\n", device, desc, data, parent, buffer);
1273
1274     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
1275     if (!object)
1276         return E_OUTOFMEMORY;
1277
1278     FIXME("Ignoring access flags (pool)\n");
1279
1280     hr = buffer_init(object, device, desc->byte_width, desc->usage, WINED3DFMT_UNKNOWN,
1281             WINED3D_POOL_MANAGED, GL_ARRAY_BUFFER_ARB, data, parent, parent_ops);
1282     if (FAILED(hr))
1283     {
1284         WARN("Failed to initialize buffer, hr %#x.\n", hr);
1285         HeapFree(GetProcessHeap(), 0, object);
1286         return hr;
1287     }
1288     object->desc = *desc;
1289
1290     TRACE("Created buffer %p.\n", object);
1291
1292     *buffer = object;
1293
1294     return WINED3D_OK;
1295 }
1296
1297 HRESULT CDECL wined3d_buffer_create_vb(struct wined3d_device *device, UINT size, DWORD usage, enum wined3d_pool pool,
1298         void *parent, const struct wined3d_parent_ops *parent_ops, struct wined3d_buffer **buffer)
1299 {
1300     struct wined3d_buffer *object;
1301     HRESULT hr;
1302
1303     TRACE("device %p, size %u, usage %#x, pool %#x, parent %p, parent_ops %p, buffer %p.\n",
1304             device, size, usage, pool, parent, parent_ops, buffer);
1305
1306     if (pool == WINED3D_POOL_SCRATCH)
1307     {
1308         /* The d3d9 tests shows that this is not allowed. It doesn't make much
1309          * sense anyway, SCRATCH buffers wouldn't be usable anywhere. */
1310         WARN("Vertex buffer in WINED3D_POOL_SCRATCH requested, returning WINED3DERR_INVALIDCALL.\n");
1311         *buffer = NULL;
1312         return WINED3DERR_INVALIDCALL;
1313     }
1314
1315     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
1316     if (!object)
1317     {
1318         *buffer = NULL;
1319         return WINED3DERR_OUTOFVIDEOMEMORY;
1320     }
1321
1322     hr = buffer_init(object, device, size, usage, WINED3DFMT_VERTEXDATA,
1323             pool, GL_ARRAY_BUFFER_ARB, NULL, parent, parent_ops);
1324     if (FAILED(hr))
1325     {
1326         WARN("Failed to initialize buffer, hr %#x.\n", hr);
1327         HeapFree(GetProcessHeap(), 0, object);
1328         return hr;
1329     }
1330
1331     TRACE("Created buffer %p.\n", object);
1332     *buffer = object;
1333
1334     return WINED3D_OK;
1335 }
1336
1337 HRESULT CDECL wined3d_buffer_create_ib(struct wined3d_device *device, UINT size, DWORD usage, enum wined3d_pool pool,
1338         void *parent, const struct wined3d_parent_ops *parent_ops, struct wined3d_buffer **buffer)
1339 {
1340     struct wined3d_buffer *object;
1341     HRESULT hr;
1342
1343     TRACE("device %p, size %u, usage %#x, pool %#x, parent %p, parent_ops %p, buffer %p.\n",
1344             device, size, usage, pool, parent, parent_ops, buffer);
1345
1346     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
1347     if (!object)
1348     {
1349         *buffer = NULL;
1350         return WINED3DERR_OUTOFVIDEOMEMORY;
1351     }
1352
1353     hr = buffer_init(object, device, size, usage | WINED3DUSAGE_STATICDECL,
1354             WINED3DFMT_UNKNOWN, pool, GL_ELEMENT_ARRAY_BUFFER_ARB, NULL,
1355             parent, parent_ops);
1356     if (FAILED(hr))
1357     {
1358         WARN("Failed to initialize buffer, hr %#x\n", hr);
1359         HeapFree(GetProcessHeap(), 0, object);
1360         return hr;
1361     }
1362
1363     TRACE("Created buffer %p.\n", object);
1364     *buffer = object;
1365
1366     return WINED3D_OK;
1367 }