CurveModifier.js 9.5 KB

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