LightningStrike.js 32 KB

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