LightningStrike.js 33 KB

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