gallium,util: Pull u_indices and u_primconvert back into gallium
[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  * The compilation process works as follows. All vertex attributes
69  * except position are copied to vbo_save_context::attrptr (see ATTR_UNION).
70  * 'attrptr' are pointers to vbo_save_context::vertex ordered according to the enabled
71  * attributes (se upgrade_vertex).
72  * When the position attribute is received, all the attributes are then 
73  * copied to the vertex_store (see the end of ATTR_UNION).
74  * The vertex_store is simply an extensible float array.
75  * When the vertex list needs to be compiled (see compile_vertex_list),
76  * several transformations are performed:
77  *   - some primitives are merged together (eg: two consecutive GL_TRIANGLES
78  * with 3 vertices can be merged in a single GL_TRIANGLES with 6 vertices).
79  *   - an index buffer is built.
80  *   - identical vertices are detected and only one is kept.
81  * At the end of this transformation, the index buffer and the vertex buffer
82  * are uploaded in vRAM in the same buffer object.
83  * This buffer object is shared between multiple display list to allow
84  * draw calls merging later.
85  *
86  * The layout of this buffer for two display lists is:
87  *    V0A0|V0A1|V1A0|V1A1|P0I0|P0I1|V0A0V0A1V0A2|V1A1V1A1V1A2|...
88  *                                 ` new list starts
89  *        - VxAy: vertex x, attributes y
90  *        - PxIy: draw x, index y
91  *
92  * To allow draw call merging, display list must use the same VAO, including
93  * the same Offset in the buffer object. To achieve this, the start values of
94  * the primitive are shifted and the indices adjusted (see offset_diff and
95  * start_offset in compile_vertex_list).
96  *
97  * Display list using the loopback code (see vbo_save_playback_vertex_list_loopback),
98  * can't be drawn with an index buffer so this transformation is disabled
99  * in this case.
100  */
101
102
103 #include "main/glheader.h"
104 #include "main/arrayobj.h"
105 #include "main/bufferobj.h"
106 #include "main/context.h"
107 #include "main/dlist.h"
108 #include "main/enums.h"
109 #include "main/eval.h"
110 #include "main/macros.h"
111 #include "main/draw_validate.h"
112 #include "main/api_arrayelt.h"
113 #include "main/dispatch.h"
114 #include "main/state.h"
115 #include "main/varray.h"
116 #include "util/bitscan.h"
117 #include "util/u_memory.h"
118 #include "util/hash_table.h"
119 #include "gallium/auxiliary/indices/u_indices.h"
120 #include "util/u_prim.h"
121
122 #include "gallium/include/pipe/p_state.h"
123
124 #include "vbo_private.h"
125 #include "api_exec_decl.h"
126 #include "api_save.h"
127
128 #ifdef ERROR
129 #undef ERROR
130 #endif
131
132 /* An interesting VBO number/name to help with debugging */
133 #define VBO_BUF_ID  12345
134
135 static void GLAPIENTRY
136 _save_Materialfv(GLenum face, GLenum pname, const GLfloat *params);
137
138 static void GLAPIENTRY
139 _save_EvalCoord1f(GLfloat u);
140
141 static void GLAPIENTRY
142 _save_EvalCoord2f(GLfloat u, GLfloat v);
143
144 /*
145  * NOTE: Old 'parity' issue is gone, but copying can still be
146  * wrong-footed on replay.
147  */
148 static GLuint
149 copy_vertices(struct gl_context *ctx,
150               const struct vbo_save_vertex_list *node,
151               const fi_type * src_buffer)
152 {
153    struct vbo_save_context *save = &vbo_context(ctx)->save;
154    struct _mesa_prim *prim = &node->cold->prims[node->cold->prim_count - 1];
155    GLuint sz = save->vertex_size;
156
157    if (prim->end || !prim->count || !sz)
158       return 0;
159
160    const fi_type *src = src_buffer + prim->start * sz;
161    assert(save->copied.buffer == NULL);
162    save->copied.buffer = malloc(sizeof(fi_type) * sz * prim->count);
163
164    unsigned r = vbo_copy_vertices(ctx, prim->mode, prim->start, &prim->count,
165                                   prim->begin, sz, true, save->copied.buffer, src);
166    if (!r) {
167       free(save->copied.buffer);
168       save->copied.buffer = NULL;
169    }
170    return r;
171 }
172
173
174 static struct vbo_save_primitive_store *
175 realloc_prim_store(struct vbo_save_primitive_store *store, int prim_count)
176 {
177    if (store == NULL)
178       store = CALLOC_STRUCT(vbo_save_primitive_store);
179
180    uint32_t old_size = store->size;
181    store->size = prim_count;
182    assert (old_size < store->size);
183    store->prims = realloc(store->prims, store->size * sizeof(struct _mesa_prim));
184    memset(&store->prims[old_size], 0, (store->size - old_size) * sizeof(struct _mesa_prim));
185
186    return store;
187 }
188
189
190 static void
191 reset_counters(struct gl_context *ctx)
192 {
193    struct vbo_save_context *save = &vbo_context(ctx)->save;
194
195    save->vertex_store->used = 0;
196    save->prim_store->used = 0;
197    save->dangling_attr_ref = GL_FALSE;
198 }
199
200 /**
201  * For a list of prims, try merging prims that can just be extensions of the
202  * previous prim.
203  */
204 static void
205 merge_prims(struct gl_context *ctx, struct _mesa_prim *prim_list,
206             GLuint *prim_count)
207 {
208    GLuint i;
209    struct _mesa_prim *prev_prim = prim_list;
210
211    for (i = 1; i < *prim_count; i++) {
212       struct _mesa_prim *this_prim = prim_list + i;
213
214       vbo_try_prim_conversion(&this_prim->mode, &this_prim->count);
215
216       if (vbo_merge_draws(ctx, true,
217                           prev_prim->mode, this_prim->mode,
218                           prev_prim->start, this_prim->start,
219                           &prev_prim->count, this_prim->count,
220                           prev_prim->basevertex, this_prim->basevertex,
221                           &prev_prim->end,
222                           this_prim->begin, this_prim->end)) {
223          /* We've found a prim that just extend the previous one.  Tack it
224           * onto the previous one, and let this primitive struct get dropped.
225           */
226          continue;
227       }
228
229       /* If any previous primitives have been dropped, then we need to copy
230        * this later one into the next available slot.
231        */
232       prev_prim++;
233       if (prev_prim != this_prim)
234          *prev_prim = *this_prim;
235    }
236
237    *prim_count = prev_prim - prim_list + 1;
238 }
239
240
241 /**
242  * Convert GL_LINE_LOOP primitive into GL_LINE_STRIP so that drivers
243  * don't have to worry about handling the _mesa_prim::begin/end flags.
244  * See https://bugs.freedesktop.org/show_bug.cgi?id=81174
245  */
246 static void
247 convert_line_loop_to_strip(struct vbo_save_context *save,
248                            struct vbo_save_vertex_list *node)
249 {
250    struct _mesa_prim *prim = &node->cold->prims[node->cold->prim_count - 1];
251
252    assert(prim->mode == GL_LINE_LOOP);
253
254    if (prim->end) {
255       /* Copy the 0th vertex to end of the buffer and extend the
256        * vertex count by one to finish the line loop.
257        */
258       const GLuint sz = save->vertex_size;
259       /* 0th vertex: */
260       const fi_type *src = save->vertex_store->buffer_in_ram + prim->start * sz;
261       /* end of buffer: */
262       fi_type *dst = save->vertex_store->buffer_in_ram + (prim->start + prim->count) * sz;
263
264       memcpy(dst, src, sz * sizeof(float));
265
266       prim->count++;
267       node->cold->vertex_count++;
268       save->vertex_store->used += sz;
269    }
270
271    if (!prim->begin) {
272       /* Drawing the second or later section of a long line loop.
273        * Skip the 0th vertex.
274        */
275       prim->start++;
276       prim->count--;
277    }
278
279    prim->mode = GL_LINE_STRIP;
280 }
281
282
283 /* Compare the present vao if it has the same setup. */
284 static bool
285 compare_vao(gl_vertex_processing_mode mode,
286             const struct gl_vertex_array_object *vao,
287             const struct gl_buffer_object *bo, GLintptr buffer_offset,
288             GLuint stride, GLbitfield64 vao_enabled,
289             const GLubyte size[VBO_ATTRIB_MAX],
290             const GLenum16 type[VBO_ATTRIB_MAX],
291             const GLuint offset[VBO_ATTRIB_MAX])
292 {
293    if (!vao)
294       return false;
295
296    /* If the enabled arrays are not the same we are not equal. */
297    if (vao_enabled != vao->Enabled)
298       return false;
299
300    /* Check the buffer binding at 0 */
301    if (vao->BufferBinding[0].BufferObj != bo)
302       return false;
303    /* BufferBinding[0].Offset != buffer_offset is checked per attribute */
304    if (vao->BufferBinding[0].Stride != stride)
305       return false;
306    assert(vao->BufferBinding[0].InstanceDivisor == 0);
307
308    /* Retrieve the mapping from VBO_ATTRIB to VERT_ATTRIB space */
309    const GLubyte *const vao_to_vbo_map = _vbo_attribute_alias_map[mode];
310
311    /* Now check the enabled arrays */
312    GLbitfield mask = vao_enabled;
313    while (mask) {
314       const int attr = u_bit_scan(&mask);
315       const unsigned char vbo_attr = vao_to_vbo_map[attr];
316       const GLenum16 tp = type[vbo_attr];
317       const GLintptr off = offset[vbo_attr] + buffer_offset;
318       const struct gl_array_attributes *attrib = &vao->VertexAttrib[attr];
319       if (attrib->RelativeOffset + vao->BufferBinding[0].Offset != off)
320          return false;
321       if (attrib->Format.Type != tp)
322          return false;
323       if (attrib->Format.Size != size[vbo_attr])
324          return false;
325       assert(attrib->Format.Format == GL_RGBA);
326       assert(attrib->Format.Normalized == GL_FALSE);
327       assert(attrib->Format.Integer == vbo_attrtype_to_integer_flag(tp));
328       assert(attrib->Format.Doubles == vbo_attrtype_to_double_flag(tp));
329       assert(attrib->BufferBindingIndex == 0);
330    }
331
332    return true;
333 }
334
335
336 /* Create or reuse the vao for the vertex processing mode. */
337 static void
338 update_vao(struct gl_context *ctx,
339            gl_vertex_processing_mode mode,
340            struct gl_vertex_array_object **vao,
341            struct gl_buffer_object *bo, GLintptr buffer_offset,
342            GLuint stride, GLbitfield64 vbo_enabled,
343            const GLubyte size[VBO_ATTRIB_MAX],
344            const GLenum16 type[VBO_ATTRIB_MAX],
345            const GLuint offset[VBO_ATTRIB_MAX])
346 {
347    /* Compute the bitmasks of vao_enabled arrays */
348    GLbitfield vao_enabled = _vbo_get_vao_enabled_from_vbo(mode, vbo_enabled);
349
350    /*
351     * Check if we can possibly reuse the exisiting one.
352     * In the long term we should reset them when something changes.
353     */
354    if (compare_vao(mode, *vao, bo, buffer_offset, stride,
355                    vao_enabled, size, type, offset))
356       return;
357
358    /* The initial refcount is 1 */
359    _mesa_reference_vao(ctx, vao, NULL);
360    *vao = _mesa_new_vao(ctx, ~((GLuint)0));
361
362    /*
363     * assert(stride <= ctx->Const.MaxVertexAttribStride);
364     * MaxVertexAttribStride is not set for drivers that does not
365     * expose GL 44 or GLES 31.
366     */
367
368    /* Bind the buffer object at binding point 0 */
369    _mesa_bind_vertex_buffer(ctx, *vao, 0, bo, buffer_offset, stride, false,
370                             false);
371
372    /* Retrieve the mapping from VBO_ATTRIB to VERT_ATTRIB space
373     * Note that the position/generic0 aliasing is done in the VAO.
374     */
375    const GLubyte *const vao_to_vbo_map = _vbo_attribute_alias_map[mode];
376    /* Now set the enable arrays */
377    GLbitfield mask = vao_enabled;
378    while (mask) {
379       const int vao_attr = u_bit_scan(&mask);
380       const GLubyte vbo_attr = vao_to_vbo_map[vao_attr];
381       assert(offset[vbo_attr] <= ctx->Const.MaxVertexAttribRelativeOffset);
382
383       _vbo_set_attrib_format(ctx, *vao, vao_attr, buffer_offset,
384                              size[vbo_attr], type[vbo_attr], offset[vbo_attr]);
385       _mesa_vertex_attrib_binding(ctx, *vao, vao_attr, 0);
386    }
387    _mesa_enable_vertex_array_attribs(ctx, *vao, vao_enabled);
388    assert(vao_enabled == (*vao)->Enabled);
389    assert((vao_enabled & ~(*vao)->VertexAttribBufferMask) == 0);
390
391    /* Finalize and freeze the VAO */
392    _mesa_set_vao_immutable(ctx, *vao);
393 }
394
395 static void wrap_filled_vertex(struct gl_context *ctx);
396
397 /* Grow the vertex storage to accomodate for vertex_count new vertices */
398 static void
399 grow_vertex_storage(struct gl_context *ctx, int vertex_count)
400 {
401    struct vbo_save_context *save = &vbo_context(ctx)->save;
402    assert (save->vertex_store);
403
404    int new_size = (save->vertex_store->used +
405                    vertex_count * save->vertex_size) * sizeof(GLfloat);
406
407    /* Limit how much memory we allocate. */
408    if (save->prim_store->used > 0 &&
409        vertex_count > 0 &&
410        new_size > VBO_SAVE_BUFFER_SIZE) {
411       wrap_filled_vertex(ctx);
412       new_size = VBO_SAVE_BUFFER_SIZE;
413    }
414
415    if (new_size > save->vertex_store->buffer_in_ram_size) {
416       save->vertex_store->buffer_in_ram_size = new_size;
417       save->vertex_store->buffer_in_ram = realloc(save->vertex_store->buffer_in_ram,
418                                                   save->vertex_store->buffer_in_ram_size);
419       if (save->vertex_store->buffer_in_ram == NULL)
420          save->out_of_memory = true;
421    }
422 }
423
424 struct vertex_key {
425    unsigned vertex_size;
426    fi_type *vertex_attributes;
427 };
428
429 static uint32_t _hash_vertex_key(const void *key)
430 {
431    struct vertex_key *k = (struct vertex_key*)key;
432    unsigned sz = k->vertex_size;
433    assert(sz);
434    return _mesa_hash_data(k->vertex_attributes, sz * sizeof(float));
435 }
436
437 static bool _compare_vertex_key(const void *key1, const void *key2)
438 {
439    struct vertex_key *k1 = (struct vertex_key*)key1;
440    struct vertex_key *k2 = (struct vertex_key*)key2;
441    /* All the compared vertices are going to be drawn with the same VAO,
442     * so we can compare the attributes. */
443    assert (k1->vertex_size == k2->vertex_size);
444    return memcmp(k1->vertex_attributes,
445                  k2->vertex_attributes,
446                  k1->vertex_size * sizeof(float)) == 0;
447 }
448
449 static void _free_entry(struct hash_entry *entry)
450 {
451    free((void*)entry->key);
452 }
453
454 /* Add vertex to the vertex buffer and return its index. If this vertex is a duplicate
455  * of an existing vertex, return the original index instead.
456  */
457 static uint32_t
458 add_vertex(struct vbo_save_context *save, struct hash_table *hash_to_index,
459            uint32_t index, fi_type *new_buffer, uint32_t *max_index)
460 {
461    /* If vertex deduplication is disabled return the original index. */
462    if (!hash_to_index)
463       return index;
464
465    fi_type *vert = save->vertex_store->buffer_in_ram + save->vertex_size * index;
466
467    struct vertex_key *key = malloc(sizeof(struct vertex_key));
468    key->vertex_size = save->vertex_size;
469    key->vertex_attributes = vert;
470
471    struct hash_entry *entry = _mesa_hash_table_search(hash_to_index, key);
472    if (entry) {
473       free(key);
474       /* We found an existing vertex with the same hash, return its index. */
475       return (uintptr_t) entry->data;
476    } else {
477       /* This is a new vertex. Determine a new index and copy its attributes to the vertex
478        * buffer. Note that 'new_buffer' is created at each list compilation so we write vertices
479        * starting at index 0.
480        */
481       uint32_t n = _mesa_hash_table_num_entries(hash_to_index);
482       *max_index = MAX2(n, *max_index);
483
484       memcpy(&new_buffer[save->vertex_size * n],
485              vert,
486              save->vertex_size * sizeof(fi_type));
487
488       _mesa_hash_table_insert(hash_to_index, key, (void*)(uintptr_t)(n));
489
490       /* The index buffer is shared between list compilations, so add the base index to get
491        * the final index.
492        */
493       return n;
494    }
495 }
496
497
498 static uint32_t
499 get_vertex_count(struct vbo_save_context *save)
500 {
501    if (!save->vertex_size)
502       return 0;
503    return save->vertex_store->used / save->vertex_size;
504 }
505
506
507 /**
508  * Insert the active immediate struct onto the display list currently
509  * being built.
510  */
511 static void
512 compile_vertex_list(struct gl_context *ctx)
513 {
514    struct vbo_save_context *save = &vbo_context(ctx)->save;
515    struct vbo_save_vertex_list *node;
516
517    /* Allocate space for this structure in the display list currently
518     * being compiled.
519     */
520    node = (struct vbo_save_vertex_list *)
521       _mesa_dlist_alloc_vertex_list(ctx, !save->dangling_attr_ref && !save->no_current_update);
522
523    if (!node)
524       return;
525
526    node->cold = calloc(1, sizeof(*node->cold));
527
528    /* Make sure the pointer is aligned to the size of a pointer */
529    assert((GLintptr) node % sizeof(void *) == 0);
530
531    const GLsizei stride = save->vertex_size*sizeof(GLfloat);
532
533    node->cold->vertex_count = get_vertex_count(save);
534    node->cold->wrap_count = save->copied.nr;
535    node->cold->prims = malloc(sizeof(struct _mesa_prim) * save->prim_store->used);
536    memcpy(node->cold->prims, save->prim_store->prims, sizeof(struct _mesa_prim) * save->prim_store->used);
537    node->cold->ib.obj = NULL;
538    node->cold->prim_count = save->prim_store->used;
539
540    if (save->no_current_update) {
541       node->cold->current_data = NULL;
542    }
543    else {
544       GLuint current_size = save->vertex_size - save->attrsz[0];
545       node->cold->current_data = NULL;
546
547       if (current_size) {
548          node->cold->current_data = malloc(current_size * sizeof(GLfloat));
549          if (node->cold->current_data) {
550             const char *buffer = (const char *)save->vertex_store->buffer_in_ram;
551             unsigned attr_offset = save->attrsz[0] * sizeof(GLfloat);
552             unsigned vertex_offset = 0;
553
554             if (node->cold->vertex_count)
555                vertex_offset = (node->cold->vertex_count - 1) * stride;
556
557             memcpy(node->cold->current_data, buffer + vertex_offset + attr_offset,
558                    current_size * sizeof(GLfloat));
559          } else {
560             _mesa_error(ctx, GL_OUT_OF_MEMORY, "Current value allocation");
561             save->out_of_memory = true;
562          }
563       }
564    }
565
566    assert(save->attrsz[VBO_ATTRIB_POS] != 0 || node->cold->vertex_count == 0);
567
568    if (save->dangling_attr_ref)
569       ctx->ListState.Current.UseLoopback = true;
570
571    /* Copy duplicated vertices
572     */
573    save->copied.nr = copy_vertices(ctx, node, save->vertex_store->buffer_in_ram);
574
575    if (node->cold->prims[node->cold->prim_count - 1].mode == GL_LINE_LOOP) {
576       convert_line_loop_to_strip(save, node);
577    }
578
579    merge_prims(ctx, node->cold->prims, &node->cold->prim_count);
580
581    GLintptr buffer_offset = 0;
582    GLuint start_offset = 0;
583
584    /* Create an index buffer. */
585    node->cold->min_index = node->cold->max_index = 0;
586    if (node->cold->vertex_count == 0 || node->cold->prim_count == 0)
587       goto end;
588
589    /* We won't modify node->prims, so use a const alias to avoid unintended
590     * writes to it. */
591    const struct _mesa_prim *original_prims = node->cold->prims;
592
593    int end = original_prims[node->cold->prim_count - 1].start +
594              original_prims[node->cold->prim_count - 1].count;
595    int total_vert_count = end - original_prims[0].start;
596
597    node->cold->min_index = node->cold->prims[0].start;
598    node->cold->max_index = end - 1;
599
600    /* converting primitive types may result in many more indices */
601    bool all_prims_supported = (ctx->Const.DriverSupportedPrimMask & BITFIELD_MASK(PIPE_PRIM_MAX)) == BITFIELD_MASK(PIPE_PRIM_MAX);
602    int max_index_count = total_vert_count * (all_prims_supported ? 2 : 3);
603    uint32_t* indices = (uint32_t*) malloc(max_index_count * sizeof(uint32_t));
604    void *tmp_indices = all_prims_supported ? NULL : malloc(max_index_count * sizeof(uint32_t));
605    struct _mesa_prim *merged_prims = NULL;
606
607    int idx = 0;
608    struct hash_table *vertex_to_index = NULL;
609    fi_type *temp_vertices_buffer = NULL;
610
611    /* The loopback replay code doesn't use the index buffer, so we can't
612     * dedup vertices in this case.
613     */
614    if (!ctx->ListState.Current.UseLoopback) {
615       vertex_to_index = _mesa_hash_table_create(NULL, _hash_vertex_key, _compare_vertex_key);
616       temp_vertices_buffer = malloc(save->vertex_store->buffer_in_ram_size);
617    }
618
619    uint32_t max_index = 0;
620
621    int last_valid_prim = -1;
622    /* Construct indices array. */
623    for (unsigned i = 0; i < node->cold->prim_count; i++) {
624       assert(original_prims[i].basevertex == 0);
625       GLubyte mode = original_prims[i].mode;
626       bool converted_prim = false;
627       unsigned index_size;
628
629       int vertex_count = original_prims[i].count;
630       if (!vertex_count) {
631          continue;
632       }
633
634       /* Increase indices storage if the original estimation was too small. */
635       if (idx + 3 * vertex_count > max_index_count) {
636          max_index_count = max_index_count + 3 * vertex_count;
637          indices = (uint32_t*) realloc(indices, max_index_count * sizeof(uint32_t));
638          tmp_indices = all_prims_supported ? NULL : realloc(tmp_indices, max_index_count * sizeof(uint32_t));
639       }
640
641       /* Line strips may get converted to lines */
642       if (mode == GL_LINE_STRIP)
643          mode = GL_LINES;
644
645       if (!(ctx->Const.DriverSupportedPrimMask & BITFIELD_BIT(mode))) {
646          unsigned new_count;
647          u_generate_func trans_func;
648          enum pipe_prim_type pmode = (enum pipe_prim_type)mode;
649          u_index_generator(ctx->Const.DriverSupportedPrimMask,
650                            pmode, original_prims[i].start, vertex_count,
651                            PV_LAST, PV_LAST,
652                            &pmode, &index_size, &new_count,
653                            &trans_func);
654          if (new_count > 0)
655             trans_func(original_prims[i].start, new_count, tmp_indices);
656          vertex_count = new_count;
657          mode = (GLubyte)pmode;
658          converted_prim = true;
659       }
660
661       /* If 2 consecutive prims use the same mode => merge them. */
662       bool merge_prims = last_valid_prim >= 0 &&
663                          mode == merged_prims[last_valid_prim].mode &&
664                          mode != GL_LINE_LOOP && mode != GL_TRIANGLE_FAN &&
665                          mode != GL_QUAD_STRIP && mode != GL_POLYGON &&
666                          mode != GL_PATCHES;
667
668 /* index generation uses uint16_t if the index count is small enough */
669 #define CAST_INDEX(BASE, SIZE, IDX) ((SIZE == 2 ? (uint32_t)(((uint16_t*)BASE)[IDX]) : ((uint32_t*)BASE)[IDX]))
670       /* To be able to merge consecutive triangle strips we need to insert
671        * a degenerate triangle.
672        */
673       if (merge_prims &&
674           mode == GL_TRIANGLE_STRIP) {
675          /* Insert a degenerate triangle */
676          assert(merged_prims[last_valid_prim].mode == GL_TRIANGLE_STRIP);
677          unsigned tri_count = merged_prims[last_valid_prim].count - 2;
678
679          indices[idx] = indices[idx - 1];
680          indices[idx + 1] = add_vertex(save, vertex_to_index,
681                                        converted_prim ? CAST_INDEX(tmp_indices, index_size, 0) : original_prims[i].start,
682                                        temp_vertices_buffer, &max_index);
683          idx += 2;
684          merged_prims[last_valid_prim].count += 2;
685
686          if (tri_count % 2) {
687             /* Add another index to preserve winding order */
688             indices[idx++] = add_vertex(save, vertex_to_index,
689                                         converted_prim ? CAST_INDEX(tmp_indices, index_size, 0) : original_prims[i].start,
690                                         temp_vertices_buffer, &max_index);
691             merged_prims[last_valid_prim].count++;
692          }
693       }
694
695       int start = idx;
696
697       /* Convert line strips to lines if it'll allow if the previous
698        * prim mode is GL_LINES (so merge_prims is true) or if the next
699        * primitive mode is GL_LINES or GL_LINE_LOOP.
700        */
701       if (original_prims[i].mode == GL_LINE_STRIP &&
702           (merge_prims ||
703            (i < node->cold->prim_count - 1 &&
704             (original_prims[i + 1].mode == GL_LINE_STRIP ||
705              original_prims[i + 1].mode == GL_LINES)))) {
706          for (unsigned j = 0; j < vertex_count; j++) {
707             indices[idx++] = add_vertex(save, vertex_to_index,
708                                         converted_prim ? CAST_INDEX(tmp_indices, index_size, j) : original_prims[i].start + j,
709                                         temp_vertices_buffer, &max_index);
710             /* Repeat all but the first/last indices. */
711             if (j && j != vertex_count - 1) {
712                indices[idx++] = add_vertex(save, vertex_to_index,
713                                            converted_prim ? CAST_INDEX(tmp_indices, index_size, j) : original_prims[i].start + j,
714                                            temp_vertices_buffer, &max_index);
715             }
716          }
717       } else {
718          /* We didn't convert to LINES, so restore the original mode */
719          if (!converted_prim)
720             mode = original_prims[i].mode;
721
722          for (unsigned j = 0; j < vertex_count; j++) {
723             indices[idx++] = add_vertex(save, vertex_to_index,
724                                         converted_prim ? CAST_INDEX(tmp_indices, index_size, j) : original_prims[i].start + j,
725                                         temp_vertices_buffer, &max_index);
726          }
727       }
728
729       /* Duplicate the last vertex for incomplete primitives */
730       if (vertex_count > 0) {
731          unsigned min_vert = u_prim_vertex_count(mode)->min;
732          for (unsigned j = vertex_count; j < min_vert; j++) {
733             indices[idx++] = add_vertex(save, vertex_to_index,
734                                        converted_prim ? CAST_INDEX(tmp_indices, index_size, vertex_count - 1) :
735                                                          original_prims[i].start + vertex_count - 1,
736                                        temp_vertices_buffer, &max_index);
737          }
738       }
739
740 #undef CAST_INDEX
741       if (merge_prims) {
742          /* Update vertex count. */
743          merged_prims[last_valid_prim].count += idx - start;
744       } else {
745          /* Keep this primitive */
746          last_valid_prim += 1;
747          assert(last_valid_prim <= i);
748          merged_prims = realloc(merged_prims, (1 + last_valid_prim) * sizeof(struct _mesa_prim));
749          merged_prims[last_valid_prim] = original_prims[i];
750          merged_prims[last_valid_prim].start = start;
751          merged_prims[last_valid_prim].count = idx - start;
752       }
753       merged_prims[last_valid_prim].mode = mode;
754
755       /* converted prims will filter incomplete primitives and may have no indices */
756       assert((idx > 0 || converted_prim) && idx <= max_index_count);
757    }
758
759    unsigned merged_prim_count = last_valid_prim + 1;
760    node->cold->ib.ptr = NULL;
761    node->cold->ib.count = idx;
762    node->cold->ib.index_size_shift = (GL_UNSIGNED_INT - GL_UNSIGNED_BYTE) >> 1;
763
764    /* How many bytes do we need to store the indices and the vertices */
765    total_vert_count = vertex_to_index ? (max_index + 1) : idx;
766    unsigned total_bytes_needed = idx * sizeof(uint32_t) +
767                                  total_vert_count * save->vertex_size * sizeof(fi_type);
768
769    const GLintptr old_offset = save->VAO[0] ?
770       save->VAO[0]->BufferBinding[0].Offset + save->VAO[0]->VertexAttrib[VERT_ATTRIB_POS].RelativeOffset : 0;
771    if (old_offset != save->current_bo_bytes_used && stride > 0) {
772       GLintptr offset_diff = save->current_bo_bytes_used - old_offset;
773       while (offset_diff > 0 &&
774              save->current_bo_bytes_used < save->current_bo->Size &&
775              offset_diff % stride != 0) {
776          save->current_bo_bytes_used++;
777          offset_diff = save->current_bo_bytes_used - old_offset;
778       }
779    }
780    buffer_offset = save->current_bo_bytes_used;
781
782    /* Can we reuse the previous bo or should we allocate a new one? */
783    int available_bytes = save->current_bo ? save->current_bo->Size - save->current_bo_bytes_used : 0;
784    if (total_bytes_needed > available_bytes) {
785       if (save->current_bo)
786          _mesa_reference_buffer_object(ctx, &save->current_bo, NULL);
787       save->current_bo = _mesa_bufferobj_alloc(ctx, VBO_BUF_ID + 1);
788       bool success = _mesa_bufferobj_data(ctx,
789                                           GL_ELEMENT_ARRAY_BUFFER_ARB,
790                                           MAX2(total_bytes_needed, VBO_SAVE_BUFFER_SIZE),
791                                           NULL,
792                                           GL_STATIC_DRAW_ARB, GL_MAP_WRITE_BIT |
793                                           MESA_GALLIUM_VERTEX_STATE_STORAGE,
794                                           save->current_bo);
795       if (!success) {
796          _mesa_reference_buffer_object(ctx, &save->current_bo, NULL);
797          _mesa_error(ctx, GL_OUT_OF_MEMORY, "IB allocation");
798          save->out_of_memory = true;
799       } else {
800          save->current_bo_bytes_used = 0;
801          available_bytes = save->current_bo->Size;
802       }
803       buffer_offset = 0;
804    } else {
805       assert(old_offset <= buffer_offset);
806       const GLintptr offset_diff = buffer_offset - old_offset;
807       if (offset_diff > 0 && stride > 0 && offset_diff % stride == 0) {
808          /* The vertex size is an exact multiple of the buffer offset.
809           * This means that we can use zero-based vertex attribute pointers
810           * and specify the start of the primitive with the _mesa_prim::start
811           * field.  This results in issuing several draw calls with identical
812           * vertex attribute information.  This can result in fewer state
813           * changes in drivers.  In particular, the Gallium CSO module will
814           * filter out redundant vertex buffer changes.
815           */
816          /* We cannot immediately update the primitives as some methods below
817           * still need the uncorrected start vertices
818           */
819          start_offset = offset_diff/stride;
820          assert(old_offset == buffer_offset - offset_diff);
821          buffer_offset = old_offset;
822       }
823
824       /* Correct the primitive starts, we can only do this here as copy_vertices
825        * and convert_line_loop_to_strip above consume the uncorrected starts.
826        * On the other hand the _vbo_loopback_vertex_list call below needs the
827        * primitives to be corrected already.
828        */
829       for (unsigned i = 0; i < node->cold->prim_count; i++) {
830          node->cold->prims[i].start += start_offset;
831       }
832       /* start_offset shifts vertices (so v[0] becomes v[start_offset]), so we have
833        * to apply this transformation to all indices and max_index.
834        */
835       for (unsigned i = 0; i < idx; i++)
836          indices[i] += start_offset;
837       max_index += start_offset;
838    }
839
840    _mesa_reference_buffer_object(ctx, &node->cold->ib.obj, save->current_bo);
841
842    /* Upload the vertices first (see buffer_offset) */
843    _mesa_bufferobj_subdata(ctx,
844                            save->current_bo_bytes_used,
845                            total_vert_count * save->vertex_size * sizeof(fi_type),
846                            vertex_to_index ? temp_vertices_buffer : save->vertex_store->buffer_in_ram,
847                            node->cold->ib.obj);
848    save->current_bo_bytes_used += total_vert_count * save->vertex_size * sizeof(fi_type);
849    node->cold->bo_bytes_used = save->current_bo_bytes_used;
850
851   if (vertex_to_index) {
852       _mesa_hash_table_destroy(vertex_to_index, _free_entry);
853       free(temp_vertices_buffer);
854    }
855
856    /* Since we append the indices to an existing buffer, we need to adjust the start value of each
857     * primitive (not the indices themselves). */
858    if (!ctx->ListState.Current.UseLoopback) {
859       save->current_bo_bytes_used += align(save->current_bo_bytes_used, 4) - save->current_bo_bytes_used;
860       int indices_offset = save->current_bo_bytes_used / 4;
861       for (int i = 0; i < merged_prim_count; i++) {
862          merged_prims[i].start += indices_offset;
863       }
864    }
865
866    /* Then upload the indices. */
867    if (node->cold->ib.obj) {
868       _mesa_bufferobj_subdata(ctx,
869                               save->current_bo_bytes_used,
870                               idx * sizeof(uint32_t),
871                               indices,
872                               node->cold->ib.obj);
873       save->current_bo_bytes_used += idx * sizeof(uint32_t);
874    } else {
875       node->cold->vertex_count = 0;
876       node->cold->prim_count = 0;
877    }
878
879    /* Prepare for DrawGallium */
880    memset(&node->cold->info, 0, sizeof(struct pipe_draw_info));
881    /* The other info fields will be updated in vbo_save_playback_vertex_list */
882    node->cold->info.index_size = 4;
883    node->cold->info.instance_count = 1;
884    node->cold->info.index.gl_bo = node->cold->ib.obj;
885    if (merged_prim_count == 1) {
886       node->cold->info.mode = merged_prims[0].mode;
887       node->start_count.start = merged_prims[0].start;
888       node->start_count.count = merged_prims[0].count;
889       node->start_count.index_bias = 0;
890       node->modes = NULL;
891    } else {
892       node->modes = malloc(merged_prim_count * sizeof(unsigned char));
893       node->start_counts = malloc(merged_prim_count * sizeof(struct pipe_draw_start_count_bias));
894       for (unsigned i = 0; i < merged_prim_count; i++) {
895          node->start_counts[i].start = merged_prims[i].start;
896          node->start_counts[i].count = merged_prims[i].count;
897          node->start_counts[i].index_bias = 0;
898          node->modes[i] = merged_prims[i].mode;
899       }
900    }
901    node->num_draws = merged_prim_count;
902    if (node->num_draws > 1) {
903       bool same_mode = true;
904       for (unsigned i = 1; i < node->num_draws && same_mode; i++) {
905          same_mode = node->modes[i] == node->modes[0];
906       }
907       if (same_mode) {
908          /* All primitives use the same mode, so we can simplify a bit */
909          node->cold->info.mode = node->modes[0];
910          free(node->modes);
911          node->modes = NULL;
912       }
913    }
914
915    free(indices);
916    free(tmp_indices);
917    free(merged_prims);
918
919 end:
920    node->draw_begins = node->cold->prims[0].begin;
921
922    if (!save->current_bo) {
923       save->current_bo = _mesa_bufferobj_alloc(ctx, VBO_BUF_ID + 1);
924       bool success = _mesa_bufferobj_data(ctx,
925                                           GL_ELEMENT_ARRAY_BUFFER_ARB,
926                                           VBO_SAVE_BUFFER_SIZE,
927                                           NULL,
928                                           GL_STATIC_DRAW_ARB, GL_MAP_WRITE_BIT |
929                                           MESA_GALLIUM_VERTEX_STATE_STORAGE,
930                                           save->current_bo);
931       if (!success)
932          save->out_of_memory = true;
933    }
934
935    GLuint offsets[VBO_ATTRIB_MAX];
936    for (unsigned i = 0, offset = 0; i < VBO_ATTRIB_MAX; ++i) {
937       offsets[i] = offset;
938       offset += save->attrsz[i] * sizeof(GLfloat);
939    }
940    /* Create a pair of VAOs for the possible VERTEX_PROCESSING_MODEs
941     * Note that this may reuse the previous one of possible.
942     */
943    for (gl_vertex_processing_mode vpm = VP_MODE_FF; vpm < VP_MODE_MAX; ++vpm) {
944       /* create or reuse the vao */
945       update_vao(ctx, vpm, &save->VAO[vpm],
946                  save->current_bo, buffer_offset, stride,
947                  save->enabled, save->attrsz, save->attrtype, offsets);
948       /* Reference the vao in the dlist */
949       node->cold->VAO[vpm] = NULL;
950       _mesa_reference_vao(ctx, &node->cold->VAO[vpm], save->VAO[vpm]);
951    }
952
953    /* Prepare for DrawGalliumVertexState */
954    if (node->num_draws && ctx->Driver.DrawGalliumVertexState) {
955       for (unsigned i = 0; i < VP_MODE_MAX; i++) {
956          uint32_t enabled_attribs = _vbo_get_vao_filter(i) &
957                                     node->cold->VAO[i]->_EnabledWithMapMode;
958
959          node->state[i] =
960             ctx->Driver.CreateGalliumVertexState(ctx, node->cold->VAO[i],
961                                                  node->cold->ib.obj,
962                                                  enabled_attribs);
963          node->private_refcount[i] = 0;
964          node->enabled_attribs[i] = enabled_attribs;
965       }
966
967       node->ctx = ctx;
968       node->mode = node->cold->info.mode;
969       assert(node->cold->info.index_size == 4);
970    }
971
972    /* Deal with GL_COMPILE_AND_EXECUTE:
973     */
974    if (ctx->ExecuteFlag) {
975       /* _vbo_loopback_vertex_list doesn't use the index buffer, so we have to
976        * use buffer_in_ram (which contains all vertices) instead of current_bo
977        * (which contains deduplicated vertices *when* UseLoopback is false).
978        *
979        * The problem is that the VAO offset is based on current_bo's layout,
980        * so we have to use a temp value.
981        */
982       struct gl_vertex_array_object *vao = node->cold->VAO[VP_MODE_SHADER];
983       GLintptr original = vao->BufferBinding[0].Offset;
984       /* 'start_offset' has been added to all primitives 'start', so undo it here. */
985       vao->BufferBinding[0].Offset = -(GLintptr)(start_offset * stride);
986       _vbo_loopback_vertex_list(ctx, node, save->vertex_store->buffer_in_ram);
987       vao->BufferBinding[0].Offset = original;
988    }
989
990    /* Reset our structures for the next run of vertices:
991     */
992    reset_counters(ctx);
993 }
994
995
996 /**
997  * This is called when we fill a vertex buffer before we hit a glEnd().
998  * We
999  * TODO -- If no new vertices have been stored, don't bother saving it.
1000  */
1001 static void
1002 wrap_buffers(struct gl_context *ctx)
1003 {
1004    struct vbo_save_context *save = &vbo_context(ctx)->save;
1005    GLint i = save->prim_store->used - 1;
1006    GLenum mode;
1007
1008    assert(i < (GLint) save->prim_store->size);
1009    assert(i >= 0);
1010
1011    /* Close off in-progress primitive.
1012     */
1013    save->prim_store->prims[i].count = (get_vertex_count(save) - save->prim_store->prims[i].start);
1014    mode = save->prim_store->prims[i].mode;
1015
1016    /* store the copied vertices, and allocate a new list.
1017     */
1018    compile_vertex_list(ctx);
1019
1020    /* Restart interrupted primitive
1021     */
1022    save->prim_store->prims[0].mode = mode;
1023    save->prim_store->prims[0].begin = 0;
1024    save->prim_store->prims[0].end = 0;
1025    save->prim_store->prims[0].start = 0;
1026    save->prim_store->prims[0].count = 0;
1027    save->prim_store->used = 1;
1028 }
1029
1030
1031 /**
1032  * Called only when buffers are wrapped as the result of filling the
1033  * vertex_store struct.
1034  */
1035 static void
1036 wrap_filled_vertex(struct gl_context *ctx)
1037 {
1038    struct vbo_save_context *save = &vbo_context(ctx)->save;
1039    unsigned numComponents;
1040
1041    /* Emit a glEnd to close off the last vertex list.
1042     */
1043    wrap_buffers(ctx);
1044
1045    assert(save->vertex_store->used == 0 && save->vertex_store->used == 0);
1046
1047    /* Copy stored stored vertices to start of new list.
1048     */
1049    numComponents = save->copied.nr * save->vertex_size;
1050
1051    fi_type *buffer_ptr = save->vertex_store->buffer_in_ram;
1052    if (numComponents) {
1053       assert(save->copied.buffer);
1054       memcpy(buffer_ptr,
1055              save->copied.buffer,
1056              numComponents * sizeof(fi_type));
1057       free(save->copied.buffer);
1058       save->copied.buffer = NULL;
1059    }
1060    save->vertex_store->used = numComponents;
1061 }
1062
1063
1064 static void
1065 copy_to_current(struct gl_context *ctx)
1066 {
1067    struct vbo_save_context *save = &vbo_context(ctx)->save;
1068    GLbitfield64 enabled = save->enabled & (~BITFIELD64_BIT(VBO_ATTRIB_POS));
1069
1070    while (enabled) {
1071       const int i = u_bit_scan64(&enabled);
1072       assert(save->attrsz[i]);
1073
1074       if (save->attrtype[i] == GL_DOUBLE ||
1075           save->attrtype[i] == GL_UNSIGNED_INT64_ARB)
1076          memcpy(save->current[i], save->attrptr[i], save->attrsz[i] * sizeof(GLfloat));
1077       else
1078          COPY_CLEAN_4V_TYPE_AS_UNION(save->current[i], save->attrsz[i],
1079                                      save->attrptr[i], save->attrtype[i]);
1080    }
1081 }
1082
1083
1084 static void
1085 copy_from_current(struct gl_context *ctx)
1086 {
1087    struct vbo_save_context *save = &vbo_context(ctx)->save;
1088    GLbitfield64 enabled = save->enabled & (~BITFIELD64_BIT(VBO_ATTRIB_POS));
1089
1090    while (enabled) {
1091       const int i = u_bit_scan64(&enabled);
1092
1093       switch (save->attrsz[i]) {
1094       case 4:
1095          save->attrptr[i][3] = save->current[i][3];
1096          FALLTHROUGH;
1097       case 3:
1098          save->attrptr[i][2] = save->current[i][2];
1099          FALLTHROUGH;
1100       case 2:
1101          save->attrptr[i][1] = save->current[i][1];
1102          FALLTHROUGH;
1103       case 1:
1104          save->attrptr[i][0] = save->current[i][0];
1105          break;
1106       case 0:
1107          unreachable("Unexpected vertex attribute size");
1108       }
1109    }
1110 }
1111
1112
1113 /**
1114  * Called when we increase the size of a vertex attribute.  For example,
1115  * if we've seen one or more glTexCoord2f() calls and now we get a
1116  * glTexCoord3f() call.
1117  * Flush existing data, set new attrib size, replay copied vertices.
1118  */
1119 static void
1120 upgrade_vertex(struct gl_context *ctx, GLuint attr, GLuint newsz)
1121 {
1122    struct vbo_save_context *save = &vbo_context(ctx)->save;
1123    GLuint oldsz;
1124    GLuint i;
1125    fi_type *tmp;
1126
1127    /* Store the current run of vertices, and emit a GL_END.  Emit a
1128     * BEGIN in the new buffer.
1129     */
1130    if (save->vertex_store->used)
1131       wrap_buffers(ctx);
1132    else
1133       assert(save->copied.nr == 0);
1134
1135    /* Do a COPY_TO_CURRENT to ensure back-copying works for the case
1136     * when the attribute already exists in the vertex and is having
1137     * its size increased.
1138     */
1139    copy_to_current(ctx);
1140
1141    /* Fix up sizes:
1142     */
1143    oldsz = save->attrsz[attr];
1144    save->attrsz[attr] = newsz;
1145    save->enabled |= BITFIELD64_BIT(attr);
1146
1147    save->vertex_size += newsz - oldsz;
1148
1149    /* Recalculate all the attrptr[] values:
1150     */
1151    tmp = save->vertex;
1152    for (i = 0; i < VBO_ATTRIB_MAX; i++) {
1153       if (save->attrsz[i]) {
1154          save->attrptr[i] = tmp;
1155          tmp += save->attrsz[i];
1156       }
1157       else {
1158          save->attrptr[i] = NULL;       /* will not be dereferenced. */
1159       }
1160    }
1161
1162    /* Copy from current to repopulate the vertex with correct values.
1163     */
1164    copy_from_current(ctx);
1165
1166    /* Replay stored vertices to translate them to new format here.
1167     *
1168     * If there are copied vertices and the new (upgraded) attribute
1169     * has not been defined before, this list is somewhat degenerate,
1170     * and will need fixup at runtime.
1171     */
1172    if (save->copied.nr) {
1173       assert(save->copied.buffer);
1174       const fi_type *data = save->copied.buffer;
1175       grow_vertex_storage(ctx, save->copied.nr);
1176       fi_type *dest = save->vertex_store->buffer_in_ram;
1177
1178       /* Need to note this and fix up at runtime (or loopback):
1179        */
1180       if (attr != VBO_ATTRIB_POS && save->currentsz[attr][0] == 0) {
1181          assert(oldsz == 0);
1182          save->dangling_attr_ref = GL_TRUE;
1183       }
1184
1185       for (i = 0; i < save->copied.nr; i++) {
1186          GLbitfield64 enabled = save->enabled;
1187          while (enabled) {
1188             const int j = u_bit_scan64(&enabled);
1189             assert(save->attrsz[j]);
1190             if (j == attr) {
1191                int k;
1192                const fi_type *src = oldsz ? data : save->current[attr];
1193                int copy = oldsz ? oldsz : newsz;
1194                for (k = 0; k < copy; k++)
1195                   dest[k] = src[k];
1196                for (; k < newsz; k++) {
1197                   switch (save->attrtype[j]) {
1198                      case GL_FLOAT:
1199                         dest[k] = FLOAT_AS_UNION(k == 3);
1200                         break;
1201                      case GL_INT:
1202                         dest[k] = INT_AS_UNION(k == 3);
1203                         break;
1204                      case GL_UNSIGNED_INT:
1205                         dest[k] = UINT_AS_UNION(k == 3);
1206                         break;
1207                      default:
1208                         dest[k] = FLOAT_AS_UNION(k == 3);
1209                         assert(!"Unexpected type in upgrade_vertex");
1210                         break;
1211                   }
1212                }
1213                dest += newsz;
1214                data += oldsz;
1215             } else {
1216                GLint sz = save->attrsz[j];
1217                for (int k = 0; k < sz; k++)
1218                   dest[k] = data[k];
1219                data += sz;
1220                dest += sz;
1221             }
1222          }
1223       }
1224
1225       save->vertex_store->used += save->vertex_size * save->copied.nr;
1226       free(save->copied.buffer);
1227       save->copied.buffer = NULL;
1228    }
1229 }
1230
1231
1232 /**
1233  * This is called when the size of a vertex attribute changes.
1234  * For example, after seeing one or more glTexCoord2f() calls we
1235  * get a glTexCoord4f() or glTexCoord1f() call.
1236  */
1237 static void
1238 fixup_vertex(struct gl_context *ctx, GLuint attr,
1239              GLuint sz, GLenum newType)
1240 {
1241    struct vbo_save_context *save = &vbo_context(ctx)->save;
1242
1243    if (sz > save->attrsz[attr] ||
1244        newType != save->attrtype[attr]) {
1245       /* New size is larger.  Need to flush existing vertices and get
1246        * an enlarged vertex format.
1247        */
1248       upgrade_vertex(ctx, attr, sz);
1249    }
1250    else if (sz < save->active_sz[attr]) {
1251       GLuint i;
1252       const fi_type *id = vbo_get_default_vals_as_union(save->attrtype[attr]);
1253
1254       /* New size is equal or smaller - just need to fill in some
1255        * zeros.
1256        */
1257       for (i = sz; i <= save->attrsz[attr]; i++)
1258          save->attrptr[attr][i - 1] = id[i - 1];
1259    }
1260
1261    save->active_sz[attr] = sz;
1262
1263    grow_vertex_storage(ctx, 1);
1264 }
1265
1266
1267 /**
1268  * Reset the current size of all vertex attributes to the default
1269  * value of 0.  This signals that we haven't yet seen any per-vertex
1270  * commands such as glNormal3f() or glTexCoord2f().
1271  */
1272 static void
1273 reset_vertex(struct gl_context *ctx)
1274 {
1275    struct vbo_save_context *save = &vbo_context(ctx)->save;
1276
1277    while (save->enabled) {
1278       const int i = u_bit_scan64(&save->enabled);
1279       assert(save->attrsz[i]);
1280       save->attrsz[i] = 0;
1281       save->active_sz[i] = 0;
1282    }
1283
1284    save->vertex_size = 0;
1285 }
1286
1287
1288 /**
1289  * If index=0, does glVertexAttrib*() alias glVertex() to emit a vertex?
1290  * It depends on a few things, including whether we're inside or outside
1291  * of glBegin/glEnd.
1292  */
1293 static inline bool
1294 is_vertex_position(const struct gl_context *ctx, GLuint index)
1295 {
1296    return (index == 0 &&
1297            _mesa_attr_zero_aliases_vertex(ctx) &&
1298            _mesa_inside_dlist_begin_end(ctx));
1299 }
1300
1301
1302
1303 #define ERROR(err)   _mesa_compile_error(ctx, err, __func__);
1304
1305
1306 /* Only one size for each attribute may be active at once.  Eg. if
1307  * Color3f is installed/active, then Color4f may not be, even if the
1308  * vertex actually contains 4 color coordinates.  This is because the
1309  * 3f version won't otherwise set color[3] to 1.0 -- this is the job
1310  * of the chooser function when switching between Color4f and Color3f.
1311  */
1312 #define ATTR_UNION(A, N, T, C, V0, V1, V2, V3)                  \
1313 do {                                                            \
1314    struct vbo_save_context *save = &vbo_context(ctx)->save;     \
1315    int sz = (sizeof(C) / sizeof(GLfloat));                      \
1316                                                                 \
1317    if (save->active_sz[A] != N)                                 \
1318       fixup_vertex(ctx, A, N * sz, T);                          \
1319                                                                 \
1320    {                                                            \
1321       C *dest = (C *)save->attrptr[A];                          \
1322       if (N>0) dest[0] = V0;                                    \
1323       if (N>1) dest[1] = V1;                                    \
1324       if (N>2) dest[2] = V2;                                    \
1325       if (N>3) dest[3] = V3;                                    \
1326       save->attrtype[A] = T;                                    \
1327    }                                                            \
1328                                                                 \
1329    if ((A) == VBO_ATTRIB_POS) {                                 \
1330       fi_type *buffer_ptr = save->vertex_store->buffer_in_ram + \
1331                             save->vertex_store->used;           \
1332                                                                 \
1333       for (int i = 0; i < save->vertex_size; i++)               \
1334         buffer_ptr[i] = save->vertex[i];                        \
1335                                                                 \
1336       save->vertex_store->used += save->vertex_size;            \
1337       unsigned used_next = (save->vertex_store->used +          \
1338                             save->vertex_size) * sizeof(float); \
1339       if (used_next > save->vertex_store->buffer_in_ram_size) { \
1340          grow_vertex_storage(ctx, get_vertex_count(save));      \
1341          assert(used_next <=                                    \
1342                 save->vertex_store->buffer_in_ram_size);        \
1343       }                                                         \
1344    }                                                            \
1345 } while (0)
1346
1347 #define TAG(x) _save_##x
1348
1349 #include "vbo_attrib_tmp.h"
1350
1351
1352 #define MAT( ATTR, N, face, params )                            \
1353 do {                                                            \
1354    if (face != GL_BACK)                                         \
1355       MAT_ATTR( ATTR, N, params ); /* front */                  \
1356    if (face != GL_FRONT)                                        \
1357       MAT_ATTR( ATTR + 1, N, params ); /* back */               \
1358 } while (0)
1359
1360
1361 /**
1362  * Save a glMaterial call found between glBegin/End.
1363  * glMaterial calls outside Begin/End are handled in dlist.c.
1364  */
1365 static void GLAPIENTRY
1366 _save_Materialfv(GLenum face, GLenum pname, const GLfloat *params)
1367 {
1368    GET_CURRENT_CONTEXT(ctx);
1369
1370    if (face != GL_FRONT && face != GL_BACK && face != GL_FRONT_AND_BACK) {
1371       _mesa_compile_error(ctx, GL_INVALID_ENUM, "glMaterial(face)");
1372       return;
1373    }
1374
1375    switch (pname) {
1376    case GL_EMISSION:
1377       MAT(VBO_ATTRIB_MAT_FRONT_EMISSION, 4, face, params);
1378       break;
1379    case GL_AMBIENT:
1380       MAT(VBO_ATTRIB_MAT_FRONT_AMBIENT, 4, face, params);
1381       break;
1382    case GL_DIFFUSE:
1383       MAT(VBO_ATTRIB_MAT_FRONT_DIFFUSE, 4, face, params);
1384       break;
1385    case GL_SPECULAR:
1386       MAT(VBO_ATTRIB_MAT_FRONT_SPECULAR, 4, face, params);
1387       break;
1388    case GL_SHININESS:
1389       if (*params < 0 || *params > ctx->Const.MaxShininess) {
1390          _mesa_compile_error(ctx, GL_INVALID_VALUE, "glMaterial(shininess)");
1391       }
1392       else {
1393          MAT(VBO_ATTRIB_MAT_FRONT_SHININESS, 1, face, params);
1394       }
1395       break;
1396    case GL_COLOR_INDEXES:
1397       MAT(VBO_ATTRIB_MAT_FRONT_INDEXES, 3, face, params);
1398       break;
1399    case GL_AMBIENT_AND_DIFFUSE:
1400       MAT(VBO_ATTRIB_MAT_FRONT_AMBIENT, 4, face, params);
1401       MAT(VBO_ATTRIB_MAT_FRONT_DIFFUSE, 4, face, params);
1402       break;
1403    default:
1404       _mesa_compile_error(ctx, GL_INVALID_ENUM, "glMaterial(pname)");
1405       return;
1406    }
1407 }
1408
1409
1410 static void
1411 vbo_init_dispatch_save_begin_end(struct gl_context *ctx);
1412
1413
1414 /* Cope with EvalCoord/CallList called within a begin/end object:
1415  *     -- Flush current buffer
1416  *     -- Fallback to opcodes for the rest of the begin/end object.
1417  */
1418 static void
1419 dlist_fallback(struct gl_context *ctx)
1420 {
1421    struct vbo_save_context *save = &vbo_context(ctx)->save;
1422
1423    if (save->vertex_store->used || save->prim_store->used) {
1424       if (save->prim_store->used > 0 && save->vertex_store->used > 0) {
1425          assert(save->vertex_size);
1426          /* Close off in-progress primitive. */
1427          GLint i = save->prim_store->used - 1;
1428          save->prim_store->prims[i].count =
1429             get_vertex_count(save) -
1430             save->prim_store->prims[i].start;
1431       }
1432
1433       /* Need to replay this display list with loopback,
1434        * unfortunately, otherwise this primitive won't be handled
1435        * properly:
1436        */
1437       save->dangling_attr_ref = GL_TRUE;
1438
1439       compile_vertex_list(ctx);
1440    }
1441
1442    copy_to_current(ctx);
1443    reset_vertex(ctx);
1444    if (save->out_of_memory) {
1445       vbo_install_save_vtxfmt_noop(ctx);
1446    }
1447    else {
1448       _mesa_init_dispatch_save_begin_end(ctx);
1449    }
1450    ctx->Driver.SaveNeedFlush = GL_FALSE;
1451 }
1452
1453
1454 static void GLAPIENTRY
1455 _save_EvalCoord1f(GLfloat u)
1456 {
1457    GET_CURRENT_CONTEXT(ctx);
1458    dlist_fallback(ctx);
1459    CALL_EvalCoord1f(ctx->Save, (u));
1460 }
1461
1462 static void GLAPIENTRY
1463 _save_EvalCoord1fv(const GLfloat * v)
1464 {
1465    GET_CURRENT_CONTEXT(ctx);
1466    dlist_fallback(ctx);
1467    CALL_EvalCoord1fv(ctx->Save, (v));
1468 }
1469
1470 static void GLAPIENTRY
1471 _save_EvalCoord2f(GLfloat u, GLfloat v)
1472 {
1473    GET_CURRENT_CONTEXT(ctx);
1474    dlist_fallback(ctx);
1475    CALL_EvalCoord2f(ctx->Save, (u, v));
1476 }
1477
1478 static void GLAPIENTRY
1479 _save_EvalCoord2fv(const GLfloat * v)
1480 {
1481    GET_CURRENT_CONTEXT(ctx);
1482    dlist_fallback(ctx);
1483    CALL_EvalCoord2fv(ctx->Save, (v));
1484 }
1485
1486 static void GLAPIENTRY
1487 _save_EvalPoint1(GLint i)
1488 {
1489    GET_CURRENT_CONTEXT(ctx);
1490    dlist_fallback(ctx);
1491    CALL_EvalPoint1(ctx->Save, (i));
1492 }
1493
1494 static void GLAPIENTRY
1495 _save_EvalPoint2(GLint i, GLint j)
1496 {
1497    GET_CURRENT_CONTEXT(ctx);
1498    dlist_fallback(ctx);
1499    CALL_EvalPoint2(ctx->Save, (i, j));
1500 }
1501
1502 static void GLAPIENTRY
1503 _save_CallList(GLuint l)
1504 {
1505    GET_CURRENT_CONTEXT(ctx);
1506    dlist_fallback(ctx);
1507    CALL_CallList(ctx->Save, (l));
1508 }
1509
1510 static void GLAPIENTRY
1511 _save_CallLists(GLsizei n, GLenum type, const GLvoid * v)
1512 {
1513    GET_CURRENT_CONTEXT(ctx);
1514    dlist_fallback(ctx);
1515    CALL_CallLists(ctx->Save, (n, type, v));
1516 }
1517
1518
1519
1520 /**
1521  * Called when a glBegin is getting compiled into a display list.
1522  * Updating of ctx->Driver.CurrentSavePrimitive is already taken care of.
1523  */
1524 void
1525 vbo_save_NotifyBegin(struct gl_context *ctx, GLenum mode,
1526                      bool no_current_update)
1527 {
1528    struct vbo_save_context *save = &vbo_context(ctx)->save;
1529    const GLuint i = save->prim_store->used++;
1530
1531    ctx->Driver.CurrentSavePrimitive = mode;
1532
1533    if (!save->prim_store || i >= save->prim_store->size) {
1534       save->prim_store = realloc_prim_store(save->prim_store, i * 2);
1535    }
1536    save->prim_store->prims[i].mode = mode & VBO_SAVE_PRIM_MODE_MASK;
1537    save->prim_store->prims[i].begin = 1;
1538    save->prim_store->prims[i].end = 0;
1539    save->prim_store->prims[i].start = get_vertex_count(save);
1540    save->prim_store->prims[i].count = 0;
1541
1542    save->no_current_update = no_current_update;
1543
1544    vbo_init_dispatch_save_begin_end(ctx);
1545
1546    /* We need to call vbo_save_SaveFlushVertices() if there's state change */
1547    ctx->Driver.SaveNeedFlush = GL_TRUE;
1548 }
1549
1550
1551 static void GLAPIENTRY
1552 _save_End(void)
1553 {
1554    GET_CURRENT_CONTEXT(ctx);
1555    struct vbo_save_context *save = &vbo_context(ctx)->save;
1556    const GLint i = save->prim_store->used - 1;
1557
1558    ctx->Driver.CurrentSavePrimitive = PRIM_OUTSIDE_BEGIN_END;
1559    save->prim_store->prims[i].end = 1;
1560    save->prim_store->prims[i].count = (get_vertex_count(save) - save->prim_store->prims[i].start);
1561
1562    /* Swap out this vertex format while outside begin/end.  Any color,
1563     * etc. received between here and the next begin will be compiled
1564     * as opcodes.
1565     */
1566    if (save->out_of_memory) {
1567       vbo_install_save_vtxfmt_noop(ctx);
1568    }
1569    else {
1570       _mesa_init_dispatch_save_begin_end(ctx);
1571    }
1572 }
1573
1574
1575 static void GLAPIENTRY
1576 _save_Begin(GLenum mode)
1577 {
1578    GET_CURRENT_CONTEXT(ctx);
1579    (void) mode;
1580    _mesa_compile_error(ctx, GL_INVALID_OPERATION, "Recursive glBegin");
1581 }
1582
1583
1584 static void GLAPIENTRY
1585 _save_PrimitiveRestartNV(void)
1586 {
1587    GET_CURRENT_CONTEXT(ctx);
1588    struct vbo_save_context *save = &vbo_context(ctx)->save;
1589
1590    if (save->prim_store->used == 0) {
1591       /* We're not inside a glBegin/End pair, so calling glPrimitiverRestartNV
1592        * is an error.
1593        */
1594       _mesa_compile_error(ctx, GL_INVALID_OPERATION,
1595                           "glPrimitiveRestartNV called outside glBegin/End");
1596    } else {
1597       /* get current primitive mode */
1598       GLenum curPrim = save->prim_store->prims[save->prim_store->used - 1].mode;
1599       bool no_current_update = save->no_current_update;
1600
1601       /* restart primitive */
1602       CALL_End(ctx->CurrentServerDispatch, ());
1603       vbo_save_NotifyBegin(ctx, curPrim, no_current_update);
1604    }
1605 }
1606
1607
1608 void GLAPIENTRY
1609 save_Rectf(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2)
1610 {
1611    GET_CURRENT_CONTEXT(ctx);
1612    struct _glapi_table *dispatch = ctx->CurrentServerDispatch;
1613
1614    vbo_save_NotifyBegin(ctx, GL_QUADS, false);
1615    CALL_Vertex2f(dispatch, (x1, y1));
1616    CALL_Vertex2f(dispatch, (x2, y1));
1617    CALL_Vertex2f(dispatch, (x2, y2));
1618    CALL_Vertex2f(dispatch, (x1, y2));
1619    CALL_End(dispatch, ());
1620 }
1621
1622
1623 void GLAPIENTRY
1624 save_Rectdv(const GLdouble *v1, const GLdouble *v2)
1625 {
1626    save_Rectf((GLfloat) v1[0], (GLfloat) v1[1], (GLfloat) v2[0], (GLfloat) v2[1]);
1627 }
1628
1629 void GLAPIENTRY
1630 save_Rectfv(const GLfloat *v1, const GLfloat *v2)
1631 {
1632    save_Rectf(v1[0], v1[1], v2[0], v2[1]);
1633 }
1634
1635 void GLAPIENTRY
1636 save_Recti(GLint x1, GLint y1, GLint x2, GLint y2)
1637 {
1638    save_Rectf((GLfloat) x1, (GLfloat) y1, (GLfloat) x2, (GLfloat) y2);
1639 }
1640
1641 void GLAPIENTRY
1642 save_Rectiv(const GLint *v1, const GLint *v2)
1643 {
1644    save_Rectf((GLfloat) v1[0], (GLfloat) v1[1], (GLfloat) v2[0], (GLfloat) v2[1]);
1645 }
1646
1647 void GLAPIENTRY
1648 save_Rects(GLshort x1, GLshort y1, GLshort x2, GLshort y2)
1649 {
1650    save_Rectf((GLfloat) x1, (GLfloat) y1, (GLfloat) x2, (GLfloat) y2);
1651 }
1652
1653 void GLAPIENTRY
1654 save_Rectsv(const GLshort *v1, const GLshort *v2)
1655 {
1656    save_Rectf((GLfloat) v1[0], (GLfloat) v1[1], (GLfloat) v2[0], (GLfloat) v2[1]);
1657 }
1658
1659 void GLAPIENTRY
1660 save_DrawArrays(GLenum mode, GLint start, GLsizei count)
1661 {
1662    GET_CURRENT_CONTEXT(ctx);
1663    struct gl_vertex_array_object *vao = ctx->Array.VAO;
1664    struct vbo_save_context *save = &vbo_context(ctx)->save;
1665    GLint i;
1666
1667    if (!_mesa_is_valid_prim_mode(ctx, mode)) {
1668       _mesa_compile_error(ctx, GL_INVALID_ENUM, "glDrawArrays(mode)");
1669       return;
1670    }
1671    if (count < 0) {
1672       _mesa_compile_error(ctx, GL_INVALID_VALUE, "glDrawArrays(count<0)");
1673       return;
1674    }
1675
1676    if (save->out_of_memory)
1677       return;
1678
1679    grow_vertex_storage(ctx, count);
1680
1681    /* Make sure to process any VBO binding changes */
1682    _mesa_update_state(ctx);
1683
1684    _mesa_vao_map_arrays(ctx, vao, GL_MAP_READ_BIT);
1685
1686    vbo_save_NotifyBegin(ctx, mode, true);
1687
1688    for (i = 0; i < count; i++)
1689       _mesa_array_element(ctx, start + i);
1690    CALL_End(ctx->CurrentServerDispatch, ());
1691
1692    _mesa_vao_unmap_arrays(ctx, vao);
1693 }
1694
1695
1696 void GLAPIENTRY
1697 save_MultiDrawArrays(GLenum mode, const GLint *first,
1698                       const GLsizei *count, GLsizei primcount)
1699 {
1700    GET_CURRENT_CONTEXT(ctx);
1701    GLint i;
1702
1703    if (!_mesa_is_valid_prim_mode(ctx, mode)) {
1704       _mesa_compile_error(ctx, GL_INVALID_ENUM, "glMultiDrawArrays(mode)");
1705       return;
1706    }
1707
1708    if (primcount < 0) {
1709       _mesa_compile_error(ctx, GL_INVALID_VALUE,
1710                           "glMultiDrawArrays(primcount<0)");
1711       return;
1712    }
1713
1714    unsigned vertcount = 0;
1715    for (i = 0; i < primcount; i++) {
1716       if (count[i] < 0) {
1717          _mesa_compile_error(ctx, GL_INVALID_VALUE,
1718                              "glMultiDrawArrays(count[i]<0)");
1719          return;
1720       }
1721       vertcount += count[i];
1722    }
1723
1724    grow_vertex_storage(ctx, vertcount);
1725
1726    for (i = 0; i < primcount; i++) {
1727       if (count[i] > 0) {
1728          save_DrawArrays(mode, first[i], count[i]);
1729       }
1730    }
1731 }
1732
1733
1734 static void
1735 array_element(struct gl_context *ctx,
1736               GLint basevertex, GLuint elt, unsigned index_size_shift)
1737 {
1738    /* Section 10.3.5 Primitive Restart:
1739     * [...]
1740     *    When one of the *BaseVertex drawing commands specified in section 10.5
1741     * is used, the primitive restart comparison occurs before the basevertex
1742     * offset is added to the array index.
1743     */
1744    /* If PrimitiveRestart is enabled and the index is the RestartIndex
1745     * then we call PrimitiveRestartNV and return.
1746     */
1747    if (ctx->Array._PrimitiveRestart[index_size_shift] &&
1748        elt == ctx->Array._RestartIndex[index_size_shift]) {
1749       CALL_PrimitiveRestartNV(ctx->CurrentServerDispatch, ());
1750       return;
1751    }
1752
1753    _mesa_array_element(ctx, basevertex + elt);
1754 }
1755
1756
1757 /* Could do better by copying the arrays and element list intact and
1758  * then emitting an indexed prim at runtime.
1759  */
1760 void GLAPIENTRY
1761 save_DrawElementsBaseVertex(GLenum mode, GLsizei count, GLenum type,
1762                              const GLvoid * indices, GLint basevertex)
1763 {
1764    GET_CURRENT_CONTEXT(ctx);
1765    struct vbo_save_context *save = &vbo_context(ctx)->save;
1766    struct gl_vertex_array_object *vao = ctx->Array.VAO;
1767    struct gl_buffer_object *indexbuf = vao->IndexBufferObj;
1768    GLint i;
1769
1770    if (!_mesa_is_valid_prim_mode(ctx, mode)) {
1771       _mesa_compile_error(ctx, GL_INVALID_ENUM, "glDrawElements(mode)");
1772       return;
1773    }
1774    if (count < 0) {
1775       _mesa_compile_error(ctx, GL_INVALID_VALUE, "glDrawElements(count<0)");
1776       return;
1777    }
1778    if (type != GL_UNSIGNED_BYTE &&
1779        type != GL_UNSIGNED_SHORT &&
1780        type != GL_UNSIGNED_INT) {
1781       _mesa_compile_error(ctx, GL_INVALID_VALUE, "glDrawElements(count<0)");
1782       return;
1783    }
1784
1785    if (save->out_of_memory)
1786       return;
1787
1788    grow_vertex_storage(ctx, count);
1789
1790    /* Make sure to process any VBO binding changes */
1791    _mesa_update_state(ctx);
1792
1793    _mesa_vao_map(ctx, vao, GL_MAP_READ_BIT);
1794
1795    if (indexbuf)
1796       indices =
1797          ADD_POINTERS(indexbuf->Mappings[MAP_INTERNAL].Pointer, indices);
1798
1799    vbo_save_NotifyBegin(ctx, mode, true);
1800
1801    switch (type) {
1802    case GL_UNSIGNED_BYTE:
1803       for (i = 0; i < count; i++)
1804          array_element(ctx, basevertex, ((GLubyte *) indices)[i], 0);
1805       break;
1806    case GL_UNSIGNED_SHORT:
1807       for (i = 0; i < count; i++)
1808          array_element(ctx, basevertex, ((GLushort *) indices)[i], 1);
1809       break;
1810    case GL_UNSIGNED_INT:
1811       for (i = 0; i < count; i++)
1812          array_element(ctx, basevertex, ((GLuint *) indices)[i], 2);
1813       break;
1814    default:
1815       _mesa_error(ctx, GL_INVALID_ENUM, "glDrawElements(type)");
1816       break;
1817    }
1818
1819    CALL_End(ctx->CurrentServerDispatch, ());
1820
1821    _mesa_vao_unmap(ctx, vao);
1822 }
1823
1824 void GLAPIENTRY
1825 save_DrawElements(GLenum mode, GLsizei count, GLenum type,
1826                    const GLvoid * indices)
1827 {
1828    save_DrawElementsBaseVertex(mode, count, type, indices, 0);
1829 }
1830
1831
1832 void GLAPIENTRY
1833 save_DrawRangeElements(GLenum mode, GLuint start, GLuint end,
1834                             GLsizei count, GLenum type,
1835                             const GLvoid * indices)
1836 {
1837    GET_CURRENT_CONTEXT(ctx);
1838    struct vbo_save_context *save = &vbo_context(ctx)->save;
1839
1840    if (!_mesa_is_valid_prim_mode(ctx, mode)) {
1841       _mesa_compile_error(ctx, GL_INVALID_ENUM, "glDrawRangeElements(mode)");
1842       return;
1843    }
1844    if (count < 0) {
1845       _mesa_compile_error(ctx, GL_INVALID_VALUE,
1846                           "glDrawRangeElements(count<0)");
1847       return;
1848    }
1849    if (type != GL_UNSIGNED_BYTE &&
1850        type != GL_UNSIGNED_SHORT &&
1851        type != GL_UNSIGNED_INT) {
1852       _mesa_compile_error(ctx, GL_INVALID_ENUM, "glDrawRangeElements(type)");
1853       return;
1854    }
1855    if (end < start) {
1856       _mesa_compile_error(ctx, GL_INVALID_VALUE,
1857                           "glDrawRangeElements(end < start)");
1858       return;
1859    }
1860
1861    if (save->out_of_memory)
1862       return;
1863
1864    save_DrawElements(mode, count, type, indices);
1865 }
1866
1867 void GLAPIENTRY
1868 save_DrawRangeElementsBaseVertex(GLenum mode, GLuint start, GLuint end,
1869                                  GLsizei count, GLenum type,
1870                                  const GLvoid *indices, GLint basevertex)
1871 {
1872    GET_CURRENT_CONTEXT(ctx);
1873
1874    if (end < start) {
1875       _mesa_compile_error(ctx, GL_INVALID_VALUE,
1876                           "glDrawRangeElementsBaseVertex(end < start)");
1877       return;
1878    }
1879
1880    save_DrawElementsBaseVertex(mode, count, type, indices, basevertex);
1881 }
1882
1883 void GLAPIENTRY
1884 save_MultiDrawElements(GLenum mode, const GLsizei *count, GLenum type,
1885                        const GLvoid * const *indices, GLsizei primcount)
1886 {
1887    GET_CURRENT_CONTEXT(ctx);
1888    struct _glapi_table *dispatch = ctx->CurrentServerDispatch;
1889    GLsizei i;
1890
1891    int vertcount = 0;
1892    for (i = 0; i < primcount; i++) {
1893       vertcount += count[i];
1894    }
1895    grow_vertex_storage(ctx, vertcount);
1896
1897    for (i = 0; i < primcount; i++) {
1898       if (count[i] > 0) {
1899          CALL_DrawElements(dispatch, (mode, count[i], type, indices[i]));
1900       }
1901    }
1902 }
1903
1904
1905 void GLAPIENTRY
1906 save_MultiDrawElementsBaseVertex(GLenum mode, const GLsizei *count,
1907                                   GLenum type,
1908                                   const GLvoid * const *indices,
1909                                   GLsizei primcount,
1910                                   const GLint *basevertex)
1911 {
1912    GET_CURRENT_CONTEXT(ctx);
1913    struct _glapi_table *dispatch = ctx->CurrentServerDispatch;
1914    GLsizei i;
1915
1916    int vertcount = 0;
1917    for (i = 0; i < primcount; i++) {
1918       vertcount += count[i];
1919    }
1920    grow_vertex_storage(ctx, vertcount);
1921
1922    for (i = 0; i < primcount; i++) {
1923       if (count[i] > 0) {
1924          CALL_DrawElementsBaseVertex(dispatch, (mode, count[i], type,
1925                                      indices[i],
1926                                      basevertex[i]));
1927       }
1928    }
1929 }
1930
1931
1932 static void
1933 vbo_init_dispatch_save_begin_end(struct gl_context *ctx)
1934 {
1935 #define NAME_AE(x) _mesa_##x
1936 #define NAME_CALLLIST(x) _save_##x
1937 #define NAME(x) _save_##x
1938 #define NAME_ES(x) _save_##x
1939
1940    struct _glapi_table *tab = ctx->Save;
1941    #include "api_beginend_init.h"
1942 }
1943
1944
1945 void
1946 vbo_save_SaveFlushVertices(struct gl_context *ctx)
1947 {
1948    struct vbo_save_context *save = &vbo_context(ctx)->save;
1949
1950    /* Noop when we are actually active:
1951     */
1952    if (ctx->Driver.CurrentSavePrimitive <= PRIM_MAX)
1953       return;
1954
1955    if (save->vertex_store->used || save->prim_store->used)
1956       compile_vertex_list(ctx);
1957
1958    copy_to_current(ctx);
1959    reset_vertex(ctx);
1960    ctx->Driver.SaveNeedFlush = GL_FALSE;
1961 }
1962
1963
1964 /**
1965  * Called from glNewList when we're starting to compile a display list.
1966  */
1967 void
1968 vbo_save_NewList(struct gl_context *ctx, GLuint list, GLenum mode)
1969 {
1970    struct vbo_save_context *save = &vbo_context(ctx)->save;
1971
1972    (void) list;
1973    (void) mode;
1974
1975    if (!save->prim_store)
1976       save->prim_store = realloc_prim_store(NULL, 8);
1977
1978    if (!save->vertex_store)
1979       save->vertex_store = CALLOC_STRUCT(vbo_save_vertex_store);
1980
1981    reset_vertex(ctx);
1982    ctx->Driver.SaveNeedFlush = GL_FALSE;
1983 }
1984
1985
1986 /**
1987  * Called from glEndList when we're finished compiling a display list.
1988  */
1989 void
1990 vbo_save_EndList(struct gl_context *ctx)
1991 {
1992    struct vbo_save_context *save = &vbo_context(ctx)->save;
1993
1994    /* EndList called inside a (saved) Begin/End pair?
1995     */
1996    if (_mesa_inside_dlist_begin_end(ctx)) {
1997       if (save->prim_store->used > 0) {
1998          GLint i = save->prim_store->used - 1;
1999          ctx->Driver.CurrentSavePrimitive = PRIM_OUTSIDE_BEGIN_END;
2000          save->prim_store->prims[i].end = 0;
2001          save->prim_store->prims[i].count = get_vertex_count(save) - save->prim_store->prims[i].start;
2002       }
2003
2004       /* Make sure this vertex list gets replayed by the "loopback"
2005        * mechanism:
2006        */
2007       save->dangling_attr_ref = GL_TRUE;
2008       vbo_save_SaveFlushVertices(ctx);
2009
2010       /* Swap out this vertex format while outside begin/end.  Any color,
2011        * etc. received between here and the next begin will be compiled
2012        * as opcodes.
2013        */
2014       _mesa_init_dispatch_save_begin_end(ctx);
2015    }
2016
2017    assert(save->vertex_size == 0);
2018 }
2019
2020 /**
2021  * Called during context creation/init.
2022  */
2023 static void
2024 current_init(struct gl_context *ctx)
2025 {
2026    struct vbo_save_context *save = &vbo_context(ctx)->save;
2027    GLint i;
2028
2029    for (i = VBO_ATTRIB_POS; i <= VBO_ATTRIB_EDGEFLAG; i++) {
2030       const GLuint j = i - VBO_ATTRIB_POS;
2031       assert(j < VERT_ATTRIB_MAX);
2032       save->currentsz[i] = &ctx->ListState.ActiveAttribSize[j];
2033       save->current[i] = (fi_type *) ctx->ListState.CurrentAttrib[j];
2034    }
2035
2036    for (i = VBO_ATTRIB_FIRST_MATERIAL; i <= VBO_ATTRIB_LAST_MATERIAL; i++) {
2037       const GLuint j = i - VBO_ATTRIB_FIRST_MATERIAL;
2038       assert(j < MAT_ATTRIB_MAX);
2039       save->currentsz[i] = &ctx->ListState.ActiveMaterialSize[j];
2040       save->current[i] = (fi_type *) ctx->ListState.CurrentMaterial[j];
2041    }
2042 }
2043
2044
2045 /**
2046  * Initialize the display list compiler.  Called during context creation.
2047  */
2048 void
2049 vbo_save_api_init(struct vbo_save_context *save)
2050 {
2051    struct gl_context *ctx = gl_context_from_vbo_save(save);
2052
2053    current_init(ctx);
2054 }