vfetchoptimizer.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // This file is part of meshoptimizer library; see meshoptimizer.h for version/license details
  2. #include "meshoptimizer.h"
  3. #include <assert.h>
  4. #include <string.h>
  5. size_t meshopt_optimizeVertexFetchRemap(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count)
  6. {
  7. assert(index_count % 3 == 0);
  8. memset(destination, -1, vertex_count * sizeof(unsigned int));
  9. unsigned int next_vertex = 0;
  10. for (size_t i = 0; i < index_count; ++i)
  11. {
  12. unsigned int index = indices[i];
  13. assert(index < vertex_count);
  14. if (destination[index] == ~0u)
  15. {
  16. destination[index] = next_vertex++;
  17. }
  18. }
  19. assert(next_vertex <= vertex_count);
  20. return next_vertex;
  21. }
  22. size_t meshopt_optimizeVertexFetch(void* destination, unsigned int* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size)
  23. {
  24. assert(index_count % 3 == 0);
  25. assert(vertex_size > 0 && vertex_size <= 256);
  26. meshopt_Allocator allocator;
  27. // support in-place optimization
  28. if (destination == vertices)
  29. {
  30. unsigned char* vertices_copy = allocator.allocate<unsigned char>(vertex_count * vertex_size);
  31. memcpy(vertices_copy, vertices, vertex_count * vertex_size);
  32. vertices = vertices_copy;
  33. }
  34. // build vertex remap table
  35. unsigned int* vertex_remap = allocator.allocate<unsigned int>(vertex_count);
  36. memset(vertex_remap, -1, vertex_count * sizeof(unsigned int));
  37. unsigned int next_vertex = 0;
  38. for (size_t i = 0; i < index_count; ++i)
  39. {
  40. unsigned int index = indices[i];
  41. assert(index < vertex_count);
  42. unsigned int& remap = vertex_remap[index];
  43. if (remap == ~0u) // vertex was not added to destination VB
  44. {
  45. // add vertex
  46. memcpy(static_cast<unsigned char*>(destination) + next_vertex * vertex_size, static_cast<const unsigned char*>(vertices) + index * vertex_size, vertex_size);
  47. remap = next_vertex++;
  48. }
  49. // modify indices in place
  50. indices[i] = remap;
  51. }
  52. assert(next_vertex <= vertex_count);
  53. return next_vertex;
  54. }