vbo/dlist: implement primitive merging
[platform/upstream/mesa.git] / src / mesa / vbo / vbo_save_api.c
1 /**************************************************************************
2
3 Copyright 2002-2008 VMware, Inc.
4
5 All Rights Reserved.
6
7 Permission is hereby granted, free of charge, to any person obtaining a
8 copy of this software and associated documentation files (the "Software"),
9 to deal in the Software without restriction, including without limitation
10 on the rights to use, copy, modify, merge, publish, distribute, sub
11 license, and/or sell copies of the Software, and to permit persons to whom
12 the Software is furnished to do so, subject to the following conditions:
13
14 The above copyright notice and this permission notice (including the next
15 paragraph) shall be included in all copies or substantial portions of the
16 Software.
17
18 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
21 VMWARE AND/OR THEIR SUPPLIERS BE LIABLE FOR ANY CLAIM,
22 DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
23 OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
24 USE OR OTHER DEALINGS IN THE SOFTWARE.
25
26 **************************************************************************/
27
28 /*
29  * Authors:
30  *   Keith Whitwell <keithw@vmware.com>
31  */
32
33
34
35 /* Display list compiler attempts to store lists of vertices with the
36  * same vertex layout.  Additionally it attempts to minimize the need
37  * for execute-time fixup of these vertex lists, allowing them to be
38  * cached on hardware.
39  *
40  * There are still some circumstances where this can be thwarted, for
41  * example by building a list that consists of one very long primitive
42  * (eg Begin(Triangles), 1000 vertices, End), and calling that list
43  * from inside a different begin/end object (Begin(Lines), CallList,
44  * End).
45  *
46  * In that case the code will have to replay the list as individual
47  * commands through the Exec dispatch table, or fix up the copied
48  * vertices at execute-time.
49  *
50  * The other case where fixup is required is when a vertex attribute
51  * is introduced in the middle of a primitive.  Eg:
52  *  Begin(Lines)
53  *  TexCoord1f()           Vertex2f()
54  *  TexCoord1f() Color3f() Vertex2f()
55  *  End()
56  *
57  *  If the current value of Color isn't known at compile-time, this
58  *  primitive will require fixup.
59  *
60  *
61  * The list compiler currently doesn't attempt to compile lists
62  * containing EvalCoord or EvalPoint commands.  On encountering one of
63  * these, compilation falls back to opcodes.
64  *
65  * This could be improved to fallback only when a mix of EvalCoord and
66  * Vertex commands are issued within a single primitive.
67  */
68
69
70 #include "main/glheader.h"
71 #include "main/arrayobj.h"
72 #include "main/bufferobj.h"
73 #include "main/context.h"
74 #include "main/dlist.h"
75 #include "main/enums.h"
76 #include "main/eval.h"
77 #include "main/macros.h"
78 #include "main/draw_validate.h"
79 #include "main/api_arrayelt.h"
80 #include "main/vtxfmt.h"
81 #include "main/dispatch.h"
82 #include "main/state.h"
83 #include "main/varray.h"
84 #include "util/bitscan.h"
85 #include "util/u_memory.h"
86
87 #include "vbo_noop.h"
88 #include "vbo_private.h"
89
90
91 #ifdef ERROR
92 #undef ERROR
93 #endif
94
95 /**
96  * Display list flag only used by this VBO code.
97  */
98 #define DLIST_DANGLING_REFS     0x1
99
100
101 /* An interesting VBO number/name to help with debugging */
102 #define VBO_BUF_ID  12345
103
104 static void GLAPIENTRY
105 _save_Materialfv(GLenum face, GLenum pname, const GLfloat *params);
106
107 static void GLAPIENTRY
108 _save_EvalCoord1f(GLfloat u);
109
110 static void GLAPIENTRY
111 _save_EvalCoord2f(GLfloat u, GLfloat v);
112
113 /*
114  * NOTE: Old 'parity' issue is gone, but copying can still be
115  * wrong-footed on replay.
116  */
117 static GLuint
118 copy_vertices(struct gl_context *ctx,
119               const struct vbo_save_vertex_list *node,
120               const fi_type * src_buffer)
121 {
122    struct vbo_save_context *save = &vbo_context(ctx)->save;
123    struct _mesa_prim *prim = &node->prims[node->prim_count - 1];
124    GLuint sz = save->vertex_size;
125    const fi_type *src = src_buffer + prim->start * sz;
126    fi_type *dst = save->copied.buffer;
127
128    if (prim->end)
129       return 0;
130
131    return vbo_copy_vertices(ctx, prim->mode, prim, sz, true, dst, src);
132 }
133
134
135 static struct vbo_save_vertex_store *
136 alloc_vertex_store(struct gl_context *ctx)
137 {
138    struct vbo_save_context *save = &vbo_context(ctx)->save;
139    struct vbo_save_vertex_store *vertex_store =
140       CALLOC_STRUCT(vbo_save_vertex_store);
141
142    /* obj->Name needs to be non-zero, but won't ever be examined more
143     * closely than that.  In particular these buffers won't be entered
144     * into the hash and can never be confused with ones visible to the
145     * user.  Perhaps there could be a special number for internal
146     * buffers:
147     */
148    vertex_store->bufferobj = ctx->Driver.NewBufferObject(ctx, VBO_BUF_ID);
149    if (vertex_store->bufferobj) {
150       save->out_of_memory =
151          !ctx->Driver.BufferData(ctx,
152                                  GL_ARRAY_BUFFER_ARB,
153                                  VBO_SAVE_BUFFER_SIZE * sizeof(GLfloat),
154                                  NULL, GL_STATIC_DRAW_ARB,
155                                  GL_MAP_WRITE_BIT |
156                                  GL_DYNAMIC_STORAGE_BIT,
157                                  vertex_store->bufferobj);
158    }
159    else {
160       save->out_of_memory = GL_TRUE;
161    }
162
163    if (save->out_of_memory) {
164       _mesa_error(ctx, GL_OUT_OF_MEMORY, "internal VBO allocation");
165       _mesa_install_save_vtxfmt(ctx, &save->vtxfmt_noop);
166    }
167
168    vertex_store->buffer_map = NULL;
169    vertex_store->used = 0;
170
171    return vertex_store;
172 }
173
174
175 static void
176 free_vertex_store(struct gl_context *ctx,
177                   struct vbo_save_vertex_store *vertex_store)
178 {
179    assert(!vertex_store->buffer_map);
180
181    if (vertex_store->bufferobj) {
182       _mesa_reference_buffer_object(ctx, &vertex_store->bufferobj, NULL);
183    }
184
185    free(vertex_store);
186 }
187
188
189 fi_type *
190 vbo_save_map_vertex_store(struct gl_context *ctx,
191                           struct vbo_save_vertex_store *vertex_store)
192 {
193    const GLbitfield access = (GL_MAP_WRITE_BIT |
194                               GL_MAP_INVALIDATE_RANGE_BIT |
195                               GL_MAP_UNSYNCHRONIZED_BIT |
196                               GL_MAP_FLUSH_EXPLICIT_BIT |
197                               MESA_MAP_ONCE);
198
199    assert(vertex_store->bufferobj);
200    assert(!vertex_store->buffer_map);  /* the buffer should not be mapped */
201
202    if (vertex_store->bufferobj->Size > 0) {
203       /* Map the remaining free space in the VBO */
204       GLintptr offset = vertex_store->used * sizeof(GLfloat);
205       GLsizeiptr size = vertex_store->bufferobj->Size - offset;
206       fi_type *range = (fi_type *)
207          ctx->Driver.MapBufferRange(ctx, offset, size, access,
208                                     vertex_store->bufferobj,
209                                     MAP_INTERNAL);
210       if (range) {
211          /* compute address of start of whole buffer (needed elsewhere) */
212          vertex_store->buffer_map = range - vertex_store->used;
213          assert(vertex_store->buffer_map);
214          return range;
215       }
216       else {
217          vertex_store->buffer_map = NULL;
218          return NULL;
219       }
220    }
221    else {
222       /* probably ran out of memory for buffers */
223       return NULL;
224    }
225 }
226
227
228 void
229 vbo_save_unmap_vertex_store(struct gl_context *ctx,
230                             struct vbo_save_vertex_store *vertex_store)
231 {
232    if (vertex_store->bufferobj->Size > 0) {
233       GLintptr offset = 0;
234       GLsizeiptr length = vertex_store->used * sizeof(GLfloat)
235          - vertex_store->bufferobj->Mappings[MAP_INTERNAL].Offset;
236
237       /* Explicitly flush the region we wrote to */
238       ctx->Driver.FlushMappedBufferRange(ctx, offset, length,
239                                          vertex_store->bufferobj,
240                                          MAP_INTERNAL);
241
242       ctx->Driver.UnmapBuffer(ctx, vertex_store->bufferobj, MAP_INTERNAL);
243    }
244    vertex_store->buffer_map = NULL;
245 }
246
247
248 static struct vbo_save_primitive_store *
249 alloc_prim_store(void)
250 {
251    struct vbo_save_primitive_store *store =
252       CALLOC_STRUCT(vbo_save_primitive_store);
253    store->used = 0;
254    store->refcount = 1;
255    return store;
256 }
257
258
259 static void
260 reset_counters(struct gl_context *ctx)
261 {
262    struct vbo_save_context *save = &vbo_context(ctx)->save;
263
264    save->prims = save->prim_store->prims + save->prim_store->used;
265    save->buffer_map = save->vertex_store->buffer_map + save->vertex_store->used;
266
267    assert(save->buffer_map == save->buffer_ptr);
268
269    if (save->vertex_size)
270       save->max_vert = (VBO_SAVE_BUFFER_SIZE - save->vertex_store->used) /
271                         save->vertex_size;
272    else
273       save->max_vert = 0;
274
275    save->vert_count = 0;
276    save->prim_count = 0;
277    save->prim_max = VBO_SAVE_PRIM_SIZE - save->prim_store->used;
278    save->dangling_attr_ref = GL_FALSE;
279 }
280
281 /**
282  * For a list of prims, try merging prims that can just be extensions of the
283  * previous prim.
284  */
285 static void
286 merge_prims(struct gl_context *ctx, struct _mesa_prim *prim_list,
287             GLuint *prim_count)
288 {
289    GLuint i;
290    struct _mesa_prim *prev_prim = prim_list;
291
292    for (i = 1; i < *prim_count; i++) {
293       struct _mesa_prim *this_prim = prim_list + i;
294
295       vbo_try_prim_conversion(this_prim);
296
297       if (vbo_merge_draws(ctx, true, prev_prim, this_prim)) {
298          /* We've found a prim that just extend the previous one.  Tack it
299           * onto the previous one, and let this primitive struct get dropped.
300           */
301          continue;
302       }
303
304       /* If any previous primitives have been dropped, then we need to copy
305        * this later one into the next available slot.
306        */
307       prev_prim++;
308       if (prev_prim != this_prim)
309          *prev_prim = *this_prim;
310    }
311
312    *prim_count = prev_prim - prim_list + 1;
313 }
314
315
316 /**
317  * Convert GL_LINE_LOOP primitive into GL_LINE_STRIP so that drivers
318  * don't have to worry about handling the _mesa_prim::begin/end flags.
319  * See https://bugs.freedesktop.org/show_bug.cgi?id=81174
320  */
321 static void
322 convert_line_loop_to_strip(struct vbo_save_context *save,
323                            struct vbo_save_vertex_list *node)
324 {
325    struct _mesa_prim *prim = &node->prims[node->prim_count - 1];
326
327    assert(prim->mode == GL_LINE_LOOP);
328
329    if (prim->end) {
330       /* Copy the 0th vertex to end of the buffer and extend the
331        * vertex count by one to finish the line loop.
332        */
333       const GLuint sz = save->vertex_size;
334       /* 0th vertex: */
335       const fi_type *src = save->buffer_map + prim->start * sz;
336       /* end of buffer: */
337       fi_type *dst = save->buffer_map + (prim->start + prim->count) * sz;
338
339       memcpy(dst, src, sz * sizeof(float));
340
341       prim->count++;
342       node->vertex_count++;
343       save->vert_count++;
344       save->buffer_ptr += sz;
345       save->vertex_store->used += sz;
346    }
347
348    if (!prim->begin) {
349       /* Drawing the second or later section of a long line loop.
350        * Skip the 0th vertex.
351        */
352       prim->start++;
353       prim->count--;
354    }
355
356    prim->mode = GL_LINE_STRIP;
357 }
358
359
360 /* Compare the present vao if it has the same setup. */
361 static bool
362 compare_vao(gl_vertex_processing_mode mode,
363             const struct gl_vertex_array_object *vao,
364             const struct gl_buffer_object *bo, GLintptr buffer_offset,
365             GLuint stride, GLbitfield64 vao_enabled,
366             const GLubyte size[VBO_ATTRIB_MAX],
367             const GLenum16 type[VBO_ATTRIB_MAX],
368             const GLuint offset[VBO_ATTRIB_MAX])
369 {
370    if (!vao)
371       return false;
372
373    /* If the enabled arrays are not the same we are not equal. */
374    if (vao_enabled != vao->Enabled)
375       return false;
376
377    /* Check the buffer binding at 0 */
378    if (vao->BufferBinding[0].BufferObj != bo)
379       return false;
380    /* BufferBinding[0].Offset != buffer_offset is checked per attribute */
381    if (vao->BufferBinding[0].Stride != stride)
382       return false;
383    assert(vao->BufferBinding[0].InstanceDivisor == 0);
384
385    /* Retrieve the mapping from VBO_ATTRIB to VERT_ATTRIB space */
386    const GLubyte *const vao_to_vbo_map = _vbo_attribute_alias_map[mode];
387
388    /* Now check the enabled arrays */
389    GLbitfield mask = vao_enabled;
390    while (mask) {
391       const int attr = u_bit_scan(&mask);
392       const unsigned char vbo_attr = vao_to_vbo_map[attr];
393       const GLenum16 tp = type[vbo_attr];
394       const GLintptr off = offset[vbo_attr] + buffer_offset;
395       const struct gl_array_attributes *attrib = &vao->VertexAttrib[attr];
396       if (attrib->RelativeOffset + vao->BufferBinding[0].Offset != off)
397          return false;
398       if (attrib->Format.Type != tp)
399          return false;
400       if (attrib->Format.Size != size[vbo_attr])
401          return false;
402       assert(attrib->Format.Format == GL_RGBA);
403       assert(attrib->Format.Normalized == GL_FALSE);
404       assert(attrib->Format.Integer == vbo_attrtype_to_integer_flag(tp));
405       assert(attrib->Format.Doubles == vbo_attrtype_to_double_flag(tp));
406       assert(attrib->BufferBindingIndex == 0);
407    }
408
409    return true;
410 }
411
412
413 /* Create or reuse the vao for the vertex processing mode. */
414 static void
415 update_vao(struct gl_context *ctx,
416            gl_vertex_processing_mode mode,
417            struct gl_vertex_array_object **vao,
418            struct gl_buffer_object *bo, GLintptr buffer_offset,
419            GLuint stride, GLbitfield64 vbo_enabled,
420            const GLubyte size[VBO_ATTRIB_MAX],
421            const GLenum16 type[VBO_ATTRIB_MAX],
422            const GLuint offset[VBO_ATTRIB_MAX])
423 {
424    /* Compute the bitmasks of vao_enabled arrays */
425    GLbitfield vao_enabled = _vbo_get_vao_enabled_from_vbo(mode, vbo_enabled);
426
427    /*
428     * Check if we can possibly reuse the exisiting one.
429     * In the long term we should reset them when something changes.
430     */
431    if (compare_vao(mode, *vao, bo, buffer_offset, stride,
432                    vao_enabled, size, type, offset))
433       return;
434
435    /* The initial refcount is 1 */
436    _mesa_reference_vao(ctx, vao, NULL);
437    *vao = _mesa_new_vao(ctx, ~((GLuint)0));
438
439    /*
440     * assert(stride <= ctx->Const.MaxVertexAttribStride);
441     * MaxVertexAttribStride is not set for drivers that does not
442     * expose GL 44 or GLES 31.
443     */
444
445    /* Bind the buffer object at binding point 0 */
446    _mesa_bind_vertex_buffer(ctx, *vao, 0, bo, buffer_offset, stride, false,
447                             false);
448
449    /* Retrieve the mapping from VBO_ATTRIB to VERT_ATTRIB space
450     * Note that the position/generic0 aliasing is done in the VAO.
451     */
452    const GLubyte *const vao_to_vbo_map = _vbo_attribute_alias_map[mode];
453    /* Now set the enable arrays */
454    GLbitfield mask = vao_enabled;
455    while (mask) {
456       const int vao_attr = u_bit_scan(&mask);
457       const GLubyte vbo_attr = vao_to_vbo_map[vao_attr];
458       assert(offset[vbo_attr] <= ctx->Const.MaxVertexAttribRelativeOffset);
459
460       _vbo_set_attrib_format(ctx, *vao, vao_attr, buffer_offset,
461                              size[vbo_attr], type[vbo_attr], offset[vbo_attr]);
462       _mesa_vertex_attrib_binding(ctx, *vao, vao_attr, 0);
463    }
464    _mesa_enable_vertex_array_attribs(ctx, *vao, vao_enabled);
465    assert(vao_enabled == (*vao)->Enabled);
466    assert((vao_enabled & ~(*vao)->VertexAttribBufferMask) == 0);
467
468    /* Finalize and freeze the VAO */
469    _mesa_set_vao_immutable(ctx, *vao);
470 }
471
472
473 /**
474  * Insert the active immediate struct onto the display list currently
475  * being built.
476  */
477 static void
478 compile_vertex_list(struct gl_context *ctx)
479 {
480    struct vbo_save_context *save = &vbo_context(ctx)->save;
481    struct vbo_save_vertex_list *node;
482
483    /* Allocate space for this structure in the display list currently
484     * being compiled.
485     */
486    node = (struct vbo_save_vertex_list *)
487       _mesa_dlist_alloc_aligned(ctx, save->opcode_vertex_list, sizeof(*node));
488
489    if (!node)
490       return;
491
492    /* Make sure the pointer is aligned to the size of a pointer */
493    assert((GLintptr) node % sizeof(void *) == 0);
494
495    /* Duplicate our template, increment refcounts to the storage structs:
496     */
497    GLintptr old_offset = 0;
498    if (save->VAO[0]) {
499       old_offset = save->VAO[0]->BufferBinding[0].Offset
500          + save->VAO[0]->VertexAttrib[VERT_ATTRIB_POS].RelativeOffset;
501    }
502    const GLsizei stride = save->vertex_size*sizeof(GLfloat);
503    GLintptr buffer_offset =
504        (save->buffer_map - save->vertex_store->buffer_map) * sizeof(GLfloat);
505    assert(old_offset <= buffer_offset);
506    const GLintptr offset_diff = buffer_offset - old_offset;
507    GLuint start_offset = 0;
508    if (offset_diff > 0 && stride > 0 && offset_diff % stride == 0) {
509       /* The vertex size is an exact multiple of the buffer offset.
510        * This means that we can use zero-based vertex attribute pointers
511        * and specify the start of the primitive with the _mesa_prim::start
512        * field.  This results in issuing several draw calls with identical
513        * vertex attribute information.  This can result in fewer state
514        * changes in drivers.  In particular, the Gallium CSO module will
515        * filter out redundant vertex buffer changes.
516        */
517       /* We cannot immediately update the primitives as some methods below
518        * still need the uncorrected start vertices
519        */
520       start_offset = offset_diff/stride;
521       assert(old_offset == buffer_offset - offset_diff);
522       buffer_offset = old_offset;
523    }
524    GLuint offsets[VBO_ATTRIB_MAX];
525    for (unsigned i = 0, offset = 0; i < VBO_ATTRIB_MAX; ++i) {
526       offsets[i] = offset;
527       offset += save->attrsz[i] * sizeof(GLfloat);
528    }
529    node->vertex_count = save->vert_count;
530    node->wrap_count = save->copied.nr;
531    node->prims = save->prims;
532    node->prim_count = save->prim_count;
533    node->prim_store = save->prim_store;
534
535    /* Create a pair of VAOs for the possible VERTEX_PROCESSING_MODEs
536     * Note that this may reuse the previous one of possible.
537     */
538    for (gl_vertex_processing_mode vpm = VP_MODE_FF; vpm < VP_MODE_MAX; ++vpm) {
539       /* create or reuse the vao */
540       update_vao(ctx, vpm, &save->VAO[vpm],
541                  save->vertex_store->bufferobj, buffer_offset, stride,
542                  save->enabled, save->attrsz, save->attrtype, offsets);
543       /* Reference the vao in the dlist */
544       node->VAO[vpm] = NULL;
545       _mesa_reference_vao(ctx, &node->VAO[vpm], save->VAO[vpm]);
546    }
547
548    node->prim_store->refcount++;
549
550    if (save->no_current_update) {
551       node->current_data = NULL;
552    }
553    else {
554       GLuint current_size = save->vertex_size - save->attrsz[0];
555       node->current_data = NULL;
556
557       if (current_size) {
558          node->current_data = malloc(current_size * sizeof(GLfloat));
559          if (node->current_data) {
560             const char *buffer = (const char *)save->buffer_map;
561             unsigned attr_offset = save->attrsz[0] * sizeof(GLfloat);
562             unsigned vertex_offset = 0;
563
564             if (node->vertex_count)
565                vertex_offset = (node->vertex_count - 1) * stride;
566
567             memcpy(node->current_data, buffer + vertex_offset + attr_offset,
568                    current_size * sizeof(GLfloat));
569          } else {
570             _mesa_error(ctx, GL_OUT_OF_MEMORY, "Current value allocation");
571          }
572       }
573    }
574
575    assert(save->attrsz[VBO_ATTRIB_POS] != 0 || node->vertex_count == 0);
576
577    if (save->dangling_attr_ref)
578       ctx->ListState.CurrentList->Flags |= DLIST_DANGLING_REFS;
579
580    save->vertex_store->used += save->vertex_size * node->vertex_count;
581    save->prim_store->used += node->prim_count;
582
583    /* Copy duplicated vertices
584     */
585    save->copied.nr = copy_vertices(ctx, node, save->buffer_map);
586
587    if (node->prims[node->prim_count - 1].mode == GL_LINE_LOOP) {
588       convert_line_loop_to_strip(save, node);
589    }
590
591    merge_prims(ctx, node->prims, &node->prim_count);
592
593    /* Correct the primitive starts, we can only do this here as copy_vertices
594     * and convert_line_loop_to_strip above consume the uncorrected starts.
595     * On the other hand the _vbo_loopback_vertex_list call below needs the
596     * primitves to be corrected already.
597     */
598    for (unsigned i = 0; i < node->prim_count; i++) {
599       node->prims[i].start += start_offset;
600    }
601
602    /* Create an index buffer. */
603    node->min_index = node->max_index = 0;
604    if (save->vert_count) {
605       int end = node->prims[node->prim_count - 1].start +
606                 node->prims[node->prim_count - 1].count;
607       int total_vert_count = end - node->prims[0].start;
608       /* Estimate for the worst case: all prims are line strips (the +1 is because
609        * wrap_buffers may call use but the last primitive may not be complete) */
610       int max_indices_count = MAX2(total_vert_count * 2 - (node->prim_count * 2) + 1,
611                                    total_vert_count);
612       int size = max_indices_count * sizeof(uint32_t);
613       uint32_t* indices = (uint32_t*) malloc(size);
614       uint32_t max_index = 0, min_index = 0xFFFFFFFF;
615
616       int idx = 0;
617
618       int last_valid_prim = -1;
619       /* Construct indices array. */
620       for (unsigned i = 0; i < node->prim_count; i++) {
621          assert(node->prims[i].basevertex == 0);
622          GLubyte mode = node->prims[i].mode;
623
624          int vertex_count = node->prims[i].count;
625          if (!vertex_count) {
626             continue;
627          }
628
629          /* Line strips get converted to lines */
630          if (mode == GL_LINE_STRIP)
631             mode = GL_LINES;
632
633          /* If 2 consecutive prims use the same mode => merge them. */
634          bool merge_prims = last_valid_prim >= 0 &&
635                             mode == node->prims[last_valid_prim].mode &&
636                             mode != GL_LINE_LOOP && mode != GL_TRIANGLE_FAN &&
637                             mode != GL_QUAD_STRIP && mode != GL_POLYGON &&
638                             mode != GL_PATCHES;
639
640          /* To be able to merge consecutive triangle strips we need to insert
641           * a degenerate triangle.
642           */
643          if (merge_prims &&
644              mode == GL_TRIANGLE_STRIP) {
645             /* Insert a degenerate triangle */
646             assert(node->prims[last_valid_prim].mode == GL_TRIANGLE_STRIP);
647             unsigned tri_count = node->prims[last_valid_prim].count - 2;
648
649             indices[idx] = indices[idx - 1];
650             indices[idx + 1] = node->prims[i].start;
651             idx += 2;
652             node->prims[last_valid_prim].count += 2;
653
654             if (tri_count % 2) {
655                /* Add another index to preserve winding order */
656                indices[idx++] = node->prims[i].start;
657                node->prims[last_valid_prim].count++;
658             }
659          }
660
661          int start = idx;
662
663          /* Convert line strips to lines if it'll allow if the previous
664           * prim mode is GL_LINES (so merge_prims is true) or if the next
665           * primitive mode is GL_LINES or GL_LINE_LOOP.
666           */
667          if (node->prims[i].mode == GL_LINE_STRIP &&
668              (merge_prims ||
669               (i < node->prim_count - 1 &&
670                (node->prims[i + 1].mode == GL_LINE_STRIP ||
671                 node->prims[i + 1].mode == GL_LINES)))) {
672             for (unsigned j = 0; j < vertex_count; j++) {
673                indices[idx++] = node->prims[i].start + j;
674                /* Repeat all but the first/last indices. */
675                if (j && j != vertex_count - 1) {
676                   indices[idx++] = node->prims[i].start + j;
677                   node->prims[i].count++;
678                }
679             }
680             node->prims[i].mode = mode;
681          } else {
682             for (unsigned j = 0; j < vertex_count; j++) {
683                indices[idx++] = node->prims[i].start + j;
684             }
685          }
686
687          min_index = MIN2(min_index, indices[start]);
688          max_index = MAX2(max_index, indices[idx - 1]);
689
690          if (merge_prims) {
691             /* Update vertex count. */
692             node->prims[last_valid_prim].count += idx - start;
693          } else {
694             /* Keep this primitive */
695             last_valid_prim += 1;
696             assert(last_valid_prim <= i);
697             node->prims[i].start = start;
698             node->prims[last_valid_prim] = node->prims[i];
699          }
700       }
701
702       if (idx == 0)
703          goto skip_node;
704
705       assert(idx <= max_indices_count);
706
707       node->prim_count = last_valid_prim + 1;
708       node->ib.ptr = NULL;
709       node->ib.count = idx;
710       node->ib.index_size_shift = (GL_UNSIGNED_INT - GL_UNSIGNED_BYTE) >> 1;
711       node->min_index = min_index;
712       node->max_index = max_index;
713
714       node->ib.obj = ctx->Driver.NewBufferObject(ctx, VBO_BUF_ID + 1);
715       bool success = ctx->Driver.BufferData(ctx,
716                                             GL_ELEMENT_ARRAY_BUFFER_ARB,
717                                             idx * sizeof(uint32_t), indices,
718                                             GL_STATIC_DRAW_ARB, GL_MAP_WRITE_BIT,
719                                             node->ib.obj);
720
721       if (success)
722          goto out;
723
724       ctx->Driver.DeleteBuffer(ctx, node->ib.obj);
725       _mesa_error(ctx, GL_OUT_OF_MEMORY, "IB allocation");
726
727    skip_node:
728       node->ib.obj = NULL;
729       node->vertex_count = 0;
730       node->prim_count = 0;
731
732    out:
733       free(indices);
734    } else {
735       node->ib.obj = NULL;
736    }
737
738    /* Deal with GL_COMPILE_AND_EXECUTE:
739     */
740    if (ctx->ExecuteFlag) {
741       struct _glapi_table *dispatch = GET_DISPATCH();
742
743       _glapi_set_dispatch(ctx->Exec);
744
745       /* Note that the range of referenced vertices must be mapped already */
746       _vbo_loopback_vertex_list(ctx, node);
747
748       _glapi_set_dispatch(dispatch);
749    }
750
751    /* Decide whether the storage structs are full, or can be used for
752     * the next vertex lists as well.
753     */
754    if (save->vertex_store->used >
755        VBO_SAVE_BUFFER_SIZE - 16 * (save->vertex_size + 4)) {
756
757       /* Unmap old store:
758        */
759       vbo_save_unmap_vertex_store(ctx, save->vertex_store);
760
761       /* Release old reference:
762        */
763       free_vertex_store(ctx, save->vertex_store);
764       save->vertex_store = NULL;
765       /* When we have a new vbo, we will for sure need a new vao */
766       for (gl_vertex_processing_mode vpm = 0; vpm < VP_MODE_MAX; ++vpm)
767          _mesa_reference_vao(ctx, &save->VAO[vpm], NULL);
768
769       /* Allocate and map new store:
770        */
771       save->vertex_store = alloc_vertex_store(ctx);
772       save->buffer_ptr = vbo_save_map_vertex_store(ctx, save->vertex_store);
773       save->out_of_memory = save->buffer_ptr == NULL;
774    }
775    else {
776       /* update buffer_ptr for next vertex */
777       save->buffer_ptr = save->vertex_store->buffer_map
778          + save->vertex_store->used;
779    }
780
781    if (save->prim_store->used > VBO_SAVE_PRIM_SIZE - 6) {
782       save->prim_store->refcount--;
783       assert(save->prim_store->refcount != 0);
784       save->prim_store = alloc_prim_store();
785    }
786
787    /* Reset our structures for the next run of vertices:
788     */
789    reset_counters(ctx);
790 }
791
792
793 /**
794  * This is called when we fill a vertex buffer before we hit a glEnd().
795  * We
796  * TODO -- If no new vertices have been stored, don't bother saving it.
797  */
798 static void
799 wrap_buffers(struct gl_context *ctx)
800 {
801    struct vbo_save_context *save = &vbo_context(ctx)->save;
802    GLint i = save->prim_count - 1;
803    GLenum mode;
804
805    assert(i < (GLint) save->prim_max);
806    assert(i >= 0);
807
808    /* Close off in-progress primitive.
809     */
810    save->prims[i].count = (save->vert_count - save->prims[i].start);
811    mode = save->prims[i].mode;
812
813    /* store the copied vertices, and allocate a new list.
814     */
815    compile_vertex_list(ctx);
816
817    /* Restart interrupted primitive
818     */
819    save->prims[0].mode = mode;
820    save->prims[0].begin = 0;
821    save->prims[0].end = 0;
822    save->prims[0].start = 0;
823    save->prims[0].count = 0;
824    save->prim_count = 1;
825 }
826
827
828 /**
829  * Called only when buffers are wrapped as the result of filling the
830  * vertex_store struct.
831  */
832 static void
833 wrap_filled_vertex(struct gl_context *ctx)
834 {
835    struct vbo_save_context *save = &vbo_context(ctx)->save;
836    unsigned numComponents;
837
838    /* Emit a glEnd to close off the last vertex list.
839     */
840    wrap_buffers(ctx);
841
842    /* Copy stored stored vertices to start of new list.
843     */
844    assert(save->max_vert - save->vert_count > save->copied.nr);
845
846    numComponents = save->copied.nr * save->vertex_size;
847    memcpy(save->buffer_ptr,
848           save->copied.buffer,
849           numComponents * sizeof(fi_type));
850    save->buffer_ptr += numComponents;
851    save->vert_count += save->copied.nr;
852 }
853
854
855 static void
856 copy_to_current(struct gl_context *ctx)
857 {
858    struct vbo_save_context *save = &vbo_context(ctx)->save;
859    GLbitfield64 enabled = save->enabled & (~BITFIELD64_BIT(VBO_ATTRIB_POS));
860
861    while (enabled) {
862       const int i = u_bit_scan64(&enabled);
863       assert(save->attrsz[i]);
864
865       if (save->attrtype[i] == GL_DOUBLE ||
866           save->attrtype[i] == GL_UNSIGNED_INT64_ARB)
867          memcpy(save->current[i], save->attrptr[i], save->attrsz[i] * sizeof(GLfloat));
868       else
869          COPY_CLEAN_4V_TYPE_AS_UNION(save->current[i], save->attrsz[i],
870                                      save->attrptr[i], save->attrtype[i]);
871    }
872 }
873
874
875 static void
876 copy_from_current(struct gl_context *ctx)
877 {
878    struct vbo_save_context *save = &vbo_context(ctx)->save;
879    GLbitfield64 enabled = save->enabled & (~BITFIELD64_BIT(VBO_ATTRIB_POS));
880
881    while (enabled) {
882       const int i = u_bit_scan64(&enabled);
883
884       switch (save->attrsz[i]) {
885       case 4:
886          save->attrptr[i][3] = save->current[i][3];
887          FALLTHROUGH;
888       case 3:
889          save->attrptr[i][2] = save->current[i][2];
890          FALLTHROUGH;
891       case 2:
892          save->attrptr[i][1] = save->current[i][1];
893          FALLTHROUGH;
894       case 1:
895          save->attrptr[i][0] = save->current[i][0];
896          break;
897       case 0:
898          unreachable("Unexpected vertex attribute size");
899       }
900    }
901 }
902
903
904 /**
905  * Called when we increase the size of a vertex attribute.  For example,
906  * if we've seen one or more glTexCoord2f() calls and now we get a
907  * glTexCoord3f() call.
908  * Flush existing data, set new attrib size, replay copied vertices.
909  */
910 static void
911 upgrade_vertex(struct gl_context *ctx, GLuint attr, GLuint newsz)
912 {
913    struct vbo_save_context *save = &vbo_context(ctx)->save;
914    GLuint oldsz;
915    GLuint i;
916    fi_type *tmp;
917
918    /* Store the current run of vertices, and emit a GL_END.  Emit a
919     * BEGIN in the new buffer.
920     */
921    if (save->vert_count)
922       wrap_buffers(ctx);
923    else
924       assert(save->copied.nr == 0);
925
926    /* Do a COPY_TO_CURRENT to ensure back-copying works for the case
927     * when the attribute already exists in the vertex and is having
928     * its size increased.
929     */
930    copy_to_current(ctx);
931
932    /* Fix up sizes:
933     */
934    oldsz = save->attrsz[attr];
935    save->attrsz[attr] = newsz;
936    save->enabled |= BITFIELD64_BIT(attr);
937
938    save->vertex_size += newsz - oldsz;
939    save->max_vert = ((VBO_SAVE_BUFFER_SIZE - save->vertex_store->used) /
940                      save->vertex_size);
941    save->vert_count = 0;
942
943    /* Recalculate all the attrptr[] values:
944     */
945    tmp = save->vertex;
946    for (i = 0; i < VBO_ATTRIB_MAX; i++) {
947       if (save->attrsz[i]) {
948          save->attrptr[i] = tmp;
949          tmp += save->attrsz[i];
950       }
951       else {
952          save->attrptr[i] = NULL;       /* will not be dereferenced. */
953       }
954    }
955
956    /* Copy from current to repopulate the vertex with correct values.
957     */
958    copy_from_current(ctx);
959
960    /* Replay stored vertices to translate them to new format here.
961     *
962     * If there are copied vertices and the new (upgraded) attribute
963     * has not been defined before, this list is somewhat degenerate,
964     * and will need fixup at runtime.
965     */
966    if (save->copied.nr) {
967       const fi_type *data = save->copied.buffer;
968       fi_type *dest = save->buffer_map;
969
970       /* Need to note this and fix up at runtime (or loopback):
971        */
972       if (attr != VBO_ATTRIB_POS && save->currentsz[attr][0] == 0) {
973          assert(oldsz == 0);
974          save->dangling_attr_ref = GL_TRUE;
975       }
976
977       for (i = 0; i < save->copied.nr; i++) {
978          GLbitfield64 enabled = save->enabled;
979          while (enabled) {
980             const int j = u_bit_scan64(&enabled);
981             assert(save->attrsz[j]);
982             if (j == attr) {
983                if (oldsz) {
984                   COPY_CLEAN_4V_TYPE_AS_UNION(dest, oldsz, data,
985                                               save->attrtype[j]);
986                   data += oldsz;
987                   dest += newsz;
988                }
989                else {
990                   COPY_SZ_4V(dest, newsz, save->current[attr]);
991                   dest += newsz;
992                }
993             }
994             else {
995                GLint sz = save->attrsz[j];
996                COPY_SZ_4V(dest, sz, data);
997                data += sz;
998                dest += sz;
999             }
1000          }
1001       }
1002
1003       save->buffer_ptr = dest;
1004       save->vert_count += save->copied.nr;
1005    }
1006 }
1007
1008
1009 /**
1010  * This is called when the size of a vertex attribute changes.
1011  * For example, after seeing one or more glTexCoord2f() calls we
1012  * get a glTexCoord4f() or glTexCoord1f() call.
1013  */
1014 static void
1015 fixup_vertex(struct gl_context *ctx, GLuint attr,
1016              GLuint sz, GLenum newType)
1017 {
1018    struct vbo_save_context *save = &vbo_context(ctx)->save;
1019
1020    if (sz > save->attrsz[attr] ||
1021        newType != save->attrtype[attr]) {
1022       /* New size is larger.  Need to flush existing vertices and get
1023        * an enlarged vertex format.
1024        */
1025       upgrade_vertex(ctx, attr, sz);
1026    }
1027    else if (sz < save->active_sz[attr]) {
1028       GLuint i;
1029       const fi_type *id = vbo_get_default_vals_as_union(save->attrtype[attr]);
1030
1031       /* New size is equal or smaller - just need to fill in some
1032        * zeros.
1033        */
1034       for (i = sz; i <= save->attrsz[attr]; i++)
1035          save->attrptr[attr][i - 1] = id[i - 1];
1036    }
1037
1038    save->active_sz[attr] = sz;
1039 }
1040
1041
1042 /**
1043  * Reset the current size of all vertex attributes to the default
1044  * value of 0.  This signals that we haven't yet seen any per-vertex
1045  * commands such as glNormal3f() or glTexCoord2f().
1046  */
1047 static void
1048 reset_vertex(struct gl_context *ctx)
1049 {
1050    struct vbo_save_context *save = &vbo_context(ctx)->save;
1051
1052    while (save->enabled) {
1053       const int i = u_bit_scan64(&save->enabled);
1054       assert(save->attrsz[i]);
1055       save->attrsz[i] = 0;
1056       save->active_sz[i] = 0;
1057    }
1058
1059    save->vertex_size = 0;
1060 }
1061
1062
1063 /**
1064  * If index=0, does glVertexAttrib*() alias glVertex() to emit a vertex?
1065  * It depends on a few things, including whether we're inside or outside
1066  * of glBegin/glEnd.
1067  */
1068 static inline bool
1069 is_vertex_position(const struct gl_context *ctx, GLuint index)
1070 {
1071    return (index == 0 &&
1072            _mesa_attr_zero_aliases_vertex(ctx) &&
1073            _mesa_inside_dlist_begin_end(ctx));
1074 }
1075
1076
1077
1078 #define ERROR(err)   _mesa_compile_error(ctx, err, __func__);
1079
1080
1081 /* Only one size for each attribute may be active at once.  Eg. if
1082  * Color3f is installed/active, then Color4f may not be, even if the
1083  * vertex actually contains 4 color coordinates.  This is because the
1084  * 3f version won't otherwise set color[3] to 1.0 -- this is the job
1085  * of the chooser function when switching between Color4f and Color3f.
1086  */
1087 #define ATTR_UNION(A, N, T, C, V0, V1, V2, V3)                  \
1088 do {                                                            \
1089    struct vbo_save_context *save = &vbo_context(ctx)->save;     \
1090    int sz = (sizeof(C) / sizeof(GLfloat));                      \
1091                                                                 \
1092    if (save->active_sz[A] != N)                                 \
1093       fixup_vertex(ctx, A, N * sz, T);                          \
1094                                                                 \
1095    {                                                            \
1096       C *dest = (C *)save->attrptr[A];                          \
1097       if (N>0) dest[0] = V0;                                    \
1098       if (N>1) dest[1] = V1;                                    \
1099       if (N>2) dest[2] = V2;                                    \
1100       if (N>3) dest[3] = V3;                                    \
1101       save->attrtype[A] = T;                                    \
1102    }                                                            \
1103                                                                 \
1104    if ((A) == 0) {                                              \
1105       GLuint i;                                                 \
1106                                                                 \
1107       for (i = 0; i < save->vertex_size; i++)                   \
1108          save->buffer_ptr[i] = save->vertex[i];                 \
1109                                                                 \
1110       save->buffer_ptr += save->vertex_size;                    \
1111                                                                 \
1112       if (++save->vert_count >= save->max_vert)                 \
1113          wrap_filled_vertex(ctx);                               \
1114    }                                                            \
1115 } while (0)
1116
1117 #define TAG(x) _save_##x
1118
1119 #include "vbo_attrib_tmp.h"
1120
1121
1122
1123 #define MAT( ATTR, N, face, params )                    \
1124 do {                                                    \
1125    if (face != GL_BACK)                                 \
1126       MAT_ATTR( ATTR, N, params ); /* front */          \
1127    if (face != GL_FRONT)                                \
1128       MAT_ATTR( ATTR + 1, N, params ); /* back */       \
1129 } while (0)
1130
1131
1132 /**
1133  * Save a glMaterial call found between glBegin/End.
1134  * glMaterial calls outside Begin/End are handled in dlist.c.
1135  */
1136 static void GLAPIENTRY
1137 _save_Materialfv(GLenum face, GLenum pname, const GLfloat *params)
1138 {
1139    GET_CURRENT_CONTEXT(ctx);
1140
1141    if (face != GL_FRONT && face != GL_BACK && face != GL_FRONT_AND_BACK) {
1142       _mesa_compile_error(ctx, GL_INVALID_ENUM, "glMaterial(face)");
1143       return;
1144    }
1145
1146    switch (pname) {
1147    case GL_EMISSION:
1148       MAT(VBO_ATTRIB_MAT_FRONT_EMISSION, 4, face, params);
1149       break;
1150    case GL_AMBIENT:
1151       MAT(VBO_ATTRIB_MAT_FRONT_AMBIENT, 4, face, params);
1152       break;
1153    case GL_DIFFUSE:
1154       MAT(VBO_ATTRIB_MAT_FRONT_DIFFUSE, 4, face, params);
1155       break;
1156    case GL_SPECULAR:
1157       MAT(VBO_ATTRIB_MAT_FRONT_SPECULAR, 4, face, params);
1158       break;
1159    case GL_SHININESS:
1160       if (*params < 0 || *params > ctx->Const.MaxShininess) {
1161          _mesa_compile_error(ctx, GL_INVALID_VALUE, "glMaterial(shininess)");
1162       }
1163       else {
1164          MAT(VBO_ATTRIB_MAT_FRONT_SHININESS, 1, face, params);
1165       }
1166       break;
1167    case GL_COLOR_INDEXES:
1168       MAT(VBO_ATTRIB_MAT_FRONT_INDEXES, 3, face, params);
1169       break;
1170    case GL_AMBIENT_AND_DIFFUSE:
1171       MAT(VBO_ATTRIB_MAT_FRONT_AMBIENT, 4, face, params);
1172       MAT(VBO_ATTRIB_MAT_FRONT_DIFFUSE, 4, face, params);
1173       break;
1174    default:
1175       _mesa_compile_error(ctx, GL_INVALID_ENUM, "glMaterial(pname)");
1176       return;
1177    }
1178 }
1179
1180
1181 /* Cope with EvalCoord/CallList called within a begin/end object:
1182  *     -- Flush current buffer
1183  *     -- Fallback to opcodes for the rest of the begin/end object.
1184  */
1185 static void
1186 dlist_fallback(struct gl_context *ctx)
1187 {
1188    struct vbo_save_context *save = &vbo_context(ctx)->save;
1189
1190    if (save->vert_count || save->prim_count) {
1191       if (save->prim_count > 0) {
1192          /* Close off in-progress primitive. */
1193          GLint i = save->prim_count - 1;
1194          save->prims[i].count = save->vert_count - save->prims[i].start;
1195       }
1196
1197       /* Need to replay this display list with loopback,
1198        * unfortunately, otherwise this primitive won't be handled
1199        * properly:
1200        */
1201       save->dangling_attr_ref = GL_TRUE;
1202
1203       compile_vertex_list(ctx);
1204    }
1205
1206    copy_to_current(ctx);
1207    reset_vertex(ctx);
1208    reset_counters(ctx);
1209    if (save->out_of_memory) {
1210       _mesa_install_save_vtxfmt(ctx, &save->vtxfmt_noop);
1211    }
1212    else {
1213       _mesa_install_save_vtxfmt(ctx, &ctx->ListState.ListVtxfmt);
1214    }
1215    ctx->Driver.SaveNeedFlush = GL_FALSE;
1216 }
1217
1218
1219 static void GLAPIENTRY
1220 _save_EvalCoord1f(GLfloat u)
1221 {
1222    GET_CURRENT_CONTEXT(ctx);
1223    dlist_fallback(ctx);
1224    CALL_EvalCoord1f(ctx->Save, (u));
1225 }
1226
1227 static void GLAPIENTRY
1228 _save_EvalCoord1fv(const GLfloat * v)
1229 {
1230    GET_CURRENT_CONTEXT(ctx);
1231    dlist_fallback(ctx);
1232    CALL_EvalCoord1fv(ctx->Save, (v));
1233 }
1234
1235 static void GLAPIENTRY
1236 _save_EvalCoord2f(GLfloat u, GLfloat v)
1237 {
1238    GET_CURRENT_CONTEXT(ctx);
1239    dlist_fallback(ctx);
1240    CALL_EvalCoord2f(ctx->Save, (u, v));
1241 }
1242
1243 static void GLAPIENTRY
1244 _save_EvalCoord2fv(const GLfloat * v)
1245 {
1246    GET_CURRENT_CONTEXT(ctx);
1247    dlist_fallback(ctx);
1248    CALL_EvalCoord2fv(ctx->Save, (v));
1249 }
1250
1251 static void GLAPIENTRY
1252 _save_EvalPoint1(GLint i)
1253 {
1254    GET_CURRENT_CONTEXT(ctx);
1255    dlist_fallback(ctx);
1256    CALL_EvalPoint1(ctx->Save, (i));
1257 }
1258
1259 static void GLAPIENTRY
1260 _save_EvalPoint2(GLint i, GLint j)
1261 {
1262    GET_CURRENT_CONTEXT(ctx);
1263    dlist_fallback(ctx);
1264    CALL_EvalPoint2(ctx->Save, (i, j));
1265 }
1266
1267 static void GLAPIENTRY
1268 _save_CallList(GLuint l)
1269 {
1270    GET_CURRENT_CONTEXT(ctx);
1271    dlist_fallback(ctx);
1272    CALL_CallList(ctx->Save, (l));
1273 }
1274
1275 static void GLAPIENTRY
1276 _save_CallLists(GLsizei n, GLenum type, const GLvoid * v)
1277 {
1278    GET_CURRENT_CONTEXT(ctx);
1279    dlist_fallback(ctx);
1280    CALL_CallLists(ctx->Save, (n, type, v));
1281 }
1282
1283
1284
1285 /**
1286  * Called when a glBegin is getting compiled into a display list.
1287  * Updating of ctx->Driver.CurrentSavePrimitive is already taken care of.
1288  */
1289 void
1290 vbo_save_NotifyBegin(struct gl_context *ctx, GLenum mode,
1291                      bool no_current_update)
1292 {
1293    struct vbo_save_context *save = &vbo_context(ctx)->save;
1294    const GLuint i = save->prim_count++;
1295
1296    ctx->Driver.CurrentSavePrimitive = mode;
1297
1298    assert(i < save->prim_max);
1299    save->prims[i].mode = mode & VBO_SAVE_PRIM_MODE_MASK;
1300    save->prims[i].begin = 1;
1301    save->prims[i].end = 0;
1302    save->prims[i].start = save->vert_count;
1303    save->prims[i].count = 0;
1304
1305    save->no_current_update = no_current_update;
1306
1307    if (save->out_of_memory) {
1308       _mesa_install_save_vtxfmt(ctx, &save->vtxfmt_noop);
1309    }
1310    else {
1311       _mesa_install_save_vtxfmt(ctx, &save->vtxfmt);
1312    }
1313
1314    /* We need to call vbo_save_SaveFlushVertices() if there's state change */
1315    ctx->Driver.SaveNeedFlush = GL_TRUE;
1316 }
1317
1318
1319 static void GLAPIENTRY
1320 _save_End(void)
1321 {
1322    GET_CURRENT_CONTEXT(ctx);
1323    struct vbo_save_context *save = &vbo_context(ctx)->save;
1324    const GLint i = save->prim_count - 1;
1325
1326    ctx->Driver.CurrentSavePrimitive = PRIM_OUTSIDE_BEGIN_END;
1327    save->prims[i].end = 1;
1328    save->prims[i].count = (save->vert_count - save->prims[i].start);
1329
1330    if (i == (GLint) save->prim_max - 1) {
1331       compile_vertex_list(ctx);
1332       assert(save->copied.nr == 0);
1333    }
1334
1335    /* Swap out this vertex format while outside begin/end.  Any color,
1336     * etc. received between here and the next begin will be compiled
1337     * as opcodes.
1338     */
1339    if (save->out_of_memory) {
1340       _mesa_install_save_vtxfmt(ctx, &save->vtxfmt_noop);
1341    }
1342    else {
1343       _mesa_install_save_vtxfmt(ctx, &ctx->ListState.ListVtxfmt);
1344    }
1345 }
1346
1347
1348 static void GLAPIENTRY
1349 _save_Begin(GLenum mode)
1350 {
1351    GET_CURRENT_CONTEXT(ctx);
1352    (void) mode;
1353    _mesa_compile_error(ctx, GL_INVALID_OPERATION, "Recursive glBegin");
1354 }
1355
1356
1357 static void GLAPIENTRY
1358 _save_PrimitiveRestartNV(void)
1359 {
1360    GET_CURRENT_CONTEXT(ctx);
1361    struct vbo_save_context *save = &vbo_context(ctx)->save;
1362
1363    if (save->prim_count == 0) {
1364       /* We're not inside a glBegin/End pair, so calling glPrimitiverRestartNV
1365        * is an error.
1366        */
1367       _mesa_compile_error(ctx, GL_INVALID_OPERATION,
1368                           "glPrimitiveRestartNV called outside glBegin/End");
1369    } else {
1370       /* get current primitive mode */
1371       GLenum curPrim = save->prims[save->prim_count - 1].mode;
1372       bool no_current_update = save->no_current_update;
1373
1374       /* restart primitive */
1375       CALL_End(ctx->CurrentServerDispatch, ());
1376       vbo_save_NotifyBegin(ctx, curPrim, no_current_update);
1377    }
1378 }
1379
1380
1381 /* Unlike the functions above, these are to be hooked into the vtxfmt
1382  * maintained in ctx->ListState, active when the list is known or
1383  * suspected to be outside any begin/end primitive.
1384  * Note: OBE = Outside Begin/End
1385  */
1386 static void GLAPIENTRY
1387 _save_OBE_Rectf(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2)
1388 {
1389    GET_CURRENT_CONTEXT(ctx);
1390    struct _glapi_table *dispatch = ctx->CurrentServerDispatch;
1391
1392    vbo_save_NotifyBegin(ctx, GL_QUADS, false);
1393    CALL_Vertex2f(dispatch, (x1, y1));
1394    CALL_Vertex2f(dispatch, (x2, y1));
1395    CALL_Vertex2f(dispatch, (x2, y2));
1396    CALL_Vertex2f(dispatch, (x1, y2));
1397    CALL_End(dispatch, ());
1398 }
1399
1400
1401 static void GLAPIENTRY
1402 _save_OBE_Rectd(GLdouble x1, GLdouble y1, GLdouble x2, GLdouble y2)
1403 {
1404    _save_OBE_Rectf((GLfloat) x1, (GLfloat) y1, (GLfloat) x2, (GLfloat) y2);
1405 }
1406
1407 static void GLAPIENTRY
1408 _save_OBE_Rectdv(const GLdouble *v1, const GLdouble *v2)
1409 {
1410    _save_OBE_Rectf((GLfloat) v1[0], (GLfloat) v1[1], (GLfloat) v2[0], (GLfloat) v2[1]);
1411 }
1412
1413 static void GLAPIENTRY
1414 _save_OBE_Rectfv(const GLfloat *v1, const GLfloat *v2)
1415 {
1416    _save_OBE_Rectf(v1[0], v1[1], v2[0], v2[1]);
1417 }
1418
1419 static void GLAPIENTRY
1420 _save_OBE_Recti(GLint x1, GLint y1, GLint x2, GLint y2)
1421 {
1422    _save_OBE_Rectf((GLfloat) x1, (GLfloat) y1, (GLfloat) x2, (GLfloat) y2);
1423 }
1424
1425 static void GLAPIENTRY
1426 _save_OBE_Rectiv(const GLint *v1, const GLint *v2)
1427 {
1428    _save_OBE_Rectf((GLfloat) v1[0], (GLfloat) v1[1], (GLfloat) v2[0], (GLfloat) v2[1]);
1429 }
1430
1431 static void GLAPIENTRY
1432 _save_OBE_Rects(GLshort x1, GLshort y1, GLshort x2, GLshort y2)
1433 {
1434    _save_OBE_Rectf((GLfloat) x1, (GLfloat) y1, (GLfloat) x2, (GLfloat) y2);
1435 }
1436
1437 static void GLAPIENTRY
1438 _save_OBE_Rectsv(const GLshort *v1, const GLshort *v2)
1439 {
1440    _save_OBE_Rectf((GLfloat) v1[0], (GLfloat) v1[1], (GLfloat) v2[0], (GLfloat) v2[1]);
1441 }
1442
1443
1444 static void GLAPIENTRY
1445 _save_OBE_DrawArrays(GLenum mode, GLint start, GLsizei count)
1446 {
1447    GET_CURRENT_CONTEXT(ctx);
1448    struct gl_vertex_array_object *vao = ctx->Array.VAO;
1449    struct vbo_save_context *save = &vbo_context(ctx)->save;
1450    GLint i;
1451
1452    if (!_mesa_is_valid_prim_mode(ctx, mode)) {
1453       _mesa_compile_error(ctx, GL_INVALID_ENUM, "glDrawArrays(mode)");
1454       return;
1455    }
1456    if (count < 0) {
1457       _mesa_compile_error(ctx, GL_INVALID_VALUE, "glDrawArrays(count<0)");
1458       return;
1459    }
1460
1461    if (save->out_of_memory)
1462       return;
1463
1464    /* Make sure to process any VBO binding changes */
1465    _mesa_update_state(ctx);
1466
1467    _mesa_vao_map_arrays(ctx, vao, GL_MAP_READ_BIT);
1468
1469    vbo_save_NotifyBegin(ctx, mode, true);
1470
1471    for (i = 0; i < count; i++)
1472       _mesa_array_element(ctx, start + i);
1473    CALL_End(ctx->CurrentServerDispatch, ());
1474
1475    _mesa_vao_unmap_arrays(ctx, vao);
1476 }
1477
1478
1479 static void GLAPIENTRY
1480 _save_OBE_MultiDrawArrays(GLenum mode, const GLint *first,
1481                           const GLsizei *count, GLsizei primcount)
1482 {
1483    GET_CURRENT_CONTEXT(ctx);
1484    GLint i;
1485
1486    if (!_mesa_is_valid_prim_mode(ctx, mode)) {
1487       _mesa_compile_error(ctx, GL_INVALID_ENUM, "glMultiDrawArrays(mode)");
1488       return;
1489    }
1490
1491    if (primcount < 0) {
1492       _mesa_compile_error(ctx, GL_INVALID_VALUE,
1493                           "glMultiDrawArrays(primcount<0)");
1494       return;
1495    }
1496
1497    for (i = 0; i < primcount; i++) {
1498       if (count[i] < 0) {
1499          _mesa_compile_error(ctx, GL_INVALID_VALUE,
1500                              "glMultiDrawArrays(count[i]<0)");
1501          return;
1502       }
1503    }
1504
1505    for (i = 0; i < primcount; i++) {
1506       if (count[i] > 0) {
1507          _save_OBE_DrawArrays(mode, first[i], count[i]);
1508       }
1509    }
1510 }
1511
1512
1513 static void
1514 array_element(struct gl_context *ctx,
1515               GLint basevertex, GLuint elt, unsigned index_size_shift)
1516 {
1517    /* Section 10.3.5 Primitive Restart:
1518     * [...]
1519     *    When one of the *BaseVertex drawing commands specified in section 10.5
1520     * is used, the primitive restart comparison occurs before the basevertex
1521     * offset is added to the array index.
1522     */
1523    /* If PrimitiveRestart is enabled and the index is the RestartIndex
1524     * then we call PrimitiveRestartNV and return.
1525     */
1526    if (ctx->Array._PrimitiveRestart[index_size_shift] &&
1527        elt == ctx->Array._RestartIndex[index_size_shift]) {
1528       CALL_PrimitiveRestartNV(ctx->CurrentServerDispatch, ());
1529       return;
1530    }
1531
1532    _mesa_array_element(ctx, basevertex + elt);
1533 }
1534
1535
1536 /* Could do better by copying the arrays and element list intact and
1537  * then emitting an indexed prim at runtime.
1538  */
1539 static void GLAPIENTRY
1540 _save_OBE_DrawElementsBaseVertex(GLenum mode, GLsizei count, GLenum type,
1541                                  const GLvoid * indices, GLint basevertex)
1542 {
1543    GET_CURRENT_CONTEXT(ctx);
1544    struct vbo_save_context *save = &vbo_context(ctx)->save;
1545    struct gl_vertex_array_object *vao = ctx->Array.VAO;
1546    struct gl_buffer_object *indexbuf = vao->IndexBufferObj;
1547    GLint i;
1548
1549    if (!_mesa_is_valid_prim_mode(ctx, mode)) {
1550       _mesa_compile_error(ctx, GL_INVALID_ENUM, "glDrawElements(mode)");
1551       return;
1552    }
1553    if (count < 0) {
1554       _mesa_compile_error(ctx, GL_INVALID_VALUE, "glDrawElements(count<0)");
1555       return;
1556    }
1557    if (type != GL_UNSIGNED_BYTE &&
1558        type != GL_UNSIGNED_SHORT &&
1559        type != GL_UNSIGNED_INT) {
1560       _mesa_compile_error(ctx, GL_INVALID_VALUE, "glDrawElements(count<0)");
1561       return;
1562    }
1563
1564    if (save->out_of_memory)
1565       return;
1566
1567    /* Make sure to process any VBO binding changes */
1568    _mesa_update_state(ctx);
1569
1570    _mesa_vao_map(ctx, vao, GL_MAP_READ_BIT);
1571
1572    if (indexbuf)
1573       indices =
1574          ADD_POINTERS(indexbuf->Mappings[MAP_INTERNAL].Pointer, indices);
1575
1576    vbo_save_NotifyBegin(ctx, mode, true);
1577
1578    switch (type) {
1579    case GL_UNSIGNED_BYTE:
1580       for (i = 0; i < count; i++)
1581          array_element(ctx, basevertex, ((GLubyte *) indices)[i], 0);
1582       break;
1583    case GL_UNSIGNED_SHORT:
1584       for (i = 0; i < count; i++)
1585          array_element(ctx, basevertex, ((GLushort *) indices)[i], 1);
1586       break;
1587    case GL_UNSIGNED_INT:
1588       for (i = 0; i < count; i++)
1589          array_element(ctx, basevertex, ((GLuint *) indices)[i], 2);
1590       break;
1591    default:
1592       _mesa_error(ctx, GL_INVALID_ENUM, "glDrawElements(type)");
1593       break;
1594    }
1595
1596    CALL_End(ctx->CurrentServerDispatch, ());
1597
1598    _mesa_vao_unmap(ctx, vao);
1599 }
1600
1601 static void GLAPIENTRY
1602 _save_OBE_DrawElements(GLenum mode, GLsizei count, GLenum type,
1603                        const GLvoid * indices)
1604 {
1605    _save_OBE_DrawElementsBaseVertex(mode, count, type, indices, 0);
1606 }
1607
1608
1609 static void GLAPIENTRY
1610 _save_OBE_DrawRangeElements(GLenum mode, GLuint start, GLuint end,
1611                             GLsizei count, GLenum type,
1612                             const GLvoid * indices)
1613 {
1614    GET_CURRENT_CONTEXT(ctx);
1615    struct vbo_save_context *save = &vbo_context(ctx)->save;
1616
1617    if (!_mesa_is_valid_prim_mode(ctx, mode)) {
1618       _mesa_compile_error(ctx, GL_INVALID_ENUM, "glDrawRangeElements(mode)");
1619       return;
1620    }
1621    if (count < 0) {
1622       _mesa_compile_error(ctx, GL_INVALID_VALUE,
1623                           "glDrawRangeElements(count<0)");
1624       return;
1625    }
1626    if (type != GL_UNSIGNED_BYTE &&
1627        type != GL_UNSIGNED_SHORT &&
1628        type != GL_UNSIGNED_INT) {
1629       _mesa_compile_error(ctx, GL_INVALID_ENUM, "glDrawRangeElements(type)");
1630       return;
1631    }
1632    if (end < start) {
1633       _mesa_compile_error(ctx, GL_INVALID_VALUE,
1634                           "glDrawRangeElements(end < start)");
1635       return;
1636    }
1637
1638    if (save->out_of_memory)
1639       return;
1640
1641    _save_OBE_DrawElements(mode, count, type, indices);
1642 }
1643
1644
1645 static void GLAPIENTRY
1646 _save_OBE_MultiDrawElements(GLenum mode, const GLsizei *count, GLenum type,
1647                             const GLvoid * const *indices, GLsizei primcount)
1648 {
1649    GET_CURRENT_CONTEXT(ctx);
1650    struct _glapi_table *dispatch = ctx->CurrentServerDispatch;
1651    GLsizei i;
1652
1653    for (i = 0; i < primcount; i++) {
1654       if (count[i] > 0) {
1655          CALL_DrawElements(dispatch, (mode, count[i], type, indices[i]));
1656       }
1657    }
1658 }
1659
1660
1661 static void GLAPIENTRY
1662 _save_OBE_MultiDrawElementsBaseVertex(GLenum mode, const GLsizei *count,
1663                                       GLenum type,
1664                                       const GLvoid * const *indices,
1665                                       GLsizei primcount,
1666                                       const GLint *basevertex)
1667 {
1668    GET_CURRENT_CONTEXT(ctx);
1669    struct _glapi_table *dispatch = ctx->CurrentServerDispatch;
1670    GLsizei i;
1671
1672    for (i = 0; i < primcount; i++) {
1673       if (count[i] > 0) {
1674          CALL_DrawElementsBaseVertex(dispatch, (mode, count[i], type,
1675                                                       indices[i],
1676                                                       basevertex[i]));
1677       }
1678    }
1679 }
1680
1681
1682 static void
1683 vtxfmt_init(struct gl_context *ctx)
1684 {
1685    struct vbo_save_context *save = &vbo_context(ctx)->save;
1686    GLvertexformat *vfmt = &save->vtxfmt;
1687
1688 #define NAME_AE(x) _ae_##x
1689 #define NAME_CALLLIST(x) _save_##x
1690 #define NAME(x) _save_##x
1691 #define NAME_ES(x) _save_##x##ARB
1692
1693 #include "vbo_init_tmp.h"
1694 }
1695
1696
1697 /**
1698  * Initialize the dispatch table with the VBO functions for display
1699  * list compilation.
1700  */
1701 void
1702 vbo_initialize_save_dispatch(const struct gl_context *ctx,
1703                              struct _glapi_table *exec)
1704 {
1705    SET_DrawArrays(exec, _save_OBE_DrawArrays);
1706    SET_MultiDrawArrays(exec, _save_OBE_MultiDrawArrays);
1707    SET_DrawElements(exec, _save_OBE_DrawElements);
1708    SET_DrawElementsBaseVertex(exec, _save_OBE_DrawElementsBaseVertex);
1709    SET_DrawRangeElements(exec, _save_OBE_DrawRangeElements);
1710    SET_MultiDrawElementsEXT(exec, _save_OBE_MultiDrawElements);
1711    SET_MultiDrawElementsBaseVertex(exec, _save_OBE_MultiDrawElementsBaseVertex);
1712    SET_Rectf(exec, _save_OBE_Rectf);
1713    SET_Rectd(exec, _save_OBE_Rectd);
1714    SET_Rectdv(exec, _save_OBE_Rectdv);
1715    SET_Rectfv(exec, _save_OBE_Rectfv);
1716    SET_Recti(exec, _save_OBE_Recti);
1717    SET_Rectiv(exec, _save_OBE_Rectiv);
1718    SET_Rects(exec, _save_OBE_Rects);
1719    SET_Rectsv(exec, _save_OBE_Rectsv);
1720
1721    /* Note: other glDraw functins aren't compiled into display lists */
1722 }
1723
1724
1725
1726 void
1727 vbo_save_SaveFlushVertices(struct gl_context *ctx)
1728 {
1729    struct vbo_save_context *save = &vbo_context(ctx)->save;
1730
1731    /* Noop when we are actually active:
1732     */
1733    if (ctx->Driver.CurrentSavePrimitive <= PRIM_MAX)
1734       return;
1735
1736    if (save->vert_count || save->prim_count)
1737       compile_vertex_list(ctx);
1738
1739    copy_to_current(ctx);
1740    reset_vertex(ctx);
1741    reset_counters(ctx);
1742    ctx->Driver.SaveNeedFlush = GL_FALSE;
1743 }
1744
1745
1746 /**
1747  * Called from glNewList when we're starting to compile a display list.
1748  */
1749 void
1750 vbo_save_NewList(struct gl_context *ctx, GLuint list, GLenum mode)
1751 {
1752    struct vbo_save_context *save = &vbo_context(ctx)->save;
1753
1754    (void) list;
1755    (void) mode;
1756
1757    if (!save->prim_store)
1758       save->prim_store = alloc_prim_store();
1759
1760    if (!save->vertex_store)
1761       save->vertex_store = alloc_vertex_store(ctx);
1762
1763    save->buffer_ptr = vbo_save_map_vertex_store(ctx, save->vertex_store);
1764
1765    reset_vertex(ctx);
1766    reset_counters(ctx);
1767    ctx->Driver.SaveNeedFlush = GL_FALSE;
1768 }
1769
1770
1771 /**
1772  * Called from glEndList when we're finished compiling a display list.
1773  */
1774 void
1775 vbo_save_EndList(struct gl_context *ctx)
1776 {
1777    struct vbo_save_context *save = &vbo_context(ctx)->save;
1778
1779    /* EndList called inside a (saved) Begin/End pair?
1780     */
1781    if (_mesa_inside_dlist_begin_end(ctx)) {
1782       if (save->prim_count > 0) {
1783          GLint i = save->prim_count - 1;
1784          ctx->Driver.CurrentSavePrimitive = PRIM_OUTSIDE_BEGIN_END;
1785          save->prims[i].end = 0;
1786          save->prims[i].count = save->vert_count - save->prims[i].start;
1787       }
1788
1789       /* Make sure this vertex list gets replayed by the "loopback"
1790        * mechanism:
1791        */
1792       save->dangling_attr_ref = GL_TRUE;
1793       vbo_save_SaveFlushVertices(ctx);
1794
1795       /* Swap out this vertex format while outside begin/end.  Any color,
1796        * etc. received between here and the next begin will be compiled
1797        * as opcodes.
1798        */
1799       _mesa_install_save_vtxfmt(ctx, &ctx->ListState.ListVtxfmt);
1800    }
1801
1802    vbo_save_unmap_vertex_store(ctx, save->vertex_store);
1803
1804    assert(save->vertex_size == 0);
1805 }
1806
1807
1808 /**
1809  * Called from the display list code when we're about to execute a
1810  * display list.
1811  */
1812 void
1813 vbo_save_BeginCallList(struct gl_context *ctx, struct gl_display_list *dlist)
1814 {
1815    struct vbo_save_context *save = &vbo_context(ctx)->save;
1816    save->replay_flags |= dlist->Flags;
1817 }
1818
1819
1820 /**
1821  * Called from the display list code when we're finished executing a
1822  * display list.
1823  */
1824 void
1825 vbo_save_EndCallList(struct gl_context *ctx)
1826 {
1827    struct vbo_save_context *save = &vbo_context(ctx)->save;
1828
1829    if (ctx->ListState.CallDepth == 1)
1830       save->replay_flags = 0;
1831 }
1832
1833
1834 /**
1835  * Called by display list code when a display list is being deleted.
1836  */
1837 static void
1838 vbo_destroy_vertex_list(struct gl_context *ctx, void *data)
1839 {
1840    struct vbo_save_vertex_list *node = (struct vbo_save_vertex_list *) data;
1841
1842    for (gl_vertex_processing_mode vpm = VP_MODE_FF; vpm < VP_MODE_MAX; ++vpm)
1843       _mesa_reference_vao(ctx, &node->VAO[vpm], NULL);
1844
1845    if (--node->prim_store->refcount == 0)
1846       free(node->prim_store);
1847
1848    _mesa_reference_buffer_object(ctx, &node->ib.obj, NULL);
1849    free(node->current_data);
1850    node->current_data = NULL;
1851 }
1852
1853
1854 static void
1855 vbo_print_vertex_list(struct gl_context *ctx, void *data, FILE *f)
1856 {
1857    struct vbo_save_vertex_list *node = (struct vbo_save_vertex_list *) data;
1858    GLuint i;
1859    struct gl_buffer_object *buffer = node->VAO[0]->BufferBinding[0].BufferObj;
1860    const GLuint vertex_size = _vbo_save_get_stride(node)/sizeof(GLfloat);
1861    (void) ctx;
1862
1863    fprintf(f, "VBO-VERTEX-LIST, %u vertices, %d primitives, %d vertsize, "
1864            "buffer %p\n",
1865            node->vertex_count, node->prim_count, vertex_size,
1866            buffer);
1867
1868    for (i = 0; i < node->prim_count; i++) {
1869       struct _mesa_prim *prim = &node->prims[i];
1870       fprintf(f, "   prim %d: %s %d..%d %s %s\n",
1871              i,
1872              _mesa_lookup_prim_by_nr(prim->mode),
1873              prim->start,
1874              prim->start + prim->count,
1875              (prim->begin) ? "BEGIN" : "(wrap)",
1876              (prim->end) ? "END" : "(wrap)");
1877    }
1878 }
1879
1880
1881 /**
1882  * Called during context creation/init.
1883  */
1884 static void
1885 current_init(struct gl_context *ctx)
1886 {
1887    struct vbo_save_context *save = &vbo_context(ctx)->save;
1888    GLint i;
1889
1890    for (i = VBO_ATTRIB_POS; i <= VBO_ATTRIB_GENERIC15; i++) {
1891       const GLuint j = i - VBO_ATTRIB_POS;
1892       assert(j < VERT_ATTRIB_MAX);
1893       save->currentsz[i] = &ctx->ListState.ActiveAttribSize[j];
1894       save->current[i] = (fi_type *) ctx->ListState.CurrentAttrib[j];
1895    }
1896
1897    for (i = VBO_ATTRIB_FIRST_MATERIAL; i <= VBO_ATTRIB_LAST_MATERIAL; i++) {
1898       const GLuint j = i - VBO_ATTRIB_FIRST_MATERIAL;
1899       assert(j < MAT_ATTRIB_MAX);
1900       save->currentsz[i] = &ctx->ListState.ActiveMaterialSize[j];
1901       save->current[i] = (fi_type *) ctx->ListState.CurrentMaterial[j];
1902    }
1903 }
1904
1905
1906 /**
1907  * Initialize the display list compiler.  Called during context creation.
1908  */
1909 void
1910 vbo_save_api_init(struct vbo_save_context *save)
1911 {
1912    struct gl_context *ctx = gl_context_from_vbo_save(save);
1913
1914    save->opcode_vertex_list =
1915       _mesa_dlist_alloc_opcode(ctx,
1916                                sizeof(struct vbo_save_vertex_list),
1917                                vbo_save_playback_vertex_list,
1918                                vbo_destroy_vertex_list,
1919                                vbo_print_vertex_list);
1920
1921    vtxfmt_init(ctx);
1922    current_init(ctx);
1923    _mesa_noop_vtxfmt_init(ctx, &save->vtxfmt_noop);
1924 }