├── .gitignore ├── LICENSE ├── README.md ├── doc ├── autoencoder_schema.jpg ├── kaleiodoscope.png ├── lights.png └── report.pdf ├── learning ├── models │ ├── autoencoder.prototxt │ └── autoencoder_solver.prototxt ├── run_autoencoder.sh ├── scripts │ ├── addTrainingSamplesToLMDB.py │ ├── downloadTrainingSamples.py │ ├── exportFeatures.py │ ├── extractSpectrograms.py │ ├── params.py │ ├── playlists.txt │ ├── rawAudioToMono.sh │ ├── toLMDB.py │ └── visualize.py └── train_autoencoder.sh └── web-app ├── animation.js ├── animations ├── kaleidoscope │ ├── KaleidoShader.js │ ├── RGBShiftShader.js │ ├── lib │ │ ├── postprocessing │ │ │ ├── EffectComposer.js │ │ │ ├── MaskPass.js │ │ │ ├── RenderPass.js │ │ │ └── ShaderPass.js │ │ └── shaders │ │ │ └── CopyShader.js │ ├── main.js │ └── parameters.json ├── lights │ ├── main.js │ ├── parameters.json │ ├── particle.png │ ├── particulate.js │ └── util.js └── particles │ ├── GPUParticleSystem.js │ ├── TrackballControls.js │ ├── main.js │ ├── parameters.json │ ├── particle2.png │ └── perlin-512.png ├── audio.js ├── favicon.ico ├── features.js ├── fonts ├── SourceSansPro-ExtraLight.otf └── SourceSansPro-Light.otf ├── index.html ├── lib ├── jquery-3.2.1.min.js └── three.js ├── main.js ├── next_button.png ├── paramMapping.js ├── playlist.js ├── playlist.json └── style.css /.gitignore: -------------------------------------------------------------------------------- 1 | # Folders 2 | learning/data/raw_audio 3 | learning/data/lmdb 4 | learning/data/spectro_data 5 | learning/snapshots 6 | learning/weights 7 | web-app/weights 8 | web-app/node_modules 9 | web-app/lib 10 | web-app/models 11 | web-app/samples 12 | 13 | lib 14 | timeline.txt 15 | 16 | # Python 17 | *.pyc 18 | 19 | # Compiled Object files 20 | *.slo 21 | *.lo 22 | *.o 23 | *.obj 24 | 25 | # Precompiled Headers 26 | *.gch 27 | *.pch 28 | 29 | # Compiled Dynamic libraries 30 | *.so 31 | *.dylib 32 | *.dll 33 | 34 | # Fortran module files 35 | *.mod 36 | *.smod 37 | 38 | # Compiled Static libraries 39 | *.lai 40 | *.la 41 | *.a 42 | *.lib 43 | 44 | # Executables 45 | *.exe 46 | *.out 47 | *.app 48 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Deep Audio Visualization 2 | 3 | Live demo: https://br-g.github.io/Deep-Audio-Visualization/web-app 4 | 5 | Audio visualization usually relies on hand-crafted features, like intensity, timbre or pitch. These metrics are defined by humans and are biased towards our cultural representation of sound. 6 | In this project, we have trained a Neural Net to generate these features directly from spectrograms, in an unsupervized way. We thus get rid of this bias and hope the resulting visualizations can help us perceive music in different ways. 7 | 8 | The demo is built in Javascript, with *Three.js*. We used *Caffe* for deep learning. 9 | Animations relies on some code from [Charlie Hoey](http://charliehoey.com), [Felix Turner](http://airtight.cc) and [Jay Weeks](https://github.com/jpweeks/particulate-js). 10 | 11 | 12 | ## System overview 13 | There is two distinct phases to generate the visualizations: feature extraction (computationally intensive, performed offline) and real-time visualization. 14 | Extracting features consists in computing a low dimensional representation of the audio input, that is, performing a lossy compression of sound. To do so, a stacked autoencoder is trained to generate a non-linear mapping, from spectrograms to small vectors. In this project, spectrograms are vectors of size 11,025 (for half a second of sound, at sample rate 22,050 Hz) that we compress to vectors of size 10 (for 10 features), using 7 layers. With a GPU, training the model and encoding songs takes a few minutes. 15 | 16 |

17 | Autoencoder schema 18 |

19 | 20 | Then, for each animation, generated features are mapped dynamically to parameters such as speed, size or color, in real time. Features and parameters are mapped randomly. This enables *10!* (~ 3.6 million) possible mappings and as many possible visualizations - each visit to the demo is a unique experience! 21 | 22 | 23 | ## Installation (Unix) 24 | * `git clone git@github.com:br-g/Deep-Audio-Visualization.git` 25 | * `cd Deep-Audio-Visualization/web-app` 26 | * `http-server` (install it with *npm* if needed) 27 | * Open http://127.0.0.1:8080/index.html in *Chrome* 28 | -------------------------------------------------------------------------------- /doc/autoencoder_schema.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/br-g/Deep-Audio-Visualization/9dce262cbbe18fed0b5f2e9e0e49d4b4556ec4b2/doc/autoencoder_schema.jpg -------------------------------------------------------------------------------- /doc/kaleiodoscope.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/br-g/Deep-Audio-Visualization/9dce262cbbe18fed0b5f2e9e0e49d4b4556ec4b2/doc/kaleiodoscope.png -------------------------------------------------------------------------------- /doc/lights.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/br-g/Deep-Audio-Visualization/9dce262cbbe18fed0b5f2e9e0e49d4b4556ec4b2/doc/lights.png -------------------------------------------------------------------------------- /doc/report.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/br-g/Deep-Audio-Visualization/9dce262cbbe18fed0b5f2e9e0e49d4b4556ec4b2/doc/report.pdf -------------------------------------------------------------------------------- /learning/models/autoencoder.prototxt: -------------------------------------------------------------------------------- 1 | name: "Autoencoder" 2 | layer { 3 | name: "data" 4 | type: "Data" 5 | top: "data" 6 | include { 7 | phase: TRAIN 8 | } 9 | data_param { 10 | source: "../lmdb/data8" 11 | batch_size: 100 12 | backend: LMDB 13 | } 14 | } 15 | layer { 16 | name: "data" 17 | type: "Data" 18 | top: "data" 19 | include { 20 | phase: TEST 21 | } 22 | data_param { 23 | source: "../lmdb/data7" 24 | batch_size: 100 25 | backend: LMDB 26 | } 27 | } 28 | layer { 29 | name: "flatdata" 30 | type: "Flatten" 31 | bottom: "data" 32 | top: "flatdata" 33 | } 34 | layer { 35 | name: "encode1" 36 | type: "InnerProduct" 37 | bottom: "data" 38 | top: "encode1" 39 | param { 40 | lr_mult: 1 41 | decay_mult: 1 42 | } 43 | param { 44 | lr_mult: 1 45 | decay_mult: 0 46 | } 47 | inner_product_param { 48 | num_output: 5000 49 | weight_filler { 50 | type: "gaussian" 51 | std: 1 52 | sparse: 10 53 | } 54 | bias_filler { 55 | type: "constant" 56 | value: 0 57 | } 58 | } 59 | } 60 | layer { 61 | name: "encode1neuron" 62 | type: "Sigmoid" 63 | bottom: "encode1" 64 | top: "encode1neuron" 65 | } 66 | layer { 67 | name: "encode2" 68 | type: "InnerProduct" 69 | bottom: "encode1neuron" 70 | top: "encode2" 71 | param { 72 | lr_mult: 1 73 | decay_mult: 1 74 | } 75 | param { 76 | lr_mult: 1 77 | decay_mult: 0 78 | } 79 | inner_product_param { 80 | num_output: 2048 81 | weight_filler { 82 | type: "gaussian" 83 | std: 1 84 | sparse: 10 85 | } 86 | bias_filler { 87 | type: "constant" 88 | value: 0 89 | } 90 | } 91 | } 92 | layer { 93 | name: "encode2neuron" 94 | type: "Sigmoid" 95 | bottom: "encode2" 96 | top: "encode2neuron" 97 | } 98 | layer { 99 | name: "encode3" 100 | type: "InnerProduct" 101 | bottom: "encode2neuron" 102 | top: "encode3" 103 | param { 104 | lr_mult: 1 105 | decay_mult: 1 106 | } 107 | param { 108 | lr_mult: 1 109 | decay_mult: 0 110 | } 111 | inner_product_param { 112 | num_output: 1024 113 | weight_filler { 114 | type: "gaussian" 115 | std: 1 116 | sparse: 10 117 | } 118 | bias_filler { 119 | type: "constant" 120 | value: 0 121 | } 122 | } 123 | } 124 | layer { 125 | name: "encode3neuron" 126 | type: "Sigmoid" 127 | bottom: "encode3" 128 | top: "encode3neuron" 129 | } 130 | layer { 131 | name: "encode4" 132 | type: "InnerProduct" 133 | bottom: "encode3neuron" 134 | top: "encode4" 135 | param { 136 | lr_mult: 1 137 | decay_mult: 1 138 | } 139 | param { 140 | lr_mult: 1 141 | decay_mult: 0 142 | } 143 | inner_product_param { 144 | num_output: 512 145 | weight_filler { 146 | type: "gaussian" 147 | std: 1 148 | sparse: 10 149 | } 150 | bias_filler { 151 | type: "constant" 152 | value: 0 153 | } 154 | } 155 | } 156 | layer { 157 | name: "encode4neuron" 158 | type: "Sigmoid" 159 | bottom: "encode4" 160 | top: "encode4neuron" 161 | } 162 | layer { 163 | name: "encode5" 164 | type: "InnerProduct" 165 | bottom: "encode4neuron" 166 | top: "encode5" 167 | param { 168 | lr_mult: 1 169 | decay_mult: 1 170 | } 171 | param { 172 | lr_mult: 1 173 | decay_mult: 0 174 | } 175 | inner_product_param { 176 | num_output: 128 177 | weight_filler { 178 | type: "gaussian" 179 | std: 1 180 | sparse: 10 181 | } 182 | bias_filler { 183 | type: "constant" 184 | value: 0 185 | } 186 | } 187 | } 188 | layer { 189 | name: "encode5neuron" 190 | type: "Sigmoid" 191 | bottom: "encode5" 192 | top: "encode5neuron" 193 | } 194 | layer { 195 | name: "encode6" 196 | type: "InnerProduct" 197 | bottom: "encode5neuron" 198 | top: "encode6" 199 | param { 200 | lr_mult: 1 201 | decay_mult: 1 202 | } 203 | param { 204 | lr_mult: 1 205 | decay_mult: 0 206 | } 207 | inner_product_param { 208 | num_output: 32 209 | weight_filler { 210 | type: "gaussian" 211 | std: 1 212 | sparse: 10 213 | } 214 | bias_filler { 215 | type: "constant" 216 | value: 0 217 | } 218 | } 219 | } 220 | layer { 221 | name: "encode6neuron" 222 | type: "Sigmoid" 223 | bottom: "encode6" 224 | top: "encode6neuron" 225 | } 226 | layer { 227 | name: "encode7" 228 | type: "InnerProduct" 229 | bottom: "encode6neuron" 230 | top: "encode7" 231 | param { 232 | lr_mult: 1 233 | decay_mult: 1 234 | } 235 | param { 236 | lr_mult: 1 237 | decay_mult: 0 238 | } 239 | inner_product_param { 240 | num_output: 10 241 | weight_filler { 242 | type: "gaussian" 243 | std: 1 244 | sparse: 10 245 | } 246 | bias_filler { 247 | type: "constant" 248 | value: 0 249 | } 250 | } 251 | } 252 | layer { 253 | name: "decode7" 254 | type: "InnerProduct" 255 | bottom: "encode7" 256 | top: "decode7" 257 | param { 258 | lr_mult: 1 259 | decay_mult: 1 260 | } 261 | param { 262 | lr_mult: 1 263 | decay_mult: 0 264 | } 265 | inner_product_param { 266 | num_output: 32 267 | weight_filler { 268 | type: "gaussian" 269 | std: 1 270 | sparse: 10 271 | } 272 | bias_filler { 273 | type: "constant" 274 | value: 0 275 | } 276 | } 277 | } 278 | layer { 279 | name: "decode7neuron" 280 | type: "Sigmoid" 281 | bottom: "decode7" 282 | top: "decode7neuron" 283 | } 284 | layer { 285 | name: "decode6" 286 | type: "InnerProduct" 287 | bottom: "decode7" 288 | top: "decode6" 289 | param { 290 | lr_mult: 1 291 | decay_mult: 1 292 | } 293 | param { 294 | lr_mult: 1 295 | decay_mult: 0 296 | } 297 | inner_product_param { 298 | num_output: 128 299 | weight_filler { 300 | type: "gaussian" 301 | std: 1 302 | sparse: 10 303 | } 304 | bias_filler { 305 | type: "constant" 306 | value: 0 307 | } 308 | } 309 | } 310 | layer { 311 | name: "decode6neuron" 312 | type: "Sigmoid" 313 | bottom: "decode6" 314 | top: "decode6neuron" 315 | } 316 | layer { 317 | name: "decode5" 318 | type: "InnerProduct" 319 | bottom: "decode6neuron" 320 | top: "decode5" 321 | param { 322 | lr_mult: 1 323 | decay_mult: 1 324 | } 325 | param { 326 | lr_mult: 1 327 | decay_mult: 0 328 | } 329 | inner_product_param { 330 | num_output: 512 331 | weight_filler { 332 | type: "gaussian" 333 | std: 1 334 | sparse: 10 335 | } 336 | bias_filler { 337 | type: "constant" 338 | value: 0 339 | } 340 | } 341 | } 342 | layer { 343 | name: "decode5neuron" 344 | type: "Sigmoid" 345 | bottom: "decode5" 346 | top: "decode5neuron" 347 | } 348 | layer { 349 | name: "decode4" 350 | type: "InnerProduct" 351 | bottom: "decode5neuron" 352 | top: "decode4" 353 | param { 354 | lr_mult: 1 355 | decay_mult: 1 356 | } 357 | param { 358 | lr_mult: 1 359 | decay_mult: 0 360 | } 361 | inner_product_param { 362 | num_output: 1024 363 | weight_filler { 364 | type: "gaussian" 365 | std: 1 366 | sparse: 10 367 | } 368 | bias_filler { 369 | type: "constant" 370 | value: 0 371 | } 372 | } 373 | } 374 | layer { 375 | name: "decode4neuron" 376 | type: "Sigmoid" 377 | bottom: "decode4" 378 | top: "decode4neuron" 379 | } 380 | layer { 381 | name: "decode3" 382 | type: "InnerProduct" 383 | bottom: "decode4neuron" 384 | top: "decode3" 385 | param { 386 | lr_mult: 1 387 | decay_mult: 1 388 | } 389 | param { 390 | lr_mult: 1 391 | decay_mult: 0 392 | } 393 | inner_product_param { 394 | num_output: 2048 395 | weight_filler { 396 | type: "gaussian" 397 | std: 1 398 | sparse: 10 399 | } 400 | bias_filler { 401 | type: "constant" 402 | value: 0 403 | } 404 | } 405 | } 406 | layer { 407 | name: "decode3neuron" 408 | type: "Sigmoid" 409 | bottom: "decode3" 410 | top: "decode3neuron" 411 | } 412 | layer { 413 | name: "decode2" 414 | type: "InnerProduct" 415 | bottom: "decode3neuron" 416 | top: "decode2" 417 | param { 418 | lr_mult: 1 419 | decay_mult: 1 420 | } 421 | param { 422 | lr_mult: 1 423 | decay_mult: 0 424 | } 425 | inner_product_param { 426 | num_output: 5000 427 | weight_filler { 428 | type: "gaussian" 429 | std: 1 430 | sparse: 10 431 | } 432 | bias_filler { 433 | type: "constant" 434 | value: 0 435 | } 436 | } 437 | } 438 | layer { 439 | name: "decode2neuron" 440 | type: "Sigmoid" 441 | bottom: "decode2" 442 | top: "decode2neuron" 443 | } 444 | layer { 445 | name: "decode1" 446 | type: "InnerProduct" 447 | bottom: "decode2neuron" 448 | top: "decode1" 449 | param { 450 | lr_mult: 1 451 | decay_mult: 1 452 | } 453 | param { 454 | lr_mult: 1 455 | decay_mult: 0 456 | } 457 | inner_product_param { 458 | num_output: 11025 459 | weight_filler { 460 | type: "gaussian" 461 | std: 1 462 | sparse: 10 463 | } 464 | bias_filler { 465 | type: "constant" 466 | value: 0 467 | } 468 | } 469 | } 470 | layer { 471 | name: "loss" 472 | type: "EuclideanLoss" 473 | bottom: "decode1" 474 | bottom: "flatdata" 475 | top: "l2_error" 476 | loss_weight: 1 477 | } 478 | -------------------------------------------------------------------------------- /learning/models/autoencoder_solver.prototxt: -------------------------------------------------------------------------------- 1 | net: "models/autoencoder.prototxt" 2 | test_state: { stage: 'test-on-train' } 3 | test_iter: 100 4 | test_interval: 1000000 5 | test_compute_loss: true 6 | base_lr: 0.0000001 7 | lr_policy: "step" 8 | gamma: 0.1 9 | stepsize: 10000000 10 | display: 100 11 | max_iter: 2000 12 | weight_decay: 0.0005 13 | snapshot: 1000 14 | snapshot_prefix: "snapshots/data8_" 15 | momentum: 0.9 16 | solver_mode: GPU 17 | type: "SGD" 18 | -------------------------------------------------------------------------------- /learning/run_autoencoder.sh: -------------------------------------------------------------------------------- 1 | ../lib/caffe/build/tools/caffe test -weights snapshots/autoencoder__iter_50000.caffemodel -model models/autoencoder.prototxt -------------------------------------------------------------------------------- /learning/scripts/addTrainingSamplesToLMDB.py: -------------------------------------------------------------------------------- 1 | #### 2 | # Adds random training samples to LMDB. 3 | # param 1: output LMDB file path 4 | # param 2: number of samples to add 5 | # param 3: batch size 6 | ### 7 | 8 | import sys 9 | import extractSpectrograms 10 | import toLMDB 11 | 12 | def addTrainingSamples(rawAudiofilePath, lmdbPath): 13 | spectrograms = extractSpectrograms.extractSpectrogram(rawAudiofilePath, True) 14 | if spectrograms != None: 15 | toLMDB.toLMDB(spectrograms, lmdbPath) 16 | else: 17 | print("Error") 18 | 19 | if __name__ == "__main__": 20 | rawAudiofilePath = sys.argv[1]; 21 | lmdbPath = sys.argv[2]; 22 | addTrainingSamples(rawAudiofilePath, lmdbPath) -------------------------------------------------------------------------------- /learning/scripts/downloadTrainingSamples.py: -------------------------------------------------------------------------------- 1 | # Downloads some youtube music from various youtube playlists 2 | # param 1: downloaded files prefix 3 | # param 2: number of videos to download 4 | 5 | from __future__ import unicode_literals 6 | import sys 7 | import commands 8 | from random import randint, shuffle 9 | import params 10 | 11 | def downloadFromYouTube(outputPrefix, nbVideos): 12 | # Loads playlists 13 | with open("./playlists.txt", "r") as f: 14 | playlists = [] 15 | for line in f: 16 | playlists.append(line) 17 | playlists = [x.strip() for x in playlists] 18 | shuffle(playlists) 19 | 20 | # Download music from various youtube playlists. 21 | # Audio only, best possible quality 22 | for i in range(0, int(nbVideos)): 23 | print("Download " + repr(i)) 24 | try: 25 | playlistInd = randint(1,500) 26 | commands.getstatusoutput("youtube-dl \ 27 | --ignore-errors \ 28 | --audio-quality 0 \ 29 | -x \ 30 | -o '" + outputPrefix + repr(i) + ".%(ext)s' \ 31 | --audio-format wav \ 32 | --playlist-start " + repr(playlistInd) + " --playlist-end " + repr(playlistInd) + " "\ 33 | + playlists[i % len(playlists)]) 34 | except: 35 | print("Error during download") 36 | 37 | if __name__ == "__main__": 38 | downloadFromYouTube(sys.argv[1], int(sys.argv[2])) -------------------------------------------------------------------------------- /learning/scripts/exportFeatures.py: -------------------------------------------------------------------------------- 1 | #### 2 | # Extracts features from raw audio and exports it in JSON 3 | ### 4 | 5 | import numpy as np 6 | import caffe 7 | from pylab import * 8 | from scipy.io import wavfile 9 | from scipy.signal import spectrogram, resample 10 | import matplotlib 11 | import json 12 | import sys 13 | import os 14 | import params 15 | import extractSpectrograms 16 | import jsonpickle 17 | 18 | rawAudioPath = sys.argv[1] 19 | outFilePath = sys.argv[2] 20 | modelPath = sys.argv[3] 21 | snapshotPath = sys.argv[4] 22 | 23 | # Features container 24 | class Features: 25 | def __init__(self, sampleRate): 26 | self.sampleRate = sampleRate 27 | self.featuresData = {} 28 | 29 | #### 30 | # Extracts spectrograms from raw audio 31 | ### 32 | originalSampleFreq, audioData = wavfile.read(rawAudioPath) 33 | 34 | # If sample rate different from the standart one, resamples. 35 | if originalSampleFreq != params.SAMPLE_RATE: 36 | print "Resampling..." 37 | #audioData = resample(audioData, 38 | # int(float(len(audioData)) * float(params.SAMPLE_RATE) / float(originalSampleFreq))) 39 | newFilePath = rawAudioPath[:-4] + "_resamp.wav" 40 | os.system("sox " + rawAudioPath + " -r " + str(params.SAMPLE_RATE) + " " + newFilePath) 41 | originalSampleFreq, audioData = wavfile.read(newFilePath) 42 | 43 | audioData = audioData / (2.**15) # Map values into [-1, 1] 44 | step = int(params.SAMPLE_RATE / params.MAX_FPS) 45 | spectrograms = np.empty((len(audioData) / step, params.WINDOW_SIZE)) 46 | 47 | print "Extracting spectrogram..." 48 | for i in range(0, len(audioData) / step): 49 | if i*step+params.WINDOW_SIZE <= len(audioData): 50 | spectrograms[i,:] = abs( np.fft.fft(audioData[i*step:i*step+params.WINDOW_SIZE]) ) 51 | 52 | 53 | #### 54 | # Runs the model and gets features 55 | ### 56 | features = np.empty((len(audioData) / step, params.NB_FEATURES)) 57 | 58 | if params.USE_GPU: 59 | caffe.set_device(0) 60 | caffe.set_mode_gpu() 61 | else: 62 | caffe.set_mode_cpu() 63 | 64 | net = caffe.Net(modelPath, 65 | snapshotPath, 66 | caffe.TEST) 67 | 68 | 69 | print "Computing features..." 70 | 71 | def netForward(batch): 72 | initialBatchSize = len(batch) 73 | if (initialBatchSize < params.BATCH_SIZE): 74 | newBatch = np.empty((params.BATCH_SIZE, params.WINDOW_SIZE)) 75 | newBatch[0:initialBatchSize] = batch 76 | batch = newBatch 77 | 78 | net.blobs['data'].data[...] = np.reshape(batch, (params.BATCH_SIZE,1,1,params.WINDOW_SIZE)) 79 | return net.forward(end="encode7")['encode7'][0:initialBatchSize] 80 | 81 | for i in range(0, len(spectrograms) / params.BATCH_SIZE): 82 | startInd = i*params.BATCH_SIZE 83 | endInd = startInd + params.BATCH_SIZE 84 | features[startInd:endInd,:] = netForward(spectrograms[startInd:endInd,:]) 85 | 86 | if len(spectrograms) % params.BATCH_SIZE > 0: 87 | startInd = int(len(spectrograms)/params.BATCH_SIZE)*params.BATCH_SIZE 88 | features[startInd:,:] = netForward(spectrograms[startInd:,:]) 89 | 90 | 91 | #### 92 | # Creates features object and computes blur 93 | ### 94 | print "Computing blur..." 95 | 96 | featuresContainer = Features(params.MAX_FPS) 97 | blurLevels = [1, 10, 50, 100, 300, 1000, 3000] 98 | 99 | for blurValue in blurLevels: 100 | featuresContainer.featuresData["blur" + str(blurValue)] = np.zeros((len(features), params.NB_FEATURES)) 101 | 102 | for curFrameInd in range(0, len(features)): 103 | minBound = int(math.ceil(curFrameInd-0.5*blurValue)) 104 | if minBound < 0: 105 | minBound = 0 106 | maxBound = int(math.ceil(curFrameInd+0.5*blurValue)) 107 | if maxBound > len(features): 108 | maxBound = len(features) 109 | 110 | for curFeatureInd in range(0, params.NB_FEATURES): 111 | meanValue = np.mean(features[minBound:maxBound, curFeatureInd]) 112 | featuresContainer.featuresData["blur" + str(blurValue)][curFrameInd, curFeatureInd] = meanValue 113 | 114 | #### 115 | # Normalizes features 116 | ### 117 | print "Normalizing..." 118 | 119 | for blurValue in blurLevels: 120 | for curFeatureInd in range(0, params.NB_FEATURES): 121 | _max = max(featuresContainer.featuresData["blur" + str(blurValue)][:,curFeatureInd]) 122 | _min = min(featuresContainer.featuresData["blur" + str(blurValue)][:,curFeatureInd]) 123 | featuresContainer.featuresData["blur" + str(blurValue)][:,curFeatureInd] = np.around((featuresContainer.featuresData["blur" + str(blurValue)][:,curFeatureInd] - _min) / (_max - _min), params.FEATURES_PRECISION_DIGITS) 124 | 125 | for blurValue in blurLevels: 126 | featuresContainer.featuresData["blur" + str(blurValue)] = featuresContainer.featuresData["blur" + str(blurValue)].tolist() 127 | 128 | #### 129 | # Exports features in JSON 130 | ### 131 | print "Exporting in JSON..." 132 | 133 | """def exportJSON(): 134 | def exportFeatures(): 135 | def exportFrame(frame): 136 | featureString = "[" 137 | for feature in frame[:-1]: 138 | featureString += str(feature) + "," 139 | featureString += str(frame[-1]) 140 | featureString += "]" 141 | return featureString 142 | featuresString = "[" 143 | for frame in features[:-1]: 144 | featuresString += exportFrame(frame) + "," 145 | featuresString += exportFrame(features[-1]) 146 | featuresString += "]" 147 | return featuresString 148 | 149 | jsonString = "{" 150 | jsonString += "\"FPS\":\"" + str(params.MAX_FPS) + "\"," 151 | jsonString += "\"Features\":" + exportFeatures() 152 | jsonString += "}" 153 | return jsonString""" 154 | 155 | with open(outFilePath, 'w') as outfile: 156 | outfile.write(json.dumps(featuresContainer, default=lambda o: o.__dict__)) 157 | 158 | print "Done" -------------------------------------------------------------------------------- /learning/scripts/extractSpectrograms.py: -------------------------------------------------------------------------------- 1 | #### 2 | # Extracts spectrograms from raw audio file and exports pickled data 3 | # param 1: raw audio file path 4 | # param 2: Resample if necessary? 5 | ### 6 | 7 | from pylab import * 8 | from scipy.io import wavfile 9 | from scipy.signal import * 10 | from scipy import * 11 | import matplotlib 12 | import sys 13 | import os 14 | import pickle 15 | 16 | import params 17 | 18 | def getMax(arr): 19 | _max = -1. 20 | for i in range(0, len(arr)): 21 | for j in range(0, len(arr[0])): 22 | if (arr[i,j] > _max): 23 | _max = arr[i,j] 24 | return _max 25 | 26 | def extractSpectrogram(rawAudioPath, doResample=False) : 27 | originalSampleFreq, audioData = wavfile.read(rawAudioPath) 28 | 29 | # If sample rate different from the standart one, resamples. 30 | if originalSampleFreq != params.SAMPLE_RATE: 31 | if doResample: 32 | print "Resampling..." 33 | """audioData = resample(audioData, 34 | int(float(len(audioData)) * float(params.SAMPLE_RATE) / float(originalSampleFreq)))""" 35 | 36 | newFilePath = rawAudioPath[:-4] + "_resamp.wav" 37 | print("sox " + rawAudioPath + " -r " + str(params.SAMPLE_RATE) + " " + newFilePath) 38 | os.system("sox " + rawAudioPath + " -r " + str(params.SAMPLE_RATE) + " " + newFilePath) 39 | originalSampleFreq, audioData = wavfile.read(newFilePath) 40 | else: 41 | return None 42 | 43 | audioData = audioData / (2.**15) # Map values into [-1, 1] 44 | spectrograms = np.empty((len(audioData) / params.WINDOW_SIZE, params.WINDOW_SIZE)) 45 | 46 | print "Extracting spectrogram..." 47 | for i in range(0, len(audioData) / params.WINDOW_SIZE): 48 | spectrograms[i,:] = abs( np.fft.fft(audioData[i*params.WINDOW_SIZE:(i+1)*params.WINDOW_SIZE]) ) 49 | 50 | return spectrograms 51 | 52 | if __name__ == "__main__": 53 | extractSpectrogram(sys.argv[1], sys.argv[2]) -------------------------------------------------------------------------------- /learning/scripts/params.py: -------------------------------------------------------------------------------- 1 | WINDOW_SIZE = 11025 2 | SAMPLE_RATE = 22050 3 | MAX_FPS = 60 4 | NB_FEATURES = 10 5 | USE_GPU = False 6 | BATCH_SIZE = 100 7 | FEATURES_PRECISION_DIGITS = 4 -------------------------------------------------------------------------------- /learning/scripts/playlists.txt: -------------------------------------------------------------------------------- 1 | PLcfQmtiAG0X-fmM85dPlql5wfYbmFumzQ 2 | PLFPg_IUxqnZNnACUGsfn50DySIOVSkiKI 3 | PLDcnymzs18LWrKzHmzrGH1JzLBqrHi3xQ 4 | PL5ep_pPaQcTe05W_o7KIuS374Q8s7jMDo 5 | PLhd1HyMTk3f5PzRjJzmzH7kkxjfdVoPPj 6 | PL0zQrw6ZA60Z6JT4lFH-lAq5AfDnO2-aE 7 | PLFRSDckdQc1th9sUu8hpV1pIbjjBgRmDw 8 | PLr8RdoI29cXIlkmTAQDgOuwBhDh3yJDBQ 9 | PLYAYp5OI4lRLf_oZapf5T5RUZeUcF9eRO 10 | PLQog_FHUHAFUDDQPOTeAWSHwzFV1Zz5PZ 11 | PLLMA7Sh3JsOQQFAtj1no-_keicrqjEZDm 12 | PL47oRh0-pTouthHPv6AbALWPvPJHlKiF7 13 | PLvLX2y1VZ-tFJCfRG7hi_OjIAyCriNUT2 14 | PLXupg6NyTvTxw5-_rzIsBgqJ2tysQFYt5 15 | PLWNXn_iQ2yrKzFcUarHPdC4c_LPm-kjQy 16 | PL9NMEBQcQqlzwlwLWRz5DMowimCk88FJk 17 | PLVXq77mXV53-Np39jM456si2PeTrEm9Mj 18 | PLfY-m4YMsF-OM1zG80pMguej_Ufm8t0VC -------------------------------------------------------------------------------- /learning/scripts/rawAudioToMono.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | ###### 4 | # Converts a raw audio files to mono 5 | ###### 6 | 7 | echo "Converting to mono: $1" 8 | sox -v 0.5 "$1" -c 1 "${1::-4}_mono.wav" -------------------------------------------------------------------------------- /learning/scripts/toLMDB.py: -------------------------------------------------------------------------------- 1 | #### 2 | # Appends pickled data to LMDB file 3 | # param 1: pickle file path 4 | # param 2: output file path 5 | ### 6 | 7 | import numpy as np 8 | import lmdb 9 | import caffe 10 | import pickle 11 | import sys 12 | import random 13 | 14 | import params 15 | 16 | def toLMDB(spectrograms, outputFilePath): 17 | #spectrograms = pickle.load(open(pickleFilePath, "r")) 18 | N = len(spectrograms) 19 | 20 | # Sets map size to 30 GB 21 | map_size = 30 * 1024 * 1024 * 1024 22 | 23 | env = lmdb.open(outputFilePath, map_size=map_size) 24 | 25 | with env.begin(write=True) as txn: 26 | for i in range(N): 27 | datum = caffe.proto.caffe_pb2.Datum() 28 | datum.channels = 1 29 | datum.height = 1 30 | datum.width = params.WINDOW_SIZE 31 | datum.data = spectrograms[i,:].tostring() 32 | #str_id = '{:08}'.format(i) 33 | str_id = '{:05}'.format(random.randint(1,99000))+'{:05}'.format(i) # shuffle data 34 | txn.put(str_id.encode('ascii'), datum.SerializeToString()) 35 | 36 | if __name__ == "__main__": 37 | toLMDB(sys.argv[1], sys.argv[2]) -------------------------------------------------------------------------------- /learning/scripts/visualize.py: -------------------------------------------------------------------------------- 1 | #### 2 | # Plots test loss, from Caffe training logs 3 | ### 4 | 5 | import numpy as np 6 | import re 7 | import click 8 | from matplotlib import pylab as plt 9 | 10 | 11 | @click.command() 12 | @click.argument('files', nargs=-1, type=click.Path(exists=True)) 13 | def main(files): 14 | plt.style.use('ggplot') 15 | fig, ax1 = plt.subplots() 16 | ax1.set_xlabel('iteration') 17 | ax1.set_ylabel('loss') 18 | for i, log_file in enumerate(files): 19 | loss_iterations, losses = parse_log(log_file) 20 | disp_results(fig, ax1, loss_iterations, losses, color_ind=i) 21 | plt.show() 22 | 23 | 24 | def parse_log(log_file): 25 | with open(log_file, 'r') as log_file: 26 | log = log_file.read() 27 | 28 | #loss_pattern = r"l2_error = (?P[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?)" 29 | loss_pattern = r"Test net output #0: l2_error = (?P[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?)" 30 | losses = [] 31 | loss_iterations = [] 32 | 33 | count = 0 34 | for r in re.findall(loss_pattern, log): 35 | loss_iterations.append(count) 36 | count += 100 37 | losses.append(float(r[0])) 38 | 39 | loss_iterations = np.array(loss_iterations) 40 | losses = np.array(losses) 41 | 42 | print(losses) 43 | return loss_iterations, losses 44 | 45 | 46 | def disp_results(fig, ax1, loss_iterations, losses, color_ind=0): 47 | modula = len(plt.rcParams['axes.color_cycle']) 48 | ax1.plot(loss_iterations, losses, color=plt.rcParams['axes.color_cycle'][(color_ind * 2 + 0) % modula]) 49 | 50 | if __name__ == '__main__': 51 | main() -------------------------------------------------------------------------------- /learning/train_autoencoder.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | set -e 3 | 4 | ../lib/caffe/build/tools/caffe train \ 5 | --solver=./models/autoencoder_solver.prototxt $@ -------------------------------------------------------------------------------- /web-app/animation.js: -------------------------------------------------------------------------------- 1 | function AnimationManager() { 2 | var camera = null; 3 | var scene = null; 4 | var anim = null; 5 | var renderer = null; 6 | var features = null; 7 | var paramMapping = null; 8 | var lastRenderTime = 0; 9 | var curAnimName = null; 10 | var audioManager = null; 11 | 12 | var SYNC_CONSTANT = 260.0; // ms 13 | 14 | this.init = function() { 15 | this.createSceneAndCamera(); 16 | renderer = new THREE.WebGLRenderer(); 17 | renderer.setSize(window.innerWidth, window.innerHeight); 18 | document.body.appendChild(renderer.domElement); 19 | } 20 | 21 | this.createSceneAndCamera = function () { 22 | scene = new THREE.Scene(); 23 | camera = new THREE.PerspectiveCamera(55, window.innerWidth / window.innerHeight, 0.1, 1000); 24 | } 25 | 26 | this.setAnimation = function(animName) { 27 | switch (animName) { 28 | case 'kaleidoscope': 29 | anim = new Kaleidoscope(); 30 | break; 31 | case 'particles': 32 | anim = new Particles(); 33 | break; 34 | case 'lights': 35 | anim = new Lights(); 36 | break; 37 | default: 38 | console.log('Error: Unknow animation name.'); 39 | } 40 | if (anim) { 41 | this.createSceneAndCamera(); 42 | anim.init(camera, scene, renderer); 43 | } 44 | 45 | var _this = this; 46 | return loadParamMapping().then(function () { 47 | _this.curAnimName = animName; 48 | _this.randomize(); 49 | }); 50 | } 51 | 52 | this.setAudioManager = function(_audioManager) { 53 | audioManager = _audioManager; 54 | } 55 | 56 | this.nextAnimation = function() { 57 | if (this.curAnimName == null) { 58 | this.curAnimName = 'particles'; 59 | } 60 | switch (this.curAnimName) { 61 | case 'particles': 62 | return this.setAnimation('lights'); 63 | case 'lights': 64 | return this.setAnimation('kaleidoscope'); 65 | case 'kaleidoscope': 66 | return this.setAnimation('particles'); 67 | default: 68 | console.log('Error: Unknow animation name.'); 69 | } 70 | } 71 | 72 | this.loadFeatures = function(filePath) { 73 | features = new Features(); 74 | return features.load(filePath); 75 | } 76 | 77 | this.onWindowResize = function() { 78 | camera.aspect = window.innerWidth / window.innerHeight; 79 | camera.updateProjectionMatrix(); 80 | renderer.setSize(window.innerWidth, window.innerHeight); 81 | } 82 | 83 | function loadParamMapping() { 84 | paramMapping = new ParamMapping(); 85 | return paramMapping.load(anim.getPath() + '/parameters.json'); 86 | } 87 | 88 | this.launch = function() { 89 | lastRenderTime = 0; 90 | renderAnimation(); 91 | } 92 | 93 | this.randomize = function() { 94 | paramMapping.randomize(); 95 | } 96 | 97 | window.addEventListener('resize', function () { 98 | renderer.setSize(window.innerWidth, window.innerHeight); 99 | camera.aspect = window.innerWidth / window.innerHeight; 100 | camera.updateProjectionMatrix(); 101 | }); 102 | 103 | function renderAnimation () { 104 | requestAnimationFrame(renderAnimation); 105 | renderer.render(scene, camera); 106 | var curTime = audioManager.getElapsedTime() * 1000.0; 107 | 108 | if (audioManager.ended()) { 109 | app.playNextSong(); 110 | } 111 | if (curTime <= 0) { 112 | anim.updateDefault(); 113 | } else { 114 | var curParameters = paramMapping.doMap(features.get(audioManager.getElapsedTime() * 1000.0 + SYNC_CONSTANT)); 115 | if (curParameters == null || curParameters == undefined) { 116 | anim.updateDefault(); 117 | } else { 118 | anim.update((curTime - lastRenderTime) / 1000.0, 119 | curParameters, 120 | curTime - lastRenderTime); 121 | } 122 | } 123 | lastRenderTime = curTime; 124 | } 125 | }; 126 | -------------------------------------------------------------------------------- /web-app/animations/kaleidoscope/KaleidoShader.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @author felixturner / http://airtight.cc/ 3 | * 4 | * Kaleidoscope Shader 5 | * Radial reflection around center point 6 | * Ported from: http://pixelshaders.com/editor/ 7 | * by Toby Schachman / http://tobyschachman.com/ 8 | * 9 | * sides: number of reflections 10 | * angle: initial angle in radians 11 | */ 12 | 13 | THREE.KaleidoShader = { 14 | 15 | uniforms: { 16 | 17 | "tDiffuse": { type: "t", value: null }, 18 | "sides": { type: "f", value: 6.0 }, 19 | "angle": { type: "f", value: 0.0 } 20 | 21 | }, 22 | 23 | vertexShader: [ 24 | 25 | "varying vec2 vUv;", 26 | 27 | "void main() {", 28 | 29 | "vUv = uv;", 30 | "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", 31 | 32 | "}" 33 | 34 | ].join("\n"), 35 | 36 | fragmentShader: [ 37 | 38 | "uniform sampler2D tDiffuse;", 39 | "uniform float sides;", 40 | "uniform float angle;", 41 | 42 | "varying vec2 vUv;", 43 | 44 | "void main() {", 45 | 46 | "vec2 p = vUv - 0.5;", 47 | "float r = length(p);", 48 | "float a = atan(p.y, p.x) + angle;", 49 | "float tau = 2. * 3.1416 ;", 50 | "a = mod(a, tau/sides);", 51 | "a = abs(a - tau/sides/2.) ;", 52 | "p = r * vec2(cos(a), sin(a));", 53 | "vec4 color = texture2D(tDiffuse, p + 0.5);", 54 | "gl_FragColor = color;", 55 | 56 | "}" 57 | 58 | ].join("\n") 59 | 60 | }; 61 | -------------------------------------------------------------------------------- /web-app/animations/kaleidoscope/RGBShiftShader.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @author felixturner / http://airtight.cc/ 3 | * 4 | * RGB Shift Shader 5 | * Shifts red and blue channels from center in opposite directions 6 | * Ported from http://kriss.cx/tom/2009/05/rgb-shift/ 7 | * by Tom Butterworth / http://kriss.cx/tom/ 8 | * 9 | * amount: shift distance (1 is width of input) 10 | * angle: shift angle in radians 11 | */ 12 | 13 | THREE.RGBShiftShader = { 14 | 15 | uniforms: { 16 | 17 | "tDiffuse": { type: "t", value: null }, 18 | "amount": { type: "f", value: 0.005 }, 19 | "angle": { type: "f", value: 0.0 } 20 | 21 | }, 22 | 23 | vertexShader: [ 24 | 25 | "varying vec2 vUv;", 26 | 27 | "void main() {", 28 | 29 | "vUv = uv;", 30 | "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", 31 | 32 | "}" 33 | 34 | ].join("\n"), 35 | 36 | fragmentShader: [ 37 | 38 | "uniform sampler2D tDiffuse;", 39 | "uniform float amount;", 40 | "uniform float angle;", 41 | 42 | "varying vec2 vUv;", 43 | 44 | "void main() {", 45 | 46 | "vec2 offset = amount * vec2( cos(angle), sin(angle));", 47 | "vec4 cr = texture2D(tDiffuse, vUv + offset);", 48 | "vec4 cga = texture2D(tDiffuse, vUv);", 49 | "vec4 cb = texture2D(tDiffuse, vUv - offset);", 50 | "gl_FragColor = vec4(cr.r, cga.g, cb.b, cga.a);", 51 | 52 | "}" 53 | 54 | ].join("\n") 55 | 56 | }; 57 | -------------------------------------------------------------------------------- /web-app/animations/kaleidoscope/lib/postprocessing/EffectComposer.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @author alteredq / http://alteredqualia.com/ 3 | */ 4 | 5 | THREE.EffectComposer = function ( renderer, renderTarget ) { 6 | 7 | this.renderer = renderer; 8 | 9 | this.renderTarget1 = renderTarget; 10 | 11 | if ( this.renderTarget1 === undefined ) { 12 | 13 | var width = window.innerWidth || 1; 14 | var height = window.innerHeight || 1; 15 | 16 | this.renderTargetParameters = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat, stencilBuffer: false }; 17 | this.renderTarget1 = new THREE.WebGLRenderTarget( width, height, this.renderTargetParameters ); 18 | 19 | } 20 | 21 | this.renderTarget2 = this.renderTarget1.clone(); 22 | 23 | this.writeBuffer = this.renderTarget1; 24 | this.readBuffer = this.renderTarget2; 25 | 26 | this.passes = []; 27 | 28 | if ( THREE.CopyShader === undefined ) 29 | console.error( "THREE.EffectComposer relies on THREE.CopyShader" ); 30 | 31 | this.copyPass = new THREE.ShaderPass( THREE.CopyShader ); 32 | 33 | }; 34 | 35 | THREE.EffectComposer.prototype = { 36 | 37 | swapBuffers: function() { 38 | 39 | var tmp = this.readBuffer; 40 | this.readBuffer = this.writeBuffer; 41 | this.writeBuffer = tmp; 42 | 43 | }, 44 | 45 | addPass: function ( pass ) { 46 | 47 | this.passes.push( pass ); 48 | 49 | }, 50 | 51 | render: function ( delta ) { 52 | 53 | this.writeBuffer = this.renderTarget1; 54 | this.readBuffer = this.renderTarget2; 55 | 56 | var maskActive = false; 57 | 58 | var pass, i, il = this.passes.length; 59 | 60 | for ( i = 0; i < il; i ++ ) { 61 | 62 | pass = this.passes[ i ]; 63 | 64 | if ( !pass.enabled ) continue; 65 | 66 | pass.render( this.renderer, this.writeBuffer, this.readBuffer, delta, maskActive ); 67 | 68 | if ( pass.needsSwap ) { 69 | 70 | if ( maskActive ) { 71 | 72 | var context = this.renderer.context; 73 | 74 | context.stencilFunc( context.NOTEQUAL, 1, 0xffffffff ); 75 | 76 | this.copyPass.render( this.renderer, this.writeBuffer, this.readBuffer, delta ); 77 | 78 | context.stencilFunc( context.EQUAL, 1, 0xffffffff ); 79 | 80 | } 81 | 82 | this.swapBuffers(); 83 | 84 | } 85 | 86 | if ( pass instanceof THREE.MaskPass ) { 87 | 88 | maskActive = true; 89 | 90 | } else if ( pass instanceof THREE.ClearMaskPass ) { 91 | 92 | maskActive = false; 93 | 94 | } 95 | 96 | } 97 | 98 | }, 99 | 100 | reset: function ( renderTarget ) { 101 | 102 | this.renderTarget1 = renderTarget; 103 | 104 | if ( this.renderTarget1 === undefined ) { 105 | 106 | this.renderTarget1 = new THREE.WebGLRenderTarget( window.innerWidth, window.innerHeight, this.renderTargetParameters ); 107 | 108 | } 109 | 110 | this.renderTarget2 = this.renderTarget1.clone(); 111 | 112 | this.writeBuffer = this.renderTarget1; 113 | this.readBuffer = this.renderTarget2; 114 | 115 | } 116 | 117 | }; 118 | 119 | // shared ortho camera 120 | 121 | THREE.EffectComposer.camera = new THREE.OrthographicCamera( -1, 1, 1, -1, 0, 1 ); 122 | 123 | THREE.EffectComposer.quad = new THREE.Mesh( new THREE.PlaneGeometry( 2, 2 ), null ); 124 | 125 | THREE.EffectComposer.scene = new THREE.Scene(); 126 | THREE.EffectComposer.scene.add( THREE.EffectComposer.quad ); 127 | -------------------------------------------------------------------------------- /web-app/animations/kaleidoscope/lib/postprocessing/MaskPass.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @author alteredq / http://alteredqualia.com/ 3 | */ 4 | 5 | THREE.MaskPass = function ( scene, camera ) { 6 | 7 | this.scene = scene; 8 | this.camera = camera; 9 | 10 | this.enabled = true; 11 | this.clear = true; 12 | this.needsSwap = false; 13 | 14 | this.inverse = false; 15 | 16 | }; 17 | 18 | THREE.MaskPass.prototype = { 19 | 20 | render: function ( renderer, writeBuffer, readBuffer, delta ) { 21 | 22 | var context = renderer.context; 23 | 24 | // don't update color or depth 25 | 26 | context.colorMask( false, false, false, false ); 27 | context.depthMask( false ); 28 | 29 | // set up stencil 30 | 31 | var writeValue, clearValue; 32 | 33 | if ( this.inverse ) { 34 | 35 | writeValue = 0; 36 | clearValue = 1; 37 | 38 | } else { 39 | 40 | writeValue = 1; 41 | clearValue = 0; 42 | 43 | } 44 | 45 | context.enable( context.STENCIL_TEST ); 46 | context.stencilOp( context.REPLACE, context.REPLACE, context.REPLACE ); 47 | context.stencilFunc( context.ALWAYS, writeValue, 0xffffffff ); 48 | context.clearStencil( clearValue ); 49 | 50 | // draw into the stencil buffer 51 | 52 | renderer.render( this.scene, this.camera, readBuffer, this.clear ); 53 | renderer.render( this.scene, this.camera, writeBuffer, this.clear ); 54 | 55 | // re-enable update of color and depth 56 | 57 | context.colorMask( true, true, true, true ); 58 | context.depthMask( true ); 59 | 60 | // only render where stencil is set to 1 61 | 62 | context.stencilFunc( context.EQUAL, 1, 0xffffffff ); // draw if == 1 63 | context.stencilOp( context.KEEP, context.KEEP, context.KEEP ); 64 | 65 | } 66 | 67 | }; 68 | 69 | 70 | THREE.ClearMaskPass = function () { 71 | 72 | this.enabled = true; 73 | 74 | }; 75 | 76 | THREE.ClearMaskPass.prototype = { 77 | 78 | render: function ( renderer, writeBuffer, readBuffer, delta ) { 79 | 80 | var context = renderer.context; 81 | 82 | context.disable( context.STENCIL_TEST ); 83 | 84 | } 85 | 86 | }; 87 | -------------------------------------------------------------------------------- /web-app/animations/kaleidoscope/lib/postprocessing/RenderPass.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @author alteredq / http://alteredqualia.com/ 3 | */ 4 | 5 | THREE.RenderPass = function ( scene, camera, overrideMaterial, clearColor, clearAlpha ) { 6 | 7 | this.scene = scene; 8 | this.camera = camera; 9 | 10 | this.overrideMaterial = overrideMaterial; 11 | 12 | this.clearColor = clearColor; 13 | this.clearAlpha = ( clearAlpha !== undefined ) ? clearAlpha : 1; 14 | 15 | this.oldClearColor = new THREE.Color(); 16 | this.oldClearAlpha = 1; 17 | 18 | this.enabled = true; 19 | this.clear = true; 20 | this.needsSwap = false; 21 | 22 | }; 23 | 24 | THREE.RenderPass.prototype = { 25 | 26 | render: function ( renderer, writeBuffer, readBuffer, delta ) { 27 | 28 | this.scene.overrideMaterial = this.overrideMaterial; 29 | 30 | if ( this.clearColor ) { 31 | 32 | this.oldClearColor.copy( renderer.getClearColor() ); 33 | this.oldClearAlpha = renderer.getClearAlpha(); 34 | 35 | renderer.setClearColor( this.clearColor, this.clearAlpha ); 36 | 37 | } 38 | 39 | renderer.render( this.scene, this.camera, readBuffer, this.clear ); 40 | 41 | if ( this.clearColor ) { 42 | 43 | renderer.setClearColor( this.oldClearColor, this.oldClearAlpha ); 44 | 45 | } 46 | 47 | this.scene.overrideMaterial = null; 48 | 49 | } 50 | 51 | }; 52 | -------------------------------------------------------------------------------- /web-app/animations/kaleidoscope/lib/postprocessing/ShaderPass.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @author alteredq / http://alteredqualia.com/ 3 | */ 4 | 5 | THREE.ShaderPass = function ( shader, textureID ) { 6 | 7 | this.textureID = ( textureID !== undefined ) ? textureID : "tDiffuse"; 8 | 9 | this.uniforms = THREE.UniformsUtils.clone( shader.uniforms ); 10 | 11 | this.material = new THREE.ShaderMaterial( { 12 | 13 | uniforms: this.uniforms, 14 | vertexShader: shader.vertexShader, 15 | fragmentShader: shader.fragmentShader 16 | 17 | } ); 18 | 19 | this.renderToScreen = false; 20 | 21 | this.enabled = true; 22 | this.needsSwap = true; 23 | this.clear = false; 24 | 25 | }; 26 | 27 | THREE.ShaderPass.prototype = { 28 | 29 | render: function ( renderer, writeBuffer, readBuffer, delta ) { 30 | 31 | if ( this.uniforms[ this.textureID ] ) { 32 | 33 | this.uniforms[ this.textureID ].value = readBuffer; 34 | 35 | } 36 | 37 | THREE.EffectComposer.quad.material = this.material; 38 | 39 | if ( this.renderToScreen ) { 40 | 41 | renderer.render( THREE.EffectComposer.scene, THREE.EffectComposer.camera ); 42 | 43 | } else { 44 | 45 | renderer.render( THREE.EffectComposer.scene, THREE.EffectComposer.camera, writeBuffer, this.clear ); 46 | 47 | } 48 | 49 | } 50 | 51 | }; 52 | -------------------------------------------------------------------------------- /web-app/animations/kaleidoscope/lib/shaders/CopyShader.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @author alteredq / http://alteredqualia.com/ 3 | * 4 | * Full-screen textured quad shader 5 | */ 6 | 7 | THREE.CopyShader = { 8 | 9 | uniforms: { 10 | 11 | "tDiffuse": { value: null }, 12 | "opacity": { value: 1.0 } 13 | 14 | }, 15 | 16 | vertexShader: [ 17 | 18 | "varying vec2 vUv;", 19 | 20 | "void main() {", 21 | 22 | "vUv = uv;", 23 | "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", 24 | 25 | "}" 26 | 27 | ].join( "\n" ), 28 | 29 | fragmentShader: [ 30 | 31 | "uniform float opacity;", 32 | 33 | "uniform sampler2D tDiffuse;", 34 | 35 | "varying vec2 vUv;", 36 | 37 | "void main() {", 38 | 39 | "vec4 texel = texture2D( tDiffuse, vUv );", 40 | "gl_FragColor = opacity * texel;", 41 | 42 | "}" 43 | 44 | ].join( "\n" ) 45 | 46 | }; 47 | -------------------------------------------------------------------------------- /web-app/animations/kaleidoscope/main.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Animation from felixturner - http://airtight.cc 3 | */ 4 | 5 | function Kaleidoscope() { 6 | 7 | this.rgbParams; 8 | this.rgbPass; 9 | this.kaleidoParams; 10 | this.kaleidoPass; 11 | this.composer; 12 | this.cubeHolder; 13 | 14 | 15 | this.getPath = function (ctx) { 16 | return 'animations/kaleidoscope'; 17 | } 18 | 19 | this.init = function (camera, scene, renderer) { 20 | camera = new THREE.PerspectiveCamera(50, 1.0, 0.1, 10000); 21 | camera.position.z = 1000; 22 | 23 | //init object to hold cubes and rotate 24 | this.cubeHolder = new THREE.Object3D(); 25 | scene.add(this.cubeHolder); 26 | 27 | //add light 28 | var light = new THREE.PointLight(0xFFFFFF, 1); 29 | light.position = new THREE.Vector3(1000, 1000, 1000); 30 | scene.add(light); 31 | 32 | //use lambert material to get greyscale shadows 33 | var material = new THREE.MeshLambertMaterial(); 34 | 35 | //create cubes 36 | var geometry = new THREE.CubeGeometry(100, 100, 100); 37 | var spread = 2000; 38 | for(var j = 0; j < 100; j++) { 39 | var cube = new THREE.Mesh(geometry, material); 40 | //randomize size, posn + rotation 41 | cube.scale.x = cube.scale.y = cube.scale.z = Math.random() * 3 + .05; 42 | this.cubeHolder.add(cube); 43 | cube.position.x = Math.random() * spread - spread / 2; 44 | cube.position.y = Math.random() * spread - spread / 2; 45 | cube.position.z = Math.random() * spread - spread / 2; 46 | cube.rotation.x = Math.random() * 2 * Math.PI - Math.PI; 47 | cube.rotation.y = Math.random() * 2 * Math.PI - Math.PI; 48 | cube.rotation.z = Math.random() * 2 * Math.PI - Math.PI; 49 | } 50 | 51 | //POST PROCESSING 52 | //Create Shader Passes 53 | //render pass renders scene into effects composer 54 | var renderPass = new THREE.RenderPass( scene, camera ); 55 | this.rgbPass = new THREE.ShaderPass( THREE.RGBShiftShader ); 56 | this.kaleidoPass = new THREE.ShaderPass( THREE.KaleidoShader ); 57 | 58 | //Add Shader Passes to Composer 59 | //order is important 60 | this.composer = new THREE.EffectComposer( renderer); 61 | this.composer.addPass( renderPass ); 62 | this.composer.addPass( this.kaleidoPass ); 63 | this.composer.addPass( this.rgbPass ); 64 | 65 | //set last pass in composer chain to renderToScreen 66 | this.rgbPass.renderToScreen = true; 67 | 68 | this.rgbPass.uniforms[ "angle" ].value = 0.0*3.1416; 69 | this.rgbPass.uniforms[ "amount" ].value = 0.005; 70 | this.kaleidoPass.uniforms[ "sides" ].value = 12; 71 | this.kaleidoPass.uniforms[ "angle" ].value = 0.0*3.1416; 72 | } 73 | 74 | this.updateDefault = function () { 75 | this.cubeHolder.rotation.y += 0.002; 76 | this.cubeHolder.rotation.x += 0.002; 77 | this.composer.render(0.1); 78 | } 79 | 80 | this.update = function (timeDelta, parameters) { 81 | this.cubeHolder.rotation.y += parameters.rotationY; 82 | this.cubeHolder.rotation.x += parameters.rotationX; 83 | this.rgbPass.uniforms[ "angle" ].value = parameters.angleRGB*3.1416; 84 | this.rgbPass.uniforms[ "amount" ].value = parameters.amount; 85 | this.kaleidoPass.uniforms[ "sides" ].value = parameters.sides; 86 | this.composer.render(0.1); 87 | } 88 | } -------------------------------------------------------------------------------- /web-app/animations/kaleidoscope/parameters.json: -------------------------------------------------------------------------------- 1 | { 2 | "parameters": [ 3 | { "name": "rotationX", "avg": 0.004, "min": 0.0, "max": 0.008, "step": -1, "blur": 1, "FPS": 1.0 }, 4 | { "name": "rotationY", "avg": 0.004, "min": 0.0, "max": 0.008, "step": -1, "blur": 1, "FPS": 1.0 }, 5 | { "name": "amount", "avg": 0.1, "min": 0.0, "max": 1.0, "step": -1, "blur": 100, "FPS": 0.1 }, 6 | { "name": "sides", "avg": 12, "min": 0, "max": 24, "step": -1, "blur": 100, "FPS": 0.02 }, 7 | { "name": "angleRGB", "avg": 0.5, "min": 0.0, "max": 2.0, "step": -1, "blur": 100, "FPS": 0.1 }, 8 | { "name": "nothing1", "avg": 0.0, "min": 0.0, "max": 1.0, "step": -1, "blur": 1, "FPS": 0.0 }, 9 | { "name": "nothing2", "avg": 0.0, "min": 0.0, "max": 1.0, "step": -1, "blur": 1, "FPS": 0.0 }, 10 | { "name": "nothing3", "avg": 0.0, "min": 0.0, "max": 1.0, "step": -1, "blur": 1, "FPS": 0.0 }, 11 | { "name": "nothing4", "avg": 0.0, "min": 0.0, "max": 1.0, "step": -1, "blur": 1, "FPS": 0.0 }, 12 | { "name": "nothing5", "avg": 0.0, "min": 0.0, "max": 1.0, "step": -1, "blur": 1, "FPS": 0.0 } 13 | ] 14 | } -------------------------------------------------------------------------------- /web-app/animations/lights/main.js: -------------------------------------------------------------------------------- 1 | /***************************************************/ 2 | /* Animation using the "Particulate.js" library. 3 | /* Inspired from one of its example. 4 | /* 5 | /* https://particulatejs.org 6 | /***************************************************/ 7 | 8 | function Lights() { 9 | 10 | this.simulation = null; 11 | this.composer = null; 12 | this.lines = null; 13 | this.renderer = null; 14 | this.visParticles = null; 15 | this.visConnectors = null; 16 | this.bounds = null; 17 | this.distances = null; 18 | 19 | this.dots = null; 20 | this.texture = null; 21 | 22 | this.getPath = function () { 23 | return 'animations/lights'; 24 | } 25 | 26 | this.init = function (camera, scene, renderer) { 27 | 28 | //*********************/ 29 | // Init scene 30 | //*********************/ 31 | scene.fog = new THREE.Fog(0x050505, 1, 200); 32 | camera.position.set(0, 50, -40); 33 | camera.lookAt(scene.position); 34 | 35 | 36 | //*********************/ 37 | // Init simulation 38 | //*********************/ 39 | var tris = 1000; 40 | var particles = tris * 3; 41 | var distance = 1.0; 42 | simulation = Particulate.ParticleSystem.create(particles, 2); 43 | 44 | this.bounds = Particulate.PointForce.create([0, 0, 0], { 45 | type : Particulate.Force.ATTRACTOR_REPULSOR, 46 | intensity : 0.05, 47 | radius : 15.0 48 | }); 49 | 50 | var linkIndices = []; 51 | var visIndices = []; 52 | (function () { 53 | var a, b, c; 54 | for (var i = 2, il = particles; i < il; i ++) { 55 | a = i; 56 | b = a - 1; 57 | c = a - 2; 58 | linkIndices.push(a, b, b, c, c, a); 59 | visIndices.push(a); 60 | } 61 | }()); 62 | 63 | simulation.each(function (i) { 64 | simulation.setPosition(i, 65 | (Math.random() - 0.5) * 10, 66 | (Math.random() - 0.5) * 10, 67 | (Math.random() - 0.5) * 10); 68 | }); 69 | 70 | this.distances = Particulate.DistanceConstraint.create([distance * 0.5, distance], linkIndices); 71 | 72 | simulation.addConstraint(this.distances); 73 | simulation.addForce(this.bounds); 74 | 75 | (function relax() { 76 | for (var i = 0; i < 50; i ++) { 77 | this.simulation.tick(1); 78 | } 79 | }()); 80 | 81 | this.simulation = simulation; 82 | 83 | 84 | //*********************/ 85 | // Init visualization 86 | //*********************/ 87 | var vertices = new THREE.BufferAttribute(this.simulation.positions, 3); 88 | var indices = new THREE.BufferAttribute(new Uint16Array(visIndices), 1); 89 | 90 | // Particles 91 | this.texture = THREE.ImageUtils.loadTexture(this.getPath() + '/particle.png'); 92 | this.dots = new THREE.BufferGeometry(); 93 | this.dots.addAttribute('position', vertices); 94 | 95 | this.visParticles = new THREE.PointCloud(this.dots, 96 | new THREE.PointCloudMaterial({ 97 | color : "hsl(220, 50%, 50%)", 98 | blending : THREE.AdditiveBlending, 99 | transparent : true, 100 | map : this.texture, 101 | size : 1.0, 102 | opacity : 0.7 103 | })); 104 | 105 | // Connections 106 | this.lines = new THREE.BufferGeometry(); 107 | this.lines.addAttribute('position', vertices); 108 | this.lines.addAttribute('index', indices); 109 | 110 | this.visConnectors = new THREE.Line(this.lines, 111 | new THREE.LineBasicMaterial({ 112 | blending : THREE.AdditiveBlending, 113 | transparent : true, 114 | color : "hsl(220, 50%, 50%)", 115 | linewidth : 1, 116 | opacity : 0.7 117 | })); 118 | 119 | scene.add(this.visParticles); 120 | scene.add(this.visConnectors); 121 | 122 | 123 | //*********************/ 124 | // Init renderer 125 | //*********************/ 126 | renderer.autoClear = false; 127 | renderer.setClearColor(0x050505, 1); 128 | 129 | 130 | //*********************/ 131 | // Init post FX 132 | //*********************/ 133 | this.composer = new THREE.EffectComposer(renderer); 134 | var renderScene = new THREE.RenderPass(scene, camera); 135 | var bloom = new THREE.BloomPass(2.0); 136 | var copy = new THREE.ShaderPass(THREE.CopyShader); 137 | 138 | copy.renderToScreen = true; 139 | 140 | this.composer.addPass(renderScene); 141 | this.composer.addPass(bloom); 142 | this.composer.addPass(copy); 143 | } 144 | 145 | this.updateDefault = function () { 146 | this.composer.render(0.1); 147 | this.simulation.tick(0.5); 148 | this.lines.attributes.position.needsUpdate = true; 149 | } 150 | 151 | this.update = function (timeDelta, parameters) { 152 | 153 | var colorString = "hsl(" + parameters.hue + ", " + parameters.saturation + "%, " + parameters.lightness + "%)" 154 | this.visParticles.material.color = new THREE.Color( colorString ); 155 | this.visConnectors.material.color = new THREE.Color( colorString ); 156 | 157 | this.visConnectors.material.opacity = parameters.opacity; 158 | this.visParticles.material.opacity = parameters.opacity; 159 | 160 | this.visParticles.material.size = parameters.size; 161 | 162 | this.distances.setDistance(parameters.edgesDistance); 163 | this.simulation.setWeights(parameters.particlesWeight); 164 | 165 | this.composer.render(0.1); 166 | this.simulation.tick(0.5); 167 | this.lines.attributes.position.needsUpdate = true; 168 | } 169 | } -------------------------------------------------------------------------------- /web-app/animations/lights/parameters.json: -------------------------------------------------------------------------------- 1 | { 2 | "parameters": [ 3 | { "name": "particlesWeight", "avg": 0.6, "min": 0.001, "max": 2.0, "step": -1, "blur": 300, "FPS": 0.2 }, 4 | { "name": "edgesDistance", "avg": 0.8, "min": 0.2, "max": 1.0, "step": -1, "blur": 300, "FPS": 0.8 }, 5 | { "name": "hue", "avg": 200, "min": 150, "max": 255, "step": 1, "blur": 100, "FPS": 0.06 }, 6 | { "name": "saturation", "avg": 50, "min": 43, "max": 57, "step": 1, "blur": 1, "FPS": 4.0 }, 7 | { "name": "lightness", "avg": 50, "min": 43, "max": 57, "step": 1, "blur": 1, "FPS": 4.0 }, 8 | { "name": "opacity", "avg": 0.7, "min": 0.5, "max": 0.9, "step": -1, "blur": 50, "FPS": 0.2 }, 9 | { "name": "size", "avg": 1.0, "min": 0.7, "max": 3.0, "step": -1, "blur": 300, "FPS": 0.1 }, 10 | { "name": "empty1", "avg": 0.5, "min": 0.0, "max": 1.0, "step": 0.001, "blur": 1, "FPS": -1 }, 11 | { "name": "empty2", "avg": 0.5, "min": 0.0, "max": 1.0, "step": 0.001, "blur": 1, "FPS": -1 }, 12 | { "name": "empty3", "avg": 0.5, "min": 0.0, "max": 1.0, "step": 0.001, "blur": 1, "FPS": -1 } 13 | ] 14 | } -------------------------------------------------------------------------------- /web-app/animations/lights/particle.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/br-g/Deep-Audio-Visualization/9dce262cbbe18fed0b5f2e9e0e49d4b4556ec4b2/web-app/animations/lights/particle.png -------------------------------------------------------------------------------- /web-app/animations/lights/particulate.js: -------------------------------------------------------------------------------- 1 | // .................................................. 2 | // Particulate.js 3 | // 4 | // version : 0.3.3 5 | // authors : Jay Weeks 6 | // license : MIT 7 | // particulatejs.org 8 | // .................................................. 9 | 10 | (function (global, factory) { 11 | typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : 12 | typeof define === 'function' && define.amd ? define(['exports'], factory) : 13 | (factory((global.Particulate = global.Particulate || {}))); 14 | }(this, function (exports) { 'use strict'; 15 | 16 | /** 17 | @module utils 18 | @class Particulate 19 | */ 20 | 21 | /** 22 | Functional constructor utility. 23 | 24 | @method ctor 25 | @param {Function} Ctor Constructor function used to instantiate class 26 | @return {Function} constructor 27 | @private 28 | @static 29 | */ 30 | function ctor(Ctor) { 31 | return function () { 32 | var instance = Object.create(Ctor.prototype) 33 | Ctor.apply(instance, arguments) 34 | return instance 35 | } 36 | } 37 | 38 | /** 39 | Functional inheritance utility 40 | 41 | @method inherit 42 | @param {Function} Ctor Class constructor 43 | @param {Function} ParentCtor Parent class constructor 44 | @private 45 | @static 46 | */ 47 | function inherit(Ctor, ParentCtor) { 48 | Ctor.create = ctor(Ctor) 49 | Ctor.prototype = Object.create(ParentCtor.prototype) 50 | Ctor.prototype.constructor = Ctor 51 | } 52 | 53 | /** 54 | @module math 55 | @main math 56 | */ 57 | 58 | /** 59 | Math utilities. 60 | 61 | @class Math 62 | @static 63 | */ 64 | 65 | /** 66 | Clamp value to `[min, max]` range. 67 | 68 | @method clamp 69 | @static 70 | @param {Float} min 71 | @param {Float} max 72 | @param {Float} v Value to clamp 73 | @return {Float} Clamped value 74 | */ 75 | function clamp (min, max, v) { 76 | return Math.min(Math.max(v, min), max) 77 | } 78 | 79 | /** 80 | Constraints define relationships between multiple particles or 81 | between particles and geometric primitives. 82 | 83 | @module constraints 84 | @main constraints 85 | */ 86 | 87 | /** 88 | Base class for defining particle constraints. 89 | 90 | @class Constraint 91 | @constructor 92 | @param {Int} size Number of indices to be stored 93 | @param {Int} itemSize Number of particles per constraint relation 94 | @param {Int} [indexOffset] Number of indices to save at beginning of index array 95 | */ 96 | function Constraint(size, itemSize, indexOffset) { 97 | indexOffset = indexOffset || 0 98 | 99 | /** 100 | Particle indices defining constraint relations 101 | 102 | @property indices 103 | @type Uint16Array 104 | */ 105 | this.indices = new Uint16Array(size + indexOffset) 106 | 107 | /** 108 | Number of constraint relations managed by this instance 109 | 110 | @property _count 111 | @type Int 112 | @private 113 | */ 114 | this._count = size / itemSize 115 | 116 | /** 117 | Number of particles per constraint relation 118 | 119 | @property _itemSize 120 | @type Int 121 | @private 122 | */ 123 | this._itemSize = itemSize 124 | 125 | /** 126 | Number of indices to save at beginning of index array 127 | 128 | @property _offset 129 | @type Int 130 | @private 131 | */ 132 | this._offset = indexOffset 133 | } 134 | 135 | /** 136 | Create instance, accepts constructor arguments. 137 | 138 | @method create 139 | @static 140 | */ 141 | inherit(Constraint, Object) 142 | 143 | /** 144 | Set particle indices with `Array` or list of `arguments`. 145 | 146 | @method setIndices 147 | @param {Int|Array} indices Single or many particle indices 148 | @param {Int} [...a] Particle index 149 | */ 150 | Constraint.prototype.setIndices = function (indices) { 151 | var offset = this._offset 152 | var inx = indices.length ? indices : arguments 153 | var ii = this.indices 154 | 155 | for (var i = 0; i < inx.length; i ++) { 156 | ii[i + offset] = inx[i] 157 | } 158 | } 159 | 160 | /** 161 | Apply constraint to one set of particles defining a constrint relation. 162 | Called `_count` times per relaxation loop. 163 | 164 | @method applyConstraint 165 | @param {Int} index Constraint set index 166 | @param {Float32Array (Vec3)} p0 Reference to `ParticleSystem.positions` 167 | @param {Float32Array (Vec3)} p1 Reference to `ParticleSystem.positionsPrev` 168 | @protected 169 | */ 170 | Constraint.prototype.applyConstraint = function (index, p0, p1) {} 171 | 172 | /** 173 | @module constraints 174 | */ 175 | 176 | /** 177 | Defines one or many relationships between sets of three particles. 178 | 179 | ```javascript 180 | var a = 0, b = 1, c = 2 181 | var single = AngleConstraint.create(Math.PI, a, b, c) 182 | var many = AngleConstraint.create(Math.PI, [a, b, c, b, c, a]) 183 | ``` 184 | 185 | Particles are constrained by a fixed angle or an angle range. 186 | The angle is defined by segments `ab` and `bc`. 187 | 188 | ```javascript 189 | var min = Math.PI * 0.25, max = Math.PI * 0.5 190 | var fixed = AngleConstraint.create(max, 0, 1, 2) 191 | var range = AngleConstraint.create([min, max], 0, 1, 2) 192 | ``` 193 | 194 | @class AngleConstraint 195 | @extends Constraint 196 | @constructor 197 | @param {Float|Array} angle Angle or angle range `[min, max]` between particles 198 | @param {Int|Array} a Particle index or list of many constraint sets 199 | @param {Int} [b] Particle index (only used if `a` is not an array) 200 | @param {Int} [c] Particle index (only used if `a` is not an array) 201 | */ 202 | function AngleConstraint(angle, a, b, c) { 203 | var size = a.length || arguments.length - 1 204 | var min = angle.length ? angle[0] : angle 205 | var max = angle.length ? angle[1] : angle 206 | 207 | Constraint.call(this, size, 3) 208 | this.setAngle(min, max) 209 | this.setIndices(a, b, c) 210 | } 211 | 212 | /** 213 | Create instance, accepts constructor arguments. 214 | 215 | @method create 216 | @static 217 | */ 218 | inherit(AngleConstraint, Constraint) 219 | 220 | /** 221 | Set angle 222 | 223 | @method setAngle 224 | @param {Float} min 225 | @param {Float} [max] 226 | */ 227 | AngleConstraint.prototype.setAngle = function (min, max) { 228 | max = max != null ? max : min 229 | this.setMin(min) 230 | this.setMax(max) 231 | } 232 | 233 | /** 234 | Set minimum angle 235 | 236 | @method setMin 237 | @param {Float} min 238 | */ 239 | AngleConstraint.prototype.setMin = function (min) { 240 | this._min = this.clampAngle(min) 241 | } 242 | 243 | /** 244 | Minimum angle 245 | 246 | @property _min 247 | @type Float 248 | @private 249 | */ 250 | AngleConstraint.prototype._min = null 251 | 252 | /** 253 | Set maximum angle 254 | 255 | @method setMax 256 | @param {Float} max 257 | */ 258 | AngleConstraint.prototype.setMax = function (max) { 259 | this._max = this.clampAngle(max) 260 | } 261 | 262 | /** 263 | Maximum angle 264 | 265 | @property _max 266 | @type Float 267 | @private 268 | */ 269 | AngleConstraint.prototype._max = null 270 | 271 | AngleConstraint.prototype.clampAngle = function (angle) { 272 | var p = 0.0000001 273 | return clamp(p, Math.PI - p, angle) 274 | } 275 | 276 | /** 277 | Angle used to classify obtuse angles in constraint solver. For accute angles, 278 | only particles `a` and `c` are repositioned to satisfy the particle set's 279 | target angle. For obtuse angles, particle `b` is also repositioned. 280 | 281 | @property ANGLE_OBTUSE 282 | @type Float 283 | @default 3/4 Π 284 | @static 285 | @final 286 | */ 287 | AngleConstraint.ANGLE_OBTUSE = Math.PI * 0.75 288 | 289 | // TODO: Optimize, reduce usage of Math.sqrt 290 | AngleConstraint.prototype.applyConstraint = function (index, p0, p1) { 291 | /*jshint maxcomplexity:15*/ 292 | 293 | var ii = this.indices 294 | var ai = ii[index], bi = ii[index + 1], ci = ii[index + 2] 295 | 296 | var aix = ai * 3, aiy = aix + 1, aiz = aix + 2 297 | var bix = bi * 3, biy = bix + 1, biz = bix + 2 298 | var cix = ci * 3, ciy = cix + 1, ciz = cix + 2 299 | 300 | // AB (A -> B) 301 | var abX = p0[bix] - p0[aix] 302 | var abY = p0[biy] - p0[aiy] 303 | var abZ = p0[biz] - p0[aiz] 304 | 305 | // BC (B -> C) 306 | var bcX = p0[cix] - p0[bix] 307 | var bcY = p0[ciy] - p0[biy] 308 | var bcZ = p0[ciz] - p0[biz] 309 | 310 | // AC (A -> C) 311 | var acX = p0[cix] - p0[aix] 312 | var acY = p0[ciy] - p0[aiy] 313 | var acZ = p0[ciz] - p0[aiz] 314 | 315 | // Perturb coincident particles 316 | if (!(acX || acY || acZ)) { 317 | p0[aix] += 0.1 318 | p0[biy] += 0.1 319 | p0[cix] -= 0.1 320 | return 321 | } 322 | 323 | var abLenSq = abX * abX + abY * abY + abZ * abZ 324 | var bcLenSq = bcX * bcX + bcY * bcY + bcZ * bcZ 325 | var acLenSq = acX * acX + acY * acY + acZ * acZ 326 | 327 | var abLen = Math.sqrt(abLenSq) 328 | var bcLen = Math.sqrt(bcLenSq) 329 | var acLen = Math.sqrt(acLenSq) 330 | 331 | var abLenInv = 1 / abLen 332 | var bcLenInv = 1 / bcLen 333 | 334 | var minAngle = this._min 335 | var maxAngle = this._max 336 | var bAngle = Math.acos( 337 | -abX * abLenInv * bcX * bcLenInv + 338 | -abY * abLenInv * bcY * bcLenInv + 339 | -abZ * abLenInv * bcZ * bcLenInv) 340 | 341 | if (bAngle > minAngle && bAngle < maxAngle) { return; } 342 | var bAngleTarget = bAngle < minAngle ? minAngle : maxAngle 343 | 344 | // Target length for AC 345 | var acLenTargetSq = abLenSq + bcLenSq - 2 * abLen * bcLen * Math.cos(bAngleTarget) 346 | var acLenTarget = Math.sqrt(acLenTargetSq) 347 | var acDiff = (acLen - acLenTarget) / acLen * 0.5 348 | 349 | p0[aix] += acX * acDiff 350 | p0[aiy] += acY * acDiff 351 | p0[aiz] += acZ * acDiff 352 | 353 | p0[cix] -= acX * acDiff 354 | p0[ciy] -= acY * acDiff 355 | p0[ciz] -= acZ * acDiff 356 | 357 | // Only manipulate particle B for obtuse targets 358 | if (bAngleTarget < AngleConstraint.ANGLE_OBTUSE) { return; } 359 | 360 | // Target angle for A 361 | var aAngleTarget = Math.acos((abLenSq + acLenTargetSq - bcLenSq) / (2 * abLen * acLenTarget)) 362 | 363 | // Unit vector AC 364 | var acLenInv = 1 / acLen 365 | var acuX = acX * acLenInv 366 | var acuY = acY * acLenInv 367 | var acuZ = acZ * acLenInv 368 | 369 | // Project B onto AC as vector AP 370 | var pt = acuX * abX + acuY * abY + acuZ * abZ 371 | var apX = acuX * pt 372 | var apY = acuY * pt 373 | var apZ = acuZ * pt 374 | 375 | // BP (B -> P) 376 | var bpX = apX - abX 377 | var bpY = apY - abY 378 | var bpZ = apZ - abZ 379 | 380 | // B is inline with AC 381 | if (!(bpX || bpY || bpZ)) { 382 | if (bAngleTarget < Math.PI) { 383 | p0[bix] += 0.1 384 | p0[biy] += 0.1 385 | p0[biz] += 0.1 386 | } 387 | return 388 | } 389 | 390 | var apLenSq = apX * apX + apY * apY + apZ * apZ 391 | var bpLenSq = bpX * bpX + bpY * bpY + bpZ * bpZ 392 | var apLen = Math.sqrt(apLenSq) 393 | var bpLen = Math.sqrt(bpLenSq) 394 | 395 | var bpLenTarget = apLen * Math.tan(aAngleTarget) 396 | var bpDiff = (bpLen - bpLenTarget) / bpLen 397 | 398 | p0[bix] += bpX * bpDiff 399 | p0[biy] += bpY * bpDiff 400 | p0[biz] += bpZ * bpDiff 401 | } 402 | 403 | /** 404 | @module constraints 405 | */ 406 | 407 | /** 408 | Defines one or many relationships between an infinite axis and single particles. 409 | 410 | Orientaiton of the axis is defined by 2 points: `axisA` and `axisB`. 411 | 412 | ```javascript 413 | var axisA = 0, axisB = 1 414 | var a = 2, b = 3, c = 4 415 | var single = AxisConstraint.create(axisA, axisB, a) 416 | var many = AxisConstraint.create(axisA, axisB, [a, b, c]) 417 | ``` 418 | 419 | @class AxisConstraint 420 | @extends Constraint 421 | @constructor 422 | @param {Int} axisA Particle index defining start of axis 423 | @param {Int} axisB Particle index defining end of axis 424 | @param {Int|Array} a Particle index or list of many indices 425 | */ 426 | function AxisConstraint(axisA, axisB, a) { 427 | var size = a.length || 1 428 | 429 | Constraint.call(this, size, 1, 2) 430 | this.setAxis(axisA, axisB) 431 | this.setIndices(a) 432 | } 433 | 434 | /** 435 | Create instance, accepts constructor arguments. 436 | 437 | @method create 438 | @static 439 | */ 440 | inherit(AxisConstraint, Constraint) 441 | 442 | /** 443 | Set particles defining constraint axis 444 | 445 | @method setAxis 446 | @param {Int} a Particle index defining start of axis 447 | @param {Int} b Particle index defining end of axis 448 | */ 449 | AxisConstraint.prototype.setAxis = function (a, b) { 450 | var ii = this.indices 451 | 452 | ii[0] = a 453 | ii[1] = b 454 | } 455 | 456 | AxisConstraint.prototype.applyConstraint = function (index, p0, p1) { 457 | var ii = this.indices 458 | var ai = ii[0], bi = ii[index + 2], ci = ii[1] 459 | 460 | var aix = ai * 3, aiy = aix + 1, aiz = aix + 2 461 | var bix = bi * 3, biy = bix + 1, biz = bix + 2 462 | var cix = ci * 3, ciy = cix + 1, ciz = cix + 2 463 | 464 | // AB (A -> B) 465 | var abX = p0[bix] - p0[aix] 466 | var abY = p0[biy] - p0[aiy] 467 | var abZ = p0[biz] - p0[aiz] 468 | 469 | // AC (A -> C) 470 | var acX = p0[cix] - p0[aix] 471 | var acY = p0[ciy] - p0[aiy] 472 | var acZ = p0[ciz] - p0[aiz] 473 | 474 | var acLenSq = acX * acX + acY * acY + acZ * acZ 475 | var acLen = Math.sqrt(acLenSq) 476 | 477 | // Unit vector AC 478 | var acLenInv = 1 / acLen 479 | var acuX = acX * acLenInv 480 | var acuY = acY * acLenInv 481 | var acuZ = acZ * acLenInv 482 | 483 | // Project B onto AC as vector AP 484 | var pt = acuX * abX + acuY * abY + acuZ * abZ 485 | var apX = acuX * pt 486 | var apY = acuY * pt 487 | var apZ = acuZ * pt 488 | 489 | p0[bix] = p0[aix] + apX 490 | p0[biy] = p0[aiy] + apY 491 | p0[biz] = p0[aiz] + apZ 492 | } 493 | 494 | // .................................................. 495 | // Vec3 496 | // .................................................. 497 | 498 | var Vec3 = {} 499 | /** 500 | @module math 501 | */ 502 | 503 | /** 504 | Vector utilities. 505 | 506 | @class Vec3 507 | @static 508 | */ 509 | 510 | /** 511 | @method create 512 | @static 513 | @param {Int|Array} positions Number of vectors or array of initial values 514 | @return {Float32Array} Vec3 buffer 515 | */ 516 | Vec3.create = function (positions) { 517 | positions = positions || 1 518 | var isCount = typeof positions === 'number' 519 | return new Float32Array(isCount ? positions * 3 : positions) 520 | } 521 | 522 | /** 523 | Set single vector in buffer 524 | 525 | @method set 526 | @static 527 | @param {Array} b0 Vec3 buffer 528 | @param {Int} i Vector index 529 | @param {Array|Float} x Vector or x component value 530 | @param {Float} [y] 531 | @param {Float} [z] 532 | */ 533 | Vec3.set = function (b0, i, x, y, z) { 534 | var ix = i * 3, iy = ix + 1, iz = ix + 2 535 | 536 | if (y == null) { 537 | z = x[2] 538 | y = x[1] 539 | x = x[0] 540 | } 541 | 542 | b0[ix] = x 543 | b0[iy] = y 544 | b0[iz] = z 545 | } 546 | 547 | /** 548 | @method copy 549 | @static 550 | @param {Array} b0 Vec3 buffer 551 | @param {Int} ai Vector index 552 | @param {Array} out Destination vector 553 | */ 554 | Vec3.copy = function (b0, ai, out) { 555 | var aix = ai * 3, aiy = aix + 1, aiz = aix + 2 556 | 557 | out[0] = b0[aix] 558 | out[1] = b0[aiy] 559 | out[2] = b0[aiz] 560 | 561 | return out 562 | } 563 | 564 | /** 565 | @method lengthSq 566 | @static 567 | @param {Array} b0 Vec3 buffer 568 | @param {Int} ai Vector index 569 | @return {Float} Squared length of vector 570 | */ 571 | Vec3.lengthSq = function (b0, ai) { 572 | var aix = ai * 3, aiy = aix + 1, aiz = aix + 2 573 | var x = b0[aix] 574 | var y = b0[aiy] 575 | var z = b0[aiz] 576 | 577 | return x * x + y * y + z * z 578 | } 579 | 580 | /** 581 | @method length 582 | @static 583 | @param {Array} b0 Vec3 buffer 584 | @param {Int} ai Vector index 585 | @return {Float} Length of vector 586 | */ 587 | Vec3.length = function (b0, ai) { 588 | var aix = ai * 3, aiy = aix + 1, aiz = aix + 2 589 | var x = b0[aix] 590 | var y = b0[aiy] 591 | var z = b0[aiz] 592 | 593 | return Math.sqrt(x * x + y * y + z * z) 594 | } 595 | 596 | /** 597 | @method distanceSq 598 | @static 599 | @param {Array} b0 Vec3 buffer 600 | @param {Int} ai Vector index a 601 | @param {Int} bi Vector index b 602 | @return {Float} Squared distance from a to b 603 | */ 604 | Vec3.distanceSq = function (b0, ai, bi) { 605 | var aix = ai * 3, aiy = aix + 1, aiz = aix + 2 606 | var bix = bi * 3, biy = bix + 1, biz = bix + 2 607 | 608 | var dx = b0[aix] - b0[bix] 609 | var dy = b0[aiy] - b0[biy] 610 | var dz = b0[aiz] - b0[biz] 611 | 612 | return dx * dx + dy * dy + dz * dz 613 | } 614 | 615 | /** 616 | @method distance 617 | @static 618 | @param {Array} b0 Vec3 buffer 619 | @param {Int} ai Vector index a 620 | @param {Int} bi Vector index b 621 | @return {Float} Distance from a to b 622 | */ 623 | Vec3.distance = function (b0, ai, bi) { 624 | var aix = ai * 3, aiy = aix + 1, aiz = aix + 2 625 | var bix = bi * 3, biy = bix + 1, biz = bix + 2 626 | 627 | var dx = b0[aix] - b0[bix] 628 | var dy = b0[aiy] - b0[biy] 629 | var dz = b0[aiz] - b0[biz] 630 | 631 | return Math.sqrt(dx * dx + dy * dy + dz * dz) 632 | } 633 | 634 | /** 635 | Normalize vector in place 636 | 637 | @method normalize 638 | @static 639 | @param {Array} b0 Vec3 buffer 640 | @param {Int} ai Vector index a 641 | */ 642 | Vec3.normalize = function (b0, ai) { 643 | var aix = ai * 3, aiy = aix + 1, aiz = aix + 2 644 | var x = b0[aix] 645 | var y = b0[aiy] 646 | var z = b0[aiz] 647 | var lenInv = 1 / Math.sqrt(x * x + y * y + z * z) 648 | 649 | b0[aix] *= lenInv 650 | b0[aiy] *= lenInv 651 | b0[aiz] *= lenInv 652 | } 653 | 654 | /** 655 | Calculate angle between segments `ab` and `bc` 656 | 657 | @method angle 658 | @static 659 | @param {Array} b0 Vec3 buffer 660 | @param {Int} ai Vector index a 661 | @param {Int} bi Vector index b 662 | @param {Int} ci Vector index c 663 | @return {Float} Angle in radians 664 | */ 665 | Vec3.angle = function (b0, ai, bi, ci) { 666 | var aix = ai * 3, aiy = aix + 1, aiz = aix + 2 667 | var bix = bi * 3, biy = bix + 1, biz = bix + 2 668 | var cix = ci * 3, ciy = cix + 1, ciz = cix + 2 669 | 670 | var baLenInv = 1 / Vec3.distance(b0, bi, ai) 671 | var bcLenInv = 1 / Vec3.distance(b0, bi, ci) 672 | 673 | var baX = (b0[aix] - b0[bix]) * baLenInv 674 | var baY = (b0[aiy] - b0[biy]) * baLenInv 675 | var baZ = (b0[aiz] - b0[biz]) * baLenInv 676 | 677 | var bcX = (b0[cix] - b0[bix]) * bcLenInv 678 | var bcY = (b0[ciy] - b0[biy]) * bcLenInv 679 | var bcZ = (b0[ciz] - b0[biz]) * bcLenInv 680 | 681 | var dot = baX * bcX + baY * bcY + baZ * bcZ 682 | 683 | return Math.acos(dot) 684 | } 685 | 686 | /** 687 | @module constraints 688 | */ 689 | 690 | /** 691 | Defines an infinite bounding plane which constrains all particles in the system. 692 | 693 | ```javascript 694 | var origin = [1.0, 2.0, 5.0] 695 | var normal = [0.0, 1.0, 0.0] 696 | var bounds = BoundingPlaneConstraint.create(origin, normal) 697 | var plane = BoundingPlaneConstraint.create(origin, normal, Infinity) 698 | ``` 699 | 700 | @class BoundingPlaneConstraint 701 | @extends Constraint 702 | @constructor 703 | @param {Array (Vec3)} origin Plane origin 704 | @param {Array (Vec3)} normal Plane normal / orientation 705 | @param {Float} [distance] Maximum positive distance to affect particles 706 | */ 707 | function BoundingPlaneConstraint(origin, normal, distance) { 708 | /** 709 | Positive distance from plane within which particles will be constrained. 710 | 711 | A value of `Infinity` will constrain all particles to be inline with the plane, while 712 | the default of `0` constrains all particles to space in front of the plane 713 | relative to its `origin` and orientation `normal`. 714 | 715 | @property distance 716 | @type Float 717 | @default 0 718 | */ 719 | this.distance = distance || 0 720 | 721 | /** 722 | Damping factor to apply to particles being constrained to bounds 723 | 724 | @property friction 725 | @type Float 726 | @default 0.05 727 | */ 728 | this.friction = 0.05 729 | 730 | /** 731 | Vec3 buffer which stores plane origin and normal 732 | 733 | @property bufferVec3 734 | @type Float32Array (Vec3) 735 | @private 736 | */ 737 | this.bufferVec3 = Vec3.create(2) 738 | 739 | this.setOrigin(origin) 740 | this.setNormal(normal) 741 | } 742 | 743 | /** 744 | Create instance, accepts constructor arguments. 745 | 746 | @method create 747 | @static 748 | */ 749 | inherit(BoundingPlaneConstraint, Constraint) 750 | 751 | /** 752 | Global constraint flag 753 | 754 | @property _isGlobal 755 | @type Bool 756 | @private 757 | */ 758 | BoundingPlaneConstraint.prototype._isGlobal = true 759 | 760 | /** 761 | Set origin 762 | 763 | @method setOrigin 764 | @param {Float} x 765 | @param {Float} y 766 | @param {Float} z 767 | */ 768 | BoundingPlaneConstraint.prototype.setOrigin = function (x, y, z) { 769 | Vec3.set(this.bufferVec3, 0, x, y, z) 770 | } 771 | 772 | /** 773 | Set normal (automatically normalizes vector) 774 | 775 | @method setNormal 776 | @param {Float} x 777 | @param {Float} y 778 | @param {Float} z 779 | */ 780 | BoundingPlaneConstraint.prototype.setNormal = function (x, y, z) { 781 | Vec3.set(this.bufferVec3, 1, x, y, z) 782 | Vec3.normalize(this.bufferVec3, 1) 783 | } 784 | 785 | BoundingPlaneConstraint.prototype.applyConstraint = function (index, p0, p1) { 786 | var friction = this.friction 787 | var b0 = this.bufferVec3 788 | var ix = index, iy = ix + 1, iz = ix + 2 789 | 790 | // OP (O -> P) 791 | var opX = p0[ix] - b0[0] 792 | var opY = p0[iy] - b0[1] 793 | var opZ = p0[iz] - b0[2] 794 | 795 | // N 796 | var nX = b0[3] 797 | var nY = b0[4] 798 | var nZ = b0[5] 799 | 800 | // Project OP onto normal vector N 801 | var pt = opX * nX + opY * nY + opZ * nZ 802 | if (pt > this.distance) { return; } 803 | 804 | p0[ix] -= nX * pt 805 | p0[iy] -= nY * pt 806 | p0[iz] -= nZ * pt 807 | 808 | p1[ix] -= (p1[ix] - p0[ix]) * friction 809 | p1[iy] -= (p1[iy] - p0[iy]) * friction 810 | p1[iz] -= (p1[iz] - p0[iz]) * friction 811 | } 812 | 813 | /** 814 | @module constraints 815 | */ 816 | 817 | /** 818 | Defines an axis-aligned bounding box which constrains all particles 819 | in the system to its bounds. 820 | 821 | ```javascript 822 | var min = [-10.0, -10.0, -10.0] 823 | var max = [10.0, 10.0, 10.0] 824 | var box = BoxConstraint.create(min, max) 825 | ``` 826 | 827 | @class BoxConstraint 828 | @extends Constraint 829 | @constructor 830 | @param {Array (Vec3)} min Bounds minimum 831 | @param {Array (Vec3)} max Bounds maximum 832 | */ 833 | function BoxConstraint(min, max) { 834 | /** 835 | Damping factor to apply to particles being constrained to bounds 836 | 837 | @property friction 838 | @type Float 839 | @default 0.05 840 | */ 841 | this.friction = 0.05 842 | 843 | /** 844 | Vec3 buffer which stores bounds 845 | 846 | @property bufferVec3 847 | @type Float32Array (Vec3) 848 | @private 849 | */ 850 | this.bufferVec3 = Vec3.create(2) 851 | 852 | this.setBounds(min, max) 853 | } 854 | 855 | /** 856 | Create instance, accepts constructor arguments. 857 | 858 | @method create 859 | @static 860 | */ 861 | inherit(BoxConstraint, Constraint) 862 | 863 | /** 864 | Global constraint flag 865 | 866 | @property _isGlobal 867 | @type Bool 868 | @private 869 | */ 870 | BoxConstraint.prototype._isGlobal = true 871 | 872 | /** 873 | Set bounds 874 | 875 | @method setBounds 876 | @param {Array (Vec3)} min 877 | @param {Array (Vec3)} max 878 | */ 879 | BoxConstraint.prototype.setBounds = function (min, max) { 880 | this.setMin(min) 881 | this.setMax(max) 882 | } 883 | 884 | /** 885 | Set bounds minimum; alias for `Vec3.set`. 886 | 887 | @method setMin 888 | @param {Float} x 889 | @param {Float} y 890 | @param {Float} z 891 | */ 892 | BoxConstraint.prototype.setMin = function (x, y, z) { 893 | Vec3.set(this.bufferVec3, 0, x, y, z) 894 | } 895 | 896 | /** 897 | Set bounds maximum; alias for `Vec3.set`. 898 | 899 | @method setMin 900 | @param {Float} x 901 | @param {Float} y 902 | @param {Float} z 903 | */ 904 | BoxConstraint.prototype.setMax = function (x, y, z) { 905 | Vec3.set(this.bufferVec3, 1, x, y, z) 906 | } 907 | 908 | BoxConstraint.prototype.applyConstraint = function (index, p0, p1) { 909 | var friction = this.friction 910 | var b0 = this.bufferVec3 911 | var ix = index, iy = ix + 1, iz = ix + 2 912 | 913 | var px = clamp(b0[0], b0[3], p0[ix]) 914 | var py = clamp(b0[1], b0[4], p0[iy]) 915 | var pz = clamp(b0[2], b0[5], p0[iz]) 916 | 917 | var dx = p0[ix] - px 918 | var dy = p0[iy] - py 919 | var dz = p0[iz] - pz 920 | 921 | p0[ix] = px 922 | p0[iy] = py 923 | p0[iz] = pz 924 | 925 | if (dx || dy || dz) { 926 | p1[ix] -= (p1[ix] - px) * friction 927 | p1[iy] -= (p1[iy] - py) * friction 928 | p1[iz] -= (p1[iz] - pz) * friction 929 | } 930 | } 931 | 932 | /** 933 | @module constraints 934 | */ 935 | 936 | /** 937 | Defines one or many relationships between sets of two particles. 938 | 939 | ```javascript 940 | var a = 0, b = 1, c = 2 941 | var single = DistanceConstraint.create(10, a, b) 942 | var many = DistanceConstraint.create(10, [a, b, a, c]) 943 | ``` 944 | 945 | Particles are constrained by a fixed distance or a distance range. 946 | 947 | ```javascript 948 | var min = 0.5, max = 2.5 949 | var fixed = DistanceConstraint.create(max, 0, 1) 950 | var range = DistanceConstraint.create([min, max], 0, 1) 951 | ``` 952 | 953 | @class DistanceConstraint 954 | @extends Constraint 955 | @constructor 956 | @param {Float|Array} distance Distance or distance range `[min, max]` between particles 957 | @param {Int|Array} a Particle index or list of many constraint sets 958 | @param {Int} [b] Particle index (only used if `a` is not an array) 959 | */ 960 | function DistanceConstraint(distance, a, b) { 961 | var size = a.length || arguments.length - 1 962 | var min = distance.length ? distance[0] : distance 963 | var max = distance.length ? distance[1] : distance 964 | 965 | Constraint.call(this, size, 2) 966 | this.setDistance(min, max) 967 | this.setIndices(a, b) 968 | } 969 | 970 | /** 971 | Create instance, accepts constructor arguments. 972 | 973 | @method create 974 | @static 975 | */ 976 | inherit(DistanceConstraint, Constraint) 977 | 978 | /** 979 | Set distance 980 | 981 | @method setDistance 982 | @param {Float} min 983 | @param {Float} [max] 984 | */ 985 | DistanceConstraint.prototype.setDistance = function (min, max) { 986 | this.setMin(min) 987 | this.setMax(max != null ? max : min) 988 | } 989 | 990 | /** 991 | Set minimum distance 992 | 993 | @method setMin 994 | @param {Float} min 995 | */ 996 | DistanceConstraint.prototype.setMin = function (min) { 997 | this._min2 = min * min 998 | } 999 | 1000 | /** 1001 | Cached value of minimum distance squared 1002 | 1003 | @property _min2 1004 | @type Float 1005 | @private 1006 | */ 1007 | DistanceConstraint.prototype._min2 = null 1008 | 1009 | /** 1010 | Set maximum distance 1011 | 1012 | @method setMax 1013 | @param {Float} max 1014 | */ 1015 | DistanceConstraint.prototype.setMax = function (max) { 1016 | this._max2 = max * max 1017 | } 1018 | 1019 | /** 1020 | Cached value of maximum distance squared 1021 | 1022 | @property _max2 1023 | @type Float 1024 | @private 1025 | */ 1026 | DistanceConstraint.prototype._max2 = null 1027 | 1028 | DistanceConstraint.prototype.applyConstraint = function (index, p0, p1) { 1029 | var ii = this.indices 1030 | var ai = ii[index], bi = ii[index + 1] 1031 | 1032 | var ax = ai * 3, ay = ax + 1, az = ax + 2 1033 | var bx = bi * 3, by = bx + 1, bz = bx + 2 1034 | 1035 | var dx = p0[bx] - p0[ax] 1036 | var dy = p0[by] - p0[ay] 1037 | var dz = p0[bz] - p0[az] 1038 | 1039 | if (!(dx || dy || dz)) { 1040 | dx = dy = dz = 0.1 1041 | } 1042 | 1043 | var dist2 = dx * dx + dy * dy + dz * dz 1044 | var min2 = this._min2 1045 | var max2 = this._max2 1046 | 1047 | if (dist2 < max2 && dist2 > min2) { return; } 1048 | 1049 | var target2 = dist2 < min2 ? min2 : max2 1050 | var diff = target2 / (dist2 + target2) 1051 | var aDiff = diff - 0.5 1052 | var bDiff = diff - 0.5 1053 | 1054 | p0[ax] -= dx * aDiff 1055 | p0[ay] -= dy * aDiff 1056 | p0[az] -= dz * aDiff 1057 | 1058 | p0[bx] += dx * bDiff 1059 | p0[by] += dy * bDiff 1060 | p0[bz] += dz * bDiff 1061 | } 1062 | 1063 | /** 1064 | @module constraints 1065 | */ 1066 | 1067 | /** 1068 | Defines one or many relationships between an infinite plane and single particles. 1069 | 1070 | Orientaiton of the plane is defined by 3 points: `planeA`, `planeB`, and `planeC`. 1071 | 1072 | ```javascript 1073 | var planeA = 0, planeB = 1, planeC = 2 1074 | var a = 3, b = 4, c = 5 1075 | var single = PlaneConstraint.create(planeA, planeB, planeC, a) 1076 | var many = PlaneConstraint.create(planeA, planeB, planeC, [a, b, c]) 1077 | ``` 1078 | 1079 | @class PlaneConstraint 1080 | @extends Constraint 1081 | @constructor 1082 | @param {Int} planeA Particle index defining point on plane 1083 | @param {Int} planeB Particle index defining point on plane 1084 | @param {Int} planeC Particle index defining point on plane 1085 | @param {Int|Array} a Particle index or list of many indices 1086 | */ 1087 | function PlaneConstraint(planeA, planeB, planeC, a) { 1088 | var size = a.length || 1 1089 | 1090 | Constraint.call(this, size, 1, 3) 1091 | 1092 | /** 1093 | Vec3 buffer which stores plane normal. 1094 | 1095 | @property bufferVec3 1096 | @type Float32Array (Vec3) 1097 | @private 1098 | */ 1099 | this.bufferVec3 = Vec3.create(1) 1100 | 1101 | this.setPlane(planeA, planeB, planeC) 1102 | this.setIndices(a) 1103 | } 1104 | 1105 | /** 1106 | Create instance, accepts constructor arguments. 1107 | 1108 | @method create 1109 | @static 1110 | */ 1111 | inherit(PlaneConstraint, Constraint) 1112 | 1113 | /** 1114 | Set particles defining constraint plane 1115 | 1116 | @method setPlane 1117 | @param {Int} a Particle index point on plane 1118 | @param {Int} b Particle index point on plane 1119 | @param {Int} c Particle index point on plane 1120 | */ 1121 | PlaneConstraint.prototype.setPlane = function (a, b, c) { 1122 | var ii = this.indices 1123 | 1124 | ii[0] = a 1125 | ii[1] = b 1126 | ii[2] = c 1127 | } 1128 | 1129 | /** 1130 | Calculate and cache plane normal vector. 1131 | Calculated once per relaxation loop iteration. 1132 | 1133 | @method _calculateNormal 1134 | @param {Int} index Constraint set index 1135 | @param {Float32Array (Vec3)} p0 Reference to `ParticleSystem.positions` 1136 | @private 1137 | */ 1138 | PlaneConstraint.prototype._calculateNormal = function (index, p0) { 1139 | var b0 = this.bufferVec3 1140 | var ii = this.indices 1141 | var ai = ii[0], bi = ii[1], ci = ii[2] 1142 | 1143 | var aix = ai * 3, aiy = aix + 1, aiz = aix + 2 1144 | var bix = bi * 3, biy = bix + 1, biz = bix + 2 1145 | var cix = ci * 3, ciy = cix + 1, ciz = cix + 2 1146 | 1147 | // AB (B -> A) 1148 | var abX = p0[aix] - p0[bix] 1149 | var abY = p0[aiy] - p0[biy] 1150 | var abZ = p0[aiz] - p0[biz] 1151 | 1152 | // BC (B -> C) 1153 | var bcX = p0[cix] - p0[bix] 1154 | var bcY = p0[ciy] - p0[biy] 1155 | var bcZ = p0[ciz] - p0[biz] 1156 | 1157 | // N (plane normal vector) 1158 | var nX = abY * bcZ - abZ * bcY 1159 | var nY = abZ * bcX - abX * bcZ 1160 | var nZ = abX * bcY - abY * bcX 1161 | var nLenSq = nX * nX + nY * nY + nZ * nZ 1162 | 1163 | // AB and BC are parallel 1164 | if (!nLenSq) { 1165 | p0[aix] += 0.1 1166 | p0[biy] += 0.1 1167 | p0[cix] -= 0.1 1168 | 1169 | this._hasNormal = false 1170 | return 1171 | } 1172 | 1173 | var nLenInv = 1 / Math.sqrt(nLenSq) 1174 | b0[0] = nX * nLenInv 1175 | b0[1] = nY * nLenInv 1176 | b0[2] = nZ * nLenInv 1177 | 1178 | this._hasNormal = true 1179 | } 1180 | 1181 | /** 1182 | State of constraint's plane normal resolution 1183 | 1184 | @property _hasNormal 1185 | @type Bool 1186 | @private 1187 | */ 1188 | PlaneConstraint.prototype._hasNormal = false 1189 | 1190 | PlaneConstraint.prototype.applyConstraint = function (index, p0, p1) { 1191 | var b0 = this.bufferVec3 1192 | var ii = this.indices 1193 | var bi = ii[1], pi = ii[index + 3] 1194 | 1195 | var bix = bi * 3, biy = bix + 1, biz = bix + 2 1196 | var pix = pi * 3, piy = pix + 1, piz = pix + 2 1197 | 1198 | if (index === 0) { 1199 | this._calculateNormal(index, p0) 1200 | } 1201 | 1202 | if (!this._hasNormal) { return; } 1203 | 1204 | // N (plane normal vector) 1205 | var nX = b0[0] 1206 | var nY = b0[1] 1207 | var nZ = b0[2] 1208 | 1209 | // BP (B -> P) 1210 | var opX = p0[pix] - p0[bix] 1211 | var opY = p0[piy] - p0[biy] 1212 | var opZ = p0[piz] - p0[biz] 1213 | 1214 | // Project BP onto normal vector N 1215 | var pt = opX * nX + opY * nY + opZ * nZ 1216 | 1217 | p0[pix] -= nX * pt 1218 | p0[piy] -= nY * pt 1219 | p0[piz] -= nZ * pt 1220 | } 1221 | 1222 | /** 1223 | @module constraints 1224 | */ 1225 | 1226 | /** 1227 | Defines one or many relationships between a fixed point and single particles. 1228 | 1229 | ```javascript 1230 | var point = [0.5, 10.0, 3.0] 1231 | var a = 0, b = 1 1232 | var single = PointConstraint.create(point, a) 1233 | var many = PointConstraint.create(point, [a, b]) 1234 | ``` 1235 | 1236 | @class PointConstraint 1237 | @extends Constraint 1238 | @constructor 1239 | @param {Array (Vec3)} position Point position 1240 | @param {Int|Array} a Particle index or list of many indices 1241 | */ 1242 | function PointConstraint(position, a) { 1243 | var size = a.length || 1 1244 | 1245 | Constraint.call(this, size, 1) 1246 | 1247 | /** 1248 | Vec3 buffer which stores point position. 1249 | 1250 | @property bufferVec3 1251 | @type Float32Array (Vec3) 1252 | @private 1253 | */ 1254 | this.bufferVec3 = Vec3.create(1) 1255 | 1256 | this.setPosition(position) 1257 | this.setIndices(a) 1258 | } 1259 | 1260 | /** 1261 | Create instance, accepts constructor arguments. 1262 | 1263 | @method create 1264 | @static 1265 | */ 1266 | inherit(PointConstraint, Constraint) 1267 | 1268 | /** 1269 | Set point position. 1270 | 1271 | @method setPosition 1272 | @param {Float} x 1273 | @param {Float} y 1274 | @param {Float} z 1275 | */ 1276 | PointConstraint.prototype.setPosition = function (x, y, z) { 1277 | Vec3.set(this.bufferVec3, 0, x, y, z) 1278 | } 1279 | 1280 | PointConstraint.prototype.applyConstraint = function (index, p0, p1) { 1281 | var b0 = this.bufferVec3 1282 | var ai = this.indices[index] 1283 | var ix = ai * 3, iy = ix + 1, iz = ix + 2 1284 | 1285 | p0[ix] = p1[ix] = b0[0] 1286 | p0[iy] = p1[iy] = b0[1] 1287 | p0[iz] = p1[iz] = b0[2] 1288 | } 1289 | 1290 | /** 1291 | Forces are accumulated and applied to particles, affecting their 1292 | acceleration and velocity in the system's integration step. 1293 | 1294 | @module forces 1295 | @main forces 1296 | */ 1297 | 1298 | /** 1299 | Base class for defining forces. 1300 | 1301 | @class Force 1302 | @constructor 1303 | @param {Array (Vec3)} vector 1304 | @param {Object} [opts] Options 1305 | @param {Int (Enum)} [opts.type] 1306 | */ 1307 | function Force(vector, opts) { 1308 | opts = opts || {} 1309 | this.vector = new Float32Array(3) 1310 | 1311 | if (opts.type) { this.type = opts.type; } 1312 | if (vector != null) { this.set(vector); } 1313 | } 1314 | 1315 | /** 1316 | Create instance, accepts constructor arguments. 1317 | 1318 | @method create 1319 | @static 1320 | */ 1321 | inherit(Force, Object) 1322 | 1323 | /** 1324 | Force type enum: `Force.ATTRACTOR`, `Force.REPULSOR`, `Force.ATTRACTOR_REPULSOR`. 1325 | 1326 | @property type 1327 | @type {Int (Enum)} 1328 | @default Force.ATTRACTOR 1329 | */ 1330 | Force.ATTRACTOR = 0 1331 | Force.REPULSOR = 1 1332 | Force.ATTRACTOR_REPULSOR = 2 1333 | Force.prototype.type = Force.ATTRACTOR 1334 | 1335 | /** 1336 | Alias for `Vec3.set`. 1337 | 1338 | @method set 1339 | @param {Float} x 1340 | @param {Float} y 1341 | @param {Float} z 1342 | */ 1343 | Force.prototype.set = function (x, y, z) { 1344 | Vec3.set(this.vector, 0, x, y, z) 1345 | } 1346 | 1347 | /** 1348 | Apply force to one particle in system. 1349 | 1350 | @method applyForce 1351 | @param {Int} ix Particle vector `x` index 1352 | @param {Float32Array (Vec3)} f0 Reference to `ParticleSystem.accumulatedForces` 1353 | @param {Float32Array (Vec3)} p0 Reference to `ParticleSystem.positions` 1354 | @param {Float32Array (Vec3)} p1 Reference to `ParticleSystem.positionsPrev` 1355 | @protected 1356 | */ 1357 | Force.prototype.applyForce = function (ix, f0, p0, p1) {} 1358 | 1359 | /** 1360 | @module forces 1361 | */ 1362 | 1363 | /** 1364 | Defines a directional force that affects all particles in the system. 1365 | 1366 | ```javascript 1367 | var gravity = DirectionalForce.create([0.0, -0.1, 0.0]) 1368 | ``` 1369 | 1370 | @class DirectionalForce 1371 | @extends Force 1372 | @constructor 1373 | @param {Array (Vec3)} vector Direction vector 1374 | */ 1375 | function DirectionalForce(vector) { 1376 | Force.call(this, vector) 1377 | } 1378 | 1379 | /** 1380 | Create instance, accepts constructor arguments. 1381 | 1382 | @method create 1383 | @static 1384 | */ 1385 | inherit(DirectionalForce, Force) 1386 | 1387 | DirectionalForce.prototype.applyForce = function (ix, f0, p0, p1) { 1388 | var v0 = this.vector 1389 | f0[ix] += v0[0] 1390 | f0[ix + 1] += v0[1] 1391 | f0[ix + 2] += v0[2] 1392 | } 1393 | 1394 | /** 1395 | @module forces 1396 | */ 1397 | 1398 | /** 1399 | Defines a directional force that affects all particles in the system. 1400 | 1401 | ```javascript 1402 | var repulsor = PointForce.create([0.0, 2.0, 3.0], { 1403 | type : Force.REPULSOR, 1404 | radius : 15.0, 1405 | intensity : 0.1 1406 | }) 1407 | ``` 1408 | 1409 | @class PointForce 1410 | @extends Force 1411 | @constructor 1412 | @param {Array (Vec3)} position Force position 1413 | @param {Object} [opts] Options 1414 | @param {Int (Enum)} [opts.type] 1415 | @param {Float} [opts.radius] 1416 | @param {Float} [opts.intensity] 1417 | */ 1418 | function PointForce(position, opts) { 1419 | opts = opts || {} 1420 | Force.apply(this, arguments) 1421 | 1422 | /** 1423 | Magnitude of force vector 1424 | 1425 | @property intensity 1426 | @type Float 1427 | @default 0.05 1428 | */ 1429 | this.intensity = opts.intensity || 0.05 1430 | 1431 | this.setRadius(opts.radius || 0) 1432 | } 1433 | 1434 | var pf_ATTRACTOR = Force.ATTRACTOR 1435 | var pf_REPULSOR = Force.REPULSOR 1436 | var pf_ATTRACTOR_REPULSOR = Force.ATTRACTOR_REPULSOR 1437 | 1438 | /** 1439 | Create instance, accepts constructor arguments. 1440 | 1441 | @method create 1442 | @static 1443 | */ 1444 | inherit(PointForce, Force) 1445 | 1446 | /** 1447 | Set radius 1448 | 1449 | @method setRadius 1450 | @param {Float} r Radius 1451 | */ 1452 | PointForce.prototype.setRadius = function (r) { 1453 | this._radius2 = r * r 1454 | } 1455 | 1456 | /** 1457 | Cached value of squared influence radius 1458 | 1459 | @property _radius2 1460 | @type Float 1461 | @private 1462 | */ 1463 | PointForce.prototype._radius2 = null 1464 | 1465 | PointForce.prototype.applyForce = function (ix, f0, p0, p1) { 1466 | var v0 = this.vector 1467 | var iy = ix + 1 1468 | var iz = ix + 2 1469 | 1470 | var dx = p0[ix] - v0[0] 1471 | var dy = p0[iy] - v0[1] 1472 | var dz = p0[iz] - v0[2] 1473 | 1474 | var dist = dx * dx + dy * dy + dz * dz 1475 | var diff = dist - this._radius2 1476 | var isActive, scale 1477 | 1478 | switch (this.type) { 1479 | case pf_ATTRACTOR: 1480 | isActive = dist > 0 && diff > 0 1481 | break 1482 | case pf_REPULSOR: 1483 | isActive = dist > 0 && diff < 0 1484 | break 1485 | case pf_ATTRACTOR_REPULSOR: 1486 | isActive = dx || dy || dz 1487 | break 1488 | } 1489 | 1490 | if (isActive) { 1491 | scale = diff / dist * this.intensity 1492 | 1493 | f0[ix] -= dx * scale 1494 | f0[iy] -= dy * scale 1495 | f0[iz] -= dz * scale 1496 | } 1497 | } 1498 | 1499 | /** 1500 | @module utils 1501 | */ 1502 | 1503 | /** 1504 | Collection utilities. 1505 | 1506 | @class Collection 1507 | @static 1508 | */ 1509 | 1510 | /** 1511 | Remove all instances of an object from an array. 1512 | 1513 | @method removeAll 1514 | @param {Array} buffer Collection of objects 1515 | @param {any} item Item to remove from collection 1516 | */ 1517 | function removeAll(buffer, item) { 1518 | var index = buffer.indexOf(item) 1519 | if (index < 0) { return; } 1520 | 1521 | for (var i = buffer.length - 1; i >= index; i --) { 1522 | if (buffer[i] === item) { 1523 | buffer.splice(i, 1) 1524 | } 1525 | } 1526 | } 1527 | 1528 | /** 1529 | @module systems 1530 | */ 1531 | 1532 | /** 1533 | Manages particle state as well as the forces and constraints that act on its particles. 1534 | 1535 | @class ParticleSystem 1536 | @constructor 1537 | @param {Int|Array} particles Number of particles or array of initial particle positions 1538 | @param {Int} iterations Number of constraint iterations per system tick 1539 | */ 1540 | function ParticleSystem(particles, iterations) { 1541 | var isCount = typeof particles === 'number' 1542 | var length = isCount ? particles * 3 : particles.length 1543 | var count = length / 3 1544 | var positions = isCount ? length : particles 1545 | 1546 | /** 1547 | Current particle positions 1548 | 1549 | @property positions 1550 | @type Float32Array (Vec3) 1551 | */ 1552 | this.positions = new Float32Array(positions) 1553 | 1554 | /** 1555 | Previous particle positions 1556 | 1557 | @property positionsPrev 1558 | @type Float32Array (Vec3) 1559 | */ 1560 | this.positionsPrev = new Float32Array(positions) 1561 | 1562 | /** 1563 | Accumulated forces currently acting on particles 1564 | 1565 | @property accumulatedForces 1566 | @type Float32Array (Vec3) 1567 | */ 1568 | this.accumulatedForces = new Float32Array(length) 1569 | 1570 | /** 1571 | Particle mass 1572 | 1573 | @property weights 1574 | @type Float32Array (Float) 1575 | */ 1576 | this.weights = new Float32Array(count) 1577 | this.setWeights(1) 1578 | 1579 | /** 1580 | Number of constraint relaxation loop iterations 1581 | 1582 | @property _iterations 1583 | @type Int 1584 | @private 1585 | */ 1586 | this._iterations = iterations || 1 1587 | 1588 | /** 1589 | Number of particles in system 1590 | 1591 | @property _count 1592 | @type Int 1593 | @private 1594 | */ 1595 | this._count = count 1596 | 1597 | this._globalConstraints = [] 1598 | this._localConstraints = [] 1599 | this._pinConstraints = [] 1600 | this._forces = [] 1601 | } 1602 | 1603 | /** 1604 | Create instance, accepts constructor arguments. 1605 | 1606 | @method create 1607 | @static 1608 | */ 1609 | inherit(ParticleSystem, Object) 1610 | 1611 | /** 1612 | Alias for `Vec3.set`. Sets vector of `positions` and `positionsPrev`. 1613 | 1614 | @method setPosition 1615 | @param {Int} i Particle index 1616 | @param {Float} x 1617 | @param {Float} y 1618 | @param {Float} z 1619 | */ 1620 | ParticleSystem.prototype.setPosition = function (i, x, y, z) { 1621 | Vec3.set(this.positions, i, x, y, z) 1622 | Vec3.set(this.positionsPrev, i, x, y, z) 1623 | } 1624 | 1625 | /** 1626 | Alias for `Vec3.copy`. Copys vector from `positions`. 1627 | 1628 | @method getPosition 1629 | @param {Int} i Particle index 1630 | @param {Vec3} out 1631 | @return {Vec3} out 1632 | */ 1633 | ParticleSystem.prototype.getPosition = function (i, out) { 1634 | return Vec3.copy(this.positions, i, out) 1635 | } 1636 | 1637 | /** 1638 | Alias for `Vec3.getDistance`. Calculates distance from `positions`. 1639 | 1640 | @method getDistance 1641 | @param {Int} a Particle index 1642 | @param {Int} b Particle index 1643 | @return {Float} Distance 1644 | */ 1645 | ParticleSystem.prototype.getDistance = function (a, b) { 1646 | return Vec3.distance(this.positions, a, b) 1647 | } 1648 | 1649 | /** 1650 | Alias for `Vec3.angle`. Calculates angle from `positions`. 1651 | 1652 | @method getAngle 1653 | @param {Int} a Particle index 1654 | @param {Int} b Particle index 1655 | @param {Int} c Particle index 1656 | @return {Float} Angle in radians 1657 | */ 1658 | ParticleSystem.prototype.getAngle = function (a, b, c) { 1659 | return Vec3.angle(this.positions, a, b, c) 1660 | } 1661 | 1662 | /** 1663 | Set a particle's mass 1664 | 1665 | @method setWeight 1666 | @param {Int} i Particle index 1667 | @param {Float} w Weight 1668 | */ 1669 | ParticleSystem.prototype.setWeight = function (i, w) { 1670 | this.weights[i] = w 1671 | } 1672 | 1673 | ParticleSystem.prototype.setWeights = function (w) { 1674 | var weights = this.weights 1675 | for (var i = 0, il = weights.length; i < il; i ++) { 1676 | weights[i] = w 1677 | } 1678 | } 1679 | 1680 | ParticleSystem.prototype.each = function (iterator, context) { 1681 | context = context || this 1682 | for (var i = 0, il = this._count; i < il; i ++) { 1683 | iterator.call(context, i, this) 1684 | } 1685 | } 1686 | 1687 | ParticleSystem.prototype.perturb = function (scale) { 1688 | var positions = this.positions 1689 | var positionsPrev = this.positionsPrev 1690 | var dist 1691 | 1692 | for (var i = 0, il = positions.length; i < il; i ++) { 1693 | dist = Math.random() * scale 1694 | positions[i] += dist 1695 | positionsPrev[i] += dist 1696 | } 1697 | } 1698 | 1699 | // .................................................. 1700 | // Verlet Integration 1701 | // 1702 | 1703 | function ps_integrateParticle(i, p0, p1, f0, weight, d2) { 1704 | var pt = p0[i] 1705 | p0[i] += pt - p1[i] + f0[i] * weight * d2 1706 | p1[i] = pt 1707 | } 1708 | 1709 | /** 1710 | Calculate particle's next position through Verlet integration. 1711 | Called as part of `tick`. 1712 | 1713 | @method integrate 1714 | @param {Float} delta Time step 1715 | @private 1716 | */ 1717 | ParticleSystem.prototype.integrate = function (delta) { 1718 | var d2 = delta * delta 1719 | var p0 = this.positions 1720 | var p1 = this.positionsPrev 1721 | var f0 = this.accumulatedForces 1722 | var w0 = this.weights 1723 | var ix, weight 1724 | 1725 | for (var i = 0, il = this._count; i < il; i ++) { 1726 | weight = w0[i] 1727 | ix = i * 3 1728 | 1729 | ps_integrateParticle(ix, p0, p1, f0, weight, d2) 1730 | ps_integrateParticle(ix + 1, p0, p1, f0, weight, d2) 1731 | ps_integrateParticle(ix + 2, p0, p1, f0, weight, d2) 1732 | } 1733 | } 1734 | 1735 | // .................................................. 1736 | // Constraints 1737 | // 1738 | 1739 | ParticleSystem.prototype._getConstraintBuffer = function (constraint) { 1740 | return constraint._isGlobal ? this._globalConstraints : this._localConstraints 1741 | } 1742 | 1743 | /** 1744 | Add a constraint 1745 | 1746 | @method addConstraint 1747 | @param {Constraint} constraint 1748 | */ 1749 | ParticleSystem.prototype.addConstraint = function (constraint) { 1750 | this._getConstraintBuffer(constraint).push(constraint) 1751 | } 1752 | 1753 | /** 1754 | Alias for `Collection.removeAll`. Remove all references to a constraint. 1755 | 1756 | @method removeConstraint 1757 | @param {Constraint} constraint 1758 | */ 1759 | ParticleSystem.prototype.removeConstraint = function (constraint) { 1760 | removeAll(this._getConstraintBuffer(constraint), constraint) 1761 | } 1762 | 1763 | /** 1764 | Add a pin constraint. 1765 | Although intended for instances of `PointConstraint`, this can be any 1766 | type of constraint and will be resolved last in the relaxation loop. 1767 | 1768 | @method addPinConstraint 1769 | @param {Constraint} constraint 1770 | */ 1771 | ParticleSystem.prototype.addPinConstraint = function (constraint) { 1772 | this._pinConstraints.push(constraint) 1773 | } 1774 | 1775 | /** 1776 | Alias for `Collection.removeAll`. Remove all references to a pin constraint. 1777 | 1778 | @method removePinConstraint 1779 | @param {Constraint} constraint 1780 | */ 1781 | ParticleSystem.prototype.removePinConstraint = function (constraint) { 1782 | removeAll(this._pinConstraints, constraint) 1783 | } 1784 | 1785 | /** 1786 | Run relaxation loop, resolving constraints per defined iterations. 1787 | Constraints are resolved in order by type: global, local, pin. 1788 | 1789 | @method satisfyConstraints 1790 | @private 1791 | */ 1792 | ParticleSystem.prototype.satisfyConstraints = function () { 1793 | var iterations = this._iterations 1794 | var global = this._globalConstraints 1795 | var local = this._localConstraints 1796 | var pins = this._pinConstraints 1797 | var globalCount = this._count 1798 | var globalItemSize = 3 1799 | 1800 | for (var i = 0; i < iterations; i ++) { 1801 | this.satisfyConstraintGroup(global, globalCount, globalItemSize) 1802 | this.satisfyConstraintGroup(local) 1803 | 1804 | if (!pins.length) { continue; } 1805 | this.satisfyConstraintGroup(pins) 1806 | } 1807 | } 1808 | 1809 | /** 1810 | Resolve a group of constraints. 1811 | 1812 | @method satisfyConstraintGroup 1813 | @param {Array} group List of constraints 1814 | @param {Int} [count] Override for number of particles a constraint affects 1815 | @param {Int} [itemSize] Override for particle index stride 1816 | @private 1817 | */ 1818 | ParticleSystem.prototype.satisfyConstraintGroup = function (group, count, itemSize) { 1819 | var p0 = this.positions 1820 | var p1 = this.positionsPrev 1821 | var hasUniqueCount = !count 1822 | var constraint 1823 | 1824 | for (var i = 0, il = group.length; i < il; i ++) { 1825 | constraint = group[i] 1826 | 1827 | if (hasUniqueCount) { 1828 | count = constraint._count 1829 | itemSize = constraint._itemSize 1830 | } 1831 | 1832 | for (var j = 0; j < count; j ++) { 1833 | constraint.applyConstraint(j * itemSize, p0, p1) 1834 | } 1835 | } 1836 | } 1837 | 1838 | // .................................................. 1839 | // Forces 1840 | // 1841 | 1842 | /** 1843 | Add a force 1844 | 1845 | @method addForce 1846 | @param {Force} force 1847 | */ 1848 | ParticleSystem.prototype.addForce = function (force) { 1849 | this._forces.push(force) 1850 | } 1851 | 1852 | /** 1853 | Alias for `Collection.removeAll`. Remove all references to a force. 1854 | 1855 | @method removeForce 1856 | @param {Force} force 1857 | */ 1858 | ParticleSystem.prototype.removeForce = function (force) { 1859 | removeAll(this._forces, force) 1860 | } 1861 | 1862 | /** 1863 | Accumulate forces acting on particles. 1864 | 1865 | @method accumulateForces 1866 | @param {Float} delta Time step 1867 | @private 1868 | */ 1869 | ParticleSystem.prototype.accumulateForces = function (delta) { 1870 | var forces = this._forces 1871 | var f0 = this.accumulatedForces 1872 | var p0 = this.positions 1873 | var p1 = this.positionsPrev 1874 | var ix 1875 | 1876 | for (var i = 0, il = this._count; i < il; i ++) { 1877 | ix = i * 3 1878 | f0[ix] = f0[ix + 1] = f0[ix + 2] = 0 1879 | 1880 | for (var j = 0, jl = forces.length; j < jl; j ++) { 1881 | forces[j].applyForce(ix, f0, p0, p1) 1882 | } 1883 | } 1884 | } 1885 | 1886 | /** 1887 | Step simulation forward one frame. 1888 | Applies forces, calculates particle positions, and resolves constraints. 1889 | 1890 | @method tick 1891 | @param {Float} delta Time step 1892 | */ 1893 | ParticleSystem.prototype.tick = function (delta) { 1894 | this.accumulateForces(delta) 1895 | this.integrate(delta) 1896 | this.satisfyConstraints() 1897 | } 1898 | 1899 | /** 1900 | @class Particulate 1901 | @static 1902 | */ 1903 | var VERSION = '0.3.3' 1904 | 1905 | exports.VERSION = VERSION; 1906 | exports.AngleConstraint = AngleConstraint; 1907 | exports.AxisConstraint = AxisConstraint; 1908 | exports.BoundingPlaneConstraint = BoundingPlaneConstraint; 1909 | exports.BoxConstraint = BoxConstraint; 1910 | exports.Constraint = Constraint; 1911 | exports.DistanceConstraint = DistanceConstraint; 1912 | exports.PlaneConstraint = PlaneConstraint; 1913 | exports.PointConstraint = PointConstraint; 1914 | exports.DirectionalForce = DirectionalForce; 1915 | exports.Force = Force; 1916 | exports.PointForce = PointForce; 1917 | exports.Vec3 = Vec3; 1918 | exports.ParticleSystem = ParticleSystem; 1919 | exports.ctor = ctor; 1920 | exports.inherit = inherit; 1921 | 1922 | Object.defineProperty(exports, '__esModule', { value: true }); 1923 | 1924 | })); -------------------------------------------------------------------------------- /web-app/animations/lights/util.js: -------------------------------------------------------------------------------- 1 | !function() { 2 | THREE.TrackballControls = function(a, b) { 3 | function c(a) { 4 | l.enabled !== !1 && (window.removeEventListener("keydown", c), q = p, p === m.NONE && (a.keyCode !== l.keys[m.ROTATE] || l.noRotate ? a.keyCode !== l.keys[m.ZOOM] || l.noZoom ? a.keyCode !== l.keys[m.PAN] || l.noPan || (p = m.PAN) : p = m.ZOOM : p = m.ROTATE)) 5 | } 6 | 7 | function d(a) { 8 | l.enabled !== !1 && (p = q, window.addEventListener("keydown", c, !1)) 9 | } 10 | 11 | function e(a) { 12 | l.enabled !== !1 && (a.preventDefault(), a.stopPropagation(), p === m.NONE && (p = a.button), p !== m.ROTATE || l.noRotate ? p !== m.ZOOM || l.noZoom ? p !== m.PAN || l.noPan || (A.copy(F(a.pageX, a.pageY)), B.copy(A)) : (w.copy(F(a.pageX, a.pageY)), x.copy(w)) : (t.copy(G(a.pageX, a.pageY)), s.copy(t)), document.addEventListener("mousemove", f, !1), document.addEventListener("mouseup", g, !1), l.dispatchEvent(D)) 13 | } 14 | 15 | function f(a) { 16 | l.enabled !== !1 && (a.preventDefault(), a.stopPropagation(), p !== m.ROTATE || l.noRotate ? p !== m.ZOOM || l.noZoom ? p !== m.PAN || l.noPan || B.copy(F(a.pageX, a.pageY)) : x.copy(F(a.pageX, a.pageY)) : (s.copy(t), t.copy(G(a.pageX, a.pageY)))) 17 | } 18 | 19 | function g(a) { 20 | l.enabled !== !1 && (a.preventDefault(), a.stopPropagation(), p = m.NONE, document.removeEventListener("mousemove", f), document.removeEventListener("mouseup", g), l.dispatchEvent(E)) 21 | } 22 | 23 | function h(a) { 24 | if (l.enabled !== !1) { 25 | a.preventDefault(), a.stopPropagation(); 26 | var b = 0; 27 | a.wheelDelta ? b = a.wheelDelta / 40 : a.detail && (b = -a.detail / 3), w.y += .01 * b, l.dispatchEvent(D), l.dispatchEvent(E) 28 | } 29 | } 30 | 31 | function i(a) { 32 | if (l.enabled !== !1) { 33 | switch (a.touches.length) { 34 | case 1: 35 | p = m.TOUCH_ROTATE, t.copy(G(a.touches[0].pageX, a.touches[0].pageY)), s.copy(t); 36 | break; 37 | case 2: 38 | p = m.TOUCH_ZOOM_PAN; 39 | var b = a.touches[0].pageX - a.touches[1].pageX, 40 | c = a.touches[0].pageY - a.touches[1].pageY; 41 | z = y = Math.sqrt(b * b + c * c); 42 | var d = (a.touches[0].pageX + a.touches[1].pageX) / 2, 43 | e = (a.touches[0].pageY + a.touches[1].pageY) / 2; 44 | A.copy(F(d, e)), B.copy(A); 45 | break; 46 | default: 47 | p = m.NONE 48 | } 49 | l.dispatchEvent(D) 50 | } 51 | } 52 | 53 | function j(a) { 54 | if (l.enabled !== !1) switch (a.preventDefault(), a.stopPropagation(), a.touches.length) { 55 | case 1: 56 | s.copy(t), t.copy(G(a.touches[0].pageX, a.touches[0].pageY)); 57 | break; 58 | case 2: 59 | var b = a.touches[0].pageX - a.touches[1].pageX, 60 | c = a.touches[0].pageY - a.touches[1].pageY; 61 | z = Math.sqrt(b * b + c * c); 62 | var d = (a.touches[0].pageX + a.touches[1].pageX) / 2, 63 | e = (a.touches[0].pageY + a.touches[1].pageY) / 2; 64 | B.copy(F(d, e)); 65 | break; 66 | default: 67 | p = m.NONE 68 | } 69 | } 70 | 71 | function k(a) { 72 | if (l.enabled !== !1) { 73 | switch (a.touches.length) { 74 | case 1: 75 | s.copy(t), t.copy(G(a.touches[0].pageX, a.touches[0].pageY)); 76 | break; 77 | case 2: 78 | y = z = 0; 79 | var b = (a.touches[0].pageX + a.touches[1].pageX) / 2, 80 | c = (a.touches[0].pageY + a.touches[1].pageY) / 2; 81 | B.copy(F(b, c)), A.copy(B) 82 | } 83 | p = m.NONE, l.dispatchEvent(E) 84 | } 85 | } 86 | var l = this, 87 | m = { 88 | NONE: -1, 89 | ROTATE: 0, 90 | ZOOM: 1, 91 | PAN: 2, 92 | TOUCH_ROTATE: 3, 93 | TOUCH_ZOOM_PAN: 4 94 | }; 95 | this.object = a, this.domElement = void 0 !== b ? b : document, this.enabled = !0, this.screen = { 96 | left: 0, 97 | top: 0, 98 | width: 0, 99 | height: 0 100 | }, this.rotateSpeed = 1, this.zoomSpeed = 1.2, this.panSpeed = .3, this.noRotate = !1, this.noZoom = !1, this.noPan = !1, this.staticMoving = !1, this.dynamicDampingFactor = .2, this.minDistance = 0, this.maxDistance = 1 / 0, this.keys = [65, 83, 68], this.target = new THREE.Vector3; 101 | var n = 1e-6, 102 | o = new THREE.Vector3, 103 | p = m.NONE, 104 | q = m.NONE, 105 | r = new THREE.Vector3, 106 | s = new THREE.Vector2, 107 | t = new THREE.Vector2, 108 | u = new THREE.Vector3, 109 | v = 0, 110 | w = new THREE.Vector2, 111 | x = new THREE.Vector2, 112 | y = 0, 113 | z = 0, 114 | A = new THREE.Vector2, 115 | B = new THREE.Vector2; 116 | this.target0 = this.target.clone(), this.position0 = this.object.position.clone(), this.up0 = this.object.up.clone(); 117 | var C = { 118 | type: "change" 119 | }, 120 | D = { 121 | type: "start" 122 | }, 123 | E = { 124 | type: "end" 125 | }; 126 | this.handleResize = function() { 127 | if (this.domElement === document) this.screen.left = 0, this.screen.top = 0, this.screen.width = window.innerWidth, this.screen.height = window.innerHeight; 128 | else { 129 | var a = this.domElement.getBoundingClientRect(), 130 | b = this.domElement.ownerDocument.documentElement; 131 | this.screen.left = a.left + window.pageXOffset - b.clientLeft, this.screen.top = a.top + window.pageYOffset - b.clientTop, this.screen.width = a.width, this.screen.height = a.height 132 | } 133 | }, this.handleEvent = function(a) { 134 | "function" == typeof this[a.type] && this[a.type](a) 135 | }; 136 | var F = function() { 137 | var a = new THREE.Vector2; 138 | return function(b, c) { 139 | return a.set((b - l.screen.left) / l.screen.width, (c - l.screen.top) / l.screen.height), a 140 | } 141 | }(), 142 | G = function() { 143 | var a = new THREE.Vector2; 144 | return function(b, c) { 145 | return a.set((b - .5 * l.screen.width - l.screen.left) / (.5 * l.screen.width), (l.screen.height + 2 * (l.screen.top - c)) / l.screen.width), a 146 | } 147 | }(); 148 | this.rotateCamera = function() { 149 | var a, b = new THREE.Vector3, 150 | c = new THREE.Quaternion, 151 | d = new THREE.Vector3, 152 | e = new THREE.Vector3, 153 | f = new THREE.Vector3, 154 | g = new THREE.Vector3; 155 | return function() { 156 | g.set(t.x - s.x, t.y - s.y, 0), a = g.length(), a ? (r.copy(l.object.position).sub(l.target), d.copy(r).normalize(), e.copy(l.object.up).normalize(), f.crossVectors(e, d).normalize(), e.setLength(t.y - s.y), f.setLength(t.x - s.x), g.copy(e.add(f)), b.crossVectors(g, r).normalize(), a *= l.rotateSpeed, c.setFromAxisAngle(b, a), r.applyQuaternion(c), l.object.up.applyQuaternion(c), u.copy(b), v = a) : !l.staticMoving && v && (v *= Math.sqrt(1 - l.dynamicDampingFactor), r.copy(l.object.position).sub(l.target), c.setFromAxisAngle(u, v), r.applyQuaternion(c), l.object.up.applyQuaternion(c)), s.copy(t) 157 | } 158 | }(), this.zoomCamera = function() { 159 | var a; 160 | p === m.TOUCH_ZOOM_PAN ? (a = y / z, y = z, r.multiplyScalar(a)) : (a = 1 + (x.y - w.y) * l.zoomSpeed, 1 !== a && a > 0 && (r.multiplyScalar(a), l.staticMoving ? w.copy(x) : w.y += (x.y - w.y) * this.dynamicDampingFactor)) 161 | }, this.panCamera = function() { 162 | var a = new THREE.Vector2, 163 | b = new THREE.Vector3, 164 | c = new THREE.Vector3; 165 | return function() { 166 | a.copy(B).sub(A), a.lengthSq() && (a.multiplyScalar(r.length() * l.panSpeed), c.copy(r).cross(l.object.up).setLength(a.x), c.add(b.copy(l.object.up).setLength(a.y)), l.object.position.add(c), l.target.add(c), l.staticMoving ? A.copy(B) : A.add(a.subVectors(B, A).multiplyScalar(l.dynamicDampingFactor))) 167 | } 168 | }(), this.checkDistances = function() { 169 | l.noZoom && l.noPan || (r.lengthSq() > l.maxDistance * l.maxDistance && (l.object.position.addVectors(l.target, r.setLength(l.maxDistance)), w.copy(x)), r.lengthSq() < l.minDistance * l.minDistance && (l.object.position.addVectors(l.target, r.setLength(l.minDistance)), w.copy(x))) 170 | }, this.update = function() { 171 | r.subVectors(l.object.position, l.target), l.noRotate || l.rotateCamera(), l.noZoom || l.zoomCamera(), l.noPan || l.panCamera(), l.object.position.addVectors(l.target, r), l.checkDistances(), l.object.lookAt(l.target), o.distanceToSquared(l.object.position) > n && (l.dispatchEvent(C), o.copy(l.object.position)) 172 | }, this.reset = function() { 173 | p = m.NONE, q = m.NONE, l.target.copy(l.target0), l.object.position.copy(l.position0), l.object.up.copy(l.up0), r.subVectors(l.object.position, l.target), l.object.lookAt(l.target), l.dispatchEvent(C), o.copy(l.object.position) 174 | }, this.domElement.addEventListener("contextmenu", function(a) { 175 | a.preventDefault() 176 | }, !1), this.domElement.addEventListener("mousedown", e, !1), this.domElement.addEventListener("mousewheel", h, !1), this.domElement.addEventListener("DOMMouseScroll", h, !1), this.domElement.addEventListener("touchstart", i, !1), this.domElement.addEventListener("touchend", k, !1), this.domElement.addEventListener("touchmove", j, !1), window.addEventListener("keydown", c, !1), window.addEventListener("keyup", d, !1), this.handleResize(), this.update() 177 | }, THREE.TrackballControls.prototype = Object.create(THREE.EventDispatcher.prototype), THREE.TrackballControls.prototype.constructor = THREE.TrackballControls 178 | }(), 179 | function() { 180 | THREE.PlaneBufferGeometry = function(a, b, c, d) { 181 | THREE.BufferGeometry.call(this), this.type = "PlaneBufferGeometry", this.parameters = { 182 | width: a, 183 | height: b, 184 | widthSegments: c, 185 | heightSegments: d 186 | }; 187 | for (var e = a / 2, f = b / 2, g = c || 1, h = d || 1, i = g + 1, j = h + 1, k = a / g, l = b / h, m = new Float32Array(i * j * 3), n = new Float32Array(i * j * 3), o = new Float32Array(i * j * 2), p = 0, q = 0, r = 0; r < j; r++) 188 | for (var s = r * l - f, t = 0; t < i; t++) { 189 | var u = t * k - e; 190 | m[p] = u, m[p + 1] = -s, n[p + 2] = 1, o[q] = t / g, o[q + 1] = 1 - r / h, p += 3, q += 2 191 | } 192 | p = 0; 193 | for (var v = new(m.length / 3 > 65535 ? Uint32Array : Uint16Array)(g * h * 6), r = 0; r < h; r++) 194 | for (var t = 0; t < g; t++) { 195 | var w = t + i * r, 196 | x = t + i * (r + 1), 197 | y = t + 1 + i * (r + 1), 198 | z = t + 1 + i * r; 199 | v[p] = w, v[p + 1] = x, v[p + 2] = z, v[p + 3] = x, v[p + 4] = y, v[p + 5] = z, p += 6 200 | } 201 | this.addAttribute("index", new THREE.BufferAttribute(v, 1)), this.addAttribute("position", new THREE.BufferAttribute(m, 3)), this.addAttribute("normal", new THREE.BufferAttribute(n, 3)), this.addAttribute("uv", new THREE.BufferAttribute(o, 2)) 202 | }, THREE.PlaneBufferGeometry.prototype = Object.create(THREE.BufferGeometry.prototype) 203 | }(), 204 | function() { 205 | THREE.CopyShader = { 206 | uniforms: { 207 | tDiffuse: { 208 | type: "t", 209 | value: null 210 | }, 211 | opacity: { 212 | type: "f", 213 | value: 1 214 | } 215 | }, 216 | vertexShader: ["varying vec2 vUv;", "void main() {", "vUv = uv;", "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", "}"].join("\n"), 217 | fragmentShader: ["uniform float opacity;", "uniform sampler2D tDiffuse;", "varying vec2 vUv;", "void main() {", "vec4 texel = texture2D( tDiffuse, vUv );", "gl_FragColor = opacity * texel;", "}"].join("\n") 218 | } 219 | }(), 220 | function() { 221 | THREE.ConvolutionShader = { 222 | defines: { 223 | KERNEL_SIZE_FLOAT: "25.0", 224 | KERNEL_SIZE_INT: "25" 225 | }, 226 | uniforms: { 227 | tDiffuse: { 228 | type: "t", 229 | value: null 230 | }, 231 | uImageIncrement: { 232 | type: "v2", 233 | value: new THREE.Vector2(.001953125, 0) 234 | }, 235 | cKernel: { 236 | type: "fv1", 237 | value: [] 238 | } 239 | }, 240 | vertexShader: ["uniform vec2 uImageIncrement;", "varying vec2 vUv;", "void main() {", "vUv = uv - ( ( KERNEL_SIZE_FLOAT - 1.0 ) / 2.0 ) * uImageIncrement;", "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", "}"].join("\n"), 241 | fragmentShader: ["uniform float cKernel[ KERNEL_SIZE_INT ];", "uniform sampler2D tDiffuse;", "uniform vec2 uImageIncrement;", "varying vec2 vUv;", "void main() {", "vec2 imageCoord = vUv;", "vec4 sum = vec4( 0.0, 0.0, 0.0, 0.0 );", "for( int i = 0; i < KERNEL_SIZE_INT; i ++ ) {", "sum += texture2D( tDiffuse, imageCoord ) * cKernel[ i ];", "imageCoord += uImageIncrement;", "}", "gl_FragColor = sum;", "}"].join("\n"), 242 | buildKernel: function(a) { 243 | function b(a, b) { 244 | return Math.exp(-(a * a) / (2 * b * b)) 245 | } 246 | var c, d, e, f, g = 25, 247 | h = 2 * Math.ceil(3 * a) + 1; 248 | for (h > g && (h = g), f = .5 * (h - 1), d = new Array(h), e = 0, c = 0; c < h; ++c) d[c] = b(c - f, a), e += d[c]; 249 | for (c = 0; c < h; ++c) d[c] /= e; 250 | return d 251 | } 252 | } 253 | }(), 254 | function() { 255 | THREE.EffectComposer = function(a, b) { 256 | if (this.renderer = a, void 0 === b) { 257 | var c = window.innerWidth || 1, 258 | d = window.innerHeight || 1, 259 | e = { 260 | minFilter: THREE.LinearFilter, 261 | magFilter: THREE.LinearFilter, 262 | format: THREE.RGBFormat, 263 | stencilBuffer: !1 264 | }; 265 | b = new THREE.WebGLRenderTarget(c, d, e) 266 | } 267 | this.renderTarget1 = b, this.renderTarget2 = b.clone(), this.writeBuffer = this.renderTarget1, this.readBuffer = this.renderTarget2, this.passes = [], void 0 === THREE.CopyShader && console.error("THREE.EffectComposer relies on THREE.CopyShader"), this.copyPass = new THREE.ShaderPass(THREE.CopyShader) 268 | }, THREE.EffectComposer.prototype = { 269 | swapBuffers: function() { 270 | var a = this.readBuffer; 271 | this.readBuffer = this.writeBuffer, this.writeBuffer = a 272 | }, 273 | addPass: function(a) { 274 | this.passes.push(a) 275 | }, 276 | insertPass: function(a, b) { 277 | this.passes.splice(b, 0, a) 278 | }, 279 | render: function(a) { 280 | this.writeBuffer = this.renderTarget1, this.readBuffer = this.renderTarget2; 281 | var b, c, d = !1, 282 | e = this.passes.length; 283 | for (c = 0; c < e; c++) 284 | if (b = this.passes[c], b.enabled) { 285 | if (b.render(this.renderer, this.writeBuffer, this.readBuffer, a, d), b.needsSwap) { 286 | if (d) { 287 | var f = this.renderer.context; 288 | f.stencilFunc(f.NOTEQUAL, 1, 4294967295), this.copyPass.render(this.renderer, this.writeBuffer, this.readBuffer, a), f.stencilFunc(f.EQUAL, 1, 4294967295) 289 | } 290 | this.swapBuffers() 291 | } 292 | b instanceof THREE.MaskPass ? d = !0 : b instanceof THREE.ClearMaskPass && (d = !1) 293 | } 294 | }, 295 | reset: function(a) { 296 | void 0 === a && (a = this.renderTarget1.clone(), a.width = window.innerWidth, a.height = window.innerHeight), this.renderTarget1 = a, this.renderTarget2 = a.clone(), this.writeBuffer = this.renderTarget1, this.readBuffer = this.renderTarget2 297 | }, 298 | setSize: function(a, b) { 299 | var c = this.renderTarget1.clone(); 300 | c.width = a, c.height = b, this.reset(c) 301 | } 302 | } 303 | }(), 304 | function() { 305 | THREE.MaskPass = function(a, b) { 306 | this.scene = a, this.camera = b, this.enabled = !0, this.clear = !0, this.needsSwap = !1, this.inverse = !1 307 | }, THREE.MaskPass.prototype = { 308 | render: function(a, b, c, d) { 309 | var e = a.context; 310 | e.colorMask(!1, !1, !1, !1), e.depthMask(!1); 311 | var f, g; 312 | this.inverse ? (f = 0, g = 1) : (f = 1, g = 0), e.enable(e.STENCIL_TEST), e.stencilOp(e.REPLACE, e.REPLACE, e.REPLACE), e.stencilFunc(e.ALWAYS, f, 4294967295), e.clearStencil(g), a.render(this.scene, this.camera, c, this.clear), a.render(this.scene, this.camera, b, this.clear), e.colorMask(!0, !0, !0, !0), e.depthMask(!0), e.stencilFunc(e.EQUAL, 1, 4294967295), e.stencilOp(e.KEEP, e.KEEP, e.KEEP) 313 | } 314 | }, THREE.ClearMaskPass = function() { 315 | this.enabled = !0 316 | }, THREE.ClearMaskPass.prototype = { 317 | render: function(a, b, c, d) { 318 | var e = a.context; 319 | e.disable(e.STENCIL_TEST) 320 | } 321 | } 322 | }(), 323 | function() { 324 | THREE.RenderPass = function(a, b, c, d, e) { 325 | this.scene = a, this.camera = b, this.overrideMaterial = c, this.clearColor = d, this.clearAlpha = void 0 !== e ? e : 1, this.oldClearColor = new THREE.Color, this.oldClearAlpha = 1, this.enabled = !0, this.clear = !0, this.needsSwap = !1 326 | }, THREE.RenderPass.prototype = { 327 | render: function(a, b, c, d) { 328 | this.scene.overrideMaterial = this.overrideMaterial, this.clearColor && (this.oldClearColor.copy(a.getClearColor()), this.oldClearAlpha = a.getClearAlpha(), a.setClearColor(this.clearColor, this.clearAlpha)), a.render(this.scene, this.camera, c, this.clear), this.clearColor && a.setClearColor(this.oldClearColor, this.oldClearAlpha), this.scene.overrideMaterial = null 329 | } 330 | } 331 | }(), 332 | function() { 333 | THREE.ShaderPass = function(a, b) { 334 | this.textureID = void 0 !== b ? b : "tDiffuse", this.uniforms = THREE.UniformsUtils.clone(a.uniforms), this.material = new THREE.ShaderMaterial({ 335 | uniforms: this.uniforms, 336 | vertexShader: a.vertexShader, 337 | fragmentShader: a.fragmentShader 338 | }), this.renderToScreen = !1, this.enabled = !0, this.needsSwap = !0, this.clear = !1, this.camera = new THREE.OrthographicCamera((-1), 1, 1, (-1), 0, 1), this.scene = new THREE.Scene, this.quad = new THREE.Mesh(new THREE.PlaneBufferGeometry(2, 2), null), this.scene.add(this.quad) 339 | }, THREE.ShaderPass.prototype = { 340 | render: function(a, b, c, d) { 341 | this.uniforms[this.textureID] && (this.uniforms[this.textureID].value = c), this.quad.material = this.material, this.renderToScreen ? a.render(this.scene, this.camera) : a.render(this.scene, this.camera, b, this.clear) 342 | } 343 | } 344 | }(), 345 | function() { 346 | THREE.BloomPass = function(a, b, c, d) { 347 | a = void 0 !== a ? a : 1, b = void 0 !== b ? b : 25, c = void 0 !== c ? c : 4, d = void 0 !== d ? d : 256; 348 | var e = { 349 | minFilter: THREE.LinearFilter, 350 | magFilter: THREE.LinearFilter, 351 | format: THREE.RGBFormat 352 | }; 353 | this.renderTargetX = new THREE.WebGLRenderTarget(d, d, e), this.renderTargetY = new THREE.WebGLRenderTarget(d, d, e), void 0 === THREE.CopyShader && console.error("THREE.BloomPass relies on THREE.CopyShader"); 354 | var f = THREE.CopyShader; 355 | this.copyUniforms = THREE.UniformsUtils.clone(f.uniforms), this.copyUniforms.opacity.value = a, this.materialCopy = new THREE.ShaderMaterial({ 356 | uniforms: this.copyUniforms, 357 | vertexShader: f.vertexShader, 358 | fragmentShader: f.fragmentShader, 359 | blending: THREE.AdditiveBlending, 360 | transparent: !0 361 | }), void 0 === THREE.ConvolutionShader && console.error("THREE.BloomPass relies on THREE.ConvolutionShader"); 362 | var g = THREE.ConvolutionShader; 363 | this.convolutionUniforms = THREE.UniformsUtils.clone(g.uniforms), this.convolutionUniforms.uImageIncrement.value = THREE.BloomPass.blurx, this.convolutionUniforms.cKernel.value = THREE.ConvolutionShader.buildKernel(c), this.materialConvolution = new THREE.ShaderMaterial({ 364 | uniforms: this.convolutionUniforms, 365 | vertexShader: g.vertexShader, 366 | fragmentShader: g.fragmentShader, 367 | defines: { 368 | KERNEL_SIZE_FLOAT: b.toFixed(1), 369 | KERNEL_SIZE_INT: b.toFixed(0) 370 | } 371 | }), this.enabled = !0, this.needsSwap = !1, this.clear = !1, this.camera = new THREE.OrthographicCamera((-1), 1, 1, (-1), 0, 1), this.scene = new THREE.Scene, this.quad = new THREE.Mesh(new THREE.PlaneBufferGeometry(2, 2), null), this.scene.add(this.quad) 372 | }, THREE.BloomPass.prototype = { 373 | render: function(a, b, c, d, e) { 374 | e && a.context.disable(a.context.STENCIL_TEST), this.quad.material = this.materialConvolution, this.convolutionUniforms.tDiffuse.value = c, this.convolutionUniforms.uImageIncrement.value = THREE.BloomPass.blurX, a.render(this.scene, this.camera, this.renderTargetX, !0), this.convolutionUniforms.tDiffuse.value = this.renderTargetX, this.convolutionUniforms.uImageIncrement.value = THREE.BloomPass.blurY, a.render(this.scene, this.camera, this.renderTargetY, !0), this.quad.material = this.materialCopy, this.copyUniforms.tDiffuse.value = this.renderTargetY, e && a.context.enable(a.context.STENCIL_TEST), a.render(this.scene, this.camera, c, this.clear) 375 | } 376 | }, THREE.BloomPass.blurX = new THREE.Vector2(.001953125, 0), THREE.BloomPass.blurY = new THREE.Vector2(0, .001953125) 377 | }(); -------------------------------------------------------------------------------- /web-app/animations/particles/GPUParticleSystem.js: -------------------------------------------------------------------------------- 1 | THREE.GPUParticleSystem = function( options ) { 2 | 3 | THREE.Object3D.apply( this, arguments ); 4 | 5 | options = options || {}; 6 | 7 | // parse options and use defaults 8 | 9 | this.PARTICLE_COUNT = options.maxParticles || 1000000; 10 | this.PARTICLE_CONTAINERS = options.containerCount || 1; 11 | 12 | this.PARTICLE_NOISE_TEXTURE = options.particleNoiseTex || null; 13 | this.PARTICLE_SPRITE_TEXTURE = options.particleSpriteTex || null; 14 | 15 | this.PARTICLES_PER_CONTAINER = Math.ceil( this.PARTICLE_COUNT / this.PARTICLE_CONTAINERS ); 16 | this.PARTICLE_CURSOR = 0; 17 | this.time = 0; 18 | this.particleContainers = []; 19 | this.rand = []; 20 | 21 | // custom vertex and fragement shader 22 | 23 | var GPUParticleShader = { 24 | 25 | vertexShader: [ 26 | 27 | 'uniform float uTime;', 28 | 'uniform float uScale;', 29 | 'uniform sampler2D tNoise;', 30 | 31 | 'attribute vec3 positionStart;', 32 | 'attribute float startTime;', 33 | 'attribute vec3 velocity;', 34 | 'attribute float turbulence;', 35 | 'attribute vec3 color;', 36 | 'attribute float size;', 37 | 'attribute float lifeTime;', 38 | 39 | 'varying vec4 vColor;', 40 | 'varying float lifeLeft;', 41 | 42 | 'void main() {', 43 | 44 | // unpack things from our attributes' 45 | 46 | ' vColor = vec4( color, 1.0 );', 47 | 48 | // convert our velocity back into a value we can use' 49 | 50 | ' vec3 newPosition;', 51 | ' vec3 v;', 52 | 53 | ' float timeElapsed = uTime - startTime;', 54 | 55 | ' lifeLeft = 1.0 - ( timeElapsed / lifeTime );', 56 | 57 | ' gl_PointSize = ( uScale * size ) * lifeLeft;', 58 | 59 | ' v.x = ( velocity.x - 0.5 ) * 3.0;', 60 | ' v.y = ( velocity.y - 0.5 ) * 3.0;', 61 | ' v.z = ( velocity.z - 0.5 ) * 3.0;', 62 | 63 | ' newPosition = positionStart + ( v * 10.0 ) * ( uTime - startTime );', 64 | 65 | ' vec3 noise = texture2D( tNoise, vec2( newPosition.x * 0.015 + ( uTime * 0.05 ), newPosition.y * 0.02 + ( uTime * 0.015 ) ) ).rgb;', 66 | ' vec3 noiseVel = ( noise.rgb - 0.5 ) * 30.0;', 67 | 68 | ' newPosition = mix( newPosition, newPosition + vec3( noiseVel * ( turbulence * 5.0 ) ), ( timeElapsed / lifeTime ) );', 69 | 70 | ' if( v.y > 0. && v.y < .05 ) {', 71 | 72 | ' lifeLeft = 0.0;', 73 | 74 | ' }', 75 | 76 | ' if( v.x < - 1.45 ) {', 77 | 78 | ' lifeLeft = 0.0;', 79 | 80 | ' }', 81 | 82 | ' if( timeElapsed > 0.0 ) {', 83 | 84 | ' gl_Position = projectionMatrix * modelViewMatrix * vec4( newPosition, 1.0 );', 85 | 86 | ' } else {', 87 | 88 | ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', 89 | ' lifeLeft = 0.0;', 90 | ' gl_PointSize = 0.;', 91 | 92 | ' }', 93 | 94 | '}' 95 | 96 | ].join( '\n' ), 97 | 98 | fragmentShader: [ 99 | 100 | 'float scaleLinear( float value, vec2 valueDomain ) {', 101 | 102 | ' return ( value - valueDomain.x ) / ( valueDomain.y - valueDomain.x );', 103 | 104 | '}', 105 | 106 | 'float scaleLinear( float value, vec2 valueDomain, vec2 valueRange ) {', 107 | 108 | ' return mix( valueRange.x, valueRange.y, scaleLinear( value, valueDomain ) );', 109 | 110 | '}', 111 | 112 | 'varying vec4 vColor;', 113 | 'varying float lifeLeft;', 114 | 115 | 'uniform sampler2D tSprite;', 116 | 117 | 'void main() {', 118 | 119 | ' float alpha = 0.;', 120 | 121 | ' if( lifeLeft > 0.995 ) {', 122 | 123 | ' alpha = scaleLinear( lifeLeft, vec2( 1.0, 0.995 ), vec2( 0.0, 1.0 ) );', 124 | 125 | ' } else {', 126 | 127 | ' alpha = lifeLeft * 0.75;', 128 | 129 | ' }', 130 | 131 | ' vec4 tex = texture2D( tSprite, gl_PointCoord );', 132 | ' gl_FragColor = vec4( vColor.rgb * tex.a, alpha * tex.a );', 133 | 134 | '}' 135 | 136 | ].join( '\n' ) 137 | 138 | }; 139 | 140 | // preload a million random numbers 141 | 142 | var i; 143 | 144 | for ( i = 1e5; i > 0; i-- ) { 145 | 146 | this.rand.push( Math.random() - 0.5 ); 147 | 148 | } 149 | 150 | this.random = function() { 151 | 152 | return ++ i >= this.rand.length ? this.rand[ i = 1 ] : this.rand[ i ]; 153 | 154 | }; 155 | 156 | var textureLoader = new THREE.TextureLoader(); 157 | 158 | this.particleNoiseTex = this.PARTICLE_NOISE_TEXTURE || textureLoader.load( 'animations/particles/perlin-512.png' ); 159 | this.particleNoiseTex.wrapS = this.particleNoiseTex.wrapT = THREE.RepeatWrapping; 160 | 161 | this.particleSpriteTex = this.PARTICLE_SPRITE_TEXTURE || textureLoader.load( 'animations/particles/particle2.png' ); 162 | this.particleSpriteTex.wrapS = this.particleSpriteTex.wrapT = THREE.RepeatWrapping; 163 | 164 | this.particleShaderMat = new THREE.ShaderMaterial( { 165 | transparent: true, 166 | depthWrite: false, 167 | uniforms: { 168 | 'uTime': { 169 | value: 0.0 170 | }, 171 | 'uScale': { 172 | value: 1.0 173 | }, 174 | 'tNoise': { 175 | value: this.particleNoiseTex 176 | }, 177 | 'tSprite': { 178 | value: this.particleSpriteTex 179 | } 180 | }, 181 | blending: THREE.AdditiveBlending, 182 | vertexShader: GPUParticleShader.vertexShader, 183 | fragmentShader: GPUParticleShader.fragmentShader 184 | } ); 185 | 186 | // define defaults for all values 187 | 188 | this.particleShaderMat.defaultAttributeValues.particlePositionsStartTime = [ 0, 0, 0, 0 ]; 189 | this.particleShaderMat.defaultAttributeValues.particleVelColSizeLife = [ 0, 0, 0, 0 ]; 190 | 191 | this.init = function() { 192 | 193 | for ( var i = 0; i < this.PARTICLE_CONTAINERS; i ++ ) { 194 | 195 | var c = new THREE.GPUParticleContainer( this.PARTICLES_PER_CONTAINER, this ); 196 | this.particleContainers.push( c ); 197 | this.add( c ); 198 | 199 | } 200 | 201 | }; 202 | 203 | this.spawnParticle = function( options ) { 204 | 205 | this.PARTICLE_CURSOR ++; 206 | 207 | if ( this.PARTICLE_CURSOR >= this.PARTICLE_COUNT ) { 208 | 209 | this.PARTICLE_CURSOR = 1; 210 | 211 | } 212 | 213 | var currentContainer = this.particleContainers[ Math.floor( this.PARTICLE_CURSOR / this.PARTICLES_PER_CONTAINER ) ]; 214 | 215 | currentContainer.spawnParticle( options ); 216 | 217 | }; 218 | 219 | this.update = function( time ) { 220 | 221 | for ( var i = 0; i < this.PARTICLE_CONTAINERS; i ++ ) { 222 | 223 | this.particleContainers[ i ].update( time ); 224 | 225 | } 226 | 227 | }; 228 | 229 | this.dispose = function() { 230 | 231 | this.particleShaderMat.dispose(); 232 | this.particleNoiseTex.dispose(); 233 | this.particleSpriteTex.dispose(); 234 | 235 | for ( var i = 0; i < this.PARTICLE_CONTAINERS; i ++ ) { 236 | 237 | this.particleContainers[ i ].dispose(); 238 | 239 | } 240 | 241 | }; 242 | 243 | this.init(); 244 | 245 | }; 246 | 247 | THREE.GPUParticleSystem.prototype = Object.create( THREE.Object3D.prototype ); 248 | THREE.GPUParticleSystem.prototype.constructor = THREE.GPUParticleSystem; 249 | 250 | 251 | // Subclass for particle containers, allows for very large arrays to be spread out 252 | 253 | THREE.GPUParticleContainer = function( maxParticles, particleSystem ) { 254 | 255 | THREE.Object3D.apply( this, arguments ); 256 | 257 | this.PARTICLE_COUNT = maxParticles || 100000; 258 | this.PARTICLE_CURSOR = 0; 259 | this.time = 0; 260 | this.offset = 0; 261 | this.count = 0; 262 | this.DPR = window.devicePixelRatio; 263 | this.GPUParticleSystem = particleSystem; 264 | this.particleUpdate = false; 265 | 266 | // geometry 267 | 268 | this.particleShaderGeo = new THREE.BufferGeometry(); 269 | 270 | this.particleShaderGeo.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( this.PARTICLE_COUNT * 3 ), 3 ).setDynamic( true ) ); 271 | this.particleShaderGeo.addAttribute( 'positionStart', new THREE.BufferAttribute( new Float32Array( this.PARTICLE_COUNT * 3 ), 3 ).setDynamic( true ) ); 272 | this.particleShaderGeo.addAttribute( 'startTime', new THREE.BufferAttribute( new Float32Array( this.PARTICLE_COUNT ), 1 ).setDynamic( true ) ); 273 | this.particleShaderGeo.addAttribute( 'velocity', new THREE.BufferAttribute( new Float32Array( this.PARTICLE_COUNT * 3 ), 3 ).setDynamic( true ) ); 274 | this.particleShaderGeo.addAttribute( 'turbulence', new THREE.BufferAttribute( new Float32Array( this.PARTICLE_COUNT ), 1 ).setDynamic( true ) ); 275 | this.particleShaderGeo.addAttribute( 'color', new THREE.BufferAttribute( new Float32Array( this.PARTICLE_COUNT * 3 ), 3 ).setDynamic( true ) ); 276 | this.particleShaderGeo.addAttribute( 'size', new THREE.BufferAttribute( new Float32Array( this.PARTICLE_COUNT ), 1 ).setDynamic( true ) ); 277 | this.particleShaderGeo.addAttribute( 'lifeTime', new THREE.BufferAttribute( new Float32Array( this.PARTICLE_COUNT ), 1 ).setDynamic( true ) ); 278 | 279 | // material 280 | 281 | this.particleShaderMat = this.GPUParticleSystem.particleShaderMat; 282 | 283 | var position = new THREE.Vector3(); 284 | var velocity = new THREE.Vector3(); 285 | var color = new THREE.Color(); 286 | 287 | this.spawnParticle = function( options ) { 288 | 289 | var positionStartAttribute = this.particleShaderGeo.getAttribute( 'positionStart' ); 290 | var startTimeAttribute = this.particleShaderGeo.getAttribute( 'startTime' ); 291 | var velocityAttribute = this.particleShaderGeo.getAttribute( 'velocity' ); 292 | var turbulenceAttribute = this.particleShaderGeo.getAttribute( 'turbulence' ); 293 | var colorAttribute = this.particleShaderGeo.getAttribute( 'color' ); 294 | var sizeAttribute = this.particleShaderGeo.getAttribute( 'size' ); 295 | var lifeTimeAttribute = this.particleShaderGeo.getAttribute( 'lifeTime' ); 296 | 297 | options = options || {}; 298 | 299 | // setup reasonable default values for all arguments 300 | 301 | position = options.position !== undefined ? position.copy( options.position ) : position.set( 0, 0, 0 ); 302 | velocity = options.velocity !== undefined ? velocity.copy( options.velocity ) : velocity.set( 0, 0, 0 ); 303 | color = options.color !== undefined ? color.set( options.color ) : color.set( 0xffffff ); 304 | 305 | var positionRandomness = options.positionRandomness !== undefined ? options.positionRandomness : 0; 306 | var velocityRandomness = options.velocityRandomness !== undefined ? options.velocityRandomness : 0; 307 | var colorRandomness = options.colorRandomness !== undefined ? options.colorRandomness : 1; 308 | var turbulence = options.turbulence !== undefined ? options.turbulence : 1; 309 | var lifetime = options.lifetime !== undefined ? options.lifetime : 5; 310 | var size = options.size !== undefined ? options.size : 10; 311 | var sizeRandomness = options.sizeRandomness !== undefined ? options.sizeRandomness : 0; 312 | var smoothPosition = options.smoothPosition !== undefined ? options.smoothPosition : false; 313 | 314 | if ( this.DPR !== undefined ) size *= this.DPR; 315 | 316 | i = this.PARTICLE_CURSOR; 317 | 318 | // position 319 | 320 | positionStartAttribute.array[ i * 3 + 0 ] = position.x + ( particleSystem.random() * positionRandomness ); 321 | positionStartAttribute.array[ i * 3 + 1 ] = position.y + ( particleSystem.random() * positionRandomness ); 322 | positionStartAttribute.array[ i * 3 + 2 ] = position.z + ( particleSystem.random() * positionRandomness ); 323 | 324 | if ( smoothPosition === true ) { 325 | 326 | positionStartAttribute.array[ i * 3 + 0 ] += - ( velocity.x * particleSystem.random() ); 327 | positionStartAttribute.array[ i * 3 + 1 ] += - ( velocity.y * particleSystem.random() ); 328 | positionStartAttribute.array[ i * 3 + 2 ] += - ( velocity.z * particleSystem.random() ); 329 | 330 | } 331 | 332 | // velocity 333 | 334 | var maxVel = 2; 335 | 336 | var velX = velocity.x + particleSystem.random() * velocityRandomness; 337 | var velY = velocity.y + particleSystem.random() * velocityRandomness; 338 | var velZ = velocity.z + particleSystem.random() * velocityRandomness; 339 | 340 | velX = THREE.Math.clamp( ( velX - ( - maxVel ) ) / ( maxVel - ( - maxVel ) ), 0, 1 ); 341 | velY = THREE.Math.clamp( ( velY - ( - maxVel ) ) / ( maxVel - ( - maxVel ) ), 0, 1 ); 342 | velZ = THREE.Math.clamp( ( velZ - ( - maxVel ) ) / ( maxVel - ( - maxVel ) ), 0, 1 ); 343 | 344 | velocityAttribute.array[ i * 3 + 0 ] = velX; 345 | velocityAttribute.array[ i * 3 + 1 ] = velY; 346 | velocityAttribute.array[ i * 3 + 2 ] = velZ; 347 | 348 | // color 349 | 350 | color.r = THREE.Math.clamp( color.r + particleSystem.random() * colorRandomness, 0, 1 ); 351 | color.g = THREE.Math.clamp( color.g + particleSystem.random() * colorRandomness, 0, 1 ); 352 | color.b = THREE.Math.clamp( color.b + particleSystem.random() * colorRandomness, 0, 1 ); 353 | 354 | colorAttribute.array[ i * 3 + 0 ] = color.r; 355 | colorAttribute.array[ i * 3 + 1 ] = color.g; 356 | colorAttribute.array[ i * 3 + 2 ] = color.b; 357 | 358 | // turbulence, size, lifetime and starttime 359 | 360 | turbulenceAttribute.array[ i ] = turbulence; 361 | sizeAttribute.array[ i ] = size + particleSystem.random() * sizeRandomness; 362 | lifeTimeAttribute.array[ i ] = lifetime; 363 | startTimeAttribute.array[ i ] = this.time + particleSystem.random() * 2e-2; 364 | 365 | // offset 366 | 367 | if ( this.offset === 0 ) { 368 | 369 | this.offset = this.PARTICLE_CURSOR; 370 | 371 | } 372 | 373 | // counter and cursor 374 | 375 | this.count ++; 376 | this.PARTICLE_CURSOR ++; 377 | 378 | if ( this.PARTICLE_CURSOR >= this.PARTICLE_COUNT ) { 379 | 380 | this.PARTICLE_CURSOR = 0; 381 | 382 | } 383 | 384 | this.particleUpdate = true; 385 | 386 | }; 387 | 388 | this.init = function() { 389 | 390 | this.particleSystem = new THREE.Points( this.particleShaderGeo, this.particleShaderMat ); 391 | this.particleSystem.frustumCulled = false; 392 | this.add( this.particleSystem ); 393 | 394 | }; 395 | 396 | this.update = function( time ) { 397 | 398 | this.time = time; 399 | this.particleShaderMat.uniforms.uTime.value = time; 400 | 401 | this.geometryUpdate(); 402 | 403 | }; 404 | 405 | this.geometryUpdate = function() { 406 | 407 | if ( this.particleUpdate === true ) { 408 | 409 | this.particleUpdate = false; 410 | 411 | var positionStartAttribute = this.particleShaderGeo.getAttribute( 'positionStart' ); 412 | var startTimeAttribute = this.particleShaderGeo.getAttribute( 'startTime' ); 413 | var velocityAttribute = this.particleShaderGeo.getAttribute( 'velocity' ); 414 | var turbulenceAttribute = this.particleShaderGeo.getAttribute( 'turbulence' ); 415 | var colorAttribute = this.particleShaderGeo.getAttribute( 'color' ); 416 | var sizeAttribute = this.particleShaderGeo.getAttribute( 'size' ); 417 | var lifeTimeAttribute = this.particleShaderGeo.getAttribute( 'lifeTime' ); 418 | 419 | if ( this.offset + this.count < this.PARTICLE_COUNT ) { 420 | 421 | positionStartAttribute.updateRange.offset = this.offset * positionStartAttribute.itemSize; 422 | startTimeAttribute.updateRange.offset = this.offset * startTimeAttribute.itemSize; 423 | velocityAttribute.updateRange.offset = this.offset * velocityAttribute.itemSize; 424 | turbulenceAttribute.updateRange.offset = this.offset * turbulenceAttribute.itemSize; 425 | colorAttribute.updateRange.offset = this.offset * colorAttribute.itemSize; 426 | sizeAttribute.updateRange.offset = this.offset * sizeAttribute.itemSize; 427 | lifeTimeAttribute.updateRange.offset = this.offset * lifeTimeAttribute.itemSize; 428 | 429 | positionStartAttribute.updateRange.count = this.count * positionStartAttribute.itemSize; 430 | startTimeAttribute.updateRange.count = this.count * startTimeAttribute.itemSize; 431 | velocityAttribute.updateRange.count = this.count * velocityAttribute.itemSize; 432 | turbulenceAttribute.updateRange.count = this.count * turbulenceAttribute.itemSize; 433 | colorAttribute.updateRange.count = this.count * colorAttribute.itemSize; 434 | sizeAttribute.updateRange.count = this.count * sizeAttribute.itemSize; 435 | lifeTimeAttribute.updateRange.count = this.count * lifeTimeAttribute.itemSize; 436 | 437 | } else { 438 | 439 | positionStartAttribute.updateRange.offset = 0; 440 | startTimeAttribute.updateRange.offset = 0; 441 | velocityAttribute.updateRange.offset = 0; 442 | turbulenceAttribute.updateRange.offset = 0; 443 | colorAttribute.updateRange.offset = 0; 444 | sizeAttribute.updateRange.offset = 0; 445 | lifeTimeAttribute.updateRange.offset = 0; 446 | 447 | positionStartAttribute.updateRange.count = positionStartAttribute.count; 448 | startTimeAttribute.updateRange.count = startTimeAttribute.count; 449 | velocityAttribute.updateRange.count = velocityAttribute.count; 450 | turbulenceAttribute.updateRange.count = turbulenceAttribute.count; 451 | colorAttribute.updateRange.count = colorAttribute.count; 452 | sizeAttribute.updateRange.count = sizeAttribute.count; 453 | lifeTimeAttribute.updateRange.count = lifeTimeAttribute.count; 454 | 455 | } 456 | 457 | positionStartAttribute.needsUpdate = true; 458 | startTimeAttribute.needsUpdate = true; 459 | velocityAttribute.needsUpdate = true; 460 | turbulenceAttribute.needsUpdate = true; 461 | colorAttribute.needsUpdate = true; 462 | sizeAttribute.needsUpdate = true; 463 | lifeTimeAttribute.needsUpdate = true; 464 | 465 | this.offset = 0; 466 | this.count = 0; 467 | 468 | } 469 | 470 | }; 471 | 472 | this.dispose = function() { 473 | 474 | this.particleShaderGeo.dispose(); 475 | 476 | }; 477 | 478 | this.init(); 479 | 480 | }; 481 | 482 | THREE.GPUParticleContainer.prototype = Object.create( THREE.Object3D.prototype ); 483 | THREE.GPUParticleContainer.prototype.constructor = THREE.GPUParticleContainer; 484 | -------------------------------------------------------------------------------- /web-app/animations/particles/TrackballControls.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @author Eberhard Graether / http://egraether.com/ 3 | * @author Mark Lundin / http://mark-lundin.com 4 | * @author Simone Manini / http://daron1337.github.io 5 | * @author Luca Antiga / http://lantiga.github.io 6 | */ 7 | 8 | THREE.TrackballControls = function ( object, domElement ) { 9 | 10 | var _this = this; 11 | var STATE = { NONE: - 1, ROTATE: 0, ZOOM: 1, PAN: 2, TOUCH_ROTATE: 3, TOUCH_ZOOM_PAN: 4 }; 12 | 13 | this.object = object; 14 | this.domElement = ( domElement !== undefined ) ? domElement : document; 15 | 16 | // API 17 | 18 | this.enabled = true; 19 | 20 | this.screen = { left: 0, top: 0, width: 0, height: 0 }; 21 | 22 | this.rotateSpeed = 1.0; 23 | this.zoomSpeed = 1.2; 24 | this.panSpeed = 0.3; 25 | 26 | this.noRotate = false; 27 | this.noZoom = false; 28 | this.noPan = false; 29 | 30 | this.staticMoving = false; 31 | this.dynamicDampingFactor = 0.2; 32 | 33 | this.minDistance = 0; 34 | this.maxDistance = Infinity; 35 | 36 | this.keys = [ 65 /*A*/, 83 /*S*/, 68 /*D*/ ]; 37 | 38 | // internals 39 | 40 | this.target = new THREE.Vector3(); 41 | 42 | var EPS = 0.000001; 43 | 44 | var lastPosition = new THREE.Vector3(); 45 | 46 | var _state = STATE.NONE, 47 | _prevState = STATE.NONE, 48 | 49 | _eye = new THREE.Vector3(), 50 | 51 | _movePrev = new THREE.Vector2(), 52 | _moveCurr = new THREE.Vector2(), 53 | 54 | _lastAxis = new THREE.Vector3(), 55 | _lastAngle = 0, 56 | 57 | _zoomStart = new THREE.Vector2(), 58 | _zoomEnd = new THREE.Vector2(), 59 | 60 | _touchZoomDistanceStart = 0, 61 | _touchZoomDistanceEnd = 0, 62 | 63 | _panStart = new THREE.Vector2(), 64 | _panEnd = new THREE.Vector2(); 65 | 66 | // for reset 67 | 68 | this.target0 = this.target.clone(); 69 | this.position0 = this.object.position.clone(); 70 | this.up0 = this.object.up.clone(); 71 | 72 | // events 73 | 74 | var changeEvent = { type: 'change' }; 75 | var startEvent = { type: 'start' }; 76 | var endEvent = { type: 'end' }; 77 | 78 | 79 | // methods 80 | 81 | this.handleResize = function () { 82 | 83 | if ( this.domElement === document ) { 84 | 85 | this.screen.left = 0; 86 | this.screen.top = 0; 87 | this.screen.width = window.innerWidth; 88 | this.screen.height = window.innerHeight; 89 | 90 | } else { 91 | 92 | var box = this.domElement.getBoundingClientRect(); 93 | // adjustments come from similar code in the jquery offset() function 94 | var d = this.domElement.ownerDocument.documentElement; 95 | this.screen.left = box.left + window.pageXOffset - d.clientLeft; 96 | this.screen.top = box.top + window.pageYOffset - d.clientTop; 97 | this.screen.width = box.width; 98 | this.screen.height = box.height; 99 | 100 | } 101 | 102 | }; 103 | 104 | this.handleEvent = function ( event ) { 105 | 106 | if ( typeof this[ event.type ] == 'function' ) { 107 | 108 | this[ event.type ]( event ); 109 | 110 | } 111 | 112 | }; 113 | 114 | var getMouseOnScreen = ( function () { 115 | 116 | var vector = new THREE.Vector2(); 117 | 118 | return function getMouseOnScreen( pageX, pageY ) { 119 | 120 | vector.set( 121 | ( pageX - _this.screen.left ) / _this.screen.width, 122 | ( pageY - _this.screen.top ) / _this.screen.height 123 | ); 124 | 125 | return vector; 126 | 127 | }; 128 | 129 | }() ); 130 | 131 | var getMouseOnCircle = ( function () { 132 | 133 | var vector = new THREE.Vector2(); 134 | 135 | return function getMouseOnCircle( pageX, pageY ) { 136 | 137 | vector.set( 138 | ( ( pageX - _this.screen.width * 0.5 - _this.screen.left ) / ( _this.screen.width * 0.5 ) ), 139 | ( ( _this.screen.height + 2 * ( _this.screen.top - pageY ) ) / _this.screen.width ) // screen.width intentional 140 | ); 141 | 142 | return vector; 143 | 144 | }; 145 | 146 | }() ); 147 | 148 | this.rotateCamera = ( function() { 149 | 150 | var axis = new THREE.Vector3(), 151 | quaternion = new THREE.Quaternion(), 152 | eyeDirection = new THREE.Vector3(), 153 | objectUpDirection = new THREE.Vector3(), 154 | objectSidewaysDirection = new THREE.Vector3(), 155 | moveDirection = new THREE.Vector3(), 156 | angle; 157 | 158 | return function rotateCamera() { 159 | 160 | moveDirection.set( _moveCurr.x - _movePrev.x, _moveCurr.y - _movePrev.y, 0 ); 161 | angle = moveDirection.length(); 162 | 163 | if ( angle ) { 164 | 165 | _eye.copy( _this.object.position ).sub( _this.target ); 166 | 167 | eyeDirection.copy( _eye ).normalize(); 168 | objectUpDirection.copy( _this.object.up ).normalize(); 169 | objectSidewaysDirection.crossVectors( objectUpDirection, eyeDirection ).normalize(); 170 | 171 | objectUpDirection.setLength( _moveCurr.y - _movePrev.y ); 172 | objectSidewaysDirection.setLength( _moveCurr.x - _movePrev.x ); 173 | 174 | moveDirection.copy( objectUpDirection.add( objectSidewaysDirection ) ); 175 | 176 | axis.crossVectors( moveDirection, _eye ).normalize(); 177 | 178 | angle *= _this.rotateSpeed; 179 | quaternion.setFromAxisAngle( axis, angle ); 180 | 181 | _eye.applyQuaternion( quaternion ); 182 | _this.object.up.applyQuaternion( quaternion ); 183 | 184 | _lastAxis.copy( axis ); 185 | _lastAngle = angle; 186 | 187 | } else if ( ! _this.staticMoving && _lastAngle ) { 188 | 189 | _lastAngle *= Math.sqrt( 1.0 - _this.dynamicDampingFactor ); 190 | _eye.copy( _this.object.position ).sub( _this.target ); 191 | quaternion.setFromAxisAngle( _lastAxis, _lastAngle ); 192 | _eye.applyQuaternion( quaternion ); 193 | _this.object.up.applyQuaternion( quaternion ); 194 | 195 | } 196 | 197 | _movePrev.copy( _moveCurr ); 198 | 199 | }; 200 | 201 | }() ); 202 | 203 | 204 | this.zoomCamera = function () { 205 | 206 | var factor; 207 | 208 | if ( _state === STATE.TOUCH_ZOOM_PAN ) { 209 | 210 | factor = _touchZoomDistanceStart / _touchZoomDistanceEnd; 211 | _touchZoomDistanceStart = _touchZoomDistanceEnd; 212 | _eye.multiplyScalar( factor ); 213 | 214 | } else { 215 | 216 | factor = 1.0 + ( _zoomEnd.y - _zoomStart.y ) * _this.zoomSpeed; 217 | 218 | if ( factor !== 1.0 && factor > 0.0 ) { 219 | 220 | _eye.multiplyScalar( factor ); 221 | 222 | } 223 | 224 | if ( _this.staticMoving ) { 225 | 226 | _zoomStart.copy( _zoomEnd ); 227 | 228 | } else { 229 | 230 | _zoomStart.y += ( _zoomEnd.y - _zoomStart.y ) * this.dynamicDampingFactor; 231 | 232 | } 233 | 234 | } 235 | 236 | }; 237 | 238 | this.panCamera = ( function() { 239 | 240 | var mouseChange = new THREE.Vector2(), 241 | objectUp = new THREE.Vector3(), 242 | pan = new THREE.Vector3(); 243 | 244 | return function panCamera() { 245 | 246 | mouseChange.copy( _panEnd ).sub( _panStart ); 247 | 248 | if ( mouseChange.lengthSq() ) { 249 | 250 | mouseChange.multiplyScalar( _eye.length() * _this.panSpeed ); 251 | 252 | pan.copy( _eye ).cross( _this.object.up ).setLength( mouseChange.x ); 253 | pan.add( objectUp.copy( _this.object.up ).setLength( mouseChange.y ) ); 254 | 255 | _this.object.position.add( pan ); 256 | _this.target.add( pan ); 257 | 258 | if ( _this.staticMoving ) { 259 | 260 | _panStart.copy( _panEnd ); 261 | 262 | } else { 263 | 264 | _panStart.add( mouseChange.subVectors( _panEnd, _panStart ).multiplyScalar( _this.dynamicDampingFactor ) ); 265 | 266 | } 267 | 268 | } 269 | 270 | }; 271 | 272 | }() ); 273 | 274 | this.checkDistances = function () { 275 | 276 | if ( ! _this.noZoom || ! _this.noPan ) { 277 | 278 | if ( _eye.lengthSq() > _this.maxDistance * _this.maxDistance ) { 279 | 280 | _this.object.position.addVectors( _this.target, _eye.setLength( _this.maxDistance ) ); 281 | _zoomStart.copy( _zoomEnd ); 282 | 283 | } 284 | 285 | if ( _eye.lengthSq() < _this.minDistance * _this.minDistance ) { 286 | 287 | _this.object.position.addVectors( _this.target, _eye.setLength( _this.minDistance ) ); 288 | _zoomStart.copy( _zoomEnd ); 289 | 290 | } 291 | 292 | } 293 | 294 | }; 295 | 296 | this.update = function () { 297 | 298 | _eye.subVectors( _this.object.position, _this.target ); 299 | 300 | if ( ! _this.noRotate ) { 301 | 302 | _this.rotateCamera(); 303 | 304 | } 305 | 306 | if ( ! _this.noZoom ) { 307 | 308 | _this.zoomCamera(); 309 | 310 | } 311 | 312 | if ( ! _this.noPan ) { 313 | 314 | _this.panCamera(); 315 | 316 | } 317 | 318 | _this.object.position.addVectors( _this.target, _eye ); 319 | 320 | _this.checkDistances(); 321 | 322 | _this.object.lookAt( _this.target ); 323 | 324 | if ( lastPosition.distanceToSquared( _this.object.position ) > EPS ) { 325 | 326 | _this.dispatchEvent( changeEvent ); 327 | 328 | lastPosition.copy( _this.object.position ); 329 | 330 | } 331 | 332 | }; 333 | 334 | this.reset = function () { 335 | 336 | _state = STATE.NONE; 337 | _prevState = STATE.NONE; 338 | 339 | _this.target.copy( _this.target0 ); 340 | _this.object.position.copy( _this.position0 ); 341 | _this.object.up.copy( _this.up0 ); 342 | 343 | _eye.subVectors( _this.object.position, _this.target ); 344 | 345 | _this.object.lookAt( _this.target ); 346 | 347 | _this.dispatchEvent( changeEvent ); 348 | 349 | lastPosition.copy( _this.object.position ); 350 | 351 | }; 352 | 353 | // listeners 354 | 355 | function keydown( event ) { 356 | 357 | if ( _this.enabled === false ) return; 358 | 359 | window.removeEventListener( 'keydown', keydown ); 360 | 361 | _prevState = _state; 362 | 363 | if ( _state !== STATE.NONE ) { 364 | 365 | return; 366 | 367 | } else if ( event.keyCode === _this.keys[ STATE.ROTATE ] && ! _this.noRotate ) { 368 | 369 | _state = STATE.ROTATE; 370 | 371 | } else if ( event.keyCode === _this.keys[ STATE.ZOOM ] && ! _this.noZoom ) { 372 | 373 | _state = STATE.ZOOM; 374 | 375 | } else if ( event.keyCode === _this.keys[ STATE.PAN ] && ! _this.noPan ) { 376 | 377 | _state = STATE.PAN; 378 | 379 | } 380 | 381 | } 382 | 383 | function keyup( event ) { 384 | 385 | if ( _this.enabled === false ) return; 386 | 387 | _state = _prevState; 388 | 389 | window.addEventListener( 'keydown', keydown, false ); 390 | 391 | } 392 | 393 | function mousedown( event ) { 394 | 395 | if ( _this.enabled === false ) return; 396 | 397 | event.preventDefault(); 398 | event.stopPropagation(); 399 | 400 | if ( _state === STATE.NONE ) { 401 | 402 | _state = event.button; 403 | 404 | } 405 | 406 | if ( _state === STATE.ROTATE && ! _this.noRotate ) { 407 | 408 | _moveCurr.copy( getMouseOnCircle( event.pageX, event.pageY ) ); 409 | _movePrev.copy( _moveCurr ); 410 | 411 | } else if ( _state === STATE.ZOOM && ! _this.noZoom ) { 412 | 413 | _zoomStart.copy( getMouseOnScreen( event.pageX, event.pageY ) ); 414 | _zoomEnd.copy( _zoomStart ); 415 | 416 | } else if ( _state === STATE.PAN && ! _this.noPan ) { 417 | 418 | _panStart.copy( getMouseOnScreen( event.pageX, event.pageY ) ); 419 | _panEnd.copy( _panStart ); 420 | 421 | } 422 | 423 | document.addEventListener( 'mousemove', mousemove, false ); 424 | document.addEventListener( 'mouseup', mouseup, false ); 425 | 426 | _this.dispatchEvent( startEvent ); 427 | 428 | } 429 | 430 | function mousemove( event ) { 431 | 432 | if ( _this.enabled === false ) return; 433 | 434 | event.preventDefault(); 435 | event.stopPropagation(); 436 | 437 | if ( _state === STATE.ROTATE && ! _this.noRotate ) { 438 | 439 | _movePrev.copy( _moveCurr ); 440 | _moveCurr.copy( getMouseOnCircle( event.pageX, event.pageY ) ); 441 | 442 | } else if ( _state === STATE.ZOOM && ! _this.noZoom ) { 443 | 444 | _zoomEnd.copy( getMouseOnScreen( event.pageX, event.pageY ) ); 445 | 446 | } else if ( _state === STATE.PAN && ! _this.noPan ) { 447 | 448 | _panEnd.copy( getMouseOnScreen( event.pageX, event.pageY ) ); 449 | 450 | } 451 | 452 | } 453 | 454 | function mouseup( event ) { 455 | 456 | if ( _this.enabled === false ) return; 457 | 458 | event.preventDefault(); 459 | event.stopPropagation(); 460 | 461 | _state = STATE.NONE; 462 | 463 | document.removeEventListener( 'mousemove', mousemove ); 464 | document.removeEventListener( 'mouseup', mouseup ); 465 | _this.dispatchEvent( endEvent ); 466 | 467 | } 468 | 469 | function mousewheel( event ) { 470 | 471 | if ( _this.enabled === false ) return; 472 | 473 | event.preventDefault(); 474 | event.stopPropagation(); 475 | 476 | switch ( event.deltaMode ) { 477 | 478 | case 2: 479 | // Zoom in pages 480 | _zoomStart.y -= event.deltaY * 0.025; 481 | break; 482 | 483 | case 1: 484 | // Zoom in lines 485 | _zoomStart.y -= event.deltaY * 0.01; 486 | break; 487 | 488 | default: 489 | // undefined, 0, assume pixels 490 | _zoomStart.y -= event.deltaY * 0.00025; 491 | break; 492 | 493 | } 494 | 495 | _this.dispatchEvent( startEvent ); 496 | _this.dispatchEvent( endEvent ); 497 | 498 | } 499 | 500 | function touchstart( event ) { 501 | 502 | if ( _this.enabled === false ) return; 503 | 504 | switch ( event.touches.length ) { 505 | 506 | case 1: 507 | _state = STATE.TOUCH_ROTATE; 508 | _moveCurr.copy( getMouseOnCircle( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ) ); 509 | _movePrev.copy( _moveCurr ); 510 | break; 511 | 512 | default: // 2 or more 513 | _state = STATE.TOUCH_ZOOM_PAN; 514 | var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX; 515 | var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY; 516 | _touchZoomDistanceEnd = _touchZoomDistanceStart = Math.sqrt( dx * dx + dy * dy ); 517 | 518 | var x = ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX ) / 2; 519 | var y = ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY ) / 2; 520 | _panStart.copy( getMouseOnScreen( x, y ) ); 521 | _panEnd.copy( _panStart ); 522 | break; 523 | 524 | } 525 | 526 | _this.dispatchEvent( startEvent ); 527 | 528 | } 529 | 530 | function touchmove( event ) { 531 | 532 | if ( _this.enabled === false ) return; 533 | 534 | event.preventDefault(); 535 | event.stopPropagation(); 536 | 537 | switch ( event.touches.length ) { 538 | 539 | case 1: 540 | _movePrev.copy( _moveCurr ); 541 | _moveCurr.copy( getMouseOnCircle( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ) ); 542 | break; 543 | 544 | default: // 2 or more 545 | var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX; 546 | var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY; 547 | _touchZoomDistanceEnd = Math.sqrt( dx * dx + dy * dy ); 548 | 549 | var x = ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX ) / 2; 550 | var y = ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY ) / 2; 551 | _panEnd.copy( getMouseOnScreen( x, y ) ); 552 | break; 553 | 554 | } 555 | 556 | } 557 | 558 | function touchend( event ) { 559 | 560 | if ( _this.enabled === false ) return; 561 | 562 | switch ( event.touches.length ) { 563 | 564 | case 0: 565 | _state = STATE.NONE; 566 | break; 567 | 568 | case 1: 569 | _state = STATE.TOUCH_ROTATE; 570 | _moveCurr.copy( getMouseOnCircle( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ) ); 571 | _movePrev.copy( _moveCurr ); 572 | break; 573 | 574 | } 575 | 576 | _this.dispatchEvent( endEvent ); 577 | 578 | } 579 | 580 | function contextmenu( event ) { 581 | 582 | event.preventDefault(); 583 | 584 | } 585 | 586 | this.dispose = function() { 587 | 588 | this.domElement.removeEventListener( 'contextmenu', contextmenu, false ); 589 | this.domElement.removeEventListener( 'mousedown', mousedown, false ); 590 | this.domElement.removeEventListener( 'wheel', mousewheel, false ); 591 | 592 | this.domElement.removeEventListener( 'touchstart', touchstart, false ); 593 | this.domElement.removeEventListener( 'touchend', touchend, false ); 594 | this.domElement.removeEventListener( 'touchmove', touchmove, false ); 595 | 596 | document.removeEventListener( 'mousemove', mousemove, false ); 597 | document.removeEventListener( 'mouseup', mouseup, false ); 598 | 599 | window.removeEventListener( 'keydown', keydown, false ); 600 | window.removeEventListener( 'keyup', keyup, false ); 601 | 602 | }; 603 | 604 | this.domElement.addEventListener( 'contextmenu', contextmenu, false ); 605 | this.domElement.addEventListener( 'mousedown', mousedown, false ); 606 | this.domElement.addEventListener( 'wheel', mousewheel, false ); 607 | 608 | this.domElement.addEventListener( 'touchstart', touchstart, false ); 609 | this.domElement.addEventListener( 'touchend', touchend, false ); 610 | this.domElement.addEventListener( 'touchmove', touchmove, false ); 611 | 612 | window.addEventListener( 'keydown', keydown, false ); 613 | window.addEventListener( 'keyup', keyup, false ); 614 | 615 | this.handleResize(); 616 | 617 | // force an update at start 618 | this.update(); 619 | 620 | }; 621 | 622 | THREE.TrackballControls.prototype = Object.create( THREE.EventDispatcher.prototype ); 623 | THREE.TrackballControls.prototype.constructor = THREE.TrackballControls; 624 | -------------------------------------------------------------------------------- /web-app/animations/particles/main.js: -------------------------------------------------------------------------------- 1 | /***************************************************/ 2 | /* Original animation from Charlie Hoey 3 | /* http://charliehoey.com 4 | /***************************************************/ 5 | 6 | function Particles() { 7 | var options; 8 | var tick = 0; 9 | var particleSystem; 10 | 11 | this.getPath = function () { 12 | return 'animations/particles'; 13 | } 14 | 15 | this.init = function (camera, scene, renderer) { 16 | camera.position.z = 34; 17 | particleSystem = new THREE.GPUParticleSystem({ 18 | maxParticles: 250000 19 | }); 20 | scene.add(particleSystem); 21 | 22 | options = { 23 | horizontalSpeed: 0.8, 24 | verticalSpeed: 0.4, 25 | color: 0xaa88ff 26 | }; 27 | } 28 | 29 | this.updateDefault = function () { 30 | tick += 0.02; // in sec 31 | particleSystem.update(tick); 32 | } 33 | 34 | this.update = function (timeDelta, parameters) { 35 | tick += timeDelta; // in sec 36 | parameters.position = new THREE.Vector3(); 37 | parameters.position.x = Math.sin(tick * options.horizontalSpeed) * 20; 38 | parameters.position.y = Math.sin(tick * options.verticalSpeed) * 10; 39 | parameters.position.z = Math.sin(tick * options.horizontalSpeed + options.verticalSpeed) * 5; 40 | 41 | var colorString = "hsl(" + parameters.hue + ", " + parameters.saturation + "%, " + parameters.lightness + "%)" 42 | parameters.color = colorString; 43 | 44 | parameters.sizeRandomness = 2.0; 45 | parameters.colorRandomness = 0.2; 46 | 47 | for (var x = 0; x < parameters.spawnRate * timeDelta; x++) { 48 | particleSystem.spawnParticle(parameters); 49 | } 50 | particleSystem.update(tick); 51 | } 52 | } -------------------------------------------------------------------------------- /web-app/animations/particles/parameters.json: -------------------------------------------------------------------------------- 1 | { 2 | "parameters": [ 3 | { "name": "velocityRandomness", "avg": 1.0, "min": 0.0, "max": 3.0, "step": -1, "blur": 1, "FPS": 1.0 }, 4 | { "name": "positionRandomness", "avg": 0.70, "min": 0.0, "max": 1.5, "step": -1, "blur": 50, "FPS": 0.1 }, 5 | { "name": "size", "avg": 4.5, "min": 3.5, "max": 13.0, "step": -1, "blur": 50, "FPS": 0.1 }, 6 | { "name": "lifetime", "avg": 8.0, "min": 2.0, "max": 20.0, "step": -1, "blur": 1, "FPS": 1.0 }, 7 | { "name": "turbulence", "avg": 0.2, "min": 0.1, "max": 0.5, "step": -1, "blur": 100, "FPS": 0.1 }, 8 | { "name": "spawnRate", "avg": 6000, "min": 1000.0, "max": 30000.0, "step": -1, "blur": 1, "FPS": 2.0 }, 9 | { "name": "timeScale", "avg": 0.5, "min": 0.1, "max": 1.0, "step": -1, "blur": 100, "FPS": 0.1 }, 10 | { "name": "hue", "avg": 180, "min": 0, "max": 360, "step": 1, "blur": 100, "FPS": 0.08 }, 11 | { "name": "saturation", "avg": 50, "min": 30, "max": 80, "step": 1, "blur": 50, "FPS": 1.0 }, 12 | { "name": "lightness", "avg": 50, "min": 30, "max": 80, "step": 1, "blur": 50, "FPS": 1.0 } 13 | ] 14 | } -------------------------------------------------------------------------------- /web-app/animations/particles/particle2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/br-g/Deep-Audio-Visualization/9dce262cbbe18fed0b5f2e9e0e49d4b4556ec4b2/web-app/animations/particles/particle2.png -------------------------------------------------------------------------------- /web-app/animations/particles/perlin-512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/br-g/Deep-Audio-Visualization/9dce262cbbe18fed0b5f2e9e0e49d4b4556ec4b2/web-app/animations/particles/perlin-512.png -------------------------------------------------------------------------------- /web-app/audio.js: -------------------------------------------------------------------------------- 1 | function AudioManager () { 2 | this.audio = null; 3 | 4 | this.load = function (filePath) { 5 | this.audio = new Audio(filePath); 6 | } 7 | this.playMusic = function () { 8 | this.audio.play(); 9 | } 10 | this.pauseMusic = function () { 11 | if (this.audio != null) 12 | this.audio.pause(); 13 | } 14 | this.getElapsedTime = function() { 15 | return this.audio.currentTime; // in s 16 | } 17 | this.ended = function() { 18 | return this.audio.ended; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /web-app/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/br-g/Deep-Audio-Visualization/9dce262cbbe18fed0b5f2e9e0e49d4b4556ec4b2/web-app/favicon.ico -------------------------------------------------------------------------------- /web-app/features.js: -------------------------------------------------------------------------------- 1 | function Features () { 2 | this.sampleRate = null; 3 | this.features = null; 4 | 5 | this.load = function (filePath) { 6 | var _this = this; 7 | 8 | return $.ajax({ 9 | url: filePath, 10 | dataType: 'json', 11 | async: true, 12 | success: function(data) { 13 | console.log("Features successfully loaded"); 14 | _this.sampleRate = data['sampleRate']; 15 | _this.features = data['featuresData']; 16 | } 17 | }); 18 | } 19 | 20 | // Get features at given time in the music. 21 | // Time in ms. 22 | this.get = function (elapsedTime) { 23 | var frameIndex = Math.round(elapsedTime * this.sampleRate / 1000.0); 24 | var frame = {} 25 | for (var b in this.features) { 26 | frame[b] = this.features[b][frameIndex]; 27 | } 28 | return /*this.features["blur" + blur][frameIndex]*/ frame; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /web-app/fonts/SourceSansPro-ExtraLight.otf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/br-g/Deep-Audio-Visualization/9dce262cbbe18fed0b5f2e9e0e49d4b4556ec4b2/web-app/fonts/SourceSansPro-ExtraLight.otf -------------------------------------------------------------------------------- /web-app/fonts/SourceSansPro-Light.otf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/br-g/Deep-Audio-Visualization/9dce262cbbe18fed0b5f2e9e0e49d4b4556ec4b2/web-app/fonts/SourceSansPro-Light.otf -------------------------------------------------------------------------------- /web-app/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Deep Audio visualization 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | About 45 | 46 |
47 |
48 |

Deep Audio Visualization

49 |

Bruno Godefroy - 2017

50 | [about] 51 |

Click to continue

52 |
53 |
54 | 55 |
Click to change animation
56 |
57 |
58 |
59 |
60 |
61 | 62 |
63 | 64 | 65 | -------------------------------------------------------------------------------- /web-app/main.js: -------------------------------------------------------------------------------- 1 | function App () { 2 | this.animationManager = null; 3 | this.audioManager = null; 4 | this.playlistManager = null; 5 | 6 | this.init = function () { 7 | this.audioManager = new AudioManager(); 8 | this.animationManager = new AnimationManager(); 9 | this.animationManager.init(); 10 | this.playlistManager = new PlaylistManager(); 11 | return this.animationManager.nextAnimation(); 12 | } 13 | 14 | this.loadPlaylist = function (filePath) { 15 | var _this = this; 16 | 17 | return this.playlistManager.load(filePath) 18 | .then(function() { 19 | _this.playlistManager.randomize(); 20 | }); 21 | } 22 | 23 | this.setAnimation = function(animName) { 24 | this.animationManager.setAnimation(animName); 25 | } 26 | 27 | this.nextAnimation = function() { 28 | return this.animationManager.nextAnimation(); 29 | } 30 | 31 | this.playNextSong = function () { 32 | var nextSong = this.playlistManager.nextSong(); 33 | this.updateSongInfo(); 34 | this.audioManager.pauseMusic(); 35 | this.audioManager.load(this.playlistManager.getAudioPath()); 36 | this.animationManager.setAudioManager(this.audioManager); 37 | 38 | var _this = this; 39 | return this.animationManager.loadFeatures(this.playlistManager.getFeaturesPath()).then(function() { 40 | _this.audioManager.playMusic(); 41 | }); 42 | } 43 | 44 | this.updateSongInfo = function () { 45 | $("#controls > #songInfo > #title").html(this.playlistManager.getTitle()); 46 | $("#controls > #songInfo > #artist").html(this.playlistManager.getArtist()); 47 | } 48 | } 49 | 50 | 51 | var app = null; 52 | function startApp() { 53 | showInterface(); 54 | showStartMessage(); 55 | setTimeout(hideStartMessage, 10000); 56 | 57 | app.init().then(function() { 58 | app.loadPlaylist('playlist.json').then(function() { 59 | app.playNextSong().then(function() { 60 | app.animationManager.launch(); 61 | 62 | $("#controls > #next").click(function() { 63 | app.playNextSong(); 64 | }); 65 | 66 | $("canvas").click(function() { 67 | hideStartMessage(); 68 | app.nextAnimation(); 69 | }); 70 | }); 71 | }); 72 | }); 73 | } 74 | 75 | 76 | $(document).ready(function() { 77 | showIntro(); 78 | $('body').on('click', function(event) { 79 | if (event.target.id != 'about' && app === null) { 80 | app = new App(); 81 | hideIntro(); 82 | setTimeout(startApp, 2000); 83 | } 84 | }); 85 | }); 86 | 87 | 88 | function showIntro() { 89 | $("#intro").animate({ 90 | opacity: 1.0 91 | }, 800); 92 | } 93 | function hideIntro() { 94 | $("#intro").animate({ 95 | opacity: 0.0 96 | }, 1400); 97 | setTimeout(function() { 98 | $("#intro").hide(); 99 | }, 1400); 100 | } 101 | function showStartMessage() { 102 | $("#startMessage").show(); 103 | $("#startMessage").animate({ 104 | opacity: 1.0 105 | }, 800); 106 | } 107 | function hideStartMessage() { 108 | $("#startMessage").animate({ 109 | opacity: 0.0 110 | }, 1400); 111 | } 112 | function showInterface() { 113 | $("#controls").show(); 114 | $("#controls").animate({ 115 | opacity: 1.0 116 | }, 800); 117 | 118 | $("#readMeLink").show(); 119 | $("#readMeLink").animate({ 120 | opacity: 1.0 121 | }, 800); 122 | } 123 | -------------------------------------------------------------------------------- /web-app/next_button.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/br-g/Deep-Audio-Visualization/9dce262cbbe18fed0b5f2e9e0e49d4b4556ec4b2/web-app/next_button.png -------------------------------------------------------------------------------- /web-app/paramMapping.js: -------------------------------------------------------------------------------- 1 | // Represents an animation parameter (position, color, speed, ...) 2 | var Parameter = function (name, avg, minValue, maxValue, step, _default, blur, FPS) { 3 | this.name = name; 4 | this.avg = avg; 5 | this.minValue = minValue; 6 | this.maxValue = maxValue; 7 | this.step = step; 8 | this.default = _default; 9 | this.blur = blur; 10 | this.FPS = FPS; 11 | 12 | this.lastOutputValue = -1; 13 | this.lastChangeTime = 0; 14 | 15 | // Scales input value ([0;1]) into [minValue;maxValue]. 16 | // Takes into account FPS limitation requirements. 17 | this.scale = function (input, timeElapsed) { 18 | 19 | var curTime = new Date().getTime(); 20 | 21 | if (this.lastOutputValue != -1 && (curTime - this.lastChangeTime < 0.5 * 1.0/this.FPS * 1000 || (this.FPS != -1 && Math.random() * 60.0 / this.FPS * 0.5 > 1.0))) { 22 | return this.lastOutputValue; 23 | } 24 | else { 25 | lastChangeTime = curTime; 26 | 27 | // Computes mapped value 28 | var mappedValue = 0.0; 29 | 30 | if (input < 0.5) { 31 | mappedValue = input * 2.0 * (this.minValue - this.avg) + this.avg; 32 | } else { 33 | mappedValue = (input - 0.5) * 2.0 * (this.maxValue - this.avg) + this.avg; 34 | } 35 | //var res = this.getAveragedValue(mappedValue); 36 | if (step != -1) { 37 | mappedValue = Math.round(mappedValue / step) * step; 38 | } 39 | this.lastOutputValue = mappedValue 40 | return mappedValue; 41 | } 42 | } 43 | } 44 | 45 | // Represents a mapping from input features to animation parameters. 46 | var ParamMapping = function(size, params, map) { 47 | this.size = 0; 48 | this.params = null; 49 | this.map = null; 50 | 51 | this.isLoading = false; // Avoid conflicts while loading 52 | 53 | // Loads parameters from AJAX. 54 | this.load = function (filePath) { 55 | var _this = this; 56 | 57 | this.size = 0; 58 | this.params = null; 59 | this.map = null; 60 | 61 | this.isLoading = true; 62 | 63 | return $.ajax({ 64 | url: filePath, 65 | dataType: 'json', 66 | async: true, 67 | success: function(data) { 68 | console.log("Animation parameters successfully loaded"); 69 | _this.size = data['parameters'].length; 70 | _this.params = []; 71 | _this.map = []; 72 | for (i = 0; i < _this.size; i++) { 73 | _this.params.push(new Parameter( 74 | data['parameters'][i]['name'], 75 | data['parameters'][i]['avg'], 76 | data['parameters'][i]['min'], 77 | data['parameters'][i]['max'], 78 | data['parameters'][i]['step'], 79 | data['parameters'][i]['default'], 80 | data['parameters'][i]['blur'], 81 | data['parameters'][i]['FPS'] 82 | )); 83 | _this.map.push(i); 84 | } 85 | _this.isLoading = false; 86 | } 87 | }); 88 | } 89 | 90 | this.randomize = function () { 91 | // Uses Fisher–Yates shuffle 92 | var currentIndex = this.map.length; 93 | while (currentIndex > 0) { 94 | var randomIndex = Math.floor(Math.random() * currentIndex); 95 | currentIndex -= 1; 96 | var tmp = this.map[currentIndex]; 97 | this.map[currentIndex] = this.map[randomIndex]; 98 | this.map[randomIndex] = tmp; 99 | } 100 | } 101 | 102 | // Given some input features, provides a suitable mapping for the animation parameters. 103 | this.doMap = function (features, timeElapsed) { 104 | if (this.isLoading) return null; 105 | 106 | if (features["blur1"].length !== this.size) { 107 | console.log("Warning: features vector size and number of animation parameters are different."); 108 | } 109 | var parameters = {}; 110 | for (var i = 0; i < this.size; i++) { 111 | parameters[this.params[i].name] = this.params[i].scale(features["blur" + this.params[i].blur][this.map[i]], timeElapsed); 112 | } 113 | return parameters; 114 | } 115 | 116 | this.doMapDefault = function () { 117 | if (this.isLoading) return null; 118 | 119 | var parameters = {}; 120 | for (var i = 0; i < this.size; i++) { 121 | parameters[this.params[i].name] = this.params[i].default; 122 | } 123 | return parameters; 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /web-app/playlist.js: -------------------------------------------------------------------------------- 1 | function PlaylistManager () { 2 | this.list = null; 3 | this.pointer = -1; 4 | 5 | this.randomize = function () { 6 | // Uses Fisher–Yates shuffle 7 | var currentIndex = this.list.length; 8 | while (currentIndex > 0) { 9 | var randomIndex = Math.floor(Math.random() * currentIndex); 10 | currentIndex -= 1; 11 | var tmp = this.list[currentIndex]; 12 | this.list[currentIndex] = this.list[randomIndex]; 13 | this.list[randomIndex] = tmp; 14 | } 15 | } 16 | 17 | this.load = function (filePath) { 18 | var _this = this; 19 | 20 | return $.ajax({ 21 | url: filePath, 22 | dataType: 'json', 23 | async: true, 24 | success: function(data) { 25 | console.log("Sample songs successfully loaded"); 26 | _this.list = data['playlist']; 27 | } 28 | }); 29 | } 30 | 31 | this.nextSong = function () { 32 | this.pointer = (this.pointer + 1) % this.list.length; 33 | } 34 | 35 | this.getFeaturesPath = function () { 36 | return this.list[this.pointer]['featuresFilePath']; 37 | } 38 | 39 | this.getAudioPath = function () { 40 | return this.list[this.pointer]['audioFilePath']; 41 | } 42 | 43 | this.getTitle = function () { 44 | return this.list[this.pointer]['title']; 45 | } 46 | 47 | this.getArtist = function () { 48 | return this.list[this.pointer]['artist']; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /web-app/playlist.json: -------------------------------------------------------------------------------- 1 | { 2 | "playlist": [ 3 | { "title": "Bopin'", "artist": "Vodovoz", "audioFilePath": "https://br-g.github.io/Deep-Audio-Visualization/web-app/audio/Bopin - Vodovoz.wav", "featuresFilePath": "https://br-g.github.io/Deep-Audio-Visualization/web-app/features/Bopin - Vodovoz.json" }, 4 | { "title": "Cosmic Storm", "artist": "A. Himitsu", "audioFilePath": "https://br-g.github.io/Deep-Audio-Visualization/web-app/audio/Cosmic Storm - A Himitsu.wav", "featuresFilePath": "https://br-g.github.io/Deep-Audio-Visualization/web-app/features/Cosmic Storm - A Himitsu.json" }, 5 | { "title": "Dubstep", "artist": "Bensound", "audioFilePath": "https://br-g.github.io/Deep-Audio-Visualization/web-app/audio/Dubstep - Bensound.wav", "featuresFilePath": "https://br-g.github.io/Deep-Audio-Visualization/web-app/features/Dubstep - Bensound.json" }, 6 | { "title": "Grand canyon", "artist": "David Löhstana", "audioFilePath": "https://br-g.github.io/Deep-Audio-Visualization/web-app/audio/Grand canyon - David Löhstana.wav", "featuresFilePath": "https://br-g.github.io/Deep-Audio-Visualization/web-app/features/Grand canyon - David Löhstana.json" }, 7 | { "title": "Hip Hop", "artist": "Aleksandr Shamaluev", "audioFilePath": "https://br-g.github.io/Deep-Audio-Visualization/web-app/audio/Hip Hop - Aleksandr Shamaluev.wav", "featuresFilePath": "https://br-g.github.io/Deep-Audio-Visualization/web-app/features/Hip Hop - Aleksandr Shamaluev.json" }, 8 | { "title": "Island", "artist": "MBB", "audioFilePath": "https://br-g.github.io/Deep-Audio-Visualization/web-app/audio/Island - MBB.wav", "featuresFilePath": "https://br-g.github.io/Deep-Audio-Visualization/web-app/features/Island - MBB.json" }, 9 | { "title": "Prelude No. 18", "artist": "Chris Zabriskie", "audioFilePath": "https://br-g.github.io/Deep-Audio-Visualization/web-app/audio/Prelude No 18 - Chris Zabriskie.wav", "featuresFilePath": "https://br-g.github.io/Deep-Audio-Visualization/web-app/features/Prelude No 18 - Chris Zabriskie.json" }, 10 | { "title": "William Tell Overture (Final)", "artist": "Rossini", "audioFilePath": "https://br-g.github.io/Deep-Audio-Visualization/web-app/audio/William Tell Overture (Final) - Rossini.wav", "featuresFilePath": "https://br-g.github.io/Deep-Audio-Visualization/web-app/features/William Tell Overture (Final) - Rossini.json" } 11 | ] 12 | } 13 | -------------------------------------------------------------------------------- /web-app/style.css: -------------------------------------------------------------------------------- 1 | @font-face { 2 | font-family: 'SourceSansPro-Light'; 3 | src: url(fonts/SourceSansPro-Light.otf); 4 | } 5 | @font-face { 6 | font-family: 'SourceSansPro-ExtraLight'; 7 | src: url(fonts/SourceSansPro-ExtraLight.otf); 8 | } 9 | 10 | 11 | html, body { 12 | width: 100%; 13 | height: 100%; 14 | margin: 0px; 15 | border: 0; 16 | overflow: hidden; 17 | display: block; 18 | user-select: none; 19 | -moz-user-select: none; 20 | -khtml-user-select: none; 21 | -webkit-user-select: none; 22 | -o-user-select: none; 23 | background-color: black; 24 | } 25 | canvas { 26 | width: 100%; 27 | height: 100%; 28 | margin: 0; 29 | } 30 | #readMeLink { 31 | position: fixed; 32 | top: 13px; 33 | text-align: right; 34 | width: 100%; 35 | color: rgba(255, 255, 255, 0.39); 36 | font-family: 'SourceSansPro-Light', Helvetica, Arial, sans-serif; 37 | font-size: 15px; 38 | right: 20px; 39 | opacity: 0; 40 | display: none; 41 | } 42 | #readMeLink:hover { 43 | color: rgba(255, 255, 255, 0.51); 44 | } 45 | #startMessage { 46 | font-family: 'SourceSansPro-Light', Helvetica, Arial, sans-serif; 47 | position: fixed; 48 | bottom: 80px; 49 | text-align: center; 50 | width: 100%; 51 | color: rgba(255, 255, 255, 0.69); 52 | font-size: 20px; 53 | cursor: default; 54 | display: none; 55 | opacity: 0; 56 | } 57 | #controls { 58 | position: fixed; 59 | bottom: 0px; 60 | background-color: #131313; 61 | height: 50px; 62 | width: 100%; 63 | border-top: #333333; 64 | border-style: solid; 65 | border-top-width: 2px; 66 | opacity: 0.5; 67 | cursor: default; 68 | display: none; 69 | opacity: 0; 70 | } 71 | #controls > #next { 72 | width: 31px; 73 | position: absolute; 74 | right: 24px; 75 | bottom: 9px; 76 | cursor: pointer; 77 | } 78 | #controls > #songInfo { 79 | color: white; 80 | text-align: center; 81 | font-family: sans-serif; 82 | } 83 | #controls > #songInfo > #title { 84 | font-size: 19px; 85 | font-weight: 600; 86 | margin-top: 6px; 87 | } 88 | #controls > #songInfo > #artist { 89 | font-size: 13px; 90 | font-weight: 200; 91 | font-style: italic; 92 | margin-top: -1px; 93 | margin-bottom: 0px; 94 | } 95 | #intro { 96 | color: #e9e9e9; 97 | font-family: 'SourceSansPro-ExtraLight', Helvetica, Arial, sans-serif; 98 | opacity: 0; 99 | } 100 | #intro h2 { 101 | font-size: 40px; 102 | margin-bottom: 0px; 103 | margin-top: 0px; 104 | } 105 | #intro h4 { 106 | font-size: 22px; 107 | margin-top: 9px; 108 | margin-bottom: 11px; 109 | } 110 | #intro a { 111 | font-size: 22px; 112 | color: #9c7e43; 113 | text-decoration: none; 114 | } 115 | #intro a:hover { 116 | color: #b08f4f; 117 | } 118 | #intro p { 119 | color: #c1c1c1; 120 | text-align: center; 121 | position: relative; 122 | margin: auto; 123 | bottom: 50px; 124 | position: absolute; 125 | width: 100%; 126 | font-size: 19px; 127 | } 128 | 129 | 130 | .centerContainer { 131 | height: 100%; 132 | position: relative; 133 | } 134 | .centerContent { 135 | width: 70%; 136 | margin: 0; 137 | position: absolute; 138 | top: 50%; 139 | left: 50%; 140 | -ms-transform: translate(-50%, -50%); 141 | transform: translate(-50%, -50%); 142 | text-align: right; 143 | height: 70%; 144 | } 145 | .blinking { 146 | animation: blinker 2.8s linear infinite; 147 | } 148 | @keyframes blinker { 149 | 50% { 150 | opacity: 0.5; 151 | } 152 | } 153 | --------------------------------------------------------------------------------