u_vbuf.c revision b5e5e61439bda7a3cf1f909b48467371ea53d9d7
1/**************************************************************************
2 *
3 * Copyright 2011 Marek Olšák <maraeo@gmail.com>
4 * All Rights Reserved.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the
8 * "Software"), to deal in the Software without restriction, including
9 * without limitation the rights to use, copy, modify, merge, publish,
10 * distribute, sub license, and/or sell copies of the Software, and to
11 * permit persons to whom the Software is furnished to do so, subject to
12 * the following conditions:
13 *
14 * The above copyright notice and this permission notice (including the
15 * next paragraph) shall be included in all copies or substantial portions
16 * of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
21 * IN NO EVENT SHALL AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR
22 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
23 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
24 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25 *
26 **************************************************************************/
27
28#include "util/u_vbuf.h"
29
30#include "util/u_dump.h"
31#include "util/u_format.h"
32#include "util/u_inlines.h"
33#include "util/u_memory.h"
34#include "util/u_upload_mgr.h"
35#include "translate/translate.h"
36#include "translate/translate_cache.h"
37#include "cso_cache/cso_cache.h"
38#include "cso_cache/cso_hash.h"
39
40struct u_vbuf_elements {
41   unsigned count;
42   struct pipe_vertex_element ve[PIPE_MAX_ATTRIBS];
43
44   unsigned src_format_size[PIPE_MAX_ATTRIBS];
45
46   /* If (velem[i].src_format != native_format[i]), the vertex buffer
47    * referenced by the vertex element cannot be used for rendering and
48    * its vertex data must be translated to native_format[i]. */
49   enum pipe_format native_format[PIPE_MAX_ATTRIBS];
50   unsigned native_format_size[PIPE_MAX_ATTRIBS];
51
52   /* This might mean two things:
53    * - src_format != native_format, as discussed above.
54    * - src_offset % 4 != 0 (if the caps don't allow such an offset). */
55   uint32_t incompatible_elem_mask; /* each bit describes a corresp. attrib  */
56   /* Which buffer has at least one vertex element referencing it
57    * incompatible. */
58   uint32_t incompatible_vb_mask_any;
59   /* Which buffer has all vertex elements referencing it incompatible. */
60   uint32_t incompatible_vb_mask_all;
61   /* Which buffer has at least one vertex element referencing it
62    * compatible. */
63   uint32_t compatible_vb_mask_any;
64   /* Which buffer has all vertex elements referencing it compatible. */
65   uint32_t compatible_vb_mask_all;
66
67   /* Which buffer has at least one vertex element referencing it
68    * non-instanced. */
69   uint32_t noninstance_vb_mask_any;
70
71   void *driver_cso;
72};
73
74enum {
75   VB_VERTEX = 0,
76   VB_INSTANCE = 1,
77   VB_CONST = 2,
78   VB_NUM = 3
79};
80
81struct u_vbuf {
82   struct u_vbuf_caps caps;
83
84   struct pipe_context *pipe;
85   struct translate_cache *translate_cache;
86   struct cso_cache *cso_cache;
87   struct u_upload_mgr *uploader;
88
89   /* This is what was set in set_vertex_buffers.
90    * May contain user buffers. */
91   struct pipe_vertex_buffer vertex_buffer[PIPE_MAX_ATTRIBS];
92   unsigned nr_vertex_buffers;
93
94   /* Saved vertex buffers. */
95   struct pipe_vertex_buffer vertex_buffer_saved[PIPE_MAX_ATTRIBS];
96   unsigned nr_vertex_buffers_saved;
97
98   /* Vertex buffers for the driver.
99    * There are no user buffers. */
100   struct pipe_vertex_buffer real_vertex_buffer[PIPE_MAX_ATTRIBS];
101   int nr_real_vertex_buffers;
102   boolean vertex_buffers_dirty;
103
104   /* The index buffer. */
105   struct pipe_index_buffer index_buffer;
106
107   /* Vertex elements. */
108   struct u_vbuf_elements *ve, *ve_saved;
109
110   /* Vertex elements used for the translate fallback. */
111   struct pipe_vertex_element fallback_velems[PIPE_MAX_ATTRIBS];
112   /* If non-NULL, this is a vertex element state used for the translate
113    * fallback and therefore used for rendering too. */
114   boolean using_translate;
115   /* The vertex buffer slot index where translated vertices have been
116    * stored in. */
117   unsigned fallback_vbs[VB_NUM];
118
119   /* Which buffer is a user buffer. */
120   uint32_t user_vb_mask; /* each bit describes a corresp. buffer */
121   /* Which buffer is incompatible (unaligned). */
122   uint32_t incompatible_vb_mask; /* each bit describes a corresp. buffer */
123   /* Which buffer has a non-zero stride. */
124   uint32_t nonzero_stride_vb_mask; /* each bit describes a corresp. buffer */
125};
126
127static void *
128u_vbuf_create_vertex_elements(struct u_vbuf *mgr, unsigned count,
129                              const struct pipe_vertex_element *attribs);
130static void u_vbuf_delete_vertex_elements(struct u_vbuf *mgr, void *cso);
131
132
133void u_vbuf_get_caps(struct pipe_screen *screen, struct u_vbuf_caps *caps)
134{
135   caps->format_fixed32 =
136      screen->is_format_supported(screen, PIPE_FORMAT_R32_FIXED, PIPE_BUFFER,
137                                  0, PIPE_BIND_VERTEX_BUFFER);
138
139   caps->format_float16 =
140      screen->is_format_supported(screen, PIPE_FORMAT_R16_FLOAT, PIPE_BUFFER,
141                                  0, PIPE_BIND_VERTEX_BUFFER);
142
143   caps->format_float64 =
144      screen->is_format_supported(screen, PIPE_FORMAT_R64_FLOAT, PIPE_BUFFER,
145                                  0, PIPE_BIND_VERTEX_BUFFER);
146
147   caps->format_norm32 =
148      screen->is_format_supported(screen, PIPE_FORMAT_R32_UNORM, PIPE_BUFFER,
149                                  0, PIPE_BIND_VERTEX_BUFFER) &&
150      screen->is_format_supported(screen, PIPE_FORMAT_R32_SNORM, PIPE_BUFFER,
151                                  0, PIPE_BIND_VERTEX_BUFFER);
152
153   caps->format_scaled32 =
154      screen->is_format_supported(screen, PIPE_FORMAT_R32_USCALED, PIPE_BUFFER,
155                                  0, PIPE_BIND_VERTEX_BUFFER) &&
156      screen->is_format_supported(screen, PIPE_FORMAT_R32_SSCALED, PIPE_BUFFER,
157                                  0, PIPE_BIND_VERTEX_BUFFER);
158
159   caps->buffer_offset_unaligned =
160      !screen->get_param(screen,
161                        PIPE_CAP_VERTEX_BUFFER_OFFSET_4BYTE_ALIGNED_ONLY);
162
163   caps->buffer_stride_unaligned =
164      !screen->get_param(screen,
165                        PIPE_CAP_VERTEX_BUFFER_STRIDE_4BYTE_ALIGNED_ONLY);
166
167   caps->velem_src_offset_unaligned =
168      !screen->get_param(screen,
169                        PIPE_CAP_VERTEX_ELEMENT_SRC_OFFSET_4BYTE_ALIGNED_ONLY);
170
171   caps->user_vertex_buffers =
172      screen->get_param(screen, PIPE_CAP_USER_VERTEX_BUFFERS);
173}
174
175struct u_vbuf *
176u_vbuf_create(struct pipe_context *pipe,
177              struct u_vbuf_caps *caps)
178{
179   struct u_vbuf *mgr = CALLOC_STRUCT(u_vbuf);
180
181   mgr->caps = *caps;
182   mgr->pipe = pipe;
183   mgr->cso_cache = cso_cache_create();
184   mgr->translate_cache = translate_cache_create();
185   memset(mgr->fallback_vbs, ~0, sizeof(mgr->fallback_vbs));
186
187   mgr->uploader = u_upload_create(pipe, 1024 * 1024, 4,
188                                   PIPE_BIND_VERTEX_BUFFER);
189
190   return mgr;
191}
192
193/* u_vbuf uses its own caching for vertex elements, because it needs to keep
194 * its own preprocessed state per vertex element CSO. */
195static struct u_vbuf_elements *
196u_vbuf_set_vertex_elements_internal(struct u_vbuf *mgr, unsigned count,
197                                    const struct pipe_vertex_element *states)
198{
199   struct pipe_context *pipe = mgr->pipe;
200   unsigned key_size, hash_key;
201   struct cso_hash_iter iter;
202   struct u_vbuf_elements *ve;
203   struct cso_velems_state velems_state;
204
205   /* need to include the count into the stored state data too. */
206   key_size = sizeof(struct pipe_vertex_element) * count + sizeof(unsigned);
207   velems_state.count = count;
208   memcpy(velems_state.velems, states,
209          sizeof(struct pipe_vertex_element) * count);
210   hash_key = cso_construct_key((void*)&velems_state, key_size);
211   iter = cso_find_state_template(mgr->cso_cache, hash_key, CSO_VELEMENTS,
212                                  (void*)&velems_state, key_size);
213
214   if (cso_hash_iter_is_null(iter)) {
215      struct cso_velements *cso = MALLOC_STRUCT(cso_velements);
216      memcpy(&cso->state, &velems_state, key_size);
217      cso->data = u_vbuf_create_vertex_elements(mgr, count, states);
218      cso->delete_state = (cso_state_callback)u_vbuf_delete_vertex_elements;
219      cso->context = (void*)mgr;
220
221      iter = cso_insert_state(mgr->cso_cache, hash_key, CSO_VELEMENTS, cso);
222      ve = cso->data;
223   } else {
224      ve = ((struct cso_velements *)cso_hash_iter_data(iter))->data;
225   }
226
227   assert(ve);
228   pipe->bind_vertex_elements_state(pipe, ve->driver_cso);
229   return ve;
230}
231
232void u_vbuf_set_vertex_elements(struct u_vbuf *mgr, unsigned count,
233                               const struct pipe_vertex_element *states)
234{
235   mgr->ve = u_vbuf_set_vertex_elements_internal(mgr, count, states);
236}
237
238void u_vbuf_destroy(struct u_vbuf *mgr)
239{
240   unsigned i;
241
242   for (i = 0; i < mgr->nr_vertex_buffers; i++) {
243      pipe_resource_reference(&mgr->vertex_buffer[i].buffer, NULL);
244   }
245   for (i = 0; i < mgr->nr_real_vertex_buffers; i++) {
246      pipe_resource_reference(&mgr->real_vertex_buffer[i].buffer, NULL);
247   }
248
249   translate_cache_destroy(mgr->translate_cache);
250   u_upload_destroy(mgr->uploader);
251   cso_cache_delete(mgr->cso_cache);
252   FREE(mgr);
253}
254
255static void
256u_vbuf_translate_buffers(struct u_vbuf *mgr, struct translate_key *key,
257                         unsigned vb_mask, unsigned out_vb,
258                         int start_vertex, unsigned num_vertices,
259                         int start_index, unsigned num_indices, int min_index,
260                         boolean unroll_indices)
261{
262   struct translate *tr;
263   struct pipe_transfer *vb_transfer[PIPE_MAX_ATTRIBS] = {0};
264   struct pipe_resource *out_buffer = NULL;
265   uint8_t *out_map;
266   unsigned i, out_offset;
267
268   /* Get a translate object. */
269   tr = translate_cache_find(mgr->translate_cache, key);
270
271   /* Map buffers we want to translate. */
272   for (i = 0; i < mgr->nr_vertex_buffers; i++) {
273      if (vb_mask & (1 << i)) {
274         struct pipe_vertex_buffer *vb = &mgr->vertex_buffer[i];
275         unsigned offset = vb->buffer_offset + vb->stride * start_vertex;
276         uint8_t *map;
277
278         if (vb->buffer->user_ptr) {
279            map = vb->buffer->user_ptr + offset;
280         } else {
281            unsigned size = vb->stride ? num_vertices * vb->stride
282                                       : sizeof(double)*4;
283
284            if (offset+size > vb->buffer->width0) {
285               size = vb->buffer->width0 - offset;
286            }
287
288            map = pipe_buffer_map_range(mgr->pipe, vb->buffer, offset, size,
289                                        PIPE_TRANSFER_READ, &vb_transfer[i]);
290         }
291
292         /* Subtract min_index so that indexing with the index buffer works. */
293         if (unroll_indices) {
294            map -= vb->stride * min_index;
295         }
296
297         tr->set_buffer(tr, i, map, vb->stride, ~0);
298      }
299   }
300
301   /* Translate. */
302   if (unroll_indices) {
303      struct pipe_index_buffer *ib = &mgr->index_buffer;
304      struct pipe_transfer *transfer = NULL;
305      unsigned offset = ib->offset + start_index * ib->index_size;
306      uint8_t *map;
307
308      assert(ib->buffer && ib->index_size);
309
310      if (ib->buffer->user_ptr) {
311         map = ib->buffer->user_ptr + offset;
312      } else {
313         map = pipe_buffer_map_range(mgr->pipe, ib->buffer, offset,
314                                     num_indices * ib->index_size,
315                                     PIPE_TRANSFER_READ, &transfer);
316      }
317
318      /* Create and map the output buffer. */
319      u_upload_alloc(mgr->uploader, 0,
320                     key->output_stride * num_indices,
321                     &out_offset, &out_buffer,
322                     (void**)&out_map);
323
324      switch (ib->index_size) {
325      case 4:
326         tr->run_elts(tr, (unsigned*)map, num_indices, 0, out_map);
327         break;
328      case 2:
329         tr->run_elts16(tr, (uint16_t*)map, num_indices, 0, out_map);
330         break;
331      case 1:
332         tr->run_elts8(tr, map, num_indices, 0, out_map);
333         break;
334      }
335
336      if (transfer) {
337         pipe_buffer_unmap(mgr->pipe, transfer);
338      }
339   } else {
340      /* Create and map the output buffer. */
341      u_upload_alloc(mgr->uploader,
342                     key->output_stride * start_vertex,
343                     key->output_stride * num_vertices,
344                     &out_offset, &out_buffer,
345                     (void**)&out_map);
346
347      out_offset -= key->output_stride * start_vertex;
348
349      tr->run(tr, 0, num_vertices, 0, out_map);
350   }
351
352   /* Unmap all buffers. */
353   for (i = 0; i < mgr->nr_vertex_buffers; i++) {
354      if (vb_transfer[i]) {
355         pipe_buffer_unmap(mgr->pipe, vb_transfer[i]);
356      }
357   }
358
359   /* Setup the new vertex buffer. */
360   mgr->real_vertex_buffer[out_vb].buffer_offset = out_offset;
361   mgr->real_vertex_buffer[out_vb].stride = key->output_stride;
362
363   /* Move the buffer reference. */
364   pipe_resource_reference(
365      &mgr->real_vertex_buffer[out_vb].buffer, NULL);
366   mgr->real_vertex_buffer[out_vb].buffer = out_buffer;
367}
368
369static boolean
370u_vbuf_translate_find_free_vb_slots(struct u_vbuf *mgr,
371                                    unsigned mask[VB_NUM])
372{
373   unsigned i, type;
374   unsigned nr = mgr->ve->count;
375   boolean used_vb[PIPE_MAX_ATTRIBS] = {0};
376   unsigned fallback_vbs[VB_NUM];
377
378   memset(fallback_vbs, ~0, sizeof(fallback_vbs));
379
380   /* Mark used vertex buffers as... used. */
381   for (i = 0; i < nr; i++) {
382      if (!(mgr->ve->incompatible_elem_mask & (1 << i))) {
383         unsigned index = mgr->ve->ve[i].vertex_buffer_index;
384
385         if (!(mgr->incompatible_vb_mask & (1 << index))) {
386            used_vb[index] = TRUE;
387         }
388      }
389   }
390
391   /* Find free slots for each type if needed. */
392   i = 0;
393   for (type = 0; type < VB_NUM; type++) {
394      if (mask[type]) {
395         for (; i < PIPE_MAX_ATTRIBS; i++) {
396            if (!used_vb[i]) {
397               /*printf("found slot=%i for type=%i\n", i, type);*/
398               fallback_vbs[type] = i;
399               i++;
400               if (i > mgr->nr_real_vertex_buffers) {
401                  mgr->nr_real_vertex_buffers = i;
402               }
403               break;
404            }
405         }
406         if (i == PIPE_MAX_ATTRIBS) {
407            /* fail, reset the number to its original value */
408            mgr->nr_real_vertex_buffers = mgr->nr_vertex_buffers;
409            return FALSE;
410         }
411      }
412   }
413
414   memcpy(mgr->fallback_vbs, fallback_vbs, sizeof(fallback_vbs));
415   return TRUE;
416}
417
418static boolean
419u_vbuf_translate_begin(struct u_vbuf *mgr,
420                       int start_vertex, unsigned num_vertices,
421                       int start_instance, unsigned num_instances,
422                       int start_index, unsigned num_indices, int min_index,
423                       boolean unroll_indices)
424{
425   unsigned mask[VB_NUM] = {0};
426   struct translate_key key[VB_NUM];
427   unsigned elem_index[VB_NUM][PIPE_MAX_ATTRIBS]; /* ... into key.elements */
428   unsigned i, type;
429
430   int start[VB_NUM] = {
431      start_vertex,     /* VERTEX */
432      start_instance,   /* INSTANCE */
433      0                 /* CONST */
434   };
435
436   unsigned num[VB_NUM] = {
437      num_vertices,     /* VERTEX */
438      num_instances,    /* INSTANCE */
439      1                 /* CONST */
440   };
441
442   memset(key, 0, sizeof(key));
443   memset(elem_index, ~0, sizeof(elem_index));
444
445   /* See if there are vertex attribs of each type to translate and
446    * which ones. */
447   for (i = 0; i < mgr->ve->count; i++) {
448      unsigned vb_index = mgr->ve->ve[i].vertex_buffer_index;
449
450      if (!mgr->vertex_buffer[vb_index].stride) {
451         if (!(mgr->ve->incompatible_elem_mask & (1 << i)) &&
452             !(mgr->incompatible_vb_mask & (1 << vb_index))) {
453            continue;
454         }
455         mask[VB_CONST] |= 1 << vb_index;
456      } else if (mgr->ve->ve[i].instance_divisor) {
457         if (!(mgr->ve->incompatible_elem_mask & (1 << i)) &&
458             !(mgr->incompatible_vb_mask & (1 << vb_index))) {
459            continue;
460         }
461         mask[VB_INSTANCE] |= 1 << vb_index;
462      } else {
463         if (!unroll_indices &&
464             !(mgr->ve->incompatible_elem_mask & (1 << i)) &&
465             !(mgr->incompatible_vb_mask & (1 << vb_index))) {
466            continue;
467         }
468         mask[VB_VERTEX] |= 1 << vb_index;
469      }
470   }
471
472   assert(mask[VB_VERTEX] || mask[VB_INSTANCE] || mask[VB_CONST]);
473
474   /* Find free vertex buffer slots. */
475   if (!u_vbuf_translate_find_free_vb_slots(mgr, mask)) {
476      return FALSE;
477   }
478
479   /* Initialize the translate keys. */
480   for (i = 0; i < mgr->ve->count; i++) {
481      struct translate_key *k;
482      struct translate_element *te;
483      unsigned bit, vb_index = mgr->ve->ve[i].vertex_buffer_index;
484      bit = 1 << vb_index;
485
486      if (!(mgr->ve->incompatible_elem_mask & (1 << i)) &&
487          !(mgr->incompatible_vb_mask & (1 << vb_index)) &&
488          (!unroll_indices || !(mask[VB_VERTEX] & bit))) {
489         continue;
490      }
491
492      /* Set type to what we will translate.
493       * Whether vertex, instance, or constant attribs. */
494      for (type = 0; type < VB_NUM; type++) {
495         if (mask[type] & bit) {
496            break;
497         }
498      }
499      assert(type < VB_NUM);
500      assert(translate_is_output_format_supported(mgr->ve->native_format[i]));
501      /*printf("velem=%i type=%i\n", i, type);*/
502
503      /* Add the vertex element. */
504      k = &key[type];
505      elem_index[type][i] = k->nr_elements;
506
507      te = &k->element[k->nr_elements];
508      te->type = TRANSLATE_ELEMENT_NORMAL;
509      te->instance_divisor = 0;
510      te->input_buffer = vb_index;
511      te->input_format = mgr->ve->ve[i].src_format;
512      te->input_offset = mgr->ve->ve[i].src_offset;
513      te->output_format = mgr->ve->native_format[i];
514      te->output_offset = k->output_stride;
515
516      k->output_stride += mgr->ve->native_format_size[i];
517      k->nr_elements++;
518   }
519
520   /* Translate buffers. */
521   for (type = 0; type < VB_NUM; type++) {
522      if (key[type].nr_elements) {
523         u_vbuf_translate_buffers(mgr, &key[type], mask[type],
524                                  mgr->fallback_vbs[type],
525                                  start[type], num[type],
526                                  start_index, num_indices, min_index,
527                                  unroll_indices && type == VB_VERTEX);
528
529         /* Fixup the stride for constant attribs. */
530         if (type == VB_CONST) {
531            mgr->real_vertex_buffer[mgr->fallback_vbs[VB_CONST]].stride = 0;
532         }
533      }
534   }
535
536   /* Setup new vertex elements. */
537   for (i = 0; i < mgr->ve->count; i++) {
538      for (type = 0; type < VB_NUM; type++) {
539         if (elem_index[type][i] < key[type].nr_elements) {
540            struct translate_element *te = &key[type].element[elem_index[type][i]];
541            mgr->fallback_velems[i].instance_divisor = mgr->ve->ve[i].instance_divisor;
542            mgr->fallback_velems[i].src_format = te->output_format;
543            mgr->fallback_velems[i].src_offset = te->output_offset;
544            mgr->fallback_velems[i].vertex_buffer_index = mgr->fallback_vbs[type];
545
546            /* elem_index[type][i] can only be set for one type. */
547            assert(type > VB_INSTANCE || elem_index[type+1][i] == ~0);
548            assert(type > VB_VERTEX   || elem_index[type+2][i] == ~0);
549            break;
550         }
551      }
552      /* No translating, just copy the original vertex element over. */
553      if (type == VB_NUM) {
554         memcpy(&mgr->fallback_velems[i], &mgr->ve->ve[i],
555                sizeof(struct pipe_vertex_element));
556      }
557   }
558
559   u_vbuf_set_vertex_elements_internal(mgr, mgr->ve->count,
560                                       mgr->fallback_velems);
561   mgr->using_translate = TRUE;
562   return TRUE;
563}
564
565static void u_vbuf_translate_end(struct u_vbuf *mgr)
566{
567   unsigned i;
568
569   /* Restore vertex elements. */
570   mgr->pipe->bind_vertex_elements_state(mgr->pipe, mgr->ve->driver_cso);
571   mgr->using_translate = FALSE;
572
573   /* Unreference the now-unused VBOs. */
574   for (i = 0; i < VB_NUM; i++) {
575      unsigned vb = mgr->fallback_vbs[i];
576      if (vb != ~0) {
577         pipe_resource_reference(&mgr->real_vertex_buffer[vb].buffer, NULL);
578         mgr->fallback_vbs[i] = ~0;
579      }
580   }
581   mgr->nr_real_vertex_buffers = mgr->nr_vertex_buffers;
582}
583
584#define FORMAT_REPLACE(what, withwhat) \
585    case PIPE_FORMAT_##what: format = PIPE_FORMAT_##withwhat; break
586
587static void *
588u_vbuf_create_vertex_elements(struct u_vbuf *mgr, unsigned count,
589                              const struct pipe_vertex_element *attribs)
590{
591   struct pipe_context *pipe = mgr->pipe;
592   unsigned i;
593   struct pipe_vertex_element driver_attribs[PIPE_MAX_ATTRIBS];
594   struct u_vbuf_elements *ve = CALLOC_STRUCT(u_vbuf_elements);
595   uint32_t used_buffers = 0;
596
597   ve->count = count;
598
599   memcpy(ve->ve, attribs, sizeof(struct pipe_vertex_element) * count);
600   memcpy(driver_attribs, attribs, sizeof(struct pipe_vertex_element) * count);
601
602   /* Set the best native format in case the original format is not
603    * supported. */
604   for (i = 0; i < count; i++) {
605      enum pipe_format format = ve->ve[i].src_format;
606
607      ve->src_format_size[i] = util_format_get_blocksize(format);
608
609      used_buffers |= 1 << ve->ve[i].vertex_buffer_index;
610
611      if (!ve->ve[i].instance_divisor) {
612         ve->noninstance_vb_mask_any |= 1 << ve->ve[i].vertex_buffer_index;
613      }
614
615      /* Choose a native format.
616       * For now we don't care about the alignment, that's going to
617       * be sorted out later. */
618      if (!mgr->caps.format_fixed32) {
619         switch (format) {
620            FORMAT_REPLACE(R32_FIXED,           R32_FLOAT);
621            FORMAT_REPLACE(R32G32_FIXED,        R32G32_FLOAT);
622            FORMAT_REPLACE(R32G32B32_FIXED,     R32G32B32_FLOAT);
623            FORMAT_REPLACE(R32G32B32A32_FIXED,  R32G32B32A32_FLOAT);
624            default:;
625         }
626      }
627      if (!mgr->caps.format_float16) {
628         switch (format) {
629            FORMAT_REPLACE(R16_FLOAT,           R32_FLOAT);
630            FORMAT_REPLACE(R16G16_FLOAT,        R32G32_FLOAT);
631            FORMAT_REPLACE(R16G16B16_FLOAT,     R32G32B32_FLOAT);
632            FORMAT_REPLACE(R16G16B16A16_FLOAT,  R32G32B32A32_FLOAT);
633            default:;
634         }
635      }
636      if (!mgr->caps.format_float64) {
637         switch (format) {
638            FORMAT_REPLACE(R64_FLOAT,           R32_FLOAT);
639            FORMAT_REPLACE(R64G64_FLOAT,        R32G32_FLOAT);
640            FORMAT_REPLACE(R64G64B64_FLOAT,     R32G32B32_FLOAT);
641            FORMAT_REPLACE(R64G64B64A64_FLOAT,  R32G32B32A32_FLOAT);
642            default:;
643         }
644      }
645      if (!mgr->caps.format_norm32) {
646         switch (format) {
647            FORMAT_REPLACE(R32_UNORM,           R32_FLOAT);
648            FORMAT_REPLACE(R32G32_UNORM,        R32G32_FLOAT);
649            FORMAT_REPLACE(R32G32B32_UNORM,     R32G32B32_FLOAT);
650            FORMAT_REPLACE(R32G32B32A32_UNORM,  R32G32B32A32_FLOAT);
651            FORMAT_REPLACE(R32_SNORM,           R32_FLOAT);
652            FORMAT_REPLACE(R32G32_SNORM,        R32G32_FLOAT);
653            FORMAT_REPLACE(R32G32B32_SNORM,     R32G32B32_FLOAT);
654            FORMAT_REPLACE(R32G32B32A32_SNORM,  R32G32B32A32_FLOAT);
655            default:;
656         }
657      }
658      if (!mgr->caps.format_scaled32) {
659         switch (format) {
660            FORMAT_REPLACE(R32_USCALED,         R32_FLOAT);
661            FORMAT_REPLACE(R32G32_USCALED,      R32G32_FLOAT);
662            FORMAT_REPLACE(R32G32B32_USCALED,   R32G32B32_FLOAT);
663            FORMAT_REPLACE(R32G32B32A32_USCALED,R32G32B32A32_FLOAT);
664            FORMAT_REPLACE(R32_SSCALED,         R32_FLOAT);
665            FORMAT_REPLACE(R32G32_SSCALED,      R32G32_FLOAT);
666            FORMAT_REPLACE(R32G32B32_SSCALED,   R32G32B32_FLOAT);
667            FORMAT_REPLACE(R32G32B32A32_SSCALED,R32G32B32A32_FLOAT);
668            default:;
669         }
670      }
671
672      driver_attribs[i].src_format = format;
673      ve->native_format[i] = format;
674      ve->native_format_size[i] =
675            util_format_get_blocksize(ve->native_format[i]);
676
677      if (ve->ve[i].src_format != format ||
678          (!mgr->caps.velem_src_offset_unaligned &&
679           ve->ve[i].src_offset % 4 != 0)) {
680         ve->incompatible_elem_mask |= 1 << i;
681         ve->incompatible_vb_mask_any |= 1 << ve->ve[i].vertex_buffer_index;
682      } else {
683         ve->compatible_vb_mask_any |= 1 << ve->ve[i].vertex_buffer_index;
684      }
685   }
686
687   ve->compatible_vb_mask_all = ~ve->incompatible_vb_mask_any & used_buffers;
688   ve->incompatible_vb_mask_all = ~ve->compatible_vb_mask_any & used_buffers;
689
690   /* Align the formats to the size of DWORD if needed. */
691   if (!mgr->caps.velem_src_offset_unaligned) {
692      for (i = 0; i < count; i++) {
693         ve->native_format_size[i] = align(ve->native_format_size[i], 4);
694      }
695   }
696
697   ve->driver_cso =
698      pipe->create_vertex_elements_state(pipe, count, driver_attribs);
699   return ve;
700}
701
702static void u_vbuf_delete_vertex_elements(struct u_vbuf *mgr, void *cso)
703{
704   struct pipe_context *pipe = mgr->pipe;
705   struct u_vbuf_elements *ve = cso;
706
707   pipe->delete_vertex_elements_state(pipe, ve->driver_cso);
708   FREE(ve);
709}
710
711void u_vbuf_set_vertex_buffers(struct u_vbuf *mgr, unsigned count,
712                               const struct pipe_vertex_buffer *bufs)
713{
714   unsigned i;
715
716   mgr->user_vb_mask = 0;
717   mgr->incompatible_vb_mask = 0;
718   mgr->nonzero_stride_vb_mask = 0;
719
720   for (i = 0; i < count; i++) {
721      const struct pipe_vertex_buffer *vb = &bufs[i];
722      struct pipe_vertex_buffer *orig_vb = &mgr->vertex_buffer[i];
723      struct pipe_vertex_buffer *real_vb = &mgr->real_vertex_buffer[i];
724
725      pipe_resource_reference(&orig_vb->buffer, vb->buffer);
726
727      real_vb->buffer_offset = orig_vb->buffer_offset = vb->buffer_offset;
728      real_vb->stride = orig_vb->stride = vb->stride;
729
730      if (vb->stride) {
731         mgr->nonzero_stride_vb_mask |= 1 << i;
732      }
733
734      if (!vb->buffer) {
735         pipe_resource_reference(&real_vb->buffer, NULL);
736         continue;
737      }
738
739      if ((!mgr->caps.buffer_offset_unaligned && vb->buffer_offset % 4 != 0) ||
740          (!mgr->caps.buffer_stride_unaligned && vb->stride % 4 != 0)) {
741         mgr->incompatible_vb_mask |= 1 << i;
742         pipe_resource_reference(&real_vb->buffer, NULL);
743         continue;
744      }
745
746      if (vb->buffer->user_ptr) {
747         mgr->user_vb_mask |= 1 << i;
748         pipe_resource_reference(&real_vb->buffer, NULL);
749         continue;
750      }
751
752      pipe_resource_reference(&real_vb->buffer, vb->buffer);
753   }
754
755   for (i = count; i < mgr->nr_vertex_buffers; i++) {
756      pipe_resource_reference(&mgr->vertex_buffer[i].buffer, NULL);
757   }
758   for (i = count; i < mgr->nr_real_vertex_buffers; i++) {
759      pipe_resource_reference(&mgr->real_vertex_buffer[i].buffer, NULL);
760   }
761
762   mgr->nr_vertex_buffers = count;
763   mgr->nr_real_vertex_buffers = count;
764   mgr->vertex_buffers_dirty = TRUE;
765}
766
767void u_vbuf_set_index_buffer(struct u_vbuf *mgr,
768                             const struct pipe_index_buffer *ib)
769{
770   struct pipe_context *pipe = mgr->pipe;
771
772   if (ib && ib->buffer) {
773      assert(ib->offset % ib->index_size == 0);
774      pipe_resource_reference(&mgr->index_buffer.buffer, ib->buffer);
775      mgr->index_buffer.offset = ib->offset;
776      mgr->index_buffer.index_size = ib->index_size;
777   } else {
778      pipe_resource_reference(&mgr->index_buffer.buffer, NULL);
779   }
780
781   pipe->set_index_buffer(pipe, ib);
782}
783
784static void
785u_vbuf_upload_buffers(struct u_vbuf *mgr,
786                      int start_vertex, unsigned num_vertices,
787                      int start_instance, unsigned num_instances)
788{
789   unsigned i;
790   unsigned nr_velems = mgr->ve->count;
791   unsigned nr_vbufs = mgr->nr_vertex_buffers;
792   struct pipe_vertex_element *velems =
793         mgr->using_translate ? mgr->fallback_velems : mgr->ve->ve;
794   unsigned start_offset[PIPE_MAX_ATTRIBS];
795   unsigned end_offset[PIPE_MAX_ATTRIBS] = {0};
796
797   /* Determine how much data needs to be uploaded. */
798   for (i = 0; i < nr_velems; i++) {
799      struct pipe_vertex_element *velem = &velems[i];
800      unsigned index = velem->vertex_buffer_index;
801      struct pipe_vertex_buffer *vb = &mgr->vertex_buffer[index];
802      unsigned instance_div, first, size;
803
804      /* Skip the buffers generated by translate. */
805      if (index == mgr->fallback_vbs[VB_VERTEX] ||
806          index == mgr->fallback_vbs[VB_INSTANCE] ||
807          index == mgr->fallback_vbs[VB_CONST]) {
808         continue;
809      }
810
811      assert(vb->buffer);
812
813      if (!vb->buffer->user_ptr) {
814         continue;
815      }
816
817      instance_div = velem->instance_divisor;
818      first = vb->buffer_offset + velem->src_offset;
819
820      if (!vb->stride) {
821         /* Constant attrib. */
822         size = mgr->ve->src_format_size[i];
823      } else if (instance_div) {
824         /* Per-instance attrib. */
825         unsigned count = (num_instances + instance_div - 1) / instance_div;
826         first += vb->stride * start_instance;
827         size = vb->stride * (count - 1) + mgr->ve->src_format_size[i];
828      } else {
829         /* Per-vertex attrib. */
830         first += vb->stride * start_vertex;
831         size = vb->stride * (num_vertices - 1) + mgr->ve->src_format_size[i];
832      }
833
834      /* Update offsets. */
835      if (!end_offset[index]) {
836         start_offset[index] = first;
837         end_offset[index] = first + size;
838      } else {
839         if (first < start_offset[index])
840            start_offset[index] = first;
841         if (first + size > end_offset[index])
842            end_offset[index] = first + size;
843      }
844   }
845
846   /* Upload buffers. */
847   for (i = 0; i < nr_vbufs; i++) {
848      unsigned start, end = end_offset[i];
849      struct pipe_vertex_buffer *real_vb;
850      uint8_t *ptr;
851
852      if (!end) {
853         continue;
854      }
855
856      start = start_offset[i];
857      assert(start < end);
858
859      real_vb = &mgr->real_vertex_buffer[i];
860      ptr = mgr->vertex_buffer[i].buffer->user_ptr;
861
862      u_upload_data(mgr->uploader, start, end - start, ptr + start,
863                    &real_vb->buffer_offset, &real_vb->buffer);
864
865      real_vb->buffer_offset -= start;
866   }
867}
868
869static boolean u_vbuf_need_minmax_index(struct u_vbuf *mgr)
870{
871   /* See if there are any per-vertex attribs which will be uploaded or
872    * translated. Use bitmasks to get the info instead of looping over vertex
873    * elements. */
874   return ((mgr->user_vb_mask | mgr->incompatible_vb_mask |
875            mgr->ve->incompatible_vb_mask_any) &
876           mgr->ve->noninstance_vb_mask_any & mgr->nonzero_stride_vb_mask) != 0;
877}
878
879static boolean u_vbuf_mapping_vertex_buffer_blocks(struct u_vbuf *mgr)
880{
881   /* Return true if there are hw buffers which don't need to be translated.
882    *
883    * We could query whether each buffer is busy, but that would
884    * be way more costly than this. */
885   return (~mgr->user_vb_mask & ~mgr->incompatible_vb_mask &
886           mgr->ve->compatible_vb_mask_all & mgr->ve->noninstance_vb_mask_any &
887           mgr->nonzero_stride_vb_mask) != 0;
888}
889
890static void u_vbuf_get_minmax_index(struct pipe_context *pipe,
891                                    struct pipe_index_buffer *ib,
892                                    const struct pipe_draw_info *info,
893                                    int *out_min_index,
894                                    int *out_max_index)
895{
896   struct pipe_transfer *transfer = NULL;
897   const void *indices;
898   unsigned i;
899   unsigned restart_index = info->restart_index;
900
901   if (ib->buffer->user_ptr) {
902      indices = ib->buffer->user_ptr +
903                ib->offset + info->start * ib->index_size;
904   } else {
905      indices = pipe_buffer_map_range(pipe, ib->buffer,
906                                      ib->offset + info->start * ib->index_size,
907                                      info->count * ib->index_size,
908                                      PIPE_TRANSFER_READ, &transfer);
909   }
910
911   switch (ib->index_size) {
912   case 4: {
913      const unsigned *ui_indices = (const unsigned*)indices;
914      unsigned max_ui = 0;
915      unsigned min_ui = ~0U;
916      if (info->primitive_restart) {
917         for (i = 0; i < info->count; i++) {
918            if (ui_indices[i] != restart_index) {
919               if (ui_indices[i] > max_ui) max_ui = ui_indices[i];
920               if (ui_indices[i] < min_ui) min_ui = ui_indices[i];
921            }
922         }
923      }
924      else {
925         for (i = 0; i < info->count; i++) {
926            if (ui_indices[i] > max_ui) max_ui = ui_indices[i];
927            if (ui_indices[i] < min_ui) min_ui = ui_indices[i];
928         }
929      }
930      *out_min_index = min_ui;
931      *out_max_index = max_ui;
932      break;
933   }
934   case 2: {
935      const unsigned short *us_indices = (const unsigned short*)indices;
936      unsigned max_us = 0;
937      unsigned min_us = ~0U;
938      if (info->primitive_restart) {
939         for (i = 0; i < info->count; i++) {
940            if (us_indices[i] != restart_index) {
941               if (us_indices[i] > max_us) max_us = us_indices[i];
942               if (us_indices[i] < min_us) min_us = us_indices[i];
943            }
944         }
945      }
946      else {
947         for (i = 0; i < info->count; i++) {
948            if (us_indices[i] > max_us) max_us = us_indices[i];
949            if (us_indices[i] < min_us) min_us = us_indices[i];
950         }
951      }
952      *out_min_index = min_us;
953      *out_max_index = max_us;
954      break;
955   }
956   case 1: {
957      const unsigned char *ub_indices = (const unsigned char*)indices;
958      unsigned max_ub = 0;
959      unsigned min_ub = ~0U;
960      if (info->primitive_restart) {
961         for (i = 0; i < info->count; i++) {
962            if (ub_indices[i] != restart_index) {
963               if (ub_indices[i] > max_ub) max_ub = ub_indices[i];
964               if (ub_indices[i] < min_ub) min_ub = ub_indices[i];
965            }
966         }
967      }
968      else {
969         for (i = 0; i < info->count; i++) {
970            if (ub_indices[i] > max_ub) max_ub = ub_indices[i];
971            if (ub_indices[i] < min_ub) min_ub = ub_indices[i];
972         }
973      }
974      *out_min_index = min_ub;
975      *out_max_index = max_ub;
976      break;
977   }
978   default:
979      assert(0);
980      *out_min_index = 0;
981      *out_max_index = 0;
982   }
983
984   if (transfer) {
985      pipe_buffer_unmap(pipe, transfer);
986   }
987}
988
989void u_vbuf_draw_vbo(struct u_vbuf *mgr, const struct pipe_draw_info *info)
990{
991   struct pipe_context *pipe = mgr->pipe;
992   int start_vertex, min_index;
993   unsigned num_vertices;
994   boolean unroll_indices = FALSE;
995
996   /* Normal draw. No fallback and no user buffers. */
997   if (!mgr->incompatible_vb_mask &&
998       !mgr->ve->incompatible_elem_mask &&
999       !mgr->user_vb_mask) {
1000      /* Set vertex buffers if needed. */
1001      if (mgr->vertex_buffers_dirty) {
1002         pipe->set_vertex_buffers(pipe, mgr->nr_real_vertex_buffers,
1003                                  mgr->real_vertex_buffer);
1004         mgr->vertex_buffers_dirty = FALSE;
1005      }
1006
1007      pipe->draw_vbo(pipe, info);
1008      return;
1009   }
1010
1011   if (info->indexed) {
1012      /* See if anything needs to be done for per-vertex attribs. */
1013      if (u_vbuf_need_minmax_index(mgr)) {
1014         int max_index;
1015
1016         if (info->max_index != ~0) {
1017            min_index = info->min_index;
1018            max_index = info->max_index;
1019         } else {
1020            u_vbuf_get_minmax_index(mgr->pipe, &mgr->index_buffer, info,
1021                                    &min_index, &max_index);
1022         }
1023
1024         assert(min_index <= max_index);
1025
1026         start_vertex = min_index + info->index_bias;
1027         num_vertices = max_index + 1 - min_index;
1028
1029         /* Primitive restart doesn't work when unrolling indices.
1030          * We would have to break this drawing operation into several ones. */
1031         /* Use some heuristic to see if unrolling indices improves
1032          * performance. */
1033         if (!info->primitive_restart &&
1034             num_vertices > info->count*2 &&
1035             num_vertices-info->count > 32 &&
1036             !u_vbuf_mapping_vertex_buffer_blocks(mgr)) {
1037            /*printf("num_vertices=%i count=%i\n", num_vertices, info->count);*/
1038            unroll_indices = TRUE;
1039         }
1040      } else {
1041         /* Nothing to do for per-vertex attribs. */
1042         start_vertex = 0;
1043         num_vertices = 0;
1044         min_index = 0;
1045      }
1046   } else {
1047      start_vertex = info->start;
1048      num_vertices = info->count;
1049      min_index = 0;
1050   }
1051
1052   /* Translate vertices with non-native layouts or formats. */
1053   if (unroll_indices ||
1054       mgr->incompatible_vb_mask ||
1055       mgr->ve->incompatible_elem_mask) {
1056      /* XXX check the return value */
1057      u_vbuf_translate_begin(mgr, start_vertex, num_vertices,
1058                             info->start_instance, info->instance_count,
1059                             info->start, info->count, min_index,
1060                             unroll_indices);
1061   }
1062
1063   /* Upload user buffers. */
1064   if (mgr->user_vb_mask) {
1065      u_vbuf_upload_buffers(mgr, start_vertex, num_vertices,
1066                            info->start_instance, info->instance_count);
1067   }
1068
1069   /*
1070   if (unroll_indices) {
1071      printf("unrolling indices: start_vertex = %i, num_vertices = %i\n",
1072             start_vertex, num_vertices);
1073      util_dump_draw_info(stdout, info);
1074      printf("\n");
1075   }
1076
1077   unsigned i;
1078   for (i = 0; i < mgr->nr_vertex_buffers; i++) {
1079      printf("input %i: ", i);
1080      util_dump_vertex_buffer(stdout, mgr->vertex_buffer+i);
1081      printf("\n");
1082   }
1083   for (i = 0; i < mgr->nr_real_vertex_buffers; i++) {
1084      printf("real %i: ", i);
1085      util_dump_vertex_buffer(stdout, mgr->real_vertex_buffer+i);
1086      printf("\n");
1087   }
1088   */
1089
1090   u_upload_unmap(mgr->uploader);
1091   pipe->set_vertex_buffers(pipe, mgr->nr_real_vertex_buffers,
1092                            mgr->real_vertex_buffer);
1093
1094   if (unlikely(unroll_indices)) {
1095      struct pipe_draw_info new_info = *info;
1096      new_info.indexed = FALSE;
1097      new_info.index_bias = 0;
1098      new_info.min_index = 0;
1099      new_info.max_index = info->count - 1;
1100      new_info.start = 0;
1101
1102      pipe->draw_vbo(pipe, &new_info);
1103   } else {
1104      pipe->draw_vbo(pipe, info);
1105   }
1106
1107   if (mgr->using_translate) {
1108      u_vbuf_translate_end(mgr);
1109   }
1110   mgr->vertex_buffers_dirty = TRUE;
1111}
1112
1113void u_vbuf_save_vertex_elements(struct u_vbuf *mgr)
1114{
1115   assert(!mgr->ve_saved);
1116   mgr->ve_saved = mgr->ve;
1117}
1118
1119void u_vbuf_restore_vertex_elements(struct u_vbuf *mgr)
1120{
1121   if (mgr->ve != mgr->ve_saved) {
1122      struct pipe_context *pipe = mgr->pipe;
1123
1124      mgr->ve = mgr->ve_saved;
1125      pipe->bind_vertex_elements_state(pipe,
1126                                       mgr->ve ? mgr->ve->driver_cso : NULL);
1127   }
1128   mgr->ve_saved = NULL;
1129}
1130
1131void u_vbuf_save_vertex_buffers(struct u_vbuf *mgr)
1132{
1133   util_copy_vertex_buffers(mgr->vertex_buffer_saved,
1134                            &mgr->nr_vertex_buffers_saved,
1135                            mgr->vertex_buffer,
1136                            mgr->nr_vertex_buffers);
1137}
1138
1139void u_vbuf_restore_vertex_buffers(struct u_vbuf *mgr)
1140{
1141   unsigned i;
1142
1143   u_vbuf_set_vertex_buffers(mgr, mgr->nr_vertex_buffers_saved,
1144                             mgr->vertex_buffer_saved);
1145   for (i = 0; i < mgr->nr_vertex_buffers_saved; i++) {
1146      pipe_resource_reference(&mgr->vertex_buffer_saved[i].buffer, NULL);
1147   }
1148   mgr->nr_vertex_buffers_saved = 0;
1149}
1150