LightningStrike.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  1. ( function () {
  2. /**
  3. * @fileoverview LightningStrike object for creating lightning strikes and voltaic arcs.
  4. *
  5. *
  6. * Usage
  7. *
  8. * var myRay = new LightningStrike( paramsObject );
  9. * var myRayMesh = new THREE.Mesh( myRay, myMaterial );
  10. * scene.add( myRayMesh );
  11. * ...
  12. * myRay.update( currentTime );
  13. *
  14. * The "currentTime" can vary its rate, go forwards, backwards or even jump, but it cannot be negative.
  15. *
  16. * You should normally leave the ray position to (0, 0, 0). You should control it by changing the sourceOffset and destOffset parameters.
  17. *
  18. *
  19. * LightningStrike parameters
  20. *
  21. * The paramsObject can contain any of the following parameters.
  22. *
  23. * Legend:
  24. * 'LightningStrike' (also called 'ray'): An independent voltaic arc with its ramifications and defined with a set of parameters.
  25. * 'Subray': A ramification of the ray. It is not a LightningStrike object.
  26. * 'Segment': A linear segment piece of a subray.
  27. * 'Leaf segment': A ray segment which cannot be smaller.
  28. *
  29. *
  30. * The following parameters can be changed any time and if they vary smoothly, the ray form will also change smoothly:
  31. *
  32. * @param {Vector3} sourceOffset The point where the ray starts.
  33. *
  34. * @param {Vector3} destOffset The point where the ray ends.
  35. *
  36. * @param {double} timeScale The rate at wich the ray form changes in time. Default: 1
  37. *
  38. * @param {double} roughness From 0 to 1. The higher the value, the more wrinkled is the ray. Default: 0.9
  39. *
  40. * @param {double} straightness From 0 to 1. The higher the value, the more straight will be a subray path. Default: 0.7
  41. *
  42. * @param {Vector3} up0 Ray 'up' direction at the ray starting point. Must be normalized. It should be perpendicular to the ray forward direction but it doesn't matter much.
  43. *
  44. * @param {Vector3} up1 Like the up0 parameter but at the end of the ray. Must be normalized.
  45. *
  46. * @param {double} radius0 Radius of the main ray trunk at the start point. Default: 1
  47. *
  48. * @param {double} radius1 Radius of the main ray trunk at the end point. Default: 1
  49. *
  50. * @param {double} radius0Factor The radius0 of a subray is this factor times the radius0 of its parent subray. Default: 0.5
  51. *
  52. * @param {double} radius1Factor The radius1 of a subray is this factor times the radius1 of its parent subray. Default: 0.2
  53. *
  54. * @param {minRadius} Minimum value a subray radius0 or radius1 can get. Default: 0.1
  55. *
  56. *
  57. * The following parameters should not be changed after lightning creation. They can be changed but the ray will change its form abruptly:
  58. *
  59. * @param {boolean} isEternal If true the ray never extinguishes. Otherwise its life is controlled by the 'birthTime' and 'deathTime' parameters. Default: true if any of those two parameters is undefined.
  60. *
  61. * @param {double} birthTime The time at which the ray starts its life and begins propagating. Only if isEternal is false. Default: None.
  62. *
  63. * @param {double} deathTime The time at which the ray ends vanishing and its life. Only if isEternal is false. Default: None.
  64. *
  65. * @param {double} propagationTimeFactor From 0 to 1. Lifetime factor at which the ray ends propagating and enters the steady phase. For example, 0.1 means it is propagating 1/10 of its lifetime. Default: 0.1
  66. *
  67. * @param {double} vanishingTimeFactor From 0 to 1. Lifetime factor at which the ray ends the steady phase and begins vanishing. For example, 0.9 means it is vanishing 1/10 of its lifetime. Default: 0.9
  68. *
  69. * @param {double} subrayPeriod Subrays cycle periodically. This is their time period. Default: 4
  70. *
  71. * @param {double} subrayDutyCycle From 0 to 1. This is the fraction of time a subray is active. Default: 0.6
  72. *
  73. *
  74. * These parameters cannot change after lightning creation:
  75. *
  76. * @param {integer} maxIterations: Greater than 0. The number of ray's leaf segments is 2**maxIterations. Default: 9
  77. *
  78. * @param {boolean} isStatic Set to true only for rays which won't change over time and are not attached to moving objects (Rare case). It is used to set the vertex buffers non-dynamic. You can omit calling update() for these rays.
  79. *
  80. * @param {integer} ramification Greater than 0. Maximum number of child subrays a subray can have. Default: 5
  81. *
  82. * @param {integer} maxSubrayRecursion Greater than 0. Maximum level of recursion (subray descendant generations). Default: 3
  83. *
  84. * @param {double} recursionProbability From 0 to 1. The lower the value, the less chance each new generation of subrays has to generate new subrays. Default: 0.6
  85. *
  86. * @param {boolean} generateUVs If true, the ray geometry will have uv coordinates generated. u runs along the ray, and v across its perimeter. Default: false.
  87. *
  88. * @param {Object} randomGenerator Set here your random number generator which will seed the THREE.SimplexNoise and other decisions during ray tree creation.
  89. * It can be used to generate repeatable rays. For that, set also the noiseSeed parameter, and each ray created with that generator and seed pair will be identical in time.
  90. * The randomGenerator parameter should be an object with a random() function similar to Math.random, but seedable.
  91. * It must have also a getSeed() method, which returns the current seed, and a setSeed( seed ) method, which accepts as seed a fractional number from 0 to 1, as well as any other number.
  92. * The default value is an internal generator for some uses and Math.random for others (It is non-repeatable even if noiseSeed is supplied)
  93. *
  94. * @param {double} noiseSeed Seed used to make repeatable rays (see the randomGenerator)
  95. *
  96. * @param {function} onDecideSubrayCreation Set this to change the callback which decides subray creation. You can look at the default callback in the code (createDefaultSubrayCreationCallbacks)for more info.
  97. *
  98. * @param {function} onSubrayCreation This is another callback, more simple than the previous one. It can be used to adapt the form of subrays or other parameters once a subray has been created and initialized. It is used in the examples to adapt subrays to a sphere or to a plane.
  99. *
  100. *
  101. */
  102. class LightningStrike extends THREE.BufferGeometry {
  103. constructor( rayParameters = {} ) {
  104. super();
  105. this.isLightningStrike = true;
  106. this.type = 'LightningStrike';
  107. // Set parameters, and set undefined parameters to default values
  108. this.init( LightningStrike.copyParameters( rayParameters, rayParameters ) );
  109. // Creates and populates the mesh
  110. this.createMesh();
  111. }
  112. static createRandomGenerator() {
  113. const numSeeds = 2053;
  114. const seeds = [];
  115. for ( let i = 0; i < numSeeds; i ++ ) {
  116. seeds.push( Math.random() );
  117. }
  118. const generator = {
  119. currentSeed: 0,
  120. random: function () {
  121. const value = seeds[ generator.currentSeed ];
  122. generator.currentSeed = ( generator.currentSeed + 1 ) % numSeeds;
  123. return value;
  124. },
  125. getSeed: function () {
  126. return generator.currentSeed / numSeeds;
  127. },
  128. setSeed: function ( seed ) {
  129. generator.currentSeed = Math.floor( seed * numSeeds ) % numSeeds;
  130. }
  131. };
  132. return generator;
  133. }
  134. static copyParameters( dest = {}, source = {} ) {
  135. const vecCopy = function ( v ) {
  136. if ( source === dest ) {
  137. return v;
  138. } else {
  139. return v.clone();
  140. }
  141. };
  142. dest.sourceOffset = source.sourceOffset !== undefined ? vecCopy( source.sourceOffset ) : new THREE.Vector3( 0, 100, 0 ), dest.destOffset = source.destOffset !== undefined ? vecCopy( source.destOffset ) : new THREE.Vector3( 0, 0, 0 ), dest.timeScale = source.timeScale !== undefined ? source.timeScale : 1, dest.roughness = source.roughness !== undefined ? source.roughness : 0.9, dest.straightness = source.straightness !== undefined ? source.straightness : 0.7, dest.up0 = source.up0 !== undefined ? vecCopy( source.up0 ) : new THREE.Vector3( 0, 0, 1 );
  143. dest.up1 = source.up1 !== undefined ? vecCopy( source.up1 ) : new THREE.Vector3( 0, 0, 1 ), dest.radius0 = source.radius0 !== undefined ? source.radius0 : 1, dest.radius1 = source.radius1 !== undefined ? source.radius1 : 1, dest.radius0Factor = source.radius0Factor !== undefined ? source.radius0Factor : 0.5, dest.radius1Factor = source.radius1Factor !== undefined ? source.radius1Factor : 0.2, dest.minRadius = source.minRadius !== undefined ? source.minRadius : 0.2,
  144. // These parameters should not be changed after lightning creation. They can be changed but the ray will change its form abruptly:
  145. dest.isEternal = source.isEternal !== undefined ? source.isEternal : source.birthTime === undefined || source.deathTime === undefined, dest.birthTime = source.birthTime, dest.deathTime = source.deathTime, dest.propagationTimeFactor = source.propagationTimeFactor !== undefined ? source.propagationTimeFactor : 0.1, dest.vanishingTimeFactor = source.vanishingTimeFactor !== undefined ? source.vanishingTimeFactor : 0.9, dest.subrayPeriod = source.subrayPeriod !== undefined ? source.subrayPeriod : 4, dest.subrayDutyCycle = source.subrayDutyCycle !== undefined ? source.subrayDutyCycle : 0.6;
  146. // These parameters cannot change after lightning creation:
  147. dest.maxIterations = source.maxIterations !== undefined ? source.maxIterations : 9;
  148. dest.isStatic = source.isStatic !== undefined ? source.isStatic : false;
  149. dest.ramification = source.ramification !== undefined ? source.ramification : 5;
  150. dest.maxSubrayRecursion = source.maxSubrayRecursion !== undefined ? source.maxSubrayRecursion : 3;
  151. dest.recursionProbability = source.recursionProbability !== undefined ? source.recursionProbability : 0.6;
  152. dest.generateUVs = source.generateUVs !== undefined ? source.generateUVs : false;
  153. dest.randomGenerator = source.randomGenerator, dest.noiseSeed = source.noiseSeed, dest.onDecideSubrayCreation = source.onDecideSubrayCreation, dest.onSubrayCreation = source.onSubrayCreation;
  154. return dest;
  155. }
  156. update( time ) {
  157. if ( this.isStatic ) return;
  158. if ( this.rayParameters.isEternal || this.rayParameters.birthTime <= time && time <= this.rayParameters.deathTime ) {
  159. this.updateMesh( time );
  160. if ( time < this.subrays[ 0 ].endPropagationTime ) {
  161. this.state = LightningStrike.RAY_PROPAGATING;
  162. } else if ( time > this.subrays[ 0 ].beginVanishingTime ) {
  163. this.state = LightningStrike.RAY_VANISHING;
  164. } else {
  165. this.state = LightningStrike.RAY_STEADY;
  166. }
  167. this.visible = true;
  168. } else {
  169. this.visible = false;
  170. if ( time < this.rayParameters.birthTime ) {
  171. this.state = LightningStrike.RAY_UNBORN;
  172. } else {
  173. this.state = LightningStrike.RAY_EXTINGUISHED;
  174. }
  175. }
  176. }
  177. init( rayParameters ) {
  178. // Init all the state from the parameters
  179. this.rayParameters = rayParameters;
  180. // These parameters cannot change after lightning creation:
  181. this.maxIterations = rayParameters.maxIterations !== undefined ? Math.floor( rayParameters.maxIterations ) : 9;
  182. rayParameters.maxIterations = this.maxIterations;
  183. this.isStatic = rayParameters.isStatic !== undefined ? rayParameters.isStatic : false;
  184. rayParameters.isStatic = this.isStatic;
  185. this.ramification = rayParameters.ramification !== undefined ? Math.floor( rayParameters.ramification ) : 5;
  186. rayParameters.ramification = this.ramification;
  187. this.maxSubrayRecursion = rayParameters.maxSubrayRecursion !== undefined ? Math.floor( rayParameters.maxSubrayRecursion ) : 3;
  188. rayParameters.maxSubrayRecursion = this.maxSubrayRecursion;
  189. this.recursionProbability = rayParameters.recursionProbability !== undefined ? rayParameters.recursionProbability : 0.6;
  190. rayParameters.recursionProbability = this.recursionProbability;
  191. this.generateUVs = rayParameters.generateUVs !== undefined ? rayParameters.generateUVs : false;
  192. rayParameters.generateUVs = this.generateUVs;
  193. // Random generator
  194. if ( rayParameters.randomGenerator !== undefined ) {
  195. this.randomGenerator = rayParameters.randomGenerator;
  196. this.seedGenerator = rayParameters.randomGenerator;
  197. if ( rayParameters.noiseSeed !== undefined ) {
  198. this.seedGenerator.setSeed( rayParameters.noiseSeed );
  199. }
  200. } else {
  201. this.randomGenerator = LightningStrike.createRandomGenerator();
  202. this.seedGenerator = Math;
  203. }
  204. // Ray creation callbacks
  205. if ( rayParameters.onDecideSubrayCreation !== undefined ) {
  206. this.onDecideSubrayCreation = rayParameters.onDecideSubrayCreation;
  207. } else {
  208. this.createDefaultSubrayCreationCallbacks();
  209. if ( rayParameters.onSubrayCreation !== undefined ) {
  210. this.onSubrayCreation = rayParameters.onSubrayCreation;
  211. }
  212. }
  213. // Internal state
  214. this.state = LightningStrike.RAY_INITIALIZED;
  215. this.maxSubrays = Math.ceil( 1 + Math.pow( this.ramification, Math.max( 0, this.maxSubrayRecursion - 1 ) ) );
  216. rayParameters.maxSubrays = this.maxSubrays;
  217. this.maxRaySegments = 2 * ( 1 << this.maxIterations );
  218. this.subrays = [];
  219. for ( let i = 0; i < this.maxSubrays; i ++ ) {
  220. this.subrays.push( this.createSubray() );
  221. }
  222. this.raySegments = [];
  223. for ( let i = 0; i < this.maxRaySegments; i ++ ) {
  224. this.raySegments.push( this.createSegment() );
  225. }
  226. this.time = 0;
  227. this.timeFraction = 0;
  228. this.currentSegmentCallback = null;
  229. this.currentCreateTriangleVertices = this.generateUVs ? this.createTriangleVerticesWithUVs : this.createTriangleVerticesWithoutUVs;
  230. this.numSubrays = 0;
  231. this.currentSubray = null;
  232. this.currentSegmentIndex = 0;
  233. this.isInitialSegment = false;
  234. this.subrayProbability = 0;
  235. this.currentVertex = 0;
  236. this.currentIndex = 0;
  237. this.currentCoordinate = 0;
  238. this.currentUVCoordinate = 0;
  239. this.vertices = null;
  240. this.uvs = null;
  241. this.indices = null;
  242. this.positionAttribute = null;
  243. this.uvsAttribute = null;
  244. this.simplexX = new THREE.SimplexNoise( this.seedGenerator );
  245. this.simplexY = new THREE.SimplexNoise( this.seedGenerator );
  246. this.simplexZ = new THREE.SimplexNoise( this.seedGenerator );
  247. // Temp vectors
  248. this.forwards = new THREE.Vector3();
  249. this.forwardsFill = new THREE.Vector3();
  250. this.side = new THREE.Vector3();
  251. this.down = new THREE.Vector3();
  252. this.middlePos = new THREE.Vector3();
  253. this.middleLinPos = new THREE.Vector3();
  254. this.newPos = new THREE.Vector3();
  255. this.vPos = new THREE.Vector3();
  256. this.cross1 = new THREE.Vector3();
  257. }
  258. createMesh() {
  259. const maxDrawableSegmentsPerSubRay = 1 << this.maxIterations;
  260. const maxVerts = 3 * ( maxDrawableSegmentsPerSubRay + 1 ) * this.maxSubrays;
  261. const maxIndices = 18 * maxDrawableSegmentsPerSubRay * this.maxSubrays;
  262. this.vertices = new Float32Array( maxVerts * 3 );
  263. this.indices = new Uint32Array( maxIndices );
  264. if ( this.generateUVs ) {
  265. this.uvs = new Float32Array( maxVerts * 2 );
  266. }
  267. // Populate the mesh
  268. this.fillMesh( 0 );
  269. this.setIndex( new THREE.Uint32BufferAttribute( this.indices, 1 ) );
  270. this.positionAttribute = new THREE.Float32BufferAttribute( this.vertices, 3 );
  271. this.setAttribute( 'position', this.positionAttribute );
  272. if ( this.generateUVs ) {
  273. this.uvsAttribute = new THREE.Float32BufferAttribute( new Float32Array( this.uvs ), 2 );
  274. this.setAttribute( 'uv', this.uvsAttribute );
  275. }
  276. if ( ! this.isStatic ) {
  277. this.index.usage = THREE.DynamicDrawUsage;
  278. this.positionAttribute.usage = THREE.DynamicDrawUsage;
  279. if ( this.generateUVs ) {
  280. this.uvsAttribute.usage = THREE.DynamicDrawUsage;
  281. }
  282. }
  283. // Store buffers for later modification
  284. this.vertices = this.positionAttribute.array;
  285. this.indices = this.index.array;
  286. if ( this.generateUVs ) {
  287. this.uvs = this.uvsAttribute.array;
  288. }
  289. }
  290. updateMesh( time ) {
  291. this.fillMesh( time );
  292. this.drawRange.count = this.currentIndex;
  293. this.index.needsUpdate = true;
  294. this.positionAttribute.needsUpdate = true;
  295. if ( this.generateUVs ) {
  296. this.uvsAttribute.needsUpdate = true;
  297. }
  298. }
  299. fillMesh( time ) {
  300. const scope = this;
  301. this.currentVertex = 0;
  302. this.currentIndex = 0;
  303. this.currentCoordinate = 0;
  304. this.currentUVCoordinate = 0;
  305. this.fractalRay( time, function fillVertices( segment ) {
  306. const subray = scope.currentSubray;
  307. if ( time < subray.birthTime ) {
  308. //&& ( ! this.rayParameters.isEternal || scope.currentSubray.recursion > 0 ) ) {
  309. return;
  310. } else if ( this.rayParameters.isEternal && scope.currentSubray.recursion == 0 ) {
  311. // Eternal rays don't propagate nor vanish, but its subrays do
  312. scope.createPrism( segment );
  313. scope.onDecideSubrayCreation( segment, scope );
  314. } else if ( time < subray.endPropagationTime ) {
  315. if ( scope.timeFraction >= segment.fraction0 * subray.propagationTimeFactor ) {
  316. // Ray propagation has arrived to this segment
  317. scope.createPrism( segment );
  318. scope.onDecideSubrayCreation( segment, scope );
  319. }
  320. } else if ( time < subray.beginVanishingTime ) {
  321. // Ray is steady (nor propagating nor vanishing)
  322. scope.createPrism( segment );
  323. scope.onDecideSubrayCreation( segment, scope );
  324. } else {
  325. if ( scope.timeFraction <= subray.vanishingTimeFactor + segment.fraction1 * ( 1 - subray.vanishingTimeFactor ) ) {
  326. // Segment has not yet vanished
  327. scope.createPrism( segment );
  328. }
  329. scope.onDecideSubrayCreation( segment, scope );
  330. }
  331. } );
  332. }
  333. addNewSubray() {
  334. return this.subrays[ this.numSubrays ++ ];
  335. }
  336. initSubray( subray, rayParameters ) {
  337. subray.pos0.copy( rayParameters.sourceOffset );
  338. subray.pos1.copy( rayParameters.destOffset );
  339. subray.up0.copy( rayParameters.up0 );
  340. subray.up1.copy( rayParameters.up1 );
  341. subray.radius0 = rayParameters.radius0;
  342. subray.radius1 = rayParameters.radius1;
  343. subray.birthTime = rayParameters.birthTime;
  344. subray.deathTime = rayParameters.deathTime;
  345. subray.timeScale = rayParameters.timeScale;
  346. subray.roughness = rayParameters.roughness;
  347. subray.straightness = rayParameters.straightness;
  348. subray.propagationTimeFactor = rayParameters.propagationTimeFactor;
  349. subray.vanishingTimeFactor = rayParameters.vanishingTimeFactor;
  350. subray.maxIterations = this.maxIterations;
  351. subray.seed = rayParameters.noiseSeed !== undefined ? rayParameters.noiseSeed : 0;
  352. subray.recursion = 0;
  353. }
  354. fractalRay( time, segmentCallback ) {
  355. this.time = time;
  356. this.currentSegmentCallback = segmentCallback;
  357. this.numSubrays = 0;
  358. // Add the top level subray
  359. this.initSubray( this.addNewSubray(), this.rayParameters );
  360. // Process all subrays that are being generated until consuming all of them
  361. for ( let subrayIndex = 0; subrayIndex < this.numSubrays; subrayIndex ++ ) {
  362. const subray = this.subrays[ subrayIndex ];
  363. this.currentSubray = subray;
  364. this.randomGenerator.setSeed( subray.seed );
  365. subray.endPropagationTime = THREE.MathUtils.lerp( subray.birthTime, subray.deathTime, subray.propagationTimeFactor );
  366. subray.beginVanishingTime = THREE.MathUtils.lerp( subray.deathTime, subray.birthTime, 1 - subray.vanishingTimeFactor );
  367. const random1 = this.randomGenerator.random;
  368. subray.linPos0.set( random1(), random1(), random1() ).multiplyScalar( 1000 );
  369. subray.linPos1.set( random1(), random1(), random1() ).multiplyScalar( 1000 );
  370. this.timeFraction = ( time - subray.birthTime ) / ( subray.deathTime - subray.birthTime );
  371. this.currentSegmentIndex = 0;
  372. this.isInitialSegment = true;
  373. const segment = this.getNewSegment();
  374. segment.iteration = 0;
  375. segment.pos0.copy( subray.pos0 );
  376. segment.pos1.copy( subray.pos1 );
  377. segment.linPos0.copy( subray.linPos0 );
  378. segment.linPos1.copy( subray.linPos1 );
  379. segment.up0.copy( subray.up0 );
  380. segment.up1.copy( subray.up1 );
  381. segment.radius0 = subray.radius0;
  382. segment.radius1 = subray.radius1;
  383. segment.fraction0 = 0;
  384. segment.fraction1 = 1;
  385. segment.positionVariationFactor = 1 - subray.straightness;
  386. this.subrayProbability = this.ramification * Math.pow( this.recursionProbability, subray.recursion ) / ( 1 << subray.maxIterations );
  387. this.fractalRayRecursive( segment );
  388. }
  389. this.currentSegmentCallback = null;
  390. this.currentSubray = null;
  391. }
  392. fractalRayRecursive( segment ) {
  393. // Leave recursion condition
  394. if ( segment.iteration >= this.currentSubray.maxIterations ) {
  395. this.currentSegmentCallback( segment );
  396. return;
  397. }
  398. // Interpolation
  399. this.forwards.subVectors( segment.pos1, segment.pos0 );
  400. let lForwards = this.forwards.length();
  401. if ( lForwards < 0.000001 ) {
  402. this.forwards.set( 0, 0, 0.01 );
  403. lForwards = this.forwards.length();
  404. }
  405. const middleRadius = ( segment.radius0 + segment.radius1 ) * 0.5;
  406. const middleFraction = ( segment.fraction0 + segment.fraction1 ) * 0.5;
  407. const timeDimension = this.time * this.currentSubray.timeScale * Math.pow( 2, segment.iteration );
  408. this.middlePos.lerpVectors( segment.pos0, segment.pos1, 0.5 );
  409. this.middleLinPos.lerpVectors( segment.linPos0, segment.linPos1, 0.5 );
  410. const p = this.middleLinPos;
  411. // Noise
  412. this.newPos.set( this.simplexX.noise4d( p.x, p.y, p.z, timeDimension ), this.simplexY.noise4d( p.x, p.y, p.z, timeDimension ), this.simplexZ.noise4d( p.x, p.y, p.z, timeDimension ) );
  413. this.newPos.multiplyScalar( segment.positionVariationFactor * lForwards );
  414. this.newPos.add( this.middlePos );
  415. // Recursion
  416. const newSegment1 = this.getNewSegment();
  417. newSegment1.pos0.copy( segment.pos0 );
  418. newSegment1.pos1.copy( this.newPos );
  419. newSegment1.linPos0.copy( segment.linPos0 );
  420. newSegment1.linPos1.copy( this.middleLinPos );
  421. newSegment1.up0.copy( segment.up0 );
  422. newSegment1.up1.copy( segment.up1 );
  423. newSegment1.radius0 = segment.radius0;
  424. newSegment1.radius1 = middleRadius;
  425. newSegment1.fraction0 = segment.fraction0;
  426. newSegment1.fraction1 = middleFraction;
  427. newSegment1.positionVariationFactor = segment.positionVariationFactor * this.currentSubray.roughness;
  428. newSegment1.iteration = segment.iteration + 1;
  429. const newSegment2 = this.getNewSegment();
  430. newSegment2.pos0.copy( this.newPos );
  431. newSegment2.pos1.copy( segment.pos1 );
  432. newSegment2.linPos0.copy( this.middleLinPos );
  433. newSegment2.linPos1.copy( segment.linPos1 );
  434. this.cross1.crossVectors( segment.up0, this.forwards.normalize() );
  435. newSegment2.up0.crossVectors( this.forwards, this.cross1 ).normalize();
  436. newSegment2.up1.copy( segment.up1 );
  437. newSegment2.radius0 = middleRadius;
  438. newSegment2.radius1 = segment.radius1;
  439. newSegment2.fraction0 = middleFraction;
  440. newSegment2.fraction1 = segment.fraction1;
  441. newSegment2.positionVariationFactor = segment.positionVariationFactor * this.currentSubray.roughness;
  442. newSegment2.iteration = segment.iteration + 1;
  443. this.fractalRayRecursive( newSegment1 );
  444. this.fractalRayRecursive( newSegment2 );
  445. }
  446. createPrism( segment ) {
  447. // Creates one triangular prism and its vertices at the segment
  448. this.forwardsFill.subVectors( segment.pos1, segment.pos0 ).normalize();
  449. if ( this.isInitialSegment ) {
  450. this.currentCreateTriangleVertices( segment.pos0, segment.up0, this.forwardsFill, segment.radius0, 0 );
  451. this.isInitialSegment = false;
  452. }
  453. this.currentCreateTriangleVertices( segment.pos1, segment.up0, this.forwardsFill, segment.radius1, segment.fraction1 );
  454. this.createPrismFaces();
  455. }
  456. createTriangleVerticesWithoutUVs( pos, up, forwards, radius ) {
  457. // Create an equilateral triangle (only vertices)
  458. this.side.crossVectors( up, forwards ).multiplyScalar( radius * LightningStrike.COS30DEG );
  459. this.down.copy( up ).multiplyScalar( - radius * LightningStrike.SIN30DEG );
  460. const p = this.vPos;
  461. const v = this.vertices;
  462. p.copy( pos ).sub( this.side ).add( this.down );
  463. v[ this.currentCoordinate ++ ] = p.x;
  464. v[ this.currentCoordinate ++ ] = p.y;
  465. v[ this.currentCoordinate ++ ] = p.z;
  466. p.copy( pos ).add( this.side ).add( this.down );
  467. v[ this.currentCoordinate ++ ] = p.x;
  468. v[ this.currentCoordinate ++ ] = p.y;
  469. v[ this.currentCoordinate ++ ] = p.z;
  470. p.copy( up ).multiplyScalar( radius ).add( pos );
  471. v[ this.currentCoordinate ++ ] = p.x;
  472. v[ this.currentCoordinate ++ ] = p.y;
  473. v[ this.currentCoordinate ++ ] = p.z;
  474. this.currentVertex += 3;
  475. }
  476. createTriangleVerticesWithUVs( pos, up, forwards, radius, u ) {
  477. // Create an equilateral triangle (only vertices)
  478. this.side.crossVectors( up, forwards ).multiplyScalar( radius * LightningStrike.COS30DEG );
  479. this.down.copy( up ).multiplyScalar( - radius * LightningStrike.SIN30DEG );
  480. const p = this.vPos;
  481. const v = this.vertices;
  482. const uv = this.uvs;
  483. p.copy( pos ).sub( this.side ).add( this.down );
  484. v[ this.currentCoordinate ++ ] = p.x;
  485. v[ this.currentCoordinate ++ ] = p.y;
  486. v[ this.currentCoordinate ++ ] = p.z;
  487. uv[ this.currentUVCoordinate ++ ] = u;
  488. uv[ this.currentUVCoordinate ++ ] = 0;
  489. p.copy( pos ).add( this.side ).add( this.down );
  490. v[ this.currentCoordinate ++ ] = p.x;
  491. v[ this.currentCoordinate ++ ] = p.y;
  492. v[ this.currentCoordinate ++ ] = p.z;
  493. uv[ this.currentUVCoordinate ++ ] = u;
  494. uv[ this.currentUVCoordinate ++ ] = 0.5;
  495. p.copy( up ).multiplyScalar( radius ).add( pos );
  496. v[ this.currentCoordinate ++ ] = p.x;
  497. v[ this.currentCoordinate ++ ] = p.y;
  498. v[ this.currentCoordinate ++ ] = p.z;
  499. uv[ this.currentUVCoordinate ++ ] = u;
  500. uv[ this.currentUVCoordinate ++ ] = 1;
  501. this.currentVertex += 3;
  502. }
  503. createPrismFaces( vertex /*, index*/ ) {
  504. const indices = this.indices;
  505. vertex = this.currentVertex - 6;
  506. indices[ this.currentIndex ++ ] = vertex + 1;
  507. indices[ this.currentIndex ++ ] = vertex + 2;
  508. indices[ this.currentIndex ++ ] = vertex + 5;
  509. indices[ this.currentIndex ++ ] = vertex + 1;
  510. indices[ this.currentIndex ++ ] = vertex + 5;
  511. indices[ this.currentIndex ++ ] = vertex + 4;
  512. indices[ this.currentIndex ++ ] = vertex + 0;
  513. indices[ this.currentIndex ++ ] = vertex + 1;
  514. indices[ this.currentIndex ++ ] = vertex + 4;
  515. indices[ this.currentIndex ++ ] = vertex + 0;
  516. indices[ this.currentIndex ++ ] = vertex + 4;
  517. indices[ this.currentIndex ++ ] = vertex + 3;
  518. indices[ this.currentIndex ++ ] = vertex + 2;
  519. indices[ this.currentIndex ++ ] = vertex + 0;
  520. indices[ this.currentIndex ++ ] = vertex + 3;
  521. indices[ this.currentIndex ++ ] = vertex + 2;
  522. indices[ this.currentIndex ++ ] = vertex + 3;
  523. indices[ this.currentIndex ++ ] = vertex + 5;
  524. }
  525. createDefaultSubrayCreationCallbacks() {
  526. const random1 = this.randomGenerator.random;
  527. this.onDecideSubrayCreation = function ( segment, lightningStrike ) {
  528. // Decide subrays creation at parent (sub)ray segment
  529. const subray = lightningStrike.currentSubray;
  530. const period = lightningStrike.rayParameters.subrayPeriod;
  531. const dutyCycle = lightningStrike.rayParameters.subrayDutyCycle;
  532. const phase0 = lightningStrike.rayParameters.isEternal && subray.recursion == 0 ? - random1() * period : THREE.MathUtils.lerp( subray.birthTime, subray.endPropagationTime, segment.fraction0 ) - random1() * period;
  533. const phase = lightningStrike.time - phase0;
  534. const currentCycle = Math.floor( phase / period );
  535. const childSubraySeed = random1() * ( currentCycle + 1 );
  536. const isActive = phase % period <= dutyCycle * period;
  537. let probability = 0;
  538. if ( isActive ) {
  539. probability = lightningStrike.subrayProbability;
  540. // Distribution test: probability *= segment.fraction0 > 0.5 && segment.fraction0 < 0.9 ? 1 / 0.4 : 0;
  541. }
  542. if ( subray.recursion < lightningStrike.maxSubrayRecursion && lightningStrike.numSubrays < lightningStrike.maxSubrays && random1() < probability ) {
  543. const childSubray = lightningStrike.addNewSubray();
  544. const parentSeed = lightningStrike.randomGenerator.getSeed();
  545. childSubray.seed = childSubraySeed;
  546. lightningStrike.randomGenerator.setSeed( childSubraySeed );
  547. childSubray.recursion = subray.recursion + 1;
  548. childSubray.maxIterations = Math.max( 1, subray.maxIterations - 1 );
  549. childSubray.linPos0.set( random1(), random1(), random1() ).multiplyScalar( 1000 );
  550. childSubray.linPos1.set( random1(), random1(), random1() ).multiplyScalar( 1000 );
  551. childSubray.up0.copy( subray.up0 );
  552. childSubray.up1.copy( subray.up1 );
  553. childSubray.radius0 = segment.radius0 * lightningStrike.rayParameters.radius0Factor;
  554. childSubray.radius1 = Math.min( lightningStrike.rayParameters.minRadius, segment.radius1 * lightningStrike.rayParameters.radius1Factor );
  555. childSubray.birthTime = phase0 + currentCycle * period;
  556. childSubray.deathTime = childSubray.birthTime + period * dutyCycle;
  557. if ( ! lightningStrike.rayParameters.isEternal && subray.recursion == 0 ) {
  558. childSubray.birthTime = Math.max( childSubray.birthTime, subray.birthTime );
  559. childSubray.deathTime = Math.min( childSubray.deathTime, subray.deathTime );
  560. }
  561. childSubray.timeScale = subray.timeScale * 2;
  562. childSubray.roughness = subray.roughness;
  563. childSubray.straightness = subray.straightness;
  564. childSubray.propagationTimeFactor = subray.propagationTimeFactor;
  565. childSubray.vanishingTimeFactor = subray.vanishingTimeFactor;
  566. lightningStrike.onSubrayCreation( segment, subray, childSubray, lightningStrike );
  567. lightningStrike.randomGenerator.setSeed( parentSeed );
  568. }
  569. };
  570. const vec1Pos = new THREE.Vector3();
  571. const vec2Forward = new THREE.Vector3();
  572. const vec3Side = new THREE.Vector3();
  573. const vec4Up = new THREE.Vector3();
  574. this.onSubrayCreation = function ( segment, parentSubray, childSubray, lightningStrike ) {
  575. // Decide childSubray origin and destination positions (pos0 and pos1) and possibly other properties of childSubray
  576. // Just use the default cone position generator
  577. lightningStrike.subrayCylinderPosition( segment, parentSubray, childSubray, 0.5, 0.6, 0.2 );
  578. };
  579. this.subrayConePosition = function ( segment, parentSubray, childSubray, heightFactor, sideWidthFactor, minSideWidthFactor ) {
  580. // Sets childSubray pos0 and pos1 in a cone
  581. childSubray.pos0.copy( segment.pos0 );
  582. vec1Pos.subVectors( parentSubray.pos1, parentSubray.pos0 );
  583. vec2Forward.copy( vec1Pos ).normalize();
  584. vec1Pos.multiplyScalar( segment.fraction0 + ( 1 - segment.fraction0 ) * ( random1() * heightFactor ) );
  585. const length = vec1Pos.length();
  586. vec3Side.crossVectors( parentSubray.up0, vec2Forward );
  587. const angle = 2 * Math.PI * random1();
  588. vec3Side.multiplyScalar( Math.cos( angle ) );
  589. vec4Up.copy( parentSubray.up0 ).multiplyScalar( Math.sin( angle ) );
  590. childSubray.pos1.copy( vec3Side ).add( vec4Up ).multiplyScalar( length * sideWidthFactor * ( minSideWidthFactor + random1() * ( 1 - minSideWidthFactor ) ) ).add( vec1Pos ).add( parentSubray.pos0 );
  591. };
  592. this.subrayCylinderPosition = function ( segment, parentSubray, childSubray, heightFactor, sideWidthFactor, minSideWidthFactor ) {
  593. // Sets childSubray pos0 and pos1 in a cylinder
  594. childSubray.pos0.copy( segment.pos0 );
  595. vec1Pos.subVectors( parentSubray.pos1, parentSubray.pos0 );
  596. vec2Forward.copy( vec1Pos ).normalize();
  597. vec1Pos.multiplyScalar( segment.fraction0 + ( 1 - segment.fraction0 ) * ( ( 2 * random1() - 1 ) * heightFactor ) );
  598. const length = vec1Pos.length();
  599. vec3Side.crossVectors( parentSubray.up0, vec2Forward );
  600. const angle = 2 * Math.PI * random1();
  601. vec3Side.multiplyScalar( Math.cos( angle ) );
  602. vec4Up.copy( parentSubray.up0 ).multiplyScalar( Math.sin( angle ) );
  603. childSubray.pos1.copy( vec3Side ).add( vec4Up ).multiplyScalar( length * sideWidthFactor * ( minSideWidthFactor + random1() * ( 1 - minSideWidthFactor ) ) ).add( vec1Pos ).add( parentSubray.pos0 );
  604. };
  605. }
  606. createSubray() {
  607. return {
  608. seed: 0,
  609. maxIterations: 0,
  610. recursion: 0,
  611. pos0: new THREE.Vector3(),
  612. pos1: new THREE.Vector3(),
  613. linPos0: new THREE.Vector3(),
  614. linPos1: new THREE.Vector3(),
  615. up0: new THREE.Vector3(),
  616. up1: new THREE.Vector3(),
  617. radius0: 0,
  618. radius1: 0,
  619. birthTime: 0,
  620. deathTime: 0,
  621. timeScale: 0,
  622. roughness: 0,
  623. straightness: 0,
  624. propagationTimeFactor: 0,
  625. vanishingTimeFactor: 0,
  626. endPropagationTime: 0,
  627. beginVanishingTime: 0
  628. };
  629. }
  630. createSegment() {
  631. return {
  632. iteration: 0,
  633. pos0: new THREE.Vector3(),
  634. pos1: new THREE.Vector3(),
  635. linPos0: new THREE.Vector3(),
  636. linPos1: new THREE.Vector3(),
  637. up0: new THREE.Vector3(),
  638. up1: new THREE.Vector3(),
  639. radius0: 0,
  640. radius1: 0,
  641. fraction0: 0,
  642. fraction1: 0,
  643. positionVariationFactor: 0
  644. };
  645. }
  646. getNewSegment() {
  647. return this.raySegments[ this.currentSegmentIndex ++ ];
  648. }
  649. copy( source ) {
  650. super.copy( source );
  651. this.init( LightningStrike.copyParameters( {}, source.rayParameters ) );
  652. return this;
  653. }
  654. clone() {
  655. return new this.constructor( LightningStrike.copyParameters( {}, this.rayParameters ) );
  656. }
  657. }
  658. // Ray states
  659. LightningStrike.RAY_INITIALIZED = 0;
  660. LightningStrike.RAY_UNBORN = 1;
  661. LightningStrike.RAY_PROPAGATING = 2;
  662. LightningStrike.RAY_STEADY = 3;
  663. LightningStrike.RAY_VANISHING = 4;
  664. LightningStrike.RAY_EXTINGUISHED = 5;
  665. LightningStrike.COS30DEG = Math.cos( 30 * Math.PI / 180 );
  666. LightningStrike.SIN30DEG = Math.sin( 30 * Math.PI / 180 );
  667. THREE.LightningStrike = LightningStrike;
  668. } )();