Path: blob/master/thirdparty/meshoptimizer/simplifier.cpp
9896 views
// This file is part of meshoptimizer library; see meshoptimizer.h for version/license details1#include "meshoptimizer.h"23#include <assert.h>4#include <float.h>5#include <math.h>6#include <string.h>78#ifndef TRACE9#define TRACE 010#endif1112#if TRACE13#include <stdio.h>14#endif1516#if TRACE17#define TRACESTATS(i) stats[i]++;18#else19#define TRACESTATS(i) (void)020#endif2122// This work is based on:23// Michael Garland and Paul S. Heckbert. Surface simplification using quadric error metrics. 199724// Michael Garland. Quadric-based polygonal surface simplification. 199925// Peter Lindstrom. Out-of-Core Simplification of Large Polygonal Models. 200026// Matthias Teschner, Bruno Heidelberger, Matthias Mueller, Danat Pomeranets, Markus Gross. Optimized Spatial Hashing for Collision Detection of Deformable Objects. 200327// Peter Van Sandt, Yannis Chronis, Jignesh M. Patel. Efficiently Searching In-Memory Sorted Arrays: Revenge of the Interpolation Search? 201928// Hugues Hoppe. New Quadric Metric for Simplifying Meshes with Appearance Attributes. 199929namespace meshopt30{3132struct EdgeAdjacency33{34struct Edge35{36unsigned int next;37unsigned int prev;38};3940unsigned int* offsets;41Edge* data;42};4344static void prepareEdgeAdjacency(EdgeAdjacency& adjacency, size_t index_count, size_t vertex_count, meshopt_Allocator& allocator)45{46adjacency.offsets = allocator.allocate<unsigned int>(vertex_count + 1);47adjacency.data = allocator.allocate<EdgeAdjacency::Edge>(index_count);48}4950static void updateEdgeAdjacency(EdgeAdjacency& adjacency, const unsigned int* indices, size_t index_count, size_t vertex_count, const unsigned int* remap)51{52size_t face_count = index_count / 3;53unsigned int* offsets = adjacency.offsets + 1;54EdgeAdjacency::Edge* data = adjacency.data;5556// fill edge counts57memset(offsets, 0, vertex_count * sizeof(unsigned int));5859for (size_t i = 0; i < index_count; ++i)60{61unsigned int v = remap ? remap[indices[i]] : indices[i];62assert(v < vertex_count);6364offsets[v]++;65}6667// fill offset table68unsigned int offset = 0;6970for (size_t i = 0; i < vertex_count; ++i)71{72unsigned int count = offsets[i];73offsets[i] = offset;74offset += count;75}7677assert(offset == index_count);7879// fill edge data80for (size_t i = 0; i < face_count; ++i)81{82unsigned int a = indices[i * 3 + 0], b = indices[i * 3 + 1], c = indices[i * 3 + 2];8384if (remap)85{86a = remap[a];87b = remap[b];88c = remap[c];89}9091data[offsets[a]].next = b;92data[offsets[a]].prev = c;93offsets[a]++;9495data[offsets[b]].next = c;96data[offsets[b]].prev = a;97offsets[b]++;9899data[offsets[c]].next = a;100data[offsets[c]].prev = b;101offsets[c]++;102}103104// finalize offsets105adjacency.offsets[0] = 0;106assert(adjacency.offsets[vertex_count] == index_count);107}108109struct PositionHasher110{111const float* vertex_positions;112size_t vertex_stride_float;113const unsigned int* sparse_remap;114115size_t hash(unsigned int index) const116{117unsigned int ri = sparse_remap ? sparse_remap[index] : index;118const unsigned int* key = reinterpret_cast<const unsigned int*>(vertex_positions + ri * vertex_stride_float);119120unsigned int x = key[0], y = key[1], z = key[2];121122// replace negative zero with zero123x = (x == 0x80000000) ? 0 : x;124y = (y == 0x80000000) ? 0 : y;125z = (z == 0x80000000) ? 0 : z;126127// scramble bits to make sure that integer coordinates have entropy in lower bits128x ^= x >> 17;129y ^= y >> 17;130z ^= z >> 17;131132// Optimized Spatial Hashing for Collision Detection of Deformable Objects133return (x * 73856093) ^ (y * 19349663) ^ (z * 83492791);134}135136bool equal(unsigned int lhs, unsigned int rhs) const137{138unsigned int li = sparse_remap ? sparse_remap[lhs] : lhs;139unsigned int ri = sparse_remap ? sparse_remap[rhs] : rhs;140141const float* lv = vertex_positions + li * vertex_stride_float;142const float* rv = vertex_positions + ri * vertex_stride_float;143144return lv[0] == rv[0] && lv[1] == rv[1] && lv[2] == rv[2];145}146};147148struct RemapHasher149{150unsigned int* remap;151152size_t hash(unsigned int id) const153{154return id * 0x5bd1e995;155}156157bool equal(unsigned int lhs, unsigned int rhs) const158{159return remap[lhs] == rhs;160}161};162163static size_t hashBuckets2(size_t count)164{165size_t buckets = 1;166while (buckets < count + count / 4)167buckets *= 2;168169return buckets;170}171172template <typename T, typename Hash>173static T* hashLookup2(T* table, size_t buckets, const Hash& hash, const T& key, const T& empty)174{175assert(buckets > 0);176assert((buckets & (buckets - 1)) == 0);177178size_t hashmod = buckets - 1;179size_t bucket = hash.hash(key) & hashmod;180181for (size_t probe = 0; probe <= hashmod; ++probe)182{183T& item = table[bucket];184185if (item == empty)186return &item;187188if (hash.equal(item, key))189return &item;190191// hash collision, quadratic probing192bucket = (bucket + probe + 1) & hashmod;193}194195assert(false && "Hash table is full"); // unreachable196return NULL;197}198199static void buildPositionRemap(unsigned int* remap, unsigned int* wedge, const float* vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride, const unsigned int* sparse_remap, meshopt_Allocator& allocator)200{201PositionHasher hasher = {vertex_positions_data, vertex_positions_stride / sizeof(float), sparse_remap};202203size_t table_size = hashBuckets2(vertex_count);204unsigned int* table = allocator.allocate<unsigned int>(table_size);205memset(table, -1, table_size * sizeof(unsigned int));206207// build forward remap: for each vertex, which other (canonical) vertex does it map to?208// we use position equivalence for this, and remap vertices to other existing vertices209for (size_t i = 0; i < vertex_count; ++i)210{211unsigned int index = unsigned(i);212unsigned int* entry = hashLookup2(table, table_size, hasher, index, ~0u);213214if (*entry == ~0u)215*entry = index;216217remap[index] = *entry;218}219220allocator.deallocate(table);221222if (!wedge)223return;224225// build wedge table: for each vertex, which other vertex is the next wedge that also maps to the same vertex?226// entries in table form a (cyclic) wedge loop per vertex; for manifold vertices, wedge[i] == remap[i] == i227for (size_t i = 0; i < vertex_count; ++i)228wedge[i] = unsigned(i);229230for (size_t i = 0; i < vertex_count; ++i)231if (remap[i] != i)232{233unsigned int r = remap[i];234235wedge[i] = wedge[r];236wedge[r] = unsigned(i);237}238}239240static unsigned int* buildSparseRemap(unsigned int* indices, size_t index_count, size_t vertex_count, size_t* out_vertex_count, meshopt_Allocator& allocator)241{242// use a bit set to compute the precise number of unique vertices243unsigned char* filter = allocator.allocate<unsigned char>((vertex_count + 7) / 8);244memset(filter, 0, (vertex_count + 7) / 8);245246size_t unique = 0;247for (size_t i = 0; i < index_count; ++i)248{249unsigned int index = indices[i];250assert(index < vertex_count);251252unique += (filter[index / 8] & (1 << (index % 8))) == 0;253filter[index / 8] |= 1 << (index % 8);254}255256unsigned int* remap = allocator.allocate<unsigned int>(unique);257size_t offset = 0;258259// temporary map dense => sparse; we allocate it last so that we can deallocate it260size_t revremap_size = hashBuckets2(unique);261unsigned int* revremap = allocator.allocate<unsigned int>(revremap_size);262memset(revremap, -1, revremap_size * sizeof(unsigned int));263264// fill remap, using revremap as a helper, and rewrite indices in the same pass265RemapHasher hasher = {remap};266267for (size_t i = 0; i < index_count; ++i)268{269unsigned int index = indices[i];270271unsigned int* entry = hashLookup2(revremap, revremap_size, hasher, index, ~0u);272273if (*entry == ~0u)274{275remap[offset] = index;276*entry = unsigned(offset);277offset++;278}279280indices[i] = *entry;281}282283allocator.deallocate(revremap);284285assert(offset == unique);286*out_vertex_count = unique;287288return remap;289}290291enum VertexKind292{293Kind_Manifold, // not on an attribute seam, not on any boundary294Kind_Border, // not on an attribute seam, has exactly two open edges295Kind_Seam, // on an attribute seam with exactly two attribute seam edges296Kind_Complex, // none of the above; these vertices can move as long as all wedges move to the target vertex297Kind_Locked, // none of the above; these vertices can't move298299Kind_Count300};301302// manifold vertices can collapse onto anything303// border/seam vertices can collapse onto border/seam respectively, or locked304// complex vertices can collapse onto complex/locked305// a rule of thumb is that collapsing kind A into kind B preserves the kind B in the target vertex306// for example, while we could collapse Complex into Manifold, this would mean the target vertex isn't Manifold anymore307const unsigned char kCanCollapse[Kind_Count][Kind_Count] = {308{1, 1, 1, 1, 1},309{0, 1, 0, 0, 1},310{0, 0, 1, 0, 1},311{0, 0, 0, 1, 1},312{0, 0, 0, 0, 0},313};314315// if a vertex is manifold or seam, adjoining edges are guaranteed to have an opposite edge316// note that for seam edges, the opposite edge isn't present in the attribute-based topology317// but is present if you consider a position-only mesh variant318const unsigned char kHasOpposite[Kind_Count][Kind_Count] = {319{1, 1, 1, 0, 1},320{1, 0, 1, 0, 0},321{1, 1, 1, 0, 1},322{0, 0, 0, 0, 0},323{1, 0, 1, 0, 0},324};325326static bool hasEdge(const EdgeAdjacency& adjacency, unsigned int a, unsigned int b)327{328unsigned int count = adjacency.offsets[a + 1] - adjacency.offsets[a];329const EdgeAdjacency::Edge* edges = adjacency.data + adjacency.offsets[a];330331for (size_t i = 0; i < count; ++i)332if (edges[i].next == b)333return true;334335return false;336}337338static void classifyVertices(unsigned char* result, unsigned int* loop, unsigned int* loopback, size_t vertex_count, const EdgeAdjacency& adjacency, const unsigned int* remap, const unsigned int* wedge, const unsigned char* vertex_lock, const unsigned int* sparse_remap, unsigned int options)339{340memset(loop, -1, vertex_count * sizeof(unsigned int));341memset(loopback, -1, vertex_count * sizeof(unsigned int));342343// incoming & outgoing open edges: ~0u if no open edges, i if there are more than 1344// note that this is the same data as required in loop[] arrays; loop[] data is only valid for border/seam345// but here it's okay to fill the data out for other types of vertices as well346unsigned int* openinc = loopback;347unsigned int* openout = loop;348349for (size_t i = 0; i < vertex_count; ++i)350{351unsigned int vertex = unsigned(i);352353unsigned int count = adjacency.offsets[vertex + 1] - adjacency.offsets[vertex];354const EdgeAdjacency::Edge* edges = adjacency.data + adjacency.offsets[vertex];355356for (size_t j = 0; j < count; ++j)357{358unsigned int target = edges[j].next;359360if (target == vertex)361{362// degenerate triangles have two distinct edges instead of three, and the self edge363// is bi-directional by definition; this can break border/seam classification by "closing"364// the open edge from another triangle and falsely marking the vertex as manifold365// instead we mark the vertex as having >1 open edges which turns it into locked/complex366openinc[vertex] = openout[vertex] = vertex;367}368else if (!hasEdge(adjacency, target, vertex))369{370openinc[target] = (openinc[target] == ~0u) ? vertex : target;371openout[vertex] = (openout[vertex] == ~0u) ? target : vertex;372}373}374}375376#if TRACE377size_t stats[4] = {};378#endif379380for (size_t i = 0; i < vertex_count; ++i)381{382if (remap[i] == i)383{384if (wedge[i] == i)385{386// no attribute seam, need to check if it's manifold387unsigned int openi = openinc[i], openo = openout[i];388389// note: we classify any vertices with no open edges as manifold390// this is technically incorrect - if 4 triangles share an edge, we'll classify vertices as manifold391// it's unclear if this is a problem in practice392if (openi == ~0u && openo == ~0u)393{394result[i] = Kind_Manifold;395}396else if (openi != i && openo != i)397{398result[i] = Kind_Border;399}400else401{402result[i] = Kind_Locked;403TRACESTATS(0);404}405}406else if (wedge[wedge[i]] == i)407{408// attribute seam; need to distinguish between Seam and Locked409unsigned int w = wedge[i];410unsigned int openiv = openinc[i], openov = openout[i];411unsigned int openiw = openinc[w], openow = openout[w];412413// seam should have one open half-edge for each vertex, and the edges need to "connect" - point to the same vertex post-remap414if (openiv != ~0u && openiv != i && openov != ~0u && openov != i &&415openiw != ~0u && openiw != w && openow != ~0u && openow != w)416{417if (remap[openiv] == remap[openow] && remap[openov] == remap[openiw] && remap[openiv] != remap[openov])418{419result[i] = Kind_Seam;420}421else422{423result[i] = Kind_Locked;424TRACESTATS(1);425}426}427else428{429result[i] = Kind_Locked;430TRACESTATS(2);431}432}433else434{435// more than one vertex maps to this one; we don't have classification available436result[i] = Kind_Locked;437TRACESTATS(3);438}439}440else441{442assert(remap[i] < i);443444result[i] = result[remap[i]];445}446}447448if (vertex_lock)449{450// vertex_lock may lock any wedge, not just the primary vertex, so we need to lock the primary vertex and relock any wedges451for (size_t i = 0; i < vertex_count; ++i)452{453unsigned int ri = sparse_remap ? sparse_remap[i] : unsigned(i);454assert(vertex_lock[ri] <= 1); // values other than 0/1 are reserved for future use455456if (vertex_lock[ri])457result[remap[i]] = Kind_Locked;458}459460for (size_t i = 0; i < vertex_count; ++i)461if (result[remap[i]] == Kind_Locked)462result[i] = Kind_Locked;463}464465if (options & meshopt_SimplifyLockBorder)466for (size_t i = 0; i < vertex_count; ++i)467if (result[i] == Kind_Border)468result[i] = Kind_Locked;469470#if TRACE471printf("locked: many open edges %d, disconnected seam %d, many seam edges %d, many wedges %d\n",472int(stats[0]), int(stats[1]), int(stats[2]), int(stats[3]));473#endif474}475476struct Vector3477{478float x, y, z;479};480481static float rescalePositions(Vector3* result, const float* vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride, const unsigned int* sparse_remap = NULL)482{483size_t vertex_stride_float = vertex_positions_stride / sizeof(float);484485float minv[3] = {FLT_MAX, FLT_MAX, FLT_MAX};486float maxv[3] = {-FLT_MAX, -FLT_MAX, -FLT_MAX};487488for (size_t i = 0; i < vertex_count; ++i)489{490unsigned int ri = sparse_remap ? sparse_remap[i] : unsigned(i);491const float* v = vertex_positions_data + ri * vertex_stride_float;492493if (result)494{495result[i].x = v[0];496result[i].y = v[1];497result[i].z = v[2];498}499500for (int j = 0; j < 3; ++j)501{502float vj = v[j];503504minv[j] = minv[j] > vj ? vj : minv[j];505maxv[j] = maxv[j] < vj ? vj : maxv[j];506}507}508509float extent = 0.f;510511extent = (maxv[0] - minv[0]) < extent ? extent : (maxv[0] - minv[0]);512extent = (maxv[1] - minv[1]) < extent ? extent : (maxv[1] - minv[1]);513extent = (maxv[2] - minv[2]) < extent ? extent : (maxv[2] - minv[2]);514515if (result)516{517float scale = extent == 0 ? 0.f : 1.f / extent;518519for (size_t i = 0; i < vertex_count; ++i)520{521result[i].x = (result[i].x - minv[0]) * scale;522result[i].y = (result[i].y - minv[1]) * scale;523result[i].z = (result[i].z - minv[2]) * scale;524}525}526527return extent;528}529530static void rescaleAttributes(float* result, const float* vertex_attributes_data, size_t vertex_count, size_t vertex_attributes_stride, const float* attribute_weights, size_t attribute_count, const unsigned int* attribute_remap, const unsigned int* sparse_remap)531{532size_t vertex_attributes_stride_float = vertex_attributes_stride / sizeof(float);533534for (size_t i = 0; i < vertex_count; ++i)535{536unsigned int ri = sparse_remap ? sparse_remap[i] : unsigned(i);537538for (size_t k = 0; k < attribute_count; ++k)539{540unsigned int rk = attribute_remap[k];541float a = vertex_attributes_data[ri * vertex_attributes_stride_float + rk];542543result[i * attribute_count + k] = a * attribute_weights[rk];544}545}546}547548static const size_t kMaxAttributes = 32;549550struct Quadric551{552// a00*x^2 + a11*y^2 + a22*z^2 + 2*(a10*xy + a20*xz + a21*yz) + b0*x + b1*y + b2*z + c553float a00, a11, a22;554float a10, a20, a21;555float b0, b1, b2, c;556float w;557};558559struct QuadricGrad560{561// gx*x + gy*y + gz*z + gw562float gx, gy, gz, gw;563};564565struct Reservoir566{567float x, y, z;568float r, g, b;569float w;570};571572struct Collapse573{574unsigned int v0;575unsigned int v1;576577union578{579unsigned int bidi;580float error;581unsigned int errorui;582};583};584585static float normalize(Vector3& v)586{587float length = sqrtf(v.x * v.x + v.y * v.y + v.z * v.z);588589if (length > 0)590{591v.x /= length;592v.y /= length;593v.z /= length;594}595596return length;597}598599static void quadricAdd(Quadric& Q, const Quadric& R)600{601Q.a00 += R.a00;602Q.a11 += R.a11;603Q.a22 += R.a22;604Q.a10 += R.a10;605Q.a20 += R.a20;606Q.a21 += R.a21;607Q.b0 += R.b0;608Q.b1 += R.b1;609Q.b2 += R.b2;610Q.c += R.c;611Q.w += R.w;612}613614static void quadricAdd(QuadricGrad* G, const QuadricGrad* R, size_t attribute_count)615{616for (size_t k = 0; k < attribute_count; ++k)617{618G[k].gx += R[k].gx;619G[k].gy += R[k].gy;620G[k].gz += R[k].gz;621G[k].gw += R[k].gw;622}623}624625static float quadricEval(const Quadric& Q, const Vector3& v)626{627float rx = Q.b0;628float ry = Q.b1;629float rz = Q.b2;630631rx += Q.a10 * v.y;632ry += Q.a21 * v.z;633rz += Q.a20 * v.x;634635rx *= 2;636ry *= 2;637rz *= 2;638639rx += Q.a00 * v.x;640ry += Q.a11 * v.y;641rz += Q.a22 * v.z;642643float r = Q.c;644r += rx * v.x;645r += ry * v.y;646r += rz * v.z;647648return r;649}650651static float quadricError(const Quadric& Q, const Vector3& v)652{653float r = quadricEval(Q, v);654float s = Q.w == 0.f ? 0.f : 1.f / Q.w;655656return fabsf(r) * s;657}658659static float quadricError(const Quadric& Q, const QuadricGrad* G, size_t attribute_count, const Vector3& v, const float* va)660{661float r = quadricEval(Q, v);662663// see quadricFromAttributes for general derivation; here we need to add the parts of (eval(pos) - attr)^2 that depend on attr664for (size_t k = 0; k < attribute_count; ++k)665{666float a = va[k];667float g = v.x * G[k].gx + v.y * G[k].gy + v.z * G[k].gz + G[k].gw;668669r += a * (a * Q.w - 2 * g);670}671672// note: unlike position error, we do not normalize by Q.w to retain edge scaling as described in quadricFromAttributes673return fabsf(r);674}675676static void quadricFromPlane(Quadric& Q, float a, float b, float c, float d, float w)677{678float aw = a * w;679float bw = b * w;680float cw = c * w;681float dw = d * w;682683Q.a00 = a * aw;684Q.a11 = b * bw;685Q.a22 = c * cw;686Q.a10 = a * bw;687Q.a20 = a * cw;688Q.a21 = b * cw;689Q.b0 = a * dw;690Q.b1 = b * dw;691Q.b2 = c * dw;692Q.c = d * dw;693Q.w = w;694}695696static void quadricFromTriangle(Quadric& Q, const Vector3& p0, const Vector3& p1, const Vector3& p2, float weight)697{698Vector3 p10 = {p1.x - p0.x, p1.y - p0.y, p1.z - p0.z};699Vector3 p20 = {p2.x - p0.x, p2.y - p0.y, p2.z - p0.z};700701// normal = cross(p1 - p0, p2 - p0)702Vector3 normal = {p10.y * p20.z - p10.z * p20.y, p10.z * p20.x - p10.x * p20.z, p10.x * p20.y - p10.y * p20.x};703float area = normalize(normal);704705float distance = normal.x * p0.x + normal.y * p0.y + normal.z * p0.z;706707// we use sqrtf(area) so that the error is scaled linearly; this tends to improve silhouettes708quadricFromPlane(Q, normal.x, normal.y, normal.z, -distance, sqrtf(area) * weight);709}710711static void quadricFromTriangleEdge(Quadric& Q, const Vector3& p0, const Vector3& p1, const Vector3& p2, float weight)712{713Vector3 p10 = {p1.x - p0.x, p1.y - p0.y, p1.z - p0.z};714715// edge length; keep squared length around for projection correction716float lengthsq = p10.x * p10.x + p10.y * p10.y + p10.z * p10.z;717float length = sqrtf(lengthsq);718719// p20p = length of projection of p2-p0 onto p1-p0; note that p10 is unnormalized so we need to correct it later720Vector3 p20 = {p2.x - p0.x, p2.y - p0.y, p2.z - p0.z};721float p20p = p20.x * p10.x + p20.y * p10.y + p20.z * p10.z;722723// perp = perpendicular vector from p2 to line segment p1-p0724// note: since p10 is unnormalized we need to correct the projection; we scale p20 instead to take advantage of normalize below725Vector3 perp = {p20.x * lengthsq - p10.x * p20p, p20.y * lengthsq - p10.y * p20p, p20.z * lengthsq - p10.z * p20p};726normalize(perp);727728float distance = perp.x * p0.x + perp.y * p0.y + perp.z * p0.z;729730// note: the weight is scaled linearly with edge length; this has to match the triangle weight731quadricFromPlane(Q, perp.x, perp.y, perp.z, -distance, length * weight);732}733734static void quadricFromAttributes(Quadric& Q, QuadricGrad* G, const Vector3& p0, const Vector3& p1, const Vector3& p2, const float* va0, const float* va1, const float* va2, size_t attribute_count)735{736// for each attribute we want to encode the following function into the quadric:737// (eval(pos) - attr)^2738// where eval(pos) interpolates attribute across the triangle like so:739// eval(pos) = pos.x * gx + pos.y * gy + pos.z * gz + gw740// where gx/gy/gz/gw are gradients741Vector3 p10 = {p1.x - p0.x, p1.y - p0.y, p1.z - p0.z};742Vector3 p20 = {p2.x - p0.x, p2.y - p0.y, p2.z - p0.z};743744// normal = cross(p1 - p0, p2 - p0)745Vector3 normal = {p10.y * p20.z - p10.z * p20.y, p10.z * p20.x - p10.x * p20.z, p10.x * p20.y - p10.y * p20.x};746float area = sqrtf(normal.x * normal.x + normal.y * normal.y + normal.z * normal.z) * 0.5f;747748// quadric is weighted with the square of edge length (= area)749// this equalizes the units with the positional error (which, after normalization, is a square of distance)750// as a result, a change in weighted attribute of 1 along distance d is approximately equivalent to a change in position of d751float w = area;752753// we compute gradients using barycentric coordinates; barycentric coordinates can be computed as follows:754// v = (d11 * d20 - d01 * d21) / denom755// w = (d00 * d21 - d01 * d20) / denom756// u = 1 - v - w757// here v0, v1 are triangle edge vectors, v2 is a vector from point to triangle corner, and dij = dot(vi, vj)758// note: v2 and d20/d21 can not be evaluated here as v2 is effectively an unknown variable; we need these only as variables for derivation of gradients759const Vector3& v0 = p10;760const Vector3& v1 = p20;761float d00 = v0.x * v0.x + v0.y * v0.y + v0.z * v0.z;762float d01 = v0.x * v1.x + v0.y * v1.y + v0.z * v1.z;763float d11 = v1.x * v1.x + v1.y * v1.y + v1.z * v1.z;764float denom = d00 * d11 - d01 * d01;765float denomr = denom == 0 ? 0.f : 1.f / denom;766767// precompute gradient factors768// these are derived by directly computing derivative of eval(pos) = a0 * u + a1 * v + a2 * w and factoring out expressions that are shared between attributes769float gx1 = (d11 * v0.x - d01 * v1.x) * denomr;770float gx2 = (d00 * v1.x - d01 * v0.x) * denomr;771float gy1 = (d11 * v0.y - d01 * v1.y) * denomr;772float gy2 = (d00 * v1.y - d01 * v0.y) * denomr;773float gz1 = (d11 * v0.z - d01 * v1.z) * denomr;774float gz2 = (d00 * v1.z - d01 * v0.z) * denomr;775776memset(&Q, 0, sizeof(Quadric));777778Q.w = w;779780for (size_t k = 0; k < attribute_count; ++k)781{782float a0 = va0[k], a1 = va1[k], a2 = va2[k];783784// compute gradient of eval(pos) for x/y/z/w785// the formulas below are obtained by directly computing derivative of eval(pos) = a0 * u + a1 * v + a2 * w786float gx = gx1 * (a1 - a0) + gx2 * (a2 - a0);787float gy = gy1 * (a1 - a0) + gy2 * (a2 - a0);788float gz = gz1 * (a1 - a0) + gz2 * (a2 - a0);789float gw = a0 - p0.x * gx - p0.y * gy - p0.z * gz;790791// quadric encodes (eval(pos)-attr)^2; this means that the resulting expansion needs to compute, for example, pos.x * pos.y * K792// since quadrics already encode factors for pos.x * pos.y, we can accumulate almost everything in basic quadric fields793// note: for simplicity we scale all factors by weight here instead of outside the loop794Q.a00 += w * (gx * gx);795Q.a11 += w * (gy * gy);796Q.a22 += w * (gz * gz);797798Q.a10 += w * (gy * gx);799Q.a20 += w * (gz * gx);800Q.a21 += w * (gz * gy);801802Q.b0 += w * (gx * gw);803Q.b1 += w * (gy * gw);804Q.b2 += w * (gz * gw);805806Q.c += w * (gw * gw);807808// the only remaining sum components are ones that depend on attr; these will be addded during error evaluation, see quadricError809G[k].gx = w * gx;810G[k].gy = w * gy;811G[k].gz = w * gz;812G[k].gw = w * gw;813}814}815816static void fillFaceQuadrics(Quadric* vertex_quadrics, const unsigned int* indices, size_t index_count, const Vector3* vertex_positions, const unsigned int* remap)817{818for (size_t i = 0; i < index_count; i += 3)819{820unsigned int i0 = indices[i + 0];821unsigned int i1 = indices[i + 1];822unsigned int i2 = indices[i + 2];823824Quadric Q;825quadricFromTriangle(Q, vertex_positions[i0], vertex_positions[i1], vertex_positions[i2], 1.f);826827quadricAdd(vertex_quadrics[remap[i0]], Q);828quadricAdd(vertex_quadrics[remap[i1]], Q);829quadricAdd(vertex_quadrics[remap[i2]], Q);830}831}832833static void fillEdgeQuadrics(Quadric* vertex_quadrics, const unsigned int* indices, size_t index_count, const Vector3* vertex_positions, const unsigned int* remap, const unsigned char* vertex_kind, const unsigned int* loop, const unsigned int* loopback)834{835for (size_t i = 0; i < index_count; i += 3)836{837static const int next[4] = {1, 2, 0, 1};838839for (int e = 0; e < 3; ++e)840{841unsigned int i0 = indices[i + e];842unsigned int i1 = indices[i + next[e]];843844unsigned char k0 = vertex_kind[i0];845unsigned char k1 = vertex_kind[i1];846847// check that either i0 or i1 are border/seam and are on the same edge loop848// note that we need to add the error even for edged that connect e.g. border & locked849// if we don't do that, the adjacent border->border edge won't have correct errors for corners850if (k0 != Kind_Border && k0 != Kind_Seam && k1 != Kind_Border && k1 != Kind_Seam)851continue;852853if ((k0 == Kind_Border || k0 == Kind_Seam) && loop[i0] != i1)854continue;855856if ((k1 == Kind_Border || k1 == Kind_Seam) && loopback[i1] != i0)857continue;858859// seam edges should occur twice (i0->i1 and i1->i0) - skip redundant edges860if (kHasOpposite[k0][k1] && remap[i1] > remap[i0])861continue;862863unsigned int i2 = indices[i + next[e + 1]];864865// we try hard to maintain border edge geometry; seam edges can move more freely866// due to topological restrictions on collapses, seam quadrics slightly improves collapse structure but aren't critical867const float kEdgeWeightSeam = 1.f;868const float kEdgeWeightBorder = 10.f;869870float edgeWeight = (k0 == Kind_Border || k1 == Kind_Border) ? kEdgeWeightBorder : kEdgeWeightSeam;871872Quadric Q;873quadricFromTriangleEdge(Q, vertex_positions[i0], vertex_positions[i1], vertex_positions[i2], edgeWeight);874875quadricAdd(vertex_quadrics[remap[i0]], Q);876quadricAdd(vertex_quadrics[remap[i1]], Q);877}878}879}880881static void fillAttributeQuadrics(Quadric* attribute_quadrics, QuadricGrad* attribute_gradients, const unsigned int* indices, size_t index_count, const Vector3* vertex_positions, const float* vertex_attributes, size_t attribute_count)882{883for (size_t i = 0; i < index_count; i += 3)884{885unsigned int i0 = indices[i + 0];886unsigned int i1 = indices[i + 1];887unsigned int i2 = indices[i + 2];888889Quadric QA;890QuadricGrad G[kMaxAttributes];891quadricFromAttributes(QA, G, vertex_positions[i0], vertex_positions[i1], vertex_positions[i2], &vertex_attributes[i0 * attribute_count], &vertex_attributes[i1 * attribute_count], &vertex_attributes[i2 * attribute_count], attribute_count);892893quadricAdd(attribute_quadrics[i0], QA);894quadricAdd(attribute_quadrics[i1], QA);895quadricAdd(attribute_quadrics[i2], QA);896897quadricAdd(&attribute_gradients[i0 * attribute_count], G, attribute_count);898quadricAdd(&attribute_gradients[i1 * attribute_count], G, attribute_count);899quadricAdd(&attribute_gradients[i2 * attribute_count], G, attribute_count);900}901}902903// does triangle ABC flip when C is replaced with D?904static bool hasTriangleFlip(const Vector3& a, const Vector3& b, const Vector3& c, const Vector3& d)905{906Vector3 eb = {b.x - a.x, b.y - a.y, b.z - a.z};907Vector3 ec = {c.x - a.x, c.y - a.y, c.z - a.z};908Vector3 ed = {d.x - a.x, d.y - a.y, d.z - a.z};909910Vector3 nbc = {eb.y * ec.z - eb.z * ec.y, eb.z * ec.x - eb.x * ec.z, eb.x * ec.y - eb.y * ec.x};911Vector3 nbd = {eb.y * ed.z - eb.z * ed.y, eb.z * ed.x - eb.x * ed.z, eb.x * ed.y - eb.y * ed.x};912913float ndp = nbc.x * nbd.x + nbc.y * nbd.y + nbc.z * nbd.z;914float abc = nbc.x * nbc.x + nbc.y * nbc.y + nbc.z * nbc.z;915float abd = nbd.x * nbd.x + nbd.y * nbd.y + nbd.z * nbd.z;916917// scale is cos(angle); somewhat arbitrarily set to ~75 degrees918// note that the "pure" check is ndp <= 0 (90 degree cutoff) but that allows flipping through a series of close-to-90 collapses919return ndp <= 0.25f * sqrtf(abc * abd);920}921922static bool hasTriangleFlips(const EdgeAdjacency& adjacency, const Vector3* vertex_positions, const unsigned int* collapse_remap, unsigned int i0, unsigned int i1)923{924assert(collapse_remap[i0] == i0);925assert(collapse_remap[i1] == i1);926927const Vector3& v0 = vertex_positions[i0];928const Vector3& v1 = vertex_positions[i1];929930const EdgeAdjacency::Edge* edges = &adjacency.data[adjacency.offsets[i0]];931size_t count = adjacency.offsets[i0 + 1] - adjacency.offsets[i0];932933for (size_t i = 0; i < count; ++i)934{935unsigned int a = collapse_remap[edges[i].next];936unsigned int b = collapse_remap[edges[i].prev];937938// skip triangles that will get collapsed by i0->i1 collapse or already got collapsed previously939if (a == i1 || b == i1 || a == b)940continue;941942// early-out when at least one triangle flips due to a collapse943if (hasTriangleFlip(vertex_positions[a], vertex_positions[b], v0, v1))944{945#if TRACE >= 2946printf("edge block %d -> %d: flip welded %d %d %d\n", i0, i1, a, i0, b);947#endif948949return true;950}951}952953return false;954}955956static size_t boundEdgeCollapses(const EdgeAdjacency& adjacency, size_t vertex_count, size_t index_count, unsigned char* vertex_kind)957{958size_t dual_count = 0;959960for (size_t i = 0; i < vertex_count; ++i)961{962unsigned char k = vertex_kind[i];963unsigned int e = adjacency.offsets[i + 1] - adjacency.offsets[i];964965dual_count += (k == Kind_Manifold || k == Kind_Seam) ? e : 0;966}967968assert(dual_count <= index_count);969970// pad capacity by 3 so that we can check for overflow once per triangle instead of once per edge971return (index_count - dual_count / 2) + 3;972}973974static size_t pickEdgeCollapses(Collapse* collapses, size_t collapse_capacity, const unsigned int* indices, size_t index_count, const unsigned int* remap, const unsigned char* vertex_kind, const unsigned int* loop, const unsigned int* loopback)975{976size_t collapse_count = 0;977978for (size_t i = 0; i < index_count; i += 3)979{980static const int next[3] = {1, 2, 0};981982// this should never happen as boundEdgeCollapses should give an upper bound for the collapse count, but in an unlikely event it does we can just drop extra collapses983if (collapse_count + 3 > collapse_capacity)984break;985986for (int e = 0; e < 3; ++e)987{988unsigned int i0 = indices[i + e];989unsigned int i1 = indices[i + next[e]];990991// this can happen either when input has a zero-length edge, or when we perform collapses for complex992// topology w/seams and collapse a manifold vertex that connects to both wedges onto one of them993// we leave edges like this alone since they may be important for preserving mesh integrity994if (remap[i0] == remap[i1])995continue;996997unsigned char k0 = vertex_kind[i0];998unsigned char k1 = vertex_kind[i1];9991000// the edge has to be collapsible in at least one direction1001if (!(kCanCollapse[k0][k1] | kCanCollapse[k1][k0]))1002continue;10031004// manifold and seam edges should occur twice (i0->i1 and i1->i0) - skip redundant edges1005if (kHasOpposite[k0][k1] && remap[i1] > remap[i0])1006continue;10071008// two vertices are on a border or a seam, but there's no direct edge between them1009// this indicates that they belong to two different edge loops and we should not collapse this edge1010// loop[] tracks half edges so we only need to check i0->i11011if (k0 == k1 && (k0 == Kind_Border || k0 == Kind_Seam) && loop[i0] != i1)1012continue;10131014if (k0 == Kind_Locked || k1 == Kind_Locked)1015{1016// the same check as above, but for border/seam -> locked collapses1017// loop[] and loopback[] track half edges so we only need to check one of them1018if ((k0 == Kind_Border || k0 == Kind_Seam) && loop[i0] != i1)1019continue;1020if ((k1 == Kind_Border || k1 == Kind_Seam) && loopback[i1] != i0)1021continue;1022}10231024// edge can be collapsed in either direction - we will pick the one with minimum error1025// note: we evaluate error later during collapse ranking, here we just tag the edge as bidirectional1026if (kCanCollapse[k0][k1] & kCanCollapse[k1][k0])1027{1028Collapse c = {i0, i1, {/* bidi= */ 1}};1029collapses[collapse_count++] = c;1030}1031else1032{1033// edge can only be collapsed in one direction1034unsigned int e0 = kCanCollapse[k0][k1] ? i0 : i1;1035unsigned int e1 = kCanCollapse[k0][k1] ? i1 : i0;10361037Collapse c = {e0, e1, {/* bidi= */ 0}};1038collapses[collapse_count++] = c;1039}1040}1041}10421043return collapse_count;1044}10451046static void rankEdgeCollapses(Collapse* collapses, size_t collapse_count, const Vector3* vertex_positions, const float* vertex_attributes, const Quadric* vertex_quadrics, const Quadric* attribute_quadrics, const QuadricGrad* attribute_gradients, size_t attribute_count, const unsigned int* remap, const unsigned int* wedge, const unsigned char* vertex_kind, const unsigned int* loop, const unsigned int* loopback)1047{1048for (size_t i = 0; i < collapse_count; ++i)1049{1050Collapse& c = collapses[i];10511052unsigned int i0 = c.v0;1053unsigned int i1 = c.v1;10541055// most edges are bidirectional which means we need to evaluate errors for two collapses1056// to keep this code branchless we just use the same edge for unidirectional edges1057unsigned int j0 = c.bidi ? i1 : i0;1058unsigned int j1 = c.bidi ? i0 : i1;10591060float ei = quadricError(vertex_quadrics[remap[i0]], vertex_positions[i1]);1061float ej = c.bidi ? quadricError(vertex_quadrics[remap[j0]], vertex_positions[j1]) : FLT_MAX;10621063#if TRACE >= 31064float di = ei, dj = ej;1065#endif10661067if (attribute_count)1068{1069ei += quadricError(attribute_quadrics[i0], &attribute_gradients[i0 * attribute_count], attribute_count, vertex_positions[i1], &vertex_attributes[i1 * attribute_count]);1070ej += c.bidi ? quadricError(attribute_quadrics[j0], &attribute_gradients[j0 * attribute_count], attribute_count, vertex_positions[j1], &vertex_attributes[j1 * attribute_count]) : 0;10711072// note: seam edges need to aggregate attribute errors between primary and secondary edges, as attribute quadrics are separate1073if (vertex_kind[i0] == Kind_Seam)1074{1075// for seam collapses we need to find the seam pair; this is a bit tricky since we need to rely on edge loops as target vertex may be locked (and thus have more than two wedges)1076unsigned int s0 = wedge[i0];1077unsigned int s1 = loop[i0] == i1 ? loopback[s0] : loop[s0];10781079assert(s0 != i0 && wedge[s0] == i0);1080assert(s1 != ~0u && remap[s1] == remap[i1]);10811082// note: this should never happen due to the assertion above, but when disabled if we ever hit this case we'll get a memory safety issue; for now play it safe1083s1 = (s1 != ~0u) ? s1 : wedge[i1];10841085ei += quadricError(attribute_quadrics[s0], &attribute_gradients[s0 * attribute_count], attribute_count, vertex_positions[s1], &vertex_attributes[s1 * attribute_count]);1086ej += c.bidi ? quadricError(attribute_quadrics[s1], &attribute_gradients[s1 * attribute_count], attribute_count, vertex_positions[s0], &vertex_attributes[s0 * attribute_count]) : 0;1087}1088}10891090// pick edge direction with minimal error1091c.v0 = ei <= ej ? i0 : j0;1092c.v1 = ei <= ej ? i1 : j1;1093c.error = ei <= ej ? ei : ej;10941095#if TRACE >= 31096if (i0 == j0) // c.bidi has been overwritten1097printf("edge eval %d -> %d: error %f (pos %f, attr %f)\n", c.v0, c.v1,1098sqrtf(c.error), sqrtf(ei <= ej ? di : dj), sqrtf(ei <= ej ? ei - di : ej - dj));1099else1100printf("edge eval %d -> %d: error %f (pos %f, attr %f); reverse %f (pos %f, attr %f)\n", c.v0, c.v1,1101sqrtf(ei <= ej ? ei : ej), sqrtf(ei <= ej ? di : dj), sqrtf(ei <= ej ? ei - di : ej - dj),1102sqrtf(ei <= ej ? ej : ei), sqrtf(ei <= ej ? dj : di), sqrtf(ei <= ej ? ej - dj : ei - di));1103#endif1104}1105}11061107static void sortEdgeCollapses(unsigned int* sort_order, const Collapse* collapses, size_t collapse_count)1108{1109// we use counting sort to order collapses by error; since the exact sort order is not as critical,1110// only top 12 bits of exponent+mantissa (8 bits of exponent and 4 bits of mantissa) are used.1111// to avoid excessive stack usage, we clamp the exponent range as collapses with errors much higher than 1 are not useful.1112const unsigned int sort_bits = 12;1113const unsigned int sort_bins = 2048 + 512; // exponent range [-127, 32)11141115// fill histogram for counting sort1116unsigned int histogram[sort_bins];1117memset(histogram, 0, sizeof(histogram));11181119for (size_t i = 0; i < collapse_count; ++i)1120{1121// skip sign bit since error is non-negative1122unsigned int error = collapses[i].errorui;1123unsigned int key = (error << 1) >> (32 - sort_bits);1124key = key < sort_bins ? key : sort_bins - 1;11251126histogram[key]++;1127}11281129// compute offsets based on histogram data1130size_t histogram_sum = 0;11311132for (size_t i = 0; i < sort_bins; ++i)1133{1134size_t count = histogram[i];1135histogram[i] = unsigned(histogram_sum);1136histogram_sum += count;1137}11381139assert(histogram_sum == collapse_count);11401141// compute sort order based on offsets1142for (size_t i = 0; i < collapse_count; ++i)1143{1144// skip sign bit since error is non-negative1145unsigned int error = collapses[i].errorui;1146unsigned int key = (error << 1) >> (32 - sort_bits);1147key = key < sort_bins ? key : sort_bins - 1;11481149sort_order[histogram[key]++] = unsigned(i);1150}1151}11521153static size_t performEdgeCollapses(unsigned int* collapse_remap, unsigned char* collapse_locked, const Collapse* collapses, size_t collapse_count, const unsigned int* collapse_order, const unsigned int* remap, const unsigned int* wedge, const unsigned char* vertex_kind, const unsigned int* loop, const unsigned int* loopback, const Vector3* vertex_positions, const EdgeAdjacency& adjacency, size_t triangle_collapse_goal, float error_limit, float& result_error)1154{1155size_t edge_collapses = 0;1156size_t triangle_collapses = 0;11571158// most collapses remove 2 triangles; use this to establish a bound on the pass in terms of error limit1159// note that edge_collapse_goal is an estimate; triangle_collapse_goal will be used to actually limit collapses1160size_t edge_collapse_goal = triangle_collapse_goal / 2;11611162#if TRACE1163size_t stats[7] = {};1164#endif11651166for (size_t i = 0; i < collapse_count; ++i)1167{1168const Collapse& c = collapses[collapse_order[i]];11691170TRACESTATS(0);11711172if (c.error > error_limit)1173{1174TRACESTATS(4);1175break;1176}11771178if (triangle_collapses >= triangle_collapse_goal)1179{1180TRACESTATS(5);1181break;1182}11831184// we limit the error in each pass based on the error of optimal last collapse; since many collapses will be locked1185// as they will share vertices with other successfull collapses, we need to increase the acceptable error by some factor1186float error_goal = edge_collapse_goal < collapse_count ? 1.5f * collapses[collapse_order[edge_collapse_goal]].error : FLT_MAX;11871188// on average, each collapse is expected to lock 6 other collapses; to avoid degenerate passes on meshes with odd1189// topology, we only abort if we got over 1/6 collapses accordingly.1190if (c.error > error_goal && c.error > result_error && triangle_collapses > triangle_collapse_goal / 6)1191{1192TRACESTATS(6);1193break;1194}11951196unsigned int i0 = c.v0;1197unsigned int i1 = c.v1;11981199unsigned int r0 = remap[i0];1200unsigned int r1 = remap[i1];12011202unsigned char kind = vertex_kind[i0];12031204// we don't collapse vertices that had source or target vertex involved in a collapse1205// it's important to not move the vertices twice since it complicates the tracking/remapping logic1206// it's important to not move other vertices towards a moved vertex to preserve error since we don't re-rank collapses mid-pass1207if (collapse_locked[r0] | collapse_locked[r1])1208{1209TRACESTATS(1);1210continue;1211}12121213if (hasTriangleFlips(adjacency, vertex_positions, collapse_remap, r0, r1))1214{1215// adjust collapse goal since this collapse is invalid and shouldn't factor into error goal1216edge_collapse_goal++;12171218TRACESTATS(2);1219continue;1220}12211222#if TRACE >= 21223printf("edge commit %d -> %d: kind %d->%d, error %f\n", i0, i1, vertex_kind[i0], vertex_kind[i1], sqrtf(c.error));1224#endif12251226assert(collapse_remap[r0] == r0);1227assert(collapse_remap[r1] == r1);12281229if (kind == Kind_Complex)1230{1231// remap all vertices in the complex to the target vertex1232unsigned int v = i0;12331234do1235{1236collapse_remap[v] = i1;1237v = wedge[v];1238} while (v != i0);1239}1240else if (kind == Kind_Seam)1241{1242// for seam collapses we need to move the seam pair together; this is a bit tricky since we need to rely on edge loops as target vertex may be locked (and thus have more than two wedges)1243unsigned int s0 = wedge[i0];1244unsigned int s1 = loop[i0] == i1 ? loopback[s0] : loop[s0];1245assert(s0 != i0 && wedge[s0] == i0);1246assert(s1 != ~0u && remap[s1] == r1);12471248// additional asserts to verify that the seam pair is consistent1249assert(kind != vertex_kind[i1] || s1 == wedge[i1]);1250assert(loop[i0] == i1 || loopback[i0] == i1);1251assert(loop[s0] == s1 || loopback[s0] == s1);12521253// note: this should never happen due to the assertion above, but when disabled if we ever hit this case we'll get a memory safety issue; for now play it safe1254s1 = (s1 != ~0u) ? s1 : wedge[i1];12551256collapse_remap[i0] = i1;1257collapse_remap[s0] = s1;1258}1259else1260{1261assert(wedge[i0] == i0);12621263collapse_remap[i0] = i1;1264}12651266// note: we technically don't need to lock r1 if it's a locked vertex, as it can't move and its quadric won't be used1267// however, this results in slightly worse error on some meshes because the locked collapses get an unfair advantage wrt scheduling1268collapse_locked[r0] = 1;1269collapse_locked[r1] = 1;12701271// border edges collapse 1 triangle, other edges collapse 2 or more1272triangle_collapses += (kind == Kind_Border) ? 1 : 2;1273edge_collapses++;12741275result_error = result_error < c.error ? c.error : result_error;1276}12771278#if TRACE1279float error_goal_last = edge_collapse_goal < collapse_count ? 1.5f * collapses[collapse_order[edge_collapse_goal]].error : FLT_MAX;1280float error_goal_limit = error_goal_last < error_limit ? error_goal_last : error_limit;12811282printf("removed %d triangles, error %e (goal %e); evaluated %d/%d collapses (done %d, skipped %d, invalid %d); %s\n",1283int(triangle_collapses), sqrtf(result_error), sqrtf(error_goal_limit),1284int(stats[0]), int(collapse_count), int(edge_collapses), int(stats[1]), int(stats[2]),1285stats[4] ? "error limit" : (stats[5] ? "count limit" : (stats[6] ? "error goal" : "out of collapses")));1286#endif12871288return edge_collapses;1289}12901291static void updateQuadrics(const unsigned int* collapse_remap, size_t vertex_count, Quadric* vertex_quadrics, Quadric* attribute_quadrics, QuadricGrad* attribute_gradients, size_t attribute_count, const Vector3* vertex_positions, const unsigned int* remap, float& vertex_error)1292{1293for (size_t i = 0; i < vertex_count; ++i)1294{1295if (collapse_remap[i] == i)1296continue;12971298unsigned int i0 = unsigned(i);1299unsigned int i1 = collapse_remap[i];13001301unsigned int r0 = remap[i0];1302unsigned int r1 = remap[i1];13031304// ensure we only update vertex_quadrics once: primary vertex must be moved if any wedge is moved1305if (i0 == r0)1306quadricAdd(vertex_quadrics[r1], vertex_quadrics[r0]);13071308if (attribute_count)1309{1310quadricAdd(attribute_quadrics[i1], attribute_quadrics[i0]);1311quadricAdd(&attribute_gradients[i1 * attribute_count], &attribute_gradients[i0 * attribute_count], attribute_count);13121313if (i0 == r0)1314{1315// when attributes are used, distance error needs to be recomputed as collapses don't track it; it is safe to do this after the quadric adjustment1316float derr = quadricError(vertex_quadrics[r0], vertex_positions[r1]);1317vertex_error = vertex_error < derr ? derr : vertex_error;1318}1319}1320}1321}13221323static size_t remapIndexBuffer(unsigned int* indices, size_t index_count, const unsigned int* collapse_remap)1324{1325size_t write = 0;13261327for (size_t i = 0; i < index_count; i += 3)1328{1329unsigned int v0 = collapse_remap[indices[i + 0]];1330unsigned int v1 = collapse_remap[indices[i + 1]];1331unsigned int v2 = collapse_remap[indices[i + 2]];13321333// we never move the vertex twice during a single pass1334assert(collapse_remap[v0] == v0);1335assert(collapse_remap[v1] == v1);1336assert(collapse_remap[v2] == v2);13371338if (v0 != v1 && v0 != v2 && v1 != v2)1339{1340indices[write + 0] = v0;1341indices[write + 1] = v1;1342indices[write + 2] = v2;1343write += 3;1344}1345}13461347return write;1348}13491350static void remapEdgeLoops(unsigned int* loop, size_t vertex_count, const unsigned int* collapse_remap)1351{1352for (size_t i = 0; i < vertex_count; ++i)1353{1354// note: this is a no-op for vertices that were remapped1355// ideally we would clear the loop entries for those for consistency, even though they aren't going to be used1356// however, the remapping process needs loop information for remapped vertices, so this would require a separate pass1357if (loop[i] != ~0u)1358{1359unsigned int l = loop[i];1360unsigned int r = collapse_remap[l];13611362// i == r is a special case when the seam edge is collapsed in a direction opposite to where loop goes1363if (i == r)1364loop[i] = (loop[l] != ~0u) ? collapse_remap[loop[l]] : ~0u;1365else1366loop[i] = r;1367}1368}1369}13701371static unsigned int follow(unsigned int* parents, unsigned int index)1372{1373while (index != parents[index])1374{1375unsigned int parent = parents[index];1376parents[index] = parents[parent];1377index = parent;1378}13791380return index;1381}13821383static size_t buildComponents(unsigned int* components, size_t vertex_count, const unsigned int* indices, size_t index_count, const unsigned int* remap)1384{1385for (size_t i = 0; i < vertex_count; ++i)1386components[i] = unsigned(i);13871388// compute a unique (but not sequential!) index for each component via union-find1389for (size_t i = 0; i < index_count; i += 3)1390{1391static const int next[4] = {1, 2, 0, 1};13921393for (int e = 0; e < 3; ++e)1394{1395unsigned int i0 = indices[i + e];1396unsigned int i1 = indices[i + next[e]];13971398unsigned int r0 = remap[i0];1399unsigned int r1 = remap[i1];14001401r0 = follow(components, r0);1402r1 = follow(components, r1);14031404// merge components with larger indices into components with smaller indices1405// this guarantees that the root of the component is always the one with the smallest index1406if (r0 != r1)1407components[r0 < r1 ? r1 : r0] = r0 < r1 ? r0 : r1;1408}1409}14101411// make sure each element points to the component root *before* we renumber the components1412for (size_t i = 0; i < vertex_count; ++i)1413if (remap[i] == i)1414components[i] = follow(components, unsigned(i));14151416unsigned int next_component = 0;14171418// renumber components using sequential indices1419// a sequential pass is sufficient because component root always has the smallest index1420// note: it is unsafe to use follow() in this pass because we're replacing component links with sequential indices inplace1421for (size_t i = 0; i < vertex_count; ++i)1422{1423if (remap[i] == i)1424{1425unsigned int root = components[i];1426assert(root <= i); // make sure we already computed the component for non-roots1427components[i] = (root == i) ? next_component++ : components[root];1428}1429else1430{1431assert(remap[i] < i); // make sure we already computed the component1432components[i] = components[remap[i]];1433}1434}14351436return next_component;1437}14381439static void measureComponents(float* component_errors, size_t component_count, const unsigned int* components, const Vector3* vertex_positions, size_t vertex_count)1440{1441memset(component_errors, 0, component_count * 4 * sizeof(float));14421443// compute approximate sphere center for each component as an average1444for (size_t i = 0; i < vertex_count; ++i)1445{1446unsigned int c = components[i];1447assert(components[i] < component_count);14481449Vector3 v = vertex_positions[i]; // copy avoids aliasing issues14501451component_errors[c * 4 + 0] += v.x;1452component_errors[c * 4 + 1] += v.y;1453component_errors[c * 4 + 2] += v.z;1454component_errors[c * 4 + 3] += 1; // weight1455}14561457// complete the center computation, and reinitialize [3] as a radius1458for (size_t i = 0; i < component_count; ++i)1459{1460float w = component_errors[i * 4 + 3];1461float iw = w == 0.f ? 0.f : 1.f / w;14621463component_errors[i * 4 + 0] *= iw;1464component_errors[i * 4 + 1] *= iw;1465component_errors[i * 4 + 2] *= iw;1466component_errors[i * 4 + 3] = 0; // radius1467}14681469// compute squared radius for each component1470for (size_t i = 0; i < vertex_count; ++i)1471{1472unsigned int c = components[i];14731474float dx = vertex_positions[i].x - component_errors[c * 4 + 0];1475float dy = vertex_positions[i].y - component_errors[c * 4 + 1];1476float dz = vertex_positions[i].z - component_errors[c * 4 + 2];1477float r = dx * dx + dy * dy + dz * dz;14781479component_errors[c * 4 + 3] = component_errors[c * 4 + 3] < r ? r : component_errors[c * 4 + 3];1480}14811482// we've used the output buffer as scratch space, so we need to move the results to proper indices1483for (size_t i = 0; i < component_count; ++i)1484{1485#if TRACE >= 21486printf("component %d: center %f %f %f, error %e\n", int(i),1487component_errors[i * 4 + 0], component_errors[i * 4 + 1], component_errors[i * 4 + 2], sqrtf(component_errors[i * 4 + 3]));1488#endif1489// note: we keep the squared error to make it match quadric error metric1490component_errors[i] = component_errors[i * 4 + 3];1491}1492}14931494static size_t pruneComponents(unsigned int* indices, size_t index_count, const unsigned int* components, const float* component_errors, size_t component_count, float error_cutoff, float& nexterror)1495{1496size_t write = 0;14971498for (size_t i = 0; i < index_count; i += 3)1499{1500unsigned int c = components[indices[i]];1501assert(c == components[indices[i + 1]] && c == components[indices[i + 2]]);15021503if (component_errors[c] > error_cutoff)1504{1505indices[write + 0] = indices[i + 0];1506indices[write + 1] = indices[i + 1];1507indices[write + 2] = indices[i + 2];1508write += 3;1509}1510}15111512#if TRACE1513size_t pruned_components = 0;1514for (size_t i = 0; i < component_count; ++i)1515pruned_components += (component_errors[i] >= nexterror && component_errors[i] <= error_cutoff);15161517printf("pruned %d triangles in %d components (goal %e)\n", int((index_count - write) / 3), int(pruned_components), sqrtf(error_cutoff));1518#endif15191520// update next error with the smallest error of the remaining components for future pruning1521nexterror = FLT_MAX;1522for (size_t i = 0; i < component_count; ++i)1523if (component_errors[i] > error_cutoff)1524nexterror = nexterror > component_errors[i] ? component_errors[i] : nexterror;15251526return write;1527}15281529struct CellHasher1530{1531const unsigned int* vertex_ids;15321533size_t hash(unsigned int i) const1534{1535unsigned int h = vertex_ids[i];15361537// MurmurHash2 finalizer1538h ^= h >> 13;1539h *= 0x5bd1e995;1540h ^= h >> 15;1541return h;1542}15431544bool equal(unsigned int lhs, unsigned int rhs) const1545{1546return vertex_ids[lhs] == vertex_ids[rhs];1547}1548};15491550struct IdHasher1551{1552size_t hash(unsigned int id) const1553{1554unsigned int h = id;15551556// MurmurHash2 finalizer1557h ^= h >> 13;1558h *= 0x5bd1e995;1559h ^= h >> 15;1560return h;1561}15621563bool equal(unsigned int lhs, unsigned int rhs) const1564{1565return lhs == rhs;1566}1567};15681569struct TriangleHasher1570{1571const unsigned int* indices;15721573size_t hash(unsigned int i) const1574{1575const unsigned int* tri = indices + i * 3;15761577// Optimized Spatial Hashing for Collision Detection of Deformable Objects1578return (tri[0] * 73856093) ^ (tri[1] * 19349663) ^ (tri[2] * 83492791);1579}15801581bool equal(unsigned int lhs, unsigned int rhs) const1582{1583const unsigned int* lt = indices + lhs * 3;1584const unsigned int* rt = indices + rhs * 3;15851586return lt[0] == rt[0] && lt[1] == rt[1] && lt[2] == rt[2];1587}1588};15891590static void computeVertexIds(unsigned int* vertex_ids, const Vector3* vertex_positions, size_t vertex_count, int grid_size)1591{1592assert(grid_size >= 1 && grid_size <= 1024);1593float cell_scale = float(grid_size - 1);15941595for (size_t i = 0; i < vertex_count; ++i)1596{1597const Vector3& v = vertex_positions[i];15981599int xi = int(v.x * cell_scale + 0.5f);1600int yi = int(v.y * cell_scale + 0.5f);1601int zi = int(v.z * cell_scale + 0.5f);16021603vertex_ids[i] = (xi << 20) | (yi << 10) | zi;1604}1605}16061607static size_t countTriangles(const unsigned int* vertex_ids, const unsigned int* indices, size_t index_count)1608{1609size_t result = 0;16101611for (size_t i = 0; i < index_count; i += 3)1612{1613unsigned int id0 = vertex_ids[indices[i + 0]];1614unsigned int id1 = vertex_ids[indices[i + 1]];1615unsigned int id2 = vertex_ids[indices[i + 2]];16161617result += (id0 != id1) & (id0 != id2) & (id1 != id2);1618}16191620return result;1621}16221623static size_t fillVertexCells(unsigned int* table, size_t table_size, unsigned int* vertex_cells, const unsigned int* vertex_ids, size_t vertex_count)1624{1625CellHasher hasher = {vertex_ids};16261627memset(table, -1, table_size * sizeof(unsigned int));16281629size_t result = 0;16301631for (size_t i = 0; i < vertex_count; ++i)1632{1633unsigned int* entry = hashLookup2(table, table_size, hasher, unsigned(i), ~0u);16341635if (*entry == ~0u)1636{1637*entry = unsigned(i);1638vertex_cells[i] = unsigned(result++);1639}1640else1641{1642vertex_cells[i] = vertex_cells[*entry];1643}1644}16451646return result;1647}16481649static size_t countVertexCells(unsigned int* table, size_t table_size, const unsigned int* vertex_ids, size_t vertex_count)1650{1651IdHasher hasher;16521653memset(table, -1, table_size * sizeof(unsigned int));16541655size_t result = 0;16561657for (size_t i = 0; i < vertex_count; ++i)1658{1659unsigned int id = vertex_ids[i];1660unsigned int* entry = hashLookup2(table, table_size, hasher, id, ~0u);16611662result += (*entry == ~0u);1663*entry = id;1664}16651666return result;1667}16681669static void fillCellQuadrics(Quadric* cell_quadrics, const unsigned int* indices, size_t index_count, const Vector3* vertex_positions, const unsigned int* vertex_cells)1670{1671for (size_t i = 0; i < index_count; i += 3)1672{1673unsigned int i0 = indices[i + 0];1674unsigned int i1 = indices[i + 1];1675unsigned int i2 = indices[i + 2];16761677unsigned int c0 = vertex_cells[i0];1678unsigned int c1 = vertex_cells[i1];1679unsigned int c2 = vertex_cells[i2];16801681int single_cell = (c0 == c1) & (c0 == c2);16821683Quadric Q;1684quadricFromTriangle(Q, vertex_positions[i0], vertex_positions[i1], vertex_positions[i2], single_cell ? 3.f : 1.f);16851686if (single_cell)1687{1688quadricAdd(cell_quadrics[c0], Q);1689}1690else1691{1692quadricAdd(cell_quadrics[c0], Q);1693quadricAdd(cell_quadrics[c1], Q);1694quadricAdd(cell_quadrics[c2], Q);1695}1696}1697}16981699static void fillCellReservoirs(Reservoir* cell_reservoirs, size_t cell_count, const Vector3* vertex_positions, const float* vertex_colors, size_t vertex_colors_stride, size_t vertex_count, const unsigned int* vertex_cells)1700{1701static const float dummy_color[] = {0.f, 0.f, 0.f};17021703size_t vertex_colors_stride_float = vertex_colors_stride / sizeof(float);17041705for (size_t i = 0; i < vertex_count; ++i)1706{1707unsigned int cell = vertex_cells[i];1708const Vector3& v = vertex_positions[i];1709Reservoir& r = cell_reservoirs[cell];17101711const float* color = vertex_colors ? &vertex_colors[i * vertex_colors_stride_float] : dummy_color;17121713r.x += v.x;1714r.y += v.y;1715r.z += v.z;1716r.r += color[0];1717r.g += color[1];1718r.b += color[2];1719r.w += 1.f;1720}17211722for (size_t i = 0; i < cell_count; ++i)1723{1724Reservoir& r = cell_reservoirs[i];17251726float iw = r.w == 0.f ? 0.f : 1.f / r.w;17271728r.x *= iw;1729r.y *= iw;1730r.z *= iw;1731r.r *= iw;1732r.g *= iw;1733r.b *= iw;1734}1735}17361737static void fillCellRemap(unsigned int* cell_remap, float* cell_errors, size_t cell_count, const unsigned int* vertex_cells, const Quadric* cell_quadrics, const Vector3* vertex_positions, size_t vertex_count)1738{1739memset(cell_remap, -1, cell_count * sizeof(unsigned int));17401741for (size_t i = 0; i < vertex_count; ++i)1742{1743unsigned int cell = vertex_cells[i];1744float error = quadricError(cell_quadrics[cell], vertex_positions[i]);17451746if (cell_remap[cell] == ~0u || cell_errors[cell] > error)1747{1748cell_remap[cell] = unsigned(i);1749cell_errors[cell] = error;1750}1751}1752}17531754static void fillCellRemap(unsigned int* cell_remap, float* cell_errors, size_t cell_count, const unsigned int* vertex_cells, const Reservoir* cell_reservoirs, const Vector3* vertex_positions, const float* vertex_colors, size_t vertex_colors_stride, float color_weight, size_t vertex_count)1755{1756static const float dummy_color[] = {0.f, 0.f, 0.f};17571758size_t vertex_colors_stride_float = vertex_colors_stride / sizeof(float);17591760memset(cell_remap, -1, cell_count * sizeof(unsigned int));17611762for (size_t i = 0; i < vertex_count; ++i)1763{1764unsigned int cell = vertex_cells[i];1765const Vector3& v = vertex_positions[i];1766const Reservoir& r = cell_reservoirs[cell];17671768const float* color = vertex_colors ? &vertex_colors[i * vertex_colors_stride_float] : dummy_color;17691770float pos_error = (v.x - r.x) * (v.x - r.x) + (v.y - r.y) * (v.y - r.y) + (v.z - r.z) * (v.z - r.z);1771float col_error = (color[0] - r.r) * (color[0] - r.r) + (color[1] - r.g) * (color[1] - r.g) + (color[2] - r.b) * (color[2] - r.b);1772float error = pos_error + color_weight * col_error;17731774if (cell_remap[cell] == ~0u || cell_errors[cell] > error)1775{1776cell_remap[cell] = unsigned(i);1777cell_errors[cell] = error;1778}1779}1780}17811782static size_t filterTriangles(unsigned int* destination, unsigned int* tritable, size_t tritable_size, const unsigned int* indices, size_t index_count, const unsigned int* vertex_cells, const unsigned int* cell_remap)1783{1784TriangleHasher hasher = {destination};17851786memset(tritable, -1, tritable_size * sizeof(unsigned int));17871788size_t result = 0;17891790for (size_t i = 0; i < index_count; i += 3)1791{1792unsigned int c0 = vertex_cells[indices[i + 0]];1793unsigned int c1 = vertex_cells[indices[i + 1]];1794unsigned int c2 = vertex_cells[indices[i + 2]];17951796if (c0 != c1 && c0 != c2 && c1 != c2)1797{1798unsigned int a = cell_remap[c0];1799unsigned int b = cell_remap[c1];1800unsigned int c = cell_remap[c2];18011802if (b < a && b < c)1803{1804unsigned int t = a;1805a = b, b = c, c = t;1806}1807else if (c < a && c < b)1808{1809unsigned int t = c;1810c = b, b = a, a = t;1811}18121813destination[result * 3 + 0] = a;1814destination[result * 3 + 1] = b;1815destination[result * 3 + 2] = c;18161817unsigned int* entry = hashLookup2(tritable, tritable_size, hasher, unsigned(result), ~0u);18181819if (*entry == ~0u)1820*entry = unsigned(result++);1821}1822}18231824return result * 3;1825}18261827static float interpolate(float y, float x0, float y0, float x1, float y1, float x2, float y2)1828{1829// three point interpolation from "revenge of interpolation search" paper1830float num = (y1 - y) * (x1 - x2) * (x1 - x0) * (y2 - y0);1831float den = (y2 - y) * (x1 - x2) * (y0 - y1) + (y0 - y) * (x1 - x0) * (y1 - y2);1832return x1 + num / den;1833}18341835} // namespace meshopt18361837// Note: this is only exposed for debug visualization purposes; do *not* use1838enum1839{1840meshopt_SimplifyInternalDebug = 1 << 301841};18421843size_t meshopt_simplifyEdge(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride, const float* vertex_attributes_data, size_t vertex_attributes_stride, const float* attribute_weights, size_t attribute_count, const unsigned char* vertex_lock, size_t target_index_count, float target_error, unsigned int options, float* out_result_error)1844{1845using namespace meshopt;18461847assert(index_count % 3 == 0);1848assert(vertex_positions_stride >= 12 && vertex_positions_stride <= 256);1849assert(vertex_positions_stride % sizeof(float) == 0);1850assert(target_index_count <= index_count);1851assert(target_error >= 0);1852assert((options & ~(meshopt_SimplifyLockBorder | meshopt_SimplifySparse | meshopt_SimplifyErrorAbsolute | meshopt_SimplifyPrune | meshopt_SimplifyInternalDebug)) == 0);1853assert(vertex_attributes_stride >= attribute_count * sizeof(float) && vertex_attributes_stride <= 256);1854assert(vertex_attributes_stride % sizeof(float) == 0);1855assert(attribute_count <= kMaxAttributes);1856for (size_t i = 0; i < attribute_count; ++i)1857assert(attribute_weights[i] >= 0);18581859meshopt_Allocator allocator;18601861unsigned int* result = destination;1862if (result != indices)1863memcpy(result, indices, index_count * sizeof(unsigned int));18641865// build an index remap and update indices/vertex_count to minimize the subsequent work1866// note: as a consequence, errors will be computed relative to the subset extent1867unsigned int* sparse_remap = NULL;1868if (options & meshopt_SimplifySparse)1869sparse_remap = buildSparseRemap(result, index_count, vertex_count, &vertex_count, allocator);18701871// build adjacency information1872EdgeAdjacency adjacency = {};1873prepareEdgeAdjacency(adjacency, index_count, vertex_count, allocator);1874updateEdgeAdjacency(adjacency, result, index_count, vertex_count, NULL);18751876// build position remap that maps each vertex to the one with identical position1877// wedge table stores next vertex with identical position for each vertex1878unsigned int* remap = allocator.allocate<unsigned int>(vertex_count);1879unsigned int* wedge = allocator.allocate<unsigned int>(vertex_count);1880buildPositionRemap(remap, wedge, vertex_positions_data, vertex_count, vertex_positions_stride, sparse_remap, allocator);18811882// classify vertices; vertex kind determines collapse rules, see kCanCollapse1883unsigned char* vertex_kind = allocator.allocate<unsigned char>(vertex_count);1884unsigned int* loop = allocator.allocate<unsigned int>(vertex_count);1885unsigned int* loopback = allocator.allocate<unsigned int>(vertex_count);1886classifyVertices(vertex_kind, loop, loopback, vertex_count, adjacency, remap, wedge, vertex_lock, sparse_remap, options);18871888#if TRACE1889size_t unique_positions = 0;1890for (size_t i = 0; i < vertex_count; ++i)1891unique_positions += remap[i] == i;18921893printf("position remap: %d vertices => %d positions\n", int(vertex_count), int(unique_positions));18941895size_t kinds[Kind_Count] = {};1896for (size_t i = 0; i < vertex_count; ++i)1897kinds[vertex_kind[i]] += remap[i] == i;18981899printf("kinds: manifold %d, border %d, seam %d, complex %d, locked %d\n",1900int(kinds[Kind_Manifold]), int(kinds[Kind_Border]), int(kinds[Kind_Seam]), int(kinds[Kind_Complex]), int(kinds[Kind_Locked]));1901#endif19021903Vector3* vertex_positions = allocator.allocate<Vector3>(vertex_count);1904float vertex_scale = rescalePositions(vertex_positions, vertex_positions_data, vertex_count, vertex_positions_stride, sparse_remap);19051906float* vertex_attributes = NULL;19071908if (attribute_count)1909{1910unsigned int attribute_remap[kMaxAttributes];19111912// remap attributes to only include ones with weight > 0 to minimize memory/compute overhead for quadrics1913size_t attributes_used = 0;1914for (size_t i = 0; i < attribute_count; ++i)1915if (attribute_weights[i] > 0)1916attribute_remap[attributes_used++] = unsigned(i);19171918attribute_count = attributes_used;1919vertex_attributes = allocator.allocate<float>(vertex_count * attribute_count);1920rescaleAttributes(vertex_attributes, vertex_attributes_data, vertex_count, vertex_attributes_stride, attribute_weights, attribute_count, attribute_remap, sparse_remap);1921}19221923Quadric* vertex_quadrics = allocator.allocate<Quadric>(vertex_count);1924memset(vertex_quadrics, 0, vertex_count * sizeof(Quadric));19251926Quadric* attribute_quadrics = NULL;1927QuadricGrad* attribute_gradients = NULL;19281929if (attribute_count)1930{1931attribute_quadrics = allocator.allocate<Quadric>(vertex_count);1932memset(attribute_quadrics, 0, vertex_count * sizeof(Quadric));19331934attribute_gradients = allocator.allocate<QuadricGrad>(vertex_count * attribute_count);1935memset(attribute_gradients, 0, vertex_count * attribute_count * sizeof(QuadricGrad));1936}19371938fillFaceQuadrics(vertex_quadrics, result, index_count, vertex_positions, remap);1939fillEdgeQuadrics(vertex_quadrics, result, index_count, vertex_positions, remap, vertex_kind, loop, loopback);19401941if (attribute_count)1942fillAttributeQuadrics(attribute_quadrics, attribute_gradients, result, index_count, vertex_positions, vertex_attributes, attribute_count);19431944unsigned int* components = NULL;1945float* component_errors = NULL;1946size_t component_count = 0;1947float component_nexterror = 0;19481949if (options & meshopt_SimplifyPrune)1950{1951components = allocator.allocate<unsigned int>(vertex_count);1952component_count = buildComponents(components, vertex_count, result, index_count, remap);19531954component_errors = allocator.allocate<float>(component_count * 4); // overallocate for temporary use inside measureComponents1955measureComponents(component_errors, component_count, components, vertex_positions, vertex_count);19561957component_nexterror = FLT_MAX;1958for (size_t i = 0; i < component_count; ++i)1959component_nexterror = component_nexterror > component_errors[i] ? component_errors[i] : component_nexterror;19601961#if TRACE1962printf("components: %d (min error %e)\n", int(component_count), sqrtf(component_nexterror));1963#endif1964}19651966#if TRACE1967size_t pass_count = 0;1968#endif19691970size_t collapse_capacity = boundEdgeCollapses(adjacency, vertex_count, index_count, vertex_kind);19711972Collapse* edge_collapses = allocator.allocate<Collapse>(collapse_capacity);1973unsigned int* collapse_order = allocator.allocate<unsigned int>(collapse_capacity);1974unsigned int* collapse_remap = allocator.allocate<unsigned int>(vertex_count);1975unsigned char* collapse_locked = allocator.allocate<unsigned char>(vertex_count);19761977size_t result_count = index_count;1978float result_error = 0;1979float vertex_error = 0;19801981// target_error input is linear; we need to adjust it to match quadricError units1982float error_scale = (options & meshopt_SimplifyErrorAbsolute) ? vertex_scale : 1.f;1983float error_limit = (target_error * target_error) / (error_scale * error_scale);19841985while (result_count > target_index_count)1986{1987// note: throughout the simplification process adjacency structure reflects welded topology for result-in-progress1988updateEdgeAdjacency(adjacency, result, result_count, vertex_count, remap);19891990size_t edge_collapse_count = pickEdgeCollapses(edge_collapses, collapse_capacity, result, result_count, remap, vertex_kind, loop, loopback);1991assert(edge_collapse_count <= collapse_capacity);19921993// no edges can be collapsed any more due to topology restrictions1994if (edge_collapse_count == 0)1995break;19961997#if TRACE1998printf("pass %d:%c", int(pass_count++), TRACE >= 2 ? '\n' : ' ');1999#endif20002001rankEdgeCollapses(edge_collapses, edge_collapse_count, vertex_positions, vertex_attributes, vertex_quadrics, attribute_quadrics, attribute_gradients, attribute_count, remap, wedge, vertex_kind, loop, loopback);20022003sortEdgeCollapses(collapse_order, edge_collapses, edge_collapse_count);20042005size_t triangle_collapse_goal = (result_count - target_index_count) / 3;20062007for (size_t i = 0; i < vertex_count; ++i)2008collapse_remap[i] = unsigned(i);20092010memset(collapse_locked, 0, vertex_count);20112012size_t collapses = performEdgeCollapses(collapse_remap, collapse_locked, edge_collapses, edge_collapse_count, collapse_order, remap, wedge, vertex_kind, loop, loopback, vertex_positions, adjacency, triangle_collapse_goal, error_limit, result_error);20132014// no edges can be collapsed any more due to hitting the error limit or triangle collapse limit2015if (collapses == 0)2016break;20172018updateQuadrics(collapse_remap, vertex_count, vertex_quadrics, attribute_quadrics, attribute_gradients, attribute_count, vertex_positions, remap, vertex_error);20192020// updateQuadrics will update vertex error if we use attributes, but if we don't then result_error and vertex_error are equivalent2021vertex_error = attribute_count == 0 ? result_error : vertex_error;20222023remapEdgeLoops(loop, vertex_count, collapse_remap);2024remapEdgeLoops(loopback, vertex_count, collapse_remap);20252026size_t new_count = remapIndexBuffer(result, result_count, collapse_remap);2027assert(new_count < result_count);20282029result_count = new_count;20302031if ((options & meshopt_SimplifyPrune) && result_count > target_index_count && component_nexterror <= vertex_error)2032result_count = pruneComponents(result, result_count, components, component_errors, component_count, vertex_error, component_nexterror);2033}20342035// we're done with the regular simplification but we're still short of the target; try pruning more aggressively towards error_limit2036while ((options & meshopt_SimplifyPrune) && result_count > target_index_count && component_nexterror <= error_limit)2037{2038#if TRACE2039printf("pass %d: cleanup; ", int(pass_count++));2040#endif20412042float component_cutoff = component_nexterror * 1.5f < error_limit ? component_nexterror * 1.5f : error_limit;20432044// track maximum error in eligible components as we are increasing resulting error2045float component_maxerror = 0;2046for (size_t i = 0; i < component_count; ++i)2047if (component_errors[i] > component_maxerror && component_errors[i] <= component_cutoff)2048component_maxerror = component_errors[i];20492050size_t new_count = pruneComponents(result, result_count, components, component_errors, component_count, component_cutoff, component_nexterror);2051if (new_count == result_count)2052break;20532054result_count = new_count;2055result_error = result_error < component_maxerror ? component_maxerror : result_error;2056vertex_error = vertex_error < component_maxerror ? component_maxerror : vertex_error;2057}20582059#if TRACE2060printf("result: %d triangles, error: %e; total %d passes\n", int(result_count / 3), sqrtf(result_error), int(pass_count));2061#endif20622063// if debug visualization data is requested, fill it instead of index data; for simplicity, this doesn't work with sparsity2064if ((options & meshopt_SimplifyInternalDebug) && !sparse_remap)2065{2066assert(Kind_Count <= 8 && vertex_count < (1 << 28)); // 3 bit kind, 1 bit loop20672068for (size_t i = 0; i < result_count; i += 3)2069{2070unsigned int a = result[i + 0], b = result[i + 1], c = result[i + 2];20712072result[i + 0] |= (vertex_kind[a] << 28) | (unsigned(loop[a] == b || loopback[b] == a) << 31);2073result[i + 1] |= (vertex_kind[b] << 28) | (unsigned(loop[b] == c || loopback[c] == b) << 31);2074result[i + 2] |= (vertex_kind[c] << 28) | (unsigned(loop[c] == a || loopback[a] == c) << 31);2075}2076}20772078// convert resulting indices back into the dense space of the larger mesh2079if (sparse_remap)2080for (size_t i = 0; i < result_count; ++i)2081result[i] = sparse_remap[result[i]];20822083// result_error is quadratic; we need to remap it back to linear2084if (out_result_error)2085*out_result_error = sqrtf(result_error) * error_scale;20862087return result_count;2088}20892090size_t meshopt_simplify(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride, size_t target_index_count, float target_error, unsigned int options, float* out_result_error)2091{2092return meshopt_simplifyEdge(destination, indices, index_count, vertex_positions_data, vertex_count, vertex_positions_stride, NULL, 0, NULL, 0, NULL, target_index_count, target_error, options, out_result_error);2093}20942095size_t meshopt_simplifyWithAttributes(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride, const float* vertex_attributes_data, size_t vertex_attributes_stride, const float* attribute_weights, size_t attribute_count, const unsigned char* vertex_lock, size_t target_index_count, float target_error, unsigned int options, float* out_result_error)2096{2097return meshopt_simplifyEdge(destination, indices, index_count, vertex_positions_data, vertex_count, vertex_positions_stride, vertex_attributes_data, vertex_attributes_stride, attribute_weights, attribute_count, vertex_lock, target_index_count, target_error, options, out_result_error);2098}20992100size_t meshopt_simplifySloppy(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride, size_t target_index_count, float target_error, float* out_result_error)2101{2102using namespace meshopt;21032104assert(index_count % 3 == 0);2105assert(vertex_positions_stride >= 12 && vertex_positions_stride <= 256);2106assert(vertex_positions_stride % sizeof(float) == 0);2107assert(target_index_count <= index_count);21082109// we expect to get ~2 triangles/vertex in the output2110size_t target_cell_count = target_index_count / 6;21112112meshopt_Allocator allocator;21132114Vector3* vertex_positions = allocator.allocate<Vector3>(vertex_count);2115rescalePositions(vertex_positions, vertex_positions_data, vertex_count, vertex_positions_stride);21162117// find the optimal grid size using guided binary search2118#if TRACE2119printf("source: %d vertices, %d triangles\n", int(vertex_count), int(index_count / 3));2120printf("target: %d cells, %d triangles\n", int(target_cell_count), int(target_index_count / 3));2121#endif21222123unsigned int* vertex_ids = allocator.allocate<unsigned int>(vertex_count);21242125const int kInterpolationPasses = 5;21262127// invariant: # of triangles in min_grid <= target_count2128int min_grid = int(1.f / (target_error < 1e-3f ? 1e-3f : target_error));2129int max_grid = 1025;2130size_t min_triangles = 0;2131size_t max_triangles = index_count / 3;21322133// when we're error-limited, we compute the triangle count for the min. size; this accelerates convergence and provides the correct answer when we can't use a larger grid2134if (min_grid > 1)2135{2136computeVertexIds(vertex_ids, vertex_positions, vertex_count, min_grid);2137min_triangles = countTriangles(vertex_ids, indices, index_count);2138}21392140// instead of starting in the middle, let's guess as to what the answer might be! triangle count usually grows as a square of grid size...2141int next_grid_size = int(sqrtf(float(target_cell_count)) + 0.5f);21422143for (int pass = 0; pass < 10 + kInterpolationPasses; ++pass)2144{2145if (min_triangles >= target_index_count / 3 || max_grid - min_grid <= 1)2146break;21472148// we clamp the prediction of the grid size to make sure that the search converges2149int grid_size = next_grid_size;2150grid_size = (grid_size <= min_grid) ? min_grid + 1 : (grid_size >= max_grid ? max_grid - 1 : grid_size);21512152computeVertexIds(vertex_ids, vertex_positions, vertex_count, grid_size);2153size_t triangles = countTriangles(vertex_ids, indices, index_count);21542155#if TRACE2156printf("pass %d (%s): grid size %d, triangles %d, %s\n",2157pass, (pass == 0) ? "guess" : (pass <= kInterpolationPasses ? "lerp" : "binary"),2158grid_size, int(triangles),2159(triangles <= target_index_count / 3) ? "under" : "over");2160#endif21612162float tip = interpolate(float(size_t(target_index_count / 3)), float(min_grid), float(min_triangles), float(grid_size), float(triangles), float(max_grid), float(max_triangles));21632164if (triangles <= target_index_count / 3)2165{2166min_grid = grid_size;2167min_triangles = triangles;2168}2169else2170{2171max_grid = grid_size;2172max_triangles = triangles;2173}21742175// we start by using interpolation search - it usually converges faster2176// however, interpolation search has a worst case of O(N) so we switch to binary search after a few iterations which converges in O(logN)2177next_grid_size = (pass < kInterpolationPasses) ? int(tip + 0.5f) : (min_grid + max_grid) / 2;2178}21792180if (min_triangles == 0)2181{2182if (out_result_error)2183*out_result_error = 1.f;21842185return 0;2186}21872188// build vertex->cell association by mapping all vertices with the same quantized position to the same cell2189size_t table_size = hashBuckets2(vertex_count);2190unsigned int* table = allocator.allocate<unsigned int>(table_size);21912192unsigned int* vertex_cells = allocator.allocate<unsigned int>(vertex_count);21932194computeVertexIds(vertex_ids, vertex_positions, vertex_count, min_grid);2195size_t cell_count = fillVertexCells(table, table_size, vertex_cells, vertex_ids, vertex_count);21962197// build a quadric for each target cell2198Quadric* cell_quadrics = allocator.allocate<Quadric>(cell_count);2199memset(cell_quadrics, 0, cell_count * sizeof(Quadric));22002201fillCellQuadrics(cell_quadrics, indices, index_count, vertex_positions, vertex_cells);22022203// for each target cell, find the vertex with the minimal error2204unsigned int* cell_remap = allocator.allocate<unsigned int>(cell_count);2205float* cell_errors = allocator.allocate<float>(cell_count);22062207fillCellRemap(cell_remap, cell_errors, cell_count, vertex_cells, cell_quadrics, vertex_positions, vertex_count);22082209// compute error2210float result_error = 0.f;22112212for (size_t i = 0; i < cell_count; ++i)2213result_error = result_error < cell_errors[i] ? cell_errors[i] : result_error;22142215// collapse triangles!2216// note that we need to filter out triangles that we've already output because we very frequently generate redundant triangles between cells :(2217size_t tritable_size = hashBuckets2(min_triangles);2218unsigned int* tritable = allocator.allocate<unsigned int>(tritable_size);22192220size_t write = filterTriangles(destination, tritable, tritable_size, indices, index_count, vertex_cells, cell_remap);22212222#if TRACE2223printf("result: %d cells, %d triangles (%d unfiltered), error %e\n", int(cell_count), int(write / 3), int(min_triangles), sqrtf(result_error));2224#endif22252226if (out_result_error)2227*out_result_error = sqrtf(result_error);22282229return write;2230}22312232size_t meshopt_simplifyPrune(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride, float target_error)2233{2234using namespace meshopt;22352236assert(index_count % 3 == 0);2237assert(vertex_positions_stride >= 12 && vertex_positions_stride <= 256);2238assert(vertex_positions_stride % sizeof(float) == 0);2239assert(target_error >= 0);22402241meshopt_Allocator allocator;22422243unsigned int* result = destination;2244if (result != indices)2245memcpy(result, indices, index_count * sizeof(unsigned int));22462247// build position remap that maps each vertex to the one with identical position2248unsigned int* remap = allocator.allocate<unsigned int>(vertex_count);2249buildPositionRemap(remap, NULL, vertex_positions_data, vertex_count, vertex_positions_stride, NULL, allocator);22502251Vector3* vertex_positions = allocator.allocate<Vector3>(vertex_count);2252rescalePositions(vertex_positions, vertex_positions_data, vertex_count, vertex_positions_stride, NULL);22532254unsigned int* components = allocator.allocate<unsigned int>(vertex_count);2255size_t component_count = buildComponents(components, vertex_count, indices, index_count, remap);22562257float* component_errors = allocator.allocate<float>(component_count * 4); // overallocate for temporary use inside measureComponents2258measureComponents(component_errors, component_count, components, vertex_positions, vertex_count);22592260float component_nexterror = 0;2261size_t result_count = pruneComponents(result, index_count, components, component_errors, component_count, target_error * target_error, component_nexterror);22622263return result_count;2264}22652266size_t meshopt_simplifyPoints(unsigned int* destination, const float* vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride, const float* vertex_colors, size_t vertex_colors_stride, float color_weight, size_t target_vertex_count)2267{2268using namespace meshopt;22692270assert(vertex_positions_stride >= 12 && vertex_positions_stride <= 256);2271assert(vertex_positions_stride % sizeof(float) == 0);2272assert(vertex_colors_stride == 0 || (vertex_colors_stride >= 12 && vertex_colors_stride <= 256));2273assert(vertex_colors_stride % sizeof(float) == 0);2274assert(vertex_colors == NULL || vertex_colors_stride != 0);2275assert(target_vertex_count <= vertex_count);22762277size_t target_cell_count = target_vertex_count;22782279if (target_cell_count == 0)2280return 0;22812282meshopt_Allocator allocator;22832284Vector3* vertex_positions = allocator.allocate<Vector3>(vertex_count);2285rescalePositions(vertex_positions, vertex_positions_data, vertex_count, vertex_positions_stride);22862287// find the optimal grid size using guided binary search2288#if TRACE2289printf("source: %d vertices\n", int(vertex_count));2290printf("target: %d cells\n", int(target_cell_count));2291#endif22922293unsigned int* vertex_ids = allocator.allocate<unsigned int>(vertex_count);22942295size_t table_size = hashBuckets2(vertex_count);2296unsigned int* table = allocator.allocate<unsigned int>(table_size);22972298const int kInterpolationPasses = 5;22992300// invariant: # of vertices in min_grid <= target_count2301int min_grid = 0;2302int max_grid = 1025;2303size_t min_vertices = 0;2304size_t max_vertices = vertex_count;23052306// instead of starting in the middle, let's guess as to what the answer might be! triangle count usually grows as a square of grid size...2307int next_grid_size = int(sqrtf(float(target_cell_count)) + 0.5f);23082309for (int pass = 0; pass < 10 + kInterpolationPasses; ++pass)2310{2311assert(min_vertices < target_vertex_count);2312assert(max_grid - min_grid > 1);23132314// we clamp the prediction of the grid size to make sure that the search converges2315int grid_size = next_grid_size;2316grid_size = (grid_size <= min_grid) ? min_grid + 1 : (grid_size >= max_grid ? max_grid - 1 : grid_size);23172318computeVertexIds(vertex_ids, vertex_positions, vertex_count, grid_size);2319size_t vertices = countVertexCells(table, table_size, vertex_ids, vertex_count);23202321#if TRACE2322printf("pass %d (%s): grid size %d, vertices %d, %s\n",2323pass, (pass == 0) ? "guess" : (pass <= kInterpolationPasses ? "lerp" : "binary"),2324grid_size, int(vertices),2325(vertices <= target_vertex_count) ? "under" : "over");2326#endif23272328float tip = interpolate(float(target_vertex_count), float(min_grid), float(min_vertices), float(grid_size), float(vertices), float(max_grid), float(max_vertices));23292330if (vertices <= target_vertex_count)2331{2332min_grid = grid_size;2333min_vertices = vertices;2334}2335else2336{2337max_grid = grid_size;2338max_vertices = vertices;2339}23402341if (vertices == target_vertex_count || max_grid - min_grid <= 1)2342break;23432344// we start by using interpolation search - it usually converges faster2345// however, interpolation search has a worst case of O(N) so we switch to binary search after a few iterations which converges in O(logN)2346next_grid_size = (pass < kInterpolationPasses) ? int(tip + 0.5f) : (min_grid + max_grid) / 2;2347}23482349if (min_vertices == 0)2350return 0;23512352// build vertex->cell association by mapping all vertices with the same quantized position to the same cell2353unsigned int* vertex_cells = allocator.allocate<unsigned int>(vertex_count);23542355computeVertexIds(vertex_ids, vertex_positions, vertex_count, min_grid);2356size_t cell_count = fillVertexCells(table, table_size, vertex_cells, vertex_ids, vertex_count);23572358// accumulate points into a reservoir for each target cell2359Reservoir* cell_reservoirs = allocator.allocate<Reservoir>(cell_count);2360memset(cell_reservoirs, 0, cell_count * sizeof(Reservoir));23612362fillCellReservoirs(cell_reservoirs, cell_count, vertex_positions, vertex_colors, vertex_colors_stride, vertex_count, vertex_cells);23632364// for each target cell, find the vertex with the minimal error2365unsigned int* cell_remap = allocator.allocate<unsigned int>(cell_count);2366float* cell_errors = allocator.allocate<float>(cell_count);23672368// we scale the color weight to bring it to the same scale as position so that error addition makes sense2369float color_weight_scaled = color_weight * (min_grid == 1 ? 1.f : 1.f / (min_grid - 1));23702371fillCellRemap(cell_remap, cell_errors, cell_count, vertex_cells, cell_reservoirs, vertex_positions, vertex_colors, vertex_colors_stride, color_weight_scaled * color_weight_scaled, vertex_count);23722373// copy results to the output2374assert(cell_count <= target_vertex_count);2375memcpy(destination, cell_remap, sizeof(unsigned int) * cell_count);23762377#if TRACE2378// compute error2379float result_error = 0.f;23802381for (size_t i = 0; i < cell_count; ++i)2382result_error = result_error < cell_errors[i] ? cell_errors[i] : result_error;23832384printf("result: %d cells, %e error\n", int(cell_count), sqrtf(result_error));2385#endif23862387return cell_count;2388}23892390float meshopt_simplifyScale(const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride)2391{2392using namespace meshopt;23932394assert(vertex_positions_stride >= 12 && vertex_positions_stride <= 256);2395assert(vertex_positions_stride % sizeof(float) == 0);23962397float extent = rescalePositions(NULL, vertex_positions, vertex_count, vertex_positions_stride);23982399return extent;2400}240124022403