├── .github └── workflows │ └── deploy.yml ├── .gitignore ├── LICENSE ├── README.md ├── astro.config.ts ├── package.json ├── patches └── fourwastaken@0.2.0.patch ├── pnpm-lock.yaml ├── public ├── 2k_earth_bump.jpg ├── 2k_earth_clouds.jpeg ├── 2k_earth_color.jpeg ├── 2k_earth_night.jpeg ├── 2k_earth_specular.jpeg ├── 2k_jupiter.jpg ├── 2k_mars.jpg ├── 2k_mercury.jpg ├── 2k_moon.jpeg ├── 2k_venus.jpg ├── 3DNoise.bin ├── 4k_stars.jpg ├── 8k_stars.jpg ├── earth.jpg ├── favicon.png ├── jupiter.jpg ├── mars.jpg ├── mercury.jpg ├── moon.jpg ├── procedural.jpg └── venus.jpg ├── screenshots ├── earth-ui.jpg ├── earth.jpg ├── jupiter.jpg ├── mars.jpg ├── mercury.jpg ├── moon.jpg ├── procedural-1.jpg ├── procedural-2.jpg ├── procedural-3.jpg ├── procedural-ui.jpg └── venus.jpg ├── src ├── components │ ├── Author.astro │ ├── Canvas.astro │ ├── Footer.astro │ ├── GitHubIcon.astro │ ├── MainNavigation.astro │ ├── MainTitle.astro │ ├── Meta.astro │ └── TextureCredits.astro ├── controls │ ├── light.controls.ts │ ├── monitor.controls.ts │ ├── planet.controls.ts │ ├── quality.controls.ts │ ├── rotation.controls.ts │ └── setup.ts ├── env.d.ts ├── layouts │ └── Layout.astro ├── pages │ ├── earth.astro │ ├── jupiter.astro │ ├── mars.astro │ ├── mercury.astro │ ├── moon.astro │ ├── procedural.astro │ └── venus.astro └── webgl │ ├── loaders │ ├── noise.loader.ts │ ├── texture.loader.ts │ └── texture.types.ts │ ├── renderer.ts │ ├── settings │ ├── device.ts │ ├── quality.ts │ └── uniforms.ts │ ├── shaders │ ├── earth.fragment.glsl │ ├── planet.fragment.glsl │ ├── procedural.fragment.glsl │ └── vertex.glsl │ └── textures │ └── starsTexture.ts └── tsconfig.json /.github/workflows/deploy.yml: -------------------------------------------------------------------------------- 1 | name: Deploy to GitHub Pages 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | branches: 9 | - main 10 | workflow_dispatch: 11 | 12 | permissions: 13 | contents: read 14 | pages: write 15 | id-token: write 16 | 17 | concurrency: 18 | group: "pages" 19 | cancel-in-progress: false 20 | 21 | jobs: 22 | build: 23 | runs-on: ubuntu-latest 24 | steps: 25 | - uses: actions/checkout@v3 26 | - uses: pnpm/action-setup@v2 27 | with: 28 | version: 8 29 | - uses: actions/setup-node@v3 30 | with: 31 | node-version: latest 32 | cache: pnpm 33 | - uses: actions/configure-pages@v3 34 | - run: pnpm install 35 | - run: pnpm build 36 | - uses: actions/upload-pages-artifact@v2 37 | with: 38 | path: dist 39 | 40 | deploy: 41 | runs-on: ubuntu-latest 42 | environment: 43 | name: github-pages 44 | url: ${{ steps.deployment.outputs.page_url }} 45 | needs: build 46 | steps: 47 | - name: Deploy to GitHub Pages 48 | id: deployment 49 | uses: actions/deploy-pages@v2 50 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | pnpm-debug.log* 8 | lerna-debug.log* 9 | 10 | node_modules 11 | dist 12 | dist-ssr 13 | *.local 14 | /textures 15 | 16 | # Editor directories and files 17 | .vscode/* 18 | !.vscode/extensions.json 19 | .idea 20 | .DS_Store 21 | *.suo 22 | *.ntvs* 23 | *.njsproj 24 | *.sln 25 | *.sw? 26 | -------------------------------------------------------------------------------- /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 | 635 | Copyright (C) 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 | Copyright (C) 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 | # Realtime planet shader in WebGL 2 | 3 | ## Procedural 4 | 5 |
6 | screenshot of the procedural shader with the UI 7 | 8 |
9 |
10 | 11 | live demo 12 |
13 | 14 |
15 | 16 | This is a GLSL fragment shader I originally made on [Shadertoy](https://www.shadertoy.com/view/Ds3XRl) when learning raymarching. Later I switched to analytic raycasting for better performance. It's made by raycasting simple spheres with a bunch of fbm noises used for the normals and colors, and a fake atmosphere computed with distance functions. 17 | 18 | I wanted to display it on a web page so that I can make a nice GUI to tweak the uniforms. Here it is ! 19 | 20 | It runs at 60fps on my old low-end phone, so it should also be quite smooth on whatever device you have. 21 | 22 |
23 | 24 | ## Textures 25 | 26 |
27 | screenshot of the earth shader with the UI 28 | 29 |
30 |
31 | 32 | live demo 33 |
34 | 35 |
36 | 37 | After the procedural version, I found a bunch of textures to display a realistic view of some planets of our solar system. Still with a few controls, and no quality setting because it should already run at full fps on most devices. 38 | 39 | ## Note 40 | 41 | If you want a minimalist setup to render GLSL shaders on a canvas like this one, you can check out the [little study](https://github.com/jsulpis/webgl-libs-comparison) I made before this project. 42 | 43 | ## More renders 44 | 45 |
46 | a render of the Earth 47 | a render of the Moon 48 | a render of Mercury 49 | a render of Venus 50 | a render of Mars 51 | a render of Jupiter 52 | a render of the procedural planet 53 | a render of the procedural planet 54 | a render of the procedural planet 55 |
56 | -------------------------------------------------------------------------------- /astro.config.ts: -------------------------------------------------------------------------------- 1 | import topLevelAwait from "vite-plugin-top-level-await"; 2 | import glsl from "vite-plugin-glsl"; 3 | import { defineConfig } from "astro/config"; 4 | 5 | export default defineConfig({ 6 | base: "/realtime-planet-shader", 7 | redirects: { 8 | "/": "/realtime-planet-shader/earth", 9 | }, 10 | vite: { 11 | plugins: [glsl(), topLevelAwait()], // top-level await present in the "four" library 12 | }, 13 | }); 14 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "realtime-planet-shader", 3 | "version": "0.0.0", 4 | "private": true, 5 | "type": "module", 6 | "scripts": { 7 | "build": "astro check && astro build", 8 | "dev": "astro dev", 9 | "preview": "astro preview", 10 | "serve": "pnpm build && pnpm preview" 11 | }, 12 | "devDependencies": { 13 | "@astrojs/check": "0.3.1", 14 | "@tweakpane/core": "2.0.0", 15 | "@types/node": "20.8.3", 16 | "astro": "3.4.4", 17 | "four": "npm:fourwastaken@0.2.0", 18 | "sass": "1.66.1", 19 | "tweakpane": "4.0.0", 20 | "typescript": "5.1.6", 21 | "vite": "4.4.9", 22 | "vite-plugin-glsl": "1.1.2", 23 | "vite-plugin-top-level-await": "1.3.1" 24 | }, 25 | "pnpm": { 26 | "patchedDependencies": { 27 | "fourwastaken@0.2.0": "patches/fourwastaken@0.2.0.patch" 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /patches/fourwastaken@0.2.0.patch: -------------------------------------------------------------------------------- 1 | diff --git a/package.json b/package.json 2 | index 4afc4d8c859021f5bf8a3fa7c2fb77ab3a480ad1..1eff2e34706a533005cd829c631690ce63d3388f 100644 3 | --- a/package.json 4 | +++ b/package.json 5 | @@ -22,7 +22,7 @@ 6 | "src/*" 7 | ], 8 | "type": "module", 9 | - "exports": "./dist/index.js", 10 | + "exports": "./src/index.ts", 11 | "sideEffects": false, 12 | "devDependencies": { 13 | "@types/node": "^20.4.2", 14 | diff --git a/src/Sampler.ts b/src/Sampler.ts 15 | index c0fdef75bcddb0c704b19dd1066712a5cc3c2e51..e6dbc0276ccfde53023c1feb6e6423fca6fc43f5 100644 16 | --- a/src/Sampler.ts 17 | +++ b/src/Sampler.ts 18 | @@ -1,7 +1,7 @@ 19 | /** 20 | * Represents a texel filter. 21 | */ 22 | -export type Filter = 'nearest' | 'linear' 23 | +export type Filter = 'nearest' | 'linear' | 'nearestMipmapNearest' | 'nearestMipmapLinear' | 'linearMipmapNearest' | 'linearMipmapLinear' 24 | 25 | /** 26 | * Represents a wrapping mode. 27 | diff --git a/src/WebGLRenderer.ts b/src/WebGLRenderer.ts 28 | index 28c182b54334be0b8bfb07b32e94aabaef879fac..8d545aec1a63b93fe525da70ebffd6eedbd74c8c 100644 29 | --- a/src/WebGLRenderer.ts 30 | +++ b/src/WebGLRenderer.ts 31 | @@ -42,10 +42,18 @@ const GL_RASTERIZER_DISCARD = 0x8c89 32 | 33 | const GL_NEAREST = 0x2600 34 | const GL_LINEAR = 0x2601 35 | +const GL_NEAREST_MIPMAP_NEAREST = 0x2700 36 | +const GL_NEAREST_MIPMAP_LINEAR = 0x2702 37 | +const GL_LINEAR_MIPMAP_NEAREST = 0x2701 38 | +const GL_LINEAR_MIPMAP_LINEAR = 0x2703 39 | 40 | const GL_FILTERS: Record = { 41 | nearest: GL_NEAREST, 42 | linear: GL_LINEAR, 43 | + nearestMipmapNearest: GL_NEAREST_MIPMAP_NEAREST, 44 | + nearestMipmapLinear: GL_NEAREST_MIPMAP_LINEAR, 45 | + linearMipmapNearest: GL_LINEAR_MIPMAP_NEAREST, 46 | + linearMipmapLinear: GL_LINEAR_MIPMAP_LINEAR, 47 | } as const 48 | 49 | const GL_REPEAT = 0x2901 50 | @@ -266,6 +274,10 @@ export class WebGLRenderer { 51 | this.gl.samplerParameteri(target, anisotropyExt.TEXTURE_MAX_ANISOTROPY_EXT, sampler.anisotropy) 52 | } 53 | 54 | + if (sampler.magFilter.includes('Mipmap') || sampler.minFilter.includes('Mipmap')) { 55 | + this.gl.generateMipmap(GL_TEXTURE_2D) 56 | + } 57 | + 58 | this.gl.samplerParameteri(target, GL_TEXTURE_MAG_FILTER, GL_FILTERS[sampler.magFilter]) 59 | this.gl.samplerParameteri(target, GL_TEXTURE_MIN_FILTER, GL_FILTERS[sampler.minFilter]) 60 | -------------------------------------------------------------------------------- /public/2k_earth_bump.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsulpis/realtime-planet-shader/cfa2776033d31250bb826b677e4539c4cecbd4be/public/2k_earth_bump.jpg -------------------------------------------------------------------------------- /public/2k_earth_clouds.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsulpis/realtime-planet-shader/cfa2776033d31250bb826b677e4539c4cecbd4be/public/2k_earth_clouds.jpeg -------------------------------------------------------------------------------- /public/2k_earth_color.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsulpis/realtime-planet-shader/cfa2776033d31250bb826b677e4539c4cecbd4be/public/2k_earth_color.jpeg -------------------------------------------------------------------------------- /public/2k_earth_night.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsulpis/realtime-planet-shader/cfa2776033d31250bb826b677e4539c4cecbd4be/public/2k_earth_night.jpeg -------------------------------------------------------------------------------- /public/2k_earth_specular.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsulpis/realtime-planet-shader/cfa2776033d31250bb826b677e4539c4cecbd4be/public/2k_earth_specular.jpeg -------------------------------------------------------------------------------- /public/2k_jupiter.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsulpis/realtime-planet-shader/cfa2776033d31250bb826b677e4539c4cecbd4be/public/2k_jupiter.jpg -------------------------------------------------------------------------------- /public/2k_mars.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsulpis/realtime-planet-shader/cfa2776033d31250bb826b677e4539c4cecbd4be/public/2k_mars.jpg -------------------------------------------------------------------------------- /public/2k_mercury.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsulpis/realtime-planet-shader/cfa2776033d31250bb826b677e4539c4cecbd4be/public/2k_mercury.jpg -------------------------------------------------------------------------------- /public/2k_moon.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsulpis/realtime-planet-shader/cfa2776033d31250bb826b677e4539c4cecbd4be/public/2k_moon.jpeg -------------------------------------------------------------------------------- /public/2k_venus.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsulpis/realtime-planet-shader/cfa2776033d31250bb826b677e4539c4cecbd4be/public/2k_venus.jpg -------------------------------------------------------------------------------- /public/3DNoise.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsulpis/realtime-planet-shader/cfa2776033d31250bb826b677e4539c4cecbd4be/public/3DNoise.bin -------------------------------------------------------------------------------- /public/4k_stars.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsulpis/realtime-planet-shader/cfa2776033d31250bb826b677e4539c4cecbd4be/public/4k_stars.jpg -------------------------------------------------------------------------------- /public/8k_stars.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsulpis/realtime-planet-shader/cfa2776033d31250bb826b677e4539c4cecbd4be/public/8k_stars.jpg -------------------------------------------------------------------------------- /public/earth.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsulpis/realtime-planet-shader/cfa2776033d31250bb826b677e4539c4cecbd4be/public/earth.jpg -------------------------------------------------------------------------------- /public/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsulpis/realtime-planet-shader/cfa2776033d31250bb826b677e4539c4cecbd4be/public/favicon.png -------------------------------------------------------------------------------- /public/jupiter.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsulpis/realtime-planet-shader/cfa2776033d31250bb826b677e4539c4cecbd4be/public/jupiter.jpg -------------------------------------------------------------------------------- /public/mars.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsulpis/realtime-planet-shader/cfa2776033d31250bb826b677e4539c4cecbd4be/public/mars.jpg -------------------------------------------------------------------------------- /public/mercury.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsulpis/realtime-planet-shader/cfa2776033d31250bb826b677e4539c4cecbd4be/public/mercury.jpg -------------------------------------------------------------------------------- /public/moon.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsulpis/realtime-planet-shader/cfa2776033d31250bb826b677e4539c4cecbd4be/public/moon.jpg -------------------------------------------------------------------------------- /public/procedural.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsulpis/realtime-planet-shader/cfa2776033d31250bb826b677e4539c4cecbd4be/public/procedural.jpg -------------------------------------------------------------------------------- /public/venus.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsulpis/realtime-planet-shader/cfa2776033d31250bb826b677e4539c4cecbd4be/public/venus.jpg -------------------------------------------------------------------------------- /screenshots/earth-ui.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsulpis/realtime-planet-shader/cfa2776033d31250bb826b677e4539c4cecbd4be/screenshots/earth-ui.jpg -------------------------------------------------------------------------------- /screenshots/earth.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsulpis/realtime-planet-shader/cfa2776033d31250bb826b677e4539c4cecbd4be/screenshots/earth.jpg -------------------------------------------------------------------------------- /screenshots/jupiter.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsulpis/realtime-planet-shader/cfa2776033d31250bb826b677e4539c4cecbd4be/screenshots/jupiter.jpg -------------------------------------------------------------------------------- /screenshots/mars.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsulpis/realtime-planet-shader/cfa2776033d31250bb826b677e4539c4cecbd4be/screenshots/mars.jpg -------------------------------------------------------------------------------- /screenshots/mercury.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsulpis/realtime-planet-shader/cfa2776033d31250bb826b677e4539c4cecbd4be/screenshots/mercury.jpg -------------------------------------------------------------------------------- /screenshots/moon.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsulpis/realtime-planet-shader/cfa2776033d31250bb826b677e4539c4cecbd4be/screenshots/moon.jpg -------------------------------------------------------------------------------- /screenshots/procedural-1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsulpis/realtime-planet-shader/cfa2776033d31250bb826b677e4539c4cecbd4be/screenshots/procedural-1.jpg -------------------------------------------------------------------------------- /screenshots/procedural-2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsulpis/realtime-planet-shader/cfa2776033d31250bb826b677e4539c4cecbd4be/screenshots/procedural-2.jpg -------------------------------------------------------------------------------- /screenshots/procedural-3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsulpis/realtime-planet-shader/cfa2776033d31250bb826b677e4539c4cecbd4be/screenshots/procedural-3.jpg -------------------------------------------------------------------------------- /screenshots/procedural-ui.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsulpis/realtime-planet-shader/cfa2776033d31250bb826b677e4539c4cecbd4be/screenshots/procedural-ui.jpg -------------------------------------------------------------------------------- /screenshots/venus.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsulpis/realtime-planet-shader/cfa2776033d31250bb826b677e4539c4cecbd4be/screenshots/venus.jpg -------------------------------------------------------------------------------- /src/components/Author.astro: -------------------------------------------------------------------------------- 1 | --- 2 | import GitHubIcon from "./GitHubIcon.astro"; 3 | --- 4 | 5 |
6 | Made by @jsulpis 7 | 12 | 13 | 14 |
15 | 16 | 38 | -------------------------------------------------------------------------------- /src/components/Canvas.astro: -------------------------------------------------------------------------------- 1 | 2 | 3 | 22 | -------------------------------------------------------------------------------- /src/components/Footer.astro: -------------------------------------------------------------------------------- 1 |
2 | 3 |
4 | 5 | 31 | -------------------------------------------------------------------------------- /src/components/GitHubIcon.astro: -------------------------------------------------------------------------------- 1 | 10 | 11 | 14 | 15 | 16 | 17 | 18 | 26 | -------------------------------------------------------------------------------- /src/components/MainNavigation.astro: -------------------------------------------------------------------------------- 1 | --- 2 | const routeNames = [ 3 | "procedural", 4 | "earth", 5 | "moon", 6 | "mercury", 7 | "venus", 8 | "mars", 9 | "jupiter", 10 | ]; 11 | 12 | const currentPath = Astro.url.pathname; 13 | --- 14 | 15 | 22 | 23 | 39 | 40 | 69 | -------------------------------------------------------------------------------- /src/components/MainTitle.astro: -------------------------------------------------------------------------------- 1 |

2 | 3 | 22 | -------------------------------------------------------------------------------- /src/components/Meta.astro: -------------------------------------------------------------------------------- 1 | --- 2 | const { class: className, ...rest } = Astro.props; // https://docs.astro.build/en/guides/styling/#passing-a-class-to-a-child-component 3 | --- 4 | 5 |
6 | 7 |
8 | 9 | 14 | -------------------------------------------------------------------------------- /src/components/TextureCredits.astro: -------------------------------------------------------------------------------- 1 |
2 | 3 |
4 | 5 | 11 | -------------------------------------------------------------------------------- /src/controls/light.controls.ts: -------------------------------------------------------------------------------- 1 | import type { Pane } from "tweakpane"; 2 | import type { CustomUniforms } from "../webgl/settings/uniforms"; 3 | 4 | export function addLightControls(pane: Pane, uniforms: CustomUniforms) { 5 | const light = pane.addFolder({ 6 | title: "Light", 7 | expanded: window.innerHeight > 800, 8 | }); 9 | 10 | light 11 | .addBinding({ pos: { x: 1, y: 1 } }, "pos", { 12 | label: "Sun position", 13 | picker: "inline", 14 | expanded: true, 15 | y: { inverted: true, min: -1, max: 1 }, 16 | x: { min: -1, max: 1 }, 17 | }) 18 | .on("change", ({ value: { x, y } }) => { 19 | uniforms.sunDirectionXY = [x, y]; 20 | }); 21 | 22 | light 23 | .addBinding( 24 | { value: round(Math.pow(uniforms.uSunIntensity / 5, 1 / 3)) }, 25 | "value", 26 | { 27 | label: "Sun intensity", 28 | min: 0, 29 | max: 1, 30 | } 31 | ) 32 | .on("change", ({ value }) => { 33 | uniforms.uSunIntensity = Math.pow(value, 3) * 5; 34 | }); 35 | light 36 | .addBinding( 37 | { value: round(Math.pow(uniforms.uAmbientLight, 1 / 5)) }, 38 | "value", 39 | { 40 | label: "Ambient light", 41 | min: 0, 42 | max: 1, 43 | } 44 | ) 45 | .on("change", ({ value }) => { 46 | uniforms.uAmbientLight = Math.pow(value, 5); 47 | }); 48 | } 49 | 50 | function round(n: number) { 51 | return Math.round(n * 100) / 100; 52 | } 53 | -------------------------------------------------------------------------------- /src/controls/monitor.controls.ts: -------------------------------------------------------------------------------- 1 | import type { Pane } from "tweakpane"; 2 | 3 | export function addMonitor(pane: Pane) { 4 | const monitorFolder = pane.addFolder({ 5 | title: "Monitor", 6 | expanded: false, 7 | }); 8 | 9 | const fps = { value: 0 }; 10 | 11 | monitorFolder.addBinding(fps, "value", { 12 | label: "FPS", 13 | readonly: true, 14 | }); 15 | monitorFolder.addBinding(fps, "value", { 16 | label: "", 17 | readonly: true, 18 | view: "graph", 19 | min: 0, 20 | max: 120, 21 | }); 22 | 23 | let deltaMs = 0; 24 | let frameIndex = 1; 25 | let frameMeasure; 26 | const frameWindowSize = 100; 27 | 28 | performance.mark("previous-frame"); 29 | 30 | requestAnimationFrame(function loop() { 31 | requestAnimationFrame(loop); 32 | 33 | // Measure duration of frame window 34 | if (frameIndex++ !== frameWindowSize) { 35 | return; 36 | } 37 | 38 | frameIndex = 1; 39 | performance.mark("current-frame"); 40 | frameMeasure = performance.measure( 41 | "duration", 42 | "previous-frame", 43 | "current-frame" 44 | ); 45 | performance.mark("previous-frame"); 46 | 47 | deltaMs = frameMeasure.duration / frameWindowSize; 48 | fps.value = Math.floor(1 / ((deltaMs || Infinity) / 1000)); 49 | }); 50 | } 51 | -------------------------------------------------------------------------------- /src/controls/planet.controls.ts: -------------------------------------------------------------------------------- 1 | import type { Pane } from "tweakpane"; 2 | import type { CustomUniforms } from "../webgl/settings/uniforms"; 3 | import type { ControlsOptions } from "./setup"; 4 | 5 | export function addPlanetControls( 6 | pane: Pane, 7 | uniforms: CustomUniforms, 8 | options: ControlsOptions["planet"] = {} 9 | ) { 10 | const planetFolder = pane.addFolder({ 11 | title: "Planet", 12 | expanded: window.innerHeight > 800, 13 | }); 14 | 15 | if (options.geometry === true) { 16 | const geometry = planetFolder.addFolder({ title: "Geometry" }); 17 | 18 | geometry 19 | .addBinding({ pos: { x: 0, y: 0 } }, "pos", { 20 | label: "Position", 21 | picker: "inline", 22 | y: { inverted: true, min: -2, max: 2 }, 23 | x: { min: -2, max: 2 }, 24 | }) 25 | .on("change", ({ value: { x, y } }) => { 26 | uniforms.uPlanetPosition = [x, y, 0]; 27 | }); 28 | geometry.addBinding(uniforms, "uPlanetRadius", { 29 | label: "Radius", 30 | min: 0.5, 31 | max: 5, 32 | }); 33 | } 34 | 35 | if (options.terrain === true) { 36 | const terrain = planetFolder.addFolder({ title: "Terrain" }); 37 | 38 | terrain.addBinding(uniforms, "uNoiseStrength", { 39 | label: "Height", 40 | min: 0, 41 | max: 0.4, 42 | }); 43 | terrain.addBinding(uniforms, "uTerrainScale", { 44 | label: "Scale", 45 | min: 0.2, 46 | max: 1.5, 47 | }); 48 | } 49 | 50 | if (options.clouds === true) { 51 | const clouds = planetFolder.addFolder({ title: "Clouds" }); 52 | 53 | clouds.addBinding(uniforms, "uCloudsDensity", { 54 | label: "Density", 55 | min: 0, 56 | max: 1, 57 | }); 58 | if (uniforms.uCloudsScale !== -1) { 59 | clouds.addBinding(uniforms, "uCloudsScale", { 60 | label: "Scale", 61 | min: 0.3, 62 | max: 1.5, 63 | }); 64 | } 65 | if (uniforms.uCloudsSpeed !== -1) { 66 | clouds.addBinding(uniforms, "uCloudsSpeed", { 67 | label: "Speed", 68 | min: 0, 69 | max: 5, 70 | }); 71 | } 72 | } 73 | 74 | const atmosphere = planetFolder.addFolder({ title: "Atmosphere" }); 75 | 76 | atmosphere 77 | .addBinding( 78 | { 79 | col: { 80 | r: uniforms.uAtmosphereColor[0], 81 | g: uniforms.uAtmosphereColor[1], 82 | b: uniforms.uAtmosphereColor[2], 83 | }, 84 | }, 85 | "col", 86 | { 87 | label: "Color", 88 | color: { type: "float" }, 89 | } 90 | ) 91 | .on("change", ({ value: { r, g, b } }) => { 92 | uniforms.uAtmosphereColor = [r, g, b]; 93 | }); 94 | atmosphere.addBinding(uniforms, "uAtmosphereDensity", { 95 | label: "Density", 96 | min: 0, 97 | max: 1, 98 | }); 99 | } 100 | -------------------------------------------------------------------------------- /src/controls/quality.controls.ts: -------------------------------------------------------------------------------- 1 | import { WebGLRenderer } from "four"; 2 | import { ListBladeApi, Pane } from "tweakpane"; 3 | import { Quality } from "../webgl/settings/quality"; 4 | import type { CustomUniforms } from "../webgl/settings/uniforms"; 5 | 6 | export function addQualityControl( 7 | pane: Pane, 8 | uniforms: CustomUniforms, 9 | renderer: WebGLRenderer, 10 | defaultValue: Quality 11 | ) { 12 | ( 13 | pane.addBlade({ 14 | view: "list", 15 | label: "quality", 16 | options: [ 17 | { text: "low", value: Quality.LOW }, 18 | { text: "medium", value: Quality.MEDIUM }, 19 | { text: "optimal", value: Quality.OPTIMAL }, 20 | ], 21 | value: defaultValue, 22 | }) as ListBladeApi 23 | ).on("change", ({ value }) => { 24 | uniforms.uQuality = value; 25 | renderer.setSize(window.innerWidth * value, window.innerHeight * value); 26 | }); 27 | } 28 | -------------------------------------------------------------------------------- /src/controls/rotation.controls.ts: -------------------------------------------------------------------------------- 1 | import type { Pane } from "tweakpane"; 2 | import type { CustomUniforms } from "../webgl/settings/uniforms"; 3 | 4 | export function addRotationControls( 5 | pane: Pane, 6 | uniforms: CustomUniforms, 7 | canvas: HTMLCanvasElement 8 | ) { 9 | const damping = { value: 0.95 }; 10 | const speedMultiplier = 4 / Math.max(window.innerWidth, window.innerHeight); // don't really know why this works, but it does 11 | 12 | let lastPointerPos = 0; 13 | let velocity = 0; 14 | let previousTime = 0; 15 | let deltaTime = 0; 16 | 17 | function updateRotationOffset(e: PointerEvent | TouchEvent) { 18 | const clientX = getClientX(e); 19 | 20 | const currentTime = Date.now(); 21 | if (currentTime === previousTime) { 22 | return; 23 | } 24 | deltaTime = currentTime - previousTime; 25 | const deltaPos = clientX - lastPointerPos; 26 | velocity = deltaPos / deltaTime; 27 | 28 | uniforms.uRotationOffset += deltaPos * speedMultiplier; 29 | 30 | lastPointerPos = clientX; 31 | previousTime = currentTime; 32 | } 33 | 34 | function applyInertia() { 35 | if (Math.abs(velocity) < 0.01) { 36 | return; 37 | } 38 | 39 | velocity *= damping.value; 40 | const deltaPos = velocity * deltaTime; 41 | 42 | uniforms.uRotationOffset += deltaPos * speedMultiplier; 43 | window.requestAnimationFrame(applyInertia); 44 | } 45 | 46 | canvas.addEventListener("pointerdown", (e: PointerEvent | TouchEvent) => { 47 | canvas.classList.add("grabbing"); 48 | lastPointerPos = getClientX(e); 49 | previousTime = Date.now(); 50 | 51 | canvas.addEventListener("pointermove", updateRotationOffset); 52 | 53 | canvas.addEventListener( 54 | "pointerup", 55 | () => { 56 | canvas.classList.remove("grabbing"); 57 | canvas.removeEventListener("pointermove", updateRotationOffset); 58 | applyInertia(); 59 | }, 60 | { once: true } 61 | ); 62 | }); 63 | 64 | const rotationFolder = pane.addFolder({ 65 | title: "Rotation", 66 | expanded: window.innerHeight > 800, 67 | }); 68 | rotationFolder.addBinding(uniforms, "uRotationSpeed", { 69 | label: "Speed", 70 | min: 0, 71 | max: 5, 72 | }); 73 | rotationFolder.addBinding(damping, "value", { 74 | label: "Damping", 75 | min: 0.8, 76 | max: 1, 77 | }); 78 | } 79 | 80 | function getClientX(e: PointerEvent | TouchEvent) { 81 | return "touches" in e ? e.touches[0].clientX : e.clientX; 82 | } 83 | -------------------------------------------------------------------------------- /src/controls/setup.ts: -------------------------------------------------------------------------------- 1 | import type { WebGLRenderer } from "four"; 2 | import type { CustomUniforms } from "../webgl/settings/uniforms"; 3 | import { addLightControls } from "./light.controls"; 4 | import { addMonitor } from "./monitor.controls"; 5 | import { addPlanetControls } from "./planet.controls"; 6 | import { addQualityControl } from "./quality.controls"; 7 | import { addRotationControls } from "./rotation.controls"; 8 | import type { Quality } from "../webgl/settings/quality"; 9 | 10 | export type ControlsOptions = { 11 | expanded?: boolean; 12 | quality?: boolean; 13 | planet?: { 14 | geometry?: boolean; 15 | terrain?: boolean; 16 | clouds?: boolean; 17 | }; 18 | }; 19 | 20 | export async function setupControls( 21 | { 22 | canvas, 23 | uniforms, 24 | renderer, 25 | defaultQuality, 26 | }: { 27 | canvas: HTMLCanvasElement; 28 | uniforms: CustomUniforms; 29 | renderer?: WebGLRenderer; 30 | defaultQuality?: Quality; 31 | }, 32 | options?: ControlsOptions 33 | ) { 34 | const { Pane } = await import("tweakpane"); 35 | 36 | const pane = new Pane({ 37 | title: "Controls", 38 | expanded: options?.expanded === true, 39 | }); 40 | 41 | if (options?.quality && renderer && defaultQuality) { 42 | addQualityControl(pane, uniforms, renderer, defaultQuality); 43 | } 44 | addRotationControls(pane, uniforms, canvas); 45 | addPlanetControls(pane, uniforms, options?.planet); 46 | addLightControls(pane, uniforms); 47 | addMonitor(pane); 48 | } 49 | -------------------------------------------------------------------------------- /src/env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | declare module "*.glsl" { 4 | const shaderSource: string; 5 | export default shaderSource; 6 | } 7 | -------------------------------------------------------------------------------- /src/layouts/Layout.astro: -------------------------------------------------------------------------------- 1 | --- 2 | import MainTitle from "../components/MainTitle.astro"; 3 | 4 | const { title, description } = Astro.props; 5 | 6 | const slug = Astro.url.pathname.replace(/\/$/, "").split("/").at(-1); 7 | const fullTitle = `${title} | Interactive 3D planet animation`; 8 | const baseUrl = "https://jsulpis.github.io/realtime-planet-shader"; 9 | --- 10 | 11 | 12 | 13 | 14 | 15 | 20 | 21 | {fullTitle} 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 40 | 41 | 42 | {title} 43 | 44 | 45 | 46 | 47 | 105 | -------------------------------------------------------------------------------- /src/pages/earth.astro: -------------------------------------------------------------------------------- 1 | --- 2 | import Author from "../components/Author.astro"; 3 | import Canvas from "../components/Canvas.astro"; 4 | import Footer from "../components/Footer.astro"; 5 | import MainNavigation from "../components/MainNavigation.astro"; 6 | import Meta from "../components/Meta.astro"; 7 | import Layout from "../layouts/Layout.astro"; 8 | import TextureCredits from "../components/TextureCredits.astro"; 9 | --- 10 | 11 | 61 | 62 | 63 | 64 | 77 | 78 | -------------------------------------------------------------------------------- /src/pages/jupiter.astro: -------------------------------------------------------------------------------- 1 | --- 2 | import Author from "../components/Author.astro"; 3 | import Canvas from "../components/Canvas.astro"; 4 | import Footer from "../components/Footer.astro"; 5 | import MainNavigation from "../components/MainNavigation.astro"; 6 | import Meta from "../components/Meta.astro"; 7 | import TextureCredits from "../components/TextureCredits.astro"; 8 | import Layout from "../layouts/Layout.astro"; 9 | --- 10 | 11 | 41 | 42 | 43 | 44 | 56 | 57 | -------------------------------------------------------------------------------- /src/pages/mars.astro: -------------------------------------------------------------------------------- 1 | --- 2 | import Author from "../components/Author.astro"; 3 | import Canvas from "../components/Canvas.astro"; 4 | import Footer from "../components/Footer.astro"; 5 | import MainNavigation from "../components/MainNavigation.astro"; 6 | import Meta from "../components/Meta.astro"; 7 | import TextureCredits from "../components/TextureCredits.astro"; 8 | import Layout from "../layouts/Layout.astro"; 9 | --- 10 | 11 | 40 | 41 | 42 | 43 | 55 | 56 | -------------------------------------------------------------------------------- /src/pages/mercury.astro: -------------------------------------------------------------------------------- 1 | --- 2 | import Author from "../components/Author.astro"; 3 | import Canvas from "../components/Canvas.astro"; 4 | import Footer from "../components/Footer.astro"; 5 | import MainNavigation from "../components/MainNavigation.astro"; 6 | import Meta from "../components/Meta.astro"; 7 | import TextureCredits from "../components/TextureCredits.astro"; 8 | import Layout from "../layouts/Layout.astro"; 9 | --- 10 | 11 | 39 | 40 | 41 | 42 | 54 | 55 | -------------------------------------------------------------------------------- /src/pages/moon.astro: -------------------------------------------------------------------------------- 1 | --- 2 | import Author from "../components/Author.astro"; 3 | import Canvas from "../components/Canvas.astro"; 4 | import Footer from "../components/Footer.astro"; 5 | import MainNavigation from "../components/MainNavigation.astro"; 6 | import Meta from "../components/Meta.astro"; 7 | import TextureCredits from "../components/TextureCredits.astro"; 8 | import Layout from "../layouts/Layout.astro"; 9 | --- 10 | 11 | 39 | 40 | 41 | 42 | 54 | 55 | -------------------------------------------------------------------------------- /src/pages/procedural.astro: -------------------------------------------------------------------------------- 1 | --- 2 | import Author from "../components/Author.astro"; 3 | import Canvas from "../components/Canvas.astro"; 4 | import Footer from "../components/Footer.astro"; 5 | import MainNavigation from "../components/MainNavigation.astro"; 6 | import Meta from "../components/Meta.astro"; 7 | import Layout from "../layouts/Layout.astro"; 8 | --- 9 | 10 | 48 | 49 | 53 | 54 |
55 | 56 | 57 | 58 | 59 |
60 |
61 | 62 | 69 | -------------------------------------------------------------------------------- /src/pages/venus.astro: -------------------------------------------------------------------------------- 1 | --- 2 | import Author from "../components/Author.astro"; 3 | import Canvas from "../components/Canvas.astro"; 4 | import Footer from "../components/Footer.astro"; 5 | import MainNavigation from "../components/MainNavigation.astro"; 6 | import Meta from "../components/Meta.astro"; 7 | import TextureCredits from "../components/TextureCredits.astro"; 8 | import Layout from "../layouts/Layout.astro"; 9 | --- 10 | 11 | 40 | 41 | 42 | 43 | 55 | 56 | -------------------------------------------------------------------------------- /src/webgl/loaders/noise.loader.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * load a 3D texture file borrowed from Shadertoy 3 | */ 4 | export async function load3DNoiseTexture() { 5 | const gl = document.querySelector("canvas")?.getContext("webgl2"); 6 | if (!gl) return; 7 | 8 | const response = await fetch("/realtime-planet-shader/3DNoise.bin"); 9 | const binaryData = await response.arrayBuffer(); 10 | const volumeTexture = gl.createTexture(); 11 | gl.bindTexture(gl.TEXTURE_3D, volumeTexture); 12 | gl.texImage3D( 13 | gl.TEXTURE_3D, 14 | 0, 15 | gl.R8, 16 | 32, 17 | 32, 18 | 32, 19 | 0, 20 | gl.RED, 21 | gl.UNSIGNED_BYTE, 22 | new Uint8Array(binaryData) 23 | ); 24 | gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); 25 | gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); 26 | } 27 | -------------------------------------------------------------------------------- /src/webgl/loaders/texture.loader.ts: -------------------------------------------------------------------------------- 1 | import { type SamplerOptions, Texture, Sampler } from "four"; 2 | import type { TextureData } from "./texture.types"; 3 | 4 | export async function loadTexture( 5 | url: string, 6 | width: number, 7 | height: number, 8 | samplerOptions?: Partial 9 | ) { 10 | const imageData = await fetch(url); 11 | const imageBlob = await imageData.blob(); 12 | const bitmap = await createImageBitmap(imageBlob, 0, 0, width, height, { 13 | imageOrientation: "flipY", 14 | }); 15 | 16 | return new Texture( 17 | bitmap, 18 | new Sampler({ 19 | wrapS: "repeat", 20 | wrapT: "repeat", 21 | ...samplerOptions, 22 | }) 23 | ); 24 | } 25 | 26 | export async function loadTextures(texturesData: TextureData[]) { 27 | return Promise.all( 28 | texturesData.map(({ path, width = 2048, height = 1024, options }) => 29 | loadTexture(`/realtime-planet-shader/${path}`, width, height, options) 30 | ) 31 | ); 32 | } 33 | -------------------------------------------------------------------------------- /src/webgl/loaders/texture.types.ts: -------------------------------------------------------------------------------- 1 | import type { SamplerOptions } from "four"; 2 | 3 | export type TextureData = { 4 | path: string; 5 | width?: number; 6 | height?: number; 7 | options?: Partial; 8 | }; 9 | -------------------------------------------------------------------------------- /src/webgl/renderer.ts: -------------------------------------------------------------------------------- 1 | import { 2 | WebGLRenderer, 3 | PerspectiveCamera, 4 | Material, 5 | Geometry, 6 | Mesh, 7 | } from "four"; 8 | import type { CustomUniforms } from "./settings/uniforms"; 9 | 10 | function flatten(array: T[][]): T[] { 11 | return array.reduce((acc, val) => acc.concat(val), []); 12 | } 13 | 14 | type MaterialOptions = ConstructorParameters[0]; 15 | type Args = MaterialOptions & { canvas?: HTMLCanvasElement }; 16 | 17 | export function useGlslCanvas({ canvas: canvasArg, ...materialOptions }: Args) { 18 | let canvas = canvasArg ?? document.querySelector("canvas")!; 19 | 20 | const renderer = new WebGLRenderer({ canvas }); 21 | renderer.setSize( 22 | window.innerWidth * (materialOptions?.uniforms?.uQuality as number), 23 | window.innerHeight * (materialOptions?.uniforms?.uQuality as number) 24 | ); 25 | 26 | const camera = new PerspectiveCamera(); 27 | 28 | const material = new Material(materialOptions); 29 | 30 | const geometry = new Geometry({ 31 | position: { 32 | size: 3, 33 | data: new Float32Array( 34 | flatten([ 35 | [0, 0, 0], 36 | [1, 0, 0], 37 | [0, 1, 0], 38 | [0, 1, 0], 39 | [1, 0, 0], 40 | [1, 1, 0], 41 | ]) 42 | ), 43 | }, 44 | }); 45 | 46 | const mesh = new Mesh(geometry, material); 47 | 48 | const rafCallbacks: Function[] = []; 49 | 50 | /** 51 | * Usage: 52 | * ```javascript 53 | * raf(() => { 54 | * // do something at each frame 55 | * }) 56 | * ``` 57 | * @param callback function to execute at each frame 58 | */ 59 | function raf(callback: Function) { 60 | rafCallbacks.push(callback); 61 | } 62 | 63 | const uniforms = mesh.material.uniforms; 64 | 65 | requestAnimationFrame(function animate() { 66 | requestAnimationFrame(animate); 67 | 68 | rafCallbacks.forEach((callback) => callback()); 69 | 70 | (uniforms.uTime as number) += (uniforms.uRotationSpeed as number) * 0.01; 71 | 72 | renderer.render(mesh, camera); 73 | }); 74 | 75 | window.addEventListener("resize", () => { 76 | const quality = mesh.material.uniforms.uQuality as number; 77 | renderer.setSize( 78 | window.innerWidth * quality, 79 | window.innerHeight * quality 80 | ); 81 | mesh.material.uniforms.uResolution = [ 82 | window.innerWidth, 83 | window.innerHeight, 84 | ]; 85 | }); 86 | 87 | canvas.classList.add("loaded"); 88 | 89 | return { 90 | renderer, 91 | raf, 92 | uniforms: mesh.material.uniforms as CustomUniforms, 93 | canvas, 94 | }; 95 | } 96 | -------------------------------------------------------------------------------- /src/webgl/settings/device.ts: -------------------------------------------------------------------------------- 1 | export const isPhone = window.innerWidth < 700; 2 | -------------------------------------------------------------------------------- /src/webgl/settings/quality.ts: -------------------------------------------------------------------------------- 1 | export enum Quality { 2 | LOW = 0.5, 3 | MEDIUM = 1, 4 | OPTIMAL = 2, 5 | } 6 | -------------------------------------------------------------------------------- /src/webgl/settings/uniforms.ts: -------------------------------------------------------------------------------- 1 | export const defaultUniforms = { 2 | uTime: 0, 3 | uQuality: Math.min(window.devicePixelRatio, 2), 4 | uRotationSpeed: 1, 5 | uResolution: [window.innerWidth, window.innerHeight], 6 | uPlanetPosition: [0, 0, -10], 7 | uRotationOffset: 0.6, 8 | uPlanetRadius: 2, 9 | uBumpStrength: 0.01, 10 | uNoiseStrength: 0.2, 11 | uTerrainScale: 0.8, 12 | uCloudsDensity: 0.5, 13 | uCloudsScale: 1, 14 | uCloudsSpeed: 1.5, 15 | uAtmosphereColor: [0.05, 0.3, 0.9], 16 | uAtmosphereDensity: 0.3, 17 | uAmbientLight: 0.01, 18 | uSunIntensity: 3, 19 | sunDirectionXY: [1, 1], 20 | }; 21 | 22 | export type CustomUniforms = typeof defaultUniforms; 23 | -------------------------------------------------------------------------------- /src/webgl/shaders/earth.fragment.glsl: -------------------------------------------------------------------------------- 1 | //=======================================================================================// 2 | // 3 | // Earth Shader 4 | // by Julien Sulpis (https://twitter.com/jsulpis) 5 | // 6 | //=======================================================================================// 7 | 8 | #version 300 es 9 | 10 | precision highp float; 11 | precision mediump int; 12 | precision mediump sampler3D; 13 | precision mediump sampler2D; 14 | 15 | in vec2 uv; 16 | out vec4 fragColor; 17 | 18 | //===================// 19 | // Global uniforms // 20 | //===================// 21 | 22 | uniform float uTime; 23 | uniform float uRotationOffset; 24 | uniform vec2 uResolution; 25 | uniform sampler2D uEarthColor; 26 | uniform sampler2D uEarthClouds; 27 | uniform sampler2D uEarthSpecular; 28 | uniform sampler2D uEarthBump; 29 | uniform sampler2D uEarthNight; 30 | uniform sampler2D uStars; 31 | 32 | //==========================// 33 | // Controllable uniforms // 34 | //==========================// 35 | 36 | uniform vec3 uPlanetPosition; 37 | uniform float uPlanetRadius; 38 | uniform float uCloudsDensity; 39 | uniform vec3 uAtmosphereColor; 40 | uniform float uAtmosphereDensity; 41 | uniform float uSunIntensity; 42 | uniform float uAmbientLight; 43 | in vec3 uSunDirection; 44 | 45 | //==========================================================// 46 | // Constants (could be turned into controllable uniforms) // 47 | //==========================================================// 48 | 49 | // Planet geometry 50 | #define ROTATION_SPEED .1 51 | #define PLANET_ROTATION rotateY(uTime * ROTATION_SPEED + uRotationOffset) 52 | 53 | // Planet colors 54 | #define CLOUD_COLOR vec3(1., 1., 1.) 55 | 56 | // Lighting 57 | #define SUN_COLOR vec3(1.0, 1.0, 0.9) 58 | #define DEEP_SPACE vec3(0., 0., 0.0005) 59 | 60 | // Ray tracing 61 | #define INFINITY 1e10 62 | #define CAMERA_POSITION vec3(0., 0., 6.0) 63 | #define FOCAL_LENGTH CAMERA_POSITION.z / (CAMERA_POSITION.z - uPlanetPosition.z) 64 | 65 | #define PI acos(-1.) 66 | 67 | //=========// 68 | // Types // 69 | //=========// 70 | 71 | struct Material { 72 | vec3 color; 73 | float diffuse; 74 | float specular; 75 | vec3 emission; 76 | }; 77 | 78 | struct Hit { 79 | float len; 80 | vec3 normal; 81 | Material material; 82 | }; 83 | 84 | struct Sphere { 85 | vec3 position; 86 | float radius; 87 | }; 88 | 89 | // Note: I had created a struct for Ray but then deleted it because it caused artifacts on some mobile devices 90 | // because of a precision issue with struct (https://github.com/KhronosGroup/WebGL/issues/3351) 91 | // I use ro and rd instead in this shader. 92 | 93 | Hit miss = Hit(INFINITY, vec3(0.), Material(vec3(0.), -1., -1., vec3(-1.))); 94 | 95 | Sphere getPlanet() { 96 | return Sphere(uPlanetPosition, uPlanetRadius); 97 | } 98 | 99 | //===============================================// 100 | // Generic utilities stolen from smarter people // 101 | //===============================================// 102 | 103 | float inverseLerp(float v, float minValue, float maxValue) { 104 | return (v - minValue) / (maxValue - minValue); 105 | } 106 | 107 | float remap(float v, float inMin, float inMax, float outMin, float outMax) { 108 | float t = inverseLerp(v, inMin, inMax); 109 | return mix(outMin, outMax, t); 110 | } 111 | 112 | vec2 sphereProjection(vec3 p, vec3 origin) { 113 | vec3 dir = normalize(p - origin); 114 | float longitude = atan(dir.x, dir.z); // [-PI, PI] 115 | float latitude = asin(dir.y); // [-PI/2, PI/2] 116 | 117 | return vec2( 118 | (longitude + PI) / (2. * PI), // [0, 1] 119 | (latitude + PI / 2.) / PI // [0, 1] 120 | ); 121 | } 122 | 123 | // https://iquilezles.org/articles/intersectors/ 124 | float sphIntersect(in vec3 ro, in vec3 rd, in Sphere sphere) { 125 | vec3 oc = ro - sphere.position; 126 | float b = dot(oc, rd); 127 | float c = dot(oc, oc) - sphere.radius * sphere.radius; 128 | float h = b * b - c; 129 | if(h < 0.0) 130 | return -1.; // no intersection 131 | return -b - sqrt(h); 132 | } 133 | 134 | mat3 rotateY(float angle) { 135 | float c = cos(angle); 136 | float s = sin(angle); 137 | return mat3(// 138 | vec3(c, 0, s),// 139 | vec3(0, 1, 0),// 140 | vec3(-s, 0, c)// 141 | ); 142 | } 143 | 144 | // Zavie - https://www.shadertoy.com/view/lslGzl 145 | vec3 simpleReinhardToneMapping(vec3 color) { 146 | float exposure = 1.5; 147 | color *= exposure / (1. + color / exposure); 148 | color = pow(color, vec3(1. / 2.4)); 149 | return color; 150 | } 151 | 152 | //========// 153 | // Misc // 154 | //========// 155 | 156 | float planetNoise(vec3 p) { 157 | vec2 textureCoord = sphereProjection(p, uPlanetPosition); 158 | float bump = texture(uEarthBump, textureCoord).r; 159 | float cloudsDensity = texture(uEarthClouds, textureCoord).r; 160 | 161 | return .01 * mix(bump, max(bump, smoothstep(-.5, 2., cloudsDensity)), uCloudsDensity); 162 | ; 163 | } 164 | 165 | float planetDist(in vec3 ro, in vec3 rd) { 166 | float smoothSphereDist = sphIntersect(ro, rd, getPlanet()); 167 | 168 | vec3 intersection = ro + smoothSphereDist * rd; 169 | vec3 intersectionWithRotation = PLANET_ROTATION * (intersection - uPlanetPosition) + uPlanetPosition; 170 | 171 | return sphIntersect(ro, rd, Sphere(uPlanetPosition, uPlanetRadius + planetNoise(intersectionWithRotation))); 172 | } 173 | 174 | vec3 planetNormal(vec3 p) { 175 | vec3 rd = uPlanetPosition - p; 176 | float dist = planetDist(p, rd); 177 | // if e is too small it causes artifacts on mobile, so I interpolate 178 | // between .01 (large screens) and .03 (small screens) 179 | vec2 e = vec2(max(.01, .03 * smoothstep(1300., 300., uResolution.x)), 0); 180 | 181 | vec3 normal = dist - vec3(planetDist(p - e.xyy, rd), planetDist(p - e.yxy, rd), planetDist(p + e.yyx, rd)); 182 | return normalize(normal); 183 | } 184 | 185 | vec3 spaceColor(vec3 direction) { 186 | vec3 backgroundCoord = direction * rotateY(uTime * ROTATION_SPEED / 3. + 1.5); 187 | 188 | vec2 textureCoord = sphereProjection(backgroundCoord, vec3(0.)); 189 | textureCoord.x = 1. - textureCoord.x; // flip X because we are inside the texture 190 | vec3 stars = texture(uStars, textureCoord).rgb; 191 | 192 | return DEEP_SPACE + stars * stars * stars * .5; 193 | } 194 | 195 | vec3 atmosphereColor(vec3 ro, vec3 rd, float spaceMask) { 196 | float distCameraToPlanetOrigin = length(uPlanetPosition - CAMERA_POSITION); 197 | float distCameraToPlanetEdge = sqrt(distCameraToPlanetOrigin * distCameraToPlanetOrigin - uPlanetRadius * uPlanetRadius); 198 | 199 | float planetMask = 1.0 - spaceMask; 200 | 201 | vec3 coordFromCenter = (ro + rd * distCameraToPlanetEdge) - uPlanetPosition; 202 | float distFromEdge = abs(length(coordFromCenter) - uPlanetRadius); 203 | float planetEdge = max(uPlanetRadius - distFromEdge, 0.) / uPlanetRadius; 204 | float atmosphereMask = pow(remap(dot(uSunDirection, coordFromCenter), -uPlanetRadius, uPlanetRadius / 2., 0., 1.), 5.); 205 | atmosphereMask *= uAtmosphereDensity * uPlanetRadius * uSunIntensity; 206 | 207 | vec3 atmosphere = vec3(pow(planetEdge, 120.)) * .5; 208 | atmosphere += pow(planetEdge, 50.) * .3 * (1.5 - planetMask); 209 | atmosphere += pow(planetEdge, 15.) * .015; 210 | atmosphere += pow(planetEdge, 5.) * .04 * planetMask; 211 | 212 | return atmosphere * uAtmosphereColor * atmosphereMask; 213 | } 214 | 215 | //===============// 216 | // Ray Tracing // 217 | //===============// 218 | 219 | Hit intersectPlanet(vec3 ro, vec3 rd) { 220 | float len = sphIntersect(ro, rd, getPlanet()); 221 | 222 | if(len < 0.) { 223 | return miss; 224 | } 225 | 226 | vec3 position = ro + len * rd; 227 | vec3 rotatedPosition = PLANET_ROTATION * (position - uPlanetPosition) + uPlanetPosition; 228 | 229 | vec2 textureCoord = sphereProjection(rotatedPosition, uPlanetPosition); 230 | vec3 color = texture(uEarthColor, textureCoord).rgb; 231 | 232 | vec3 normal = planetNormal(position); 233 | float specular = texture(uEarthSpecular, textureCoord).r; 234 | 235 | float nightLightIntensity = clamp(dot(-normal, uSunDirection) + .1, smoothstep(1., 0., pow((uSunIntensity + uAmbientLight), .3)), 1.); 236 | vec3 nightColor = pow(texture(uEarthNight, textureCoord).r, 3.) * vec3(1., .8, .6); 237 | nightColor *= nightLightIntensity; 238 | 239 | float cloudsDensity = texture(uEarthClouds, textureCoord).r; 240 | float cloudsThreshold = 1. - uCloudsDensity; 241 | float smoothness = uCloudsDensity * (1. - uCloudsDensity); 242 | cloudsDensity *= smoothstep(cloudsThreshold - smoothness, cloudsThreshold, cloudsDensity); 243 | color = mix(color, CLOUD_COLOR, cloudsDensity); 244 | 245 | return Hit(len, normal, Material(color, 1., specular, nightColor)); 246 | } 247 | 248 | Hit intersectScene(vec3 ro, vec3 rd) { 249 | return intersectPlanet(ro, rd); 250 | } 251 | 252 | vec3 radiance(vec3 ro, vec3 rd) { 253 | vec3 color = vec3(0.); 254 | float spaceMask = 1.; 255 | Hit hit = intersectScene(ro, rd); 256 | 257 | if(hit.len < INFINITY) { 258 | spaceMask = 0.; 259 | 260 | // Diffuse 261 | float directLightIntensity = pow(clamp(dot(hit.normal, uSunDirection), 0.0, 1.0), 2.) * uSunIntensity; // the power softens the shadow. Not physically accurate but it looks better to me 262 | vec3 diffuseLight = directLightIntensity * SUN_COLOR; 263 | vec3 diffuseColor = hit.material.color.rgb * (uAmbientLight + diffuseLight); 264 | 265 | // Phong specular 266 | vec3 reflected = normalize(reflect(-uSunDirection, hit.normal)); 267 | vec3 phongRd = normalize(vec3(uv * pow(FOCAL_LENGTH, -1.), -1.)); // I want the reflection to stay on the edge of the planet 268 | float phongValue = pow(max(0.0, dot(phongRd, reflected)), 8.) * .2 * uSunIntensity; 269 | vec3 specularColor = hit.material.specular * vec3(phongValue); 270 | 271 | color = diffuseColor + specularColor + hit.material.emission; 272 | } else { 273 | float zoomFactor = min(uResolution.x / uResolution.y, 1.); // zoom for portrait mode because the background image is cropped to optimize file size 274 | vec3 backgroundRd = normalize(vec3(uv * zoomFactor, -1.)); // background not affected by focal length 275 | color = spaceColor(backgroundRd); 276 | } 277 | 278 | return color + atmosphereColor(ro, rd, spaceMask); 279 | } 280 | 281 | //========// 282 | // Main // 283 | //========// 284 | 285 | void main() { 286 | vec3 ro = vec3(CAMERA_POSITION); 287 | vec3 rd = normalize(vec3(uv * FOCAL_LENGTH, -1.)); 288 | 289 | vec3 color = radiance(ro, rd); 290 | 291 | // color grading 292 | color = simpleReinhardToneMapping(color); 293 | 294 | // vignette 295 | color *= 1. - 0.5 * pow(length(uv), 3.); 296 | 297 | fragColor = vec4(color, 1.0); 298 | } -------------------------------------------------------------------------------- /src/webgl/shaders/planet.fragment.glsl: -------------------------------------------------------------------------------- 1 | //=======================================================================================// 2 | // 3 | // Planet Shader 4 | // by Julien Sulpis (https://twitter.com/jsulpis) 5 | // 6 | //=======================================================================================// 7 | 8 | #version 300 es 9 | 10 | precision highp float; 11 | precision mediump int; 12 | precision mediump sampler2D; 13 | 14 | in vec2 uv; 15 | out vec4 fragColor; 16 | 17 | //===================// 18 | // Global uniforms // 19 | //===================// 20 | 21 | uniform float uTime; 22 | uniform vec2 uResolution; 23 | uniform vec3 uPlanetPosition; 24 | uniform float uPlanetRadius; 25 | uniform float uRotationOffset; 26 | uniform float uBumpStrength; 27 | uniform sampler2D uPlanetColor; 28 | uniform sampler2D uStars; 29 | 30 | //==========================// 31 | // Controllable uniforms // 32 | //==========================// 33 | 34 | uniform vec3 uAtmosphereColor; 35 | uniform float uAtmosphereDensity; 36 | uniform float uSunIntensity; 37 | uniform float uAmbientLight; 38 | in vec3 uSunDirection; 39 | 40 | //==========================================================// 41 | // Constants (could be turned into controllable uniforms) // 42 | //==========================================================// 43 | 44 | // Planet geometry 45 | #define ROTATION_SPEED .1 46 | #define PLANET_ROTATION rotateY(uTime * ROTATION_SPEED + uRotationOffset) 47 | 48 | // Lighting 49 | #define SUN_COLOR vec3(1.0, 1.0, 1.0) 50 | #define DEEP_SPACE vec3(0., 0., 0.0005) 51 | 52 | // Ray tracing 53 | #define INFINITY 1e10 54 | #define CAMERA_POSITION vec3(0., 0., 6.0) 55 | #define FOCAL_LENGTH CAMERA_POSITION.z / (CAMERA_POSITION.z - uPlanetPosition.z) 56 | 57 | #define PI acos(-1.) 58 | 59 | //=========// 60 | // Types // 61 | //=========// 62 | 63 | struct Material { 64 | vec3 color; 65 | float diffuse; 66 | float specular; 67 | vec3 emission; 68 | }; 69 | 70 | struct Hit { 71 | float len; 72 | vec3 normal; 73 | Material material; 74 | }; 75 | 76 | struct Sphere { 77 | vec3 position; 78 | float radius; 79 | }; 80 | 81 | // Note: I had created a struct for Ray but then deleted it because it caused artifacts on some mobile devices 82 | // because of a precision issue with struct (https://github.com/KhronosGroup/WebGL/issues/3351) 83 | // I use ro and rd instead in this shader. 84 | 85 | Hit miss = Hit(INFINITY, vec3(0.), Material(vec3(0.), -1., -1., vec3(-1.))); 86 | 87 | Sphere getPlanet() { 88 | return Sphere(uPlanetPosition, uPlanetRadius); 89 | } 90 | 91 | //===============================================// 92 | // Generic utilities stolen from smarter people // 93 | //===============================================// 94 | 95 | float inverseLerp(float v, float minValue, float maxValue) { 96 | return (v - minValue) / (maxValue - minValue); 97 | } 98 | 99 | float remap(float v, float inMin, float inMax, float outMin, float outMax) { 100 | float t = inverseLerp(v, inMin, inMax); 101 | return mix(outMin, outMax, t); 102 | } 103 | 104 | vec2 sphereProjection(vec3 p, vec3 origin) { 105 | vec3 dir = normalize(p - origin); 106 | float longitude = atan(dir.x, dir.z); // [-PI, PI] 107 | float latitude = asin(dir.y); // [-PI/2, PI/2] 108 | 109 | return vec2( 110 | (longitude + PI) / (2. * PI), // [0, 1] 111 | (latitude + PI / 2.) / PI // [0, 1] 112 | ); 113 | } 114 | 115 | // https://iquilezles.org/articles/intersectors/ 116 | float sphIntersect(in vec3 ro, in vec3 rd, in Sphere sphere) { 117 | vec3 oc = ro - sphere.position; 118 | float b = dot(oc, rd); 119 | float c = dot(oc, oc) - sphere.radius * sphere.radius; 120 | float h = b * b - c; 121 | if(h < 0.0) 122 | return -1.; // no intersection 123 | return -b - sqrt(h); 124 | } 125 | 126 | mat3 rotateY(float angle) { 127 | float c = cos(angle); 128 | float s = sin(angle); 129 | return mat3(// 130 | vec3(c, 0, s),// 131 | vec3(0, 1, 0),// 132 | vec3(-s, 0, c)// 133 | ); 134 | } 135 | 136 | // Zavie - https://www.shadertoy.com/view/lslGzl 137 | vec3 simpleReinhardToneMapping(vec3 color) { 138 | float exposure = 1.5; 139 | color *= exposure / (1. + color / exposure); 140 | color = pow(color, vec3(1. / 2.4)); 141 | return color; 142 | } 143 | 144 | // https://www.shadertoy.com/view/MtX3z2 145 | float Sigmoid (float x) { 146 | return 1.0 / (1.0 + (exp(-(x - 0.7) * 6.5))); 147 | } 148 | 149 | vec3 Scurve (vec3 color) { 150 | return vec3(Sigmoid(color.x), Sigmoid(color.y), Sigmoid(color.z)); 151 | } 152 | 153 | //========// 154 | // Misc // 155 | //========// 156 | 157 | float planetNoise(vec3 p) { 158 | vec2 textureCoord = sphereProjection(p, uPlanetPosition); 159 | float bump = length(texture(uPlanetColor, textureCoord)); 160 | 161 | return uBumpStrength * bump; 162 | } 163 | 164 | float planetDist(in vec3 ro, in vec3 rd) { 165 | float smoothSphereDist = sphIntersect(ro, rd, getPlanet()); 166 | 167 | vec3 intersection = ro + smoothSphereDist * rd; 168 | vec3 intersectionWithRotation = PLANET_ROTATION * (intersection - uPlanetPosition) + uPlanetPosition; 169 | 170 | return sphIntersect(ro, rd, Sphere(uPlanetPosition, uPlanetRadius + planetNoise(intersectionWithRotation))); 171 | } 172 | 173 | vec3 planetNormal(vec3 p) { 174 | vec3 rd = uPlanetPosition - p; 175 | float dist = planetDist(p, rd); 176 | // if e is too small it causes artifacts on mobile, so I interpolate 177 | // between .01 (large screens) and .03 (small screens) 178 | vec2 e = vec2(max(.01, .03 * smoothstep(1300., 300., uResolution.x)), 0); 179 | 180 | vec3 normal = dist - vec3(planetDist(p - e.xyy, rd), planetDist(p - e.yxy, rd), planetDist(p + e.yyx, rd)); 181 | return normalize(normal); 182 | } 183 | 184 | vec3 spaceColor(vec3 direction) { 185 | vec3 backgroundCoord = direction * rotateY(uTime * ROTATION_SPEED / 3. + 1.5); 186 | 187 | vec2 textureCoord = sphereProjection(backgroundCoord, vec3(0.)); 188 | textureCoord.x = 1. - textureCoord.x; // flip X because we are inside the texture 189 | vec3 stars = texture(uStars, textureCoord).rgb; 190 | 191 | return DEEP_SPACE + stars * stars * stars * .5; 192 | } 193 | 194 | vec3 atmosphereColor(vec3 ro, vec3 rd, float spaceMask) { 195 | float distCameraToPlanetOrigin = length(uPlanetPosition - CAMERA_POSITION); 196 | float distCameraToPlanetEdge = sqrt(distCameraToPlanetOrigin * distCameraToPlanetOrigin - uPlanetRadius * uPlanetRadius); 197 | 198 | float planetMask = 1.0 - spaceMask; 199 | 200 | vec3 coordFromCenter = (ro + rd * distCameraToPlanetEdge) - uPlanetPosition; 201 | float distFromEdge = abs(length(coordFromCenter) - uPlanetRadius); 202 | float planetEdge = max(uPlanetRadius - distFromEdge, 0.) / uPlanetRadius; 203 | float atmosphereMask = pow(remap(dot(uSunDirection, coordFromCenter), -uPlanetRadius, uPlanetRadius / 2., 0., 1.), 5.); 204 | atmosphereMask *= uAtmosphereDensity * uPlanetRadius * uSunIntensity; 205 | 206 | vec3 atmosphere = vec3(pow(planetEdge, 120.)) * .5; 207 | atmosphere += pow(planetEdge, 50.) * .3 * (1.5 - planetMask); 208 | atmosphere += pow(planetEdge, 15.) * .015; 209 | atmosphere += pow(planetEdge, 5.) * .04 * planetMask; 210 | 211 | return atmosphere * uAtmosphereColor * atmosphereMask; 212 | } 213 | 214 | //===============// 215 | // Ray Tracing // 216 | //===============// 217 | 218 | Hit intersectPlanet(vec3 ro, vec3 rd) { 219 | float len = sphIntersect(ro, rd, getPlanet()); 220 | 221 | if(len < 0.) { 222 | return miss; 223 | } 224 | 225 | vec3 position = ro + len * rd; 226 | vec3 rotatedPosition = PLANET_ROTATION * (position - uPlanetPosition) + uPlanetPosition; 227 | 228 | vec2 textureCoord = sphereProjection(rotatedPosition, uPlanetPosition); 229 | vec3 color = texture(uPlanetColor, textureCoord).rgb; 230 | color = Scurve(color); 231 | 232 | vec3 normal = planetNormal(position); 233 | 234 | return Hit(len, normal, Material(color, 1., 0., vec3(0.))); 235 | } 236 | 237 | Hit intersectScene(vec3 ro, vec3 rd) { 238 | return intersectPlanet(ro, rd); 239 | } 240 | 241 | vec3 radiance(vec3 ro, vec3 rd) { 242 | vec3 color = vec3(0.); 243 | float spaceMask = 1.; 244 | Hit hit = intersectScene(ro, rd); 245 | 246 | if(hit.len < INFINITY) { 247 | spaceMask = 0.; 248 | 249 | // Diffuse 250 | float directLightIntensity = pow(clamp(dot(hit.normal, uSunDirection), 0.0, 1.0), 2.) * uSunIntensity; // the power softens the shadow. Not physically accurate but it looks better to me 251 | vec3 diffuseLight = directLightIntensity * SUN_COLOR; 252 | vec3 diffuseColor = hit.material.color.rgb * (uAmbientLight + diffuseLight); 253 | 254 | // Phong specular 255 | vec3 reflected = normalize(reflect(-uSunDirection, hit.normal)); 256 | float phongValue = pow(max(0.0, dot(rd, reflected)), 10.) * .2 * uSunIntensity; 257 | vec3 specularColor = hit.material.specular * vec3(phongValue); 258 | 259 | color = diffuseColor + specularColor + hit.material.emission; 260 | } else { 261 | float zoomFactor = min(uResolution.x / uResolution.y, 1.); // zoom for portrait mode because the background image is cropped to optimize file size 262 | vec3 backgroundRd = normalize(vec3(uv * zoomFactor, -1.)); // background not affected by focal length 263 | color = spaceColor(backgroundRd); 264 | } 265 | 266 | return color + atmosphereColor(ro, rd, spaceMask); 267 | } 268 | 269 | //========// 270 | // Main // 271 | //========// 272 | 273 | void main() { 274 | vec3 ro = vec3(CAMERA_POSITION); 275 | vec3 rd = normalize(vec3(uv * FOCAL_LENGTH, -1.)); 276 | 277 | vec3 color = radiance(ro, rd); 278 | 279 | // color grading 280 | color = simpleReinhardToneMapping(color); 281 | 282 | // vignette 283 | color *= 1. - 0.5 * pow(length(uv), 3.); 284 | 285 | fragColor = vec4(color, 1.0); 286 | } -------------------------------------------------------------------------------- /src/webgl/shaders/procedural.fragment.glsl: -------------------------------------------------------------------------------- 1 | //=======================================================================================// 2 | // 3 | // Procedural Blue Planet 4 | // by Julien Sulpis (https://twitter.com/jsulpis) 5 | // https://www.shadertoy.com/view/Ds3XRl 6 | // 7 | //=======================================================================================// 8 | 9 | 10 | #version 300 es 11 | 12 | precision highp float; 13 | precision mediump int; 14 | precision mediump sampler3D; 15 | 16 | in vec2 uv; 17 | out vec4 fragColor; 18 | 19 | //===================// 20 | // Global uniforms // 21 | //===================// 22 | 23 | uniform float uTime; 24 | uniform float uRotationOffset; 25 | uniform vec2 uResolution; 26 | uniform sampler3D uNoiseTexture; 27 | 28 | //==========================// 29 | // Controllable uniforms // 30 | //==========================// 31 | 32 | uniform float uQuality; 33 | uniform vec3 uPlanetPosition; 34 | uniform float uPlanetRadius; 35 | uniform float uNoiseStrength; 36 | uniform float uCloudsDensity; 37 | uniform float uCloudsScale; 38 | uniform float uCloudsSpeed; 39 | uniform float uTerrainScale; 40 | uniform vec3 uAtmosphereColor; 41 | uniform float uAtmosphereDensity; 42 | uniform float uSunIntensity; 43 | uniform float uAmbientLight; 44 | in vec3 uSunDirection; 45 | 46 | //==========================================================// 47 | // Constants (could be turned into controllable uniforms) // 48 | //==========================================================// 49 | 50 | // Planets geometry 51 | #define ROTATION_SPEED .1 52 | #define PLANET_ROTATION rotateY(uTime * ROTATION_SPEED + uRotationOffset) 53 | 54 | #define MOON_RADIUS .08 55 | #define MOON_ROTATION_SPEED - ROTATION_SPEED * 5. 56 | #define MOON_OFFSET vec3(uPlanetRadius * 1.2, uPlanetRadius / 4., 0.) 57 | #define MOON_ROTATION_AXIS (MOON_OFFSET - uPlanetPosition) * rotateZ(PI/2.) 58 | 59 | // Planet colors 60 | #define WATER_COLOR_DEEP vec3(0.01, 0.05, 0.15) 61 | #define WATER_COLOR_SURFACE vec3(0.02, 0.12, 0.27) 62 | #define SAND_COLOR vec3(1.0, 1.0, 0.85) 63 | #define TREE_COLOR vec3(.02, .1, .06) 64 | #define ROCK_COLOR vec3(0.15, 0.12, 0.12) 65 | #define ICE_COLOR vec3(0.8, .9, .9) 66 | #define CLOUD_COLOR vec3(1., 1., 1.) 67 | 68 | #define WATER_SURFACE_LEVEL 0.0 69 | #define SAND_LEVEL .028 70 | #define TREE_LEVEL .03 71 | #define ROCK_LEVEL .1 72 | #define ICE_LEVEL .15 73 | #define TRANSITION .02 74 | 75 | // Lighting 76 | #define SUN_COLOR vec3(1.0, 1.0, 0.9) 77 | #define DEEP_SPACE vec3(0., 0., 0.001) 78 | 79 | // Ray tracing 80 | #define EPSILON 1e-3 81 | #define INFINITY 1e10 82 | #define CAMERA_POSITION vec3(0., 0., 6.0) 83 | 84 | #define PI acos(-1.) 85 | 86 | //=========// 87 | // Types // 88 | //=========// 89 | 90 | struct Material { 91 | vec3 color; 92 | float diffuse; 93 | float specular; 94 | }; 95 | 96 | struct Hit { 97 | float len; 98 | vec3 normal; 99 | Material material; 100 | }; 101 | 102 | struct Sphere { 103 | vec3 position; 104 | float radius; 105 | }; 106 | 107 | // Note: I had created a struct for Ray but then deleted it because it caused artifacts on some mobile devices 108 | // because of a precision issue with struct (https://github.com/KhronosGroup/WebGL/issues/3351) 109 | // I use ro and rd instead in this shader. 110 | 111 | Hit miss = Hit(INFINITY, vec3(0.), Material(vec3(0.), -1., -1.)); 112 | 113 | Sphere getPlanet() { 114 | return Sphere(uPlanetPosition, uPlanetRadius); 115 | } 116 | 117 | //===============================================// 118 | // Generic utilities stolen from smarter people // 119 | //===============================================// 120 | 121 | float inverseLerp(float v, float minValue, float maxValue) { 122 | return (v - minValue) / (maxValue - minValue); 123 | } 124 | 125 | float remap(float v, float inMin, float inMax, float outMin, float outMax) { 126 | float t = inverseLerp(v, inMin, inMax); 127 | return mix(outMin, outMax, t); 128 | } 129 | 130 | float noise(vec3 p) { 131 | return texture(uNoiseTexture, p * .05).r; 132 | } 133 | 134 | // https://iquilezles.org/articles/intersectors/ 135 | float sphIntersect(in vec3 ro, in vec3 rd, in Sphere sphere) { 136 | vec3 oc = ro - sphere.position; 137 | float b = dot(oc, rd); 138 | float c = dot(oc, oc) - sphere.radius * sphere.radius; 139 | float h = b * b - c; 140 | if(h < 0.0) 141 | return -1.; // no intersection 142 | return -b - sqrt(h); 143 | } 144 | 145 | // Comes from a course by SimonDev (https://www.youtube.com/channel/UCEwhtpXrg5MmwlH04ANpL8A) 146 | // https://simondev.teachable.com/p/glsl-shaders-from-scratch 147 | float fbm(vec3 p, int octaves, float persistence, float lacunarity, float exponentiation) { 148 | float amplitude = 0.5; 149 | float frequency = 3.0; 150 | float total = 0.0; 151 | float normalization = 0.0; 152 | int qualityDegradation = 2 - int(floor(uQuality)); // 0 when quality=optimal, 2 when quality=low 153 | int octavesWithQuality = max(octaves - qualityDegradation, 1); 154 | 155 | for(int i = 0; i < octavesWithQuality; ++i) { 156 | float noiseValue = noise(p * frequency); 157 | total += noiseValue * amplitude; 158 | normalization += amplitude; 159 | amplitude *= persistence; 160 | frequency *= lacunarity; 161 | } 162 | 163 | total /= normalization; 164 | total = total * 0.8 + 0.1; 165 | total = pow(total, exponentiation); 166 | 167 | return total; 168 | } 169 | 170 | mat3 rotateY(float angle) { 171 | float c = cos(angle); 172 | float s = sin(angle); 173 | return mat3(// 174 | vec3(c, 0, s),// 175 | vec3(0, 1, 0),// 176 | vec3(-s, 0, c)// 177 | ); 178 | } 179 | 180 | mat3 rotateZ(float angle) { 181 | float c = cos(angle); 182 | float s = sin(angle); 183 | return mat3(// 184 | vec3(c, -s, 0),// 185 | vec3(s, c, 0),// 186 | vec3(0, 0, 1)// 187 | ); 188 | } 189 | 190 | // https://github.com/dmnsgn/glsl-rotate/blob/main/rotation-3d.glsl 191 | mat3 rotate3d(vec3 axis, float angle) { 192 | axis = normalize(axis); 193 | float s = sin(angle); 194 | float c = cos(angle); 195 | float oc = 1.0 - c; 196 | 197 | return mat3(// 198 | oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s,// 199 | oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s,// 200 | oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c// 201 | ); 202 | } 203 | 204 | // nimitz - https://www.shadertoy.com/view/XsyGWV 205 | // I reused the 3D noise texture instead of nimitz's hash function for better performance 206 | vec3 stars(in vec3 p) { 207 | vec3 c = vec3(0.); 208 | float res = uResolution.x * uQuality * 0.8; 209 | 210 | for(float i = 0.; i < 3.; i++) { 211 | vec3 q = fract(p * (.15 * res)) - 0.5; 212 | vec3 id = floor(p * (.15 * res)); 213 | vec2 rn = vec2(noise(id/2.), noise(id.zyx*2.))*.03; 214 | float c2 = 1. - smoothstep(0., .6, length(q)); 215 | c2 *= step(rn.x, .003 + i * 0.0005); 216 | c += c2 * (mix(vec3(1.0, 0.49, 0.1), vec3(0.75, 0.9, 1.), rn.y) * 0.25 + 1.2); 217 | p *= 1.8; 218 | } 219 | return c * c; 220 | } 221 | 222 | // Comes from a course by SimonDev (https://www.youtube.com/channel/UCEwhtpXrg5MmwlH04ANpL8A) 223 | // https://simondev.teachable.com/p/glsl-shaders-from-scratch 224 | float domainWarpingFBM(vec3 p, int octaves, float persistence, float lacunarity, float exponentiation) { 225 | vec3 offset = vec3(// 226 | fbm(p, octaves, persistence, lacunarity, exponentiation), // 227 | fbm(p + vec3(43.235, 23.112, 0.0), octaves, persistence, lacunarity, exponentiation), // 228 | 0.0// 229 | ); 230 | 231 | return fbm(p + 1. * offset, 2, persistence, lacunarity, exponentiation); 232 | } 233 | 234 | // Zavie - https://www.shadertoy.com/view/lslGzl 235 | vec3 simpleReinhardToneMapping(vec3 color) { 236 | float exposure = 1.5; 237 | color *= exposure / (1. + color / exposure); 238 | color = pow(color, vec3(1. / 2.4)); 239 | return color; 240 | } 241 | 242 | 243 | //========// 244 | // Misc // 245 | //========// 246 | 247 | float planetNoise(vec3 p) { 248 | float fbm = fbm(p * uTerrainScale, 6, .5, 2., 5.) * uNoiseStrength; 249 | 250 | // Flatten the noise on the oceans 251 | return mix(// 252 | fbm / 3. + uNoiseStrength / 50., // 253 | fbm, // 254 | smoothstep(SAND_LEVEL, SAND_LEVEL + TRANSITION / 2., fbm * 5.)// 255 | ); 256 | } 257 | 258 | /** 259 | * Standard ray-sphere intersection but with fbm noise added on the radius. 260 | * Probably not exact (especially near the edges), but it looks good enough 261 | */ 262 | float planetDist(in vec3 ro, in vec3 rd) { 263 | float smoothSphereDist = sphIntersect(ro, rd, getPlanet()); 264 | 265 | vec3 intersection = ro + smoothSphereDist * rd; 266 | vec3 intersectionWithRotation = PLANET_ROTATION * (intersection - uPlanetPosition) + uPlanetPosition; 267 | 268 | return sphIntersect(ro, rd, Sphere(uPlanetPosition, uPlanetRadius + planetNoise(intersectionWithRotation))); 269 | } 270 | 271 | vec3 planetNormal(vec3 p) { 272 | vec3 rd = uPlanetPosition - p; 273 | float dist = planetDist(p, rd); 274 | // if e is too small it causes artifacts on mobile, so I interpolate 275 | // between .01 (large screens) and .03 (small screens) 276 | vec2 e = vec2(max(.01, .03 * smoothstep(1300., 300., uResolution.x)), 0); 277 | 278 | vec3 normal = dist - vec3(planetDist(p - e.xyy, rd), planetDist(p - e.yxy, rd), planetDist(p + e.yyx, rd)); 279 | return normalize(normal); 280 | } 281 | 282 | vec3 currentMoonPosition() { 283 | mat3 moonRotation = rotate3d(MOON_ROTATION_AXIS, uTime * MOON_ROTATION_SPEED); 284 | return MOON_OFFSET * moonRotation + uPlanetPosition; 285 | } 286 | 287 | vec3 spaceColor(vec3 direction) { 288 | mat3 backgroundRotation = rotateY(uTime * ROTATION_SPEED / 4.); 289 | vec3 backgroundCoord = direction * backgroundRotation; 290 | float spaceNoise = fbm(backgroundCoord * 3., 4, .5, 2., 6.); 291 | 292 | return stars(backgroundCoord) + mix(DEEP_SPACE, uAtmosphereColor / 12., spaceNoise); 293 | } 294 | 295 | vec3 atmosphereColor(vec3 ro, vec3 rd, float spaceMask, Hit firstHit) { 296 | vec3 position = ro + firstHit.len * rd; 297 | 298 | float distCameraToPlanetOrigin = length(uPlanetPosition - CAMERA_POSITION); 299 | float distCameraToPlanetEdge = sqrt(distCameraToPlanetOrigin * distCameraToPlanetOrigin - uPlanetRadius * uPlanetRadius); 300 | float distCameraToMoon = length(currentMoonPosition() - CAMERA_POSITION); 301 | float isMoonInFront = smoothstep(-uPlanetRadius/2., uPlanetRadius/2., distCameraToPlanetEdge - distCameraToMoon); 302 | 303 | float moonMask = (1.0 - spaceMask) * step(uPlanetRadius + EPSILON, length(position - uPlanetPosition)); 304 | float planetMask = 1.0 - spaceMask - moonMask; 305 | 306 | vec3 coordFromCenter = (ro + rd * distCameraToPlanetEdge) - uPlanetPosition; 307 | float distFromEdge = abs(length(coordFromCenter) - uPlanetRadius); 308 | float planetEdge = max(uPlanetRadius - distFromEdge, 0.) / uPlanetRadius; 309 | float atmosphereMask = pow(remap(dot(uSunDirection, coordFromCenter), -uPlanetRadius, uPlanetRadius / 2., 0., 1.), 5.); 310 | atmosphereMask *= uAtmosphereDensity * uPlanetRadius * uSunIntensity; 311 | 312 | vec3 atmosphere = vec3(pow(planetEdge, 120.)) * .5; 313 | atmosphere += pow(planetEdge, 50.) * .3 * (1.5 - planetMask); 314 | atmosphere += pow(planetEdge, 15.) * .03; 315 | atmosphere += pow(planetEdge, 5.) * .04 * planetMask; 316 | 317 | return atmosphere * uAtmosphereColor * atmosphereMask * (1. - moonMask * isMoonInFront); 318 | } 319 | 320 | //===============// 321 | // Ray Tracing // 322 | //===============// 323 | 324 | Hit intersectPlanet(vec3 ro, vec3 rd) { 325 | float len = sphIntersect(ro, rd, getPlanet()); 326 | 327 | if(len < 0.) { 328 | return miss; 329 | } 330 | 331 | vec3 position = ro + len * rd; 332 | vec3 rotatedCoord = PLANET_ROTATION * (position - uPlanetPosition) + uPlanetPosition; 333 | float altitude = 5. * planetNoise(rotatedCoord); 334 | 335 | vec3 normal = planetNormal(position); 336 | 337 | vec3 color = mix(WATER_COLOR_DEEP, WATER_COLOR_SURFACE, smoothstep(WATER_SURFACE_LEVEL, WATER_SURFACE_LEVEL + TRANSITION, altitude)); 338 | color = mix(color, SAND_COLOR, smoothstep(SAND_LEVEL, SAND_LEVEL + TRANSITION / 2., altitude)); 339 | color = mix(color, TREE_COLOR, smoothstep(TREE_LEVEL, TREE_LEVEL + TRANSITION, altitude)); 340 | color = mix(color, ROCK_COLOR, smoothstep(ROCK_LEVEL, ROCK_LEVEL + TRANSITION, altitude)); 341 | color = mix(color, ICE_COLOR, smoothstep(ICE_LEVEL, ICE_LEVEL + TRANSITION, altitude)); 342 | 343 | vec3 cloudsCoord = (rotatedCoord + vec3(uTime * .008 * uCloudsSpeed)) * uCloudsScale; 344 | float cloudsDensity = remap(domainWarpingFBM(cloudsCoord, 3, .3, 5., uCloudsScale), -1.0, 1.0, 0.0, 1.0); 345 | float cloudsThreshold = 1. - uCloudsDensity * .5; 346 | cloudsDensity *= smoothstep(cloudsThreshold, cloudsThreshold + .1, cloudsDensity); 347 | cloudsDensity *= smoothstep(ROCK_LEVEL, (ROCK_LEVEL + TREE_LEVEL) / 2., altitude); 348 | color = mix(color, CLOUD_COLOR, cloudsDensity); 349 | 350 | float specular = smoothstep(SAND_LEVEL + TRANSITION, SAND_LEVEL, altitude); 351 | 352 | return Hit(len, normal, Material(color, 1., specular)); 353 | } 354 | 355 | Hit intersectMoon(vec3 ro, vec3 rd) { 356 | vec3 moonPosition = currentMoonPosition(); 357 | float length = sphIntersect(ro, rd, Sphere(moonPosition, MOON_RADIUS)); 358 | 359 | if(length < 0.) { 360 | return miss; 361 | } 362 | 363 | vec3 position = ro + length * rd; 364 | vec3 originalPosition = position * rotate3d(MOON_ROTATION_AXIS, -uTime * MOON_ROTATION_SPEED); 365 | vec3 color = vec3(sqrt(fbm(originalPosition * 12., 6, .5, 2., 5.))); 366 | vec3 normal = normalize(position - moonPosition); 367 | 368 | return Hit(length, normal, Material(color, 1., 0.)); 369 | } 370 | 371 | Hit intersectScene(vec3 ro, vec3 rd) { 372 | Hit planetHit = intersectPlanet(ro, rd); 373 | Hit moonHit = intersectMoon(ro, rd); 374 | 375 | if(moonHit.len < planetHit.len) { 376 | return moonHit; 377 | } 378 | 379 | return planetHit; 380 | } 381 | 382 | vec3 radiance(vec3 ro, vec3 rd) { 383 | vec3 color = vec3(0.); 384 | float spaceMask = 1.; 385 | Hit hit = intersectScene(ro, rd); 386 | 387 | if(hit.len < INFINITY) { 388 | spaceMask = 0.; 389 | 390 | vec3 hitPosition = ro + hit.len * rd; 391 | Hit shadowHit = intersectScene(hitPosition + EPSILON * uSunDirection, uSunDirection); 392 | float hitDirectLight = clamp( 393 | step(INFINITY, shadowHit.len) 394 | + step(length(hitPosition - uPlanetPosition) - uPlanetRadius, .1), // don't cast shadow on the planet, only the moon 395 | 0., 396 | 1. 397 | ); 398 | 399 | // Diffuse 400 | float directLightIntensity = pow(clamp(dot(hit.normal, uSunDirection), 0.0, 1.0), 2.) * uSunIntensity; // the power softens the shadow. Not physically accurate but it looks better to me 401 | vec3 diffuseLight = hitDirectLight * directLightIntensity * SUN_COLOR; 402 | vec3 diffuseColor = hit.material.color.rgb * (uAmbientLight + diffuseLight); 403 | 404 | // Phong specular 405 | vec3 reflected = normalize(reflect(-uSunDirection, hit.normal)); 406 | float phongValue = pow(max(0.0, dot(rd, reflected)), 10.) * .2 * uSunIntensity; 407 | vec3 specularColor = hit.material.specular * vec3(phongValue); 408 | 409 | color = diffuseColor + specularColor; 410 | } else { 411 | color = spaceColor(rd); 412 | } 413 | 414 | return color + atmosphereColor(ro, rd, spaceMask, hit); 415 | } 416 | 417 | //========// 418 | // Main // 419 | //========// 420 | 421 | void main() { 422 | vec3 ro = vec3(CAMERA_POSITION); 423 | vec3 rd = normalize(vec3(uv, -1)); 424 | 425 | vec3 color = radiance(ro, rd); 426 | 427 | // color grading 428 | color = simpleReinhardToneMapping(color); 429 | 430 | // vignette 431 | color *= 1. - 0.5 * pow(length(uv), 3.); 432 | 433 | fragColor = vec4(color, 1.0); 434 | } -------------------------------------------------------------------------------- /src/webgl/shaders/vertex.glsl: -------------------------------------------------------------------------------- 1 | #version 300 es 2 | 3 | precision highp float; 4 | 5 | in vec3 position; 6 | uniform vec2 uResolution; 7 | uniform vec2 sunDirectionXY; 8 | uniform float uQuality; 9 | 10 | out vec3 uSunDirection; 11 | out vec2 uv; 12 | 13 | void main() { 14 | vec2 resolution = uResolution * uQuality; 15 | uv = (position.xy - 0.5) * resolution / min(resolution.y, resolution.x); 16 | uSunDirection = normalize(vec3(sunDirectionXY, 0.)); 17 | 18 | gl_Position = vec4(2.0 * position - 1.0, 1.0); 19 | } -------------------------------------------------------------------------------- /src/webgl/textures/starsTexture.ts: -------------------------------------------------------------------------------- 1 | import type { TextureData } from "../loaders/texture.types"; 2 | import { isPhone } from "../settings/device"; 3 | 4 | export const starsTexture: TextureData = isPhone 5 | ? { 6 | path: "4k_stars.jpg", 7 | width: 4096, 8 | height: 2048, 9 | options: { minFilter: "linearMipmapLinear" }, 10 | } 11 | : { 12 | path: "8k_stars.jpg", 13 | width: 8192, 14 | height: 4096, 15 | options: { minFilter: "linearMipmapLinear" }, 16 | }; 17 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "astro/tsconfigs/strict" 3 | } 4 | --------------------------------------------------------------------------------