├── .gitignore ├── AUTHORS ├── LICENSE ├── README.md ├── TIPS.md ├── assets └── favicon.ico ├── index.html ├── scripts ├── canvasConfig.js ├── closure-compiler │ ├── README │ └── externs.js ├── cursor.js ├── elements.js ├── game.js ├── menu.js ├── particles.js ├── softBody.js ├── spigots.js ├── third_party │ └── matter.min.js ├── util.js └── zombies.js └── styles.css /.gitignore: -------------------------------------------------------------------------------- 1 | *.swp 2 | compiled.js 3 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | Here is a list of people who have submitted patches. If you create, improve, 2 | or fix something, please feel free to add your name to this list. 3 | 4 | Ben Don 5 | Josh Don 6 | -------------------------------------------------------------------------------- /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 | # Project Sand 2 | 3 | Overview 4 | -------- 5 | 6 | In the early to mid 2000s, there were a series of Java applet based games based around a falling sand mechanic - collectively known as "Falling Sand Games". One of the most popular versions was referred to as the "Hell of Sand Falling Game". The website [http://androdome.com/Sand/](http://androdome.com/Sand/) provides a relatively detailed history of these applets. 7 | 8 | Seeing as Java applets are deprecated, this means that there is no easy way to play these applets online. As such, the purpose of this project is to reproduce Hell of Sand as a modern HTML5 game, with a few extra touches. The HTML5 version is named "Project Sand". It replicates the original game mechanics, while also making some tweaks, extensions, and improvements (for example, new elements, new interactions, etc.). 9 | 10 | If you'd like to watch a short history of the development of the game, click [here](https://youtu.be/8J9ljXbWR8k). 11 | 12 | See also [TIPS.md](TIPS.md) for some extra hints while playing the game. 13 | 14 | Technical Details 15 | ----------------- 16 | 17 | The game utilizes an HTML5 canvas for animation. Each pixel on the canvas represents an element, depending on its color. The core idea is that each pixel performs an action based on the color (element) of its surrounding pixels. For example, if pixel *p* at index *i* has a black BACKGROUND pixel below it (at index *i + width*), we can do `canvas[i] = BACKGROUND; canvas[i + width] = p;` in order to simulate gravity. 18 | 19 | The core game loop needs to operate pixel-by-pixel on a canvas of approximately 250,000 pixels at a rate of 60-120 times per second. Getting this to run smoothly in JavaScript was challenging due to: 20 | + The confinement to a single thread of execution. Whereas the Java applet based versions can easily spawn multiple threads (ie. separate the rendering from the game logic), there is only a single main thread available for Javascript. Web workers were deemed not worthwhile, since the communication and synchronization overhead (workers cannot directly modify the DOM) was high. 21 | + Javascript itself. Care was taken to make the Javascript code as optimized as possible: 22 | + Use of const wherever possible. This also involves moving many variables to global scope. 23 | + Minimal use of dictionaries/classes. It is much faster (though not as well abstracted) to use arrays wherever possible instead. 24 | + Caching of computed values, especially when they are reused in a loop. 25 | + Replacing comparison operators with strict inequality operators wherever possible. This gives a *slight* performance improvement. e.g. 26 | + `for (var i = 0; i < MAX; i++)` BAD 27 | + `for (var i = 0; i !== MAX; i++)` GOOD 28 | + Bit operations to convert element hex codes to element indices (see elements.js). 29 | + Pre-computation of random values. 30 | + Explicit conversion to Uint32 Arrays. 31 | + Duplication of code branches in hot paths, instead of abstracting to a method. 32 | 33 | As a result of the above optimizations, the game is able to play quite smoothly. 34 | 35 | Contributing 36 | ------------ 37 | Pull requests are welcome for bug fixes, optimizations, or novel element ideas. Comments in the code describe how to add to and modify it. 38 | 39 | If you want to trace the core game loop from the top of the call hierarchy, start with scripts/game.js:updateGame(). 40 | -------------------------------------------------------------------------------- /TIPS.md: -------------------------------------------------------------------------------- 1 | + Hold shift to draw in straight lines 2 | + You can draw vertically, horizontally, and at 45 degree angles 3 | + For a larger canvas, zoom in (ctrl +). Then, refresh the browser window in order to reset the scaling (this gives nice crisp pixels). 4 | + ??? has multiple interactions, try to find them all :) 5 | + Nitro + Soil yields a unique explosive 6 | + Lava rock + Oil will produce Methane 7 | -------------------------------------------------------------------------------- /assets/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joshdon/ProjectSand/467894210979dc0ce34b670858004431e704992c/assets/favicon.ico -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Project Sand 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 |
19 |

Project Sand

20 |
21 |
22 | Source Code 23 |
24 |
25 | By: Josh Don 26 |
27 |
28 | Original Applets 29 |
30 |
31 |
32 | 33 | Your browser doesn't support HTML5 canvas. 34 | 84 |
85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | -------------------------------------------------------------------------------- /scripts/canvasConfig.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Global game parameters for the primary canvas. 3 | * 4 | * Copyright (C) 2020, Josh Don 5 | * 6 | * Project Sand is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * Project Sand is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | 20 | const __max_width = 560; 21 | const __max_height = 480; 22 | 23 | /* Need to use a smaller size when on mobile devices with small screens */ 24 | const width = Math.min(__max_width, Math.max(screen.width - 6, 1)); 25 | const height = Math.min(__max_height, Math.max(screen.height - 200, 100)); 26 | 27 | const MAX_FPS = 120; 28 | const DEFAULT_FPS = 60; 29 | 30 | const MAX_NUM_PARTICLES = 1000; 31 | 32 | /* 33 | * The zombie animation speed is tied to the FPS setting of the game; 34 | * speeding or slowing the FPS will also change the zombie animation 35 | * speed. The following value provides the baseline speed, which then 36 | * becomes scaled by the FPS. Note that the animation engine has a limit 37 | * to how much it can simulate in each step, so the following value should 38 | * not be made too large. 39 | */ 40 | const ZOMBIE_ANIMATION_SPEED = 12; 41 | 42 | const MAX_ZOMBIES = 60; 43 | -------------------------------------------------------------------------------- /scripts/closure-compiler/README: -------------------------------------------------------------------------------- 1 | For use with the Google closure compiler, so that we can minify 2 | the javascript code that is calling into the matter.js library. 3 | 4 | DISCLAIMER: This is not a complete set of externs, but rather the 5 | set of objects and properties currently in use. If you add new 6 | calls to other matter.js properties, you must also add a declaration 7 | here, or the closure compiler may silently break the code by rewriting 8 | things it should not. 9 | 10 | 11 | The closure compiler can be invoked like so: 12 | 13 | npx google-closure-compiler --externs scripts/closure-compiler/externs.js --js scripts/*.js --compilation_level ADVANCED_OPTIMIZATIONS --js_output_file compiled.js 14 | -------------------------------------------------------------------------------- /scripts/closure-compiler/externs.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @externs 3 | * 4 | * See the README in this directory for more info. 5 | */ 6 | 7 | /** @const */ 8 | var Matter = {}; 9 | 10 | /** 11 | * @constructor 12 | */ 13 | Matter.Mouse = function() {}; 14 | 15 | /** 16 | * @param {!Matter.Mouse} mouse 17 | * @param {{x: number, y: number}} offset 18 | */ 19 | Matter.Mouse.setOffset = function(mouse, offset) {}; 20 | 21 | /** 22 | * @param {!Matter.Mouse} mouse 23 | * @param {{x: number, y: number}} scale 24 | */ 25 | Matter.Mouse.setScale = function(mouse, scale) {}; 26 | 27 | /** 28 | * @param {(!Element|null)} element 29 | * @return {!Matter.Mouse} 30 | */ 31 | Matter.Mouse.create = function(element) {}; 32 | 33 | /** 34 | * @type {{x: number, y: number}} 35 | */ 36 | Matter.Mouse.prototype.offset; 37 | 38 | /** 39 | * @constructor 40 | */ 41 | Matter.Engine = function() {}; 42 | 43 | /** 44 | * @return {!Matter.Engine} 45 | */ 46 | Matter.Engine.create = function() {}; 47 | 48 | /** 49 | * @param {!Matter.Engine} engine 50 | * @param {number} delta 51 | */ 52 | Matter.Engine.update = function(engine, delta) {}; 53 | 54 | /** 55 | * @type {{scale: number}} 56 | */ 57 | Matter.Engine.prototype.gravity; 58 | 59 | /** 60 | * @type {!Object} 61 | */ 62 | Matter.Engine.prototype.world; 63 | 64 | /** 65 | * @constructor 66 | */ 67 | Matter.Body = function() {}; 68 | 69 | /** 70 | * @type {{x: number, y: number, angle: number}} 71 | */ 72 | Matter.Body.prototype.constraintImpulse; 73 | 74 | /** 75 | * @type {{x: number, y: number}} 76 | */ 77 | Matter.Body.prototype.velocity; 78 | 79 | /** 80 | * @type {number} 81 | */ 82 | Matter.Body.prototype.angularVelocity; 83 | 84 | /** 85 | * @type {!Array<{x: number, y: number}>} 86 | */ 87 | Matter.Body.prototype.vertices; 88 | 89 | /** 90 | * @return {number} 91 | */ 92 | Matter.Body.nextCategory = function() {}; 93 | 94 | /** 95 | * @param {boolean=} isNonColliding 96 | * @return {number} 97 | */ 98 | Matter.Body.nextGroup = function(isNonColliding) {}; 99 | 100 | /** 101 | * @param {!Object} body 102 | * @param {!Object} position 103 | * @param {!Object} force 104 | */ 105 | Matter.Body.applyForce = function(body, position, force) {}; 106 | 107 | /** 108 | * @param {!Object} body 109 | * @param {boolean} isStatic 110 | */ 111 | Matter.Body.setStatic = function(body, isStatic) {}; 112 | 113 | /** 114 | * @param {!Object} body 115 | * @param {number} velocity 116 | */ 117 | Matter.Body.setAngularVelocity = function(body, velocity) {}; 118 | 119 | /** 120 | * @param {!Object} body 121 | * @param {!Object} velocity 122 | */ 123 | Matter.Body.setVelocity = function(body, velocity) {}; 124 | 125 | /** 126 | * @const 127 | */ 128 | Matter.Bodies = {}; 129 | 130 | /** 131 | * @typedef {{ 132 | * isStatic: (boolean|undefined), 133 | * restitution: (number|undefined), 134 | * friction: (number|undefined), 135 | * frictionAir: (number|undefined), 136 | * density: (number|undefined), 137 | * collisionFilter: (CollisionFilter|undefined), 138 | * chamfer: ({ 139 | * radius: (number|undefined) 140 | * }|undefined) 141 | * }} 142 | */ 143 | var BodyOptions; 144 | 145 | /** 146 | * @param {number} x 147 | * @param {number} y 148 | * @param {number} width 149 | * @param {number} height 150 | * @param {!BodyOptions=} options 151 | * @return {!Matter.Body} 152 | */ 153 | Matter.Bodies.rectangle = function(x, y, width, height, options) {}; 154 | 155 | /** 156 | * @param {number} x 157 | * @param {number} y 158 | * @param {number} radius 159 | * @param {!BodyOptions=} options 160 | * @return {!Matter.Body} 161 | */ 162 | Matter.Bodies.circle = function(x, y, radius, options) {}; 163 | 164 | /** 165 | * @constructor 166 | */ 167 | Matter.Composite = function() {}; 168 | 169 | /** 170 | * @type {!Array} 171 | */ 172 | Matter.Composite.prototype.bodies; 173 | 174 | /** 175 | * @type {!Array} 176 | */ 177 | Matter.Composite.prototype.constraints; 178 | 179 | /** 180 | * @param {!Object} composite 181 | * @param {!Object|!Array} bodyOrBodies 182 | */ 183 | Matter.Composite.add = function(composite, bodyOrBodies) {}; 184 | 185 | /** 186 | * @param {!Object} composite 187 | * @param {!Object|!Array} bodyOrBodies 188 | */ 189 | Matter.Composite.remove = function(composite, bodyOrBodies) {}; 190 | 191 | /** 192 | * @param {!Object=} options 193 | * @return {!Matter.Composite} 194 | */ 195 | Matter.Composite.create = function(options) {}; 196 | 197 | /** 198 | * @const 199 | */ 200 | Matter.MouseConstraint = {}; 201 | 202 | /** 203 | * @typedef {{ 204 | * mouse: !Matter.Mouse, 205 | * constraint: ({ 206 | * stiffness: (number|undefined), 207 | * render: ({ 208 | * visible: (boolean|undefined) 209 | * }|undefined) 210 | * }|undefined), 211 | * collisionFilter: (CollisionFilter|undefined), 212 | * stiffness: (number|undefined), 213 | * damping: (number|undefined) 214 | * }} 215 | */ 216 | var MouseConstraintOptions; 217 | 218 | /** 219 | * @param {!Matter.Engine} engine 220 | * @param {!MouseConstraintOptions} options 221 | * @return {!Object} 222 | */ 223 | Matter.MouseConstraint.create = function(engine, options) {}; 224 | 225 | /** 226 | * @const 227 | */ 228 | Matter.Events = {}; 229 | 230 | /** 231 | * @param {!Object} object 232 | * @param {string} eventName 233 | * @param {function(!Object)} callback 234 | */ 235 | Matter.Events.on = function(object, eventName, callback) {}; 236 | 237 | /** 238 | * @const 239 | */ 240 | Matter.Constraint = {}; 241 | 242 | /** 243 | * @typedef {{ 244 | * bodyA: (!Object|undefined), 245 | * bodyB: (!Object|undefined), 246 | * pointA: ({x: number, y: number}|undefined), 247 | * pointB: ({x: number, y: number}|undefined), 248 | * length: (number|undefined), 249 | * stiffness: (number|undefined), 250 | * damping: (number|undefined), 251 | * collisionFilter: (CollisionFilter|undefined) 252 | * }} 253 | */ 254 | var ConstraintOptions; 255 | 256 | /** 257 | * @param {!ConstraintOptions} options 258 | * @return {!Object} 259 | */ 260 | Matter.Constraint.create = function(options) {}; 261 | 262 | /** 263 | * @typedef {{ 264 | * category: (number|undefined), 265 | * mask: (number|undefined), 266 | * group: (number|undefined) 267 | * }} 268 | */ 269 | var CollisionFilter; 270 | 271 | -------------------------------------------------------------------------------- /scripts/cursor.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Deals with the user drawing on the canvas. 3 | * 4 | * Copyright (C) 2020, Josh Don 5 | * 6 | * Project Sand is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * Project Sand is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | 20 | /* 21 | * Cursor options. Controlled via the menu. 22 | */ 23 | var PENSIZE; 24 | var SELECTED_ELEM; 25 | var OVERWRITE_ENABLED; 26 | 27 | /* 28 | * Offscreen canvas for drawing user stroke. We draw on 29 | * this canvas and then transfer the data to the main 30 | * canvas. We can't use the built-in drawing methods directly 31 | * on the main game canvas, since it produces off-shade colors 32 | * in order to perform anti-aliasing. 33 | */ 34 | const userstrokeCanvas = document.createElement("canvas"); 35 | userstrokeCanvas.width = width; 36 | userstrokeCanvas.height = height; 37 | const userstrokeCtx = userstrokeCanvas.getContext("2d", { alpha: false }); 38 | 39 | const CURSORS = []; 40 | 41 | /* Generic cursor */ 42 | class Cursor { 43 | constructor(canvas) { 44 | /* x, y, prevX, and prevY are coordinates *inside* the canvas */ 45 | this.x = 0; 46 | this.y = 0; 47 | this.prevX = 0; 48 | this.prevY = 0; 49 | this.initX = 0; 50 | this.initY = 0; 51 | 52 | /* 53 | * documentX and documentY are coordinates relative to the canvas, but 54 | * be outside the canvas (ie. negative) 55 | */ 56 | this.documentX = 0; 57 | this.documentY = 0; 58 | 59 | this.isDown = false; 60 | this.inCanvas = false; 61 | this.canvas = canvas; 62 | } 63 | 64 | notifyCursorUp() { 65 | /* 66 | * If drawStroke() adjusted the mouse offset, we need to move it back. 67 | */ 68 | if (softBodyMouse.offset.x != 0) { 69 | Matter.Mouse.setOffset(softBodyMouse, {x: 0, y: 0}); 70 | } 71 | } 72 | 73 | canvasCursorDown(x, y) { 74 | this.isDown = true; 75 | this.inCanvas = true; 76 | 77 | this.prevX = x; 78 | this.prevY = y; 79 | this.x = x; 80 | this.y = y; 81 | this.initX = x; 82 | this.initY = y; 83 | } 84 | 85 | canvasCursorMove(getPos) { 86 | if (!this.isDown) return; 87 | 88 | const pos = getPos(); 89 | 90 | this.x = pos[0]; 91 | this.y = pos[1]; 92 | } 93 | 94 | canvasCursorEnter(getInnerCoords, getOuterCoords) { 95 | this.inCanvas = true; 96 | 97 | if (!this.isDown) return; 98 | 99 | const innerCoords = getInnerCoords(this); 100 | const outerCoords = getOuterCoords(this); 101 | 102 | Cursor.interpolateCursorBorderPosition(innerCoords, outerCoords); 103 | 104 | this.prevX = outerCoords[0]; 105 | this.prevY = outerCoords[1]; 106 | this.x = innerCoords[0]; 107 | this.y = innerCoords[1]; 108 | } 109 | 110 | canvasCursorLeave(getOuterCoords) { 111 | this.inCanvas = false; 112 | 113 | if (!this.isDown) return; 114 | 115 | const outerCoords = getOuterCoords(this); 116 | Cursor.interpolateCursorBorderPosition( 117 | [this.prevX, this.prevY], 118 | outerCoords 119 | ); 120 | 121 | this.x = outerCoords[0]; 122 | this.y = outerCoords[1]; 123 | } 124 | 125 | documentCursorMove(getPos) { 126 | if (!this.isDown) return; 127 | if (this.inCanvas) return; 128 | 129 | const pos = getPos(); 130 | this.documentX = pos[0]; 131 | this.documentY = pos[1]; 132 | } 133 | 134 | documentCursorUp() { 135 | this.isDown = false; 136 | this.notifyCursorUp(); 137 | } 138 | 139 | documentCursorDown(e, getPos) { 140 | if (e.target == onscreenCanvas) return; 141 | if (this.isDown) return; 142 | 143 | this.isDown = true; 144 | this.inCanvas = false; 145 | 146 | /* 147 | * prevent drawStroke() from mistakenly drawing another segment if the 148 | * cursor was previously in the canvas 149 | */ 150 | this.prevX = this.x; 151 | this.prevY = this.y; 152 | 153 | this.initX = this.x; 154 | this.initY = this.y; 155 | 156 | const pos = getPos(this); 157 | this.documentX = pos[0]; 158 | this.documentY = pos[1]; 159 | } 160 | 161 | documentVisibilityChange(e) {} 162 | 163 | /* 164 | * Given that the cursor moved from coordinates outside the canvas 165 | * to coordinates inside the canvas, interpolate the coordinate that 166 | * the cursor passed through on the border of the canvas. 167 | * 168 | * Modifies and returns the result in outercoords. 169 | * 170 | * Note that outercoords is relative to the canvas, not the document. 171 | */ 172 | static interpolateCursorBorderPosition(innercoords, outercoords) { 173 | /* Get line parameters */ 174 | var dy = innercoords[1] - outercoords[1]; 175 | var dx = innercoords[0] - outercoords[0]; 176 | if (dy === 0) dy = 0.001; 177 | if (dx === 0) dx = 0.001; 178 | const slope = dy / dx; 179 | const y_intercept = innercoords[1] - slope * innercoords[0]; 180 | 181 | if (outercoords[0] < 0) { 182 | outercoords[0] = 0; 183 | outercoords[1] = y_intercept; 184 | } else if (outercoords[0] > MAX_X_IDX) { 185 | outercoords[0] = MAX_X_IDX; 186 | outercoords[1] = slope * MAX_X_IDX + y_intercept; 187 | } 188 | 189 | if (outercoords[1] < 0) { 190 | outercoords[1] = 0; 191 | outercoords[0] = (0 - y_intercept) / slope; 192 | } else if (outercoords[1] > MAX_Y_IDX) { 193 | outercoords[1] = MAX_Y_IDX; 194 | outercoords[0] = (MAX_Y_IDX - y_intercept) / slope; 195 | } 196 | 197 | outercoords[0] = Math.floor(outercoords[0]); 198 | outercoords[1] = Math.floor(outercoords[1]); 199 | 200 | /* Just in case... */ 201 | outercoords[0] = Math.max(Math.min(outercoords[0], MAX_X_IDX), 0); 202 | outercoords[1] = Math.max(Math.min(outercoords[1], MAX_Y_IDX), 0); 203 | 204 | return outercoords; 205 | } 206 | 207 | /* 208 | * This is a lot of code, but the idea here is simple. 209 | * We use a subset of the cursor canvas just big enough 210 | * to fit the user stroke (ie. why bother use the entire 211 | * width*height canvas if the userstroke is really small). 212 | * However, this means that we need to do a bit of math to 213 | * translate the cursor stroke into its proper position on 214 | * the main canvas. 215 | */ 216 | drawStroke() { 217 | if (!this.isDown) return; 218 | if (!this.inCanvas) { 219 | if (this.prevX === this.x && this.prevY === this.y) return; 220 | } 221 | 222 | const color = SELECTED_ELEM; 223 | 224 | /* We only want to drag zombies, not draw them */ 225 | if (color === ZOMBIE) { 226 | return; 227 | } 228 | 229 | /* 230 | * A bit of a hack, but the goal is to avoid triggering soft body dragging if 231 | * we're already drawing an element stroke. There are two parts to the hack. 232 | * Part 1 is detection by using a rough heuristic of whether the cursor has 233 | * moved enough since the last stroke draw. Part 2 is "disabling" the soft body 234 | * mouse by moving it outside the canvas. 235 | */ 236 | if (softBodyMouse.offset.x === 0 && 237 | Math.pow(this.initX - this.x, 2) + Math.pow(this.initY - this.y, 2) > Math.pow(20, 2)) { 238 | Matter.Mouse.setOffset(softBodyMouse, {x: width + 1, y: height + 1}); 239 | } 240 | 241 | const overwrite = OVERWRITE_ENABLED || color === BACKGROUND; 242 | const r = color & 0xff; 243 | const g = (color & 0xff00) >>> 8; 244 | const b = (color & 0xff0000) >>> 16; 245 | /* 246 | * As an optimization, we skip over 0xff000000 below. 247 | * If this is our color (ie. eraser), we need to slightly 248 | * modify it. 249 | */ 250 | const colorString = 251 | color !== 0xff000000 252 | ? "rgba(" + r + "," + g + "," + b + ", 1)" 253 | : "rgba(1, 0, 0, 1)"; 254 | 255 | /* (x1, y1) is the leftmost coordinate */ 256 | const x1 = Math.min(this.prevX, this.x); 257 | const x2 = Math.max(this.prevX, this.x); 258 | const y1 = this.prevX <= this.x ? this.prevY : this.y; 259 | const y2 = this.prevX <= this.x ? this.y : this.prevY; 260 | 261 | this.prevX = this.x; 262 | this.prevY = this.y; 263 | 264 | const strokeBuffer = Math.ceil(PENSIZE / 2); 265 | const x_translate = x1 - strokeBuffer; 266 | const y_translate = Math.min(y1, y2) - strokeBuffer; 267 | const x1_relative = x1 - x_translate; 268 | const y1_relative = y1 - y_translate; 269 | const x2_relative = x2 - x_translate; 270 | const y2_relative = y2 - y_translate; 271 | 272 | /* Initialize offscreen canvas. Ensure our drawing area starts black */ 273 | const userstroke_width = x2_relative + PENSIZE + 2; 274 | const userstroke_height = Math.max(y1_relative, y2_relative) + PENSIZE + 2; 275 | if (userstrokeCanvas.width < userstroke_width) 276 | userstrokeCanvas.width = userstroke_width; 277 | if (userstrokeCanvas.height < userstroke_height) 278 | userstrokeCanvas.height = userstroke_height; 279 | 280 | userstrokeCtx.beginPath(); 281 | userstrokeCtx.rect(0, 0, userstroke_width, userstroke_height); 282 | userstrokeCtx.fillStyle = "rgba(0, 0, 0, 1)"; 283 | userstrokeCtx.fill(); 284 | 285 | /* 286 | * Some browsers *cough* Edge *cough* Safari *cough* can't 287 | * handle drawing a line if the start and end are the same point. 288 | * So, special case this and draw a circle instead. 289 | */ 290 | if (x1_relative === x2_relative && y1_relative === y2_relative) { 291 | userstrokeCtx.beginPath(); 292 | userstrokeCtx.lineWidth = 0; 293 | userstrokeCtx.fillStyle = colorString; 294 | userstrokeCtx.arc(x1_relative, y1_relative, PENSIZE / 2, 0, TWO_PI); 295 | userstrokeCtx.fill(); 296 | } else { 297 | userstrokeCtx.lineWidth = PENSIZE; 298 | userstrokeCtx.strokeStyle = colorString; 299 | userstrokeCtx.lineCap = "round"; 300 | userstrokeCtx.beginPath(); 301 | userstrokeCtx.moveTo(x1_relative, y1_relative); 302 | userstrokeCtx.lineTo(x2_relative, y2_relative); 303 | userstrokeCtx.stroke(); 304 | } 305 | 306 | const strokeImageData = userstrokeCtx.getImageData( 307 | 0, 308 | 0, 309 | userstroke_width, 310 | userstroke_height 311 | ); 312 | const strokeImageData32 = new Uint32Array(strokeImageData.data.buffer); 313 | 314 | /* Transfer line from offscreen canvas to main canvas */ 315 | var x, y; 316 | const xStart = Math.max(0, -1 * x_translate); 317 | const yStart = Math.max(0, -1 * y_translate); 318 | const xTerminate = Math.min(userstroke_width, width - x_translate); 319 | const yTerminate = Math.min(userstroke_height, height - y_translate); 320 | if (xStart > xTerminate || yStart > yTerminate) { 321 | console.log("Bug in userstroke drawing"); 322 | return; 323 | } 324 | for (y = yStart; y !== yTerminate; y++) { 325 | const y_absolute = y + y_translate; 326 | const offset_absolute = y_absolute * width; 327 | const offset_relative = y * userstroke_width; 328 | for (x = xStart; x !== xTerminate; x++) { 329 | const x_absolute = x + x_translate; 330 | 331 | /* 332 | * Note that not all pixels will be equal to 'color'; browser will 333 | * anti-alias the line, which will result in some grayscale colors as 334 | * well. So, it is sufficient (and necessary) to consider a pixel 335 | * colored as long as it is not black. 336 | */ 337 | if (strokeImageData32[x + offset_relative] !== 0xff000000) { 338 | const absIdx = x_absolute + offset_absolute; 339 | if (overwrite || gameImagedata32[absIdx] === BACKGROUND) 340 | gameImagedata32[absIdx] = color; 341 | } 342 | } 343 | } 344 | } 345 | } 346 | 347 | /* 348 | * Note: the name "Mouse" conflicts with the declaration from matter.js, 349 | * so we use MouseCursor. 350 | */ 351 | class MouseCursor extends Cursor { 352 | constructor(canvas) { 353 | super(canvas); 354 | 355 | this.shiftStartX = 0; 356 | this.shiftStartY = 0; 357 | this.shiftPressed = false; 358 | this.lineDirection = MouseCursor.NO_DIRECTION; /* for use with shift key */ 359 | } 360 | 361 | canvasMouseDown(e) { 362 | const mousePos = MouseCursor.getMousePos(e, true, this.canvas); 363 | 364 | /* Fix bug that left the canvas stuck in "shift" mode */ 365 | if (this.shiftPressed && !e.shiftKey) this.shiftPressed = false; 366 | 367 | if (this.shiftPressed) { 368 | this.shiftStartX = mousePos[0]; 369 | this.shiftStartY = mousePos[1]; 370 | this.lineDirection = MouseCursor.NO_DIRECTION; 371 | } 372 | 373 | super.canvasCursorDown(mousePos[0], mousePos[1]); 374 | } 375 | 376 | canvasMouseMove(e) { 377 | const canvas = this.canvas; 378 | const getPos = function () { 379 | return MouseCursor.getMousePos(e, true, canvas); 380 | }; 381 | 382 | super.canvasCursorMove(getPos); 383 | } 384 | 385 | canvasMouseEnter(e) { 386 | const canvas = this.canvas; 387 | const getInnerPos = function (self) { 388 | return MouseCursor.getMousePos(e, true, canvas); 389 | }; 390 | const getOuterPos = function (self) { 391 | return [self.documentX, self.documentY]; 392 | }; 393 | 394 | super.canvasCursorEnter(getInnerPos, getOuterPos); 395 | 396 | /* 397 | * relies on the fact that super.CanvasCursorEnter has already fixed 398 | * prevX/prevY to be on the canvas border 399 | */ 400 | if ( 401 | this.isDown && 402 | this.shiftPressed && 403 | this.lineDirection === MouseCursor.NO_DIRECTION 404 | ) { 405 | this.shiftStartX = this.prevX; 406 | this.shiftStartY = this.prevY; 407 | } 408 | } 409 | 410 | canvasMouseLeave(e) { 411 | const canvas = this.canvas; 412 | const getOuterPos = function (self) { 413 | return MouseCursor.getMousePos(e, false, canvas); 414 | }; 415 | 416 | super.canvasCursorLeave(getOuterPos); 417 | } 418 | 419 | documentMouseMove(e) { 420 | if (e.target == onscreenCanvas) return; 421 | 422 | const canvas = this.canvas; 423 | const getPos = function () { 424 | return MouseCursor.getMousePos(e, false, canvas); 425 | }; 426 | 427 | super.documentCursorMove(getPos); 428 | } 429 | 430 | documentMouseUp(e) { 431 | /* 432 | * Don't use e, may be passed as null. Assigning here explicitly to avoid 433 | * bugs. 434 | */ 435 | e = null; 436 | 437 | this.lineDirection = MouseCursor.NO_DIRECTION; 438 | 439 | super.documentCursorUp(); 440 | } 441 | 442 | documentMouseDown(e) { 443 | /* only need handling when clicking outside the canvas */ 444 | if (e.target == onscreenCanvas) return; 445 | 446 | const canvas = this.canvas; 447 | const getPos = function () { 448 | return MouseCursor.getMousePos(e, false, canvas); 449 | }; 450 | 451 | /* Fix bug that left the canvas stuck in "shift" mode */ 452 | if (this.shiftPressed && !e.shiftKey) this.shiftPressed = false; 453 | 454 | if (this.shiftPressed) this.lineDirection = MouseCursor.NO_DIRECTION; 455 | 456 | super.documentCursorDown(e, getPos); 457 | } 458 | 459 | static getMousePos(e, withinCanvas, canvas) { 460 | var x, y; 461 | 462 | if (withinCanvas) { 463 | x = e.offsetX; 464 | y = e.offsetY; 465 | 466 | if (x < 0) x = 0; 467 | else if (x >= width) x = MAX_X_IDX; 468 | 469 | if (y < 0) y = 0; 470 | else if (y >= height) y = MAX_Y_IDX; 471 | } else { 472 | x = e.pageX - docOffsetLeft(canvas); 473 | y = e.pageY - docOffsetTop(canvas); 474 | } 475 | 476 | return [Math.round(x), Math.round(y)]; 477 | } 478 | 479 | documentKeyDown(e) { 480 | if (!e.shiftKey) return; 481 | 482 | if (this.shiftPressed) return; 483 | 484 | this.shiftPressed = true; 485 | this.lineDirection = MouseCursor.NO_DIRECTION; 486 | 487 | if (!this.isDown) return; 488 | 489 | if (!this.inCanvas) return; 490 | 491 | this.shiftStartX = this.x; 492 | this.shiftStartY = this.y; 493 | } 494 | 495 | documentKeyUp(e) { 496 | if (!e.shiftKey && this.shiftPressed) this.shiftPressed = false; 497 | } 498 | 499 | documentVisibilityChange(e) { 500 | const visibilityState = document.visibilityState; 501 | if (visibilityState == "hidden") { 502 | this.documentMouseUp(null); 503 | this.shiftPressed = false; 504 | } 505 | 506 | super.documentVisibilityChange(e); 507 | } 508 | 509 | /* 510 | * We draw straight lines when shift is held down. 511 | * 512 | * If this returns true, skip drawing the stroke (we need 513 | * to figure out what direction the line is going). 514 | */ 515 | handleShift() { 516 | if (!this.isDown) return false; 517 | 518 | if (!this.shiftPressed) return false; 519 | 520 | if (!this.inCanvas) { 521 | if (this.prevX === this.x && this.prevY === this.y) return; 522 | } 523 | 524 | if (this.lineDirection === MouseCursor.NO_DIRECTION) { 525 | if (!this.inCanvas) return false; 526 | 527 | const dx = this.x - this.shiftStartX; 528 | const dy = this.y - this.shiftStartY; 529 | const absDx = Math.abs(dx); 530 | const absDy = Math.abs(dy); 531 | 532 | /* Wait to see what direction the mouse is going in */ 533 | if (Math.max(absDx, absDy) < 8) return true; 534 | 535 | if (Math.abs(absDx - absDy) < 5) { 536 | if (dy * dx < 0) this.lineDirection = MouseCursor.DIAGONAL_DOWN; 537 | else this.lineDirection = MouseCursor.DIAGONAL_UP; 538 | } else if (absDx > absDy) { 539 | this.lineDirection = MouseCursor.HORIZONTAL; 540 | } else { 541 | this.lineDirection = MouseCursor.VERTICAL; 542 | } 543 | } 544 | 545 | const direction = this.lineDirection; 546 | if (direction === MouseCursor.HORIZONTAL) { 547 | this.prevY = this.shiftStartY; 548 | this.y = this.shiftStartY; 549 | } else if (direction === MouseCursor.VERTICAL) { 550 | this.prevX = this.shiftStartX; 551 | this.x = this.shiftStartX; 552 | } else if ( 553 | direction === MouseCursor.DIAGONAL_DOWN || 554 | direction === MouseCursor.DIAGONAL_UP 555 | ) { 556 | this.prevX = this.shiftStartX; 557 | this.prevY = this.shiftStartY; 558 | const slope = direction === MouseCursor.DIAGONAL_DOWN ? -1 : 1; 559 | const yIntercept = this.shiftStartY - slope * this.shiftStartX; 560 | 561 | const yAdjusted = slope * this.x + yIntercept; 562 | const xAdjusted = (this.y - yIntercept) / slope; 563 | if ( 564 | distance(xAdjusted, this.y, this.shiftStartX, this.shiftStartY) > 565 | distance(this.x, yAdjusted, this.shiftStartX, this.shiftStartY) 566 | ) { 567 | this.x = xAdjusted; 568 | } else { 569 | this.y = yAdjusted; 570 | } 571 | } 572 | 573 | return false; 574 | } 575 | 576 | drawStroke() { 577 | /* alters prevX, prevY, x, and y to handle drawing in straight lines */ 578 | if (this.handleShift()) return; 579 | 580 | super.drawStroke(); 581 | } 582 | } 583 | 584 | /* Touch cursor (ie. mobile users) */ 585 | class TouchCursor extends Cursor { 586 | constructor(canvas) { 587 | super(canvas); 588 | } 589 | 590 | canvasTouchStart(e) { 591 | const pos = TouchCursor.getTouchPos(e); 592 | 593 | if (!pos) return; 594 | 595 | super.canvasCursorDown(pos[0], pos[1]); 596 | 597 | /* prevent scrolling */ 598 | e.preventDefault(); 599 | 600 | return false; 601 | } 602 | 603 | canvasTouchEnd(e) { 604 | super.documentCursorUp(); 605 | 606 | /* prevent scrolling */ 607 | e.preventDefault(); 608 | 609 | return false; 610 | } 611 | 612 | canvasTouchMove(e) { 613 | const pos = TouchCursor.getTouchPos(e); 614 | 615 | if (!pos) return; 616 | 617 | const getPos = function () { 618 | return pos; 619 | }; 620 | 621 | super.canvasCursorMove(getPos); 622 | 623 | /* prevent scrolling */ 624 | e.preventDefault(); 625 | 626 | return false; 627 | } 628 | 629 | static getTouchPos(e) { 630 | if (!e.touches) return null; 631 | 632 | const touch = e.touches[0]; 633 | if (!touch) return null; 634 | 635 | const rect = e.target.getBoundingClientRect(); 636 | var x = Math.round(touch.pageX - rect.left - window.scrollX); 637 | var y = Math.round(touch.pageY - rect.top - window.scrollY); 638 | 639 | if (x < 0) x = 0; 640 | else if (x >= width) x = MAX_X_IDX; 641 | 642 | if (y < 0) y = 0; 643 | else if (y >= height) y = MAX_Y_IDX; 644 | 645 | return [x, y]; 646 | } 647 | } 648 | 649 | function initCursors() { 650 | PENSIZE = PEN_SIZES[DEFAULT_PEN_IDX]; 651 | SELECTED_ELEM = WALL; 652 | OVERWRITE_ENABLED = true; 653 | 654 | /* Set up direction constants for drawing straight lines */ 655 | MouseCursor.NO_DIRECTION = 0; 656 | MouseCursor.HORIZONTAL = 1; 657 | MouseCursor.VERTICAL = 2; 658 | MouseCursor.DIAGONAL_UP = 3; 659 | MouseCursor.DIAGONAL_DOWN = 4; 660 | 661 | /* 662 | * Setting the event handler functions in this way allows the handlers 663 | * to properly access the 'this' pointer. 664 | */ 665 | const mouse = new MouseCursor(onscreenCanvas); 666 | onscreenCanvas.onmousedown = function (e) { 667 | mouse.canvasMouseDown(e); 668 | }; 669 | onscreenCanvas.onmousemove = function (e) { 670 | mouse.canvasMouseMove(e); 671 | }; 672 | onscreenCanvas.onmouseleave = function (e) { 673 | mouse.canvasMouseLeave(e); 674 | }; 675 | onscreenCanvas.onmouseenter = function (e) { 676 | mouse.canvasMouseEnter(e); 677 | }; 678 | document.onmouseup = function (e) { 679 | mouse.documentMouseUp(e); 680 | }; 681 | document.onmousedown = function (e) { 682 | mouse.documentMouseDown(e); 683 | }; 684 | document.onmousemove = function (e) { 685 | mouse.documentMouseMove(e); 686 | }; 687 | document.onkeydown = function (e) { 688 | mouse.documentKeyDown(e); 689 | }; 690 | document.onkeyup = function (e) { 691 | mouse.documentKeyUp(e); 692 | }; 693 | document.onvisibilitychange = function (e) { 694 | mouse.documentVisibilityChange(e); 695 | }; 696 | 697 | const touchCursor = new TouchCursor(onscreenCanvas); 698 | onscreenCanvas.addEventListener("touchstart", function (e) { 699 | touchCursor.canvasTouchStart(e); 700 | }); 701 | onscreenCanvas.addEventListener("touchend", function (e) { 702 | touchCursor.canvasTouchEnd(e); 703 | }); 704 | onscreenCanvas.addEventListener("touchmove", function (e) { 705 | touchCursor.canvasTouchMove(e); 706 | }); 707 | 708 | CURSORS.push(mouse); 709 | CURSORS.push(touchCursor); 710 | Object.freeze(CURSORS); 711 | } 712 | 713 | /* Draw the userstroke on the stroke canvas */ 714 | function updateUserStroke() { 715 | const numCursors = CURSORS.length; 716 | for (var i = 0; i !== numCursors; i++) { 717 | CURSORS[i].drawStroke(); 718 | } 719 | } 720 | -------------------------------------------------------------------------------- /scripts/game.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Drives the primary game loops. 3 | * 4 | * Copyright (C) 2020, Josh Don 5 | * 6 | * Project Sand is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * Project Sand is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | 20 | /* ================================ Globals ================================ */ 21 | 22 | /* Scaling due to device pixel ratio */ 23 | const onscreenPixelRatio = window.devicePixelRatio; 24 | const onscreenScaledWidth = onscreenPixelRatio * width; 25 | const onscreenScaledHeight = onscreenPixelRatio * height; 26 | 27 | /* Onscreen canvas. Scaled based on pixel ratio. */ 28 | const onscreenCanvas = document.getElementById("mainCanvas"); 29 | onscreenCanvas.width = onscreenScaledWidth; 30 | onscreenCanvas.height = onscreenScaledHeight; 31 | onscreenCanvas.style.width = width + "px"; 32 | onscreenCanvas.style.height = height + "px"; 33 | const onscreenCtx = onscreenCanvas.getContext("2d", { alpha: false }); 34 | 35 | /* 36 | * Offscreen game canvas. Drawn at in-game resolution, then 37 | * scaled and transferred to the onscreen canvas. 38 | */ 39 | const gameCanvas = document.createElement("canvas"); 40 | gameCanvas.width = width; 41 | gameCanvas.height = height; 42 | const gameCtx = gameCanvas.getContext("2d"); 43 | const gameImagedata = gameCtx.createImageData(width, height); 44 | const gameImagedata32 = new Uint32Array(gameImagedata.data.buffer); 45 | 46 | /* Storage for game save state. */ 47 | const saveGameImagedata32 = new Uint32Array(gameImagedata32.length); 48 | var gamestateSaved = false; 49 | 50 | /* Cached for performance */ 51 | const MAX_X_IDX = width - 1; 52 | const MAX_Y_IDX = height - 1; 53 | const MAX_IDX = width * height - 1; 54 | 55 | /* Globals for tracking and maintaining FPS */ 56 | var fpsSetting; /* controlled via menu */ 57 | var msPerFrame; 58 | var lastLoop = 0; 59 | var frameDebt = 0; 60 | var lastFPSLabelUpdate = 0; 61 | const refreshTimes = []; 62 | 63 | /* ========================================================================= */ 64 | 65 | function init() { 66 | var gameWrapper = document.getElementById("gameWrapper"); 67 | gameWrapper.style.height = height + "px"; 68 | gameWrapper.style.width = width + "px"; 69 | 70 | /* setting FPS must occur before initMenu() */ 71 | setFPS(DEFAULT_FPS); 72 | 73 | initCursors(); 74 | initElements(); 75 | initParticles(); 76 | initSpigots(); 77 | initMenu(); 78 | initSoftBody(); 79 | 80 | /* Initialize imagedata */ 81 | const len = gameImagedata32.length; 82 | for (var i = 0; i < len; i++) { 83 | gameImagedata32[i] = BACKGROUND; 84 | saveGameImagedata32[i] = BACKGROUND; 85 | } 86 | 87 | /* Nice crisp pixels, regardless of pixel ratio */ 88 | onscreenCtx.mozImageSmoothingEnabled = false; 89 | onscreenCtx.imageSmoothingEnabled = false; 90 | onscreenCtx.webkitImageSmoothingEnabled = false; 91 | onscreenCtx.msImageSmoothingEnabled = false; 92 | onscreenCtx.oImageSmoothingEnabled = false; 93 | } 94 | 95 | function setFPS(fps) { 96 | fpsSetting = fps; 97 | if (fps > 0) msPerFrame = 1000.0 / fpsSetting; 98 | else drawFPSLabel(0); 99 | } 100 | function updateGame() { 101 | updateSpigots(); 102 | updateParticles(); 103 | 104 | var x, y; 105 | var i = MAX_IDX; 106 | /* 107 | * Since i starts at MAX_IDX, we need to guarantee that we will start 108 | * our traversal by going to the left. 109 | */ 110 | const direction = MAX_Y_IDX & 1; 111 | 112 | /* 113 | * Iterate the canvas from the bottom to top, zigzagging 114 | * the rows left and right. 115 | * To optimize for speed, we duplicate the code for the 116 | * left->right and right->left cases, as this is our hottest 117 | * inner path. This sacrifices readability, and violates DRY, 118 | * but is necessary for game performance. 119 | */ 120 | for (y = MAX_Y_IDX; y !== -1; y--) { 121 | const Y = y; 122 | if ((Y & 1) === direction) { 123 | for (x = MAX_X_IDX; x !== -1; x--) { 124 | const elem = gameImagedata32[i]; 125 | if (elem === BACKGROUND) { 126 | i--; 127 | continue; /* optimize to skip background */ 128 | } 129 | const elem_idx = 130 | ((elem & 0x30000) >>> 12) + ((elem & 0x300) >>> 6) + (elem & 0x3); 131 | elementActions[elem_idx](x, Y, i); 132 | i--; 133 | } 134 | i++; 135 | } else { 136 | for (x = 0; x !== width; x++) { 137 | const elem = gameImagedata32[i]; 138 | if (elem === BACKGROUND) { 139 | i++; 140 | continue; 141 | } 142 | const elem_idx = 143 | ((elem & 0x30000) >>> 12) + ((elem & 0x300) >>> 6) + (elem & 0x3); 144 | elementActions[elem_idx](x, Y, i); 145 | i++; 146 | } 147 | i--; 148 | } 149 | i -= width; 150 | } 151 | 152 | perfRecordFrame(); 153 | frameDebt--; 154 | } 155 | 156 | function draw() { 157 | gameCtx.putImageData(gameImagedata, 0, 0); 158 | 159 | /* 160 | * To make sure our game looks crisp, we need to handle 161 | * device pixel ratio. We do this by taking our offscreen 162 | * game canvas (at our ingame resolution), and then scaling 163 | * and transferring it to the displayed canvas. 164 | */ 165 | gameCtx.scale(onscreenPixelRatio, onscreenPixelRatio); 166 | onscreenCtx.drawImage( 167 | gameCanvas, 168 | 0, 169 | 0, 170 | onscreenScaledWidth, 171 | onscreenScaledHeight 172 | ); 173 | } 174 | 175 | function setGameCanvas(elem) { 176 | const iterEnd = MAX_IDX + 1; 177 | for (var i = 0; i !== iterEnd; i++) { 178 | gameImagedata32[i] = elem; 179 | } 180 | } 181 | 182 | function clearGameCanvas() { 183 | particles.inactivateAll(); 184 | setGameCanvas(BACKGROUND); 185 | } 186 | 187 | /* 188 | * Saves the current canvas state. Note that we don't also save particle state. 189 | */ 190 | function saveGameCanvas() { 191 | /* 192 | * Copy it manually, rather than use a slice, so that we can use a constant 193 | * global pointer. 194 | */ 195 | const iterEnd = MAX_IDX + 1; 196 | for (var i = 0; i !== iterEnd; i++) 197 | saveGameImagedata32[i] = gameImagedata32[i]; 198 | 199 | gamestateSaved = true; 200 | } 201 | 202 | function loadGameCanvas() { 203 | if (!gamestateSaved) return; 204 | 205 | particles.inactivateAll(); 206 | 207 | const iterEnd = MAX_IDX + 1; 208 | for (var i = 0; i !== iterEnd; i++) 209 | gameImagedata32[i] = saveGameImagedata32[i]; 210 | } 211 | 212 | /* Signal that we've updated a game frame to our FPS counter */ 213 | function perfRecordFrame() { 214 | const now = performance.now(); 215 | const oneSecondAgo = now - 1000; 216 | while (refreshTimes.length > 0 && refreshTimes[0] <= oneSecondAgo) { 217 | refreshTimes.shift(); 218 | } 219 | refreshTimes.push(now); 220 | 221 | if (now - lastFPSLabelUpdate > 200) { 222 | drawFPSLabel(refreshTimes.length); 223 | lastFPSLabelUpdate = now; 224 | } 225 | } 226 | 227 | function mainLoop(now) { 228 | window.requestAnimationFrame(mainLoop); 229 | 230 | /* Handle initial update */ 231 | if (lastLoop === 0) { 232 | lastLoop = now; 233 | return; 234 | } 235 | 236 | const deltaMs = now - lastLoop; 237 | lastLoop = now; 238 | if (deltaMs < 0) { 239 | console.log("time has gone backwards"); 240 | return; 241 | } 242 | 243 | if (fpsSetting > 0) frameDebt += deltaMs / msPerFrame; 244 | 245 | /* 246 | * Avoid accumulating too much frame debt, which can 247 | * occur, for example, from: 248 | * - animation loop being paused due to loss of browser 249 | * tab focus 250 | * - excessive time needed for updateGame() due to 251 | * complex update 252 | * 253 | * Naturally, this also limits our max theoretical FPS, but 254 | * our MAX_FPS is set lower than this limit anyway. 255 | */ 256 | frameDebt = Math.min(frameDebt, 5); 257 | 258 | /* 259 | * Always update the user stroke, regardless of whether 260 | * we're updating the gamestate. This results in smooth 261 | * drawing regardless of the current set FPS. 262 | * 263 | * Stop drawing the stroke if we're dragging a soft body, 264 | * since we don't want both at once. 265 | */ 266 | if (!softBodyDragStart) { 267 | updateUserStroke(); 268 | } 269 | 270 | var framesUpdated = 0; 271 | if (frameDebt >= 1) { 272 | if (frameDebt == 1) { 273 | /* shortcut for the common case of a single-frame update */ 274 | updateGame(); 275 | framesUpdated++; 276 | } else { 277 | /* multi-frame update */ 278 | 279 | /* first get approx time for a single update */ 280 | const updateTimeMs = executeAndTime(updateGame); 281 | framesUpdated++; 282 | 283 | /* 284 | * Approx time for doing stroke, draw, etc. 285 | * This is very rough and could be improved. 286 | */ 287 | const loopMiscTimeMs = 3.5; 288 | var timeRemaining = deltaMs - loopMiscTimeMs - updateTimeMs; 289 | while (timeRemaining > updateTimeMs && frameDebt >= 1) { 290 | updateGame(); 291 | timeRemaining -= updateTimeMs; 292 | framesUpdated++; 293 | } 294 | } 295 | } 296 | 297 | if (framesUpdated) { 298 | softBodyAnimate(framesUpdated * ZOMBIE_ANIMATION_SPEED); 299 | softBodyRender(); 300 | } 301 | 302 | draw(); 303 | } 304 | 305 | window.onload = function () { 306 | init(); 307 | mainLoop(0); 308 | }; 309 | -------------------------------------------------------------------------------- /scripts/menu.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Code for the menu options. 3 | * 4 | * Copyright (C) 2020, Josh Don 5 | * 6 | * Project Sand is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * Project Sand is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | 20 | /* Configuration of the menu */ 21 | const ELEMENT_MENU_ELEMENTS_PER_ROW = 4; 22 | const PEN_SIZES = [2, 4, 8, 16, 32, 64]; 23 | const PEN_SIZE_LABELS = ["1px", "2px", "4px", "8px", "16px", "32px"]; 24 | const DEFAULT_PEN_IDX = 1; 25 | 26 | /* Elements listed in the menu */ 27 | // prettier-ignore 28 | const elementMenuItems = [ 29 | WALL, SAND, WATER, PLANT, 30 | FIRE, SPOUT, WELL, SALT, 31 | OIL, WAX, TORCH, ICE, 32 | GUNPOWDER, NAPALM, NITRO, C4, 33 | LAVA, CRYO, FUSE, MYSTERY, 34 | CONCRETE, METHANE, SOIL, ACID, 35 | THERMITE, BACKGROUND, ZOMBIE, 36 | ]; 37 | 38 | const menuNames = {}; 39 | menuNames[WALL] = "WALL"; 40 | menuNames[SAND] = "SAND"; 41 | menuNames[WATER] = "WATER"; 42 | menuNames[PLANT] = "PLANT"; 43 | menuNames[FIRE] = "FIRE"; 44 | menuNames[SALT] = "SALT"; 45 | menuNames[OIL] = "OIL"; 46 | menuNames[SPOUT] = "SPOUT"; 47 | menuNames[WELL] = "WELL"; 48 | menuNames[TORCH] = "TORCH"; 49 | menuNames[GUNPOWDER] = "GUNPOWDER"; 50 | menuNames[WAX] = "WAX"; 51 | menuNames[NITRO] = "NITRO"; 52 | menuNames[NAPALM] = "NAPALM"; 53 | menuNames[C4] = "C-4"; 54 | menuNames[CONCRETE] = "CONCRETE"; 55 | menuNames[BACKGROUND] = "ERASER"; 56 | menuNames[FUSE] = "FUSE"; 57 | menuNames[ICE] = "ICE"; 58 | menuNames[LAVA] = "LAVA"; 59 | menuNames[METHANE] = "METHANE"; 60 | menuNames[CRYO] = "CRYO"; 61 | menuNames[MYSTERY] = "???"; 62 | menuNames[SOIL] = "SOIL"; 63 | menuNames[ACID] = "ACID"; 64 | menuNames[THERMITE] = "THERMITE"; 65 | menuNames[ZOMBIE] = "HAND"; 66 | 67 | /* 68 | * Some element colors do not have very good contrast against 69 | * the menu background. For these elements, we use a replacement 70 | * color for the menu text. 71 | */ 72 | const menuAltColors = {}; 73 | menuAltColors[WATER] = "rgb(0, 130, 255)"; 74 | menuAltColors[WALL] = "rgb(160, 160, 160)"; 75 | menuAltColors[BACKGROUND] = "rgb(200, 100, 200)"; 76 | menuAltColors[WELL] = "rgb(158, 13, 33)"; 77 | menuAltColors[SOIL] = "rgb(171, 110, 53)"; 78 | 79 | function initMenu() { 80 | /* The wrapper div that holds the entire menu */ 81 | const menu = document.getElementById("menuWrapper"); 82 | 83 | /* Set up the wrapper div that holds the element selectors */ 84 | const elementMenu = document.getElementById("elementTable"); 85 | elementMenu.style.width = 86 | "50%"; /* force browser to scrunch the element menu */ 87 | const numRows = Math.ceil( 88 | elementMenuItems.length / ELEMENT_MENU_ELEMENTS_PER_ROW 89 | ); 90 | var elemIdx = 0; 91 | var i, k; 92 | for (i = 0; i < numRows; i++) { 93 | const row = elementMenu.insertRow(i); 94 | for (k = 0; k < ELEMENT_MENU_ELEMENTS_PER_ROW; k++) { 95 | if (elemIdx >= elementMenuItems.length) break; 96 | 97 | const cell = row.insertCell(k); 98 | const elemButton = document.createElement("input"); 99 | cell.appendChild(elemButton); 100 | 101 | elemButton.type = "button"; 102 | elemButton.className = "elementMenuButton"; 103 | 104 | const elemType = elementMenuItems[elemIdx]; 105 | if (!(elemType in menuNames)) 106 | throw "element is missing a canonical name: " + elemType; 107 | elemButton.value = menuNames[elemType]; 108 | 109 | const elemColorRGBA = elemType; 110 | elemButton.id = elemColorRGBA; 111 | 112 | var elemMenuColor; 113 | if (elemType in menuAltColors) elemMenuColor = menuAltColors[elemType]; 114 | else 115 | elemMenuColor = 116 | "rgb(" + 117 | (elemColorRGBA & 0xff) + 118 | ", " + 119 | ((elemColorRGBA & 0xff00) >>> 8) + 120 | ", " + 121 | ((elemColorRGBA & 0xff0000) >>> 16) + 122 | ")"; 123 | elemButton.style.color = elemMenuColor; 124 | 125 | elemButton.addEventListener("click", function () { 126 | document 127 | .getElementById(SELECTED_ELEM.toString()) 128 | .classList.remove("selectedElementMenuButton"); 129 | elemButton.classList.add("selectedElementMenuButton"); 130 | SELECTED_ELEM = parseInt(elemButton.id, 10); 131 | }); 132 | 133 | elemIdx++; 134 | } 135 | } 136 | document.getElementById(SELECTED_ELEM.toString()).click(); 137 | 138 | /* Set up pensize options */ 139 | const pensizes = document.getElementById("pensize"); 140 | for (i = 0; i < PEN_SIZES.length; i++) { 141 | const p = document.createElement("option"); 142 | p.value = PEN_SIZES[i]; 143 | p.text = PEN_SIZE_LABELS[i]; 144 | if (i === DEFAULT_PEN_IDX) { 145 | p.selected = "selected"; 146 | PENSIZE = parseInt(p.value, 10); 147 | } 148 | pensizes.add(p); 149 | } 150 | pensizes.addEventListener("change", function () { 151 | PENSIZE = parseInt(pensizes.value, 10); 152 | }); 153 | 154 | /* Set up spigot size options */ 155 | const spigotTypes = [ 156 | document.getElementById("spigot1Type"), 157 | document.getElementById("spigot2Type"), 158 | document.getElementById("spigot3Type"), 159 | document.getElementById("spigot4Type"), 160 | ]; 161 | const spigotSizes = [ 162 | document.getElementById("spigot1Size"), 163 | document.getElementById("spigot2Size"), 164 | document.getElementById("spigot3Size"), 165 | document.getElementById("spigot4Size"), 166 | ]; 167 | if (spigotTypes.length !== spigotSizes.length) throw "should be same length"; 168 | for (i = 0; i < spigotTypes.length; i++) { 169 | const typeSelector = spigotTypes[i]; 170 | const sizeSelector = spigotSizes[i]; 171 | for (k = 0; k < SPIGOT_ELEMENT_OPTIONS.length; k++) { 172 | const type = SPIGOT_ELEMENT_OPTIONS[k]; 173 | const option = document.createElement("option"); 174 | option.value = type; 175 | option.text = menuNames[type]; 176 | if (i === k) { 177 | option.selected = "selected"; 178 | SPIGOT_ELEMENTS[i] = type; 179 | } 180 | typeSelector.add(option); 181 | } 182 | for (k = 0; k < SPIGOT_SIZE_OPTIONS.length; k++) { 183 | const size = SPIGOT_SIZE_OPTIONS[k]; 184 | const option = document.createElement("option"); 185 | option.value = size; 186 | option.text = k.toString(10); 187 | if (k === DEFAULT_SPIGOT_SIZE_IDX) { 188 | option.selected = "selected"; 189 | SPIGOT_SIZES[i] = size; 190 | } 191 | sizeSelector.add(option); 192 | } 193 | } 194 | spigotTypes[0].addEventListener("change", function () { 195 | SPIGOT_ELEMENTS[0] = parseInt(spigotTypes[0].value, 10); 196 | }); 197 | spigotTypes[1].addEventListener("change", function () { 198 | SPIGOT_ELEMENTS[1] = parseInt(spigotTypes[1].value, 10); 199 | }); 200 | spigotTypes[2].addEventListener("change", function () { 201 | SPIGOT_ELEMENTS[2] = parseInt(spigotTypes[2].value, 10); 202 | }); 203 | spigotTypes[3].addEventListener("change", function () { 204 | SPIGOT_ELEMENTS[3] = parseInt(spigotTypes[3].value, 10); 205 | }); 206 | spigotSizes[0].addEventListener("change", function () { 207 | SPIGOT_SIZES[0] = parseInt(spigotSizes[0].value, 10); 208 | }); 209 | spigotSizes[1].addEventListener("change", function () { 210 | SPIGOT_SIZES[1] = parseInt(spigotSizes[1].value, 10); 211 | }); 212 | spigotSizes[2].addEventListener("change", function () { 213 | SPIGOT_SIZES[2] = parseInt(spigotSizes[2].value, 10); 214 | }); 215 | spigotSizes[3].addEventListener("change", function () { 216 | SPIGOT_SIZES[3] = parseInt(spigotSizes[3].value, 10); 217 | }); 218 | 219 | /* 'overwrite' checkbox */ 220 | const overwriteCheckbox = document.getElementById("overwriteCheckbox"); 221 | overwriteCheckbox.checked = OVERWRITE_ENABLED; 222 | overwriteCheckbox.addEventListener("click", function () { 223 | OVERWRITE_ENABLED = overwriteCheckbox.checked; 224 | }); 225 | 226 | /* speed slider */ 227 | const speedSlider = document.getElementById("speedSlider"); 228 | speedSlider.min = 0; 229 | speedSlider.max = MAX_FPS; 230 | speedSlider.value = DEFAULT_FPS; 231 | speedSlider.addEventListener("input", function () { 232 | const val = parseInt(speedSlider.value, 10); 233 | /* make 'magnetic' towards the default */ 234 | if (Math.abs(val - DEFAULT_FPS) < 10) speedSlider.value = DEFAULT_FPS; 235 | setFPS(parseInt(speedSlider.value, 10)); 236 | }); 237 | 238 | /* zombie slider */ 239 | const zombieSlider = document.getElementById("zombieSlider"); 240 | zombieSlider.min = 0; 241 | zombieSlider.max = MAX_ZOMBIES; 242 | zombieSlider.value = 0; 243 | zombieSlider.addEventListener("input", function () { 244 | const val = parseInt(zombieSlider.value, 10); 245 | setZombieCount(parseInt(zombieSlider.value, 10)); 246 | }); 247 | 248 | /* clear button */ 249 | const clearButton = document.getElementById("clearButton"); 250 | clearButton.onclick = clearGameCanvas; 251 | 252 | /* save button */ 253 | const saveButton = document.getElementById("saveButton"); 254 | saveButton.onclick = saveGameCanvas; 255 | 256 | /* load button */ 257 | const loadButton = document.getElementById("loadButton"); 258 | loadButton.onclick = loadGameCanvas; 259 | } 260 | 261 | function drawFPSLabel(fps) { 262 | document.getElementById("fps-counter").innerText = "FPS: " + fps; 263 | } 264 | 265 | function drawZombieCount(val) { 266 | document.getElementById("zombieCount").innerText = val; 267 | } 268 | -------------------------------------------------------------------------------- /scripts/particles.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Handling for particle animations. Unlike elements, which are 3 | * represented by colored pixels on the canvas, particles are 4 | * backed by an actual object. This means that we can store state 5 | * for each particle, in order to do things such as complex movement. 6 | * However, this also means that particles are more expensive than 7 | * regular elements, so we use them sparingly (as limited by 8 | * MAX_NUM_PARTICLES). 9 | * 10 | * Copyright (C) 2020, Josh Don 11 | * 12 | * Project Sand is free software: you can redistribute it and/or modify 13 | * it under the terms of the GNU General Public License as published by 14 | * the Free Software Foundation, either version 3 of the License, or 15 | * (at your option) any later version. 16 | * 17 | * Project Sand is distributed in the hope that it will be useful, 18 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 20 | * GNU General Public License for more details. 21 | * 22 | * You should have received a copy of the GNU General Public License 23 | * along with this program. If not, see . 24 | */ 25 | 26 | /* 27 | * ADDING NEW PARTICLES: 28 | * 29 | * 1. Define its particle index below. Pick the next available integer. 30 | * 2. Add its init and action methods to the __particleInit and 31 | * __particleActions arrays. Order here must match the particle indices. 32 | * 3. Implement the init and action methods for your particle. Importantly, 33 | * your action method is responsible for inactivating your particle (ie. 34 | * after a certain number of iterations, or when it is offCanvas()). Use 35 | * particles.makeParticleInactive(particle) for this. 36 | * 4. Your init method sets your particle color; it must pick a 37 | * PAINTABLE_PARTICLE_COLOR. 38 | */ 39 | 40 | /* Offscreen canvas for drawing particles */ 41 | const offscreenParticleCanvas = document.createElement("canvas"); 42 | const offscreenParticleCtx = offscreenParticleCanvas.getContext("2d", { 43 | alpha: false, 44 | }); 45 | 46 | /* These values index into __particleInit and __particleActions arrays */ 47 | const UNKNOWN_PARTICLE = 0; 48 | const NITRO_PARTICLE = 1; 49 | const NAPALM_PARTICLE = 2; 50 | const C4_PARTICLE = 3; 51 | const LAVA_PARTICLE = 4; 52 | const MAGIC1_PARTICLE = 5; /* multi-pronged star */ 53 | const MAGIC2_PARTICLE = 6; /* spiral */ 54 | const METHANE_PARTICLE = 7; 55 | const TREE_PARTICLE = 8; 56 | const CHARGED_NITRO_PARTICLE = 9; 57 | const NUKE_PARTICLE = 10; 58 | 59 | const __particleInit = [ 60 | UNKNOWN_PARTICLE_INIT, 61 | NITRO_PARTICLE_INIT, 62 | NAPALM_PARTICLE_INIT, 63 | C4_PARTICLE_INIT, 64 | LAVA_PARTICLE_INIT, 65 | MAGIC1_PARTICLE_INIT, 66 | MAGIC2_PARTICLE_INIT, 67 | METHANE_PARTICLE_INIT, 68 | TREE_PARTICLE_INIT, 69 | CHARGED_NITRO_PARTICLE_INIT, 70 | NUKE_PARTICLE_INIT, 71 | ]; 72 | Object.freeze(__particleInit); 73 | 74 | const __particleActions = [ 75 | UNKNOWN_PARTICLE_ACTION, 76 | NITRO_PARTICLE_ACTION, 77 | NAPALM_PARTICLE_ACTION, 78 | C4_PARTICLE_ACTION, 79 | LAVA_PARTICLE_ACTION, 80 | MAGIC1_PARTICLE_ACTION, 81 | MAGIC2_PARTICLE_ACTION, 82 | METHANE_PARTICLE_ACTION, 83 | TREE_PARTICLE_ACTION, 84 | CHARGED_NITRO_PARTICLE_ACTION, 85 | NUKE_PARTICLE_ACTION, 86 | ]; 87 | Object.freeze(__particleActions); 88 | 89 | function UNKNOWN_PARTICLE_INIT(particle) {} 90 | function UNKNOWN_PARTICLE_ACTION(particle) { 91 | throw "Unknown particle"; 92 | } 93 | 94 | function NITRO_PARTICLE_INIT(particle) { 95 | particle.setColor(FIRE); 96 | 97 | const velocity = 5 + Math.random() * 10; 98 | const angle = Math.random() * TWO_PI; 99 | particle.setVelocity(velocity, angle); 100 | 101 | particle.size = 2 + Math.random() * 7; 102 | } 103 | 104 | function NITRO_PARTICLE_ACTION(particle) { 105 | offscreenParticleCtx.beginPath(); 106 | offscreenParticleCtx.lineWidth = particle.size; 107 | offscreenParticleCtx.strokeStyle = particle.rgbaColor; 108 | offscreenParticleCtx.lineCap = "round"; 109 | offscreenParticleCtx.moveTo(particle.x, particle.y); 110 | particle.x += particle.xVelocity; 111 | particle.y += particle.yVelocity; 112 | offscreenParticleCtx.lineTo(particle.x, particle.y); 113 | offscreenParticleCtx.stroke(); 114 | 115 | const iterations = particle.actionIterations; 116 | if (iterations % 5 === 0) particle.size /= 1.3; 117 | if (iterations % 15 === 0) particle.yVelocity += 10 * (iterations / 5); 118 | 119 | if (particle.size < 1.75) particles.makeParticleInactive(particle); 120 | else if (particle.offCanvas()) particles.makeParticleInactive(particle); 121 | } 122 | 123 | function NAPALM_PARTICLE_INIT(particle) { 124 | particle.setColor(FIRE); 125 | particle.size = Math.random() * 8 + 6; 126 | particle.xVelocity = Math.random() * 8 - 4; 127 | particle.yVelocity = -1 * (Math.random() * 4 + 4); 128 | particle.maxIterations = Math.floor(Math.random() * 10) + 5; 129 | } 130 | 131 | function NAPALM_PARTICLE_ACTION(particle) { 132 | particle.drawCircle(particle.size); 133 | 134 | particle.x += particle.xVelocity; 135 | particle.y += particle.yVelocity; 136 | particle.size *= 1 + Math.random() * 0.1; 137 | 138 | if (particle.actionIterations > particle.maxIterations) 139 | particles.makeParticleInactive(particle); 140 | } 141 | 142 | function C4_PARTICLE_INIT(particle) { 143 | particle.setColor(FIRE); 144 | const rand = Math.random() * 10000; 145 | if (rand < 9000) { 146 | particle.size = Math.random() * 10 + 3; 147 | } else if (rand < 9500) { 148 | particle.size = Math.random() * 32 + 3; 149 | } else if (rand < 9800) { 150 | particle.size = Math.random() * 64 + 3; 151 | } else { 152 | particle.size = Math.random() * 128 + 3; 153 | } 154 | } 155 | 156 | function C4_PARTICLE_ACTION(particle) { 157 | particle.drawCircle(particle.size); 158 | 159 | if (particle.actionIterations % 3 === 0) { 160 | particle.size /= 3; 161 | if (particle.size <= 1) particles.makeParticleInactive(particle); 162 | } 163 | } 164 | 165 | function LAVA_PARTICLE_INIT(particle) { 166 | particle.setColor(FIRE); 167 | /* Make it harder for the angle to be steep */ 168 | var angle = QUARTER_PI + Math.random() * HALF_PI; 169 | if (random() < 75 && Math.abs(HALF_PI - angle) < EIGHTEENTH_PI) 170 | angle += EIGHTEENTH_PI * (angle > HALF_PI ? 1 : -1); 171 | 172 | particle.xVelocity = (1 + Math.random() * 3) * Math.cos(angle); 173 | particle.yVelocity = (-4 * Math.random() - 3) * Math.sin(angle); 174 | particle.initYVelocity = particle.yVelocity; 175 | particle.yAcceleration = 0.06; 176 | 177 | particle.size = 4 + Math.random() * 3; 178 | particle.y -= particle.size; 179 | } 180 | 181 | function LAVA_PARTICLE_ACTION(particle) { 182 | offscreenParticleCtx.beginPath(); 183 | offscreenParticleCtx.lineWidth = particle.size; 184 | offscreenParticleCtx.strokeStyle = particle.rgbaColor; 185 | offscreenParticleCtx.lineCap = "round"; 186 | offscreenParticleCtx.moveTo(particle.x, particle.y); 187 | 188 | const iterations = particle.actionIterations; 189 | particle.x += particle.xVelocity; 190 | particle.y = 191 | particle.initY + 192 | particle.initYVelocity * iterations + 193 | (particle.yAcceleration * iterations * iterations) / 2; 194 | 195 | offscreenParticleCtx.lineTo(particle.x, particle.y); 196 | offscreenParticleCtx.stroke(); 197 | 198 | /* Allow particle to exist "above" the canvas */ 199 | if (particle.x < 0 || particle.x > MAX_X_IDX || particle.y > MAX_Y_IDX) { 200 | particles.makeParticleInactive(particle); 201 | return; 202 | } 203 | 204 | /* possible extinguish due to water, lava, rock, ice, or wall */ 205 | if (random() < 25) { 206 | /* Need to update yVelocity before calling aboutToHit() */ 207 | particle.yVelocity = 208 | particle.initYVelocity + particle.yAcceleration * iterations; 209 | const touchingColor = particle.aboutToHit(); 210 | 211 | var replaceColor = -1; 212 | if (touchingColor === WATER || touchingColor === SALT_WATER) { 213 | if (random() < 58) replaceColor = ROCK; 214 | } else if (touchingColor === LAVA || touchingColor === ROCK) { 215 | if (random() < 75) replaceColor = LAVA; 216 | } else if ( 217 | touchingColor === ICE || 218 | touchingColor === CHILLED_ICE || 219 | touchingColor === CRYO 220 | ) { 221 | if (random() < 70) replaceColor = ROCK; 222 | } else if (touchingColor === WALL) { 223 | if (random() < 25) replaceColor = LAVA; 224 | } 225 | 226 | if (replaceColor !== -1) { 227 | particle.setColor(replaceColor); 228 | particle.drawCircle(particle.size / 2); 229 | particles.makeParticleInactive(particle); 230 | return; 231 | } 232 | } 233 | } 234 | 235 | function MAGIC1_PARTICLE_INIT(particle) { 236 | if (!particle.reinitialized) particle.setRandomColor(MAGIC_COLORS); 237 | 238 | var numSpokes = 5 + Math.round(Math.random() * 13); 239 | const spokes = [particle]; 240 | var i; 241 | for (i = 1; i !== numSpokes; i++) { 242 | /* 243 | * Temporarily set type to UNKNOWN_PARTICLE so that we don't 244 | * recurse back into this function. 245 | */ 246 | const newSpoke = particles.addActiveParticle( 247 | UNKNOWN_PARTICLE, 248 | particle.x, 249 | particle.y, 250 | particle.i 251 | ); 252 | if (!newSpoke) break; 253 | 254 | /* 255 | * We're manually changing the particle type; ensure that our 256 | * particle counts don't get corrupted. 257 | */ 258 | particles.particleCounts[newSpoke.type]--; 259 | particles.particleCounts[MAGIC1_PARTICLE]++; 260 | 261 | newSpoke.type = MAGIC1_PARTICLE; 262 | newSpoke.setColor(particle.color); 263 | spokes.push(newSpoke); 264 | } 265 | numSpokes = spokes.length; 266 | 267 | const angle = TWO_PI / numSpokes; 268 | const velocity = 7 + Math.random() * 3; 269 | const spokeSize = 4 + Math.random() * 4; 270 | 271 | var currAngle = 0; 272 | for (i = 0; i !== numSpokes; i++) { 273 | const spoke = spokes[i]; 274 | spoke.setVelocity(velocity, currAngle); 275 | spoke.size = spokeSize; 276 | currAngle += angle; 277 | } 278 | } 279 | 280 | function MAGIC1_PARTICLE_ACTION(particle) { 281 | offscreenParticleCtx.beginPath(); 282 | offscreenParticleCtx.lineWidth = particle.size; 283 | offscreenParticleCtx.strokeStyle = particle.rgbaColor; 284 | offscreenParticleCtx.lineCap = "square"; 285 | offscreenParticleCtx.moveTo(particle.x, particle.y); 286 | particle.x += particle.xVelocity; 287 | particle.y += particle.yVelocity; 288 | offscreenParticleCtx.lineTo(particle.x, particle.y); 289 | offscreenParticleCtx.stroke(); 290 | 291 | if (particle.offCanvas()) particles.makeParticleInactive(particle); 292 | } 293 | 294 | function MAGIC2_PARTICLE_INIT(particle) { 295 | particle.setRandomColor(MAGIC_COLORS); 296 | 297 | particle.size = 4 + Math.random() * 8; 298 | particle.x = Math.floor(width / 2); 299 | particle.y = Math.floor(height / 2); 300 | particle.initX = particle.x; 301 | particle.initY = particle.y; 302 | particle.magic_2_max_radius = 303 | Math.sqrt(width * width + height * height) / 2 + particle.size; 304 | particle.magic_2_theta = 0; 305 | particle.magic_2_speed = 20; 306 | particle.magic_2_radius_spacing = 25 + Math.random() * 55; 307 | particle.magic_2_radius = particle.magic_2_radius_spacing; 308 | } 309 | 310 | function MAGIC2_PARTICLE_ACTION(particle) { 311 | offscreenParticleCtx.beginPath(); 312 | offscreenParticleCtx.lineWidth = particle.size; 313 | offscreenParticleCtx.strokeStyle = particle.rgbaColor; 314 | offscreenParticleCtx.lineCap = "round"; 315 | offscreenParticleCtx.moveTo(particle.x, particle.y); 316 | 317 | const newTheta = 318 | particle.magic_2_theta + particle.magic_2_speed / particle.magic_2_radius; 319 | particle.magic_2_theta = newTheta; 320 | const newRadius = 321 | (particle.magic_2_theta / TWO_PI) * particle.magic_2_radius_spacing; 322 | particle.magic_2_radius = newRadius; 323 | 324 | particle.x = newRadius * Math.cos(newTheta) + particle.initX; 325 | particle.y = newRadius * Math.sin(newTheta) + particle.initY; 326 | 327 | offscreenParticleCtx.lineTo(particle.x, particle.y); 328 | offscreenParticleCtx.stroke(); 329 | 330 | if (newRadius > particle.magic_2_max_radius) 331 | particles.makeParticleInactive(particle); 332 | } 333 | 334 | function METHANE_PARTICLE_INIT(particle) { 335 | particle.setColor(FIRE); 336 | particle.size = 10 + Math.random() * 10; 337 | } 338 | 339 | function METHANE_PARTICLE_ACTION(particle) { 340 | const iterations = particle.actionIterations; 341 | 342 | particle.drawCircle(particle.size); 343 | 344 | if (iterations > 2) particles.makeParticleInactive(particle); 345 | } 346 | 347 | class TreeType { 348 | constructor() { 349 | throw "Should never actually instantiate this."; 350 | } 351 | 352 | /** @nocollapse */ 353 | static initTreeParticle(p, oldP) {} 354 | 355 | /** @nocollapse */ 356 | static branchAngles(treeParticle) { 357 | throw "Branch angles not implemented."; 358 | } 359 | 360 | /** @nocollapse */ 361 | static branchSpacingFactor(treeParticle) { 362 | throw "Branch spacing factor not implemented."; 363 | } 364 | } 365 | 366 | /* Standard tree */ 367 | class Tree0 extends TreeType { 368 | /** @nocollapse */ 369 | static branchAngles(treeParticle) { 370 | const branchAngle = EIGHTH_PI + Math.random() * QUARTER_PI; 371 | return [treeParticle.angle + branchAngle, treeParticle.angle - branchAngle]; 372 | } 373 | 374 | /** @nocollapse */ 375 | static branchSpacingFactor(treeParticle) { 376 | return 0.9; 377 | } 378 | } 379 | 380 | /* Single branch */ 381 | class Tree1 extends TreeType { 382 | /** @nocollapse */ 383 | static initTreeParticle(p, oldP) { 384 | const branchDirection = oldP 385 | ? oldP.branchDirection 386 | : random() < 50 387 | ? 1 388 | : -1; 389 | p.branchDirection = branchDirection; 390 | } 391 | 392 | /** @nocollapse */ 393 | static branchAngles(treeParticle) { 394 | const branchAngle = 395 | (EIGHTH_PI + Math.random() * EIGHTH_PI) * treeParticle.branchDirection; 396 | return [treeParticle.angle + branchAngle, treeParticle.angle]; 397 | } 398 | 399 | /** @nocollapse */ 400 | static branchSpacingFactor(treeParticle) { 401 | return 0.7; 402 | } 403 | } 404 | 405 | /* Lots of shallow angle branching */ 406 | class Tree2 extends TreeType { 407 | /** @nocollapse */ 408 | static branchAngles(treeParticle) { 409 | const branchAngle = Math.random() * SIXTEENTH_PI + EIGHTH_PI; 410 | return [ 411 | treeParticle.angle, 412 | treeParticle.angle + branchAngle, 413 | treeParticle.angle - branchAngle, 414 | ]; 415 | } 416 | 417 | /** @nocollapse */ 418 | static branchSpacingFactor(treeParticle) { 419 | return 0.6; 420 | } 421 | } 422 | 423 | const TREE_TYPES = [ 424 | Tree0, 425 | /* A little too cluttered to include Tree1 */ 426 | /* Tree1, */ 427 | Tree2, 428 | ]; 429 | const NUM_TREE_TYPES = TREE_TYPES.length; 430 | 431 | function TREE_PARTICLE_INIT(particle) { 432 | particle.setColor(BRANCH); 433 | particle.size = random() < 50 ? 3 : 4; 434 | 435 | const velocity = 1 + Math.random() * 0.5; 436 | const angle = -1 * (HALF_PI + EIGHTH_PI - Math.random() * QUARTER_PI); 437 | particle.setVelocity(velocity, angle); 438 | particle.generation = 1; 439 | particle.branchSpacing = 15 + Math.round(Math.random() * 45); 440 | particle.maxBranches = 1 + Math.round(Math.random() * 2); 441 | particle.nextBranch = particle.branchSpacing; 442 | particle.branches = 0; 443 | 444 | /* make it more likely to be a standard tree */ 445 | if (random() < 62) { 446 | particle.treeType = 0; 447 | } else { 448 | particle.treeType = 1 + Math.floor(Math.random() * NUM_TREE_TYPES - 1); 449 | } 450 | 451 | TREE_TYPES[particle.treeType].initTreeParticle(particle, null); 452 | } 453 | 454 | function TREE_PARTICLE_ACTION(particle) { 455 | offscreenParticleCtx.beginPath(); 456 | offscreenParticleCtx.lineWidth = particle.size; 457 | offscreenParticleCtx.strokeStyle = particle.rgbaColor; 458 | offscreenParticleCtx.lineCap = "round"; 459 | offscreenParticleCtx.moveTo(particle.x, particle.y); 460 | particle.x += particle.xVelocity; 461 | particle.y += particle.yVelocity; 462 | offscreenParticleCtx.lineTo(particle.x, particle.y); 463 | offscreenParticleCtx.stroke(); 464 | 465 | /* Don't grow through WALL */ 466 | if (particle.aboutToHit() === WALL) { 467 | particles.makeParticleInactive(particle); 468 | return; 469 | } 470 | 471 | const iterations = particle.actionIterations; 472 | 473 | if (iterations >= particle.nextBranch) { 474 | particle.branches++; 475 | 476 | if (particle.maxBranches === 0) { 477 | particles.makeParticleInactive(particle); 478 | return; 479 | } 480 | 481 | const leafBranch = 482 | particle.color === LEAF || particle.branches === particle.maxBranches; 483 | 484 | const treeInfo = TREE_TYPES[particle.treeType]; 485 | const branchAngles = treeInfo.branchAngles(particle); 486 | const numBranches = branchAngles.length; 487 | for (var i = 0; i < numBranches; i++) { 488 | const b = particles.addActiveParticle( 489 | TREE_PARTICLE, 490 | particle.x, 491 | particle.y, 492 | particle.i 493 | ); 494 | if (!b) break; 495 | b.generation = particle.generation + 1; 496 | b.maxBranches = Math.max(0, particle.maxBranches - 1); 497 | b.branchSpacing = 498 | particle.branchSpacing * treeInfo.branchSpacingFactor(particle); 499 | b.nextBranch = b.branchSpacing; 500 | b.angle = branchAngles[i]; 501 | b.setVelocity(particle.velocity, b.angle); 502 | b.size = Math.max(particle.size - 1, 2); 503 | b.treeType = particle.treeType; 504 | treeInfo.initTreeParticle(b, particle); 505 | 506 | if (leafBranch) b.setColor(LEAF); 507 | } 508 | 509 | if (particle.branches >= particle.maxBranches) { 510 | particles.makeParticleInactive(particle); 511 | return; 512 | } 513 | 514 | if (particle.branchSpacing > 45) particle.branchSpacing *= 0.8; 515 | particle.nextBranch = 516 | iterations + particle.branchSpacing * (Math.random() * 0.35 + 0.65); 517 | } 518 | } 519 | 520 | function CHARGED_NITRO_PARTICLE_INIT(particle) { 521 | particle.setColor(FIRE); 522 | particle.size = 4; 523 | particle.xVelocity = 0; 524 | particle.yVelocity = -100; 525 | 526 | /* Search upwards for a WALL collision (but don't check every pixel) */ 527 | particle.minY = -1; 528 | const step = (3 + Math.round(Math.random() * 2)) * width; 529 | for (var idx = particle.i; idx > -1; idx -= step) { 530 | if (gameImagedata32[idx] === WALL) { 531 | particle.minY = idx / width; 532 | break; 533 | } 534 | } 535 | } 536 | 537 | function CHARGED_NITRO_PARTICLE_ACTION(particle) { 538 | offscreenParticleCtx.beginPath(); 539 | offscreenParticleCtx.lineWidth = particle.size; 540 | offscreenParticleCtx.strokeStyle = particle.rgbaColor; 541 | offscreenParticleCtx.lineCap = "square"; 542 | offscreenParticleCtx.moveTo(particle.initX, particle.initY); 543 | particle.x += particle.xVelocity; 544 | particle.y = Math.max(particle.minY, particle.y + particle.yVelocity); 545 | offscreenParticleCtx.lineTo(particle.x, particle.y); 546 | offscreenParticleCtx.stroke(); 547 | 548 | if (particle.y <= particle.minY || particle.offCanvas()) { 549 | particles.makeParticleInactive(particle); 550 | return; 551 | } 552 | } 553 | 554 | function NUKE_PARTICLE_INIT(particle) { 555 | particle.setColor(FIRE); 556 | const maxDimension = Math.max(width, height); 557 | particle.size = maxDimension / 4 + (Math.random() * maxDimension) / 8; 558 | } 559 | 560 | function NUKE_PARTICLE_ACTION(particle) { 561 | particle.drawCircle(particle.size); 562 | 563 | if (particle.actionIterations > 4) particles.makeParticleInactive(particle); 564 | } 565 | 566 | class Particle { 567 | constructor() { 568 | this.type = UNKNOWN_PARTICLE; 569 | this.initX = -1; 570 | this.initY = -1; 571 | this.x = -1; 572 | this.y = -1; 573 | this.i = -1; 574 | this.color = 0; 575 | this.rgbaColor = "rgba(0, 0, 0, 1)"; 576 | this.velocity = 0; 577 | this.angle = 0; 578 | this.xVelocity = 0; 579 | this.yVelocity = 0; 580 | this.size = 0; 581 | this.actionIterations = 0; 582 | this.active = false; 583 | this.next = null; 584 | this.prev = null; 585 | this.reinitialized = false; 586 | } 587 | 588 | setColor(hexColor) { 589 | if (!Particle.warned_unpaintable_color) { 590 | if (!(hexColor in PAINTABLE_PARTICLE_COLORS)) { 591 | console.log("Unpaintable particle color: " + hexColor); 592 | Particle.warned_unpaintable_color = true; 593 | } 594 | } 595 | 596 | this.color = hexColor; 597 | 598 | const r = hexColor & 0xff; 599 | const g = (hexColor & 0xff00) >>> 8; 600 | const b = (hexColor & 0xff0000) >>> 16; 601 | this.rgbaColor = "rgba(" + r + "," + g + "," + b + ", 1)"; 602 | } 603 | 604 | setRandomColor(whitelist) { 605 | const colorIdx = Math.floor(Math.random() * whitelist.length); 606 | this.setColor(whitelist[colorIdx]); 607 | } 608 | 609 | offCanvas() { 610 | const x = this.x; 611 | const y = this.y; 612 | return x < 0 || x > MAX_X_IDX || y < 0 || y > MAX_Y_IDX; 613 | } 614 | 615 | setVelocity(velocity, angle) { 616 | this.velocity = velocity; 617 | this.angle = angle; 618 | this.xVelocity = velocity * Math.cos(angle); 619 | this.yVelocity = velocity * Math.sin(angle); 620 | } 621 | 622 | /* 623 | * For a spherical particle on a trajectory, figure out what element the 624 | * particle is about to hit (right at its tip). 625 | * 626 | * Expects caller has updated particle's x and y velocity. 627 | */ 628 | aboutToHit() { 629 | const radius = this.size / 2; 630 | const theta = Math.atan2(this.yVelocity, this.xVelocity); 631 | const xPrime = this.x + Math.cos(theta) * radius; 632 | const yPrime = this.y + Math.sin(theta) * radius; 633 | const idx = Math.round(xPrime) + Math.round(yPrime) * width; 634 | 635 | if (idx < 0 || idx > MAX_IDX) return BACKGROUND; 636 | 637 | return gameImagedata32[idx]; 638 | } 639 | 640 | drawCircle(radius) { 641 | offscreenParticleCtx.beginPath(); 642 | offscreenParticleCtx.lineWidth = 0; 643 | offscreenParticleCtx.fillStyle = this.rgbaColor; 644 | offscreenParticleCtx.arc(this.x, this.y, radius, 0, TWO_PI); 645 | offscreenParticleCtx.fill(); 646 | } 647 | } 648 | 649 | Particle.warned_unpaintable_color = false; 650 | 651 | /* 652 | * Two doubly-linked lists: one for active and one for 653 | * inactive particles 654 | */ 655 | class ParticleList { 656 | constructor() { 657 | this.activeHead = null; 658 | this.activeSize = 0; 659 | this.inactiveHead = null; 660 | this.inactiveSize = 0; 661 | this.particleCounts = new Uint32Array(__particleInit.length); 662 | 663 | /* This probably isn't necessary, but I don't trust javascript */ 664 | for (var i = 0; i < this.particleCounts.length; i++) { 665 | this.particleCounts[i] = 0; 666 | } 667 | } 668 | 669 | addActiveParticle(type, x, y, i) { 670 | if (this.inactiveSize === 0) return null; 671 | 672 | const particle = this.inactiveHead; 673 | this.inactiveHead = this.inactiveHead.next; 674 | if (this.inactiveHead) this.inactiveHead.prev = null; 675 | this.inactiveSize--; 676 | 677 | if (!this.activeHead) { 678 | particle.next = null; 679 | particle.prev = null; 680 | this.activeHead = particle; 681 | } else { 682 | this.activeHead.prev = particle; 683 | particle.next = this.activeHead; 684 | particle.prev = null; 685 | this.activeHead = particle; 686 | } 687 | this.activeSize++; 688 | 689 | particle.active = true; 690 | particle.reinitialized = false; 691 | particle.actionIterations = 0; 692 | particle.type = type; 693 | particle.initX = x; 694 | particle.initY = y; 695 | particle.x = x; 696 | particle.y = y; 697 | particle.i = i; 698 | this.particleCounts[type]++; 699 | __particleInit[type](particle); 700 | 701 | return particle; 702 | } 703 | 704 | makeParticleInactive(particle) { 705 | particle.active = false; 706 | this.particleCounts[particle.type]--; 707 | particle.type = UNKNOWN_PARTICLE; 708 | if (particle.prev) { 709 | particle.prev.next = particle.next; 710 | } 711 | if (particle.next) { 712 | particle.next.prev = particle.prev; 713 | } 714 | if (particle === this.activeHead) { 715 | this.activeHead = particle.next; 716 | } 717 | this.activeSize--; 718 | 719 | if (!this.inactiveHead) { 720 | particle.next = null; 721 | particle.prev = null; 722 | this.inactiveHead = particle; 723 | } else { 724 | this.inactiveHead.prev = particle; 725 | particle.next = this.inactiveHead; 726 | particle.prev = null; 727 | this.inactiveHead = particle; 728 | } 729 | this.inactiveSize++; 730 | } 731 | 732 | inactivateAll() { 733 | var particle = this.activeHead; 734 | while (particle) { 735 | const next = particle.next; 736 | this.makeParticleInactive(particle); 737 | particle = next; 738 | } 739 | } 740 | 741 | reinitializeParticle(particle, newType) { 742 | if (!particle.active) throw "Can only be used with active particles"; 743 | 744 | this.particleCounts[particle.type]--; 745 | this.particleCounts[newType]++; 746 | particle.type = newType; 747 | particle.reinitialized = true; 748 | __particleInit[newType](particle); 749 | } 750 | 751 | particleActive(particleType) { 752 | return this.particleCounts[particleType] > 0; 753 | } 754 | } 755 | 756 | const particles = new ParticleList(); 757 | 758 | /* 759 | * When we copy the particle strokes to the main canvas, some 760 | * of the colors will not match any elements (due to anti-aliasing 761 | * of the stroke). We need a fast way to know if a given color is 762 | * a valid color for painting. Hence, this dictionary of colors that can 763 | * be copied from the particle canvas to the main canvas. 764 | */ 765 | const PAINTABLE_PARTICLE_COLORS = {}; 766 | 767 | const MAGIC_COLORS = []; 768 | 769 | function initParticles() { 770 | if (__particleInit.length !== __particleActions.length) 771 | throw "Particle arrays must be same length"; 772 | 773 | var numParticlesToCreate = MAX_NUM_PARTICLES; 774 | var prevParticle; 775 | 776 | /* Setup the head */ 777 | particles.inactiveHead = new Particle(); 778 | particles.inactiveSize++; 779 | prevParticle = particles.inactiveHead; 780 | numParticlesToCreate--; 781 | 782 | /* 783 | * We pre-allocate all of the particles, rather than create them on demand. 784 | * This avoids latency spikes due to garbage collection reap. It does require 785 | * that we use two linked lists to keep track of them all, but that's fine. 786 | */ 787 | while (numParticlesToCreate > 0) { 788 | const particle = new Particle(); 789 | 790 | particle.prev = prevParticle; 791 | prevParticle.next = particle; 792 | particles.inactiveSize++; 793 | 794 | prevParticle = particle; 795 | 796 | numParticlesToCreate--; 797 | } 798 | 799 | offscreenParticleCanvas.width = width; 800 | offscreenParticleCanvas.height = height; 801 | 802 | PAINTABLE_PARTICLE_COLORS[FIRE] = null; 803 | PAINTABLE_PARTICLE_COLORS[WALL] = null; 804 | PAINTABLE_PARTICLE_COLORS[ROCK] = null; 805 | PAINTABLE_PARTICLE_COLORS[LAVA] = null; 806 | PAINTABLE_PARTICLE_COLORS[PLANT] = null; 807 | PAINTABLE_PARTICLE_COLORS[SPOUT] = null; 808 | PAINTABLE_PARTICLE_COLORS[WELL] = null; 809 | PAINTABLE_PARTICLE_COLORS[WAX] = null; 810 | PAINTABLE_PARTICLE_COLORS[ICE] = null; 811 | PAINTABLE_PARTICLE_COLORS[BRANCH] = null; 812 | PAINTABLE_PARTICLE_COLORS[LEAF] = null; 813 | Object.freeze(PAINTABLE_PARTICLE_COLORS); 814 | 815 | /* All of these are also in PAINTABLE_PARTICLE_COLORS */ 816 | MAGIC_COLORS.push(WALL); 817 | MAGIC_COLORS.push(PLANT); 818 | MAGIC_COLORS.push(SPOUT); 819 | MAGIC_COLORS.push(WELL); 820 | MAGIC_COLORS.push(WAX); 821 | MAGIC_COLORS.push(ICE); 822 | Object.freeze(MAGIC_COLORS); 823 | } 824 | 825 | function updateParticles() { 826 | if (!particles.activeHead) return; 827 | 828 | const canvasWidth = offscreenParticleCanvas.width; 829 | const canvasHeight = offscreenParticleCanvas.height; 830 | 831 | /* reset the particle canvas */ 832 | offscreenParticleCtx.beginPath(); 833 | offscreenParticleCtx.fillStyle = "rgba(0, 0, 0, 1)"; 834 | offscreenParticleCtx.rect(0, 0, canvasWidth, canvasHeight); 835 | offscreenParticleCtx.fill(); 836 | 837 | /* perform particle actions */ 838 | var particle = particles.activeHead; 839 | while (particle) { 840 | /* grab next before doing action, as next could change */ 841 | const next = particle.next; 842 | particle.actionIterations++; 843 | __particleActions[particle.type](particle); 844 | particle = next; 845 | } 846 | 847 | /* move particle draw state to main canvas */ 848 | const particleImageData = offscreenParticleCtx.getImageData( 849 | 0, 850 | 0, 851 | canvasWidth, 852 | canvasHeight 853 | ); 854 | const particleImageData32 = new Uint32Array(particleImageData.data.buffer); 855 | var x, y; 856 | var __yOffset = 0; 857 | const aliasingSearchDistance = 3; 858 | for (y = 0; y !== canvasHeight; y++) { 859 | const yOffset = __yOffset; /* optimization: make const copy */ 860 | for (x = 0; x !== canvasWidth; x++) { 861 | const i = x + yOffset; 862 | const particleColor = particleImageData32[i]; 863 | 864 | if (particleColor === 0xff000000) continue; 865 | 866 | /* 867 | * ImageData will container other colors due to anti-aliasing. 868 | * However, we can only copy over valid colors to the main canvas. 869 | * 870 | * If the color appears to be invalid, it is likely right along the 871 | * edge of a valid color. In this case, we can search nearby pixels 872 | * for such a color. 873 | * 874 | * The motivation for this is that when many overlapping shapes are 875 | * drawn on the canvas (ie. the various particles), the aliased border 876 | * of each sub-object created gaps of invalid colors. 877 | */ 878 | if (particleColor in PAINTABLE_PARTICLE_COLORS) { 879 | gameImagedata32[i] = particleColor; 880 | continue; 881 | } else { 882 | var searchColor; 883 | if (x - aliasingSearchDistance >= 0) { 884 | searchColor = particleImageData32[i - aliasingSearchDistance]; 885 | if (searchColor in PAINTABLE_PARTICLE_COLORS) { 886 | gameImagedata32[i] = searchColor; 887 | continue; 888 | } 889 | } 890 | if (x + aliasingSearchDistance <= MAX_X_IDX) { 891 | searchColor = particleImageData32[i + aliasingSearchDistance]; 892 | if (searchColor in PAINTABLE_PARTICLE_COLORS) { 893 | gameImagedata32[i] = searchColor; 894 | continue; 895 | } 896 | } 897 | if (y - aliasingSearchDistance >= 0) { 898 | searchColor = particleImageData32[i - aliasingSearchDistance * width]; 899 | if (searchColor in PAINTABLE_PARTICLE_COLORS) { 900 | gameImagedata32[i] = searchColor; 901 | continue; 902 | } 903 | } 904 | if (y + aliasingSearchDistance <= MAX_Y_IDX) { 905 | searchColor = particleImageData32[i + aliasingSearchDistance * width]; 906 | if (searchColor in PAINTABLE_PARTICLE_COLORS) { 907 | gameImagedata32[i] = searchColor; 908 | continue; 909 | } 910 | } 911 | } 912 | } 913 | __yOffset += canvasWidth; 914 | } 915 | } 916 | -------------------------------------------------------------------------------- /scripts/softBody.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Interaction with matter.js. 3 | * 4 | * Copyright (C) 2025, Josh Don 5 | * 6 | * Project Sand is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * Project Sand is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | 20 | /* 21 | * This encapsulates all soft body animations (which are driven by matter.js), 22 | * such as zombies.js. 23 | * 24 | * To learn how matter.js works, I recommend reading the source code: 25 | * https://github.com/liabru/matter-js 26 | */ 27 | 28 | const softBodyEngine = Matter.Engine.create(); /* The global matter.js engine */ 29 | 30 | /* 31 | * Offscreen canvas for drawing soft body animations. We draw on 32 | * this canvas and then transfer the data to the main 33 | * canvas. 34 | */ 35 | const softBodyCanvas = document.createElement("canvas"); 36 | softBodyCanvas.width = width; 37 | softBodyCanvas.height = height; 38 | const softBodyCtx = softBodyCanvas.getContext("2d", { alpha: false }); 39 | 40 | /* 41 | * Globals for handling mouse interaction (ie. dragging the 42 | * soft bodies). 43 | */ 44 | var softBodyDragStart = 0; /* timestamp in milliseconds */ 45 | var softBodyFreeDrag = false; /* whether the dragged body should ignore collisions with canvas elements */ 46 | var softBodyMouse; 47 | var softBodyMouseConstraint; 48 | 49 | /* ======================= game.js API ====================== */ 50 | 51 | /* Initialize all soft body elements */ 52 | function initSoftBody() { 53 | softBodyEngine.gravity.scale = 0.0002; /* library default is 0.001 */ 54 | 55 | /* 56 | * These are the 4 walls that bound the animation to the canvas frame 57 | */ 58 | const wallDepth = 60; /* a fairly arbitrary value, to prevent clipping */ 59 | const categoryIgnoreMouse = Matter.Body.nextCategory(); 60 | const options = { 61 | isStatic: true, 62 | collisionFilter: { category: categoryIgnoreMouse }, 63 | }; 64 | var topWall = Matter.Bodies.rectangle(width / 2, -wallDepth / 2, width * 1.2, wallDepth, options); 65 | var bottomWall = Matter.Bodies.rectangle(width / 2, height + wallDepth / 2, width * 1.2, wallDepth, options); 66 | var leftWall = Matter.Bodies.rectangle(-wallDepth / 2, height / 2, wallDepth, height * 1.2, options); 67 | var rightWall = Matter.Bodies.rectangle(width + wallDepth / 2, height / 2, wallDepth, height * 1.2, options); 68 | 69 | Matter.Composite.add(softBodyEngine.world, [ 70 | topWall, 71 | bottomWall, 72 | leftWall, 73 | rightWall, 74 | ]); 75 | 76 | /* 77 | * Add mouse handler to allow user to drag soft bodies around. 78 | */ 79 | softBodyMouse = Matter.Mouse.create(document.getElementById("mainCanvas")); 80 | softBodyMouseConstraint = Matter.MouseConstraint.create(softBodyEngine, { 81 | mouse: softBodyMouse, 82 | constraint: { 83 | stiffness: 0.2, 84 | render: { 85 | visible: false, 86 | }, 87 | }, 88 | /* We need to prevent the mouse from interacting with these invisible boundary walls */ 89 | collisionFilter: { 90 | mask: ~categoryIgnoreMouse 91 | }, 92 | }); 93 | /* 94 | * We're attaching the mouse to the main canvas, which is not the same 95 | * size as the internal game canvas. They differ in scaling by the pixel 96 | * ratio. 97 | */ 98 | Matter.Mouse.setScale(softBodyMouse, { 99 | x: 1.0 / window.devicePixelRatio, 100 | y: 1.0 / window.devicePixelRatio, 101 | }); 102 | Matter.Composite.add(softBodyEngine.world, [softBodyMouseConstraint]); 103 | 104 | Matter.Events.on(softBodyMouseConstraint, "startdrag", (event) => { 105 | softBodyDragStart = Date.now(); 106 | softBodyFreeDrag = false; 107 | }); 108 | /* 109 | * Note: this fires for all mouse up events, even when we weren't 110 | * previously dragging. 111 | */ 112 | Matter.Events.on(softBodyMouseConstraint, "mouseup", (event) => { 113 | softBodyDragStart = 0; 114 | }); 115 | } 116 | 117 | /* Advance the animation of all soft bodies by the given amount of milliseconds */ 118 | function softBodyAnimate(milliseconds) { 119 | const now = Date.now(); 120 | const numZombies = zombies.length; 121 | for (var i = 0; i < numZombies; i++) { 122 | zombies[i].animate(now, i, milliseconds); 123 | } 124 | 125 | Matter.Engine.update(softBodyEngine, milliseconds); 126 | } 127 | 128 | /* Render all soft bodies onto the main canvas */ 129 | function softBodyRender() { 130 | var normalZombies = []; 131 | var wetZombies = []; 132 | var burningZombies = []; 133 | var frozenZombies = []; 134 | 135 | const numZombies = zombies.length; 136 | for (var i = 0; i < numZombies; i++) { 137 | var zombie = zombies[i]; 138 | const state = zombie.state; 139 | if (state === ZOMBIE_STATE_NORMAL) { 140 | normalZombies.push(zombie); 141 | } else if (state === ZOMBIE_STATE_WET) { 142 | wetZombies.push(zombie); 143 | } else if (state === ZOMBIE_STATE_BURNING) { 144 | burningZombies.push(zombie); 145 | } else if (state === ZOMBIE_STATE_FROZEN) { 146 | frozenZombies.push(zombie); 147 | } else { 148 | throw "unexpected state"; 149 | } 150 | } 151 | 152 | if (normalZombies.length) { 153 | drawZombies(normalZombies, ZOMBIE); 154 | } 155 | if (wetZombies.length) { 156 | drawZombies(wetZombies, ZOMBIE_WET); 157 | } 158 | if (burningZombies.length) { 159 | drawZombies(burningZombies, ZOMBIE_BURNING); 160 | } 161 | if (frozenZombies.length) { 162 | drawZombies(frozenZombies, ZOMBIE_FROZEN); 163 | } 164 | } 165 | 166 | /* ======================= Soft Body APIs ====================== */ 167 | 168 | /* Draw the given matter.js body onto the provided `ctx`. */ 169 | function drawBody(ctx, body) { 170 | const vertices = body.vertices; 171 | 172 | ctx.moveTo(vertices[0].x, vertices[0].y); 173 | 174 | for (var j = 1; j < vertices.length; j += 1) { 175 | ctx.lineTo(vertices[j].x, vertices[j].y); 176 | } 177 | 178 | ctx.lineTo(vertices[0].x, vertices[0].y); 179 | } 180 | 181 | -------------------------------------------------------------------------------- /scripts/spigots.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Handling for the four primary game spigots. 3 | * 4 | * Copyright (C) 2020, Josh Don 5 | * 6 | * Project Sand is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * Project Sand is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | 20 | /* Menu options for the spigots */ 21 | const SPIGOT_ELEMENT_OPTIONS = [ 22 | SAND, 23 | WATER, 24 | SALT, 25 | OIL, 26 | GUNPOWDER, 27 | NITRO, 28 | NAPALM, 29 | CONCRETE, 30 | LAVA, 31 | CRYO, 32 | ACID, 33 | MYSTERY, 34 | ]; 35 | const SPIGOT_SIZE_OPTIONS = [0, 5, 10, 15, 20, 25]; 36 | const DEFAULT_SPIGOT_SIZE_IDX = 1; 37 | 38 | /* Type and size of each spigot. Controlled via the menu. */ 39 | const SPIGOT_ELEMENTS = [SAND, WATER, SALT, OIL]; 40 | const SPIGOT_SIZES = []; 41 | 42 | const SPIGOT_HEIGHT = 10; 43 | const MAX_SPIGOT_WIDTH = Math.max(...SPIGOT_SIZE_OPTIONS); 44 | const NUM_SPIGOTS = SPIGOT_ELEMENTS.length; 45 | const SPIGOT_SPACING = Math.round( 46 | (width - MAX_SPIGOT_WIDTH * NUM_SPIGOTS) / (NUM_SPIGOTS + 1) + 47 | MAX_SPIGOT_WIDTH 48 | ); 49 | const SPIGOTS_ENABLED = 50 | MAX_SPIGOT_WIDTH * NUM_SPIGOTS <= width && SPIGOT_HEIGHT <= height; 51 | 52 | function initSpigots() { 53 | const defaultSize = SPIGOT_SIZE_OPTIONS[DEFAULT_SPIGOT_SIZE_IDX]; 54 | for (var i = 0; i !== NUM_SPIGOTS; i++) { 55 | SPIGOT_SIZES.push(defaultSize); 56 | } 57 | } 58 | 59 | function updateSpigots() { 60 | if (!SPIGOTS_ENABLED) return; 61 | 62 | var i, w, h; 63 | for (i = 0; i !== NUM_SPIGOTS; i++) { 64 | const elem = SPIGOT_ELEMENTS[i]; 65 | const spigotLeft = SPIGOT_SPACING * (i + 1) - MAX_SPIGOT_WIDTH; 66 | const spigotRight = spigotLeft + SPIGOT_SIZES[i]; 67 | if (spigotLeft < 0) continue; 68 | if (spigotRight > MAX_X_IDX) break; 69 | var heightOffset = 0; 70 | for (h = 0; h !== SPIGOT_HEIGHT; h++) { 71 | for (w = spigotLeft; w !== spigotRight; w++) { 72 | if (random() < 10) gameImagedata32[w + heightOffset] = elem; 73 | } 74 | heightOffset += width; 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /scripts/util.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Miscellaneous utility functions and constants. 3 | * 4 | * Copyright (C) 2020, Josh Don 5 | * 6 | * Project Sand is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * Project Sand is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | 20 | /* Pre-compute to improve performance */ 21 | const TWO_PI = 2 * Math.PI; 22 | const HALF_PI = Math.PI / 2; 23 | const QUARTER_PI = Math.PI / 4; 24 | const EIGHTH_PI = Math.PI / 8; 25 | const SIXTEENTH_PI = Math.PI / 16; 26 | const EIGHTEENTH_PI = Math.PI / 18; 27 | 28 | const __num_rand_ints = 8192; 29 | const __rand_ints = new Uint8Array(__num_rand_ints); 30 | var __next_rand = 0; 31 | for (var i = 0; i < __num_rand_ints; i++) { 32 | __rand_ints[i] = Math.floor(Math.random() * 100); 33 | } 34 | 35 | /* 36 | * Returns a pre-generated random byte between 0-99. 37 | * This is especially important for hot-paths that 38 | * can't tolerate the time to call Math.random() directly 39 | * (or deal with floats). 40 | */ 41 | function random() { 42 | const r = __rand_ints[__next_rand]; 43 | 44 | __next_rand++; 45 | if (__next_rand === __num_rand_ints) __next_rand = 0; 46 | 47 | return r; 48 | } 49 | 50 | /* Returns a random int in range [low, high) */ 51 | function randomIntInRange(low, high) { 52 | return Math.floor(Math.random() * (high - low) + low); 53 | } 54 | 55 | function clamp(val, min, max) { 56 | return Math.max(min, Math.min(val, max)); 57 | } 58 | 59 | function executeAndTime(func) { 60 | const start = performance.now(); 61 | func(); 62 | const end = performance.now(); 63 | 64 | return end - start; 65 | } 66 | 67 | function displayPerformance(func, funcName) { 68 | const execTime = executeAndTime(func); 69 | 70 | console.log(funcName, ": ", execTime, "ms"); 71 | } 72 | 73 | function docOffsetLeft(elem) { 74 | var offsetLeft = 0; 75 | do { 76 | if (!isNaN(elem.offsetLeft)) { 77 | offsetLeft += elem.offsetLeft; 78 | } 79 | } while ((elem = elem.offsetParent)); 80 | return offsetLeft; 81 | } 82 | 83 | function docOffsetTop(elem) { 84 | var offsetTop = 0; 85 | do { 86 | if (!isNaN(elem.offsetTop)) { 87 | offsetTop += elem.offsetTop; 88 | } 89 | } while ((elem = elem.offsetParent)); 90 | return offsetTop; 91 | } 92 | 93 | function distance(x1, y1, x2, y2) { 94 | const dx = x1 - x2; 95 | const dy = y1 - y2; 96 | 97 | return Math.sqrt(dx * dx + dy * dy); 98 | } 99 | 100 | /* 101 | * We could convert i to xy using division and modulus, but 102 | * this can be slow. In cases where we want to convert a coordinate 103 | * 'i' that is known to border another coordinate with known xy, 104 | * we can determine the xy of the coordinate by iterating all 105 | * bordering pixels. 106 | */ 107 | function fastItoXYBorderingAdjacent(startX, startY, startI, goalI) { 108 | const bottom = startI + width; 109 | if (bottom === goalI) return [startX, startY + 1]; 110 | else if (bottom - 1 === goalI) return [startX - 1, startY + 1]; 111 | else if (bottom + 1 === goalI) return [startX + 1, startY + 1]; 112 | 113 | if (startI - 1 === goalI) return [startX - 1, startY]; 114 | else if (startI + 1 === goalI) return [startX + 1, startY]; 115 | 116 | const top = startI - width; 117 | if (top === goalI) return [startX, startY - 1]; 118 | else if (top - 1 === goalI) return [startX - 1, startY - 1]; 119 | else if (top + 1 === goalI) return [startX + 1, startY - 1]; 120 | 121 | throw "Not passed a bordering coordinate"; 122 | } 123 | 124 | /* 125 | * See comment on fastItoXYBorderingAdjacent. 126 | * This function does the same, but ignores corners. 127 | */ 128 | function fastItoXYBordering(startX, startY, startI, goalI) { 129 | if (startI + width === goalI) return [startX, startY + 1]; 130 | 131 | if (startI - 1 === goalI) return [startX - 1, startY]; 132 | else if (startI + 1 === goalI) return [startX + 1, startY]; 133 | 134 | if (startI - width === goalI) return [startX, startY - 1]; 135 | 136 | throw "Not passed a bordering coordinate"; 137 | } 138 | -------------------------------------------------------------------------------- /scripts/zombies.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Zombie implementation. 3 | * 4 | * Utilizes softBody.js (generic soft body support) and the third party 5 | * matter.js library. 6 | * 7 | * Copyright (C) 2025, Josh Don 8 | * 9 | * Project Sand is free software: you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License as published by 11 | * the Free Software Foundation, either version 3 of the License, or 12 | * (at your option) any later version. 13 | * 14 | * Project Sand is distributed in the hope that it will be useful, 15 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | * GNU General Public License for more details. 18 | * 19 | * You should have received a copy of the GNU General Public License 20 | * along with this program. If not, see . 21 | */ 22 | 23 | const zombies = []; /* Global list of all active zombies */ 24 | 25 | const DEFAULT_AIR_FRICTION = 0.015; /* library default is 0.01 */ 26 | const ZOMBIE_BURNING_AIR_FRICTION = 0.125; 27 | 28 | /* 29 | * DISCLAIMER: Not everything scales perfectly as zombie size is changed. 30 | */ 31 | const ZOMBIE_SIZE_SCALE = 0.75; 32 | 33 | /* Zombie states */ 34 | const ZOMBIE_STATE_NORMAL = 0; 35 | const ZOMBIE_STATE_BURNING = 1; 36 | const ZOMBIE_STATE_WET = 2; 37 | const ZOMBIE_STATE_FROZEN = 3; 38 | 39 | /* 40 | * Set the total number of zombies to `count`. This will either create new zombies or 41 | * remove existing ones, depending on what the current zombie count is. 42 | */ 43 | function setZombieCount(count) { 44 | var delta = count - zombies.length; 45 | if (delta == 0) { 46 | return; 47 | } 48 | 49 | if (delta > 0) { 50 | for (var i = 0; i < delta; i++) { 51 | new Zombie(); 52 | } 53 | } else { 54 | for (var i = delta; i < 0; i++) { 55 | popZombie(); 56 | } 57 | } 58 | 59 | drawZombieCount(count); 60 | } 61 | 62 | /* Deletes the zombie at the end of the zombies list. */ 63 | function popZombie() { 64 | var zombie = zombies.pop(); 65 | Matter.Composite.remove(softBodyEngine.world, [zombie.compositeBody]); 66 | } 67 | 68 | /* Replace the zombie at the given index with a new zombie. */ 69 | function replaceZombie(idx) { 70 | if (idx < 0 || idx >= zombies.length) { 71 | throw "invalid replace_idx"; 72 | } 73 | 74 | var zombie = new Zombie(); 75 | if (zombies.pop() !== zombie) { 76 | throw "bug in replace"; 77 | } 78 | var oldZombie = zombies[idx]; 79 | zombies[idx] = zombie; 80 | Matter.Composite.remove(softBodyEngine.world, [oldZombie.compositeBody]); 81 | } 82 | 83 | /* 84 | * Given a list of zombies, draw them to the main canvas using 85 | * the given color. 86 | */ 87 | function drawZombies(zombieList, color) { 88 | /* Clear the slate by first filling to black */ 89 | softBodyCtx.beginPath(); 90 | softBodyCtx.rect(0, 0, width, height); 91 | softBodyCtx.fillStyle = "rgba(0, 0, 0, 1)"; 92 | softBodyCtx.fill(); 93 | 94 | softBodyCtx.beginPath(); 95 | 96 | const numZombies = zombieList.length; 97 | for (var i = 0; i < numZombies; i++) { 98 | var bodies = zombieList[i].compositeBody.bodies; 99 | const numBodies = bodies.length; 100 | for (var j = 0; j < numBodies; j++) { 101 | drawBody(softBodyCtx, bodies[j]); 102 | } 103 | } 104 | 105 | softBodyCtx.lineWidth = 1; 106 | softBodyCtx.strokeStyle = "#ffffff"; 107 | softBodyCtx.stroke(); 108 | 109 | const imgData = softBodyCtx.getImageData(0, 0, width, height); 110 | const imgData32 = new Uint32Array(imgData.data.buffer); 111 | for (var i = 0; i < MAX_IDX; i++) { 112 | if (imgData32[i] === 0xff000000) { 113 | continue; 114 | } 115 | gameImagedata32[i] = color; 116 | } 117 | } 118 | 119 | class Zombie { 120 | /* 121 | * Create a new zombie and add it to the simulation. 122 | */ 123 | constructor() { 124 | /* 125 | * Use a new non colliding collision group for this zombie. This will 126 | * prevent collisions between any of the zombie's own body parts, while 127 | * still allowing collisions between this zombie and other soft bodies. 128 | */ 129 | this.collisionGroup = Matter.Body.nextGroup(/*isNonColliding=*/true); 130 | const minWallOffset = 40; 131 | const zombieX = randomIntInRange(minWallOffset, width - minWallOffset); 132 | const zombieY = randomIntInRange(minWallOffset, height - minWallOffset); 133 | /* Create underlying physics body */ 134 | this.compositeBody = Zombie.createZombieSoftBody(zombieX, zombieY, 135 | ZOMBIE_SIZE_SCALE, 136 | this.collisionGroup); 137 | 138 | /* Initialize properties */ 139 | this.cooldown = 0; 140 | this.state = ZOMBIE_STATE_NORMAL; 141 | this.burnRespawnTime = 0; 142 | this.setAirFriction(DEFAULT_AIR_FRICTION); 143 | this.forceNonStatic = false; 144 | 145 | /* 146 | * Now add to our global list and our simulation. 147 | */ 148 | zombies.push(this); 149 | Matter.Composite.add(softBodyEngine.world, [this.compositeBody]); 150 | } 151 | 152 | setAirFriction(friction) { 153 | const bodies = this.compositeBody.bodies; 154 | const numBodies = bodies.length; 155 | for (var i = 0; i < numBodies; i++) { 156 | bodies[i].frictionAir = friction; 157 | } 158 | } 159 | 160 | /* Returns true if the user is currently dragging this zombie */ 161 | isDragging() { 162 | return softBodyDragStart && 163 | softBodyMouseConstraint.body && 164 | softBodyMouseConstraint.body.collisionFilter.group === this.collisionGroup; 165 | } 166 | 167 | /* 168 | * Advance the zombie animation by a single step. This single step 169 | * represents the given number of `milliseconds`. 170 | */ 171 | animate(now, zombieIdx, milliseconds) { 172 | if (this.cooldown <= 0 && random() < 2) { 173 | this.cooldown = Math.round(Math.random() * 180); 174 | } 175 | this.cooldown -= 1; 176 | 177 | const oldState = this.state; 178 | if (oldState !== ZOMBIE_STATE_NORMAL) { 179 | /* 180 | * If wet or frozen, reset the state, since it might not longer 181 | * be applicable. We'll recheck below. 182 | */ 183 | if (oldState === ZOMBIE_STATE_FROZEN || 184 | oldState === ZOMBIE_STATE_WET) { 185 | this.state = ZOMBIE_STATE_NORMAL; 186 | } else if (oldState === ZOMBIE_STATE_BURNING) { 187 | this.burnRespawnTime -= milliseconds; 188 | if (this.burnRespawnTime <= 0) { 189 | replaceZombie(zombieIdx); 190 | return; 191 | } 192 | } 193 | } 194 | 195 | /* cache for performance */ 196 | const isDragging = this.isDragging(); 197 | 198 | const forceNonStatic = this.forceNonStatic && !isDragging; 199 | this.forceNonStatic = false; 200 | const maxStaticImpulse = 0.3; 201 | const maxVelocity = 500; 202 | 203 | const bodies = this.compositeBody.bodies; 204 | const numBodies = bodies.length; 205 | for (var j = 0; j < numBodies; j++) { 206 | var body = bodies[j]; 207 | 208 | /* 209 | * Sometimes zombies get stuck in a stretched out position, with 210 | * static parts touching canvas elements. This tends to glitch 211 | * out, so detect this case and mitigate it. 212 | */ 213 | const impulse = body.constraintImpulse; 214 | if (!isDragging && !this.forceNonStatic && random() < 15 && 215 | (Math.abs(impulse.x) >= maxStaticImpulse || 216 | Math.abs(impulse.y) >= maxStaticImpulse)) { 217 | this.forceNonStatic = true; 218 | } 219 | 220 | if (!this.forceNonStatic && !isDragging) { 221 | const velocity = body.velocity; 222 | 223 | if (Math.abs(velocity.x) > maxVelocity || 224 | Math.abs(velocity.y) > maxVelocity) { 225 | var newVelocity = { 226 | x: clamp(velocity.x, -maxVelocity, maxVelocity), 227 | y: clamp(velocity.y, -maxVelocity, maxVelocity), 228 | }; 229 | Matter.Body.setVelocity(body, newVelocity); 230 | } 231 | } 232 | 233 | /* 234 | * We use the head for self-righting and random jerk behavior. 235 | */ 236 | if (body.__isHead && oldState !== ZOMBIE_STATE_FROZEN) { 237 | /* Zombies on cooldown are less aggressive about self-righting. */ 238 | const onCooldown = (this.cooldown > 0); 239 | if (!onCooldown) { 240 | /* Try to the head up */ 241 | if (Math.random() < 0.06) { 242 | Matter.Body.applyForce(body, body.position, { 243 | x: 0, 244 | y: -0.00001 - Math.random() * 0.00001, 245 | }); 246 | } 247 | /* More aggressively try to get the head up */ 248 | if (Math.random() < 0.03) { 249 | Matter.Body.applyForce(body, body.position, { 250 | x: 0, 251 | y: -0.00003 - Math.random() * 0.00005, 252 | }); 253 | } 254 | } 255 | /* Knock the head side to side */ 256 | if (Math.random() < 0.05) { 257 | Matter.Body.applyForce(body, body.position, { 258 | x: Math.random() * 0.00001 * (Math.random() < 0.5 ? 1 : -1), 259 | y: 0, 260 | }); 261 | } 262 | } 263 | 264 | /* Handle collisions with elements on the main canvas */ 265 | var makeStatic = false; 266 | if (body.__interactsWithMainCanvas) { 267 | /* 268 | * If we're colliding with something on the main canvas, we 269 | * should set the body part to static in order to anchor it 270 | * in place (barring some exceptions, as can be seen below). 271 | */ 272 | makeStatic = this.handleCanvasCollisions(body, now, isDragging); 273 | 274 | if (makeStatic && !isDragging) { 275 | if (forceNonStatic) { 276 | makeStatic = false; 277 | } else if (this.state === ZOMBIE_STATE_BURNING) { 278 | makeStatic = false; 279 | } else if (body.__isFoot) { 280 | var head = bodies[0]; 281 | if (!head.__isHead) { 282 | throw "head misordered" 283 | } 284 | /* 285 | * If we're upside down, make the feet less sticky. 286 | */ 287 | if (random() < 5 && head.position.y > body.position.y) { 288 | makeStatic = false; 289 | } 290 | } 291 | } 292 | } 293 | 294 | if (makeStatic !== body.isStatic) { 295 | Matter.Body.setStatic(body, makeStatic); 296 | } 297 | 298 | /* 299 | * Prevent over-rotation. Without this damping, we can get body parts 300 | * spinning wildly out of control, due to the way the constraints work. 301 | */ 302 | const maxAngularVelocity = 4; 303 | if (!isDragging && !body.isStatic && 304 | Math.abs(body.angularVelocity) > maxAngularVelocity) { 305 | const dampenFactor = 0.5 + Math.random() / 3; 306 | const newVelocity = Math.max(body.angularVelocity * dampenFactor, maxAngularVelocity); 307 | Matter.Body.setAngularVelocity(body, newVelocity); 308 | } 309 | } 310 | 311 | /* 312 | * Simple check if a zombie has managed to clip through the bounding walls. 313 | * Just respawn it in this case. 314 | */ 315 | if (bodies[0].position.y > height * 2) { 316 | replaceZombie(zombieIdx); 317 | return; 318 | } 319 | 320 | /* 321 | * Make zombies fall more slowly when on fire. 322 | */ 323 | if (this.state === ZOMBIE_STATE_BURNING) { 324 | if (bodies[0].frictionAir !== ZOMBIE_BURNING_AIR_FRICTION) { 325 | this.setAirFriction(ZOMBIE_BURNING_AIR_FRICTION); 326 | } 327 | } else { 328 | if (bodies[0].frictionAir !== DEFAULT_AIR_FRICTION) { 329 | this.setAirFriction(DEFAULT_AIR_FRICTION); 330 | } 331 | } 332 | } 333 | 334 | /* 335 | * Returns true if the given zombie body part is colliding with an element 336 | * on the main canvas. 337 | * This is only expected to be called for the special "detector" body parts, 338 | * such as hands and feet (or anything with __interactsWithMainCanvas = true). 339 | * 340 | * This function is not idempotent because it may mutate the canvas to 341 | * remove points of collision, or it may initiate free dragging (in which 342 | * all collisions are ignored). 343 | */ 344 | handleCanvasCollisions(body, now, isDragging) { 345 | /* 346 | * If the user is trying to drag a zombie, stop enforcing collisions against 347 | * elements on the main canvas after a delay. 348 | */ 349 | if (isDragging) { 350 | if (softBodyFreeDrag || 351 | now - softBodyDragStart > Math.random() * 500 + 750) { 352 | softBodyFreeDrag = true; 353 | return false; 354 | } 355 | } 356 | 357 | const xBody = clamp(Math.floor(body.position.x), 0, width - 1); 358 | const yBody = clamp(Math.floor(body.position.y), 0, height - 1); 359 | const searchSize = body.__isNeck ? 3 : 2; 360 | const xStart = Math.max(0, xBody - searchSize); 361 | const xEnd = Math.min(width - 1, xBody + searchSize); 362 | const yStart = Math.max(0, yBody - searchSize); 363 | const yEnd = Math.min(height - 1, yBody + searchSize); 364 | 365 | var iBase = yStart * width; 366 | for (var y = yStart; y < yEnd; y++) { 367 | for (var x = xStart; x < xEnd; x++) { 368 | const elem = gameImagedata32[iBase + x]; 369 | if (elem === ZOMBIE || 370 | elem === ZOMBIE_WET || 371 | elem === ZOMBIE_BURNING || 372 | elem === ZOMBIE_FROZEN || 373 | elem === BACKGROUND) { 374 | continue; 375 | } 376 | 377 | if (random() < 5 && (elem === FIRE || elem === LAVA)) { 378 | if (this.state !== ZOMBIE_STATE_WET && 379 | this.state !== ZOMBIE_STATE_BURNING) { 380 | this.state = ZOMBIE_STATE_BURNING; 381 | this.burnRespawnTime = 700 + randomIntInRange(0, 500); 382 | } 383 | } else if (elem === WATER) { 384 | this.state = ZOMBIE_STATE_WET; 385 | } else if (elem === ICE || elem === CHILLED_ICE || elem === CRYO) { 386 | if (this.state === ZOMBIE_STATE_NORMAL) { 387 | this.state = ZOMBIE_STATE_FROZEN; 388 | } 389 | } 390 | 391 | /* 392 | * Give some opportunity to break free. 393 | * 394 | * This could certainly be tuned. 395 | */ 396 | if (!isDragging && random() < 1 && elem !== ICE) { 397 | gameImagedata32[iBase + x] = BACKGROUND; 398 | } 399 | 400 | return true; 401 | } 402 | iBase += width; 403 | } 404 | 405 | return false; 406 | } 407 | 408 | /* 409 | * Utility method to create the physics simulation elements 410 | * for the zombie soft body. 411 | */ 412 | static createZombieSoftBody(x, y, scale, collisionGroup) { 413 | const headSize = 6 * scale; 414 | const chestWidth = 2 * scale; 415 | const chestHeight = 25 * scale; 416 | const armWidth = 2 * scale; 417 | const upperArmHeight = 7 * scale; 418 | const lowerArmHeight = 9 * scale; 419 | const legWidth = 2 * scale; 420 | const upperLegHeight = 9 * scale; 421 | const lowerLegHeight = 13 * scale; 422 | 423 | /* 424 | * The default density for bodies is 0.001. We use a value much smaler than 425 | * that for the upper body in order to improve the ability of zombies to stand 426 | * upright. 427 | */ 428 | const upperBodyDensity = 0.0001; 429 | 430 | /* 431 | * ===================================== 432 | * First, create each of the body parts. 433 | * ===================================== 434 | */ 435 | 436 | var head = Matter.Bodies.circle( 437 | x, 438 | y - chestHeight / 2.0 - headSize, 439 | headSize, 440 | { 441 | collisionFilter: { 442 | /* 443 | * Note: It is possible that using a new collision group could 444 | * result in better behavior, to prevent the head from passing 445 | * through body parts. Currently it seems the existing behavior 446 | * is good as-is. 447 | */ 448 | group: collisionGroup, 449 | }, 450 | label: "head", 451 | density: upperBodyDensity, 452 | } 453 | ); 454 | 455 | const chestX = x; 456 | const chestY = y; 457 | var chest = Matter.Bodies.rectangle( 458 | chestX, 459 | chestY, 460 | chestWidth, 461 | chestHeight, 462 | { 463 | collisionFilter: { 464 | group: collisionGroup, 465 | }, 466 | chamfer: { 467 | radius: chestWidth / 2.0, 468 | }, 469 | density: upperBodyDensity, 470 | label: "chest", 471 | } 472 | ); 473 | 474 | /* Used for collisions with elements on the main canvas */ 475 | var neck = Matter.Bodies.circle( 476 | chestX, 477 | chestY - chestHeight / 2.0, 478 | 1, 479 | { 480 | collisionFilter: { 481 | group: collisionGroup, 482 | }, 483 | label: "neck", 484 | density: 0.000000001, 485 | } 486 | ); 487 | 488 | /* Used for collisions with elements on the main canvas */ 489 | var midChestLeft = Matter.Bodies.circle( 490 | chestX - chestWidth / 2.0, 491 | chestY, 492 | 1, 493 | { 494 | collisionFilter: { 495 | group: collisionGroup, 496 | }, 497 | label: "midChestLeft", 498 | density: 0.000000001, 499 | } 500 | ); 501 | 502 | /* Used for collisions with elements on the main canvas */ 503 | var midChestRight = Matter.Bodies.circle( 504 | chestX + chestWidth / 2.0, 505 | chestY, 506 | 1, 507 | { 508 | collisionFilter: { 509 | group: collisionGroup, 510 | }, 511 | label: "midChestRight", 512 | density: 0.000000001, 513 | } 514 | ); 515 | 516 | var rightUpperArm = Matter.Bodies.rectangle( 517 | x + chestWidth / 2.0 + armWidth / 2.0, 518 | y - chestHeight / 2.0 + upperArmHeight + 1 * scale, 519 | armWidth, 520 | upperArmHeight, 521 | { 522 | collisionFilter: { 523 | group: collisionGroup, 524 | }, 525 | chamfer: { 526 | radius: armWidth * 0.5, 527 | }, 528 | density: upperBodyDensity, 529 | } 530 | ); 531 | 532 | const rightLowerArmX = x + chestWidth / 2.0 + armWidth / 2.0; 533 | const rightLowerArmY = y - chestHeight / 2.0 + upperArmHeight + lowerArmHeight; 534 | var rightLowerArm = Matter.Bodies.rectangle( 535 | rightLowerArmX, 536 | rightLowerArmY, 537 | armWidth, 538 | lowerArmHeight, 539 | { 540 | collisionFilter: { 541 | group: collisionGroup, 542 | }, 543 | chamfer: { 544 | radius: armWidth * 0.5, 545 | }, 546 | density: upperBodyDensity, 547 | } 548 | ); 549 | 550 | var leftUpperArm = Matter.Bodies.rectangle( 551 | x - chestWidth / 2.0 - armWidth / 2.0, 552 | y - chestHeight / 2.0 + upperArmHeight + 1 * scale, 553 | armWidth, 554 | upperArmHeight, 555 | { 556 | collisionFilter: { 557 | group: collisionGroup, 558 | }, 559 | chamfer: { 560 | radius: armWidth * 0.5, 561 | }, 562 | density: upperBodyDensity, 563 | } 564 | ); 565 | 566 | const leftLowerArmX = x - chestWidth / 2.0 - armWidth / 2.0; 567 | const leftLowerArmY = y - chestHeight / 2.0 + upperArmHeight + lowerArmHeight; 568 | var leftLowerArm = Matter.Bodies.rectangle( 569 | leftLowerArmX, 570 | leftLowerArmY, 571 | armWidth, 572 | lowerArmHeight, 573 | { 574 | collisionFilter: { 575 | group: collisionGroup, 576 | }, 577 | chamfer: { 578 | radius: armWidth * 0.5, 579 | }, 580 | density: upperBodyDensity, 581 | } 582 | ); 583 | 584 | /* Used for collisions with elements on the main canvas */ 585 | var rightHand = Matter.Bodies.circle( 586 | rightLowerArmX, 587 | rightLowerArmY + lowerArmHeight / 2, 588 | 1, 589 | { 590 | collisionFilter: { 591 | group: collisionGroup, 592 | }, 593 | label: "rightHand", 594 | density: 0.000000001, 595 | } 596 | ); 597 | 598 | /* Used for collisions with elements on the main canvas */ 599 | var leftHand = Matter.Bodies.circle( 600 | leftLowerArmX, 601 | leftLowerArmY + lowerArmHeight / 2, 602 | 1, 603 | { 604 | collisionFilter: { 605 | group: collisionGroup, 606 | }, 607 | label: "leftHand", 608 | density: 0.000000001, 609 | } 610 | ); 611 | 612 | var leftUpperLeg = Matter.Bodies.rectangle( 613 | x - chestWidth / 3.0, 614 | y + chestHeight / 2.0 + upperLegHeight / 2.0, 615 | legWidth, 616 | upperLegHeight, 617 | { 618 | collisionFilter: { 619 | group: collisionGroup, 620 | }, 621 | chamfer: { 622 | radius: legWidth / 2.0, 623 | }, 624 | } 625 | ); 626 | 627 | const leftLowerLegX = x - chestWidth / 3.0; 628 | const leftLowerLegY = y + chestHeight / 2.0 + upperLegHeight + lowerLegHeight / 2.0; 629 | var leftLowerLeg = Matter.Bodies.rectangle( 630 | leftLowerLegX, 631 | leftLowerLegY, 632 | legWidth, 633 | lowerLegHeight, 634 | { 635 | collisionFilter: { 636 | group: collisionGroup, 637 | }, 638 | chamfer: { 639 | radius: legWidth / 2.0, 640 | }, 641 | label: "leftLowerLeg", 642 | } 643 | ); 644 | 645 | var rightUpperLeg = Matter.Bodies.rectangle( 646 | x + chestWidth / 3.0, 647 | y + chestHeight / 2.0 + upperLegHeight / 2.0, 648 | legWidth, 649 | upperLegHeight, 650 | { 651 | collisionFilter: { 652 | group: collisionGroup, 653 | }, 654 | chamfer: { 655 | radius: legWidth / 2.0, 656 | }, 657 | } 658 | ); 659 | 660 | const rightLowerLegX = x + chestWidth / 3.0; 661 | const rightLowerLegY = y + chestHeight / 2.0 + upperLegHeight + lowerLegHeight / 2.0; 662 | var rightLowerLeg = Matter.Bodies.rectangle( 663 | rightLowerLegX, 664 | rightLowerLegY, 665 | legWidth, 666 | lowerLegHeight, 667 | { 668 | collisionFilter: { 669 | group: collisionGroup, 670 | }, 671 | chamfer: { 672 | radius: legWidth / 2.0, 673 | }, 674 | label: "rightLowerLeg", 675 | } 676 | ); 677 | 678 | /* Used for collisions with elements on the main canvas */ 679 | var rightFoot = Matter.Bodies.circle( 680 | rightLowerLegX, 681 | rightLowerLegY + lowerLegHeight / 2, 682 | 1, 683 | { 684 | collisionFilter: { 685 | group: collisionGroup, 686 | }, 687 | label: "rightFoot", 688 | density: 0.000000001, 689 | } 690 | ); 691 | 692 | /* Used for collisions with elements on the main canvas */ 693 | var leftFoot = Matter.Bodies.circle( 694 | leftLowerLegX, 695 | leftLowerLegY + lowerLegHeight / 2, 696 | 1, 697 | { 698 | collisionFilter: { 699 | group: collisionGroup, 700 | }, 701 | label: "leftFoot", 702 | density: 0.000000001, 703 | } 704 | ); 705 | 706 | /* 707 | * =================================================================== 708 | * Now, create the constraints that will hold the body parts together. 709 | * =================================================================== 710 | */ 711 | 712 | var chestToNeck = Matter.Constraint.create({ 713 | bodyA: chest, 714 | pointA: { 715 | x: 0, 716 | y: -chestHeight / 2.0, 717 | }, 718 | bodyB: neck, 719 | pointB: { 720 | x: 0, 721 | y: 0, 722 | }, 723 | stiffness: 1, 724 | length: 0, 725 | }); 726 | 727 | var midChestLeftToChest = Matter.Constraint.create({ 728 | bodyA: chest, 729 | pointA: { 730 | x: -chestWidth / 2.0, 731 | y: 0, 732 | }, 733 | bodyB: midChestLeft, 734 | pointB: { 735 | x: 0, 736 | y: 0, 737 | }, 738 | stiffness: 1, 739 | length: 0, 740 | }); 741 | 742 | var midChestRightToChest = Matter.Constraint.create({ 743 | bodyA: chest, 744 | pointA: { 745 | x: chestWidth / 2.0, 746 | y: 0, 747 | }, 748 | bodyB: midChestRight, 749 | pointB: { 750 | x: 0, 751 | y: 0, 752 | }, 753 | stiffness: 1, 754 | length: 0, 755 | }); 756 | 757 | var chestToRightUpperArm = Matter.Constraint.create({ 758 | bodyA: chest, 759 | pointA: { 760 | x: chestWidth / 2.0, 761 | y: -chestHeight / 4.0 - 3 * scale, 762 | }, 763 | bodyB: rightUpperArm, 764 | pointB: { 765 | x: 0, 766 | y: -upperArmHeight / 2.0, 767 | }, 768 | stiffness: 0.5, 769 | length: 0, 770 | damping: 0.2, 771 | }); 772 | 773 | var chestToLeftUpperArm = Matter.Constraint.create({ 774 | bodyA: chest, 775 | pointA: { 776 | x: -chestWidth / 2.0, 777 | y: -chestHeight / 4.0 - 3 * scale, 778 | }, 779 | bodyB: leftUpperArm, 780 | pointB: { 781 | x: 0, 782 | y: -upperArmHeight / 2.0, 783 | }, 784 | stiffness: 0.5, 785 | length: 0, 786 | damping: 0.2, 787 | }); 788 | 789 | var leftArmAngle = Matter.Constraint.create({ 790 | bodyA: chest, 791 | pointA: { 792 | x: -chestWidth / 2.0 - chestWidth / 2.0 - armWidth, 793 | y: -chestHeight / 2.0 + upperArmHeight, 794 | }, 795 | bodyB: leftUpperArm, 796 | pointB: { 797 | x: 0, 798 | y: 0, 799 | }, 800 | stiffness: 0.2, 801 | length: 0, 802 | damping: 0.2, 803 | }); 804 | 805 | var rightArmAngle = Matter.Constraint.create({ 806 | bodyA: chest, 807 | pointA: { 808 | x: chestWidth / 2.0 + chestWidth / 2.0 + armWidth, 809 | y: -chestHeight / 2.0 + upperArmHeight, 810 | }, 811 | bodyB: rightUpperArm, 812 | pointB: { 813 | x: 0, 814 | y: 0, 815 | }, 816 | stiffness: 0.2, 817 | length: 0, 818 | damping: 0.2, 819 | }); 820 | 821 | var chestToLeftUpperLeg = Matter.Constraint.create({ 822 | bodyA: chest, 823 | pointA: { 824 | x: -chestWidth / 6.0, 825 | y: chestHeight / 2.0, 826 | }, 827 | bodyB: leftUpperLeg, 828 | pointB: { 829 | x: 0, 830 | y: -upperLegHeight / 2.0, 831 | }, 832 | stiffness: 0.5, 833 | length: 0, 834 | }); 835 | 836 | var chestToRightUpperLeg = Matter.Constraint.create({ 837 | bodyA: chest, 838 | pointA: { 839 | x: chestWidth / 6.0, 840 | y: chestHeight / 2.0, 841 | }, 842 | bodyB: rightUpperLeg, 843 | pointB: { 844 | x: 0, 845 | y: -upperLegHeight / 2.0, 846 | }, 847 | stiffness: 0.5, 848 | length: 0, 849 | }); 850 | 851 | var leftLegAngle = Matter.Constraint.create({ 852 | bodyA: chest, 853 | pointA: { 854 | x: -chestWidth * 1.5, 855 | y: chestHeight * 0.75, 856 | }, 857 | bodyB: leftUpperLeg, 858 | pointB: { 859 | x: 0, 860 | y: 0, 861 | }, 862 | stiffness: 0.02, 863 | length: 0, 864 | }); 865 | 866 | var rightLegAngle = Matter.Constraint.create({ 867 | bodyA: chest, 868 | pointA: { 869 | x: chestWidth * 1.5, 870 | y: chestHeight * 0.75, 871 | }, 872 | bodyB: rightUpperLeg, 873 | pointB: { 874 | x: 0, 875 | y: 0, 876 | }, 877 | stiffness: 0.02, 878 | length: 0, 879 | }); 880 | 881 | var upperToLowerRightArm = Matter.Constraint.create({ 882 | bodyA: rightUpperArm, 883 | pointA: { 884 | x: 0, 885 | y: upperArmHeight * 0.5, 886 | }, 887 | bodyB: rightLowerArm, 888 | pointB: { 889 | x: 0, 890 | y: -lowerArmHeight * 0.5, 891 | }, 892 | stiffness: 0.5, 893 | length: 0, 894 | }); 895 | 896 | var upperToLowerLeftArm = Matter.Constraint.create({ 897 | bodyA: leftUpperArm, 898 | pointA: { 899 | x: 0, 900 | y: upperArmHeight * 0.5, 901 | }, 902 | bodyB: leftLowerArm, 903 | pointB: { 904 | x: 0, 905 | y: -lowerArmHeight * 0.5, 906 | }, 907 | stiffness: 0.5, 908 | length: 0, 909 | }); 910 | 911 | var rightArmToHand = Matter.Constraint.create({ 912 | bodyA: rightLowerArm, 913 | pointA: { 914 | x: 0, 915 | y: lowerArmHeight / 2.0, 916 | }, 917 | bodyB: rightHand, 918 | pointB: { 919 | x: 0, 920 | y: 0, 921 | }, 922 | stiffness: 1, 923 | length: 0, 924 | }); 925 | 926 | var leftArmToHand = Matter.Constraint.create({ 927 | bodyA: leftLowerArm, 928 | pointA: { 929 | x: 0, 930 | y: lowerArmHeight / 2.0, 931 | }, 932 | bodyB: leftHand, 933 | pointB: { 934 | x: 0, 935 | y: 0, 936 | }, 937 | stiffness: 1, 938 | length: 0, 939 | }); 940 | 941 | var upperToLowerLeftLeg = Matter.Constraint.create({ 942 | bodyA: leftUpperLeg, 943 | pointA: { 944 | x: 0, 945 | y: upperLegHeight / 2.0, 946 | }, 947 | bodyB: leftLowerLeg, 948 | pointB: { 949 | x: 0, 950 | y: -lowerLegHeight / 2.0, 951 | }, 952 | stiffness: 0.5, 953 | length: 0, 954 | damping: 0.2, 955 | }); 956 | 957 | var upperToLowerRightLeg = Matter.Constraint.create({ 958 | bodyA: rightUpperLeg, 959 | pointA: { 960 | x: 0, 961 | y: upperLegHeight / 2.0, 962 | }, 963 | bodyB: rightLowerLeg, 964 | pointB: { 965 | x: 0, 966 | y: -lowerLegHeight / 2.0, 967 | }, 968 | stiffness: 0.5, 969 | length: 0, 970 | damping: 0.2, 971 | }); 972 | 973 | var rightLegToFoot = Matter.Constraint.create({ 974 | bodyA: rightLowerLeg, 975 | pointA: { 976 | x: 0, 977 | y: lowerLegHeight / 2.0, 978 | }, 979 | bodyB: rightFoot, 980 | pointB: { 981 | x: 0, 982 | y: 0, 983 | }, 984 | stiffness: 1, 985 | length: 0, 986 | }); 987 | 988 | var leftLegToFoot = Matter.Constraint.create({ 989 | bodyA: leftLowerLeg, 990 | pointA: { 991 | x: 0, 992 | y: lowerLegHeight / 2.0, 993 | }, 994 | bodyB: leftFoot, 995 | pointB: { 996 | x: 0, 997 | y: 0, 998 | }, 999 | stiffness: 1, 1000 | length: 0, 1001 | }); 1002 | 1003 | var interKneeStiffness = Matter.Constraint.create({ 1004 | bodyA: leftUpperLeg, 1005 | pointA: { 1006 | x: 0, 1007 | y: upperLegHeight / 2.0, 1008 | }, 1009 | bodyB: rightUpperLeg, 1010 | pointB: { 1011 | x: 0, 1012 | y: upperLegHeight / 2.0, 1013 | }, 1014 | stiffness: 0.9, 1015 | length: legWidth * 5, 1016 | damping: 0.2, 1017 | }); 1018 | 1019 | var interFootStiffness = Matter.Constraint.create({ 1020 | bodyA: leftLowerLeg, 1021 | pointA: { 1022 | x: 0, 1023 | y: lowerLegHeight / 2.0, 1024 | }, 1025 | bodyB: rightLowerLeg, 1026 | pointB: { 1027 | x: 0, 1028 | y: lowerLegHeight / 2.0, 1029 | }, 1030 | stiffness: 0.01, 1031 | length: legWidth * 7, 1032 | }); 1033 | 1034 | var leftLegStraightness = Matter.Constraint.create({ 1035 | bodyA: leftUpperLeg, 1036 | pointA: { 1037 | x: 0, 1038 | y: 0, 1039 | }, 1040 | bodyB: leftLowerLeg, 1041 | pointB: { 1042 | x: 0, 1043 | y: 0, 1044 | }, 1045 | stiffness: 0.6, 1046 | length: lowerLegHeight / 2.0 + upperLegHeight / 2.0, 1047 | damping: 0.2, 1048 | }); 1049 | 1050 | var rightLegStraightness = Matter.Constraint.create({ 1051 | bodyA: rightUpperLeg, 1052 | pointA: { 1053 | x: 0, 1054 | y: 0, 1055 | }, 1056 | bodyB: rightLowerLeg, 1057 | pointB: { 1058 | x: 0, 1059 | y: 0, 1060 | }, 1061 | stiffness: 0.6, 1062 | length: lowerLegHeight / 2.0 + upperLegHeight / 2.0, 1063 | damping: 0.2, 1064 | }); 1065 | 1066 | /* Keep the head close to the body */ 1067 | var headContraint = Matter.Constraint.create({ 1068 | bodyA: head, 1069 | pointA: { 1070 | x: 0, 1071 | y: headSize, 1072 | }, 1073 | bodyB: chest, 1074 | pointB: { 1075 | x: 0, 1076 | y: -chestHeight / 2.0, 1077 | }, 1078 | stiffness: 0.4, 1079 | length: 0, 1080 | damping: 0.5, 1081 | }); 1082 | 1083 | /* Keep the head upright rather than falling to the side */ 1084 | var headUpright = Matter.Constraint.create({ 1085 | bodyA: head, 1086 | pointA: { 1087 | x: 0, 1088 | y: -headSize, 1089 | }, 1090 | bodyB: chest, 1091 | pointB: { 1092 | x: 0, 1093 | y: chestHeight / 2.0, 1094 | }, 1095 | stiffness: 0.5, 1096 | length: chestHeight + 2 * headSize, 1097 | damping: 0.2, 1098 | }); 1099 | 1100 | /* 1101 | * All bodies and constraints have been created, now we can return 1102 | * the composite entity that represents an individual zombie. 1103 | */ 1104 | 1105 | var zombie = Matter.Composite.create({ 1106 | bodies: [ 1107 | head, /* order the head first to make it easy to find */ 1108 | chest, 1109 | midChestLeft, 1110 | midChestRight, 1111 | neck, 1112 | leftLowerArm, 1113 | leftUpperArm, 1114 | rightLowerArm, 1115 | rightUpperArm, 1116 | leftHand, 1117 | rightHand, 1118 | leftLowerLeg, 1119 | rightLowerLeg, 1120 | leftFoot, 1121 | rightFoot, 1122 | leftUpperLeg, 1123 | rightUpperLeg, 1124 | ], 1125 | constraints: [ 1126 | upperToLowerLeftArm, 1127 | upperToLowerRightArm, 1128 | leftArmToHand, 1129 | rightArmToHand, 1130 | chestToLeftUpperArm, 1131 | chestToRightUpperArm, 1132 | headContraint, 1133 | upperToLowerLeftLeg, 1134 | upperToLowerRightLeg, 1135 | rightLegToFoot, 1136 | leftLegToFoot, 1137 | chestToLeftUpperLeg, 1138 | chestToRightUpperLeg, 1139 | chestToNeck, 1140 | midChestLeftToChest, 1141 | midChestRightToChest, 1142 | leftArmAngle, 1143 | rightArmAngle, 1144 | leftLegAngle, 1145 | rightLegAngle, 1146 | interKneeStiffness, 1147 | interFootStiffness, 1148 | leftLegStraightness, 1149 | rightLegStraightness, 1150 | headUpright, 1151 | ], 1152 | }); 1153 | 1154 | const numBodies = zombie.bodies.length; 1155 | for (var i = 0; i < numBodies; i++) { 1156 | var body = zombie.bodies[i]; 1157 | 1158 | body.__isHead = (body === head); 1159 | 1160 | body.__interactsWithMainCanvas = 1161 | (body === rightFoot || 1162 | body === leftFoot || 1163 | body === rightHand || 1164 | body === leftHand || 1165 | body === neck); 1166 | 1167 | body.__isFoot = 1168 | (body === rightFoot || 1169 | body === leftFoot); 1170 | 1171 | body.__isNeck = (body === neck); 1172 | 1173 | body.__isArm = 1174 | (body === leftUpperArm || 1175 | body === rightUpperArm || 1176 | body === leftLowerArm || 1177 | body === rightLowerArm); 1178 | 1179 | body.__isLeg = 1180 | (body === leftUpperLeg || 1181 | body === rightUpperLeg || 1182 | body === leftLowerLeg || 1183 | body === rightLowerLeg); 1184 | } 1185 | 1186 | return zombie; 1187 | } 1188 | } 1189 | 1190 | -------------------------------------------------------------------------------- /styles.css: -------------------------------------------------------------------------------- 1 | canvas { 2 | padding-left: 0; 3 | padding-right: 0; 4 | border: 1px solid grey; 5 | } 6 | 7 | body { 8 | background-color: rgb(20, 20, 20); 9 | margin: 0; 10 | } 11 | 12 | a { 13 | color: white; 14 | } 15 | 16 | a:hover { 17 | color: yellow; 18 | } 19 | 20 | .subheader { 21 | color: white; 22 | user-select: none; 23 | font-family: "Arial"; 24 | } 25 | 26 | .column-left { 27 | float: left; 28 | width: 33.333%; 29 | text-align: left; 30 | } 31 | 32 | .column-center { 33 | display: inline-block; 34 | width: 33.333%; 35 | text-align: center; 36 | } 37 | 38 | .column-right { 39 | float: right; 40 | width: 33.333%; 41 | text-align: right; 42 | } 43 | 44 | .title { 45 | text-align: center; 46 | font-family: "Arial"; 47 | color: white; 48 | user-select: none; 49 | } 50 | 51 | .wrapper { 52 | font-size: 0; /* get rid of extra spacing due to font-size */ 53 | padding-top: 10px; 54 | margin: 0 auto; 55 | box-shadow: rgba(0, 0, 0, 0.16) 0px 2px 4px 0px, 56 | rgba(0, 0, 0, 0.12) 0px 2px 10px 0px; 57 | } 58 | 59 | #titleWrapper { 60 | font-size: initial; 61 | padding-bottom: 12px; 62 | } 63 | 64 | #menuWrapper { 65 | border-left: 1px solid grey; 66 | border-right: 1px solid grey; 67 | border-bottom: 1px solid grey; 68 | padding-bottom: 3px; 69 | margin-bottom: 15px; 70 | background-color: rgb(60, 60, 60); 71 | overflow: auto; 72 | font-family: "Arial"; 73 | font-size: 14px; 74 | user-select: none; 75 | position: relative; 76 | color: yellow; 77 | width: inherit; 78 | } 79 | 80 | #elementTable { 81 | border-collapse: collapse; 82 | float: left; 83 | } 84 | 85 | .elementMenuButton { 86 | background: none; 87 | border: none; 88 | text-align: left; 89 | user-select: none; 90 | width: 100%; 91 | height: 100%; 92 | } 93 | 94 | .elementMenuButton:hover { 95 | background-color: rgb(10, 10, 10); 96 | color: white !important; 97 | } 98 | 99 | .elementMenuButton:active { 100 | background-color: rgb(100, 100, 100); 101 | color: white !important; 102 | } 103 | 104 | .selectedElementMenuButton { 105 | outline: 1px solid white; 106 | } 107 | 108 | .optionsCol { 109 | float: left; 110 | } 111 | 112 | .spigotType { 113 | width: 75px; 114 | } 115 | 116 | #speedSliderDiv { 117 | margin-top: 4px; 118 | margin-bottom: 8px; 119 | } 120 | 121 | #speedSlider { 122 | width: 60px; 123 | height: 10px; 124 | border-radius: 5px; 125 | background-image: linear-gradient(to right, rgba(255, 0, 0, 0.8), rgba(0, 128, 0, 0.8)); 126 | outline: none; 127 | -webkit-appearance: none; 128 | } 129 | 130 | #zombieSliderDiv { 131 | margin-top: 4px; 132 | margin-bottom: 8px; 133 | } 134 | 135 | #zombieSlider { 136 | width: 55px; 137 | height: 10px; 138 | border-radius: 5px; 139 | outline: none; 140 | } 141 | 142 | #zombieCount { 143 | color: white; 144 | } 145 | 146 | #optionsCol2 { 147 | padding-left: 4px; 148 | } 149 | 150 | #fps-counter { 151 | position: absolute; 152 | bottom: 1px; 153 | right: 1px; 154 | } 155 | 156 | .optionButton { 157 | font-size: inherit; 158 | font-family: inherit; 159 | user-select: none; 160 | border: none; 161 | outline: none; 162 | } 163 | 164 | .optionButtonContainer { 165 | margin-top: 4px; 166 | } 167 | 168 | #clearButton:hover { 169 | background-color: rgb(255, 0, 0); 170 | } 171 | 172 | #clearButton:active { 173 | background-color: rgb(123, 0, 0); 174 | } 175 | 176 | #saveButton:hover { 177 | background-color: rgb(0, 255, 0); 178 | } 179 | 180 | #saveButton:active { 181 | background-color: rgb(0, 123, 0); 182 | } 183 | 184 | #loadButton:hover { 185 | background-color: rgb(255, 255, 0); 186 | } 187 | 188 | #loadButton:active { 189 | background-color: rgb(123, 123, 0); 190 | } 191 | 192 | #penSizeDiv { 193 | margin-bottom: 2px; 194 | } 195 | --------------------------------------------------------------------------------