UNPKG

@polygonjs/polygonjs

Version:

node-based WebGL 3D engine https://polygonjs.com

94 lines (93 loc) 2.98 kB
"use strict"; import { Triangle, BufferAttribute } from "three"; import { ThreejsPrimitive } from "./ThreejsPrimitive"; import { threeMeshFromPrimitives } from "./builders/Mesh"; import { Attribute } from "../../Attribute"; const _triangle = new Triangle(); const normalsComputedWithPositionAttributeVersion = /* @__PURE__ */ new Map(); export class ThreejsPrimitiveTriangle extends ThreejsPrimitive { constructor(object, index) { super(object, index); this._geometry = object.geometry; } static primitiveName() { return "triangle"; } static entitiesCount(object) { const geometry = object.geometry; if (!geometry) { return 0; } const index = geometry.getIndex(); if (!index) { return 0; } return index.count / 3; } static position(object, primitiveIndex, target) { setTriangle(object, primitiveIndex, _triangle); target.copy(_triangle.a).add(_triangle.b).add(_triangle.c).divideScalar(3); return target; } static normal(object, primitiveIndex, target) { setTriangle(object, primitiveIndex, _triangle); _triangle.getNormal(target); return target; } position(target) { return this.constructor.position(this._object, this._index, target); } normal(target) { return this.constructor.normal(this._object, this._index, target); } static computeVertexNormalsIfAttributeVersionChanged(object) { const geometry = object.geometry; if (!geometry) { return null; } const positionAttribute = geometry.getAttribute(Attribute.POSITION); if (!positionAttribute) { return; } if (!(positionAttribute instanceof BufferAttribute)) { return; } let lastVersion = normalsComputedWithPositionAttributeVersion.get(geometry.uuid); if (lastVersion == null || lastVersion != positionAttribute.version) { geometry.computeVertexNormals(); normalsComputedWithPositionAttributeVersion.set(geometry.uuid, positionAttribute.version); } } builder() { return threeMeshFromPrimitives; } static stride() { return 3; } static setTriangle(object, primitiveIndex, target) { setTriangle(object, primitiveIndex, target); } } export function triangleArea(triangle) { setTriangle(triangle.object(), triangle.index(), _triangle); return _triangle.getArea(); } export function setTriangle(object, primitiveIndex, target) { if (!(object && object.geometry)) { return; } const geometry = object.geometry; const positionAttribute = geometry.getAttribute(Attribute.POSITION); if (!positionAttribute) { return; } const index = geometry.getIndex(); if (!index) { return; } const indexArray = index.array; const positionArray = positionAttribute.array; target.a.fromArray(positionArray, indexArray[primitiveIndex * 3 + 0] * 3); target.b.fromArray(positionArray, indexArray[primitiveIndex * 3 + 1] * 3); target.c.fromArray(positionArray, indexArray[primitiveIndex * 3 + 2] * 3); }