LightningStrike.js 33 KB

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