{
  "name": "highlight-mesh",
  "description": "Highlight given mesh with an outline.",
  "dependencies": [
    "three"
  ],
  "devDependencies": [
    "@types/three"
  ],
  "registryDependencies": [
    "dispose-tracker",
    "utils"
  ],
  "files": [
    {
      "path": "shaders/highlight.vertex.glsl",
      "content": "\n#ifdef USE_SKINNING\nuniform mat4 bindMatrix;\nuniform mat4 bindMatrixInverse;\nuniform highp sampler2D boneTexture;\nmat4 getBoneMatrix(const in float i) {\n  int size = textureSize(boneTexture, 0).x;\n  int j = int(i) * 4;\n  int x = j % size;\n  int y = j / size;\n  vec4 v1 = texelFetch(boneTexture, ivec2(x, y), 0);\n  vec4 v2 = texelFetch(boneTexture, ivec2(x + 1, y), 0);\n  vec4 v3 = texelFetch(boneTexture, ivec2(x + 2, y), 0);\n  vec4 v4 = texelFetch(boneTexture, ivec2(x + 3, y), 0);\n  return mat4(v1, v2, v3, v4);\n}\n#endif\n\nvoid main() {\n\n  // Assuming origin is geometry center\n  // TODO : Relative offset\n  vec3 transformed = vec3(position) + vec3(normal) * 0.02;\n\n  #ifdef USE_SKINNING\n  mat4 boneMatX = getBoneMatrix(skinIndex.x);\n  mat4 boneMatY = getBoneMatrix(skinIndex.y);\n  mat4 boneMatZ = getBoneMatrix(skinIndex.z);\n  mat4 boneMatW = getBoneMatrix(skinIndex.w);\n\n  vec4 skinVertex = bindMatrix * vec4(transformed, 1.0);\n\n  vec4 skinned = vec4(0.0);\n  skinned += boneMatX * skinVertex * skinWeight.x;\n  skinned += boneMatY * skinVertex * skinWeight.y;\n  skinned += boneMatZ * skinVertex * skinWeight.z;\n  skinned += boneMatW * skinVertex * skinWeight.w;\n\n  transformed = (bindMatrixInverse * skinned).xyz;\n  #endif\n\n  vec4 mvPosition = vec4(transformed, 1.0);\n\n  #ifdef USE_BATCHING\n  mvPosition = batchingMatrix * mvPosition;\n  #endif\n\n  #ifdef USE_INSTANCING\n  mvPosition = instanceMatrix * mvPosition;\n  #endif\n\n  mvPosition = modelViewMatrix * mvPosition;\n\n  gl_Position = projectionMatrix * mvPosition;\n}\n"
    },
    {
      "path": "shaders/highlight.fragment.glsl",
      "content": "uniform vec4 color;\n\nvoid main() {\n  gl_FragColor = color;\n}\n"
    },
    {
      "path": "highlight-mesh.ts",
      "content": "import { assertIsMaterial, assertIsNotNullish } from \"@3dvf/utils/utils\";\nimport { AlwaysStencilFunc, BufferAttribute, BufferGeometry, Color, Mesh, NotEqualStencilFunc, ReplaceStencilOp, Scene, ShaderMaterial, Vector3, Vector4 } from \"three\";\nimport vertexShader from \"./shaders/highlight.vertex.glsl\";\nimport fragmentShader from \"./shaders/highlight.fragment.glsl\";\nimport { BufferGeometryUtils } from \"three/examples/jsm/Addons.js\";\nimport { addToDisposeTracker } from \"@3dvf/dispose-tracker/add-to-dispose-tracker\";\n\nconst computeNormalizedVertexNormals = (geometry: BufferGeometry): BufferGeometry => {\n  geometry.deleteAttribute('normal');\n  geometry.deleteAttribute('uv');\n  \n  geometry = BufferGeometryUtils.mergeVertices(geometry);\n  \n  const index = geometry.index;\n  assertIsNotNullish(index);\n  \n\tconst positionAttribute = geometry.getAttribute('position');\n  \n\tconst normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3);\n\tgeometry.setAttribute('normal', normalAttribute);\n   \n  const pA = new Vector3();\n  const pB = new Vector3();\n  const pC = new Vector3();\n  const nA = new Vector3();\n  const nB = new Vector3();\n  const nC = new Vector3();\n  const cb = new Vector3();\n  const ab = new Vector3();\n  const ac = new Vector3();\n  \n  let count = index.count;\n\n  // Inspired from three.js computeVertexNormals, but face normals are weighted by vertex angle, resulting in triangulation independent mean normal\n\tfor (let i = 0; i < count; i += 3) {\n\t\tconst vA = index.getX(i + 0);\n\t\tconst vB = index.getX(i + 1);\n\t\tconst vC = index.getX(i + 2);\n\n\t\tpA.fromBufferAttribute(positionAttribute, vA);\n\t\tpB.fromBufferAttribute(positionAttribute, vB);\n\t\tpC.fromBufferAttribute(positionAttribute, vC);\n\n\t\tcb.subVectors(pC, pB).normalize();\n    ab.subVectors(pA, pB).normalize();\n    ac.subVectors(pA, pC).normalize();\n    const angleA = Math.acos(ab.dot(ac));\n    const angleB = Math.acos(cb.dot(ab));\n    const angleC = Math.PI - angleA - angleB; // triangle angles sum to π\n    cb.cross(ab).normalize();\n\n\t\tnA.fromBufferAttribute(normalAttribute, vA);\n\t\tnB.fromBufferAttribute(normalAttribute, vB);\n\t\tnC.fromBufferAttribute(normalAttribute, vC);\n\n    normalAttribute.setXYZ(vA, ...nA.addScaledVector(cb, angleA).toArray());\n    normalAttribute.setXYZ(vB, ...nB.addScaledVector(cb, angleB).toArray());\n\t\tnormalAttribute.setXYZ(vC, ...nC.addScaledVector(cb, angleC).toArray());\n\t}\n  \n\tgeometry.normalizeNormals();\n  \n  normalAttribute.needsUpdate = true;\n  \n  return geometry;\n}\n\nexport const highlightMesh = (scene: Scene, mesh: Mesh, color: Color): () => void => {\n  const { material } = mesh;\n  assertIsMaterial(material)\n  \n  material.stencilWrite = true;\n  material.stencilRef = 1;\n  material.stencilFunc = AlwaysStencilFunc;\n  material.stencilZPass = ReplaceStencilOp;\n  material.stencilZFail = ReplaceStencilOp;\n  \n  let highlightData = mesh.userData[\"highlightData\"];\n  \n  if (!highlightData) {\n    let geometry = mesh.geometry.clone();\n    geometry = computeNormalizedVertexNormals(geometry);\n    addToDisposeTracker(scene, geometry);\n    \n    const outlineMaterial = new ShaderMaterial({\n      name: \"outlineMaterial\",\n      uniforms: {\n        color: {\n          value: new Vector4(color.r, color.g, color.b, 1.0)\n        }\n      },\n          vertexShader,\n          fragmentShader\n        });\n        outlineMaterial.stencilWrite = true;\n        outlineMaterial.stencilFunc = NotEqualStencilFunc;\n        outlineMaterial.stencilRef = 1;\n    outlineMaterial.depthTest = true;\n    addToDisposeTracker(scene, outlineMaterial);\n    \n    const seeThroughMaterial = new ShaderMaterial({\n      name: \"seeThroughMaterial\",\n      uniforms: {\n        color: {\n          value: new Vector4(color.r, color.g, color.b, 0.3)\n        }\n      },\n      vertexShader,\n      fragmentShader\n    })\n    seeThroughMaterial.transparent = true;\n    seeThroughMaterial.stencilWrite = true;\n    seeThroughMaterial.stencilFunc = NotEqualStencilFunc;\n    seeThroughMaterial.stencilRef = 1;\n    seeThroughMaterial.depthTest = false;\n    addToDisposeTracker(scene, seeThroughMaterial);\n    \n    const outlineMesh = new Mesh(geometry, outlineMaterial);\n    outlineMesh.renderOrder = 1;\n    mesh.add(outlineMesh);\n    \n    const seeThroughMesh = new Mesh(geometry, seeThroughMaterial);\n    mesh.add(seeThroughMesh);\n    \n    highlightData =  {\n      outlineMesh,\n      seeThroughMesh\n    }\n    \n    mesh.userData[\"highlightData\"] = highlightData;\n    }\n  \n  highlightData.outlineMesh.visible = true;\n  highlightData.seeThroughMesh.visible = true;\n  \n  return () => {\n    highlightData.outlineMesh.visible = false;\n    highlightData.seeThroughMesh.visible = false;\n  }\n}\n"
    }
  ]
}