CurveModifier.js 9.4 KB

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