function subdivide(complex) {
var positions = complex.positions
var cells = complex.cells
var newCells = []
var newPositions = []
var midpoints = {}
var f = [0, 1, 2]
var l = 0
for (var i = 0; i < cells.length; i++) {
var cell = cells[i]
var c0 = cell[0]
var c1 = cell[1]
var c2 = cell[2]
var v0 = positions[c0]
var v1 = positions[c1]
var v2 = positions[c2]
var a = getMidpoint(v0, v1)
var b = getMidpoint(v1, v2)
var c = getMidpoint(v2, v0)
var ai = newPositions.indexOf(a)
if (ai === -1) ai = l++, newPositions.push(a)
var bi = newPositions.indexOf(b)
if (bi === -1) bi = l++, newPositions.push(b)
var ci = newPositions.indexOf(c)
if (ci === -1) ci = l++, newPositions.push(c)
var v0i = newPositions.indexOf(v0)
if (v0i === -1) v0i = l++, newPositions.push(v0)
var v1i = newPositions.indexOf(v1)
if (v1i === -1) v1i = l++, newPositions.push(v1)
var v2i = newPositions.indexOf(v2)
if (v2i === -1) v2i = l++, newPositions.push(v2)
newCells.push([v0i, ai, ci])
newCells.push([v1i, bi, ai])
newCells.push([v2i, ci, bi])
newCells.push([ai, bi, ci])
}
return {
cells: newCells
, positions: newPositions
}
function getMidpoint(a, b) {
var point = midpoint(a, b)
var pointKey = pointToKey(point)
var cachedPoint = midpoints[pointKey]
if (cachedPoint) {
return cachedPoint
} else {
return midpoints[pointKey] = point
}
}
function pointToKey(point) {
return point[0].toPrecision(6) + ','
+ point[1].toPrecision(6) + ','
+ point[2].toPrecision(6)
}
function midpoint(a, b) {
return [
(a[0] + b[0]) / 2
, (a[1] + b[1]) / 2
, (a[2] + b[2]) / 2
]
}
}