LightningStrike.js 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018
  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. var LightningStrike = function ( rayParameters ) {
  111. BufferGeometry.call( this );
  112. this.type = 'LightningStrike';
  113. // Set parameters, and set undefined parameters to default values
  114. rayParameters = rayParameters || {};
  115. this.init( LightningStrike.copyParameters( rayParameters, rayParameters ) );
  116. // Creates and populates the mesh
  117. this.createMesh();
  118. };
  119. LightningStrike.prototype = Object.create( BufferGeometry.prototype );
  120. LightningStrike.prototype.constructor = LightningStrike;
  121. LightningStrike.prototype.isLightningStrike = true;
  122. // Ray states
  123. LightningStrike.RAY_INITIALIZED = 0;
  124. LightningStrike.RAY_UNBORN = 1;
  125. LightningStrike.RAY_PROPAGATING = 2;
  126. LightningStrike.RAY_STEADY = 3;
  127. LightningStrike.RAY_VANISHING = 4;
  128. LightningStrike.RAY_EXTINGUISHED = 5;
  129. LightningStrike.COS30DEG = Math.cos( 30 * Math.PI / 180 );
  130. LightningStrike.SIN30DEG = Math.sin( 30 * Math.PI / 180 );
  131. LightningStrike.createRandomGenerator = function () {
  132. var numSeeds = 2053;
  133. var seeds = [];
  134. for ( var i = 0; i < numSeeds; i ++ ) {
  135. seeds.push( Math.random() );
  136. }
  137. var generator = {
  138. currentSeed: 0,
  139. random: function () {
  140. var value = seeds[ generator.currentSeed ];
  141. generator.currentSeed = ( generator.currentSeed + 1 ) % numSeeds;
  142. return value;
  143. },
  144. getSeed: function () {
  145. return generator.currentSeed / numSeeds;
  146. },
  147. setSeed: function ( seed ) {
  148. generator.currentSeed = Math.floor( seed * numSeeds ) % numSeeds;
  149. }
  150. };
  151. return generator;
  152. };
  153. LightningStrike.copyParameters = function ( dest, source ) {
  154. source = source || {};
  155. dest = dest || {};
  156. var vecCopy = function ( v ) {
  157. if ( source === dest ) {
  158. return v;
  159. } else {
  160. return v.clone();
  161. }
  162. };
  163. dest.sourceOffset = source.sourceOffset !== undefined ? vecCopy( source.sourceOffset ) : new Vector3( 0, 100, 0 ),
  164. dest.destOffset = source.destOffset !== undefined ? vecCopy( source.destOffset ) : new Vector3( 0, 0, 0 ),
  165. dest.timeScale = source.timeScale !== undefined ? source.timeScale : 1,
  166. dest.roughness = source.roughness !== undefined ? source.roughness : 0.9,
  167. dest.straightness = source.straightness !== undefined ? source.straightness : 0.7,
  168. dest.up0 = source.up0 !== undefined ? vecCopy( source.up0 ) : new Vector3( 0, 0, 1 );
  169. dest.up1 = source.up1 !== undefined ? vecCopy( source.up1 ) : new Vector3( 0, 0, 1 ),
  170. dest.radius0 = source.radius0 !== undefined ? source.radius0 : 1,
  171. dest.radius1 = source.radius1 !== undefined ? source.radius1 : 1,
  172. dest.radius0Factor = source.radius0Factor !== undefined ? source.radius0Factor : 0.5,
  173. dest.radius1Factor = source.radius1Factor !== undefined ? source.radius1Factor : 0.2,
  174. dest.minRadius = source.minRadius !== undefined ? source.minRadius : 0.2,
  175. // These parameters should not be changed after lightning creation. They can be changed but the ray will change its form abruptly:
  176. dest.isEternal = source.isEternal !== undefined ? source.isEternal : ( source.birthTime === undefined || source.deathTime === undefined ),
  177. dest.birthTime = source.birthTime,
  178. dest.deathTime = source.deathTime,
  179. dest.propagationTimeFactor = source.propagationTimeFactor !== undefined ? source.propagationTimeFactor : 0.1,
  180. dest.vanishingTimeFactor = source.vanishingTimeFactor !== undefined ? source.vanishingTimeFactor : 0.9,
  181. dest.subrayPeriod = source.subrayPeriod !== undefined ? source.subrayPeriod : 4,
  182. dest.subrayDutyCycle = source.subrayDutyCycle !== undefined ? source.subrayDutyCycle : 0.6;
  183. // These parameters cannot change after lightning creation:
  184. dest.maxIterations = source.maxIterations !== undefined ? source.maxIterations : 9;
  185. dest.isStatic = source.isStatic !== undefined ? source.isStatic : false;
  186. dest.ramification = source.ramification !== undefined ? source.ramification : 5;
  187. dest.maxSubrayRecursion = source.maxSubrayRecursion !== undefined ? source.maxSubrayRecursion : 3;
  188. dest.recursionProbability = source.recursionProbability !== undefined ? source.recursionProbability : 0.6;
  189. dest.generateUVs = source.generateUVs !== undefined ? source.generateUVs : false;
  190. dest.randomGenerator = source.randomGenerator,
  191. dest.noiseSeed = source.noiseSeed,
  192. dest.onDecideSubrayCreation = source.onDecideSubrayCreation,
  193. dest.onSubrayCreation = source.onSubrayCreation;
  194. return dest;
  195. };
  196. LightningStrike.prototype.update = function ( time ) {
  197. if ( this.isStatic ) return;
  198. if ( this.rayParameters.isEternal || ( this.rayParameters.birthTime <= time && time <= this.rayParameters.deathTime ) ) {
  199. this.updateMesh( time );
  200. if ( time < this.subrays[ 0 ].endPropagationTime ) {
  201. this.state = LightningStrike.RAY_PROPAGATING;
  202. } else if ( time > this.subrays[ 0 ].beginVanishingTime ) {
  203. this.state = LightningStrike.RAY_VANISHING;
  204. } else {
  205. this.state = LightningStrike.RAY_STEADY;
  206. }
  207. this.visible = true;
  208. } else {
  209. this.visible = false;
  210. if ( time < this.rayParameters.birthTime ) {
  211. this.state = LightningStrike.RAY_UNBORN;
  212. } else {
  213. this.state = LightningStrike.RAY_EXTINGUISHED;
  214. }
  215. }
  216. };
  217. LightningStrike.prototype.init = function ( rayParameters ) {
  218. // Init all the state from the parameters
  219. this.rayParameters = rayParameters;
  220. // These parameters cannot change after lightning creation:
  221. this.maxIterations = rayParameters.maxIterations !== undefined ? Math.floor( rayParameters.maxIterations ) : 9;
  222. rayParameters.maxIterations = this.maxIterations;
  223. this.isStatic = rayParameters.isStatic !== undefined ? rayParameters.isStatic : false;
  224. rayParameters.isStatic = this.isStatic;
  225. this.ramification = rayParameters.ramification !== undefined ? Math.floor( rayParameters.ramification ) : 5;
  226. rayParameters.ramification = this.ramification;
  227. this.maxSubrayRecursion = rayParameters.maxSubrayRecursion !== undefined ? Math.floor( rayParameters.maxSubrayRecursion ) : 3;
  228. rayParameters.maxSubrayRecursion = this.maxSubrayRecursion;
  229. this.recursionProbability = rayParameters.recursionProbability !== undefined ? rayParameters.recursionProbability : 0.6;
  230. rayParameters.recursionProbability = this.recursionProbability;
  231. this.generateUVs = rayParameters.generateUVs !== undefined ? rayParameters.generateUVs : false;
  232. rayParameters.generateUVs = this.generateUVs;
  233. // Random generator
  234. if ( rayParameters.randomGenerator !== undefined ) {
  235. this.randomGenerator = rayParameters.randomGenerator;
  236. this.seedGenerator = rayParameters.randomGenerator;
  237. if ( rayParameters.noiseSeed !== undefined ) {
  238. this.seedGenerator.setSeed( rayParameters.noiseSeed );
  239. }
  240. } else {
  241. this.randomGenerator = LightningStrike.createRandomGenerator();
  242. this.seedGenerator = Math;
  243. }
  244. // Ray creation callbacks
  245. if ( rayParameters.onDecideSubrayCreation !== undefined ) {
  246. this.onDecideSubrayCreation = rayParameters.onDecideSubrayCreation;
  247. } else {
  248. this.createDefaultSubrayCreationCallbacks();
  249. if ( rayParameters.onSubrayCreation !== undefined ) {
  250. this.onSubrayCreation = rayParameters.onSubrayCreation;
  251. }
  252. }
  253. // Internal state
  254. this.state = LightningStrike.RAY_INITIALIZED;
  255. this.maxSubrays = Math.ceil( 1 + Math.pow( this.ramification, Math.max( 0, this.maxSubrayRecursion - 1 ) ) );
  256. rayParameters.maxSubrays = this.maxSubrays;
  257. this.maxRaySegments = 2 * ( 1 << this.maxIterations );
  258. this.subrays = [];
  259. for ( var i = 0; i < this.maxSubrays; i ++ ) {
  260. this.subrays.push( this.createSubray() );
  261. }
  262. this.raySegments = [];
  263. for ( var i = 0; i < this.maxRaySegments; i ++ ) {
  264. this.raySegments.push( this.createSegment() );
  265. }
  266. this.time = 0;
  267. this.timeFraction = 0;
  268. this.currentSegmentCallback = null;
  269. this.currentCreateTriangleVertices = this.generateUVs ? this.createTriangleVerticesWithUVs : this.createTriangleVerticesWithoutUVs;
  270. this.numSubrays = 0;
  271. this.currentSubray = null;
  272. this.currentSegmentIndex = 0;
  273. this.isInitialSegment = false;
  274. this.subrayProbability = 0;
  275. this.currentVertex = 0;
  276. this.currentIndex = 0;
  277. this.currentCoordinate = 0;
  278. this.currentUVCoordinate = 0;
  279. this.vertices = null;
  280. this.uvs = null;
  281. this.indices = null;
  282. this.positionAttribute = null;
  283. this.uvsAttribute = null;
  284. this.simplexX = new SimplexNoise( this.seedGenerator );
  285. this.simplexY = new SimplexNoise( this.seedGenerator );
  286. this.simplexZ = new SimplexNoise( this.seedGenerator );
  287. // Temp vectors
  288. this.forwards = new Vector3();
  289. this.forwardsFill = new Vector3();
  290. this.side = new Vector3();
  291. this.down = new Vector3();
  292. this.middlePos = new Vector3();
  293. this.middleLinPos = new Vector3();
  294. this.newPos = new Vector3();
  295. this.vPos = new Vector3();
  296. this.cross1 = new Vector3();
  297. };
  298. LightningStrike.prototype.createMesh = function () {
  299. var maxDrawableSegmentsPerSubRay = 1 << this.maxIterations;
  300. var maxVerts = 3 * ( maxDrawableSegmentsPerSubRay + 1 ) * this.maxSubrays;
  301. var maxIndices = 18 * maxDrawableSegmentsPerSubRay * this.maxSubrays;
  302. this.vertices = new Float32Array( maxVerts * 3 );
  303. this.indices = new Uint32Array( maxIndices );
  304. if ( this.generateUVs ) {
  305. this.uvs = new Float32Array( maxVerts * 2 );
  306. }
  307. // Populate the mesh
  308. this.fillMesh( 0 );
  309. this.setIndex( new Uint32BufferAttribute( this.indices, 1 ) );
  310. this.positionAttribute = new Float32BufferAttribute( this.vertices, 3 );
  311. this.setAttribute( 'position', this.positionAttribute );
  312. if ( this.generateUVs ) {
  313. this.uvsAttribute = new Float32BufferAttribute( new Float32Array( this.uvs ), 2 );
  314. this.setAttribute( 'uv', this.uvsAttribute );
  315. }
  316. if ( ! this.isStatic ) {
  317. this.index.usage = DynamicDrawUsage;
  318. this.positionAttribute.usage = DynamicDrawUsage;
  319. if ( this.generateUVs ) {
  320. this.uvsAttribute.usage = DynamicDrawUsage;
  321. }
  322. }
  323. // Store buffers for later modification
  324. this.vertices = this.positionAttribute.array;
  325. this.indices = this.index.array;
  326. if ( this.generateUVs ) {
  327. this.uvs = this.uvsAttribute.array;
  328. }
  329. };
  330. LightningStrike.prototype.updateMesh = function ( time ) {
  331. this.fillMesh( time );
  332. this.drawRange.count = this.currentIndex;
  333. this.index.needsUpdate = true;
  334. this.positionAttribute.needsUpdate = true;
  335. if ( this.generateUVs ) {
  336. this.uvsAttribute.needsUpdate = true;
  337. }
  338. };
  339. LightningStrike.prototype.fillMesh = function ( time ) {
  340. var scope = this;
  341. this.currentVertex = 0;
  342. this.currentIndex = 0;
  343. this.currentCoordinate = 0;
  344. this.currentUVCoordinate = 0;
  345. this.fractalRay( time, function fillVertices( segment ) {
  346. var subray = scope.currentSubray;
  347. if ( time < subray.birthTime ) { //&& ( ! this.rayParameters.isEternal || scope.currentSubray.recursion > 0 ) ) {
  348. return;
  349. } else if ( this.rayParameters.isEternal && scope.currentSubray.recursion == 0 ) {
  350. // Eternal rays don't propagate nor vanish, but its subrays do
  351. scope.createPrism( segment );
  352. scope.onDecideSubrayCreation( segment, scope );
  353. } else if ( time < subray.endPropagationTime ) {
  354. if ( scope.timeFraction >= segment.fraction0 * subray.propagationTimeFactor ) {
  355. // Ray propagation has arrived to this segment
  356. scope.createPrism( segment );
  357. scope.onDecideSubrayCreation( segment, scope );
  358. }
  359. } else if ( time < subray.beginVanishingTime ) {
  360. // Ray is steady (nor propagating nor vanishing)
  361. scope.createPrism( segment );
  362. scope.onDecideSubrayCreation( segment, scope );
  363. } else {
  364. if ( scope.timeFraction <= subray.vanishingTimeFactor + segment.fraction1 * ( 1 - subray.vanishingTimeFactor ) ) {
  365. // Segment has not yet vanished
  366. scope.createPrism( segment );
  367. }
  368. scope.onDecideSubrayCreation( segment, scope );
  369. }
  370. } );
  371. };
  372. LightningStrike.prototype.addNewSubray = function ( /*rayParameters*/ ) {
  373. return this.subrays[ this.numSubrays ++ ];
  374. };
  375. LightningStrike.prototype.initSubray = function ( subray, rayParameters ) {
  376. subray.pos0.copy( rayParameters.sourceOffset );
  377. subray.pos1.copy( rayParameters.destOffset );
  378. subray.up0.copy( rayParameters.up0 );
  379. subray.up1.copy( rayParameters.up1 );
  380. subray.radius0 = rayParameters.radius0;
  381. subray.radius1 = rayParameters.radius1;
  382. subray.birthTime = rayParameters.birthTime;
  383. subray.deathTime = rayParameters.deathTime;
  384. subray.timeScale = rayParameters.timeScale;
  385. subray.roughness = rayParameters.roughness;
  386. subray.straightness = rayParameters.straightness;
  387. subray.propagationTimeFactor = rayParameters.propagationTimeFactor;
  388. subray.vanishingTimeFactor = rayParameters.vanishingTimeFactor;
  389. subray.maxIterations = this.maxIterations;
  390. subray.seed = rayParameters.noiseSeed !== undefined ? rayParameters.noiseSeed : 0;
  391. subray.recursion = 0;
  392. };
  393. LightningStrike.prototype.fractalRay = function ( time, segmentCallback ) {
  394. this.time = time;
  395. this.currentSegmentCallback = segmentCallback;
  396. this.numSubrays = 0;
  397. // Add the top level subray
  398. this.initSubray( this.addNewSubray(), this.rayParameters );
  399. // Process all subrays that are being generated until consuming all of them
  400. for ( var subrayIndex = 0; subrayIndex < this.numSubrays; subrayIndex ++ ) {
  401. var subray = this.subrays[ subrayIndex ];
  402. this.currentSubray = subray;
  403. this.randomGenerator.setSeed( subray.seed );
  404. subray.endPropagationTime = MathUtils.lerp( subray.birthTime, subray.deathTime, subray.propagationTimeFactor );
  405. subray.beginVanishingTime = MathUtils.lerp( subray.deathTime, subray.birthTime, 1 - subray.vanishingTimeFactor );
  406. var random1 = this.randomGenerator.random;
  407. subray.linPos0.set( random1(), random1(), random1() ).multiplyScalar( 1000 );
  408. subray.linPos1.set( random1(), random1(), random1() ).multiplyScalar( 1000 );
  409. this.timeFraction = ( time - subray.birthTime ) / ( subray.deathTime - subray.birthTime );
  410. this.currentSegmentIndex = 0;
  411. this.isInitialSegment = true;
  412. var segment = this.getNewSegment();
  413. segment.iteration = 0;
  414. segment.pos0.copy( subray.pos0 );
  415. segment.pos1.copy( subray.pos1 );
  416. segment.linPos0.copy( subray.linPos0 );
  417. segment.linPos1.copy( subray.linPos1 );
  418. segment.up0.copy( subray.up0 );
  419. segment.up1.copy( subray.up1 );
  420. segment.radius0 = subray.radius0;
  421. segment.radius1 = subray.radius1;
  422. segment.fraction0 = 0;
  423. segment.fraction1 = 1;
  424. segment.positionVariationFactor = 1 - subray.straightness;
  425. this.subrayProbability = this.ramification * Math.pow( this.recursionProbability, subray.recursion ) / ( 1 << subray.maxIterations );
  426. this.fractalRayRecursive( segment );
  427. }
  428. this.currentSegmentCallback = null;
  429. this.currentSubray = null;
  430. };
  431. LightningStrike.prototype.fractalRayRecursive = function ( segment ) {
  432. // Leave recursion condition
  433. if ( segment.iteration >= this.currentSubray.maxIterations ) {
  434. this.currentSegmentCallback( segment );
  435. return;
  436. }
  437. // Interpolation
  438. this.forwards.subVectors( segment.pos1, segment.pos0 );
  439. var lForwards = this.forwards.length();
  440. if ( lForwards < 0.000001 ) {
  441. this.forwards.set( 0, 0, 0.01 );
  442. lForwards = this.forwards.length();
  443. }
  444. var middleRadius = ( segment.radius0 + segment.radius1 ) * 0.5;
  445. var middleFraction = ( segment.fraction0 + segment.fraction1 ) * 0.5;
  446. var timeDimension = this.time * this.currentSubray.timeScale * Math.pow( 2, segment.iteration );
  447. this.middlePos.lerpVectors( segment.pos0, segment.pos1, 0.5 );
  448. this.middleLinPos.lerpVectors( segment.linPos0, segment.linPos1, 0.5 );
  449. var p = this.middleLinPos;
  450. // Noise
  451. this.newPos.set( this.simplexX.noise4d( p.x, p.y, p.z, timeDimension ),
  452. this.simplexY.noise4d( p.x, p.y, p.z, timeDimension ),
  453. this.simplexZ.noise4d( p.x, p.y, p.z, timeDimension ) );
  454. this.newPos.multiplyScalar( segment.positionVariationFactor * lForwards );
  455. this.newPos.add( this.middlePos );
  456. // Recursion
  457. var newSegment1 = this.getNewSegment();
  458. newSegment1.pos0.copy( segment.pos0 );
  459. newSegment1.pos1.copy( this.newPos );
  460. newSegment1.linPos0.copy( segment.linPos0 );
  461. newSegment1.linPos1.copy( this.middleLinPos );
  462. newSegment1.up0.copy( segment.up0 );
  463. newSegment1.up1.copy( segment.up1 );
  464. newSegment1.radius0 = segment.radius0;
  465. newSegment1.radius1 = middleRadius;
  466. newSegment1.fraction0 = segment.fraction0;
  467. newSegment1.fraction1 = middleFraction;
  468. newSegment1.positionVariationFactor = segment.positionVariationFactor * this.currentSubray.roughness;
  469. newSegment1.iteration = segment.iteration + 1;
  470. var newSegment2 = this.getNewSegment();
  471. newSegment2.pos0.copy( this.newPos );
  472. newSegment2.pos1.copy( segment.pos1 );
  473. newSegment2.linPos0.copy( this.middleLinPos );
  474. newSegment2.linPos1.copy( segment.linPos1 );
  475. this.cross1.crossVectors( segment.up0, this.forwards.normalize() );
  476. newSegment2.up0.crossVectors( this.forwards, this.cross1 ).normalize();
  477. newSegment2.up1.copy( segment.up1 );
  478. newSegment2.radius0 = middleRadius;
  479. newSegment2.radius1 = segment.radius1;
  480. newSegment2.fraction0 = middleFraction;
  481. newSegment2.fraction1 = segment.fraction1;
  482. newSegment2.positionVariationFactor = segment.positionVariationFactor * this.currentSubray.roughness;
  483. newSegment2.iteration = segment.iteration + 1;
  484. this.fractalRayRecursive( newSegment1 );
  485. this.fractalRayRecursive( newSegment2 );
  486. };
  487. LightningStrike.prototype.createPrism = function ( segment ) {
  488. // Creates one triangular prism and its vertices at the segment
  489. this.forwardsFill.subVectors( segment.pos1, segment.pos0 ).normalize();
  490. if ( this.isInitialSegment ) {
  491. this.currentCreateTriangleVertices( segment.pos0, segment.up0, this.forwardsFill, segment.radius0, 0 );
  492. this.isInitialSegment = false;
  493. }
  494. this.currentCreateTriangleVertices( segment.pos1, segment.up0, this.forwardsFill, segment.radius1, segment.fraction1 );
  495. this.createPrismFaces();
  496. };
  497. LightningStrike.prototype.createTriangleVerticesWithoutUVs = function ( pos, up, forwards, radius ) {
  498. // Create an equilateral triangle (only vertices)
  499. this.side.crossVectors( up, forwards ).multiplyScalar( radius * LightningStrike.COS30DEG );
  500. this.down.copy( up ).multiplyScalar( - radius * LightningStrike.SIN30DEG );
  501. var p = this.vPos;
  502. var v = this.vertices;
  503. p.copy( pos ).sub( this.side ).add( this.down );
  504. v[ this.currentCoordinate ++ ] = p.x;
  505. v[ this.currentCoordinate ++ ] = p.y;
  506. v[ this.currentCoordinate ++ ] = p.z;
  507. p.copy( pos ).add( this.side ).add( this.down );
  508. v[ this.currentCoordinate ++ ] = p.x;
  509. v[ this.currentCoordinate ++ ] = p.y;
  510. v[ this.currentCoordinate ++ ] = p.z;
  511. p.copy( up ).multiplyScalar( radius ).add( pos );
  512. v[ this.currentCoordinate ++ ] = p.x;
  513. v[ this.currentCoordinate ++ ] = p.y;
  514. v[ this.currentCoordinate ++ ] = p.z;
  515. this.currentVertex += 3;
  516. };
  517. LightningStrike.prototype.createTriangleVerticesWithUVs = function ( pos, up, forwards, radius, u ) {
  518. // Create an equilateral triangle (only vertices)
  519. this.side.crossVectors( up, forwards ).multiplyScalar( radius * LightningStrike.COS30DEG );
  520. this.down.copy( up ).multiplyScalar( - radius * LightningStrike.SIN30DEG );
  521. var p = this.vPos;
  522. var v = this.vertices;
  523. var uv = this.uvs;
  524. p.copy( pos ).sub( this.side ).add( this.down );
  525. v[ this.currentCoordinate ++ ] = p.x;
  526. v[ this.currentCoordinate ++ ] = p.y;
  527. v[ this.currentCoordinate ++ ] = p.z;
  528. uv[ this.currentUVCoordinate ++ ] = u;
  529. uv[ this.currentUVCoordinate ++ ] = 0;
  530. p.copy( pos ).add( this.side ).add( this.down );
  531. v[ this.currentCoordinate ++ ] = p.x;
  532. v[ this.currentCoordinate ++ ] = p.y;
  533. v[ this.currentCoordinate ++ ] = p.z;
  534. uv[ this.currentUVCoordinate ++ ] = u;
  535. uv[ this.currentUVCoordinate ++ ] = 0.5;
  536. p.copy( up ).multiplyScalar( radius ).add( pos );
  537. v[ this.currentCoordinate ++ ] = p.x;
  538. v[ this.currentCoordinate ++ ] = p.y;
  539. v[ this.currentCoordinate ++ ] = p.z;
  540. uv[ this.currentUVCoordinate ++ ] = u;
  541. uv[ this.currentUVCoordinate ++ ] = 1;
  542. this.currentVertex += 3;
  543. };
  544. LightningStrike.prototype.createPrismFaces = function ( vertex/*, index*/ ) {
  545. var indices = this.indices;
  546. var vertex = this.currentVertex - 6;
  547. indices[ this.currentIndex ++ ] = vertex + 1;
  548. indices[ this.currentIndex ++ ] = vertex + 2;
  549. indices[ this.currentIndex ++ ] = vertex + 5;
  550. indices[ this.currentIndex ++ ] = vertex + 1;
  551. indices[ this.currentIndex ++ ] = vertex + 5;
  552. indices[ this.currentIndex ++ ] = vertex + 4;
  553. indices[ this.currentIndex ++ ] = vertex + 0;
  554. indices[ this.currentIndex ++ ] = vertex + 1;
  555. indices[ this.currentIndex ++ ] = vertex + 4;
  556. indices[ this.currentIndex ++ ] = vertex + 0;
  557. indices[ this.currentIndex ++ ] = vertex + 4;
  558. indices[ this.currentIndex ++ ] = vertex + 3;
  559. indices[ this.currentIndex ++ ] = vertex + 2;
  560. indices[ this.currentIndex ++ ] = vertex + 0;
  561. indices[ this.currentIndex ++ ] = vertex + 3;
  562. indices[ this.currentIndex ++ ] = vertex + 2;
  563. indices[ this.currentIndex ++ ] = vertex + 3;
  564. indices[ this.currentIndex ++ ] = vertex + 5;
  565. };
  566. LightningStrike.prototype.createDefaultSubrayCreationCallbacks = function () {
  567. var random1 = this.randomGenerator.random;
  568. this.onDecideSubrayCreation = function ( segment, lightningStrike ) {
  569. // Decide subrays creation at parent (sub)ray segment
  570. var subray = lightningStrike.currentSubray;
  571. var period = lightningStrike.rayParameters.subrayPeriod;
  572. var dutyCycle = lightningStrike.rayParameters.subrayDutyCycle;
  573. var phase0 = ( lightningStrike.rayParameters.isEternal && subray.recursion == 0 ) ? - random1() * period : MathUtils.lerp( subray.birthTime, subray.endPropagationTime, segment.fraction0 ) - random1() * period;
  574. var phase = lightningStrike.time - phase0;
  575. var currentCycle = Math.floor( phase / period );
  576. var childSubraySeed = random1() * ( currentCycle + 1 );
  577. var isActive = phase % period <= dutyCycle * period;
  578. var probability = 0;
  579. if ( isActive ) {
  580. probability = lightningStrike.subrayProbability;
  581. // Distribution test: probability *= segment.fraction0 > 0.5 && segment.fraction0 < 0.9 ? 1 / 0.4 : 0;
  582. }
  583. if ( subray.recursion < lightningStrike.maxSubrayRecursion && lightningStrike.numSubrays < lightningStrike.maxSubrays && random1() < probability ) {
  584. var childSubray = lightningStrike.addNewSubray();
  585. var parentSeed = lightningStrike.randomGenerator.getSeed();
  586. childSubray.seed = childSubraySeed;
  587. lightningStrike.randomGenerator.setSeed( childSubraySeed );
  588. childSubray.recursion = subray.recursion + 1;
  589. childSubray.maxIterations = Math.max( 1, subray.maxIterations - 1 );
  590. childSubray.linPos0.set( random1(), random1(), random1() ).multiplyScalar( 1000 );
  591. childSubray.linPos1.set( random1(), random1(), random1() ).multiplyScalar( 1000 );
  592. childSubray.up0.copy( subray.up0 );
  593. childSubray.up1.copy( subray.up1 );
  594. childSubray.radius0 = segment.radius0 * lightningStrike.rayParameters.radius0Factor;
  595. childSubray.radius1 = Math.min( lightningStrike.rayParameters.minRadius, segment.radius1 * lightningStrike.rayParameters.radius1Factor );
  596. childSubray.birthTime = phase0 + ( currentCycle ) * period;
  597. childSubray.deathTime = childSubray.birthTime + period * dutyCycle;
  598. if ( ! lightningStrike.rayParameters.isEternal && subray.recursion == 0 ) {
  599. childSubray.birthTime = Math.max( childSubray.birthTime, subray.birthTime );
  600. childSubray.deathTime = Math.min( childSubray.deathTime, subray.deathTime );
  601. }
  602. childSubray.timeScale = subray.timeScale * 2;
  603. childSubray.roughness = subray.roughness;
  604. childSubray.straightness = subray.straightness;
  605. childSubray.propagationTimeFactor = subray.propagationTimeFactor;
  606. childSubray.vanishingTimeFactor = subray.vanishingTimeFactor;
  607. lightningStrike.onSubrayCreation( segment, subray, childSubray, lightningStrike );
  608. lightningStrike.randomGenerator.setSeed( parentSeed );
  609. }
  610. };
  611. var vec1Pos = new Vector3();
  612. var vec2Forward = new Vector3();
  613. var vec3Side = new Vector3();
  614. var vec4Up = new Vector3();
  615. this.onSubrayCreation = function ( segment, parentSubray, childSubray, lightningStrike ) {
  616. // Decide childSubray origin and destination positions (pos0 and pos1) and possibly other properties of childSubray
  617. // Just use the default cone position generator
  618. lightningStrike.subrayCylinderPosition( segment, parentSubray, childSubray, 0.5, 0.6, 0.2 );
  619. };
  620. this.subrayConePosition = function ( segment, parentSubray, childSubray, heightFactor, sideWidthFactor, minSideWidthFactor ) {
  621. // Sets childSubray pos0 and pos1 in a cone
  622. childSubray.pos0.copy( segment.pos0 );
  623. vec1Pos.subVectors( parentSubray.pos1, parentSubray.pos0 );
  624. vec2Forward.copy( vec1Pos ).normalize();
  625. vec1Pos.multiplyScalar( segment.fraction0 + ( 1 - segment.fraction0 ) * ( random1() * heightFactor ) );
  626. var length = vec1Pos.length();
  627. vec3Side.crossVectors( parentSubray.up0, vec2Forward );
  628. var angle = 2 * Math.PI * random1();
  629. vec3Side.multiplyScalar( Math.cos( angle ) );
  630. vec4Up.copy( parentSubray.up0 ).multiplyScalar( Math.sin( angle ) );
  631. childSubray.pos1.copy( vec3Side ).add( vec4Up ).multiplyScalar( length * sideWidthFactor * ( minSideWidthFactor + random1() * ( 1 - minSideWidthFactor ) ) ).add( vec1Pos ).add( parentSubray.pos0 );
  632. };
  633. this.subrayCylinderPosition = function ( segment, parentSubray, childSubray, heightFactor, sideWidthFactor, minSideWidthFactor ) {
  634. // Sets childSubray pos0 and pos1 in a cylinder
  635. childSubray.pos0.copy( segment.pos0 );
  636. vec1Pos.subVectors( parentSubray.pos1, parentSubray.pos0 );
  637. vec2Forward.copy( vec1Pos ).normalize();
  638. vec1Pos.multiplyScalar( segment.fraction0 + ( 1 - segment.fraction0 ) * ( ( 2 * random1() - 1 ) * heightFactor ) );
  639. var length = vec1Pos.length();
  640. vec3Side.crossVectors( parentSubray.up0, vec2Forward );
  641. var angle = 2 * Math.PI * random1();
  642. vec3Side.multiplyScalar( Math.cos( angle ) );
  643. vec4Up.copy( parentSubray.up0 ).multiplyScalar( Math.sin( angle ) );
  644. childSubray.pos1.copy( vec3Side ).add( vec4Up ).multiplyScalar( length * sideWidthFactor * ( minSideWidthFactor + random1() * ( 1 - minSideWidthFactor ) ) ).add( vec1Pos ).add( parentSubray.pos0 );
  645. };
  646. };
  647. LightningStrike.prototype.createSubray = function () {
  648. return {
  649. seed: 0,
  650. maxIterations: 0,
  651. recursion: 0,
  652. pos0: new Vector3(),
  653. pos1: new Vector3(),
  654. linPos0: new Vector3(),
  655. linPos1: new Vector3(),
  656. up0: new Vector3(),
  657. up1: new Vector3(),
  658. radius0: 0,
  659. radius1: 0,
  660. birthTime: 0,
  661. deathTime: 0,
  662. timeScale: 0,
  663. roughness: 0,
  664. straightness: 0,
  665. propagationTimeFactor: 0,
  666. vanishingTimeFactor: 0,
  667. endPropagationTime: 0,
  668. beginVanishingTime: 0
  669. };
  670. };
  671. LightningStrike.prototype.createSegment = function () {
  672. return {
  673. iteration: 0,
  674. pos0: new Vector3(),
  675. pos1: new Vector3(),
  676. linPos0: new Vector3(),
  677. linPos1: new Vector3(),
  678. up0: new Vector3(),
  679. up1: new Vector3(),
  680. radius0: 0,
  681. radius1: 0,
  682. fraction0: 0,
  683. fraction1: 0,
  684. positionVariationFactor: 0
  685. };
  686. };
  687. LightningStrike.prototype.getNewSegment = function () {
  688. return this.raySegments[ this.currentSegmentIndex ++ ];
  689. };
  690. LightningStrike.prototype.copy = function ( source ) {
  691. BufferGeometry.prototype.copy.call( this, source );
  692. this.init( LightningStrike.copyParameters( {}, source.rayParameters ) );
  693. return this;
  694. };
  695. LightningStrike.prototype.clone = function () {
  696. return new this.constructor( LightningStrike.copyParameters( {}, this.rayParameters ) );
  697. };
  698. export { LightningStrike };