LightningStrike.js 32 KB

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