CurveModifier.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. // Original src: https://github.com/zz85/threejs-path-flow
  2. const BITS = 3;
  3. const TEXTURE_WIDTH = 1024;
  4. const TEXTURE_HEIGHT = 4;
  5. import {
  6. DataTexture,
  7. RGBFormat,
  8. FloatType,
  9. RepeatWrapping,
  10. Mesh,
  11. InstancedMesh,
  12. NearestFilter,
  13. DynamicDrawUsage,
  14. Matrix4
  15. } from '../../../build/three.module.js';
  16. /**
  17. * Make a new DataTexture to store the descriptions of the curves.
  18. *
  19. * @param { number } numberOfCurves the number of curves needed to be described by this texture.
  20. */
  21. export function initSplineTexture( numberOfCurves = 1 ) {
  22. const dataArray = new Float32Array( TEXTURE_WIDTH * TEXTURE_HEIGHT * numberOfCurves * BITS );
  23. const dataTexture = new DataTexture(
  24. dataArray,
  25. TEXTURE_WIDTH,
  26. TEXTURE_HEIGHT * numberOfCurves,
  27. RGBFormat,
  28. FloatType
  29. );
  30. dataTexture.wrapS = RepeatWrapping;
  31. dataTexture.wrapY = RepeatWrapping;
  32. dataTexture.magFilter = NearestFilter;
  33. dataTexture.needsUpdate = true;
  34. return dataTexture;
  35. }
  36. /**
  37. * Write the curve description to the data texture
  38. *
  39. * @param { DataTexture } texture The DataTexture to write to
  40. * @param { Curve } splineCurve The curve to describe
  41. * @param { number } offset Which curve slot to write to
  42. */
  43. export function updateSplineTexture( texture, splineCurve, offset = 0 ) {
  44. const numberOfPoints = Math.floor( TEXTURE_WIDTH * ( TEXTURE_HEIGHT / 4 ) );
  45. splineCurve.arcLengthDivisions = numberOfPoints / 2;
  46. splineCurve.updateArcLengths();
  47. const points = splineCurve.getSpacedPoints( numberOfPoints );
  48. const frenetFrames = splineCurve.computeFrenetFrames( numberOfPoints, true );
  49. for ( let i = 0; i < numberOfPoints; i ++ ) {
  50. const rowOffset = Math.floor( i / TEXTURE_WIDTH );
  51. const rowIndex = i % TEXTURE_WIDTH;
  52. let pt = points[ i ];
  53. setTextureValue( texture, rowIndex, pt.x, pt.y, pt.z, 0 + rowOffset + ( TEXTURE_HEIGHT * offset ) );
  54. pt = frenetFrames.tangents[ i ];
  55. setTextureValue( texture, rowIndex, pt.x, pt.y, pt.z, 1 + rowOffset + ( TEXTURE_HEIGHT * offset ) );
  56. pt = frenetFrames.normals[ i ];
  57. setTextureValue( texture, rowIndex, pt.x, pt.y, pt.z, 2 + rowOffset + ( TEXTURE_HEIGHT * offset ) );
  58. pt = frenetFrames.binormals[ i ];
  59. setTextureValue( texture, rowIndex, pt.x, pt.y, pt.z, 3 + rowOffset + ( TEXTURE_HEIGHT * offset ) );
  60. }
  61. texture.needsUpdate = true;
  62. }
  63. function setTextureValue( texture, index, x, y, z, o ) {
  64. const image = texture.image;
  65. const { data } = image;
  66. const i = BITS * TEXTURE_WIDTH * o; // Row Offset
  67. data[ index * BITS + i + 0 ] = x;
  68. data[ index * BITS + i + 1 ] = y;
  69. data[ index * BITS + i + 2 ] = z;
  70. }
  71. /**
  72. * Create a new set of uniforms for describing the curve modifier
  73. *
  74. * @param { DataTexture } Texture which holds the curve description
  75. */
  76. export function getUniforms( splineTexture ) {
  77. const uniforms = {
  78. spineTexture: { value: splineTexture },
  79. pathOffset: { type: 'f', value: 0 }, // time of path curve
  80. pathSegment: { type: 'f', value: 1 }, // fractional length of path
  81. spineOffset: { type: 'f', value: 161 },
  82. spineLength: { type: 'f', value: 400 },
  83. flow: { type: 'i', value: 1 },
  84. };
  85. return uniforms;
  86. }
  87. export function modifyShader( material, uniforms, numberOfCurves = 1 ) {
  88. if ( material.__ok ) return;
  89. material.__ok = true;
  90. material.onBeforeCompile = ( shader ) => {
  91. if ( shader.__modified ) return;
  92. shader.__modified = true;
  93. Object.assign( shader.uniforms, uniforms );
  94. const vertexShader = `
  95. uniform sampler2D spineTexture;
  96. uniform float pathOffset;
  97. uniform float pathSegment;
  98. uniform float spineOffset;
  99. uniform float spineLength;
  100. uniform int flow;
  101. float textureLayers = ${TEXTURE_HEIGHT * numberOfCurves}.;
  102. float textureStacks = ${TEXTURE_HEIGHT / 4}.;
  103. ${shader.vertexShader}
  104. `
  105. // chunk import moved in front of modified shader below
  106. .replace( '#include <beginnormal_vertex>', '' )
  107. // vec3 transformedNormal declaration overriden below
  108. .replace( '#include <defaultnormal_vertex>', '' )
  109. // vec3 transformed declaration overriden below
  110. .replace( '#include <begin_vertex>', '' )
  111. // shader override
  112. .replace(
  113. /void\s*main\s*\(\)\s*\{/,
  114. `
  115. void main() {
  116. #include <beginnormal_vertex>
  117. vec4 worldPos = modelMatrix * vec4(position, 1.);
  118. bool bend = flow > 0;
  119. float xWeight = bend ? 0. : 1.;
  120. #ifdef USE_INSTANCING
  121. float pathOffsetFromInstanceMatrix = instanceMatrix[3][2];
  122. float spineLengthFromInstanceMatrix = instanceMatrix[3][0];
  123. float spinePortion = bend ? (worldPos.x + spineOffset) / spineLengthFromInstanceMatrix : 0.;
  124. float mt = (spinePortion * pathSegment + pathOffset + pathOffsetFromInstanceMatrix)*textureStacks;
  125. #else
  126. float spinePortion = bend ? (worldPos.x + spineOffset) / spineLength : 0.;
  127. float mt = (spinePortion * pathSegment + pathOffset)*textureStacks;
  128. #endif
  129. mt = mod(mt, textureStacks);
  130. float rowOffset = floor(mt);
  131. #ifdef USE_INSTANCING
  132. rowOffset += instanceMatrix[3][1] * ${TEXTURE_HEIGHT}.;
  133. #endif
  134. vec3 spinePos = texture2D(spineTexture, vec2(mt, (0. + rowOffset + 0.5) / textureLayers)).xyz;
  135. vec3 a = texture2D(spineTexture, vec2(mt, (1. + rowOffset + 0.5) / textureLayers)).xyz;
  136. vec3 b = texture2D(spineTexture, vec2(mt, (2. + rowOffset + 0.5) / textureLayers)).xyz;
  137. vec3 c = texture2D(spineTexture, vec2(mt, (3. + rowOffset + 0.5) / textureLayers)).xyz;
  138. mat3 basis = mat3(a, b, c);
  139. vec3 transformed = basis
  140. * vec3(worldPos.x * xWeight, worldPos.y * 1., worldPos.z * 1.)
  141. + spinePos;
  142. vec3 transformedNormal = normalMatrix * (basis * objectNormal);
  143. ` ).replace(
  144. '#include <project_vertex>',
  145. `vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );
  146. gl_Position = projectionMatrix * mvPosition;`
  147. );
  148. shader.vertexShader = vertexShader;
  149. };
  150. }
  151. /**
  152. * A helper class for making meshes bend aroudn curves
  153. */
  154. export class Flow {
  155. /**
  156. * @param {Mesh} mesh The mesh to clone and modify to bend around the curve
  157. * @param {number} numberOfCurves The amount of space that should preallocated for additional curves
  158. */
  159. constructor( mesh, numberOfCurves = 1 ) {
  160. const obj3D = mesh.clone();
  161. const splineTexure = initSplineTexture( numberOfCurves );
  162. const uniforms = getUniforms( splineTexure );
  163. obj3D.traverse( function ( child ) {
  164. if (
  165. child instanceof Mesh ||
  166. child instanceof InstancedMesh
  167. ) {
  168. child.material = child.material.clone();
  169. modifyShader( child.material, uniforms, numberOfCurves );
  170. }
  171. } );
  172. this.curveArray = new Array( numberOfCurves );
  173. this.curveLengthArray = new Array( numberOfCurves );
  174. this.object3D = obj3D;
  175. this.splineTexure = splineTexure;
  176. this.uniforms = uniforms;
  177. }
  178. updateCurve( index, curve ) {
  179. if ( index >= this.curveArray.length ) throw Error( 'Index out of range for Flow' );
  180. const curveLength = curve.getLength();
  181. this.uniforms.spineLength.value = curveLength;
  182. this.curveLengthArray[ index ] = curveLength;
  183. this.curveArray[ index ] = curve;
  184. updateSplineTexture( this.splineTexure, curve, index );
  185. }
  186. moveAlongCurve( amount ) {
  187. this.uniforms.pathOffset.value += amount;
  188. }
  189. }
  190. const matrix = new Matrix4();
  191. /**
  192. * A helper class for creating instanced versions of flow, where the instances are placed on the curve.
  193. */
  194. export class InstancedFlow extends Flow {
  195. /**
  196. *
  197. * @param {number} count The number of instanced elements
  198. * @param {number} curveCount The number of curves to preallocate for
  199. * @param {Geometry} geometry The geometry to use for the instanced mesh
  200. * @param {Material} material The material to use for the instanced mesh
  201. */
  202. constructor( count, curveCount, geometry, material ) {
  203. const mesh = new InstancedMesh(
  204. geometry,
  205. material,
  206. count
  207. );
  208. mesh.instanceMatrix.setUsage( DynamicDrawUsage );
  209. super( mesh, curveCount );
  210. this.offsets = new Array( count ).fill( 0 );
  211. this.whichCurve = new Array( count ).fill( 0 );
  212. }
  213. /**
  214. * The extra information about which curve and curve position is stored in the translation components of the matrix for the instanced objects
  215. * This writes that information to the matrix and marks it as needing update.
  216. *
  217. * @param {number} index of the instanced element to update
  218. */
  219. writeChanges( index ) {
  220. matrix.makeTranslation(
  221. this.curveLengthArray[ this.whichCurve[ index ] ],
  222. this.whichCurve[ index ],
  223. this.offsets[ index ]
  224. );
  225. this.object3D.setMatrixAt( index, matrix );
  226. this.object3D.instanceMatrix.needsUpdate = true;
  227. }
  228. /**
  229. * Move an individual element along the curve by a specific amount
  230. *
  231. * @param {number} index Which element to update
  232. * @param {number} offset Move by how much
  233. */
  234. moveIndividualAlongCurve( index, offset ) {
  235. this.offsets[ index ] += offset;
  236. this.writeChanges( index );
  237. }
  238. /**
  239. * Select which curve to use for an element
  240. *
  241. * @param {number} index the index of the instanced element to update
  242. * @param {number} curveNo the index of the curve it should use
  243. */
  244. setCurve( index, curveNo ) {
  245. if ( isNaN( curveNo ) ) throw Error( 'curve index being set is Not a Number (NaN)' );
  246. this.whichCurve[ index ] = curveNo;
  247. this.writeChanges( index );
  248. }
  249. }