diff options
39 files changed, 3652 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c26d4af --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +zig-out +zig-cache @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<https://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<https://www.gnu.org/licenses/why-not-lgpl.html>. diff --git a/README.md b/README.md new file mode 100644 index 0000000..5cea861 --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +## License + +GPLv3+ diff --git a/back.png b/back.png Binary files differnew file mode 100644 index 0000000..39371d6 --- /dev/null +++ b/back.png diff --git a/build.zig b/build.zig new file mode 100644 index 0000000..af7ca00 --- /dev/null +++ b/build.zig @@ -0,0 +1,23 @@ +const std = @import("std"); +const Builder = std.build.Builder; + +pub fn build(b: *Builder) void { + const target = b.standardTargetOptions(.{}); + const mode = b.standardReleaseOptions(); + + const exe = b.addExecutable("zirc", "src/main.zig"); + exe.linkLibC(); + exe.addPackagePath("sfml", "src/sfml/sfml.zig"); + exe.addLibPath("csfml/lib/msvc/"); + exe.linkSystemLibrary("csfml-graphics"); + exe.linkSystemLibrary("csfml-system"); + exe.linkSystemLibrary("csfml-window"); + exe.linkSystemLibrary("csfml-audio"); + exe.addIncludeDir("csfml/include/"); + exe.setTarget(target); + exe.setBuildMode(mode); + exe.install(); + + const run_step = b.step("run", "Run zirc."); + run_step.dependOn(&exe.run().step); +} diff --git a/src/main.zig b/src/main.zig new file mode 100755 index 0000000..2b5f7f2 --- /dev/null +++ b/src/main.zig @@ -0,0 +1,157 @@ +const sf = struct { + pub usingnamespace @import("sfml"); + pub usingnamespace graphics; + pub usingnamespace window; +}; + +const isKeyPressed = sf.window.keyboard.isKeyPressed; + +const std = @import("std"); +usingnamespace @import("raycast.zig"); +usingnamespace @import("renderConstants.zig"); +usingnamespace @import("map.zig"); + +const screenWidth = 1280; +const screenHeight = 960; + +fn renderWall( + window: sf.graphics.RenderWindow, + sprite: sf.graphics.Sprite, + col: i32, // which column + top: f32, // top of wall + height: f32, // how tall + texfrac: f32, // how far along the texture + texture: u8, // which texture index +) !void { + const hFact = screenWidth / planeWidth; + const vFact = screenHeight / planeHeight; + const xpos = @intToFloat(f32, col) * hFact; + const length = height * vFact; + const starty = (screenHeight + vFact * planeHeight) / 2 - top * vFact; + const tind = @as(c_int, texture) * @floatToInt(c_int, 1 + wallTextureDim); + + sprite.setPosition(.{ .x = xpos, .y = starty }); + sprite.setScale(.{ .x = hFact, .y = length / wallTextureDim }); + sprite.setTextureRect(.{ .top = 0, .left = tind + @floatToInt(c_int, texfrac * wallTextureDim), .width = 1, .height = wallTextureDim }); + window.draw(sprite, null); +} + +pub fn main() !void { + const PI = std.math.pi; + + // Setup player and map + //-------------------------------------------------------------------------- + + var player = Player.new(15.75, 1.5, // pos + PI / 2.0, // ang + @intToFloat(f32, planeWidth), @intToFloat(f32, planeHeight)); + + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + + var map = try Map.new(32, 32, &gpa.allocator); + defer map.deinit(); + + var y: u32 = 0; + while (y < 32) : (y += 1) { + map.cells.items[y * 32 + 00] = Cell{ .height = MAX_HEIGHT }; + map.cells.items[y * 32 + 31] = Cell{ .height = MAX_HEIGHT }; + map.cells.items[31 * 32 + y] = Cell{ .height = MAX_HEIGHT }; + map.cells.items[00 * 32 + y] = Cell{ .height = MAX_HEIGHT }; + } + + map.cells.items[y * 15 + 15] = Cell{ .height = MAX_HEIGHT, .wall_texture = 1 }; + map.cells.items[y * 15 + 14] = Cell{ .height = MAX_HEIGHT / 1.5, .wall_texture = 1 }; + + // Initialise SFML + //-------------------------------------------------------------------------- + + var window = try sf.RenderWindow.create(.{ .x = screenWidth, .y = screenHeight }, 32, "zirc", sf.window.Style.none); + defer window.destroy(); + + window.setFramerateLimit(30); + + var backRect = try sf.RectangleShape.create(.{ .x = screenWidth, .y = screenHeight / 2 }); + defer backRect.destroy(); + + backRect.setPosition(.{ .x = 0, .y = screenHeight / 2 }); + backRect.setFillColor(sf.Color.fromRGB(50, 50, 50)); + + // Load the background skybox, really `skycylinder', and assign it to a + // sprite -- it's set to repeating so that it goes on forever. We need to + // scale the sprite so that drawing 1/4 of backTextureWidth fills the screen + // horizontally, and drawing backTextureHeight fills half of the screen + // vertically. + var backTexture = try sf.Texture.createFromFile("back.png"); + defer backTexture.destroy(); + + backTexture.setSmooth(false); // looks worse => better! + backTexture.setRepeated(true); + + var backSprite = try sf.Sprite.createFromTexture(backTexture); + defer backSprite.destroy(); + + backSprite.setScale(.{ .x = 4.0 * @intToFloat(f32, screenWidth) / backTextureWidth, .y = @intToFloat(f32, screenHeight) / (2 * backTextureHeight) }); + + // Load brick texture! + var wallTexture = try sf.Texture.createFromFile("walls.png"); + defer wallTexture.destroy(); + wallTexture.setSmooth(false); // looks worse => better! + + var wallSprite = try sf.Sprite.createFromTexture(wallTexture); + defer wallSprite.destroy(); + + // Start your engines! + //-------------------------------------------------------------------------- + + while (window.isOpen()) { + while (window.pollEvent()) |event| { + if (event == .closed) window.close(); + } + + if (isKeyPressed(.Escape)) window.close(); + + const rotation = 2.0 * PI / 100.0; + if (isKeyPressed(.R)) player.ang += rotation; + if (isKeyPressed(.T)) player.ang -= rotation; + + player.acc_x = 0; + player.acc_y = 0; + const acc_mag = 50; + if (isKeyPressed(.Right)) { + player.acc_x += std.math.cos(player.ang - PI / 2.0) * acc_mag; + player.acc_y += std.math.sin(player.ang - PI / 2.0) * acc_mag; + } + if (isKeyPressed(.Left)) { + player.acc_x -= std.math.cos(player.ang - PI / 2.0) * acc_mag; + player.acc_y -= std.math.sin(player.ang - PI / 2.0) * acc_mag; + } + if (isKeyPressed(.Up) or isKeyPressed(.F)) { + player.acc_x += std.math.cos(player.ang) * acc_mag; + player.acc_y += std.math.sin(player.ang) * acc_mag; + } + if (isKeyPressed(.Down) or isKeyPressed(.S)) { + player.acc_x -= std.math.cos(player.ang) * acc_mag; + player.acc_y -= std.math.sin(player.ang) * acc_mag; + } + + window.clear(sf.Color.fromRGB(100, 100, 100)); + + const back_scroll = @floatToInt(i32, -backTextureWidth * player.ang / (2 * PI)); + backSprite.setTextureRect(sf.IntRect{ + .left = back_scroll, // fix location of texture in the sky + .top = 0, + // scaling ensures that the next two paint it across the width of + // the screen, and for half the height of the screen + .width = backTextureWidth / 4.0, // 1/4 of texture per screen + .height = backTextureHeight, // full height of texture visible + }); + window.draw(backSprite, null); + + try player.renderMapUsing(window, wallSprite, map, renderWall); + + window.display(); + + player.tick(); + } +} diff --git a/src/map.zig b/src/map.zig new file mode 100644 index 0000000..d9b4496 --- /dev/null +++ b/src/map.zig @@ -0,0 +1,42 @@ +const std = @import("std"); + +// Let's pretend that our units are meters +pub const MAX_HEIGHT: f32 = 2.5; + +pub const Cell = struct { + height: f32, + wall_texture: u8 = 0, + floor_texture: u8 = 0, + ceiling_texture: u8 = 0, + + const floor = Cell{ .height = 0 }; +}; + +pub const Map = struct { + width: u32, + height: u32, + size: f32 = 64, + cells: std.ArrayList(Cell), + + pub fn deinit(self: Map) void { + self.cells.deinit(); + } + + pub fn new(width: u32, height: u32, alloc: *std.mem.Allocator) !Map { + var cells = std.ArrayList(Cell).init(alloc); + try cells.ensureTotalCapacity(width * height); + try cells.appendNTimes(Cell.floor, width * height); + + return Map{ .width = width, .height = height, .cells = cells }; + } + + pub fn inBounds(self: Map, x: i32, y: i32) bool { + return (x < self.width and x >= 0 and y < self.height and y >= 0); + } + + pub fn lookup(self: Map, x: i32, y: i32) Cell { + // live dangerously, no bounds check + std.debug.assert(x >= 0 and y >= 0); // compiler hint? + return self.cells.items[@intCast(u32, y) * self.width + @intCast(u32, x)]; + } +}; diff --git a/src/raycast.zig b/src/raycast.zig new file mode 100644 index 0000000..47377a5 --- /dev/null +++ b/src/raycast.zig @@ -0,0 +1,165 @@ +const std = @import("std"); + +const RenderWindow = @import("sfml").graphics.RenderWindow; +const Sprite = @import("sfml").graphics.Sprite; + +usingnamespace @import("map.zig"); + +pub const RenderWallFunction: type = fn ( + window: RenderWindow, + sprite: Sprite, + col: i32, // which column we're in + top: f32, // top of wall + length: f32, + texfrac: f32, + texture: u8, // which texture index +) anyerror!void; // TODO: narrow this error type. + +pub const Player = struct { + pos_x: f32, + pos_y: f32, + ang: f32, + vel_x: f32 = 0, + vel_y: f32 = 0, + acc_x: f32 = 0, + acc_y: f32 = 0, + fov: f32 = std.math.pi / 3.0, + height: f32 = 1.7, // TODO + + plane_height: f32, + plane_width: i32, + plane_dist: f32, + + pub fn new(pos_x: f32, pos_y: f32, ang: f32, plane_width: i32, plane_height: i32) Player { + const fov: f32 = std.math.pi / 3.0; + return Player{ + // standing still at the given location, looking in direction ang, + .pos_x = pos_x, + .pos_y = pos_y, + .ang = ang, + // plane of projection + .plane_width = plane_width, + .plane_height = @intToFloat(f32, plane_height), + // given the desired width of the image, how far away must + // the projection plane be from the camera? + .plane_dist = @intToFloat(f32, plane_width) / (2 * std.math.tan(fov / 2)), + }; + } + + pub fn tick(self: *Player) void { + const dt = 1 / 30.0; + const v_min = 0.8; + const v_decay = 1.25; + + self.pos_x += self.vel_x * dt; + self.pos_y += self.vel_y * dt; + + self.vel_x /= v_decay; + if (std.math.fabs(self.vel_x) < v_min) self.vel_x = 0; + self.vel_y /= v_decay; + if (std.math.fabs(self.vel_y) < v_min) self.vel_y = 0; + + self.vel_x += self.acc_x * dt; + self.vel_y += self.acc_y * dt; + } + + pub fn renderMapUsing( + self: Player, + window: RenderWindow, + sprite: Sprite, + map: Map, + // the abstract the rendering call + renderWall: RenderWallFunction, + ) !void { + const floor = std.math.floor; + + var col: i32 = 0; + while (col < self.plane_width) : (col += 1) { + const horiz_frac = @intToFloat(f32, col) / (@intToFloat(f32, self.plane_width) - 1); + + const ra = (0.5 - horiz_frac) * self.fov + self.ang; + + const cosra = std.math.cos(ra); + const sinra = std.math.sin(ra); + + // Observe that sqrt(1+tan^2) = abs(1/cos) sqrt(cos^2+sin^2) = + // abs(1/cos). Similarly so for cot, hence we obtain the following + // lengths for the hypotenuses assuming that x (respectively y) are + // unit length and the angle is ra. + const dy_for_x_step = std.math.fabs(1 / cosra); + const dx_for_y_step = std.math.fabs(1 / sinra); + + var step_x: i32 = -1; + var step_y: i32 = -1; + + var dist_x: f32 = undefined; + var dist_y: f32 = undefined; + + var ipos_x: i32 = @floatToInt(i32, floor(self.pos_x)); + var ipos_y: i32 = @floatToInt(i32, floor(self.pos_y)); + + // looking right + if (cosra >= 0) { + step_x = 1; + // assuming unit size grid cells + dist_y = (@intToFloat(f32, ipos_x) + 1 - self.pos_x) * dy_for_x_step; + } else { + dist_y = (self.pos_x - @intToFloat(f32, ipos_x)) * dy_for_x_step; + } + + if (sinra >= 0) { + step_y = 1; + dist_x = (@intToFloat(f32, ipos_y) + 1 - self.pos_y) * dx_for_y_step; + } else { + dist_x = (self.pos_y - @intToFloat(f32, ipos_y)) * dx_for_y_step; + } + + var distance: f32 = 0; + var still_drawing = true; + var horizontal_hit: bool = undefined; + while (still_drawing) { + + // Find the next cell on our path + if (dist_y < dist_x) { + horizontal_hit = false; + distance = dist_y; + dist_y += dy_for_x_step; + ipos_x += step_x; + } else { + horizontal_hit = true; + distance = dist_x; + dist_x += dx_for_y_step; + ipos_y += step_y; + } + + if (!map.inBounds(ipos_x, ipos_y)) break; + + var cell = map.lookup(ipos_x, ipos_y); + + // We have a wall to draw + if (cell.height > 0) { + // before we correct the distance to be the perpedicular + // distance from the plane of projection, we need to use it + // to calculate the fractional part of the relevant + // coordinate + const hit_coordinate = if (horizontal_hit) distance * cosra + self.pos_x else distance * sinra + self.pos_y; + var texfrac = std.math.modf(hit_coordinate).fpart; + // we also want to be sure that we're consistently orienting these, say clockwise + if ((horizontal_hit and sinra < 0) or (!horizontal_hit and cosra > 0)) texfrac = 1 - texfrac; + + // now correct the distance to be the shortest distance from + // the plane to the point, that is, perpendicular distance + distance *= std.math.cos(self.ang - ra); + + // project the top of the wall + const top = self.plane_height / 2 + self.plane_dist * (cell.height - self.height) / distance; + const height = self.plane_dist * cell.height / distance; + + try renderWall(window, sprite, col, top, height, texfrac, cell.wall_texture); + + still_drawing = false; + } + } + } + } +}; diff --git a/src/renderConstants.zig b/src/renderConstants.zig new file mode 100644 index 0000000..12bce07 --- /dev/null +++ b/src/renderConstants.zig @@ -0,0 +1,7 @@ +pub const planeWidth = 320; +pub const planeHeight = 240; + +pub const backTextureWidth: f32 = 1280.0; +pub const backTextureHeight: f32 = 240.0; + +pub const wallTextureDim: f32 = 16.0; diff --git a/src/sfml/LICENCE b/src/sfml/LICENCE new file mode 100644 index 0000000..d6c7f74 --- /dev/null +++ b/src/sfml/LICENCE @@ -0,0 +1,18 @@ +Copyright (C) 2021 Guigui220D <gderex8@orange.fr> + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +This project does not contain the sources of CSFML. The licence of CSFML can be found in CSFML-LICENSE + +nice_music.ogg from https://www.bensound.com/ +cute_image.png from https://github.com/ziglang/logo
\ No newline at end of file diff --git a/src/sfml/audio/Music.zig b/src/sfml/audio/Music.zig new file mode 100644 index 0000000..b02b620 --- /dev/null +++ b/src/sfml/audio/Music.zig @@ -0,0 +1,111 @@ +//! Streamed music played from an audio file. + +const sf = @import("../sfml.zig"); + +const Music = @This(); + +// Constructor/destructor + +/// Loads music from a file +pub fn createFromFile(path: [:0]const u8) !Music { + var music = sf.c.sfMusic_createFromFile(path); + if (music == null) + return sf.Error.resourceLoadingError; + return Music{ .ptr = music.? }; +} + +pub const initFromMemory = @compileError("Function is not implemented yet."); +pub const initFromStream = @compileError("Function is not implemented yet."); + +/// Destroys this music object +pub fn destroy(self: Music) void { + sf.c.sfMusic_destroy(self.ptr); +} + +// Music control functions + +/// Plays the music +pub fn play(self: Music) void { + sf.c.sfMusic_play(self.ptr); +} +/// Pauses the music +pub fn pause(self: Music) void { + sf.c.sfMusic_pause(self.ptr); +} +/// Stops the music and resets the player position +pub fn stop(self: Music) void { + sf.c.sfMusic_stop(self.ptr); +} + +// Getters / Setters + +/// Gets the total duration of the music +pub fn getDuration(self: Music) sf.Time { + return sf.Time.fromCSFML(sf.c.sfMusic_getDuration(self.ptr)); +} + +/// Gets the current stream position of the music +pub fn getPlayingOffset(self: Music) sf.Time { + return sf.Time.fromCSFML(sf.c.sfMusic_getPlayingOffset(self.ptr)); +} +/// Sets the current stream position of the music +pub fn setPlayingOffset(self: Music, offset: sf.Time) void { + sf.c.sfMusic_setPlayingOffset(self.ptr, offset.toCSFML()); +} + +/// Gets the loop points of the music +pub fn getLoopPoints(self: Music) sf.TimeSpan { + return sf.TimeSpan.fromCSFML(sf.c.sfMusic_getLoopPoints(self.ptr)); +} +/// Gets the loop points of the music +pub fn setLoopPoints(self: Music, span: sf.TimeSpan) void { + sf.c.sfMusic_setLoopPoints(self.ptr, span.toCSFML()); +} + +/// Tells whether or not this stream is in loop mode +pub fn getLoop(self: Music) bool { + return sf.c.sfMusic_getLoop(self.ptr) != 0; +} +/// Enable or disable auto loop +pub fn setLoop(self: Music, loop: bool) void { + sf.c.sfMusic_setLoop(self.ptr, if (loop) 1 else 0); +} + +/// Sets the pitch of the music +pub fn getPitch(self: Music) f32 { + return sf.c.sfMusic_getPitch(self.ptr); +} +/// Gets the pitch of the music +pub fn setPitch(self: Music, pitch: f32) void { + sf.c.sfMusic_setPitch(self.ptr, pitch); +} + +/// Sets the volume of the music +pub fn getVolume(self: Music) f32 { + return sf.c.sfMusic_getVolume(self.ptr); +} +/// Gets the volume of the music +pub fn setVolume(self: Music, volume: f32) void { + sf.c.sfMusic_setVolume(self.ptr, volume); +} + +/// Gets the sample rate of this music +pub fn getSampleRate(self: Music) usize { + return @intCast(usize, sf.c.sfMusic_getSampleRate(self.ptr)); +} + +/// Gets the channel count of the music +pub fn getChannelCount(self: Music) usize { + return @intCast(usize, sf.c.sfMusic_getChannelCount(self.ptr)); +} + +pub const getStatus = @compileError("Function is not implemented yet."); +pub const setRelativeToListener = @compileError("Function is not implemented yet."); +pub const isRelativeToListener = @compileError("Function is not implemented yet."); +pub const setMinDistance = @compileError("Function is not implemented yet."); +pub const setAttenuation = @compileError("Function is not implemented yet."); +pub const getMinDistance = @compileError("Function is not implemented yet."); +pub const getAttenuation = @compileError("Function is not implemented yet."); + +/// Pointer to the csfml music +ptr: *sf.c.sfMusic, diff --git a/src/sfml/audio/Sound.zig b/src/sfml/audio/Sound.zig new file mode 100644 index 0000000..4430dcb --- /dev/null +++ b/src/sfml/audio/Sound.zig @@ -0,0 +1,107 @@ +//! Regular sound that can be played in the audio environment. + +const sf = struct { + pub usingnamespace @import("../sfml.zig"); + pub usingnamespace audio; +}; + +const Sound = @This(); + +// Constructor/destructor + +/// Inits an empty sound +pub fn create() !Sound { + var sound = sf.c.sfSound_create(); + if (sound == null) + return sf.Error.nullptrUnknownReason; + return Sound{ .ptr = sound.? }; +} + +/// Inits a sound with a SoundBuffer object +pub fn createFromBuffer(buffer: sf.SoundBuffer) !Sound { + var sound = try Sound.create(); + sound.setBuffer(buffer); + return sound; +} + +/// Destroys this sound object +pub fn destroy(self: Sound) void { + sf.c.sfSound_destroy(self.ptr); +} + +// Sound control functions + +/// Plays the sound +pub fn play(self: Sound) void { + sf.c.sfSound_play(self.ptr); +} +/// Pauses the sound +pub fn pause(self: Sound) void { + sf.c.sfSound_pause(self.ptr); +} +/// Stops the sound and resets the player position +pub fn stop(self: Sound) void { + sf.c.sfSound_stop(self.ptr); +} + +// Getters / Setters + +/// Gets the buffer this sound is attached to +pub fn getBuffer(self: Sound) ?sf.SoundBuffer { + var buf = sf.c.sfSound_getBuffer(self.ptr); + if (buf) |buffer| { + return .{ .ptr = buffer }; + } else return null; +} + +/// Sets the buffer this sound will play +pub fn setBuffer(self: Sound, buffer: sf.SoundBuffer) void { + sf.c.sfSound_setBuffer(self.ptr, buffer.ptr); +} + +/// Gets the current playing offset of the sound +pub fn getPlayingOffset(self: Sound) sf.Time { + return sf.Time.fromCSFML(sf.c.sfSound_getPlayingOffset(self.ptr)); +} +/// Sets the current playing offset of the sound +pub fn setPlayingOffset(self: Sound, offset: sf.Time) void { + sf.c.sfSound_setPlayingOffset(self.ptr, offset.toCSFML()); +} + +/// Tells whether or not this sound is in loop mode +pub fn getLoop(self: Sound) bool { + return sf.c.sfSound_getLoop(self.ptr) != 0; +} +/// Enable or disable auto loop +pub fn setLoop(self: Sound, loop: bool) void { + sf.c.sfSound_setLoop(self.ptr, if (loop) 1 else 0); +} + +/// Sets the pitch of the sound +pub fn getPitch(self: Sound) f32 { + return sf.c.sfSound_getPitch(self.ptr); +} +/// Gets the pitch of the sound +pub fn setPitch(self: Sound, pitch: f32) void { + sf.c.sfSound_setPitch(self.ptr, pitch); +} + +/// Sets the volume of the sound +pub fn getVolume(self: Sound) f32 { + return sf.c.sfSound_getVolume(self.ptr); +} +/// Gets the volume of the sound +pub fn setVolume(self: Sound, volume: f32) void { + sf.c.sfSound_setVolume(self.ptr, volume); +} + +pub const getStatus = @compileError("Function is not implemented yet."); +pub const setRelativeToListener = @compileError("Function is not implemented yet."); +pub const isRelativeToListener = @compileError("Function is not implemented yet."); +pub const setMinDistance = @compileError("Function is not implemented yet."); +pub const setAttenuation = @compileError("Function is not implemented yet."); +pub const getMinDistance = @compileError("Function is not implemented yet."); +pub const getAttenuation = @compileError("Function is not implemented yet."); + +/// Pointer to the csfml sound +ptr: *sf.c.sfSound, diff --git a/src/sfml/audio/SoundBuffer.zig b/src/sfml/audio/SoundBuffer.zig new file mode 100644 index 0000000..9727088 --- /dev/null +++ b/src/sfml/audio/SoundBuffer.zig @@ -0,0 +1,79 @@ +//! Storage for audio samples defining a sound. + +const sf = @import("../sfml.zig"); + +const SoundBuffer = @This(); + +// Constructor/destructor +/// Loads music from a file +pub fn createFromFile(path: [:0]const u8) !SoundBuffer { + var sound = sf.c.sfSoundBuffer_createFromFile(path); + if (sound == null) + return sf.Error.resourceLoadingError; + return SoundBuffer{ .ptr = sound.? }; +} +/// Creates a sound buffer from sample data +pub fn createFromSamples(samples: []const i16, channel_count: usize, sample_rate: usize) !SoundBuffer { + var sound = sf.c.sfSoundBuffer_createFromSamples(@ptrCast([*c]const c_short, samples.ptr), samples.len, @intCast(c_uint, channel_count), @intCast(c_uint, sample_rate)); + if (sound == null) + return sf.Error.resourceLoadingError; + return SoundBuffer{ .ptr = sound.? }; +} + +pub const initFromMemory = @compileError("Function is not implemented yet."); +pub const initFromStream = @compileError("Function is not implemented yet."); + +/// Destroys this music object +pub fn destroy(self: SoundBuffer) void { + sf.c.sfSoundBuffer_destroy(self.ptr); +} + +// Getters / Setters + +/// Gets the duration of the sound +pub fn getDuration(self: SoundBuffer) sf.system.Time { + return sf.system.Time.fromCSFML(sf.c.sfSoundBuffer_getDuration(self.ptr)); +} + +/// Gets the sample count of this sound +pub fn getSampleCount(self: SoundBuffer) usize { + return @intCast(usize, sf.c.sfSoundBuffer_getSampleCount(self.ptr)); +} + +/// Gets the sample rate of this sound (n° of samples per second, often 44100) +pub fn getSampleRate(self: SoundBuffer) usize { + return @intCast(usize, sf.c.sfSoundBuffer_getSampleRate(self.ptr)); +} + +/// Gets the channel count (2 is stereo for instance) +pub fn getChannelCount(self: SoundBuffer) usize { + return @intCast(usize, sf.c.sfSoundBuffer_getChannelCount(self.ptr)); +} + +// Misc + +/// Save the sound buffer to an audio file +pub fn saveToFile(self: SoundBuffer, path: [:0]const u8) !void { + if (sf.c.sfSoundBuffer_saveToFile(self.ptr, path) != 1) + return sf.Error.savingInFileFailed; +} + +/// Pointer to the csfml texture +ptr: *sf.c.sfSoundBuffer, + +test "sound buffer: sane getter and setters" { + const std = @import("std"); + const tst = std.testing; + const allocator = std.heap.page_allocator; + + var samples = try allocator.alloc(i16, 44100 * 3); + defer allocator.free(samples); + + var buffer = try SoundBuffer.createFromSamples(samples, 1, 44100); + defer buffer.destroy(); + + try tst.expectApproxEqAbs(@as(f32, 3), buffer.getDuration().asSeconds(), 0.001); + try tst.expectEqual(@as(usize, 44100 * 3), buffer.getSampleCount()); + try tst.expectEqual(@as(usize, 44100), buffer.getSampleRate()); + try tst.expectEqual(@as(usize, 1), buffer.getChannelCount()); +} diff --git a/src/sfml/graphics/CircleShape.zig b/src/sfml/graphics/CircleShape.zig new file mode 100644 index 0000000..ce48fa8 --- /dev/null +++ b/src/sfml/graphics/CircleShape.zig @@ -0,0 +1,150 @@ +//! Specialized shape representing a circle. + +const sf = struct { + pub usingnamespace @import("../sfml.zig"); + pub usingnamespace system; + pub usingnamespace graphics; +}; + +const CircleShape = @This(); + +// Constructor/destructor + +/// Inits a circle shape with a radius. The circle will be white and have 30 points +pub fn create(radius: f32) !CircleShape { + var circle = sf.c.sfCircleShape_create(); + if (circle == null) + return sf.Error.nullptrUnknownReason; + + sf.c.sfCircleShape_setFillColor(circle, sf.c.sfWhite); + sf.c.sfCircleShape_setRadius(circle, radius); + + return CircleShape{ .ptr = circle.? }; +} + +/// Destroys a circle shape +pub fn destroy(self: CircleShape) void { + sf.c.sfCircleShape_destroy(self.ptr); +} + +// Draw function +pub fn sfDraw(self: CircleShape, window: sf.RenderWindow, states: ?*sf.c.sfRenderStates) void { + sf.c.sfRenderWindow_drawCircleShape(window.ptr, self.ptr, states); +} + +// Getters/setters + +/// Gets the fill color of this circle shape +pub fn getFillColor(self: CircleShape) sf.Color { + return sf.Color.fromCSFML(sf.c.sfCircleShape_getFillColor(self.ptr)); +} +/// Sets the fill color of this circle shape +pub fn setFillColor(self: CircleShape, color: sf.Color) void { + sf.c.sfCircleShape_setFillColor(self.ptr, color.toCSFML()); +} + +/// Gets the radius of this circle shape +pub fn getRadius(self: CircleShape) f32 { + return sf.c.sfCircleShape_getRadius(self.ptr); +} +/// Sets the radius of this circle shape +pub fn setRadius(self: CircleShape, radius: f32) void { + sf.c.sfCircleShape_setRadius(self.ptr, radius); +} + +/// Gets the position of this circle shape +pub fn getPosition(self: CircleShape) sf.Vector2f { + return sf.Vector2f.fromCSFML(sf.c.sfCircleShape_getPosition(self.ptr)); +} +/// Sets the position of this circle shape +pub fn setPosition(self: CircleShape, pos: sf.Vector2f) void { + sf.c.sfCircleShape_setPosition(self.ptr, pos.toCSFML()); +} +/// Adds the offset to this shape's position +pub fn move(self: CircleShape, offset: sf.Vector2f) void { + sf.c.sfCircleShape_move(self.ptr, offset.toCSFML()); +} + +/// Gets the origin of this circle shape +pub fn getOrigin(self: CircleShape) sf.Vector2f { + return sf.Vector2f.fromCSFML(sf.c.sfCircleShape_getOrigin(self.ptr)); +} +/// Sets the origin of this circle shape +pub fn setOrigin(self: CircleShape, origin: sf.Vector2f) void { + sf.c.sfCircleShape_setOrigin(self.ptr, origin.toCSFML()); +} + +/// Gets the rotation of this circle shape +pub fn getRotation(self: CircleShape) f32 { + return sf.c.sfCircleShape_getRotation(self.ptr); +} +/// Sets the rotation of this circle shape +pub fn setRotation(self: CircleShape, angle: f32) void { + sf.c.sfCircleShape_setRotation(self.ptr, angle); +} +/// Rotates this shape by a given amount +pub fn rotate(self: CircleShape, angle: f32) void { + sf.c.sfCircleShape_rotate(self.ptr, angle); +} + +/// Gets the texture of this shape +pub fn getTexture(self: CircleShape) ?sf.Texture { + const t = sf.c.sfCircleShape_getTexture(self.ptr); + if (t) |tex| { + return sf.Texture{ .const_ptr = tex }; + } else return null; +} +/// Sets the texture of this shape +pub fn setTexture(self: CircleShape, texture: ?sf.Texture) void { + var tex = if (texture) |t| t.get() else null; + sf.c.sfCircleShape_setTexture(self.ptr, tex, 0); +} +/// Gets the sub-rectangle of the texture that the shape will display +pub fn getTextureRect(self: CircleShape) sf.FloatRect { + return sf.FloatRect.fromCSFML(sf.c.sfCircleShape_getTextureRect(self.ptr)); +} +/// Sets the sub-rectangle of the texture that the shape will display +pub fn setTextureRect(self: CircleShape, rect: sf.FloatRect) void { + sf.c.sfCircleShape_getCircleRect(self.ptr, rect.toCSFML()); +} + +/// Gets the bounds in the local coordinates system +pub fn getLocalBounds(self: CircleShape) sf.FloatRect { + return sf.FloatRect.fromCSFML(sf.c.sfCircleShape_getLocalBounds(self.ptr)); +} + +/// Gets the bounds in the global coordinates +pub fn getGlobalBounds(self: CircleShape) sf.FloatRect { + return sf.FloatRect.fromCSFML(sf.c.sfCircleShape_getGlobalBounds(self.ptr)); +} + +/// Pointer to the csfml structure +ptr: *sf.c.sfCircleShape, + +test "circle shape: sane getters and setters" { + const tst = @import("std").testing; + + var circle = try CircleShape.create(30); + defer circle.destroy(); + + circle.setFillColor(sf.Color.Yellow); + circle.setRadius(50); + circle.setRotation(15); + circle.setPosition(.{ .x = 1, .y = 2 }); + circle.setOrigin(.{ .x = 20, .y = 25 }); + circle.setTexture(null); + + // TODO : issue #2 + try tst.expectEqual(sf.Color.Yellow, circle.getFillColor()); + try tst.expectEqual(@as(f32, 50), circle.getRadius()); + try tst.expectEqual(@as(f32, 15), circle.getRotation()); + try tst.expectEqual(sf.Vector2f{ .x = 1, .y = 2 }, circle.getPosition()); + try tst.expectEqual(sf.Vector2f{ .x = 20, .y = 25 }, circle.getOrigin()); + try tst.expectEqual(@as(?sf.Texture, null), circle.getTexture()); + + circle.rotate(5); + circle.move(.{ .x = -5, .y = 5 }); + + try tst.expectEqual(@as(f32, 20), circle.getRotation()); + try tst.expectEqual(sf.Vector2f{ .x = -4, .y = 7 }, circle.getPosition()); +} diff --git a/src/sfml/graphics/Font.zig b/src/sfml/graphics/Font.zig new file mode 100644 index 0000000..78bd5a6 --- /dev/null +++ b/src/sfml/graphics/Font.zig @@ -0,0 +1,25 @@ +//! Class for loading and manipulating character fonts. + +const sf = @import("../sfml.zig"); + +const Font = @This(); + +// Constructor/destructor + +/// Loads a font from a file +pub fn createFromFile(path: [:0]const u8) !Font { + var font = sf.c.sfFont_createFromFile(path); + if (font == null) + return sf.Error.resourceLoadingError; + return Font{ .ptr = font.? }; +} +/// Destroys a font +pub fn destroy(self: Font) void { + sf.c.sfFont_destroy(self.ptr); +} + +pub const initFromMemory = @compileError("Function is not implemented yet."); +pub const initFromStream = @compileError("Function is not implemented yet."); + +/// Pointer to the csfml font +ptr: *sf.c.sfFont, diff --git a/src/sfml/graphics/Image.zig b/src/sfml/graphics/Image.zig new file mode 100644 index 0000000..6401a6c --- /dev/null +++ b/src/sfml/graphics/Image.zig @@ -0,0 +1,110 @@ +//! Class for loading, manipulating and saving images. + +const sf = struct { + pub usingnamespace @import("../sfml.zig"); + pub usingnamespace system; + pub usingnamespace graphics; +}; + +const std = @import("std"); +const assert = std.debug.assert; + +const Image = @This(); + +// Constructor/destructor + +/// Creates a new image +pub fn create(size: sf.Vector2u, color: sf.Color) !Image { + var img = sf.c.sfImage_createFromColor(size.x, size.y, color.toCSFML()); + if (img == null) + return sf.Error.nullptrUnknownReason; + return Image{ .ptr = img.? }; +} + +/// Creates an image from a pixel array +pub fn createFromPixels(size: sf.Vector2u, pixels: []const sf.Color) !Image { + // Check if there is enough data + if (pixels.len < size.x * size.y) + return sf.Error.notEnoughData; + + var img = sf.c.sfImage_createFromPixels(size.x, size.y, @ptrCast([*]const u8, pixels.ptr)); + + if (img == null) + return sf.Error.nullptrUnknownReason; + return Image{ .ptr = img.? }; +} + +/// Loads an image from a file +pub fn createFromFile(path: [:0]const u8) !Image { + var img = sf.c.sfImage_createFromFile(path); + if (img == null) + return sf.Error.resourceLoadingError; + return Image{ .ptr = img.? }; +} + +/// Destroys an image +pub fn destroy(self: Image) void { + sf.c.sfImage_destroy(self.ptr); +} + +// Save an image to a file +pub fn saveToFile(self: Image, path: [:0]const u8) !void { + if (sf.c.sfImage_saveToFile(self.ptr, path) != 1) + return sf.Error.savingInFileFailed; +} + +// Getters/setters + +/// Gets a pixel from this image (bounds are only checked in an assertion) +pub fn getPixel(self: Image, pixel_pos: sf.Vector2u) sf.Color { + const size = self.getSize(); + assert(pixel_pos.x < size.x and pixel_pos.y < size.y); + + return sf.Color.fromCSFML(sf.c.sfImage_getPixel(self.ptr, pixel_pos.x, pixel_pos.y)); +} +/// Sets a pixel on this image (bounds are only checked in an assertion) +pub fn setPixel(self: Image, pixel_pos: sf.Vector2u, color: sf.Color) void { + const size = self.getSize(); + assert(pixel_pos.x < size.x and pixel_pos.y < size.y); + + sf.c.sfImage_setPixel(self.ptr, pixel_pos.x, pixel_pos.y, color.toCSFML()); +} + +/// Gets the size of this image +pub fn getSize(self: Image) sf.Vector2u { + // This is a hack + _ = sf.c.sfImage_getSize(self.ptr); + // Register Rax holds the return val of function calls that can fit in a register + const rax: usize = asm volatile ("" + : [ret] "={rax}" (-> usize) + ); + var x: u32 = @truncate(u32, (rax & 0x00000000FFFFFFFF) >> 00); + var y: u32 = @truncate(u32, (rax & 0xFFFFFFFF00000000) >> 32); + return sf.Vector2u{ .x = x, .y = y }; +} + +/// Pointer to the csfml texture +ptr: *sf.c.sfImage, + +test "image: sane getters and setters" { + const tst = std.testing; + const allocator = std.heap.page_allocator; + + var pixel_data = try allocator.alloc(sf.Color, 30); + defer allocator.free(pixel_data); + + for (pixel_data) |*c, i| { + c.* = sf.Color.fromHSVA(@intToFloat(f32, i) / 30 * 360, 100, 100, 1); + } + + var img = try Image.createFromPixels(.{ .x = 5, .y = 6 }, pixel_data); + defer img.destroy(); + + try tst.expectEqual(sf.Vector2u{ .x = 5, .y = 6 }, img.getSize()); + + img.setPixel(.{ .x = 1, .y = 2 }, sf.Color.Cyan); + try tst.expectEqual(sf.Color.Cyan, img.getPixel(.{ .x = 1, .y = 2 })); + + var tex = try sf.Texture.createFromImage(img, null); + defer tex.destroy(); +} diff --git a/src/sfml/graphics/RectangleShape.zig b/src/sfml/graphics/RectangleShape.zig new file mode 100644 index 0000000..7c18a82 --- /dev/null +++ b/src/sfml/graphics/RectangleShape.zig @@ -0,0 +1,152 @@ +//! Specialized shape representing a rectangle. + +const sf = struct { + pub usingnamespace @import("../sfml.zig"); + pub usingnamespace system; + pub usingnamespace graphics; +}; + +const RectangleShape = @This(); + +// Constructor/destructor + +/// Creates a rectangle shape with a size. The rectangle will be white +pub fn create(size: sf.Vector2f) !RectangleShape { + var rect = sf.c.sfRectangleShape_create(); + if (rect == null) + return sf.Error.nullptrUnknownReason; + + sf.c.sfRectangleShape_setFillColor(rect, sf.c.sfWhite); + sf.c.sfRectangleShape_setSize(rect, size.toCSFML()); + + return RectangleShape{ .ptr = rect.? }; +} + +/// Destroys a rectangle shape +pub fn destroy(self: RectangleShape) void { + sf.c.sfRectangleShape_destroy(self.ptr); +} + +// Draw function +pub fn sfDraw(self: RectangleShape, window: sf.RenderWindow, states: ?*sf.c.sfRenderStates) void { + sf.c.sfRenderWindow_drawRectangleShape(window.ptr, self.ptr, states); +} + +// Getters/setters + +/// Gets the fill color of this rectangle shape +pub fn getFillColor(self: RectangleShape) sf.Color { + return sf.Color.fromCSFML(sf.c.sfRectangleShape_getFillColor(self.ptr)); +} +/// Sets the fill color of this rectangle shape +pub fn setFillColor(self: RectangleShape, color: sf.Color) void { + sf.c.sfRectangleShape_setFillColor(self.ptr, color.toCSFML()); +} + +/// Gets the size of this rectangle shape +pub fn getSize(self: RectangleShape) sf.Vector2f { + return sf.Vector2f.fromCSFML(sf.c.sfRectangleShape_getSize(self.ptr)); +} +/// Sets the size of this rectangle shape +pub fn setSize(self: RectangleShape, size: sf.Vector2f) void { + sf.c.sfRectangleShape_setSize(self.ptr, size.toCSFML()); +} + +/// Gets the position of this rectangle shape +pub fn getPosition(self: RectangleShape) sf.Vector2f { + return sf.Vector2f.fromCSFML(sf.c.sfRectangleShape_getPosition(self.ptr)); +} +/// Sets the position of this rectangle shape +pub fn setPosition(self: RectangleShape, pos: sf.Vector2f) void { + sf.c.sfRectangleShape_setPosition(self.ptr, pos.toCSFML()); +} +/// Adds the offset to this shape's position +pub fn move(self: RectangleShape, offset: sf.Vector2f) void { + sf.c.sfRectangleShape_move(self.ptr, offset.toCSFML()); +} + +/// Gets the origin of this rectangle shape +pub fn getOrigin(self: RectangleShape) sf.Vector2f { + return sf.Vector2f.fromCSFML(sf.c.sfRectangleShape_getOrigin(self.ptr)); +} +/// Sets the origin of this rectangle shape +pub fn setOrigin(self: RectangleShape, origin: sf.Vector2f) void { + sf.c.sfRectangleShape_setOrigin(self.ptr, origin.toCSFML()); +} + +/// Gets the rotation of this rectangle shape +pub fn getRotation(self: RectangleShape) f32 { + return sf.c.sfRectangleShape_getRotation(self.ptr); +} +/// Sets the rotation of this rectangle shape +pub fn setRotation(self: RectangleShape, angle: f32) void { + sf.c.sfRectangleShape_setRotation(self.ptr, angle); +} +/// Rotates this shape by a given amount +pub fn rotate(self: RectangleShape, angle: f32) void { + sf.c.sfRectangleShape_rotate(self.ptr, angle); +} + +/// Gets the texture of this shape +pub fn getTexture(self: RectangleShape) ?sf.Texture { + const t = sf.c.sfRectangleShape_getTexture(self.ptr); + if (t) |tex| { + return sf.Texture{ .const_ptr = tex }; + } else + return null; +} +/// Sets the texture of this shape +pub fn setTexture(self: RectangleShape, texture: ?sf.Texture) void { + var tex = if (texture) |t| t.get() else null; + sf.c.sfRectangleShape_setTexture(self.ptr, tex, 0); +} +/// Gets the sub-rectangle of the texture that the shape will display +pub fn getTextureRect(self: RectangleShape) sf.FloatRect { + return sf.FloatRect.fromCSFML(sf.c.sfRectangleShape_getTextureRect(self.ptr)); +} +/// Sets the sub-rectangle of the texture that the shape will display +pub fn setTextureRect(self: RectangleShape, rect: sf.FloatRect) void { + sf.c.sfRectangleShape_getTextureRect(self.ptr, rect.toCSFML()); +} + +/// Gets the bounds in the local coordinates system +pub fn getLocalBounds(self: RectangleShape) sf.FloatRect { + return sf.FloatRect.fromCSFML(sf.c.sfRectangleShape_getLocalBounds(self.ptr)); +} + +/// Gets the bounds in the global coordinates +pub fn getGlobalBounds(self: RectangleShape) sf.FloatRect { + return sf.FloatRect.fromCSFML(sf.c.sfRectangleShape_getGlobalBounds(self.ptr)); +} + +/// Pointer to the csfml structure +ptr: *sf.c.sfRectangleShape, + +test "rectangle shape: sane getters and setters" { + const tst = @import("std").testing; + + var rect = try RectangleShape.create(sf.Vector2f{ .x = 30, .y = 50 }); + defer rect.destroy(); + + try tst.expectEqual(sf.Vector2f{ .x = 30, .y = 50 }, rect.getSize()); + + rect.setFillColor(sf.Color.Yellow); + rect.setSize(.{ .x = 15, .y = 510 }); + rect.setRotation(15); + rect.setPosition(.{ .x = 1, .y = 2 }); + rect.setOrigin(.{ .x = 20, .y = 25 }); + rect.setTexture(null); //Weirdly, getTexture if texture wasn't set gives a wrong pointer + + try tst.expectEqual(sf.Color.Yellow, rect.getFillColor()); + try tst.expectEqual(sf.Vector2f{ .x = 15, .y = 510 }, rect.getSize()); + try tst.expectEqual(@as(f32, 15), rect.getRotation()); + try tst.expectEqual(sf.Vector2f{ .x = 1, .y = 2 }, rect.getPosition()); + try tst.expectEqual(sf.Vector2f{ .x = 20, .y = 25 }, rect.getOrigin()); + try tst.expectEqual(@as(?sf.Texture, null), rect.getTexture()); + + rect.rotate(5); + rect.move(.{ .x = -5, .y = 5 }); + + try tst.expectEqual(@as(f32, 20), rect.getRotation()); + try tst.expectEqual(sf.Vector2f{ .x = -4, .y = 7 }, rect.getPosition()); +} diff --git a/src/sfml/graphics/RenderWindow.zig b/src/sfml/graphics/RenderWindow.zig new file mode 100644 index 0000000..fa60ce5 --- /dev/null +++ b/src/sfml/graphics/RenderWindow.zig @@ -0,0 +1,182 @@ +//! Window that can serve as a target for 2D drawing. + +const sf = struct { + pub usingnamespace @import("../sfml.zig"); + pub usingnamespace system; + pub usingnamespace graphics; +}; + +const RenderWindow = @This(); + +// Constructor/destructor + +/// Inits a render window with a size, a bits per pixel (most put 32), a title and a style +/// The window will have the default style +pub fn create(size: sf.Vector2u, bpp: usize, title: [:0]const u8, style: u32) !RenderWindow { + var ret: RenderWindow = undefined; + + var mode: sf.c.sfVideoMode = .{ + .width = @intCast(c_uint, size.x), + .height = @intCast(c_uint, size.y), + .bitsPerPixel = @intCast(c_uint, bpp), + }; + + var window = sf.c.sfRenderWindow_create(mode, @ptrCast([*c]const u8, title), style, null); + + if (window) |w| { + ret.ptr = w; + } else { + return sf.Error.windowCreationFailed; + } + + return ret; +} + +/// Inits a render window with a size and a title +/// The window will have the default style +pub fn createDefault(size: sf.Vector2u, title: [:0]const u8) !RenderWindow { + var ret: RenderWindow = undefined; + + var mode: sf.c.sfVideoMode = .{ + .width = @intCast(c_uint, size.x), + .height = @intCast(c_uint, size.y), + .bitsPerPixel = 32, + }; + + var window = sf.c.sfRenderWindow_create(mode, @ptrCast([*c]const u8, title), sf.window.Style.defaultStyle, null); + + if (window) |w| { + ret.ptr = w; + } else { + return sf.Error.windowCreationFailed; + } + + return ret; +} + +/// Destroys this window object +pub fn destroy(self: RenderWindow) void { + sf.c.sfRenderWindow_destroy(self.ptr); +} + +// Event related + +/// Returns true if this window is still open +pub fn isOpen(self: RenderWindow) bool { + return sf.c.sfRenderWindow_isOpen(self.ptr) != 0; +} + +/// Closes this window +pub fn close(self: RenderWindow) void { + sf.c.sfRenderWindow_close(self.ptr); +} + +/// Gets an event from the queue, returns null is theres none +/// Use while on this to get all the events in your game loop +pub fn pollEvent(self: RenderWindow) ?sf.window.Event { + var event: sf.c.sfEvent = undefined; + if (sf.c.sfRenderWindow_pollEvent(self.ptr, &event) == 0) + return null; + + // Skip sfEvtMouseWheelMoved to avoid sending mouseWheelScrolled twice + if (event.type == sf.c.sfEvtMouseWheelMoved) { + return self.pollEvent(); + } + return sf.window.Event.fromCSFML(event); +} + +// Drawing functions + +/// Clears the drawing screen with a color +pub fn clear(self: RenderWindow, color: sf.Color) void { + sf.c.sfRenderWindow_clear(self.ptr, color.toCSFML()); +} + +/// Displays what has been drawn on the render area +pub fn display(self: RenderWindow) void { + sf.c.sfRenderWindow_display(self.ptr); +} + +/// Draw something on the screen (won't be visible until display is called) +/// Object must have a sfDraw function (look at CircleShape for reference) +/// You can pass a render state or null for default +pub fn draw(self: RenderWindow, to_draw: anytype, states: ?*sf.c.sfRenderStates) void { + const T = @TypeOf(to_draw); + if (comptime @import("std").meta.trait.hasFn("sfDraw")(T)) { + // Inline call of object's draw function + @call(.{ .modifier = .always_inline }, T.sfDraw, .{ to_draw, self, states }); + // to_draw.sfDraw(self, states); + } else @compileError("You must provide a drawable object (struct with \"sfDraw\" method)."); +} + +// Getters/setters +/// Gets the current view of the window +/// Unlike in SFML, you don't get a const pointer but a copy +pub fn getView(self: RenderWindow) sf.View { + return sf.View.fromCSFML(sf.c.sfRenderWindow_getView(self.ptr).?); +} +/// Gets the default view of this window +/// Unlike in SFML, you don't get a const pointer but a copy +pub fn getDefaultView(self: RenderWindow) sf.View { + return sf.View.fromCSFML(sf.c.sfRenderWindow_getDefaultView(self.ptr).?); +} +/// Sets the view of this window +pub fn setView(self: RenderWindow, view: sf.View) void { + var cview = view.toCSFML(); + defer sf.c.sfView_destroy(cview); + sf.c.sfRenderWindow_setView(self.ptr, cview); +} + +/// Gets the size of this window +pub fn getSize(self: RenderWindow) sf.Vector2u { + return sf.Vector2u.fromCSFML(sf.c.sfRenderWindow_getSize(self.ptr)); +} +/// Sets the size of this window +pub fn setSize(self: RenderWindow, size: sf.Vector2u) void { + sf.c.sfRenderWindow_setSize(self.ptr, size.toCSFML()); +} + +/// Gets the position of this window +pub fn getPosition(self: RenderWindow) sf.Vector2i { + return sf.Vector2i.fromCSFML(sf.c.sfRenderWindow_getPosition(self.ptr)); +} +/// Sets the position of this window +pub fn setPosition(self: RenderWindow, pos: sf.Vector2i) void { + sf.c.sfRenderWindow_setPosition(self.ptr, pos.toCSFML()); +} + +// TODO : unicode title? +/// Sets the title of this window +pub fn setTitle(self: RenderWindow, title: [:0]const u8) void { + sf.c.sfRenderWindow_setTitle(self.ptr, title); +} + +/// Sets the windows's framerate limit +pub fn setFramerateLimit(self: RenderWindow, fps: c_uint) void { + sf.c.sfRenderWindow_setFramerateLimit(self.ptr, fps); +} +/// Enables or disables vertical sync +pub fn setVerticalSyncEnabled(self: RenderWindow, enabled: bool) void { + sf.c.sfRenderWindow_setFramerateLimit(self.ptr, if (enabled) 1 else 0); +} + +/// Convert a point from target coordinates to world coordinates, using the current view (or the specified view) +pub fn mapPixelToCoords(self: RenderWindow, pixel: sf.Vector2i, view: ?sf.View) sf.Vector2f { + if (view) |v| { + var cview = v.toCSFML(); + defer sf.c.sfView_destroy(cview); + return sf.Vector2f.fromCSFML(sf.c.sfRenderWindow_mapPixelToCoords(self.ptr, pixel.toCSFML(), cview)); + } else return sf.Vector2f.fromCSFML(sf.c.sfRenderWindow_mapPixelToCoords(self.ptr, pixel.toCSFML(), null)); +} + +/// Convert a point from world coordinates to target coordinates, using the current view (or the specified view) +pub fn mapCoordsToPixel(self: RenderWindow, coords: sf.Vector2f, view: ?sf.View) sf.Vector2i { + if (view) |v| { + var cview = v.toCSFML(); + defer sf.c.sfView_destroy(cview); + return sf.Vector2i.fromCSFML(sf.c.sfRenderWindow_mapCoordsToPixel(self.ptr, coords.toCSFML(), cview)); + } else return sf.Vector2i.fromCSFML(sf.c.sfRenderWindow_mapCoordsToPixel(self.ptr, coords.toCSFML(), null)); +} + +/// Pointer to the csfml structure +ptr: *sf.c.sfRenderWindow diff --git a/src/sfml/graphics/Sprite.zig b/src/sfml/graphics/Sprite.zig new file mode 100644 index 0000000..aeb66bf --- /dev/null +++ b/src/sfml/graphics/Sprite.zig @@ -0,0 +1,152 @@ +//! Drawable representation of a texture, with its own transformations, color, etc. + +const sf = struct { + pub usingnamespace @import("../sfml.zig"); + pub usingnamespace system; + pub usingnamespace graphics; +}; + +const Sprite = @This(); + +// Constructor/destructor + +/// Inits a sprite with no texture +pub fn create() !Sprite { + var sprite = sf.c.sfSprite_create(); + if (sprite == null) + return sf.Error.nullptrUnknownReason; + + return Sprite{ .ptr = sprite.? }; +} + +/// Inits a sprite with a texture +pub fn createFromTexture(texture: sf.Texture) !Sprite { + var sprite = sf.c.sfSprite_create(); + if (sprite == null) + return sf.Error.nullptrUnknownReason; + + sf.c.sfSprite_setTexture(sprite, texture.get(), 1); + + return Sprite{ .ptr = sprite.? }; +} + +/// Destroys this sprite +pub fn destroy(self: Sprite) void { + sf.c.sfSprite_destroy(self.ptr); +} + +// Draw function +pub fn sfDraw(self: Sprite, window: sf.RenderWindow, states: ?*sf.c.sfRenderStates) void { + sf.c.sfRenderWindow_drawSprite(window.ptr, self.ptr, states); +} + +// Getters/setters + +/// Gets the position of this sprite +pub fn getPosition(self: Sprite) sf.Vector2f { + return sf.Vector2f.fromCSFML(sf.c.sfSprite_getPosition(self.ptr)); +} +/// Sets the position of this sprite +pub fn setPosition(self: Sprite, pos: sf.Vector2f) void { + sf.c.sfSprite_setPosition(self.ptr, pos.toCSFML()); +} +/// Adds the offset to this shape's position +pub fn move(self: Sprite, offset: sf.Vector2f) void { + sf.c.sfSprite_move(self.ptr, offset.toCSFML()); +} + +/// Gets the scale of this sprite +pub fn getScale(self: Sprite) sf.Vector2f { + return sf.Vector2f.fromCSFML(sf.c.sfSprite_getScale(self.ptr)); +} +/// Sets the scale of this sprite +pub fn setScale(self: Sprite, factor: sf.Vector2f) void { + sf.c.sfSprite_setScale(self.ptr, factor.toCSFML()); +} +/// Scales this sprite +pub fn scale(self: Sprite, factor: sf.Vector2f) void { + sf.c.sfSprite_scale(self.ptr, factor.toCSFML()); +} + +/// Gets the origin of this sprite +pub fn getOrigin(self: Sprite) sf.Vector2f { + return sf.Vector2f.fromCSFML(sf.c.sfSprite_getOrigin(self.ptr)); +} +/// Sets the origin of this sprite +pub fn setOrigin(self: Sprite, origin: sf.Vector2f) void { + sf.c.sfSprite_setOrigin(self.ptr, origin.toCSFML()); +} + +/// Gets the rotation of this sprite +pub fn getRotation(self: Sprite) f32 { + return sf.c.sfSprite_getRotation(self.ptr); +} +/// Sets the rotation of this sprite +pub fn setRotation(self: Sprite, angle: f32) void { + sf.c.sfSprite_setRotation(self.ptr, angle); +} +/// Rotates this shape by a given amount +pub fn rotate(self: Sprite, angle: f32) void { + sf.c.sfSprite_rotate(self.ptr, angle); +} + +/// Gets the color of this sprite +pub fn getColor(self: Sprite) sf.Color { + return sf.Color.fromCSFML(sf.c.sfSprite_getColor(self.ptr)); +} +/// Sets the color of this sprite +pub fn setColor(self: Sprite, color: sf.Color) void { + sf.c.sfSprite_setColor(self.ptr, color.toCSFML()); +} + +/// Gets the texture of this shape +pub fn getTexture(self: Sprite) ?sf.Texture { + const t = sf.c.sfSprite_getTexture(self.ptr); + if (t) |tex| { + return sf.Texture{ .const_ptr = tex }; + } else return null; +} +/// Sets this sprite's texture (the sprite will take the texture's dimensions) +pub fn setTexture(self: Sprite, texture: ?sf.Texture) void { + var tex = if (texture) |t| t.get() else null; + sf.c.sfSprite_setTexture(self.ptr, tex, 1); +} +/// Gets the sub-rectangle of the texture that the sprite will display +pub fn getTextureRect(self: Sprite) sf.IntRect { + return sf.IntRect.fromCSFML(sf.c.sfSprite_getTextureRect(self.ptr)); +} +/// Sets the sub-rectangle of the texture that the sprite will display +pub fn setTextureRect(self: Sprite, rect: sf.IntRect) void { + sf.c.sfSprite_setTextureRect(self.ptr, rect.toCSFML()); +} + +/// Pointer to the csfml structure +ptr: *sf.c.sfSprite, + +test "sprite: sane getters and setters" { + const tst = @import("std").testing; + + var spr = try Sprite.create(); + defer spr.destroy(); + + spr.setColor(sf.Color.Yellow); + spr.setRotation(15); + spr.setPosition(.{ .x = 1, .y = 2 }); + spr.setOrigin(.{ .x = 20, .y = 25 }); + spr.setScale(.{ .x = 2, .y = 2 }); + spr.setTexture(null); + + try tst.expectEqual(sf.Color.Yellow, spr.getColor()); + try tst.expectEqual(sf.Vector2f{ .x = 1, .y = 2 }, spr.getPosition()); + try tst.expectEqual(sf.Vector2f{ .x = 20, .y = 25 }, spr.getOrigin()); + try tst.expectEqual(@as(?sf.Texture, null), spr.getTexture()); + try tst.expectEqual(sf.Vector2f{ .x = 2, .y = 2 }, spr.getScale()); + + spr.rotate(5); + spr.move(.{ .x = -5, .y = 5 }); + spr.scale(.{ .x = 5, .y = 5 }); + + try tst.expectEqual(@as(f32, 20), spr.getRotation()); + try tst.expectEqual(sf.Vector2f{ .x = -4, .y = 7 }, spr.getPosition()); + try tst.expectEqual(sf.Vector2f{ .x = 10, .y = 10 }, spr.getScale()); +} diff --git a/src/sfml/graphics/Text.zig b/src/sfml/graphics/Text.zig new file mode 100644 index 0000000..9208511 --- /dev/null +++ b/src/sfml/graphics/Text.zig @@ -0,0 +1,205 @@ +//! Graphical text that can be drawn to a render target. + +const sf = struct { + pub usingnamespace @import("../sfml.zig"); + pub usingnamespace system; + pub usingnamespace graphics; +}; + +const Text = @This(); + +// Constructor/destructor + +/// Inits an empty text +pub fn create() !Text { + var text = sf.c.sfText_create(); + if (text == null) + return sf.Error.nullptrUnknownReason; + return Text{ .ptr = text.? }; +} +/// Inits a text with content +pub fn createWithText(string: [:0]const u8, font: sf.Font, character_size: usize) !Text { + var text = sf.c.sfText_create(); + if (text == null) + return sf.Error.nullptrUnknownReason; + sf.c.sfText_setFont(text, font.ptr); + sf.c.sfText_setCharacterSize(text, @intCast(c_uint, character_size)); + sf.c.sfText_setString(text, string); + return Text{ .ptr = text.? }; +} +/// Destroys a text +pub fn destroy(self: Text) void { + sf.c.sfText_destroy(self.ptr); +} + +// Draw function +pub fn sfDraw(self: Text, window: sf.RenderWindow, states: ?*sf.c.sfRenderStates) void { + sf.c.sfRenderWindow_drawText(window.ptr, self.ptr, states); +} + +// Getters/setters + +/// Sets the content of this text +pub fn setString(self: Text, string: [:0]const u8) void { + sf.c.sfText_setString(self.ptr, string); +} + +/// Sets the font of this text +pub fn setFont(self: Text, font: sf.Font) void { + sf.c.sfText_setFont(self.ptr, font.ptr); +} + +/// Gets the character size of this text +pub fn getCharacterSize(self: Text) usize { + return @intCast(usize, sf.c.sfText_getCharacterSize(self.ptr)); +} +/// Sets the character size of this text +pub fn setCharacterSize(self: Text, character_size: usize) void { + sf.c.sfText_setCharacterSize(self.ptr, @intCast(c_uint, character_size)); +} + +/// Gets the fill color of this text +pub fn getFillColor(self: Text) sf.Color { + return sf.Color.fromCSFML(sf.c.sfText_getFillColor(self.ptr)); +} +/// Sets the fill color of this text +pub fn setFillColor(self: Text, color: sf.Color) void { + sf.c.sfText_setFillColor(self.ptr, color.toCSFML()); +} + +/// Gets the outline color of this text +pub fn getOutlineColor(self: Text) sf.Color { + return sf.Color.fromCSFML(sf.c.sfText_getOutlineColor(self.ptr)); +} +/// Sets the outline color of this text +pub fn setOutlineColor(self: Text, color: sf.Color) void { + sf.c.sfText_setOutlineColor(self.ptr, color.toCSFML()); +} + +/// Gets the outline thickness of this text +pub fn getOutlineThickness(self: Text) f32 { + return sf.c.sfText_getOutlineThickness(self.ptr); +} +/// Sets the outline thickness of this text +pub fn setOutlineThickness(self: Text, thickness: f32) void { + sf.c.sfText_setOutlineThickness(self.ptr, thickness); +} + +/// Gets the position of this text +pub fn getPosition(self: Text) sf.Vector2f { + return sf.Vector2f.fromCSFML(sf.c.sfText_getPosition(self.ptr)); +} +/// Sets the position of this text +pub fn setPosition(self: Text, pos: sf.Vector2f) void { + sf.c.sfText_setPosition(self.ptr, pos.toCSFML()); +} +/// Adds the offset to this text +pub fn move(self: Text, offset: sf.Vector2f) void { + sf.c.sfText_move(self.ptr, offset.toCSFML()); +} + +/// Gets the origin of this text +pub fn getOrigin(self: Text) sf.Vector2f { + return sf.Vector2f.fromCSFML(sf.c.sfText_getOrigin(self.ptr)); +} +/// Sets the origin of this text +pub fn setOrigin(self: Text, origin: sf.Vector2f) void { + sf.c.sfText_setOrigin(self.ptr, origin.toCSFML()); +} + +/// Gets the rotation of this text +pub fn getRotation(self: Text) f32 { + return sf.c.sfText_getRotation(self.ptr); +} +/// Sets the rotation of this text +pub fn setRotation(self: Text, angle: f32) void { + sf.c.sfText_setRotation(self.ptr, angle); +} +/// Rotates this text by a given amount +pub fn rotate(self: Text, angle: f32) void { + sf.c.sfText_rotate(self.ptr, angle); +} + +/// Gets the scale of this text +pub fn getScale(self: Text) sf.Vector2f { + return sf.Vector2f.fromCSFML(sf.c.sfText_getScale(self.ptr)); +} +/// Sets the scale of this text +pub fn setScale(self: Text, factor: sf.Vector2f) void { + sf.c.sfText_setScale(self.ptr, factor.toCSFML()); +} +/// Scales this text +pub fn scale(self: Text, factor: sf.Vector2f) void { + sf.c.sfText_scale(self.ptr, factor.toCSFML()); +} + +/// return the position of the index-th character +pub fn findCharacterPos(self: Text, index: usize) sf.Vector2f { + return sf.Vector2f.fromCSFML(sf.c.sfText_findCharacterPos(self.ptr, index)); +} + +/// Gets the letter spacing factor +pub fn getLetterSpacing(self: Text) f32 { + return sf.c.sfText_getLetterSpacing(self.ptr); +} +/// Sets the letter spacing factor +pub fn setLetterSpacing(self: Text, spacing_factor: f32) void { + sf.c.sfText_setLetterSpacing(self.ptr, spacing_factor); +} + +/// Gets the line spacing factor +pub fn getLineSpacing(self: Text) f32 { + return sf.c.sfText_getLineSpacing(self.ptr); +} +/// Sets the line spacing factor +pub fn setLineSpacing(self: Text, spacing_factor: f32) void { + sf.c.sfText_setLineSpacing(self.ptr, spacing_factor); +} + +/// Gets the local bounding rectangle of the text +pub fn getLocalBounds(self: Text) sf.FloatRect { + return sf.FloatRect.fromCSFML(sf.c.sfText_getLocalBounds(self.ptr)); +} +/// Gets the global bounding rectangle of the text +pub fn getGlobalBounds(self: Text) sf.FloatRect { + return sf.FloatRect.fromCSFML(sf.c.sfText_getGlobalBounds(self.ptr)); +} + +pub const getTransform = @compileError("Function is not implemented yet."); +pub const getInverseTransform = @compileError("Function is not implemented yet."); + +/// Pointer to the csfml font +ptr: *sf.c.sfText, + +test "text: sane getters and setters" { + const tst = @import("std").testing; + + var text = try Text.create(); + defer text.destroy(); + + text.setString("hello"); + text.setFillColor(sf.Color.Yellow); + text.setOutlineColor(sf.Color.Red); + text.setOutlineThickness(2); + text.setCharacterSize(10); + text.setRotation(15); + text.setPosition(.{ .x = 1, .y = 2 }); + text.setOrigin(.{ .x = 20, .y = 25 }); + text.setScale(.{ .x = 2, .y = 2 }); + + text.rotate(5); + text.move(.{ .x = -5, .y = 5 }); + text.scale(.{ .x = 2, .y = 3 }); + + try tst.expectEqual(sf.Color.Yellow, text.getFillColor()); + try tst.expectEqual(sf.Color.Red, text.getOutlineColor()); + try tst.expectEqual(@as(f32, 2), text.getOutlineThickness()); + try tst.expectEqual(@as(usize, 10), text.getCharacterSize()); + try tst.expectEqual(@as(f32, 20), text.getRotation()); + try tst.expectEqual(sf.Vector2f{ .x = -4, .y = 7 }, text.getPosition()); + try tst.expectEqual(sf.Vector2f{ .x = 20, .y = 25 }, text.getOrigin()); + try tst.expectEqual(sf.Vector2f{ .x = 4, .y = 6 }, text.getScale()); + + _ = text.getLocalBounds(); + _ = text.getGlobalBounds(); +} diff --git a/src/sfml/graphics/VertexArray.zig b/src/sfml/graphics/VertexArray.zig new file mode 100644 index 0000000..ea4ccb2 --- /dev/null +++ b/src/sfml/graphics/VertexArray.zig @@ -0,0 +1,32 @@ +//! Define a set of one or more 2D primitives. + +const sf = @import("../sfml.zig"); + +// CONSTRUCTION ZONE + +const VertexArray = @This(); + +/// Creates a vertex array from a slice of vertices +pub fn createFromSlice(vertex: []const sf.graphics.Vertex, primitive: sf.graphics.PrimitiveType) !VertexArray { + var va = sf.c.sfVertexArray_create(); + if (va) |vert| { + sf.c.sfVertexArray_setPrimitiveType(vert, @enumToInt(primitive)); + sf.c.sfVertexArray_resize(vert, vertex.len); + for (vertex) |v, i| + sf.c.sfVertexArray_getVertex(vert, i).* = @bitCast(sf.c.sfVertex, v); + return VertexArray{ .ptr = vert }; + } else return sf.Error.nullptrUnknownReason; +} + +/// Destroys a vertex array +pub fn destroy(self: VertexArray) void { + sf.c.sfVertexArray_destroy(self.ptr); +} + +// Draw function +pub fn sfDraw(self: VertexArray, window: sf.graphics.RenderWindow, states: ?*sf.c.sfRenderStates) void { + sf.c.sfRenderWindow_drawVertexArray(window.ptr, self.ptr, states); +} + +/// Pointer to the csfml structure +ptr: *sf.c.sfVertexArray, diff --git a/src/sfml/graphics/View.zig b/src/sfml/graphics/View.zig new file mode 100644 index 0000000..48882e2 --- /dev/null +++ b/src/sfml/graphics/View.zig @@ -0,0 +1,104 @@ +//! 2D camera that defines what region is shown on screen. + +const sf = struct { + pub usingnamespace @import("../sfml.zig"); + pub usingnamespace system; + pub usingnamespace graphics; +}; + +const View = @This(); + +/// Creates a view from a rectangle +pub fn fromRect(rect: sf.FloatRect) View { + var ret: View = undefined; + ret.center = rect.getCorner(); + ret.size = rect.getSize(); + ret.center = ret.center.add(ret.size.scale(0.5)); + ret.viewport = sf.FloatRect.init(0, 0, 1, 1); + return ret; +} + +/// Creates a view from a CSFML object +/// This is mainly for the inner workings of this wrapper +pub fn fromCSFML(view: *const sf.c.sfView) View { + var ret: View = undefined; + ret.center = sf.Vector2f.fromCSFML(sf.c.sfView_getCenter(view)); + ret.size = sf.Vector2f.fromCSFML(sf.c.sfView_getSize(view)); + ret.viewport = sf.FloatRect.fromCSFML(sf.c.sfView_getViewport(view)); + return ret; +} + +/// Creates a CSFML view from this view +/// This is mainly for the inner workings of this wrapper +/// The resulting view must be destroyed! +pub fn toCSFML(self: View) *sf.c.sfView { + var view = sf.c.sfView_create().?; + sf.c.sfView_setCenter(view, self.center.toCSFML()); + sf.c.sfView_setSize(view, self.size.toCSFML()); + sf.c.sfView_setViewport(view, self.viewport.toCSFML()); + return view; +} + +pub fn getRect(self: View) sf.FloatRect { + return sf.FloatRect.init( + self.center.x - self.size.x / 2, + self.center.y - self.size.y / 2, + self.size.x, + self.size.y, + ); +} + +pub fn setSize(self: *View, size: sf.Vector2f) void { + self.size = size; +} + +pub fn setCenter(self: *View, center: sf.Vector2f) void { + self.center = center; +} + +pub fn zoom(self: *View, factor: f32) void { + self.size = .{ .x = self.size.x * factor, .y = self.size.y * factor }; +} + +// View variables +/// Center of the view, what this view "looks" at +center: sf.Vector2f, +/// Width and height of the view +size: sf.Vector2f, +/// The viewport of this view +viewport: sf.FloatRect, + +test "view: from rect" { + const tst = @import("std").testing; + + // Testing if the view from rect initialization works + var rect = sf.FloatRect.init(10, -15, 700, 600); + + var view = sf.c.sfView_createFromRect(rect.toCSFML()); + defer sf.c.sfView_destroy(view); + + var view2 = View.fromRect(rect); + + var center = sf.Vector2f.fromCSFML(sf.c.sfView_getCenter(view)); + var size = sf.Vector2f.fromCSFML(sf.c.sfView_getSize(view)); + + try tst.expectApproxEqAbs(center.x, view2.center.x, 0.00001); + try tst.expectApproxEqAbs(center.y, view2.center.y, 0.00001); + try tst.expectApproxEqAbs(size.x, view2.size.x, 0.00001); + try tst.expectApproxEqAbs(size.y, view2.size.y, 0.00001); + + var rect_ret = view2.getRect(); + + try tst.expectApproxEqAbs(rect.left, rect_ret.left, 0.00001); + try tst.expectApproxEqAbs(rect.top, rect_ret.top, 0.00001); + try tst.expectApproxEqAbs(rect.width, rect_ret.width, 0.00001); + try tst.expectApproxEqAbs(rect.height, rect_ret.height, 0.00001); + + view2.setCenter(.{ .x = 400, .y = 300 }); + view2.setSize(.{ .x = 800, .y = 600 }); + rect_ret = view2.getRect(); + try tst.expectApproxEqAbs(@as(f32, 0), rect_ret.left, 0.00001); + try tst.expectApproxEqAbs(@as(f32, 0), rect_ret.top, 0.00001); + try tst.expectApproxEqAbs(@as(f32, 800), rect_ret.width, 0.00001); + try tst.expectApproxEqAbs(@as(f32, 600), rect_ret.height, 0.00001); +} diff --git a/src/sfml/graphics/color.zig b/src/sfml/graphics/color.zig new file mode 100644 index 0000000..d6aa850 --- /dev/null +++ b/src/sfml/graphics/color.zig @@ -0,0 +1,166 @@ +//! Utility class for manipulating RGBA colors. + +const sf = @import("../sfml_import.zig"); +const math = @import("std").math; + +pub const Color = packed struct { + /// Converts a color from a csfml object + /// For inner workings + pub fn fromCSFML(col: sf.c.sfColor) Color { + return @bitCast(Color, col); + } + + /// Converts this color to a csfml one + /// For inner workings + pub fn toCSFML(self: Color) sf.c.sfColor { + return @bitCast(sf.c.sfColor, self); + } + + /// Inits a color with rgb components + pub fn fromRGB(red: u8, green: u8, blue: u8) Color { + return Color{ + .r = red, + .g = green, + .b = blue, + .a = 0xff, + }; + } + + /// Inits a color with rgba components + pub fn fromRGBA(red: u8, green: u8, blue: u8, alpha: u8) Color { + return Color{ + .r = red, + .g = green, + .b = blue, + .a = alpha, + }; + } + + /// Inits a color from a 32bits value (RGBA in that order) + pub fn fromInteger(int: u32) Color { + return Color{ + .r = @truncate(u8, (int & 0xff000000) >> 24), + .g = @truncate(u8, (int & 0x00ff0000) >> 16), + .b = @truncate(u8, (int & 0x0000ff00) >> 8), + .a = @truncate(u8, (int & 0x000000ff) >> 0), + }; + } + + /// Gets a 32 bit integer representing the color + pub fn toInteger(self: Color) u32 { + return (@intCast(u32, self.r) << 24) | + (@intCast(u32, self.g) << 16) | + (@intCast(u32, self.b) << 8) | + (@intCast(u32, self.a) << 0); + } + + /// Creates a color with rgba floats from 0 to 1 + fn fromFloats(red: f32, green: f32, blue: f32, alpha: f32) Color { + return Color{ + .r = @floatToInt(u8, math.clamp(red, 0.0, 1.0) * 255.0), + .g = @floatToInt(u8, math.clamp(green, 0.0, 1.0) * 255.0), + .b = @floatToInt(u8, math.clamp(blue, 0.0, 1.0) * 255.0), + .a = @floatToInt(u8, math.clamp(alpha, 0.0, 1.0) * 255.0), + }; + } + + /// Creates a color from HSV and transparency components (this is not part of the SFML) + /// hue is in degrees, saturation and value are in percents + pub fn fromHSVA(hue: f32, saturation: f32, value: f32, alpha: f32) Color { + const h = hue; + const s = saturation / 100; + const v = value / 100; + const a = alpha; + + var hh: f32 = h; + + if (v <= 0.0) + return fromFloats(0, 0, 0, a); + + if (hh >= 360.0) + hh = 0; + hh /= 60.0; + + var ff: f32 = hh - math.floor(hh); + + var p: f32 = v * (1.0 - s); + var q: f32 = v * (1.0 - (s * ff)); + var t: f32 = v * (1.0 - (s * (1.0 - ff))); + + return switch (@floatToInt(usize, hh)) { + 0 => fromFloats(v, t, p, a), + 1 => fromFloats(q, v, p, a), + 2 => fromFloats(p, v, t, a), + 3 => fromFloats(p, q, v, a), + 4 => fromFloats(t, p, v, a), + else => fromFloats(v, p, q, a), + }; + } + + // Colors + /// Black color + pub const Black = Color.fromRGB(0, 0, 0); + /// White color + pub const White = Color.fromRGB(255, 255, 255); + /// Red color + pub const Red = Color.fromRGB(255, 0, 0); + /// Green color + pub const Green = Color.fromRGB(0, 255, 0); + /// Blue color + pub const Blue = Color.fromRGB(0, 0, 255); + /// Yellow color + pub const Yellow = Color.fromRGB(255, 255, 0); + /// Magenta color + pub const Magenta = Color.fromRGB(255, 0, 255); + /// Cyan color + pub const Cyan = Color.fromRGB(0, 255, 255); + /// Transparent color + pub const Transparent = Color.fromRGBA(0, 0, 0, 0); + + /// Red component + r: u8, + /// Green component + g: u8, + /// Blue component + b: u8, + /// Alpha (opacity) component + a: u8, +}; + +test "color: conversions" { + const tst = @import("std").testing; + + var code: u32 = 0x4BDA9CFF; + var col = Color.fromInteger(code); + + try tst.expectEqual(Color.fromRGB(75, 218, 156), col); + try tst.expectEqual(code, col.toInteger()); + + var csfml_col = sf.c.sfColor_fromInteger(@as(c_uint, code)); + + try tst.expectEqual(Color.fromCSFML(csfml_col), col); +} + +test "color: hsv to rgb" { + const tst = @import("std").testing; + + var col = Color.fromHSVA(10, 20, 100, 255); + + try tst.expectEqual(Color.fromRGB(255, 212, 204), col); +} + +test "color: sane from/to CSFML color" { + const tst = @import("std").testing; + + const col = Color.fromRGBA(5, 12, 28, 127); + const ccol = col.toCSFML(); + + try tst.expectEqual(col.r, ccol.r); + try tst.expectEqual(col.g, ccol.g); + try tst.expectEqual(col.b, ccol.b); + try tst.expectEqual(col.a, ccol.a); + + const col2 = Color.fromCSFML(ccol); + + try tst.expectEqual(col, col2); +} diff --git a/src/sfml/graphics/primitive_type.zig b/src/sfml/graphics/primitive_type.zig new file mode 100644 index 0000000..9e191a5 --- /dev/null +++ b/src/sfml/graphics/primitive_type.zig @@ -0,0 +1,9 @@ +pub const PrimitiveType = enum(c_uint) { + Points, + Lines, + LineStrip, + Triangles, + TriangleStrip, + TriangleFan, + Quads, +}; diff --git a/src/sfml/graphics/rect.zig b/src/sfml/graphics/rect.zig new file mode 100644 index 0000000..184799c --- /dev/null +++ b/src/sfml/graphics/rect.zig @@ -0,0 +1,161 @@ +//! Utility class for manipulating 2D axis aligned rectangles. + +const sf = struct { + pub usingnamespace @import("../sfml.zig"); + pub usingnamespace system; +}; +const math = @import("std").math; + +pub fn Rect(comptime T: type) type { + return packed struct { + const Self = @This(); + + /// The CSFML vector type equivalent + const CsfmlEquivalent = switch (T) { + c_int => sf.c.sfIntRect, + f32 => sf.c.sfFloatRect, + else => void, + }; + + /// Creates a rect (just for convinience) + pub fn init(left: T, top: T, width: T, height: T) Self { + return Self{ + .left = left, + .top = top, + .width = width, + .height = height, + }; + } + + /// Makes a CSFML rect with this rect (only if the corresponding type exists) + /// This is mainly for the inner workings of this wrapper + pub fn toCSFML(self: Self) CsfmlEquivalent { + if (CsfmlEquivalent == void) @compileError("This rectangle type doesn't have a CSFML equivalent."); + return @bitCast(CsfmlEquivalent, self); + } + + /// Creates a rect from a CSFML one (only if the corresponding type exists) + /// This is mainly for the inner workings of this wrapper + pub fn fromCSFML(rect: CsfmlEquivalent) Self { + if (CsfmlEquivalent == void) @compileError("This rectangle type doesn't have a CSFML equivalent."); + return @bitCast(Self, rect); + } + + /// Checks if a point is inside this recangle + pub fn contains(self: Self, vec: sf.Vector2(T)) bool { + // Shamelessly stolen + var min_x: T = math.min(self.left, self.left + self.width); + var max_x: T = math.max(self.left, self.left + self.width); + var min_y: T = math.min(self.top, self.top + self.height); + var max_y: T = math.max(self.top, self.top + self.height); + + return (vec.x >= min_x and + vec.x < max_x and + vec.y >= min_y and + vec.y < max_y); + } + + /// Checks if two rectangles have a common intersection, if yes returns that zone, if not returns null + pub fn intersects(self: Self, other: Self) ?Self { + // Shamelessly stolen too + var r1_min_x: T = math.min(self.left, self.left + self.width); + var r1_max_x: T = math.max(self.left, self.left + self.width); + var r1_min_y: T = math.min(self.top, self.top + self.height); + var r1_max_y: T = math.max(self.top, self.top + self.height); + + var r2_min_x: T = math.min(other.left, other.left + other.width); + var r2_max_x: T = math.max(other.left, other.left + other.width); + var r2_min_y: T = math.min(other.top, other.top + other.height); + var r2_max_y: T = math.max(other.top, other.top + other.height); + + var inter_left: T = math.max(r1_min_x, r2_min_x); + var inter_top: T = math.max(r1_min_y, r2_min_y); + var inter_right: T = math.min(r1_max_x, r2_max_x); + var inter_bottom: T = math.min(r1_max_y, r2_max_y); + + if (inter_left < inter_right and inter_top < inter_bottom) { + return Self.init(inter_left, inter_top, inter_right - inter_left, inter_bottom - inter_top); + } else { + return null; + } + } + + /// Checks if two rectangles are the same + pub fn equals(self: Self, other: Self) bool { + return (self.left == other.left and + self.top == other.top and + self.width == other.width and + self.height == other.height); + } + + /// Gets a vector with left and top components inside + pub fn getCorner(self: Self) sf.Vector2(T) { + return sf.Vector2(T){ .x = self.left, .y = self.top }; + } + /// Gets a vector with the bottom right corner coordinates + pub fn getOtherCorner(self: Self) sf.Vector2(T) { + return self.getCorner().add(self.getSize()); + } + /// Gets a vector with width and height components inside + pub fn getSize(self: Self) sf.Vector2(T) { + return sf.Vector2(T){ .x = self.width, .y = self.height }; + } + + /// x component of the top left corner + left: T, + /// x component of the top left corner + top: T, + /// width of the rectangle + width: T, + /// height of the rectangle + height: T + }; +} + +test "rect: intersect" { + const tst = @import("std").testing; + + var r1 = Rect(c_int).init(0, 0, 10, 10); + var r2 = Rect(c_int).init(6, 6, 20, 20); + var r3 = Rect(c_int).init(-5, -5, 10, 10); + + try tst.expectEqual(@as(?Rect(c_int), null), r2.intersects(r3)); + + var inter1: sf.c.sfIntRect = undefined; + var inter2: sf.c.sfIntRect = undefined; + + try tst.expectEqual(sf.c.sfIntRect_intersects(&r1.toCSFML(), &r2.toCSFML(), &inter1), 1); + try tst.expectEqual(sf.c.sfIntRect_intersects(&r1.toCSFML(), &r3.toCSFML(), &inter2), 1); + + try tst.expectEqual(Rect(c_int).fromCSFML(inter1), r1.intersects(r2).?); + try tst.expectEqual(Rect(c_int).fromCSFML(inter2), r1.intersects(r3).?); +} + +test "rect: contains" { + const tst = @import("std").testing; + + var r1 = Rect(f32).init(0, 0, 10, 10); + + try tst.expect(r1.contains(.{ .x = 0, .y = 0 })); + try tst.expect(r1.contains(.{ .x = 9, .y = 9 })); + try tst.expect(!r1.contains(.{ .x = 5, .y = -1 })); + try tst.expect(!r1.contains(.{ .x = 10, .y = 5 })); +} + +test "rect: sane from/to CSFML rect" { + const tst = @import("std").testing; + + inline for ([_]type{ c_int, f32 }) |T| { + const rect = Rect(T).init(1, 3, 5, 10); + const crect = rect.toCSFML(); + + try tst.expectEqual(rect.left, crect.left); + try tst.expectEqual(rect.top, crect.top); + try tst.expectEqual(rect.width, crect.width); + try tst.expectEqual(rect.height, crect.height); + + const rect2 = Rect(T).fromCSFML(crect); + + try tst.expectEqual(rect, rect2); + } +} diff --git a/src/sfml/graphics/texture.zig b/src/sfml/graphics/texture.zig new file mode 100644 index 0000000..2de3d93 --- /dev/null +++ b/src/sfml/graphics/texture.zig @@ -0,0 +1,242 @@ +//! Image living on the graphics card that can be used for drawing. + +const sf = struct { + pub usingnamespace @import("../sfml.zig"); + pub usingnamespace system; + pub usingnamespace graphics; +}; + +const std = @import("std"); +const assert = std.debug.assert; + +const TextureType = enum { ptr, const_ptr }; + +pub const Texture = union(TextureType) { + const Self = @This(); + + // Constructor/destructor + + /// Creates a texture from nothing + pub fn create(size: sf.Vector2u) !Self { + var tex = sf.c.sfTexture_create(@intCast(c_uint, size.x), @intCast(c_uint, size.y)); + if (tex == null) + return sf.Error.nullptrUnknownReason; + return Self{ .ptr = tex.? }; + } + /// Loads a texture from a file + pub fn createFromFile(path: [:0]const u8) !Self { + var tex = sf.c.sfTexture_createFromFile(path, null); + if (tex == null) + return sf.Error.resourceLoadingError; + return Self{ .ptr = tex.? }; + } + /// Creates an texture from an image + pub fn createFromImage(image: sf.Image, area: ?sf.IntRect) !Self { + var tex = if (area) |a| + sf.c.sfTexture_createFromImage(image.ptr, &a.toCSFML()) + else + sf.c.sfTexture_createFromImage(image.ptr, null); + + if (tex == null) + return sf.Error.nullptrUnknownReason; + return Self{ .ptr = tex.? }; + } + + /// Destroys a texture + /// Be careful, you can only destroy non const textures + pub fn destroy(self: Self) void { + // TODO : is it possible to detect that comptime? + // Should this panic? + if (self == .const_ptr) + @panic("Can't destroy a const texture pointer"); + sf.c.sfTexture_destroy(self.ptr); + } + + // Getters/Setters + + /// Gets a const pointer to this texture + pub fn get(self: Self) *const sf.c.sfTexture { + return switch (self) { + .ptr => self.ptr, + .const_ptr => self.const_ptr, + }; + } + /// Clones this texture (the clone won't be const) + pub fn copy(self: Self) !Self { + var cpy = sf.c.sfTexture_copy(self.get()); + if (cpy == null) + return sf.Error.nullptrUnknownReason; + return Self{ .ptr = cpy.? }; + } + /// Makes this texture constant (I don't know why you would do that) + pub fn makeConst(self: *Self) void { + self.* = Self{ .const_ptr = self.get() }; + } + + /// Gets the size of this image + pub fn getSize(self: Self) sf.Vector2u { + // This is a hack + _ = sf.c.sfTexture_getSize(self.get()); + // Register Rax holds the return val of function calls that can fit in a register + const rax: usize = asm volatile ("" + : [ret] "={rax}" (-> usize) + ); + var x: u32 = @truncate(u32, (rax & 0x00000000FFFFFFFF) >> 00); + var y: u32 = @truncate(u32, (rax & 0xFFFFFFFF00000000) >> 32); + return sf.Vector2u{ .x = x, .y = y }; + } + /// Gets the pixel count of this image + pub fn getPixelCount(self: Self) usize { + var dim = self.getSize(); + return dim.x * dim.y; + } + + /// Updates the pixels of the image from an array of pixels (colors) + pub fn updateFromPixels(self: Self, pixels: []const sf.Color, zone: ?sf.Rect(c_uint)) !void { + if (self == .const_ptr) + @panic("Can't set pixels on a const texture"); + if (self.isSrgb()) + @panic("Updating an srgb from a pixel array isn't implemented"); + + var real_zone: sf.Rect(c_uint) = undefined; + var size = self.getSize(); + + if (zone) |z| { + // Check if the given zone is fully inside the image + var intersection = z.intersects(sf.Rect(c_uint).init(0, 0, size.x, size.y)); + + if (intersection) |i| { + if (!i.equals(z)) + return sf.Error.areaDoesNotFit; + } else return sf.Error.areaDoesNotFit; + + real_zone = z; + } else { + real_zone.left = 0; + real_zone.top = 0; + real_zone.width = size.x; + real_zone.height = size.y; + } + // Check if there is enough data + if (pixels.len < real_zone.width * real_zone.height) + return sf.Error.notEnoughData; + + sf.c.sfTexture_updateFromPixels(self.ptr, @ptrCast([*]const u8, pixels.ptr), real_zone.width, real_zone.height, real_zone.left, real_zone.top); + } + /// Updates the pixels of the image from an other texture + pub fn updateFromTexture(self: Self, other: Texture, copy_pos: ?sf.Vector2u) void { + var pos = if (copy_pos) |a| a else sf.Vector2u{ .x = 0, .y = 0 }; + var max = other.getSize().add(pos); + var size = self.getSize(); + + assert(max.x < size.x and max.y < size.y); + + sf.c.sfTexture_updateFromTexture(self.ptr, other.get(), pos.x, pos.y); + } + /// Updates the pixels of the image from an image + pub fn updateFromImage(self: Self, image: sf.Image, copy_pos: ?sf.Vector2u) void { + var pos = if (copy_pos) |a| a else sf.Vector2u{ .x = 0, .y = 0 }; + var max = image.getSize().add(pos); + var size = self.getSize(); + + assert(max.x < size.x and max.y < size.y); + + sf.c.sfTexture_updateFromImage(self.ptr, image.ptr, pos.x, pos.y); + } + + /// Tells whether or not this texture is to be smoothed + pub fn isSmooth(self: Self) bool { + return sf.c.sfTexture_isSmooth(self.ptr) != 0; + } + /// Enables or disables texture smoothing + pub fn setSmooth(self: Self, smooth: bool) void { + if (self == .const_ptr) + @panic("Can't set properties on a const texture"); + + sf.c.sfTexture_setSmooth(self.ptr, if (smooth) 1 else 0); + } + + /// Tells whether or not this texture should repeat when rendering outside its bounds + pub fn isRepeated(self: Self) bool { + return sf.c.sfTexture_isRepeated(self.ptr) != 0; + } + /// Enables or disables texture repeating + pub fn setRepeated(self: Self, repeated: bool) void { + if (self == .const_ptr) + @panic("Can't set properties on a const texture"); + + sf.c.sfTexture_setRepeated(self.ptr, if (repeated) 1 else 0); + } + + /// Tells whether or not this texture has colors in the SRGB format + /// SRGB functions arent implemented yet + pub fn isSrgb(self: Self) bool { + return sf.c.sfTexture_isSrgb(self.ptr) != 0; + } + /// Enables or disables SRGB + pub fn setSrgb(self: Self, srgb: bool) void { + if (self == .const_ptr) + @panic("Can't set properties on a const texture"); + + sf.c.sfTexture_setSrgb(self.ptr, if (srgb) 1 else 0); + } + + /// Swaps this texture's contents with an other texture + pub fn swap(self: Self, other: Texture) void { + if (self == .const_ptr or other == .const_ptr) + @panic("Texture swapping must be done between two non const textures"); + + sf.c.sfTexture_swap(self.ptr, other.ptr); + } + + /// Pointer to the csfml texture + ptr: *sf.c.sfTexture, + /// Const pointer to the csfml texture + const_ptr: *const sf.c.sfTexture +}; + +test "texture: sane getters and setters" { + const tst = std.testing; + const allocator = std.heap.page_allocator; + + var tex = try Texture.create(.{ .x = 12, .y = 10 }); + defer tex.destroy(); + + var size = tex.getSize(); + + tex.setSrgb(false); + tex.setSmooth(true); + tex.setRepeated(true); + + try tst.expectEqual(@as(u32, 12), size.x); + try tst.expectEqual(@as(u32, 10), size.y); + try tst.expectEqual(@as(usize, 120), tex.getPixelCount()); + + var pixel_data = try allocator.alloc(sf.Color, 120); + defer allocator.free(pixel_data); + + for (pixel_data) |*c, i| { + c.* = sf.graphics.Color.fromHSVA(@intToFloat(f32, i) / 144 * 360, 100, 100, 1); + } + + try tex.updateFromPixels(pixel_data, null); + + try tst.expect(!tex.isSrgb()); + try tst.expect(tex.isSmooth()); + try tst.expect(tex.isRepeated()); + + var t = tex; + t.makeConst(); + + var copy = try t.copy(); + + try tst.expectEqual(@as(usize, 120), copy.getPixelCount()); + + var tex2 = try Texture.create(.{ .x = 100, .y = 100 }); + defer tex2.destroy(); + + copy.swap(tex2); + + try tst.expectEqual(@as(usize, 100 * 100), copy.getPixelCount()); + try tst.expectEqual(@as(usize, 120), tex2.getPixelCount()); +} diff --git a/src/sfml/graphics/vertex.zig b/src/sfml/graphics/vertex.zig new file mode 100644 index 0000000..97b25f5 --- /dev/null +++ b/src/sfml/graphics/vertex.zig @@ -0,0 +1,9 @@ +//! Define a point with color and texture coordinates. + +const sf = @import("../sfml.zig"); + +pub const Vertex = packed struct { + position: sf.system.Vector2f, + color: sf.graphics.Color, + tex_coords: sf.system.Vector2f, +}; diff --git a/src/sfml/sfml.zig b/src/sfml/sfml.zig new file mode 100644 index 0000000..da1dc4b --- /dev/null +++ b/src/sfml/sfml.zig @@ -0,0 +1,62 @@ +//! Import this to get all the sfml wrapper classes + +pub const c = @import("sfml_import.zig").c; + +pub const Error = @import("sfml_errors.zig").Error; + +pub const system = struct { + pub const Vector2 = @import("system/vector.zig").Vector2; + pub const Vector2i = Vector2(c_int); + pub const Vector2u = Vector2(c_uint); + pub const Vector2f = Vector2(f32); + pub const Vector3f = @import("system/vector.zig").Vector3f; + pub const Time = @import("system/Time.zig"); + pub const Clock = @import("system/Clock.zig"); +}; + +pub const window = struct { + pub const Event = @import("window/event.zig").Event; + pub const Style = @import("window/Style.zig"); + pub const keyboard = @import("window/keyboard.zig"); + pub const mouse = @import("window/mouse.zig"); +}; + +pub const graphics = struct { + pub const Color = @import("graphics/color.zig").Color; + pub const RenderWindow = @import("graphics/RenderWindow.zig"); + pub const Image = @import("graphics/Image.zig"); + pub const Texture = @import("graphics/texture.zig").Texture; + pub const Sprite = @import("graphics/Sprite.zig"); + pub const CircleShape = @import("graphics/CircleShape.zig"); + pub const RectangleShape = @import("graphics/RectangleShape.zig"); + pub const Rect = @import("graphics/rect.zig").Rect; + pub const IntRect = Rect(c_int); + pub const FloatRect = Rect(f32); + pub const View = @import("graphics/View.zig"); + pub const Font = @import("graphics/Font.zig"); + pub const Text = @import("graphics/Text.zig"); + pub const Vertex = @import("graphics/vertex.zig").Vertex; + pub const VertexArray = @import("graphics/VertexArray.zig"); + pub const PrimitiveType = @import("graphics/primitive_type.zig").PrimitiveType; +}; + +pub const audio = struct { + pub const Music = @import("audio/Music.zig"); + pub const SoundBuffer = @import("audio/SoundBuffer.zig"); + pub const Sound = @import("audio/Sound.zig"); +}; + +pub const network = @compileError("network module: to be implemented one day"); + +pub const touch = @compileError("touch not available yet"); +pub const joystick = @compileError("Joystick not available yet"); +pub const sensor = @compileError("Sensor not available yet"); +pub const clipboard = @compileError("Clipboard not available yet"); +pub const Cursor = @compileError("Cursor not available yet"); + +pub const VertexBuffer = @compileError("VertexArray not available yet"); +pub const BlendMode = @compileError("BlendMode not available yet"); +pub const RenderStates = @compileError("RenderStates not available yet"); +pub const RenderTexture = @compileError("RenderTexture not available yet"); +pub const Shader = @compileError("Shader not available yet"); +pub const Transform = @compileError("Transform not available yet"); diff --git a/src/sfml/sfml_errors.zig b/src/sfml/sfml_errors.zig new file mode 100644 index 0000000..d09da43 --- /dev/null +++ b/src/sfml/sfml_errors.zig @@ -0,0 +1,3 @@ +//! Errors for the wrapper + +pub const Error = error{ nullptrUnknownReason, windowCreationFailed, resourceLoadingError, notEnoughData, areaDoesNotFit, outOfBounds, savingInFileFailed }; diff --git a/src/sfml/sfml_import.zig b/src/sfml/sfml_import.zig new file mode 100644 index 0000000..be21671 --- /dev/null +++ b/src/sfml/sfml_import.zig @@ -0,0 +1,8 @@ +//! Imports the csfml c headers + +pub const c = @cImport({ + @cInclude("SFML/Graphics.h"); + @cInclude("SFML/Window.h"); + @cInclude("SFML/System.h"); + @cInclude("SFML/Audio.h"); +}); diff --git a/src/sfml/sfml_tests.zig b/src/sfml/sfml_tests.zig new file mode 100644 index 0000000..5977a07 --- /dev/null +++ b/src/sfml/sfml_tests.zig @@ -0,0 +1,11 @@ +//! Test suite. Most tests are fairly basic, as they're not testing the SFML itself + +const std = @import("std"); + +test "all sfml tests" { + const sf = @import("sfml.zig"); + std.testing.refAllDecls(sf.system); + std.testing.refAllDecls(sf.window); + std.testing.refAllDecls(sf.graphics); + std.testing.refAllDecls(sf.audio); +} diff --git a/src/sfml/system/Clock.zig b/src/sfml/system/Clock.zig new file mode 100644 index 0000000..17b6e5b --- /dev/null +++ b/src/sfml/system/Clock.zig @@ -0,0 +1,59 @@ +//! Utility class that measures the elapsed time. + +const sf = struct { + pub usingnamespace @import("../sfml.zig"); + pub usingnamespace system; + pub usingnamespace graphics; +}; + +const Clock = @This(); + +// Constructor/destructor + +/// Inits a clock. The clock will have its time set at 0 at this point, and automatically starts +/// Std.time timer also is a good alternative +pub fn create() !Clock { + var clock = sf.c.sfClock_create(); + if (clock == null) + return sf.Error.nullptrUnknownReason; + + return Clock{ .ptr = clock.? }; +} + +/// Destroys this clock +pub fn destroy(self: Clock) void { + sf.c.sfClock_destroy(self.ptr); +} + +// Clock control +/// Gets the elapsed seconds +pub fn getElapsedTime(self: Clock) sf.Time { + var time = sf.c.sfClock_getElapsedTime(self.ptr).microseconds; + return sf.Time{ .us = time }; +} + +/// Gets the elapsed seconds and restarts the timer +pub fn restart(self: Clock) sf.Time { + var time = sf.c.sfClock_restart(self.ptr).microseconds; + return sf.Time{ .us = time }; +} + +/// Pointer to the csfml structure +ptr: *sf.c.sfClock, + +test "clock: sleep test" { + const tst = @import("std").testing; + + // This tests just sleeps and check what the timer measured (not very accurate but eh) + var clk = try Clock.create(); + defer clk.destroy(); + + sf.Time.milliseconds(500).sleep(); + + try tst.expectApproxEqAbs(@as(f32, 0.5), clk.getElapsedTime().asSeconds(), 0.1); + + sf.Time.sleep(sf.Time.seconds(0.2)); + + try tst.expectApproxEqAbs(@as(f32, 0.7), clk.restart().asSeconds(), 0.1); + try tst.expectApproxEqAbs(@as(f32, 0), clk.getElapsedTime().asSeconds(), 0.01); +} diff --git a/src/sfml/system/Time.zig b/src/sfml/system/Time.zig new file mode 100644 index 0000000..2e8a34c --- /dev/null +++ b/src/sfml/system/Time.zig @@ -0,0 +1,114 @@ +//! Represents a time value. + +const sf = @import("../sfml.zig"); + +const Time = @This(); + +// Constructors + +/// Converts a time from a csfml object +/// For inner workings +pub fn fromCSFML(time: sf.c.sfTime) Time { + return Time{ .us = time.microseconds }; +} + +/// Converts a time to a csfml object +/// For inner workings +pub fn toCSFML(self: Time) sf.c.sfTime { + return sf.c.sfTime{ .microseconds = self.us }; +} + +/// Creates a time object from a seconds count +pub fn seconds(s: f32) Time { + return Time{ .us = @floatToInt(i64, s * 1_000) * 1_000 }; +} + +/// Creates a time object from milliseconds +pub fn milliseconds(ms: i32) Time { + return Time{ .us = @intCast(i64, ms) * 1_000 }; +} + +/// Creates a time object from microseconds +pub fn microseconds(us: i64) Time { + return Time{ .us = us }; +} + +// Getters + +/// Gets this time measurement as microseconds +pub fn asMicroseconds(self: Time) i64 { + return self.us; +} + +/// Gets this time measurement as milliseconds +pub fn asMilliseconds(self: Time) i32 { + return @truncate(i32, @divFloor(self.us, 1_000)); +} + +/// Gets this time measurement as seconds (as a float) +pub fn asSeconds(self: Time) f32 { + return @intToFloat(f32, self.us) / 1_000_000; +} + +// Misc + +/// Sleeps the amount of time specified +pub fn sleep(time: Time) void { + sf.c.sfSleep(time.toCSFML()); +} + +/// A time of zero +pub const Zero = microseconds(0); + +us: i64, + +pub const TimeSpan = struct { + // Constructors + + /// Construcs a time span + pub fn init(begin: Time, length: Time) TimeSpan { + return TimeSpan{ + .offset = begin, + .length = length, + }; + } + + /// Converts a timespan from a csfml object + /// For inner workings + pub fn fromCSFML(span: sf.c.sfTimeSpan) TimeSpan { + return TimeSpan{ + .offset = Time.fromCSFML(span.offset), + .length = Time.fromCSFML(span.length), + }; + } + + /// Converts a timespan to a csfml object + /// For inner workings + pub fn toCSFML(self: TimeSpan) sf.c.sfTimeSpan { + return sf.c.sfTimeSpan{ + .offset = self.offset.toCSFML(), + .length = self.length.toCSFML(), + }; + } + + /// The beginning of this span + offset: Time, + /// The length of this time span + length: Time, +}; + +test "time: conversion" { + const tst = @import("std").testing; + + var t = Time.microseconds(5_120_000); + + try tst.expectEqual(@as(i32, 5_120), t.asMilliseconds()); + try tst.expectApproxEqAbs(@as(f32, 5.12), t.asSeconds(), 0.0001); + + t = Time.seconds(12); + + try tst.expectApproxEqAbs(@as(f32, 12), t.asSeconds(), 0.0001); + + t = Time.microseconds(800); + try tst.expectApproxEqAbs(@as(f32, 0.0008), t.asSeconds(), 0.0001); +} diff --git a/src/sfml/system/vector.zig b/src/sfml/system/vector.zig new file mode 100644 index 0000000..7e3e500 --- /dev/null +++ b/src/sfml/system/vector.zig @@ -0,0 +1,104 @@ +//! Utility struct for manipulating 2-dimensional vectors. + +const sf = @import("../sfml_import.zig"); + +pub fn Vector2(comptime T: type) type { + return packed struct { + const Self = @This(); + + /// The CSFML vector type equivalent + const CsfmlEquivalent = switch (T) { + c_uint => sf.c.sfVector2u, + c_int => sf.c.sfVector2i, + f32 => sf.c.sfVector2f, + else => void, + }; + + /// Makes a CSFML vector with this vector (only if the corresponding type exists) + /// This is mainly for the inner workings of this wrapper + pub fn toCSFML(self: Self) CsfmlEquivalent { + if (CsfmlEquivalent == void) @compileError("This vector type doesn't have a CSFML equivalent."); + return @bitCast(CsfmlEquivalent, self); + } + + /// Creates a vector from a CSFML one (only if the corresponding type exists) + /// This is mainly for the inner workings of this wrapper + pub fn fromCSFML(vec: CsfmlEquivalent) Self { + if (CsfmlEquivalent == void) @compileError("This vector type doesn't have a CSFML equivalent."); + return @bitCast(Self, vec); + } + + /// Adds two vectors + pub fn add(self: Self, other: Self) Self { + return Self{ .x = self.x + other.x, .y = self.y + other.y }; + } + + /// Substracts two vectors + pub fn substract(self: Self, other: Self) Self { + return Self{ .x = self.x - other.x, .y = self.y - other.y }; + } + + /// Scales a vector + pub fn scale(self: Self, scalar: T) Self { + return Self{ .x = self.x * scalar, .y = self.y * scalar }; + } + + /// x component of the vector + x: T, + /// y component of the vector + y: T + }; +} + +pub const Vector3f = struct { + const Self = @This(); + + /// Makes a CSFML vector with this vector (only if the corresponding type exists) + /// This is mainly for the inner workings of this wrapper + pub fn toCSFML(self: Self) sf.c.sfVector3f { + return @bitCast(sf.c.sfVector3f, self); + } + + /// Creates a vector from a CSFML one (only if the corresponding type exists) + /// This is mainly for the inner workings of this wrapper + pub fn fromCSFML(vec: sf.c.sfVector3f) Self { + return @bitCast(Self, vec); + } + + /// x component of the vector + x: f32, + /// y component of the vector + y: f32, + /// z component of the vector + z: f32, +}; + +test "vector: sane from/to CSFML vectors" { + const tst = @import("std").testing; + + inline for ([_]type{ c_int, c_uint, f32 }) |T| { + const VecT = Vector2(T); + const vec = VecT{ .x = 1, .y = 3 }; + const cvec = vec.toCSFML(); + + try tst.expectEqual(vec.x, cvec.x); + try tst.expectEqual(vec.y, cvec.y); + + const vec2 = VecT.fromCSFML(cvec); + + try tst.expectEqual(vec, vec2); + } + + { + const vec = Vector3f{ .x = 1, .y = 3.5, .z = -12 }; + const cvec = vec.toCSFML(); + + try tst.expectEqual(vec.x, cvec.x); + try tst.expectEqual(vec.y, cvec.y); + try tst.expectEqual(vec.z, cvec.z); + + const vec2 = Vector3f.fromCSFML(cvec); + + try tst.expectEqual(vec, vec2); + } +} diff --git a/src/sfml/window/Style.zig b/src/sfml/window/Style.zig new file mode 100644 index 0000000..e9b401d --- /dev/null +++ b/src/sfml/window/Style.zig @@ -0,0 +1,5 @@ +pub const none: u32 = 0; +pub const titlebar: u32 = 1; +pub const resize: u32 = 2; +pub const close: u32 = 4; +pub const defaultStyle = titlebar | resize | close; diff --git a/src/sfml/window/event.zig b/src/sfml/window/event.zig new file mode 100644 index 0000000..d875a1c --- /dev/null +++ b/src/sfml/window/event.zig @@ -0,0 +1,162 @@ +//! Defines a system event and its parameters. + +const sf = struct { + pub usingnamespace @import("../sfml.zig"); + pub usingnamespace system; +}; + +pub const Event = union(Event.Type) { + const Self = @This(); + + pub const Type = enum(c_int) { + closed, + resized, + lostFocus, + gainedFocus, + textEntered, + keyPressed, + keyReleased, + mouseWheelScrolled, + mouseButtonPressed, + mouseButtonReleased, + mouseMoved, + mouseEntered, + mouseLeft, + joystickButtonPressed, + joystickButtonReleased, + joystickMoved, + joystickConnected, + joystickDisconnected, + touchBegan, + touchMoved, + touchEnded, + sensorChanged, + }; + + // Big oof + /// Creates this event from a csfml one + pub fn fromCSFML(event: sf.c.sfEvent) Self { + return switch (event.type) { + sf.c.sfEvtClosed => .{ .closed = {} }, + sf.c.sfEvtResized => .{ .resized = .{ .size = .{ .x = event.size.width, .y = event.size.height } } }, + sf.c.sfEvtLostFocus => .{ .lostFocus = {} }, + sf.c.sfEvtGainedFocus => .{ .gainedFocus = {} }, + sf.c.sfEvtTextEntered => .{ .textEntered = .{ .unicode = event.text.unicode } }, + sf.c.sfEvtKeyPressed => .{ .keyPressed = .{ .code = @intToEnum(sf.window.keyboard.KeyCode, event.key.code), .alt = (event.key.alt != 0), .control = (event.key.control != 0), .shift = (event.key.shift != 0), .system = (event.key.system != 0) } }, + sf.c.sfEvtKeyReleased => .{ .keyReleased = .{ .code = @intToEnum(sf.window.keyboard.KeyCode, event.key.code), .alt = (event.key.alt != 0), .control = (event.key.control != 0), .shift = (event.key.shift != 0), .system = (event.key.system != 0) } }, + sf.c.sfEvtMouseWheelScrolled => .{ .mouseWheelScrolled = .{ .wheel = @intToEnum(sf.window.mouse.Wheel, event.mouseWheelScroll.wheel), .delta = event.mouseWheelScroll.delta, .pos = .{ .x = event.mouseWheelScroll.x, .y = event.mouseWheelScroll.y } } }, + sf.c.sfEvtMouseButtonPressed => .{ .mouseButtonPressed = .{ .button = @intToEnum(sf.window.mouse.Button, event.mouseButton.button), .pos = .{ .x = event.mouseButton.x, .y = event.mouseButton.y } } }, + sf.c.sfEvtMouseButtonReleased => .{ .mouseButtonReleased = .{ .button = @intToEnum(sf.window.mouse.Button, event.mouseButton.button), .pos = .{ .x = event.mouseButton.x, .y = event.mouseButton.y } } }, + sf.c.sfEvtMouseMoved => .{ .mouseMoved = .{ .pos = .{ .x = event.mouseMove.x, .y = event.mouseMove.y } } }, + sf.c.sfEvtMouseEntered => .{ .mouseEntered = {} }, + sf.c.sfEvtMouseLeft => .{ .mouseLeft = {} }, + sf.c.sfEvtJoystickButtonPressed => .{ .joystickButtonPressed = .{ .joystickId = event.joystickButton.joystickId, .button = event.joystickButton.button } }, + sf.c.sfEvtJoystickButtonReleased => .{ .joystickButtonReleased = .{ .joystickId = event.joystickButton.joystickId, .button = event.joystickButton.button } }, + sf.c.sfEvtJoystickMoved => .{ .joystickMoved = .{ .joystickId = event.joystickMove.joystickId, .axis = event.joystickMove.axis, .position = event.joystickMove.position } }, + sf.c.sfEvtJoystickConnected => .{ .joystickConnected = .{ .joystickId = event.joystickConnect.joystickId } }, + sf.c.sfEvtJoystickDisconnected => .{ .joystickDisconnected = .{ .joystickId = event.joystickConnect.joystickId } }, + sf.c.sfEvtTouchBegan => .{ .touchBegan = .{ .finger = event.touch.finger, .pos = .{ .x = event.touch.x, .y = event.touch.y } } }, + sf.c.sfEvtTouchMoved => .{ .touchMoved = .{ .finger = event.touch.finger, .pos = .{ .x = event.touch.x, .y = event.touch.y } } }, + sf.c.sfEvtTouchEnded => .{ .touchEnded = .{ .finger = event.touch.finger, .pos = .{ .x = event.touch.x, .y = event.touch.y } } }, + sf.c.sfEvtSensorChanged => .{ .sensorChanged = .{ .sensorType = event.sensor.sensorType, .vector = .{ .x = event.sensor.x, .y = event.sensor.y, .z = event.sensor.z } } }, + sf.c.sfEvtCount => @panic("sfEvtCount should't exist as an event!"), + else => @panic("Unknown event!"), + }; + } + + /// Gets how many types of event exist + pub fn getEventCount() c_uint { + return @enumToInt(sf.c.sfEventType.sfEvtCount); + } + + /// Size events parameters + pub const SizeEvent = struct { + size: sf.Vector2u, + }; + + /// Keyboard event parameters + pub const KeyEvent = struct { + code: sf.window.keyboard.KeyCode, + alt: bool, + control: bool, + shift: bool, + system: bool, + }; + + /// Text event parameters + pub const TextEvent = struct { + unicode: u32, + }; + + /// Mouse move event parameters + pub const MouseMoveEvent = struct { + pos: sf.Vector2i, + }; + + /// Mouse buttons events parameters + pub const MouseButtonEvent = struct { + button: sf.window.mouse.Button, + pos: sf.Vector2i, + }; + + /// Mouse wheel events parameters + pub const MouseWheelScrollEvent = struct { + wheel: sf.window.mouse.Wheel, + delta: f32, + pos: sf.Vector2i, + }; + + /// Joystick axis move event parameters + pub const JoystickMoveEvent = struct { + joystickId: c_uint, + axis: sf.c.sfJoystickAxis, + position: f32, + }; + + /// Joystick buttons events parameters + pub const JoystickButtonEvent = struct { + joystickId: c_uint, + button: c_uint, + }; + + /// Joystick connection/disconnection event parameters + pub const JoystickConnectEvent = struct { + joystickId: c_uint, + }; + + /// Touch events parameters + pub const TouchEvent = struct { + finger: c_uint, + pos: sf.Vector2i, + }; + + /// Sensor event parameters + pub const SensorEvent = struct { + sensorType: sf.c.sfSensorType, + vector: sf.Vector3f, + }; + + // An event is one of those + closed: void, + resized: SizeEvent, + lostFocus: void, + gainedFocus: void, + textEntered: TextEvent, + keyPressed: KeyEvent, + keyReleased: KeyEvent, + mouseWheelScrolled: MouseWheelScrollEvent, + mouseButtonPressed: MouseButtonEvent, + mouseButtonReleased: MouseButtonEvent, + mouseMoved: MouseMoveEvent, + mouseEntered: void, + mouseLeft: void, + joystickButtonPressed: JoystickButtonEvent, + joystickButtonReleased: JoystickButtonEvent, + joystickMoved: JoystickMoveEvent, + joystickConnected: JoystickConnectEvent, + joystickDisconnected: JoystickConnectEvent, + touchBegan: TouchEvent, + touchMoved: TouchEvent, + touchEnded: TouchEvent, + sensorChanged: SensorEvent, +}; diff --git a/src/sfml/window/keyboard.zig b/src/sfml/window/keyboard.zig new file mode 100644 index 0000000..8e4e970 --- /dev/null +++ b/src/sfml/window/keyboard.zig @@ -0,0 +1,11 @@ +//! Give access to the real-time state of the keyboard. + +const sf = @import("../sfml_import.zig"); + +/// Keycodes +pub const KeyCode = enum(c_int) { Unknown = -1, A = 0, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, Num0, Num1, Num2, Num3, Num4, Num5, Num6, Num7, Num8, Num9, Escape, LControl, LShift, LAlt, LSystem, RControl, RShift, RAlt, RSystem, Menu, LBracket, RBracket, Semicolon, Comma, Period, Quote, Slash, Backslash, Tilde, Equal, Hyphen, Space, Enter, Backspace, Tab, PageUp, PageDown, End, Home, Insert, Delete, Add, Subtract, Multiply, Divide, Left, Right, Up, Down, Numpad0, Numpad1, Numpad2, Numpad3, Numpad4, Numpad5, Numpad6, Numpad7, Numpad8, Numpad9, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, Pause, KeyCount }; + +/// Returns true if the specified key is pressed +pub fn isKeyPressed(key: KeyCode) bool { + return sf.c.sfKeyboard_isKeyPressed(@enumToInt(key)) == 1; +} diff --git a/src/sfml/window/mouse.zig b/src/sfml/window/mouse.zig new file mode 100644 index 0000000..c788324 --- /dev/null +++ b/src/sfml/window/mouse.zig @@ -0,0 +1,26 @@ +//! Give access to the real-time state of the mouse. + +const sf = @import("../sfml.zig"); + +/// Mouse buttons +pub const Button = enum(c_uint) { Left, Right, Middle, XButton1, XButton2 }; +/// Mouse wheels +pub const Wheel = enum(c_uint) { Vertical, Horizontal }; + +/// Returns true if the specified mouse button is pressed +pub fn isButtonPressed(button: Button) bool { + return sf.c.sfMouse_isButtonPressed(@intToEnum(sf.c.sfMouseButton, @enumToInt(button))) == 1; +} + +/// Gets the position of the mouse cursor relative to the window passed or desktop +pub fn getPosition(window: ?sf.graphics.RenderWindow) sf.system.Vector2i { + if (window) |w| { + return sf.system.Vector2i.fromCSFML(sf.c.sfMouse_getPosition(@ptrCast(*sf.c.sfWindow, w.ptr))); + } else return sf.system.Vector2i.fromCSFML(sf.c.sfMouse_getPosition(null)); +} +/// Set the position of the mouse cursor relative to the window passed or desktop +pub fn setPosition(position: sf.system.Vector2i, window: ?sf.graphics.RenderWindow) void { + if (window) |w| { + sf.c.sfMouse_setPosition(position.toCSFML(), @ptrCast(*sf.c.sfWindow, w.ptr)); + } else sf.c.sfMouse_setPosition(position.toCSFML(), null); +} diff --git a/walls.png b/walls.png Binary files differnew file mode 100644 index 0000000..b08ad42 --- /dev/null +++ b/walls.png |
