# HG changeset patch # User John Tsiombikas # Date 1446329352 -7200 # Node ID 50683c78264e217a5d30fa9f7f7aa1225b9cc651 initial commit diff -r 000000000000 -r 50683c78264e .hgignore --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/.hgignore Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,8 @@ +\.swp$ +\.o$ +\.d$ +\.jpg$ +\.png$ +^data/ +^bin/ +^lib/ diff -r 000000000000 -r 50683c78264e LICENSE --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/LICENSE Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + 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. + + + Copyright (C) + + 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 . + +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: + + Copyright (C) + 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 +. + + 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 +. diff -r 000000000000 -r 50683c78264e Makefile --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Makefile Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,31 @@ +src = $(wildcard src/*.cc) $(wildcard src/audio/*.cc) +csrc = $(wildcard src/*.c) $(wildcard src/dsys/*.c) +obj = $(src:.cc=.o) $(csrc:.c=.o) +dep = $(obj:.o=.d) +bin = halloween + +opt = -O2 + +CFLAGS = -pedantic -Wall -g $(opt) -Isrc +CXXFLAGS = -pedantic -Wall -g $(opt) -Isrc +LDFLAGS = -lGL -lGLU -lglut -lGLEW -lvmath -limago -lm -ldl -lpthread \ + -lvorbisfile -logg -lpthread -lopenal + +$(bin): $(obj) + $(CXX) -o $@ $(obj) $(LDFLAGS) + +-include $(dep) + +%.d: %.c + @$(CPP) $(CFLAGS) $< -MM -MT $(@:.d=.o) >$@ + +%.d: %.cc + @$(CPP) $(CXXFLAGS) $< -MM -MT $(@:.d=.o) >$@ + +.PHONY: clean +clean: + rm -f $(obj) $(bin) + +.PHONY: cleandep +cleandep: + rm -f $(dep) diff -r 000000000000 -r 50683c78264e README --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/README Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,4 @@ +"party-version", 64bit GNU/Linux-only release. +Expect final v1.1 with binaries for other platforms, and more details, soon. + +Contact: nuclear@member.fsf.org diff -r 000000000000 -r 50683c78264e RUN --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/RUN Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,3 @@ +#!/bin/sh + +LD_LIBRARY_PATH=lib ./bin/halloween $* diff -r 000000000000 -r 50683c78264e sdr/default.v.glsl --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/sdr/default.v.glsl Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,16 @@ +uniform mat4 world_matrix; + +varying vec3 lpos, wpos, vpos, norm, ldir; + +void main() +{ + lpos = gl_Vertex.xyz; + gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; + + vpos = (gl_ModelViewMatrix * gl_Vertex).xyz; + wpos = (world_matrix * gl_Vertex).xyz; + norm = gl_NormalMatrix * gl_Normal; + gl_TexCoord[0] = gl_TextureMatrix[0] * gl_MultiTexCoord0; + + ldir = gl_LightSource[0].position.xyz - vpos; +} diff -r 000000000000 -r 50683c78264e sdr/spot.p.glsl --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/sdr/spot.p.glsl Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,30 @@ +uniform sampler2D tex; + +varying vec3 lpos, wpos, vpos, norm, ldir; + +#define KD gl_FrontMaterial.diffuse.rgb +#define KS gl_FrontMaterial.specular.rgb +#define LTCOL gl_LightSource[0].diffuse.rgb + +void main() +{ + vec4 texel = texture2D(tex, gl_TexCoord[0].st); + + float dist = length(wpos.xz); + float spot = 1.0 - smoothstep(4.0, 10.0, dist); + + vec3 n = normalize(norm); + vec3 v = -normalize(vpos); + vec3 l = normalize(ldir); + vec3 h = normalize(v + l); + + float ndotl = max(dot(n, l), 0.0); + float ndoth = max(dot(n, h), 0.0); + + vec3 ambient = gl_LightModel.ambient.rgb * texel.rgb; + vec3 diffuse = KD * LTCOL * ndotl * texel.rgb; + vec3 specular = KS * LTCOL * pow(ndoth, gl_FrontMaterial.shininess); + + gl_FragColor.rgb = (ambient + diffuse + specular) * spot; + gl_FragColor.a = gl_FrontMaterial.diffuse.a * texel.a; +} diff -r 000000000000 -r 50683c78264e src/audio/audio.cc --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/audio/audio.cc Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,70 @@ +#include + +#include "openal.h" +#include "audio.h" + +static ALCdevice *dev; +static ALCcontext *ctx; + +bool init_audio() +{ + if (dev) { + // Already initiated. + return true; + } + else if (!(dev = alcOpenDevice(0))) { + fprintf(stderr, "failed to open OpenAL device\n"); + return false; + } + + if (ctx) + { + return true; + } + else if (!(ctx = alcCreateContext(dev, 0))) + { + fprintf(stderr, "failed to create context\n"); + alcCloseDevice(dev); + return false; + } + + alcMakeContextCurrent(ctx); + + // Clear error state. + alGetError(); + + return true; +} + +void destroy_audio() +{ + alcMakeContextCurrent(0); + + if (ctx) { + alcDestroyContext(ctx); + } + + if (dev) { + alcCloseDevice(dev); + } +} + +void set_audio_listener(const Matrix4x4 &xform) +{ + float pos[3], orient[6]; + + pos[0] = xform[0][3]; + pos[1] = xform[1][3]; + pos[2] = xform[2][3]; + + orient[0] = xform[0][2]; + orient[1] = xform[1][2]; + orient[2] = -xform[2][2]; + + orient[3] = xform[0][1]; + orient[4] = xform[1][1]; + orient[5] = xform[2][1]; + + alListenerfv(AL_POSITION, pos); + alListenerfv(AL_ORIENTATION, orient); +} diff -r 000000000000 -r 50683c78264e src/audio/audio.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/audio/audio.h Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,11 @@ +#ifndef AUDIO_H_ +#define AUDIO_H_ + +#include "vmath/vmath.h" + +bool init_audio(); +void destroy_audio(); + +void set_audio_listener(const Matrix4x4 &xform); + +#endif // AUDIO_H_ diff -r 000000000000 -r 50683c78264e src/audio/openal.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/audio/openal.h Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,12 @@ +#ifndef OPENAL_H_ +#define OPENAL_H_ + +#ifndef __APPLE__ +#include +#include +#else +#include +#include +#endif + +#endif /* OPENAL_H_ */ diff -r 000000000000 -r 50683c78264e src/audio/ovstream.cc --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/audio/ovstream.cc Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,95 @@ +#include +#include +#include "ovstream.h" + +OggVorbisStream::OggVorbisStream() +{ + vfopen = false; + + pthread_mutex_init(&vflock, 0); +} + +OggVorbisStream::~OggVorbisStream() +{ + close(); +} + +bool OggVorbisStream::open(const char *fname) +{ + close(); + + pthread_mutex_lock(&vflock); + + if(ov_fopen(fname, &vf) != 0) { + fprintf(stderr, "failed to open ogg/vorbis stream: %s\n", fname ? fname : ""); + pthread_mutex_unlock(&vflock); + return false; + } + + vfopen = true; + pthread_mutex_unlock(&vflock); + return true; +} + +void OggVorbisStream::close() +{ + pthread_mutex_lock(&vflock); + if(vfopen) { + ov_clear(&vf); + vfopen = false; + } + pthread_mutex_unlock(&vflock); +} + +void OggVorbisStream::play(AUDIO_PLAYMODE mode) +{ + if (vfopen) + { + AudioStream::play(mode); + } else { + fprintf(stderr, "failed to play audio track.\n"); + } +} + +void OggVorbisStream::rewind() +{ + pthread_mutex_lock(&vflock); + if(vfopen) { + ov_raw_seek(&vf, 0); + } + pthread_mutex_unlock(&vflock); +} + +bool OggVorbisStream::more_samples(AudioStreamBuffer *buf) +{ + pthread_mutex_lock(&vflock); + + vorbis_info *vinfo = ov_info(&vf, -1); + buf->channels = vinfo->channels; + buf->sample_rate = vinfo->rate; + assert(buf->channels == 2); + assert(buf->sample_rate == 44100); + + long bufsz = AUDIO_BUFFER_BYTES; + long total_read = 0; + while(total_read < bufsz) { + int bitstream; + long rd = ov_read(&vf, buf->samples + total_read, bufsz - total_read, 0, 2, 1, &bitstream); + + if(!rd) { + bufsz = total_read; + } else { + total_read += rd; + } + } + + if(!total_read) { + buf->num_samples = 0; + pthread_mutex_unlock(&vflock); + return false; + } + + buf->num_samples = bufsz / vinfo->channels / 2; + pthread_mutex_unlock(&vflock); + return true; +} diff -r 000000000000 -r 50683c78264e src/audio/ovstream.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/audio/ovstream.h Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,27 @@ +#ifndef OVSTREAM_H_ +#define OVSTREAM_H_ + +#include +#include +#include "stream.h" + +class OggVorbisStream : public AudioStream { +private: + OggVorbis_File vf; + bool vfopen; + pthread_mutex_t vflock; + + virtual bool more_samples(AudioStreamBuffer *buf); + +public: + OggVorbisStream(); + virtual ~OggVorbisStream(); + + bool open(const char *fname); + void close(); + + virtual void play(AUDIO_PLAYMODE mode); + virtual void rewind(); +}; + +#endif // OVSTREAM_H_ diff -r 000000000000 -r 50683c78264e src/audio/stream.cc --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/audio/stream.cc Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,264 @@ +#include +#include +#include +#include "openal.h" +#include "stream.h" +#include "timer.h" + +static ALenum alformat(AudioStreamBuffer *buf) +{ + return buf->channels == 1 ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16; +} + +AudioStream::AudioStream() +{ + alsrc = 0; + poll_interval = 25; + done = true; + loop = false; + volume = 1.0; + pitch = 1.0; + + pthread_mutex_init(&mutex, 0); +} + +AudioStream::~AudioStream() +{ + stop(); +} + +bool AudioStream::open(const char *fname) +{ + return false; +} + +void AudioStream::close() +{ +} + +void AudioStream::set_volume(float vol) +{ + if(vol < 0.0) vol = 0.0; + if(vol > 1.0) vol = 1.0; + + volume = vol; + + pthread_mutex_lock(&mutex); + if(alsrc) { + alSourcef(alsrc, AL_GAIN, vol); + } + pthread_mutex_unlock(&mutex); +} + +float AudioStream::get_volume() const +{ + return volume; +} +void AudioStream::set_pitch(float pitch) +{ + if(pitch < 0.0) pitch = 0.0; + if(pitch > 1.0) pitch = 1.0; + + this->pitch = pitch; + + pthread_mutex_lock(&mutex); + if(alsrc) { + alSourcef(alsrc, AL_PITCH, pitch); + } + pthread_mutex_unlock(&mutex); +} + +float AudioStream::get_pitch() const +{ + return pitch; +} + + +static void *thread_func(void *arg) +{ + AudioStream *astr = (AudioStream*)arg; + astr->poll_loop(); + return 0; +} + +void AudioStream::play(AUDIO_PLAYMODE mode) +{ + loop = (mode == AUDIO_PLAYMODE_LOOP); + done = false; + + if(pthread_create(&play_thread, 0, thread_func, this) != 0) { + fprintf(stderr, "failed to create music playback thread\n"); + } +} + +void AudioStream::stop() +{ + pthread_mutex_lock(&mutex); + + if(alsrc) { + done = true; + //alSourceStop(alsrc); + printf("waiting for the music thread to stop\n"); + pthread_mutex_unlock(&mutex); + pthread_join(play_thread, 0); + } else { + pthread_mutex_unlock(&mutex); + } +} + +// gets an array of buffers and returns the index of the one matching id +static inline int find_buffer(unsigned int id, unsigned int *barr, int num) +{ + for(int i=0; inum_samples * buf->channels * 2; // 2 is for 16bit samples + alBufferData(albuf[i], alformat(buf), buf->samples, bufsz, buf->sample_rate); + + if(alGetError()) { + fprintf(stderr, "failed to load sample data into OpenAL buffer\n"); + } + + alSourceQueueBuffers(alsrc, 1, albuf + i); + BUFQ_QUEUE(i); + + if(alGetError()) { + fprintf(stderr, "failed to start streaming audio buffers\n"); + } + } else { + break; + } + } + + // start playback + alSourcePlay(alsrc); + while(!done) { + /* find out how many (if any) of the queued buffers are + * done, and free to be reused. + */ + int num_buf_done; + alGetSourcei(alsrc, AL_BUFFERS_PROCESSED, &num_buf_done); + for(int i=0; inum_samples * buf->channels * 2; // 2 is for 16bit samples + alBufferData(buf_id, alformat(buf), buf->samples, bufsz, buf->sample_rate); + if((err = alGetError())) { + fprintf(stderr, "failed to load sample data into OpenAL buffer (error: %x)\n", err); + } + + alSourceQueueBuffers(alsrc, 1, &buf_id); + if(alGetError()) { + fprintf(stderr, "failed to start streaming audio buffers\n"); + } + BUFQ_QUEUE(bidx); + } else { + // no more data... + if(loop) { + printf("audio stream looping...\n"); + rewind(); + } else { + done = true; + } + } + } + + if(num_buf_done) { + // make sure playback didn't stop + int state; + alGetSourcei(alsrc, AL_SOURCE_STATE, &state); + if(state != AL_PLAYING) { + alSourcePlay(alsrc); + } + } + + pthread_mutex_unlock(&mutex); + long msec = get_time_msec(); + long dt = msec - prev_msec; + prev_msec = msec; + + if(dt < (long)poll_interval) { + sleep_msec(poll_interval - dt); + } else { + sched_yield(); + } + pthread_mutex_lock(&mutex); + } + + + // done with the data, wait for the source to stop playing before cleanup + int state; + while(alGetSourcei(alsrc, AL_SOURCE_STATE, &state), state == AL_PLAYING) { + sched_yield(); + } + + alDeleteBuffers(AUDIO_NUM_BUFFERS, albuf); + alDeleteSources(1, &alsrc); + alsrc = 0; + pthread_mutex_unlock(&mutex); + + delete buf; +} diff -r 000000000000 -r 50683c78264e src/audio/stream.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/audio/stream.h Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,65 @@ +#ifndef STREAM_H_ +#define STREAM_H_ + +#include + +#define AUDIO_FFT_BINS 16 +#define AUDIO_FFT_DOWNSAMPLE 1 + +#define AUDIO_NUM_BUFFERS 8 +#define AUDIO_BUFFER_MSEC 32 +// TODO should the sampling rate be hardcoded? +#define AUDIO_BUFFER_SAMPLES (AUDIO_BUFFER_MSEC * 44100 / 1000) +// TODO unhardcode the channels number +#define AUDIO_BUFFER_BYTES (AUDIO_BUFFER_SAMPLES * 2 * 2) + +#define AUDIO_FFT_SAMPLES (AUDIO_BUFFER_SAMPLES / AUDIO_FFT_DOWNSAMPLE) + +enum AUDIO_PLAYMODE +{ + AUDIO_PLAYMODE_ONCE, + AUDIO_PLAYMODE_LOOP +}; + +struct AudioStreamBuffer { + char samples[AUDIO_BUFFER_BYTES]; + + int num_samples; + int channels; + int sample_rate; +}; + +class AudioStream { +private: + pthread_t play_thread; + pthread_mutex_t mutex; + + float volume, pitch; + bool done, loop; + unsigned int poll_interval; + unsigned int alsrc; + + virtual bool more_samples(AudioStreamBuffer *buf) = 0; + +public: + void poll_loop(); + + AudioStream(); + virtual ~AudioStream(); + + virtual bool open(const char *fname); + virtual void close(); + + virtual void set_volume(float vol); + virtual float get_volume() const; + + virtual void set_pitch(float p); + virtual float get_pitch() const; + + virtual void play(AUDIO_PLAYMODE mode); + virtual void stop(); + + virtual void rewind() = 0; +}; + +#endif // AUDIO_STREAM_H_ diff -r 000000000000 -r 50683c78264e src/dsys/dsys.c --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/dsys/dsys.c Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,515 @@ +#include +#include +#include +#include +#include +#include +#include "dsys.h" +#include "dsys_impl.h" + +static int read_script(struct dsys_demo *demo, FILE *fp, const char *fname); +static char *strip_ws(char *buf); +static void dbg_print_events(struct dsys_event *ev); + +static void proc_event(struct dsys_event *ev, demotime_t tm); +static void link_callback(struct dsys_event *ev, void *cls); +static void free_event(struct dsys_event *ev); + +static struct dsys_event *sort_evlist(struct dsys_event *list, int num_ev); +static struct dsys_event *merge_evlists(struct dsys_event *list1, struct dsys_event *list2); + + +struct dsys_demo *dsys_open(const char *fname) +{ + FILE *fp; + struct dsys_demo *demo; + + if(!(fp = fopen(fname, "r"))) { + fprintf(stderr, "failed to open demoscript: %s: %s\n", fname, strerror(errno)); + return 0; + } + + if(!(demo = malloc(sizeof *demo))) { + perror("failed to allocate memory"); + fclose(fp); + return 0; + } + memset(demo, 0, sizeof *demo); + + demo->src_tm = demo->start_tm = -1; + + if(read_script(demo, fp, fname) == -1) { + free(demo); + fclose(fp); + return 0; + } + + fclose(fp); + return demo; +} + +struct dsys_demo *dsys_open_stream(FILE *fp) +{ + struct dsys_demo *demo; + + if(!(demo = malloc(sizeof *demo))) { + perror("failed to allocate memory"); + return 0; + } + memset(demo, 0, sizeof *demo); + + demo->src_tm = demo->start_tm = -1; + + if(read_script(demo, fp, 0) == -1) { + free(demo); + return 0; + } + + return demo; +} + +void dsys_close(struct dsys_demo *demo) +{ + while(demo->evlist) { + struct dsys_event *ev = demo->evlist; + demo->evlist = demo->evlist->next; + free_event(ev); + } + + free(demo); +} + + +#define SEP " \t\n\r" + +static int read_script(struct dsys_demo *demo, FILE *fp, const char *fname) +{ + int nline = 0; + char buf[512], *line, *tok, *endp; + unsigned int t0, t1; + struct dsys_event *ev; + + if(!fname) { + fname = ""; + } + + demo->duration = dsys_msec_to_dtime(0); + + while(fgets(buf, sizeof buf, fp)) { + nline++; + + line = strip_ws(buf); + + if(!line || !*line) { + continue; + } + + if(!(tok = strtok(line, SEP)) || (t0 = strtol(tok, &endp, 10), endp == tok)) { + fprintf(stderr, "%s line: %d, error: expected timestamp t0\n", fname, nline); + return -1; + } + + if(!(tok = strtok(0, SEP))) { + fprintf(stderr, "%s line: %d, error: expected second timestamp or event name\n", fname, nline); + return -1; + } + + t1 = strtol(tok, &endp, 10); + if(endp == tok) { + t1 = t0; + } else { + if(!(tok = strtok(0, SEP))) { + fprintf(stderr, "%s line: %d, error: expected event name\n", fname, nline); + return -1; + } + } + + if(!(ev = malloc(sizeof *ev))) { + perror("read_script: failed to allocate memory for an event\n"); + return -1; + } + memset(ev, 0, sizeof *ev); + ev->t0 = dsys_msec_to_dtime(t0); + ev->t1 = dsys_msec_to_dtime(t1); + + if(!(ev->name = malloc(strlen(tok) + 1))) { + free(ev); + fprintf(stderr, "read_script: failed to allocate memory for the event name: %s\n", tok); + return -1; + } + strcpy(ev->name, tok); + + ev->eval = t0 == t1 ? dsys_eval_step : dsys_eval_lerp; + + ev->next = demo->evlist; + ev->prev = 0; + if(demo->evlist) { + demo->evlist->prev = ev; + } + demo->evlist = ev; + demo->num_ev++; + + if(ev->t1 > demo->duration) { + demo->duration = ev->t1; + } + } + + demo->evlist = sort_evlist(demo->evlist, demo->num_ev); + + /*dbg_print_events(demo->evlist);*/ + + return 0; +} + +static char *strip_ws(char *buf) +{ + char *ptr; + + while(isspace(*buf)) { + buf++; + } + + ptr = buf; + while(*ptr) { + if(*ptr == '\n' || *ptr == '\r' || *ptr == '#') { + *ptr = 0; + break; + } + ptr++; + } + + return buf; +} + +/*static void dbg_print_events(struct dsys_event *ev) +{ + int i; + + for(i=0; ev; i++) { + printf("%02d - %s (%f -> %f) [%s]\n", i, ev->eval == dsys_eval_step ? "step" : "lerp", + ev->t0, ev->t1, ev->name); + ev = ev->next; + } +}*/ + +void dsys_update(struct dsys_demo *demo, demotime_t tm) +{ + struct dsys_event *ev; + + demo->src_tm = tm; + + if(demo->start_tm == -1) { + dsys_start(demo); + } + + if(!demo->running) { + return; /* nothing changes */ + } + + demo->tm = tm - demo->start_tm - demo->stoppage_tm; + + if(demo->tm < 0) { + demo->tm = 0; + } + if(demo->tm > demo->duration) { + demo->tm = demo->duration; + } + + while(demo->active && demo->active->t1 <= demo->tm) { + proc_event(demo->active, demo->tm); + demo->active = demo->active->next; + } + + ev = demo->active; + while(ev && ev->t0 <= demo->tm) { + proc_event(ev, demo->tm); + ev = ev->next; + } + demo->nextev = ev; + + + if(demo->tm >= demo->duration) { + dsys_stop(demo); + } +} + +static void proc_event(struct dsys_event *ev, demotime_t tm) +{ + float val = ev->eval(ev, tm); + + if(ev->val != val) { + struct callback *cb = ev->cblist; + + ev->val = val; + + while(cb) { + cb->func(ev, cb->cls); + cb = cb->next; + } + } +} + +void dsys_start(struct dsys_demo *demo) +{ + if(demo->running) { + return; + } + + if(demo->start_tm == -1) { + demo->start_tm = demo->src_tm; + demo->nextev = demo->active = demo->evlist; + } else { + demo->stoppage_tm += demo->src_tm - demo->stop_tm; + } + + demo->running = 1; +} + +void dsys_stop(struct dsys_demo *demo) +{ + if(!demo->running) { + return; + } + + demo->stop_tm = demo->src_tm; + demo->running = 0; +} + +int dsys_is_running(struct dsys_demo *demo) +{ + return demo->running; +} + + +demotime_t dsys_duration(struct dsys_demo *demo) +{ + return demo->duration; +} + +demotime_t dsys_time(struct dsys_demo *demo) +{ + return demo->tm; +} + +float dsys_progress(struct dsys_demo *demo) +{ + return demo->tm / demo->duration; +} + +/* seek without continuity */ +void dsys_seek(struct dsys_demo *demo, demotime_t tm) +{ + struct dsys_event *ev; + + if(tm < 0) { + tm = 0; + } + if(tm > demo->duration) { + tm = demo->duration; + } + + if(tm < demo->tm) { + /* on backwards seek, invalidate the sliding window */ + demo->nextev = demo->active = demo->evlist; + } + + demo->start_tm = demo->src_tm - tm; + demo->stoppage_tm = 0; + demo->stop_tm = demo->src_tm; + demo->tm = tm; + + /* recalculate events */ + ev = demo->evlist; + while(ev) { + proc_event(ev, tm); + ev = ev->next; + } +} + +void dsys_seek_norm(struct dsys_demo *demo, float t) +{ + dsys_seek(demo, t * demo->duration); +} + +/* seek by accelerating time */ +void dsys_warp(struct dsys_demo *demo, demotime_t tm) +{ + fprintf(stderr, "dsys_warp not implemented yet\n"); +} + +void dsys_warp_norm(struct dsys_demo *demo, float t) +{ + dsys_warp(demo, t * demo->duration); +} + + +/* events */ +struct dsys_event *dsys_event(struct dsys_demo *demo, const char *name) +{ + struct dsys_event *iter = demo->evlist; + + while(iter) { + if(strcmp(iter->name, name) == 0) { + return iter; + } + iter = iter->next; + } + return 0; +} + +enum dsys_evtype dsys_event_type(struct dsys_event *ev) +{ + return ev->type; +} + +float dsys_event_value(struct dsys_event *ev) +{ + return ev->val; +} + +int dsys_event_callback(struct dsys_event *ev, void (*func)(struct dsys_event*, void*), void *cls) +{ + struct callback *cb; + + if(!(cb = malloc(sizeof *cb))) { + perror("failed to allocate memory"); + return -1; + } + cb->func = func; + cb->cls = cls; + cb->next = ev->cblist; + ev->cblist = cb; + return 0; +} + +int dsys_event_link(struct dsys_event *ev, float *link) +{ + return dsys_event_callback(ev, link_callback, link); +} + +static void link_callback(struct dsys_event *ev, void *cls) +{ + *(float*)cls = ev->val; +} + + +/* time conversion */ +demotime_t dsys_sec_to_dtime(float sec) +{ + return sec; +} + +demotime_t dsys_msec_to_dtime(unsigned long msec) +{ + return (demotime_t)msec / 1000.0; +} + +float dsys_dtime_to_sec(demotime_t tm) +{ + return tm; +} + +unsigned long dsys_dtime_to_msec(demotime_t tm) +{ + return (unsigned long)(tm * 1000.0); +} + + +float dsys_eval_step(struct dsys_event *ev, demotime_t t) +{ + return t >= ev->t1 ? 1.0 : 0.0; +} + +#define CLAMP(x, low, high) ((x) < (low) ? (low) : ((x) > (high) ? (high) : (x))) + +float dsys_eval_lerp(struct dsys_event *ev, demotime_t t) +{ + float res = (t - ev->t0) / (ev->t1 - ev->t0); + return CLAMP(res, 0.0, 1.0); +} + +float dsys_eval_sigmoid(struct dsys_event *ev, demotime_t t) +{ + t = dsys_eval_lerp(ev, t); + return 1.0 - (cos(t * M_PI) * 0.5 + 0.5); +} + +static void free_event(struct dsys_event *ev) +{ + while(ev->cblist) { + struct callback *cb = ev->cblist; + ev->cblist = ev->cblist->next; + free(cb); + } +} + +static struct dsys_event *sort_evlist(struct dsys_event *list, int num_ev) +{ + int i, num_left, num_right; + struct dsys_event *left, *right, *node = list; + + if(num_ev < 2) { + return list; + } + + num_left = num_ev / 2; + num_right = num_ev - num_left; + + for(i=0; inext; + } + + if(node->prev) { + node->prev->next = 0; + node->prev = 0; + } + + left = sort_evlist(list, num_left); + right = sort_evlist(node, num_right); + + return merge_evlists(left, right); +} + +static struct dsys_event *merge_evlists(struct dsys_event *list1, struct dsys_event *list2) +{ + struct dsys_event *head, *tail, *node; + + if(!list1) { + return list2; + } + if(!list2) { + return list1; + } + + head = tail = 0; + + while(list1 && list2) { + if(list1->t0 < list2->t0) { + node = list1; + list1 = list1->next; + } else { + node = list2; + list2 = list2->next; + } + + node->next = 0; + node->prev = tail; + + if(!head) { + head = node; + } else { + tail->next = node; + } + tail = node; + } + + if(list1) { + tail->next = list1; + list1->prev = tail; + } else if(list2) { + tail->next = list2; + list2->prev = tail; + } + + return head; +} diff -r 000000000000 -r 50683c78264e src/dsys/dsys.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/dsys/dsys.h Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,71 @@ +#ifndef DSYS2_H_ +#define DSYS2_H_ + +#include + +struct dsys_demo; +struct dsys_event; + +typedef float demotime_t; + +enum dsys_evtype { + DSYS_SINGLE, + DSYS_PERIODIC +}; + +#ifdef __cplusplus +extern "C" { +#endif + +struct dsys_demo *dsys_open(const char *fname); +struct dsys_demo *dsys_open_stream(FILE *fp); +void dsys_close(struct dsys_demo *demo); + +void dsys_update(struct dsys_demo *demo, demotime_t tm); + + +void dsys_start(struct dsys_demo *demo); +void dsys_stop(struct dsys_demo *demo); +int dsys_is_running(struct dsys_demo *demo); + + +demotime_t dsys_duration(struct dsys_demo *demo); +demotime_t dsys_time(struct dsys_demo *demo); +float dsys_progress(struct dsys_demo *demo); + +/* seek without continuity */ +void dsys_seek(struct dsys_demo *demo, demotime_t tm); +void dsys_seek_norm(struct dsys_demo *demo, float t); + +/* seek by accelerating time */ +void dsys_warp(struct dsys_demo *demo, demotime_t tm); +void dsys_warp_norm(struct dsys_demo *demo, float t); + + +/* events */ +struct dsys_event *dsys_event(struct dsys_demo *demo, const char *name); + +enum dsys_evtype dsys_event_type(struct dsys_event *ev); +float dsys_event_value(struct dsys_event *ev); + +int dsys_event_callback(struct dsys_event *ev, void (*func)(struct dsys_event*, void*), void *cls); +int dsys_event_link(struct dsys_event *ev, float *link); + +/* event evaluators */ +float dsys_eval_step(struct dsys_event *ev, demotime_t t); +float dsys_eval_lerp(struct dsys_event *ev, demotime_t t); +float dsys_eval_sigmoid(struct dsys_event *ev, demotime_t t); + +/* time conversion */ +demotime_t dsys_sec_to_dtime(float sec); +demotime_t dsys_msec_to_dtime(unsigned long msec); + +float dsys_dtime_to_sec(demotime_t tm); +unsigned long dsys_dtime_to_msec(demotime_t tm); + +#ifdef __cplusplus +} +#endif + + +#endif /* DSYS2_H_ */ diff -r 000000000000 -r 50683c78264e src/dsys/dsys_impl.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/dsys/dsys_impl.h Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,40 @@ +#ifndef DSYS_IMPL_H_ +#define DSYS_IMPL_H_ + +#include "dsys.h" + +struct dsys_demo { + demotime_t tm, src_tm, start_tm, stop_tm, duration; + demotime_t stoppage_tm; + + struct dsys_event *evlist; + int num_ev; + + struct dsys_event *nextev, *active; + + int running; +}; + +struct callback { + void (*func)(struct dsys_event*, void*); + void *cls; + + struct callback *next; +}; + + +struct dsys_event { + enum dsys_evtype type; + + char *name; + demotime_t t0, t1; + float val; + + float (*eval)(struct dsys_event*, demotime_t); + + struct callback *cblist; + + struct dsys_event *next, *prev; +}; + +#endif /* DSYS_IMPL_H_ */ diff -r 000000000000 -r 50683c78264e src/geom.cc --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/geom.cc Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,251 @@ +#include +#include +#include "geom.h" + +GeomObject::~GeomObject() +{ +} + + +Sphere::Sphere() +{ + radius = 1.0; +} + +Sphere::Sphere(const Vector3 ¢, float radius) + : center(cent) +{ + this->radius = radius; +} + +void Sphere::set_union(const GeomObject *obj1, const GeomObject *obj2) +{ + const Sphere *sph1 = dynamic_cast(obj1); + const Sphere *sph2 = dynamic_cast(obj2); + + if(!sph1 || !sph2) { + fprintf(stderr, "Sphere::set_union: arguments must be spheres"); + return; + } + + float dist = (sph1->center - sph2->center).length(); + float surf_dist = dist - (sph1->radius + sph2->radius); + float d1 = sph1->radius + surf_dist / 2.0; + float d2 = sph2->radius + surf_dist / 2.0; + float t = d1 / (d1 + d2); + + if(t < 0.0) t = 0.0; + if(t > 1.0) t = 1.0; + + center = sph1->center * t + sph2->center * (1.0 - t); + radius = std::max(dist * t + sph2->radius, dist * (1.0f - t) + sph1->radius); +} + +void Sphere::set_intersection(const GeomObject *obj1, const GeomObject *obj2) +{ + fprintf(stderr, "Sphere::intersection undefined\n"); +} + +bool Sphere::intersect(const Ray &ray, HitPoint *hit) const +{ + float a = dot_product(ray.dir, ray.dir); + float b = 2.0 * ray.dir.x * (ray.origin.x - center.x) + + 2.0 * ray.dir.y * (ray.origin.y - center.y) + + 2.0 * ray.dir.z * (ray.origin.z - center.z); + float c = dot_product(ray.origin, ray.origin) + dot_product(center, center) - + 2.0 * dot_product(ray.origin, center) - radius * radius; + + float discr = b * b - 4.0 * a * c; + if(discr < 1e-4) { + return false; + } + + float sqrt_discr = sqrt(discr); + float t0 = (-b + sqrt_discr) / (2.0 * a); + float t1 = (-b - sqrt_discr) / (2.0 * a); + + if(t0 < 1e-4) + t0 = t1; + if(t1 < 1e-4) + t1 = t0; + + float t = t0 < t1 ? t0 : t1; + if(t < 1e-4) { + return false; + } + + // fill the HitPoint structure + if(hit) { + hit->obj = this; + hit->dist = t; + hit->pos = ray.origin + ray.dir * t; + hit->normal = (hit->pos - center) / radius; + } + return true; +} + + +AABox::AABox() +{ +} + +AABox::AABox(const Vector3 &vmin, const Vector3 &vmax) + : min(vmin), max(vmax) +{ +} + +void AABox::set_union(const GeomObject *obj1, const GeomObject *obj2) +{ + const AABox *box1 = dynamic_cast(obj1); + const AABox *box2 = dynamic_cast(obj2); + + if(!box1 || !box2) { + fprintf(stderr, "AABox::set_union: arguments must be AABoxes too\n"); + return; + } + + min.x = std::min(box1->min.x, box2->min.x); + min.y = std::min(box1->min.y, box2->min.y); + min.z = std::min(box1->min.z, box2->min.z); + + max.x = std::max(box1->max.x, box2->max.x); + max.y = std::max(box1->max.y, box2->max.y); + max.z = std::max(box1->max.z, box2->max.z); +} + +void AABox::set_intersection(const GeomObject *obj1, const GeomObject *obj2) +{ + const AABox *box1 = dynamic_cast(obj1); + const AABox *box2 = dynamic_cast(obj2); + + if(!box1 || !box2) { + fprintf(stderr, "AABox::set_intersection: arguments must be AABoxes too\n"); + return; + } + + for(int i=0; i<3; i++) { + min[i] = std::max(box1->min[i], box2->min[i]); + max[i] = std::min(box1->max[i], box2->max[i]); + + if(max[i] < min[i]) { + max[i] = min[i]; + } + } +} + +bool AABox::intersect(const Ray &ray, HitPoint *hit) const +{ + Vector3 param[2] = {min, max}; + Vector3 inv_dir(1.0 / ray.dir.x, 1.0 / ray.dir.y, 1.0 / ray.dir.z); + int sign[3] = {inv_dir.x < 0, inv_dir.y < 0, inv_dir.z < 0}; + + float tmin = (param[sign[0]].x - ray.origin.x) * inv_dir.x; + float tmax = (param[1 - sign[0]].x - ray.origin.x) * inv_dir.x; + float tymin = (param[sign[1]].y - ray.origin.y) * inv_dir.y; + float tymax = (param[1 - sign[1]].y - ray.origin.y) * inv_dir.y; + + if(tmin > tymax || tymin > tmax) { + return false; + } + if(tymin > tmin) { + tmin = tymin; + } + if(tymax < tmax) { + tmax = tymax; + } + + float tzmin = (param[sign[2]].z - ray.origin.z) * inv_dir.z; + float tzmax = (param[1 - sign[2]].z - ray.origin.z) * inv_dir.z; + + if(tmin > tzmax || tzmin > tmax) { + return false; + } + if(tzmin > tmin) { + tmin = tzmin; + } + if(tzmax < tmax) { + tmax = tzmax; + } + + float t = tmin < 1e-4 ? tmax : tmin; + if(t >= 1e-4) { + + if(hit) { + hit->obj = this; + hit->dist = t; + hit->pos = ray.origin + ray.dir * t; + + float min_dist = FLT_MAX; + Vector3 offs = min + (max - min) / 2.0; + Vector3 local_hit = hit->pos - offs; + + static const Vector3 axis[] = { + Vector3(1, 0, 0), Vector3(0, 1, 0), Vector3(0, 0, 1) + }; + //int tcidx[][2] = {{2, 1}, {0, 2}, {0, 1}}; + + for(int i=0; i<3; i++) { + float dist = fabs((max[i] - offs[i]) - fabs(local_hit[i])); + if(dist < min_dist) { + min_dist = dist; + hit->normal = axis[i] * (local_hit[i] < 0.0 ? 1.0 : -1.0); + //hit->texcoord = Vector2(hit->pos[tcidx[i][0]], hit->pos[tcidx[i][1]]); + } + } + } + return true; + } + return false; + +} + +Plane::Plane() + : normal(0.0, 1.0, 0.0) +{ +} + +Plane::Plane(const Vector3 &p, const Vector3 &norm) + : pt(p) +{ + normal = norm.normalized(); +} + +Plane::Plane(const Vector3 &p1, const Vector3 &p2, const Vector3 &p3) + : pt(p1) +{ + normal = cross_product(p2 - p1, p3 - p1).normalized(); +} + +Plane::Plane(const Vector3 &normal, float dist) +{ + this->normal = normal.normalized(); + pt = this->normal * dist; +} + +void Plane::set_union(const GeomObject *obj1, const GeomObject *obj2) +{ + fprintf(stderr, "Plane::set_union undefined\n"); +} + +void Plane::set_intersection(const GeomObject *obj1, const GeomObject *obj2) +{ + fprintf(stderr, "Plane::set_intersection undefined\n"); +} + +bool Plane::intersect(const Ray &ray, HitPoint *hit) const +{ + float ndotdir = dot_product(normal, ray.dir); + if(fabs(ndotdir) < 1e-4) { + return false; + } + + if(hit) { + Vector3 ptdir = pt - ray.origin; + float t = dot_product(normal, ptdir) / ndotdir; + + hit->pos = ray.origin + ray.dir * t; + hit->normal = normal; + hit->obj = this; + } + return true; +} diff -r 000000000000 -r 50683c78264e src/geom.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/geom.h Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,70 @@ +#ifndef GEOMOBJ_H_ +#define GEOMOBJ_H_ + +#include "vmath/vmath.h" + +class GeomObject; +class SceneNode; + +struct HitPoint { + float dist; //< parametric distance along the ray + Vector3 pos; //< position of intersection (orig + dir * dist) + Vector3 normal; //< normal at the point of intersection + const void *obj; //< pointer to the intersected object + const SceneNode *node; + Ray ray; +}; + +class GeomObject { +public: + virtual ~GeomObject(); + + virtual void set_union(const GeomObject *obj1, const GeomObject *obj2) = 0; + virtual void set_intersection(const GeomObject *obj1, const GeomObject *obj2) = 0; + + virtual bool intersect(const Ray &ray, HitPoint *hit = 0) const = 0; +}; + +class Sphere : public GeomObject { +public: + Vector3 center; + float radius; + + Sphere(); + Sphere(const Vector3 ¢er, float radius); + + void set_union(const GeomObject *obj1, const GeomObject *obj2); + void set_intersection(const GeomObject *obj1, const GeomObject *obj2); + + bool intersect(const Ray &ray, HitPoint *hit = 0) const; +}; + +class AABox : public GeomObject { +public: + Vector3 min, max; + + AABox(); + AABox(const Vector3 &min, const Vector3 &max); + + void set_union(const GeomObject *obj1, const GeomObject *obj2); + void set_intersection(const GeomObject *obj1, const GeomObject *obj2); + + bool intersect(const Ray &ray, HitPoint *hit = 0) const; +}; + +class Plane : public GeomObject { +public: + Vector3 pt, normal; + + Plane(); + Plane(const Vector3 &pt, const Vector3 &normal); + Plane(const Vector3 &p1, const Vector3 &p2, const Vector3 &p3); + Plane(const Vector3 &normal, float dist); + + void set_union(const GeomObject *obj1, const GeomObject *obj2); + void set_intersection(const GeomObject *obj1, const GeomObject *obj2); + + bool intersect(const Ray &ray, HitPoint *hit = 0) const; +}; + +#endif // GEOMOBJ_H_ diff -r 000000000000 -r 50683c78264e src/image.cc --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/image.cc Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,365 @@ +#include +#include +#include +#include "opengl.h" +#include "image.h" +#include "imago2.h" + + +static unsigned int next_pow2(unsigned int x); + +Image::Image() +{ + width = height = tex_width = tex_height = 0; + pixels = 0; + tex = 0; + tex_valid = false; +} + +Image::~Image() +{ + destroy(); +} + +Image::Image(const Image &img) +{ + pixels = 0; + create(img.width, img.height, img.pixels); +} + +Image &Image::operator =(const Image &img) +{ + if(&img != this) { + create(img.width, img.height, img.pixels); + } + return *this; +} + +bool Image::create(int width, int height, unsigned char *pixels) +{ + destroy(); + + try { + unsigned char *tmp = new unsigned char[width * height * 4]; + this->pixels = tmp; + this->width = width; + this->height = height; + } + catch(...) { + return false; + } + + if(pixels) { + memcpy(this->pixels, pixels, width * height * 4); + } + return true; +} + +void Image::destroy() +{ + delete [] pixels; + pixels = 0; + width = height = 0; + + if(tex) { + glDeleteTextures(1, &tex); + tex = 0; + tex_valid = false; + } +} + +bool Image::load(const char *fname) +{ + int xsz, ysz; + unsigned char *pix = (unsigned char*)img_load_pixels(fname, &xsz, &ysz, IMG_FMT_RGBA32); + if(!pix) { + return false; + } + return create(xsz, ysz, pix); +} + +bool Image::save(const char *fname) const +{ + return img_save_pixels(fname, pixels, width, height, IMG_FMT_RGBA32) != -1; +} + +unsigned int Image::texture() const +{ + if(!pixels) { + return 0; + } + if(!tex) { + glGenTextures(1, &tex); + } + + if(!tex_valid) { + tex_width = next_pow2(width); + tex_height = next_pow2(height); + + glBindTexture(GL_TEXTURE_2D, tex); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + + if(GLEW_SGIS_generate_mipmap) { + glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, 1); + + void *data = (width == tex_width && height == tex_height) ? pixels : 0; + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex_width, tex_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); + if(!data) { + glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels); + } + } else { + gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, tex_width, tex_height, GL_RGBA, GL_UNSIGNED_BYTE, pixels); + } + + if(GLEW_EXT_texture_filter_anisotropic) { + static float max_aniso = -1.0; + + if(max_aniso < 0.0) { + glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &max_aniso); + printf("using anisotropic filtering: x%g\n", max_aniso); + } + + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, max_aniso); + } + tex_valid = true; + } + return tex; +} + +int Image::texture_width() const +{ + return tex_width; +} + +int Image::texture_height() const +{ + return tex_height; +} + +void Image::invalidate_texture() +{ + tex_valid = false; +} + + +void clear_image(Image *img) +{ + clear_image(img, 0, 0, 0, 255); +} + +void clear_image(Image *img, float r, float g, float b, float a) +{ + if(!img->pixels) { + return; + } + + unsigned char col[4]; + unsigned char *ptr = img->pixels; + int npix = img->width * img->height; + + col[0] = (int)(r * 255.0); + col[1] = (int)(g * 255.0); + col[2] = (int)(b * 255.0); + col[3] = (int)(a * 255.0); + + for(int i=0; ipixels) { + return; + } + + unsigned char alpha = (int)(a * 255.0); + unsigned char *ptr = img->pixels; + int npix = img->width * img->height; + + for(int i=0; iwidth; + int ysz = dest->height; + int npixels = xsz * ysz; + int nbytes = npixels * 4; + int tint = (int)(t * 255); + + if(aimg->width != xsz || bimg->width != xsz || aimg->height != ysz || bimg->height != ysz) { + return false; + } + + unsigned char *dptr = dest->pixels; + const unsigned char *aptr = aimg->pixels; + const unsigned char *bptr = bimg->pixels; + + switch(op) { + case IMG_OP_ADD: + for(int i=0; i 255 ? 255 : x; + } + break; + + case IMG_OP_SUB: + for(int i=0; i> 8; + *dptr++ = x > 255 ? 255 : x; + } + break; + + case IMG_OP_LERP: + for(int i=0; i> 8); + *dptr++ = x > 255 ? 255 : (x < 0 ? 0 : x); + } + break; + + default: + break; + } + + dest->invalidate_texture(); + return true; +} + +void convolve_horiz_image(Image *dest, float *kern, int ksz, float scale) +{ + if((ksz & 1) == 0) { + fprintf(stderr, "%s: kernel size (%d) must be odd, skipping last value\n", __FUNCTION__, ksz); + --ksz; + } + if(scale == 0.0) { + // calculate scale factor + float sum = 0.0; + for(int i=0; iwidth * 4 * sizeof *buf); + unsigned char *sptr = dest->pixels; + + for(int i=0; iheight; i++) { + float *bptr = buf; + for(int j=0; jwidth * 4; j++) { + *bptr++ = (float)(sptr[j] / 255.0); + } + + for(int j=0; jwidth; j++) { + float col[] = {0, 0, 0, 0}; + + for(int k=0; k= dest->width) idx = dest->width - 1; + + col[0] += buf[idx * 4] * kern[k]; + col[1] += buf[idx * 4 + 1] * kern[k]; + col[2] += buf[idx * 4 + 2] * kern[k]; + col[3] += buf[idx * 4 + 3] * kern[k]; + } + + int ri = (int)(col[0] * scale * 255.0); + int gi = (int)(col[1] * scale * 255.0); + int bi = (int)(col[2] * scale * 255.0); + int ai = (int)(col[3] * scale * 255.0); + + sptr[0] = ri < 0 ? 0 : (ri > 255 ? 255 : ri); + sptr[1] = gi < 0 ? 0 : (gi > 255 ? 255 : gi); + sptr[2] = bi < 0 ? 0 : (bi > 255 ? 255 : bi); + sptr[3] = ai < 0 ? 0 : (ai > 255 ? 255 : ai); + sptr += 4; + } + } + + dest->invalidate_texture(); +} + +void convolve_vert_image(Image *dest, float *kern, int ksz, float scale) +{ + if((ksz & 1) == 0) { + fprintf(stderr, "%s: kernel size (%d) must be odd, skipping last value\n", __FUNCTION__, ksz); + --ksz; + } + if(scale == 0.0) { + // calculate scale factor + float sum = 0.0; + for(int i=0; iheight * 4 * sizeof *buf); + unsigned char *sptr = dest->pixels; + + for(int i=0; iwidth; i++) { + float *bptr = buf; + sptr = dest->pixels + i * 4; + + for(int j=0; jheight; j++) { + for(int k=0; k<4; k++) { + *bptr++ = (float)(sptr[k] / 255.0); + } + sptr += dest->width * 4; + } + + sptr = dest->pixels + i * 4; + + for(int j=0; jheight; j++) { + float col[] = {0, 0, 0, 0}; + + for(int k=0; k= dest->height) idx = dest->height - 1; + + col[0] += buf[idx * 4] * kern[k]; + col[1] += buf[idx * 4 + 1] * kern[k]; + col[2] += buf[idx * 4 + 2] * kern[k]; + col[3] += buf[idx * 4 + 3] * kern[k]; + } + + int ri = (int)(col[0] * scale * 255.0); + int gi = (int)(col[1] * scale * 255.0); + int bi = (int)(col[2] * scale * 255.0); + int ai = (int)(col[3] * scale * 255.0); + + sptr[0] = ri < 0 ? 0 : (ri > 255 ? 255 : ri); + sptr[1] = gi < 0 ? 0 : (gi > 255 ? 255 : gi); + sptr[2] = bi < 0 ? 0 : (bi > 255 ? 255 : bi); + sptr[3] = ai < 0 ? 0 : (ai > 255 ? 255 : ai); + sptr += dest->width * 4; + } + } +} + +static unsigned int next_pow2(unsigned int x) +{ + x--; + x = (x >> 1) | x; + x = (x >> 2) | x; + x = (x >> 4) | x; + x = (x >> 8) | x; + x = (x >> 16) | x; + return x + 1; +} diff -r 000000000000 -r 50683c78264e src/image.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/image.h Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,49 @@ +#ifndef IMAGE_H_ +#define IMAGE_H_ + +class Image { +private: + mutable int tex_width, tex_height; + mutable unsigned int tex; + mutable bool tex_valid; + +public: + int width, height; + unsigned char *pixels; + + Image(); + ~Image(); + + Image(const Image &img); + Image &operator =(const Image &img); + + bool create(int width, int height, unsigned char *pixels = 0); + void destroy(); + + bool load(const char *fname); + bool save(const char *fname) const; + + unsigned int texture() const; + int texture_width() const; + int texture_height() const; + + void invalidate_texture(); +}; + +void clear_image(Image *img); +void clear_image(Image *img, float r, float g, float b, float a = 255); +void clear_image_alpha(Image *img, float a); + +enum ImgCombine { + IMG_OP_ADD, + IMG_OP_SUB, + IMG_OP_MUL, + IMG_OP_LERP +}; + +bool combine_image(Image *dest, const Image *aimg, const Image *bimg, ImgCombine op = IMG_OP_LERP, float t = 0.5); + +void convolve_horiz_image(Image *dest, float *kern, int ksz, float scale = 0.0); +void convolve_vert_image(Image *dest, float *kern, int ksz, float scale = 0.0); + +#endif // IMAGE_H_ diff -r 000000000000 -r 50683c78264e src/light.cc --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/light.cc Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,17 @@ +#include "light.h" +#include "opengl.h" + +Light::Light() + : color(1, 1, 1) +{ +} + +void Light::setup(int idx) const +{ + float lpos[] = {pos.x, pos.y, pos.z, 1.0}; + float col[] = {color.x, color.y, color.z, 1.0}; + + glLightfv(GL_LIGHT0 + idx, GL_POSITION, lpos); + glLightfv(GL_LIGHT0 + idx, GL_DIFFUSE, col); + glLightfv(GL_LIGHT0 + idx, GL_SPECULAR, col); +} diff -r 000000000000 -r 50683c78264e src/light.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/light.h Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,16 @@ +#ifndef LIGHT_H_ +#define LIGHT_H_ + +#include "vmath/vmath.h" + +class Light { +public: + Vector3 pos; + Vector3 color; + + Light(); + + void setup(int idx = 0) const; +}; + +#endif // LIGHT_H_ diff -r 000000000000 -r 50683c78264e src/main.cc --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main.cc Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,409 @@ +#include +#include +#include +#include +#include "opengl.h" +#include +#include "scene.h" +#include "meshgen.h" +#include "pnoise.h" +#include "image.h" +#include "rng.h" +#include "sdr.h" +#include "audio/audio.h" +#include "audio/ovstream.h" +#include "dsys/dsys.h" + +bool init(); +void cleanup(); +void display(); +void idle(); +void reshape(int x, int y); +void keyb(unsigned char key, int x, int y); +void mouse(int bn, int st, int x, int y); +void motion(int x, int y); + +float cam_theta, cam_phi = 25, cam_dist = 6; +Scene *scn; +bool wireframe; +int num_shells = 64; +float shell_scale = 1.015; +bool anim = true; +bool fullscr = true; + +static std::vector images; +static Object *pkin_obj; +static Mesh *pkin_mesh; +static unsigned int pkin_tex; + +static unsigned int sdr_spot; + +static float ramp[3]; + + +static OggVorbisStream *music; +static struct dsys_demo *demo; + + +int main(int argc, char **argv) +{ + glutInit(&argc, argv); + glutInitWindowSize(1280, 720); + glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE); + glutCreateWindow("DBF Halloween 2015 compo entry"); + + if(argv[1]) { + if(strcmp(argv[1], "-w") == 0 || strcmp(argv[1], "-windowed") == 0) { + fullscr = false; + } else { + fprintf(stderr, "unrecognized argument: %s\nUse -w or -windowed to run in a window\n", argv[1]); + return 1; + } + } + if(fullscr) { + glutFullScreen(); + } + + glutDisplayFunc(display); + glutIdleFunc(idle); + glutReshapeFunc(reshape); + glutKeyboardFunc(keyb); + glutMouseFunc(mouse); + glutMotionFunc(motion); + + if(!init()) { + return 1; + } + glutMainLoop(); + return 0; +} + +static float ground_func(float u, float v, void *cls) +{ + return fbm2(u * 3.0, v * 3.0, 2) * 0.8; +} + +static Vector2 pumpkin_func(float u, float v, void *cls) +{ + float theta = v * M_PI; + float r = sin(theta) * 0.5 + 0.5; + + // modulate a high-frequency short-amp wave along u to make the ribs(?) + r += fabs(sin(u * M_PI * 12.0)) * 0.02;// + 1.0; + + // throw some noise in there for good measure + r += pnoise2(u * 16.0, v * 8.0, 16) * 0.05;// + 1.0; + + float x = sin(theta) * r; + float y = cos(theta) * r; + return Vector2(x, y); +} + +#define CLAMP(x, a, b) std::max(std::min(x, b), a) + +bool init() +{ + if(init_opengl() == -1) { + return false; + } + Mesh::use_custom_sdr_attr = false; + + glEnable(GL_DEPTH_TEST); + glEnable(GL_CULL_FACE); + glEnable(GL_LIGHTING); + glEnable(GL_NORMALIZE); + + if(!(demo = dsys_open("data/demo.script"))) { + fprintf(stderr, "failed to load sequencing file\n"); + return false; + } + for(int i=0; i<3; i++) { + char name[16]; + sprintf(name, "ramp%d", i); + struct dsys_event *ev = dsys_event(demo, name); + if(ev) { + printf("found event: %s\n", name); + dsys_event_link(ev, ramp + i); + } + } + + + if(!(sdr_spot = create_program_load("sdr/default.v.glsl", "sdr/spot.p.glsl"))) { + return false; + } + + Matrix4x4 xform; + + scn = new Scene; + + Light *lt = new Light; + lt->pos = Vector3(-10, 10, 10); + scn->add_light(lt); + + // floor + Mesh *mesh = new Mesh; + gen_heightmap(mesh, 20, 20, 50, 50, ground_func); + xform.set_rotation(Vector3(-M_PI / 2.0, 0, 0)); + mesh->apply_xform(xform); + + Object *obj = new Object; + obj->set_mesh(mesh); + obj->xform().set_translation(Vector3(0, -0.9, 0)); + obj->mtl.diffuse = Vector3(0.7, 0.7, 0.7); + obj->set_shader(sdr_spot); + scn->add_object(obj); + + Image *img = new Image; + if(!img->load("data/grass02.jpg")) { + return false; + } + images.push_back(img); + obj->tex_xform().set_scaling(Vector3(5.0, 10.0, 1.0)); + obj->set_texture(img->texture()); + + // pumpkin texture + img = new Image; + if(!img->create(1024, 512)) { + return false; + } + images.push_back(img); + + static const Vector3 pkin_col = Vector3(0.824, 0.325, 0.063); + unsigned char *pptr = img->pixels; + for(int i=0; iheight; i++) { + float v = (float)i / (float)img->height; + for(int j=0; jwidth; j++) { + float u = (float)j / (float)img->width; + + float val = pfbm2(u * 64.0, v * 32.0, 3, 128) * 0.1 + 1.0; + val *= fabs(sin(u * M_PI * 12.0)) * 0.2 + 0.8; + Vector3 col = pkin_col * val; + + *pptr++ = (int)(CLAMP(col.x, 0.0, 1.0) * 255.0f); + *pptr++ = (int)(CLAMP(col.y, 0.0, 1.0) * 255.0f); + *pptr++ = (int)(CLAMP(col.z, 0.0, 1.0) * 255.0f); + *pptr++ = 255; + } + } + + // pumpkin + pkin_mesh = new Mesh; + gen_revol(pkin_mesh, 64, 20, pumpkin_func); + + pkin_obj = new Object; + pkin_obj->xform().set_rotation(Vector3(DEG_TO_RAD(-10), DEG_TO_RAD(90), 0)); + pkin_obj->set_mesh(pkin_mesh); + pkin_obj->set_texture(img->texture()); + obj->set_shader(sdr_spot); + scn->add_object(pkin_obj); + + int num_pumpkins = 20; + float dtheta = 1.0 / (float)num_pumpkins; + + for(int i=0; ixform().translate(Vector3(x, h - 0.5, y)); + obj->xform().rotate(Vector3(DEG_TO_RAD(rng_frand() * 40.0 - 20.0), rng_frand() * M_PI * 2.0, 0)); + obj->xform().scale(Vector3(0.7, 0.7, 0.7)); + obj->set_mesh(pkin_mesh); + obj->set_texture(img->texture()); + obj->set_shader(sdr_spot); + scn->add_object(obj); + } + + // pumpkin glow mask + img = new Image; + if(!img->load("data/pumpkin_mask_blured.png")) { + return false; + } + images.push_back(img); + pkin_tex = img->texture(); + + if(!init_audio()) { + fprintf(stderr, "failed to initialize audio\n"); + return false; + } + music = new OggVorbisStream; + if(!music->open("data/welcome_to_horrorland.ogg")) { + fprintf(stderr, "failed to open music\n"); + return false; + } + music->play(AUDIO_PLAYMODE_LOOP); + + return true; +} + +void cleanup() +{ + music->stop(); + delete music; + destroy_audio(); + + delete scn; + + for(size_t i=0; idraw(); + + glPushAttrib(GL_ENABLE_BIT | GL_LIGHTING_BIT); + glDisable(GL_CULL_FACE); + + glDepthMask(0); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE); + + glBindTexture(GL_TEXTURE_2D, pkin_tex); + glEnable(GL_TEXTURE_2D); + + glMatrixMode(GL_MODELVIEW); + glPushMatrix(); + glMultTransposeMatrixf(pkin_obj->xform()[0]); + + num_shells = fbm1(sec * 2.0, 2) * 28.0 + 45; + + for(int i=0; idraw(); + } + glDepthMask(1); + + glPopMatrix(); + glPopAttrib(); + + + glutSwapBuffers(); + assert(glGetError() == GL_NO_ERROR); +} + +void idle() +{ + glutPostRedisplay(); +} + +void reshape(int x, int y) +{ + glViewport(0, 0, x, y); + + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + gluPerspective(50.0, (float)x / (float)y, 0.5, 500.0); +} + +void keyb(unsigned char key, int x, int y) +{ + switch(key) { + case 27: + exit(0); + + case 'w': + wireframe = !wireframe; + break; + + case 'f': + case 'F': + { + static int prev_pos[2] = {50, 80}; + + fullscr = !fullscr; + if(fullscr) { + prev_pos[0] = glutGet(GLUT_WINDOW_X); + prev_pos[1] = glutGet(GLUT_WINDOW_Y); + glutFullScreen(); + } else { + glutPositionWindow(prev_pos[0], prev_pos[1]); + } + } + break; + } +} + +static int prev_x, prev_y; +static bool bnstate[16]; + +void mouse(int bn, int st, int x, int y) +{ + prev_x = x; + prev_y = y; + bnstate[bn - GLUT_LEFT_BUTTON] = st == GLUT_DOWN; + + anim = !(st == GLUT_DOWN); +} + +void motion(int x, int y) +{ + int dx = x - prev_x; + int dy = y - prev_y; + prev_x = x; + prev_y = y; + + if(!dx && !dy) return; + + if(bnstate[0]) { + //anim = false; + cam_theta += dx * 0.5; + cam_phi += dy * 0.5; + if(cam_phi < -90) cam_phi = -90; + if(cam_phi > 90) cam_phi = 90; + } + if(bnstate[2]) { + //anim = false; + cam_dist += dy * 0.1; + if(cam_dist < 0.0) cam_dist = 0.0; + } +} diff -r 000000000000 -r 50683c78264e src/mesh.cc --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/mesh.cc Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,1237 @@ +#include +#include +#include +#include +#include "opengl.h" +#include "mesh.h" +//#include "xform_node.h" + +#define USE_OLDGL + +bool Mesh::use_custom_sdr_attr = true; +int Mesh::global_sdr_loc[NUM_MESH_ATTR] = { 0, 1, 2, 3, 4, 5, 6 }; +/* + (int)SDR_ATTR_VERTEX, + (int)SDR_ATTR_NORMAL, + (int)SDR_ATTR_TANGENT, + (int)SDR_ATTR_TEXCOORD, + (int)SDR_ATTR_COLOR, + -1, -1}; +*/ +unsigned int Mesh::intersect_mode = ISECT_DEFAULT; +float Mesh::vertex_sel_dist = 0.01; +float Mesh::vis_vecsize = 1.0; + +Mesh::Mesh() +{ + clear(); + + glGenBuffers(NUM_MESH_ATTR + 1, buffer_objects); + + for(int i=0; iname = name; +} + +const char *Mesh::get_name() const +{ + return name.c_str(); +} + +bool Mesh::has_attrib(int attr) const +{ + if(attr < 0 || attr >= NUM_MESH_ATTR) { + return false; + } + + // if neither of these is valid, then nobody has set this attribute + return vattr[attr].vbo_valid || vattr[attr].data_valid; +} + +bool Mesh::is_indexed() const +{ + return ibo_valid || idata_valid; +} + +void Mesh::clear() +{ + //bones.clear(); + + for(int i=0; i= NUM_MESH_ATTR) { + fprintf(stderr, "%s: invalid attrib: %d\n", __FUNCTION__, attrib); + return 0; + } + + if(nverts && num != nverts) { + fprintf(stderr, "%s: attribute count missmatch (%d instead of %d)\n", __FUNCTION__, num, nverts); + return 0; + } + nverts = num; + + vattr[attrib].data.clear(); + vattr[attrib].nelem = nelem; + vattr[attrib].data.resize(num * nelem); + + if(data) { + memcpy(&vattr[attrib].data[0], data, num * nelem * sizeof *data); + } + + vattr[attrib].data_valid = true; + vattr[attrib].vbo_valid = false; + return &vattr[attrib].data[0]; +} + +float *Mesh::get_attrib_data(int attrib) +{ + if(attrib < 0 || attrib >= NUM_MESH_ATTR) { + fprintf(stderr, "%s: invalid attrib: %d\n", __FUNCTION__, attrib); + return 0; + } + + vattr[attrib].vbo_valid = false; + return (float*)((const Mesh*)this)->get_attrib_data(attrib); +} + +const float *Mesh::get_attrib_data(int attrib) const +{ + if(attrib < 0 || attrib >= NUM_MESH_ATTR) { + fprintf(stderr, "%s: invalid attrib: %d\n", __FUNCTION__, attrib); + return 0; + } + + if(!vattr[attrib].data_valid) { +#if GL_ES_VERSION_2_0 + fprintf(stderr, "%s: can't read back attrib data on CrippledGL ES\n", __FUNCTION__); + return 0; +#else + if(!vattr[attrib].vbo_valid) { + fprintf(stderr, "%s: unavailable attrib: %d\n", __FUNCTION__, attrib); + return 0; + } + + // local data copy is unavailable, grab the data from the vbo + Mesh *m = (Mesh*)this; + m->vattr[attrib].data.resize(nverts * vattr[attrib].nelem); + + glBindBuffer(GL_ARRAY_BUFFER, vattr[attrib].vbo); + void *data = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_ONLY); + memcpy(&m->vattr[attrib].data[0], data, nverts * vattr[attrib].nelem * sizeof(float)); + glUnmapBuffer(GL_ARRAY_BUFFER); + + vattr[attrib].data_valid = true; +#endif + } + + return &vattr[attrib].data[0]; +} + +void Mesh::set_attrib(int attrib, int idx, const Vector4 &v) +{ + float *data = get_attrib_data(attrib); + if(data) { + data += idx * vattr[attrib].nelem; + for(int i=0; iget_index_data(); +} + +const unsigned int *Mesh::get_index_data() const +{ + if(!idata_valid) { +#if GL_ES_VERSION_2_0 + fprintf(stderr, "%s: can't read back index data in CrippledGL ES\n", __FUNCTION__); + return 0; +#else + if(!ibo_valid) { + fprintf(stderr, "%s: indices unavailable\n", __FUNCTION__); + return 0; + } + + // local data copy is unavailable, gram the data from the ibo + Mesh *m = (Mesh*)this; + int nidx = nfaces * 3; + m->idata.resize(nidx); + + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); + void *data = glMapBuffer(GL_ELEMENT_ARRAY_BUFFER, GL_READ_ONLY); + memcpy(&m->idata[0], data, nidx * sizeof(unsigned int)); + glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER); + + idata_valid = true; +#endif + } + + return &idata[0]; +} + +int Mesh::get_index_count() const +{ + return nfaces * 3; +} + +void Mesh::append(const Mesh &mesh) +{ + unsigned int idxoffs = nverts; + + if(!nverts) { + clone(mesh); + return; + } + + nverts += mesh.nverts; + nfaces += mesh.nfaces; + + for(int i=0; i= NUM_MESH_ATTR) { + return; + } + Mesh::global_sdr_loc[attr] = loc; +} + +/// static function +int Mesh::get_attrib_location(int attr) +{ + if(attr < 0 || attr >= NUM_MESH_ATTR) { + return -1; + } + return Mesh::global_sdr_loc[attr]; +} + +/// static function +void Mesh::clear_attrib_locations() +{ + for(int i=0; i= (int)bones.size()) { + return 0; + } + return bones[idx]; +} + +int Mesh::get_bones_count() const +{ + return (int)bones.size(); +} +*/ + +bool Mesh::pre_draw() const +{ + cur_sdr = 0; + if(glcaps.shaders) { + glGetIntegerv(GL_CURRENT_PROGRAM, &cur_sdr); + } + + ((Mesh*)this)->update_buffers(); + + if(!vattr[MESH_ATTR_VERTEX].vbo_valid) { + fprintf(stderr, "%s: invalid vertex buffer\n", __FUNCTION__); + return false; + } + + if(cur_sdr && use_custom_sdr_attr) { + // rendering with shaders + if(global_sdr_loc[MESH_ATTR_VERTEX] == -1) { + fprintf(stderr, "%s: shader attribute location for vertices unset\n", __FUNCTION__); + return false; + } + + for(int i=0; i= 0 && vattr[i].vbo_valid) { + glBindBuffer(GL_ARRAY_BUFFER, vattr[i].vbo); + glVertexAttribPointer(loc, vattr[i].nelem, GL_FLOAT, GL_FALSE, 0, 0); + glEnableVertexAttribArray(loc); + } + } + } else { +#ifndef GL_ES_VERSION_2_0 + // rendering with fixed-function (not available in GLES2) + glBindBuffer(GL_ARRAY_BUFFER, vattr[MESH_ATTR_VERTEX].vbo); + glVertexPointer(vattr[MESH_ATTR_VERTEX].nelem, GL_FLOAT, 0, 0); + glEnableClientState(GL_VERTEX_ARRAY); + + if(vattr[MESH_ATTR_NORMAL].vbo_valid) { + glBindBuffer(GL_ARRAY_BUFFER, vattr[MESH_ATTR_NORMAL].vbo); + glNormalPointer(GL_FLOAT, 0, 0); + glEnableClientState(GL_NORMAL_ARRAY); + } + if(vattr[MESH_ATTR_TEXCOORD].vbo_valid) { + glBindBuffer(GL_ARRAY_BUFFER, vattr[MESH_ATTR_TEXCOORD].vbo); + glTexCoordPointer(vattr[MESH_ATTR_TEXCOORD].nelem, GL_FLOAT, 0, 0); + glEnableClientState(GL_TEXTURE_COORD_ARRAY); + } + if(vattr[MESH_ATTR_COLOR].vbo_valid) { + glBindBuffer(GL_ARRAY_BUFFER, vattr[MESH_ATTR_COLOR].vbo); + glColorPointer(vattr[MESH_ATTR_COLOR].nelem, GL_FLOAT, 0, 0); + glEnableClientState(GL_COLOR_ARRAY); + } +#endif + } + glBindBuffer(GL_ARRAY_BUFFER, 0); + + return true; +} + +void Mesh::draw() const +{ + if(!pre_draw()) return; + + if(ibo_valid) { + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); + glDrawElements(GL_TRIANGLES, nfaces * 3, GL_UNSIGNED_INT, 0); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); + } else { + glDrawArrays(GL_TRIANGLES, 0, nverts); + } + + post_draw(); +} + +void Mesh::post_draw() const +{ + if(cur_sdr && use_custom_sdr_attr) { + // rendered with shaders + for(int i=0; i= 0 && vattr[i].vbo_valid) { + glDisableVertexAttribArray(loc); + } + } + } else { +#ifndef GL_ES_VERSION_2_0 + // rendered with fixed-function + glDisableClientState(GL_VERTEX_ARRAY); + if(vattr[MESH_ATTR_NORMAL].vbo_valid) { + glDisableClientState(GL_NORMAL_ARRAY); + } + if(vattr[MESH_ATTR_TEXCOORD].vbo_valid) { + glDisableClientState(GL_TEXTURE_COORD_ARRAY); + } + if(vattr[MESH_ATTR_COLOR].vbo_valid) { + glDisableClientState(GL_COLOR_ARRAY); + } +#endif + } +} + +void Mesh::draw_wire() const +{ + if(!pre_draw()) return; + + ((Mesh*)this)->update_wire_ibo(); + + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, wire_ibo); + glDrawElements(GL_LINES, nfaces * 6, GL_UNSIGNED_INT, 0); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); + + post_draw(); +} + +void Mesh::draw_vertices() const +{ + if(!pre_draw()) return; + + glDrawArrays(GL_POINTS, 0, nverts); + + post_draw(); +} + +void Mesh::draw_normals() const +{ +#ifdef USE_OLDGL + int cur_sdr = 0; + if(glcaps.shaders) { + glGetIntegerv(GL_CURRENT_PROGRAM, &cur_sdr); + } + + Vector3 *varr = (Vector3*)get_attrib_data(MESH_ATTR_VERTEX); + Vector3 *norm = (Vector3*)get_attrib_data(MESH_ATTR_NORMAL); + if(!varr || !norm) { + return; + } + + glBegin(GL_LINES); + if(cur_sdr && use_custom_sdr_attr) { + int vert_loc = global_sdr_loc[MESH_ATTR_VERTEX]; + if(vert_loc < 0) { + glEnd(); + return; + } + + for(size_t i=0; icalc_aabb(); + } + *vmin = aabb.min; + *vmax = aabb.max; +} + +const AABox &Mesh::get_aabbox() const +{ + if(!aabb_valid) { + ((Mesh*)this)->calc_aabb(); + } + return aabb; +} + +float Mesh::get_bsphere(Vector3 *center, float *rad) const +{ + if(!bsph_valid) { + ((Mesh*)this)->calc_bsph(); + } + *center = bsph.center; + *rad = bsph.radius; + return bsph.radius; +} + +const Sphere &Mesh::get_bsphere() const +{ + if(!bsph_valid) { + ((Mesh*)this)->calc_bsph(); + } + return bsph; +} + +/// static function +void Mesh::set_intersect_mode(unsigned int mode) +{ + Mesh::intersect_mode = mode; +} + +/// static function +unsigned int Mesh::get_intersect_mode() +{ + return Mesh::intersect_mode; +} + +/// static function +void Mesh::set_vertex_select_distance(float dist) +{ + Mesh::vertex_sel_dist = dist; +} + +/// static function +float Mesh::get_vertex_select_distance() +{ + return Mesh::vertex_sel_dist; +} + +bool Mesh::intersect(const Ray &ray, HitPoint *hit) const +{ + assert((Mesh::intersect_mode & (ISECT_VERTICES | ISECT_FACE)) != (ISECT_VERTICES | ISECT_FACE)); + + const Vector3 *varr = (Vector3*)get_attrib_data(MESH_ATTR_VERTEX); + const Vector3 *narr = (Vector3*)get_attrib_data(MESH_ATTR_NORMAL); + if(!varr) { + return false; + } + const unsigned int *idxarr = get_index_data(); + + // first test with the bounding box + AABox box; + get_aabbox(&box.min, &box.max); + if(!box.intersect(ray)) { + return false; + } + + HitPoint nearest_hit; + nearest_hit.dist = FLT_MAX; + nearest_hit.obj = 0; + + if(Mesh::intersect_mode & ISECT_VERTICES) { + // we asked for "intersections" with the vertices of the mesh + long nearest_vidx = -1; + float thres_sq = Mesh::vertex_sel_dist * Mesh::vertex_sel_dist; + + for(unsigned int i=0; i 0) { + continue; + } + + // project the vertex onto the ray line + float t = dot_product(varr[i] - ray.origin, ray.dir); + Vector3 vproj = ray.origin + ray.dir * t; + + float dist_sq = (vproj - varr[i]).length_sq(); + if(dist_sq < thres_sq) { + if(!hit) { + return true; + } + if(t < nearest_hit.dist) { + nearest_hit.dist = t; + nearest_vidx = i; + } + } + } + + if(nearest_vidx != -1) { + hitvert = varr[nearest_vidx]; + nearest_hit.obj = &hitvert; + } + + } else { + // regular intersection test with polygons + + for(unsigned int i=0; i 0) { + continue; + } + + HitPoint fhit; + if(face.intersect(ray, hit ? &fhit : 0)) { + if(!hit) { + return true; + } + if(fhit.dist < nearest_hit.dist) { + nearest_hit = fhit; + hitface = face; + } + } + } + } + + if(nearest_hit.obj) { + if(hit) { + *hit = nearest_hit; + + // if we are interested in the mesh and not the faces set obj to this + if(Mesh::intersect_mode & ISECT_FACE) { + hit->obj = &hitface; + } else if(Mesh::intersect_mode & ISECT_VERTICES) { + hit->obj = &hitvert; + } else { + hit->obj = this; + } + } + return true; + } + return false; +} + + +// texture coordinate manipulation +void Mesh::texcoord_apply_xform(const Matrix4x4 &xform) +{ + if(!has_attrib(MESH_ATTR_TEXCOORD)) { + return; + } + + for(unsigned int i=0; i abs_ny && abs_nx > abs_nz ? 0 : (abs_ny > abs_nz ? 1 : 2); + + float uv[2], *uvptr = uv; + for(int j=0; j<3; j++) { + if(j == dom) continue; // skip dominant axis + + *uvptr++ = pos[j]; + } + set_attrib(MESH_ATTR_TEXCOORD, i, Vector4(uv[0], uv[1], 0, 1)); + } +} + +// ------ private member functions ------ + +void Mesh::calc_aabb() +{ + // the cast is to force calling the const version which doesn't invalidate + if(!((const Mesh*)this)->get_attrib_data(MESH_ATTR_VERTEX)) { + return; + } + + aabb.min = Vector3(FLT_MAX, FLT_MAX, FLT_MAX); + aabb.max = -aabb.min; + + for(unsigned int i=0; i aabb.max[j]) { + aabb.max[j] = v[j]; + } + } + } + aabb_valid = true; +} + +void Mesh::calc_bsph() +{ + // the cast is to force calling the const version which doesn't invalidate + if(!((const Mesh*)this)->get_attrib_data(MESH_ATTR_VERTEX)) { + return; + } + + Vector3 v; + bsph.center = Vector3(0, 0, 0); + + // first find the center + for(unsigned int i=0; i bsph.radius) { + bsph.radius = dist_sq; + } + } + bsph.radius = sqrt(bsph.radius); + + bsph_valid = true; +} + +void Mesh::update_buffers() +{ + for(int i=0; iget_index_data(); + + for(unsigned int i=0; icalc_normal(); + } + return normal; +} + +void Triangle::transform(const Matrix4x4 &xform) +{ + v[0].transform(xform); + v[1].transform(xform); + v[2].transform(xform); + normal_valid = false; +} + +void Triangle::draw() const +{ + Vector3 n[3]; + n[0] = get_normal(); + n[1] = get_normal(); + n[2] = get_normal(); + + int vloc = Mesh::get_attrib_location(MESH_ATTR_VERTEX); + int nloc = Mesh::get_attrib_location(MESH_ATTR_NORMAL); + + glEnableVertexAttribArray(vloc); + glVertexAttribPointer(vloc, 3, GL_FLOAT, GL_FALSE, 0, &v[0].x); + glVertexAttribPointer(nloc, 3, GL_FLOAT, GL_FALSE, 0, &n[0].x); + + glDrawArrays(GL_TRIANGLES, 0, 3); + + glDisableVertexAttribArray(vloc); + glDisableVertexAttribArray(nloc); +} + +void Triangle::draw_wire() const +{ + static const int idxarr[] = {0, 1, 1, 2, 2, 0}; + int vloc = Mesh::get_attrib_location(MESH_ATTR_VERTEX); + + glEnableVertexAttribArray(vloc); + glVertexAttribPointer(vloc, 3, GL_FLOAT, GL_FALSE, 0, &v[0].x); + + glDrawElements(GL_LINES, 6, GL_UNSIGNED_INT, idxarr); + + glDisableVertexAttribArray(vloc); +} + +Vector3 Triangle::calc_barycentric(const Vector3 &pos) const +{ + Vector3 norm = get_normal(); + + float area_sq = fabs(dot_product(cross_product(v[1] - v[0], v[2] - v[0]), norm)); + if(area_sq < 1e-5) { + return Vector3(0, 0, 0); + } + + float asq0 = fabs(dot_product(cross_product(v[1] - pos, v[2] - pos), norm)); + float asq1 = fabs(dot_product(cross_product(v[2] - pos, v[0] - pos), norm)); + float asq2 = fabs(dot_product(cross_product(v[0] - pos, v[1] - pos), norm)); + + return Vector3(asq0 / area_sq, asq1 / area_sq, asq2 / area_sq); +} + +bool Triangle::intersect(const Ray &ray, HitPoint *hit) const +{ + Vector3 normal = get_normal(); + + float ndotdir = dot_product(ray.dir, normal); + if(fabs(ndotdir) < 1e-4) { + return false; + } + + Vector3 vertdir = v[0] - ray.origin; + float t = dot_product(normal, vertdir) / ndotdir; + + Vector3 pos = ray.origin + ray.dir * t; + Vector3 bary = calc_barycentric(pos); + + if(bary.x + bary.y + bary.z > 1.00001) { + return false; + } + + if(hit) { + hit->dist = t; + hit->pos = ray.origin + ray.dir * t; + hit->normal = normal; + hit->obj = this; + } + return true; +} diff -r 000000000000 -r 50683c78264e src/mesh.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/mesh.h Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,236 @@ +#ifndef MESH_H_ +#define MESH_H_ + +#include +#include +#include "vmath/vmath.h" +#include "geom.h" + +enum { + MESH_ATTR_VERTEX, + MESH_ATTR_NORMAL, + MESH_ATTR_TANGENT, + MESH_ATTR_TEXCOORD, + MESH_ATTR_COLOR, + MESH_ATTR_BONEWEIGHTS, + MESH_ATTR_BONEIDX, + + NUM_MESH_ATTR +}; + +// intersection mode flags +enum { + ISECT_DEFAULT = 0, // default (whole mesh, all intersections) + ISECT_FRONT = 1, // front-faces only + ISECT_FACE = 2, // return intersected face pointer instead of mesh + ISECT_VERTICES = 4 // return (?) TODO +}; + +//class XFormNode; + + +class Triangle { +public: + Vector3 v[3]; + Vector3 normal; + bool normal_valid; + int id; + + Triangle(); + Triangle(const Vector3 &v0, const Vector3 &v1, const Vector3 &v2); + Triangle(int n, const Vector3 *varr, const unsigned int *idxarr = 0); + + /// calculate normal (quite expensive) + void calc_normal(); + const Vector3 &get_normal() const; + + void transform(const Matrix4x4 &xform); + + void draw() const; + void draw_wire() const; + + /// calculate barycentric coordinates of a point + Vector3 calc_barycentric(const Vector3 &pos) const; + + bool intersect(const Ray &ray, HitPoint *hit = 0) const; +}; + + +class Mesh { +private: + std::string name; + unsigned int nverts, nfaces; + + // current value for each attribute for the immedate mode + // interface. + Vector4 cur_val[NUM_MESH_ATTR]; + + unsigned int buffer_objects[NUM_MESH_ATTR + 1]; + + // vertex attribute data and buffer objects + struct { + int nelem; // number of elements per attribute range: [1, 4] + std::vector data; + unsigned int vbo; + mutable bool vbo_valid; // if this is false, the vbo needs updating from the data + mutable bool data_valid; // if this is false, the data needs to be pulled from the vbo + //int sdr_loc; + } vattr[NUM_MESH_ATTR]; + + static int global_sdr_loc[NUM_MESH_ATTR]; + + //std::vector bones; // bones affecting this mesh + + // index data and buffer object + std::vector idata; + unsigned int ibo; + mutable bool ibo_valid; + mutable bool idata_valid; + + // index buffer object for wireframe rendering (constructed on demand) + unsigned int wire_ibo; + mutable bool wire_ibo_valid; + + // axis-aligned bounding box + mutable AABox aabb; + mutable bool aabb_valid; + + // bounding sphere + mutable Sphere bsph; + mutable bool bsph_valid; + + // keeps the last intersected face + mutable Triangle hitface; + // keeps the last intersected vertex position + mutable Vector3 hitvert; + + void calc_aabb(); + void calc_bsph(); + + static unsigned int intersect_mode; + static float vertex_sel_dist; + + static float vis_vecsize; + + /// update the VBOs after data has changed (invalid vbo/ibo) + void update_buffers(); + /// construct/update the wireframe index buffer (called from draw_wire). + void update_wire_ibo(); + + mutable int cur_sdr; + bool pre_draw() const; + void post_draw() const; + + +public: + static bool use_custom_sdr_attr; + + Mesh(); + ~Mesh(); + + Mesh(const Mesh &rhs); + Mesh &operator =(const Mesh &rhs); + bool clone(const Mesh &m); + + void set_name(const char *name); + const char *get_name() const; + + bool has_attrib(int attr) const; + bool is_indexed() const; + + // clears everything about this mesh, and returns to the newly constructed state + void clear(); + + // access the vertex attribute data + // if vdata == 0, space is just allocated + float *set_attrib_data(int attrib, int nelem, unsigned int num, const float *vdata = 0); // invalidates vbo + float *get_attrib_data(int attrib); // invalidates vbo + const float *get_attrib_data(int attrib) const; + + // simple access to any particular attribute + void set_attrib(int attrib, int idx, const Vector4 &v); // invalidates vbo + Vector4 get_attrib(int attrib, int idx) const; + + int get_attrib_count(int attrib) const; + + // ... same for index data + unsigned int *set_index_data(int num, const unsigned int *indices = 0); // invalidates ibo + unsigned int *get_index_data(); // invalidates ibo + const unsigned int *get_index_data() const; + + int get_index_count() const; + + void append(const Mesh &mesh); + + // immediate-mode style mesh construction interface + void vertex(float x, float y, float z); + void normal(float nx, float ny, float nz); + void tangent(float tx, float ty, float tz); + void texcoord(float u, float v, float w); + void boneweights(float w1, float w2, float w3, float w4); + void boneidx(int idx1, int idx2, int idx3, int idx4); + + int get_poly_count() const; + + /* apply a transformation to the vertices and its inverse-transpose + * to the normals and tangents. + */ + void apply_xform(const Matrix4x4 &xform); + void apply_xform(const Matrix4x4 &xform, const Matrix4x4 &dir_xform); + + void flip(); // both faces and normals + void flip_faces(); + void flip_normals(); + + // adds a bone and returns its index + /*int add_bone(XFormNode *bone); + const XFormNode *get_bone(int idx) const; + int get_bones_count() const;*/ + + // access the shader attribute locations + static void set_attrib_location(int attr, int loc); + static int get_attrib_location(int attr); + static void clear_attrib_locations(); + + static void set_vis_vecsize(float sz); + static float get_vis_vecsize(); + + void draw() const; + void draw_wire() const; + void draw_vertices() const; + void draw_normals() const; + void draw_tangents() const; + + /** get the bounding box in local space. The result will be cached, and subsequent + * calls will return the same box. The cache gets invalidated by any functions that can affect + * the vertex data (non-const variant of get_attrib_data(MESH_ATTR_VERTEX, ...) included). + * @{ */ + void get_aabbox(Vector3 *vmin, Vector3 *vmax) const; + const AABox &get_aabbox() const; + /// @} + + /** get the bounding sphere in local space. The result will be cached, and subsequent + * calls will return the same box. The cache gets invalidated by any functions that can affect + * the vertex data (non-const variant of get_attrib_data(MESH_ATTR_VERTEX, ...) included). + * @{ */ + float get_bsphere(Vector3 *center, float *rad) const; + const Sphere &get_bsphere() const; + + static void set_intersect_mode(unsigned int mode); + static unsigned int get_intersect_mode(); + static void set_vertex_select_distance(float dist); + static float get_vertex_select_distance(); + + /** Find the intersection between the mesh and a ray. + * XXX Brute force at the moment, not intended to be used for anything other than picking in tools. + * If you intend to use it in a speed-critical part of the code, you'll *have* to optimize it! + */ + bool intersect(const Ray &ray, HitPoint *hit = 0) const; + + // texture coordinate manipulation + void texcoord_apply_xform(const Matrix4x4 &xform); + void texcoord_gen_plane(const Vector3 &norm, const Vector3 &tang); + void texcoord_gen_box(); +}; + +#endif // MESH_H_ diff -r 000000000000 -r 50683c78264e src/meshgen.cc --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/meshgen.cc Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,775 @@ +#include +#include "meshgen.h" +#include "mesh.h" + +// -------- sphere -------- + +#define SURAD(u) ((u) * 2.0 * M_PI) +#define SVRAD(v) ((v) * M_PI) + +static Vector3 sphvec(float theta, float phi) +{ + return Vector3(sin(theta) * sin(phi), + cos(phi), + cos(theta) * sin(phi)); +} + +void gen_sphere(Mesh *mesh, float rad, int usub, int vsub, float urange, float vrange) +{ + if(usub < 4) usub = 4; + if(vsub < 2) vsub = 2; + + int uverts = usub + 1; + int vverts = vsub + 1; + + int num_verts = uverts * vverts; + int num_quads = usub * vsub; + int num_tri = num_quads * 2; + + mesh->clear(); + Vector3 *varr = (Vector3*)mesh->set_attrib_data(MESH_ATTR_VERTEX, 3, num_verts, 0); + Vector3 *narr = (Vector3*)mesh->set_attrib_data(MESH_ATTR_NORMAL, 3, num_verts, 0); + Vector3 *tarr = (Vector3*)mesh->set_attrib_data(MESH_ATTR_TANGENT, 3, num_verts, 0); + Vector2 *uvarr = (Vector2*)mesh->set_attrib_data(MESH_ATTR_TEXCOORD, 2, num_verts, 0); + unsigned int *idxarr = mesh->set_index_data(num_tri * 3, 0); + + float du = urange / (float)(uverts - 1); + float dv = vrange / (float)(vverts - 1); + + float u = 0.0; + for(int i=0; iclear(); + Vector3 *varr = (Vector3*)mesh->set_attrib_data(MESH_ATTR_VERTEX, 3, num_verts, 0); + Vector3 *narr = (Vector3*)mesh->set_attrib_data(MESH_ATTR_NORMAL, 3, num_verts, 0); + Vector3 *tarr = (Vector3*)mesh->set_attrib_data(MESH_ATTR_TANGENT, 3, num_verts, 0); + Vector2 *uvarr = (Vector2*)mesh->set_attrib_data(MESH_ATTR_TEXCOORD, 2, num_verts, 0); + unsigned int *idxarr = mesh->set_index_data(num_tri * 3, 0); + + float du = urange / (float)(uverts - 1); + float dv = vrange / (float)(vverts - 1); + + float u = 0.0; + for(int i=0; iclear(); + Vector3 *varr = (Vector3*)mesh->set_attrib_data(MESH_ATTR_VERTEX, 3, num_verts, 0); + Vector3 *narr = (Vector3*)mesh->set_attrib_data(MESH_ATTR_NORMAL, 3, num_verts, 0); + Vector3 *tarr = (Vector3*)mesh->set_attrib_data(MESH_ATTR_TANGENT, 3, num_verts, 0); + Vector2 *uvarr = (Vector2*)mesh->set_attrib_data(MESH_ATTR_TEXCOORD, 2, num_verts, 0); + unsigned int *idxarr = mesh->set_index_data(num_tri * 3, 0); + + float du = urange / (float)(uverts - 1); + float dv = vrange / (float)(vverts - 1); + + float u = 0.0; + for(int i=0; iclear(); + Vector3 *varr = (Vector3*)mesh->set_attrib_data(MESH_ATTR_VERTEX, 3, num_verts, 0); + Vector3 *narr = (Vector3*)mesh->set_attrib_data(MESH_ATTR_NORMAL, 3, num_verts, 0); + Vector3 *tarr = (Vector3*)mesh->set_attrib_data(MESH_ATTR_TANGENT, 3, num_verts, 0); + Vector2 *uvarr = (Vector2*)mesh->set_attrib_data(MESH_ATTR_TEXCOORD, 2, num_verts, 0); + unsigned int *idxarr = mesh->set_index_data(num_tri * 3, 0); + + float du = urange / (float)(uverts - 1); + float dv = vrange / (float)(vverts - 1); + + float u = 0.0; + for(int i=0; iclear(); + + int uverts = usub + 1; + int vverts = vsub + 1; + int num_verts = uverts * vverts; + + int num_quads = usub * vsub; + int num_tri = num_quads * 2; + + Vector3 *varr = (Vector3*)mesh->set_attrib_data(MESH_ATTR_VERTEX, 3, num_verts, 0); + Vector3 *narr = (Vector3*)mesh->set_attrib_data(MESH_ATTR_NORMAL, 3, num_verts, 0); + Vector3 *tarr = (Vector3*)mesh->set_attrib_data(MESH_ATTR_TANGENT, 3, num_verts, 0); + Vector2 *uvarr = (Vector2*)mesh->set_attrib_data(MESH_ATTR_TEXCOORD, 2, num_verts, 0); + unsigned int *idxarr = mesh->set_index_data(num_tri * 3, 0); + + float du = 1.0 / (float)usub; + float dv = 1.0 / (float)vsub; + + float u = 0.0; + for(int i=0; iclear(); + + for(int i=0; i<6; i++) { + Matrix4x4 xform, dir_xform; + Mesh m; + + gen_plane(&m, 1, 1, usub, vsub); + xform.rotate(Vector3(face_angles[i][1], face_angles[i][0], 0)); + dir_xform = xform; + xform.translate(Vector3(0, 0, 0.5)); + m.apply_xform(xform, dir_xform); + + mesh->append(m); + } + + Matrix4x4 scale; + scale.set_scaling(Vector3(xsz, ysz, zsz)); + mesh->apply_xform(scale, Matrix4x4::identity); +} + +/* +void gen_box(Mesh *mesh, float xsz, float ysz, float zsz) +{ + mesh->clear(); + + const int num_faces = 6; + int num_verts = num_faces * 4; + int num_tri = num_faces * 2; + + float x = xsz / 2.0; + float y = ysz / 2.0; + float z = zsz / 2.0; + + Vector3 *varr = (Vector3*)mesh->set_attrib_data(MESH_ATTR_VERTEX, 3, num_verts, 0); + Vector3 *narr = (Vector3*)mesh->set_attrib_data(MESH_ATTR_NORMAL, 3, num_verts, 0); + Vector3 *tarr = (Vector3*)mesh->set_attrib_data(MESH_ATTR_TANGENT, 3, num_verts, 0); + Vector2 *uvarr = (Vector2*)mesh->set_attrib_data(MESH_ATTR_TEXCOORD, 2, num_verts, 0); + unsigned int *idxarr = mesh->set_index_data(num_tri * 3, 0); + + static const Vector2 uv[] = { Vector2(0, 0), Vector2(1, 0), Vector2(1, 1), Vector2(0, 1) }; + + // front + for(int i=0; i<4; i++) { + *narr++ = Vector3(0, 0, 1); + *tarr++ = Vector3(1, 0, 0); + *uvarr++ = uv[i]; + } + *varr++ = Vector3(-x, -y, z); + *varr++ = Vector3(x, -y, z); + *varr++ = Vector3(x, y, z); + *varr++ = Vector3(-x, y, z); + // right + for(int i=0; i<4; i++) { + *narr++ = Vector3(1, 0, 0); + *tarr++ = Vector3(0, 0, -1); + *uvarr++ = uv[i]; + } + *varr++ = Vector3(x, -y, z); + *varr++ = Vector3(x, -y, -z); + *varr++ = Vector3(x, y, -z); + *varr++ = Vector3(x, y, z); + // back + for(int i=0; i<4; i++) { + *narr++ = Vector3(0, 0, -1); + *tarr++ = Vector3(-1, 0, 0); + *uvarr++ = uv[i]; + } + *varr++ = Vector3(x, -y, -z); + *varr++ = Vector3(-x, -y, -z); + *varr++ = Vector3(-x, y, -z); + *varr++ = Vector3(x, y, -z); + // left + for(int i=0; i<4; i++) { + *narr++ = Vector3(-1, 0, 0); + *tarr++ = Vector3(0, 0, 1); + *uvarr++ = uv[i]; + } + *varr++ = Vector3(-x, -y, -z); + *varr++ = Vector3(-x, -y, z); + *varr++ = Vector3(-x, y, z); + *varr++ = Vector3(-x, y, -z); + // top + for(int i=0; i<4; i++) { + *narr++ = Vector3(0, 1, 0); + *tarr++ = Vector3(1, 0, 0); + *uvarr++ = uv[i]; + } + *varr++ = Vector3(-x, y, z); + *varr++ = Vector3(x, y, z); + *varr++ = Vector3(x, y, -z); + *varr++ = Vector3(-x, y, -z); + // bottom + for(int i=0; i<4; i++) { + *narr++ = Vector3(0, -1, 0); + *tarr++ = Vector3(1, 0, 0); + *uvarr++ = uv[i]; + } + *varr++ = Vector3(-x, -y, -z); + *varr++ = Vector3(x, -y, -z); + *varr++ = Vector3(x, -y, z); + *varr++ = Vector3(-x, -y, z); + + // index array + static const int faceidx[] = {0, 1, 2, 0, 2, 3}; + for(int i=0; iclear(); + + int uverts = usub + 1; + int vverts = vsub + 1; + int num_verts = uverts * vverts; + + int num_quads = usub * vsub; + int num_tri = num_quads * 2; + + Vector3 *varr = (Vector3*)mesh->set_attrib_data(MESH_ATTR_VERTEX, 3, num_verts, 0); + Vector3 *narr = (Vector3*)mesh->set_attrib_data(MESH_ATTR_NORMAL, 3, num_verts, 0); + Vector3 *tarr = (Vector3*)mesh->set_attrib_data(MESH_ATTR_TANGENT, 3, num_verts, 0); + Vector2 *uvarr = (Vector2*)mesh->set_attrib_data(MESH_ATTR_TEXCOORD, 2, num_verts, 0); + unsigned int *idxarr = mesh->set_index_data(num_tri * 3, 0); + + float du = 1.0 / (float)(uverts - 1); + float dv = 1.0 / (float)(vverts - 1); + + float u = 0.0; + for(int i=0; i 0.5 ? v - dv * 0.25 : v + dv * 0.25; + nextu = rev_vert(fmod(u + du, 1.0), new_v, rfunc, cls); + tang = nextu - pos; + } + + Vector3 normal; + if(nfunc) { + normal = rev_vert(u, v, nfunc, cls); + } else { + Vector3 nextv = rev_vert(u, v + dv, rfunc, cls); + Vector3 bitan = nextv - pos; + if(bitan.length_sq() < 1e-6) { + nextv = rev_vert(u, v - dv, rfunc, cls); + bitan = pos - nextv; + } + + normal = cross_product(tang, bitan); + } + + *varr++ = pos; + *narr++ = normal.normalized(); + *tarr++ = tang.normalized(); + *uvarr++ = Vector2(u, v); + + if(i < usub && j < vsub) { + int idx = i * vverts + j; + + *idxarr++ = idx; + *idxarr++ = idx + vverts + 1; + *idxarr++ = idx + 1; + + *idxarr++ = idx; + *idxarr++ = idx + vverts; + *idxarr++ = idx + vverts + 1; + } + + v += dv; + } + u += du; + } +} + + +static inline Vector3 sweep_vert(float u, float v, float height, Vector2 (*sf)(float, float, void*), void *cls) +{ + Vector2 pos = sf(u, v, cls); + + float x = pos.x; + float y = v * height; + float z = pos.y; + + return Vector3(x, y, z); +} + +// ---- sweep shape along a path ---- +void gen_sweep(Mesh *mesh, float height, int usub, int vsub, Vector2 (*sfunc)(float, float, void*), void *cls) +{ + if(!sfunc) return; + if(usub < 3) usub = 3; + if(vsub < 1) vsub = 1; + + mesh->clear(); + + int uverts = usub + 1; + int vverts = vsub + 1; + int num_verts = uverts * vverts; + + int num_quads = usub * vsub; + int num_tri = num_quads * 2; + + Vector3 *varr = (Vector3*)mesh->set_attrib_data(MESH_ATTR_VERTEX, 3, num_verts, 0); + Vector3 *narr = (Vector3*)mesh->set_attrib_data(MESH_ATTR_NORMAL, 3, num_verts, 0); + Vector3 *tarr = (Vector3*)mesh->set_attrib_data(MESH_ATTR_TANGENT, 3, num_verts, 0); + Vector2 *uvarr = (Vector2*)mesh->set_attrib_data(MESH_ATTR_TEXCOORD, 2, num_verts, 0); + unsigned int *idxarr = mesh->set_index_data(num_tri * 3, 0); + + float du = 1.0 / (float)(uverts - 1); + float dv = 1.0 / (float)(vverts - 1); + + float u = 0.0; + for(int i=0; i 0.5 ? v - dv * 0.25 : v + dv * 0.25; + nextu = sweep_vert(fmod(u + du, 1.0), new_v, height, sfunc, cls); + tang = nextu - pos; + } + + Vector3 normal; + Vector3 nextv = sweep_vert(u, v + dv, height, sfunc, cls); + Vector3 bitan = nextv - pos; + if(bitan.length_sq() < 1e-6) { + nextv = sweep_vert(u, v - dv, height, sfunc, cls); + bitan = pos - nextv; + } + + normal = cross_product(tang, bitan); + + *varr++ = pos; + *narr++ = normal.normalized(); + *tarr++ = tang.normalized(); + *uvarr++ = Vector2(u, v); + + if(i < usub && j < vsub) { + int idx = i * vverts + j; + + *idxarr++ = idx; + *idxarr++ = idx + vverts + 1; + *idxarr++ = idx + 1; + + *idxarr++ = idx; + *idxarr++ = idx + vverts; + *idxarr++ = idx + vverts + 1; + } + + v += dv; + } + u += du; + } +} diff -r 000000000000 -r 50683c78264e src/meshgen.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/meshgen.h Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,22 @@ +#ifndef MESHGEN_H_ +#define MESHGEN_H_ + +#include "vmath/vmath.h" + +class Mesh; + +void gen_sphere(Mesh *mesh, float rad, int usub, int vsub, float urange = 1.0, float vrange = 1.0); +void gen_torus(Mesh *mesh, float mainrad, float ringrad, int usub, int vsub, float urange = 1.0, float vrange = 1.0); +void gen_cylinder(Mesh *mesh, float rad, float height, int usub, int vsub, int capsub = 0, float urange = 1.0, float vrange = 1.0); +void gen_cone(Mesh *mesh, float rad, float height, int usub, int vsub, int capsub = 0, float urange = 1.0, float vrange = 1.0); +void gen_plane(Mesh *mesh, float width, float height, int usub = 1, int vsub = 1); +void gen_heightmap(Mesh *mesh, float width, float height, int usub, int vsub, float (*hf)(float, float, void*), void *hfdata = 0); +void gen_box(Mesh *mesh, float xsz, float ysz, float zsz, int usub = 1, int vsub = 1); + +void gen_revol(Mesh *mesh, int usub, int vsub, Vector2 (*rfunc)(float, float, void*), void *cls = 0); +void gen_revol(Mesh *mesh, int usub, int vsub, Vector2 (*rfunc)(float, float, void*), Vector2 (*nfunc)(float, float, void*), void *cls); + +/* callback args: (float u, float v, void *cls) -> Vector2 XZ offset u,v in [0, 1] */ +void gen_sweep(Mesh *mesh, float height, int usub, int vsub, Vector2 (*sfunc)(float, float, void*), void *cls = 0); + +#endif // MESHGEN_H_ diff -r 000000000000 -r 50683c78264e src/object.cc --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/object.cc Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,226 @@ +#include "object.h" +#include "opengl.h" +#include "sdr.h" + +Material::Material() + : diffuse(1, 1, 1), specular(0, 0, 0) +{ + shininess = 60.0; + alpha = 1.0; +} + +RenderOps::RenderOps() +{ + zwrite = true; + cast_shadows = true; + transparent = false; +} + +void RenderOps::setup() const +{ + if(!zwrite) { + glDepthMask(0); + } + if(transparent) { + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + } else { + glDisable(GL_BLEND); + } +} + +Object::Object() +{ + mesh = 0; + tex = 0; + sdr = 0; +} + +Object::~Object() +{ + delete mesh; +} + +Matrix4x4 &Object::xform() +{ + return matrix; +} + +const Matrix4x4 &Object::xform() const +{ + return matrix; +} + +Matrix4x4 &Object::tex_xform() +{ + return tex_matrix; +} + +const Matrix4x4 &Object::tex_xform() const +{ + return tex_matrix; +} + +void Object::set_mesh(Mesh *m) +{ + this->mesh = m; +} + +Mesh *Object::get_mesh() const +{ + return mesh; +} + +void Object::set_texture(unsigned int tex) +{ + this->tex = tex; +} + +unsigned int Object::get_texture() const +{ + return tex; +} + +void Object::set_shader(unsigned int sdr) +{ + if(GLEW_ARB_vertex_shader && GLEW_ARB_fragment_shader) { + this->sdr = sdr; + } +} + +unsigned int Object::get_shader() const +{ + return sdr; +} + +void Object::draw() const +{ + if(!mesh) return; + + /* + if(shadow_pass && !rop.cast_shadows) { + return; + } + */ + + glPushAttrib(GL_ENABLE_BIT | GL_DEPTH_BUFFER_BIT); + rop.setup(); + + glUseProgram(sdr); + + if(tex) { + glBindTexture(GL_TEXTURE_2D, tex); + glEnable(GL_TEXTURE_2D); + + glMatrixMode(GL_TEXTURE); + glPushMatrix(); + glLoadTransposeMatrixf(tex_matrix[0]); + } else { + glDisable(GL_TEXTURE_2D); + } + + glMatrixMode(GL_MODELVIEW); + glPushMatrix(); + glMultTransposeMatrixf(matrix[0]); + + if(sdr) { + set_uniform_matrix4_transposed(sdr, "world_matrix", (float*)matrix[0]); + } + + float dcol[] = {mtl.diffuse.x, mtl.diffuse.y, mtl.diffuse.z, mtl.alpha}; + glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, dcol); + float scol[] = {mtl.specular.x, mtl.specular.y, mtl.specular.z, 1.0f}; + glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, scol); + glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, mtl.shininess); + + mesh->draw(); + + if(tex) { + glDisable(GL_TEXTURE_2D); + + glMatrixMode(GL_TEXTURE); + glPopMatrix(); + } + + if(sdr) { + glUseProgram(0); + } + + glMatrixMode(GL_MODELVIEW); + glPopMatrix(); + + glPopAttrib(); +} + +void Object::draw_wire(const Vector4 &col) const +{ + glPushAttrib(GL_ENABLE_BIT); + glDisable(GL_LIGHTING); + glUseProgram(0); + + glMatrixMode(GL_MODELVIEW); + glPushMatrix(); + glMultTransposeMatrixf(matrix[0]); + + glColor4f(col.x, col.y, col.z, col.w); + mesh->draw_wire(); + + glPopMatrix(); + glPopAttrib(); +} + +void Object::draw_vertices(const Vector4 &col) const +{ + glPushAttrib(GL_ENABLE_BIT); + glDisable(GL_LIGHTING); + glUseProgram(0); + + glMatrixMode(GL_MODELVIEW); + glPushMatrix(); + glMultTransposeMatrixf(matrix[0]); + + glColor4f(col.x, col.y, col.z, col.w); + mesh->draw_vertices(); + + glPopMatrix(); + glPopAttrib(); +} + +void Object::draw_normals(float len, const Vector4 &col) const +{ + glPushAttrib(GL_ENABLE_BIT); + glDisable(GL_LIGHTING); + + glMatrixMode(GL_MODELVIEW); + glPushMatrix(); + glMultTransposeMatrixf(matrix[0]); + + glColor4f(col.x, col.y, col.z, col.w); + mesh->set_vis_vecsize(len); + mesh->draw_normals(); + + glPopMatrix(); + glPopAttrib(); +} + +void Object::draw_tangents(float len, const Vector4 &col) const +{ + glPushAttrib(GL_ENABLE_BIT); + glDisable(GL_LIGHTING); + + glMatrixMode(GL_MODELVIEW); + glPushMatrix(); + glMultTransposeMatrixf(matrix[0]); + + glColor4f(col.x, col.y, col.z, col.w); + mesh->set_vis_vecsize(len); + mesh->draw_tangents(); + + glPopMatrix(); + glPopAttrib(); +} + +bool Object::intersect(const Ray &ray, HitPoint *hit) const +{ + return false; // TODO +} diff -r 000000000000 -r 50683c78264e src/object.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/object.h Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,64 @@ +#ifndef OBJECT_H_ +#define OBJECT_H_ + +#include "mesh.h" +#include "geom.h" +#include "vmath/vmath.h" + +struct Material { + Vector3 diffuse; + Vector3 specular; + float shininess; + float alpha; + + Material(); +}; + +struct RenderOps { + bool zwrite; + bool cast_shadows; + bool transparent; + + RenderOps(); + void setup() const; +}; + +class Object { +private: + Mesh *mesh; + Matrix4x4 matrix; + unsigned int tex; + Matrix4x4 tex_matrix; + unsigned int sdr; + +public: + Material mtl; + RenderOps rop; + + Object(); + ~Object(); + + Matrix4x4 &xform(); + const Matrix4x4 &xform() const; + + Matrix4x4 &tex_xform(); + const Matrix4x4 &tex_xform() const; + + void set_mesh(Mesh *m); + Mesh *get_mesh() const; + + void set_texture(unsigned int tex); + unsigned int get_texture() const; + void set_shader(unsigned int sdr); + unsigned int get_shader() const; + + void draw() const; + void draw_wire(const Vector4 &col = Vector4(1, 1, 1, 1)) const; + void draw_vertices(const Vector4 &col = Vector4(1, 0.3, 0.2, 1)) const; + void draw_normals(float len = 1.0, const Vector4 &col = Vector4(0.1, 0.2, 1.0, 1)) const; + void draw_tangents(float len = 1.0, const Vector4 &col = Vector4(0.1, 1.0, 0.2, 1)) const; + + bool intersect(const Ray &ray, HitPoint *hit) const; +}; + +#endif // OBJECT_H_ diff -r 000000000000 -r 50683c78264e src/opengl.c --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/opengl.c Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,16 @@ +#include "opengl.h" + +struct GLCaps glcaps; + +int init_opengl() +{ + glewInit(); + + glcaps.shaders = GLEW_ARB_vertex_shader && GLEW_ARB_fragment_shader; + glcaps.fsaa = GLEW_ARB_multisample; + glcaps.sep_spec = GLEW_EXT_separate_specular_color; + glcaps.fbo = GLEW_ARB_framebuffer_object; + glcaps.shadow = GLEW_ARB_shadow | GLEW_SGIX_shadow; + + return 0; +} diff -r 000000000000 -r 50683c78264e src/opengl.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/opengl.h Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,25 @@ +#ifndef OPENGL_H_ +#define OPENGL_H_ + +#include + +struct GLCaps { + int shaders; + int fsaa; + int sep_spec; + int fbo; + int shadow; +}; +extern struct GLCaps glcaps; + +#ifdef __cplusplus +extern "C" { +#endif + +int init_opengl(); + +#ifdef __cplusplus +} +#endif + +#endif /* OPENGL_H_ */ diff -r 000000000000 -r 50683c78264e src/opt.cc --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/opt.cc Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,17 @@ +#include +#include "opt.h" + +Options opt; + +bool init_options(int argc, char **argv) +{ + // TODO read config files, parse args, etc... + + opt.xres = 1280; + opt.yres = 800; + opt.fullscreen = false; + opt.shadows = true; + opt.reflections = true; + + return true; +} diff -r 000000000000 -r 50683c78264e src/opt.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/opt.h Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,16 @@ +#ifndef OPT_H_ +#define OPT_H_ + +#include "vmath/vmath.h" + +struct Options { + int xres, yres; + bool fullscreen; + bool shadows, reflections; +}; + +extern Options opt; + +bool init_options(int argc, char **argv); + +#endif /* OPT_H_ */ diff -r 000000000000 -r 50683c78264e src/pnoise.cc --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/pnoise.cc Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,166 @@ +#include +#include "pnoise.h" +#include "vmath/vmath.h" + +#define B 0x100 +#define BM 0xff +#define N 0x1000 +#define NP 12 +#define NM 0xfff + +#define s_curve(t) ((t) * (t) * (3.0f - 2.0f * (t))) +#define setup(elem, b0, b1, r0, r1) \ + do { \ + scalar_t t = elem + N; \ + b0 = ((int)t) & BM; \ + b1 = (b0 + 1) & BM; \ + r0 = t - (int)t; \ + r1 = r0 - 1.0f; \ + } while(0) + +#define setup_p(elem, b0, b1, r0, r1, p) \ + do { \ + scalar_t t = elem + N; \ + b0 = (((int)t) & BM) % p; \ + b1 = ((b0 + 1) & BM) % p; \ + r0 = t - (int)t; \ + r1 = r0 - 1.0f; \ + } while(0) + +static int perm[B + B + 2]; +static vec2_t grad2[B + B + 2]; +static bool tables_valid; + +static void init_noise() +{ + for(int i=0; i +#include +#include "rng.h" + +//#define USE_STD_RAND + +// defined at the end +/** + * tinymt32 internal state vector and parameters + */ +struct tinymt32_t { + uint32_t status[4]; + uint32_t mat1; + uint32_t mat2; + uint32_t tmat; +}; + +#ifndef USE_STD_RAND +static void tinymt32_init(tinymt32_t * random, uint32_t seed); +inline static uint32_t tinymt32_generate_uint32(tinymt32_t * random); +inline static float tinymt32_generate_float(tinymt32_t * random); +#endif + +static RandGen defrng; + +struct RandGenState { + tinymt32_t st; +}; + +RandGen::RandGen() +{ + state = new RandGenState; + memset(state, 0, sizeof *state); +#ifndef USE_STD_RAND + tinymt32_init(&state->st, 0); +#endif +} + +RandGen::~RandGen() +{ + delete state; +} + +void RandGen::seed(uint32_t s) +{ +#ifndef USE_STD_RAND + tinymt32_init(&state->st, s); +#else + srand(s); +#endif +} + +uint32_t RandGen::generate() +{ +#ifndef USE_STD_RAND + return tinymt32_generate_uint32(&state->st); +#else + return rand(); +#endif +} + +float RandGen::generate_float() +{ +#ifndef USE_STD_RAND + return tinymt32_generate_float(&state->st); +#else + return (float)rand() / (float)RAND_MAX; +#endif +} + +void rng_srand(uint32_t s) +{ + defrng.seed(s); +} + +uint32_t rng_rand() +{ + return defrng.generate(); +} + +float rng_frand() +{ + return defrng.generate_float(); +} + + +#ifndef USE_STD_RAND +/** + * @file tinymt32.h + * + * @brief Tiny Mersenne Twister only 127 bit internal state + * + * @author Mutsuo Saito (Hiroshima University) + * @author Makoto Matsumoto (University of Tokyo) + * + * Copyright (C) 2011 Mutsuo Saito, Makoto Matsumoto, + * Hiroshima University and The University of Tokyo. + * All rights reserved. + * + * The 3-clause BSD License is applied to this software, see + * LICENSE.txt + */ +#define TINYMT32_MEXP 127 +#define TINYMT32_SH0 1 +#define TINYMT32_SH1 10 +#define TINYMT32_SH8 8 +#define TINYMT32_MASK UINT32_C(0x7fffffff) +#define TINYMT32_MUL (1.0f / 4294967296.0f) + +/** + * This function changes internal state of tinymt32. + * Users should not call this function directly. + * @param random tinymt internal status + */ +inline static void tinymt32_next_state(tinymt32_t * random) { + uint32_t x; + uint32_t y; + + y = random->status[3]; + x = (random->status[0] & TINYMT32_MASK) + ^ random->status[1] + ^ random->status[2]; + x ^= (x << TINYMT32_SH0); + y ^= (y >> TINYMT32_SH0) ^ x; + random->status[0] = random->status[1]; + random->status[1] = random->status[2]; + random->status[2] = x ^ (y << TINYMT32_SH1); + random->status[3] = y; + random->status[1] ^= -((int32_t)(y & 1)) & random->mat1; + random->status[2] ^= -((int32_t)(y & 1)) & random->mat2; +} + +/** + * This function outputs 32-bit unsigned integer from internal state. + * Users should not call this function directly. + * @param random tinymt internal status + * @return 32-bit unsigned pseudorandom number + */ +inline static uint32_t tinymt32_temper(tinymt32_t * random) { + uint32_t t0, t1; + t0 = random->status[3]; +#if defined(LINEARITY_CHECK) + t1 = random->status[0] + ^ (random->status[2] >> TINYMT32_SH8); +#else + t1 = random->status[0] + + (random->status[2] >> TINYMT32_SH8); +#endif + t0 ^= t1; + t0 ^= -((int32_t)(t1 & 1)) & random->tmat; + return t0; +} + +/** + * This function outputs 32-bit unsigned integer from internal state. + * @param random tinymt internal status + * @return 32-bit unsigned integer r (0 <= r < 2^32) + */ +inline static uint32_t tinymt32_generate_uint32(tinymt32_t * random) { + tinymt32_next_state(random); + return tinymt32_temper(random); +} + +/** + * This function outputs floating point number from internal state. + * This function is implemented using multiplying by 1 / 2^32. + * floating point multiplication is faster than using union trick in + * my Intel CPU. + * @param random tinymt internal status + * @return floating point number r (0.0 <= r < 1.0) + */ +inline static float tinymt32_generate_float(tinymt32_t * random) { + tinymt32_next_state(random); + return tinymt32_temper(random) * TINYMT32_MUL; +} + +#define MIN_LOOP 8 +#define PRE_LOOP 8 + +/** + * This function certificate the period of 2^127-1. + * @param random tinymt state vector. + */ +static void period_certification(tinymt32_t * random) { + if ((random->status[0] & TINYMT32_MASK) == 0 && + random->status[1] == 0 && + random->status[2] == 0 && + random->status[3] == 0) { + random->status[0] = 'T'; + random->status[1] = 'I'; + random->status[2] = 'N'; + random->status[3] = 'Y'; + } +} + +/** + * This function initializes the internal state array with a 32-bit + * unsigned integer seed. + * @param random tinymt state vector. + * @param seed a 32-bit unsigned integer used as a seed. + */ +static void tinymt32_init(tinymt32_t * random, uint32_t seed) { + random->status[0] = seed; + random->status[1] = random->mat1; + random->status[2] = random->mat2; + random->status[3] = random->tmat; + for (int i = 1; i < MIN_LOOP; i++) { + random->status[i & 3] ^= i + UINT32_C(1812433253) + * (random->status[(i - 1) & 3] + ^ (random->status[(i - 1) & 3] >> 30)); + } + period_certification(random); + for (int i = 0; i < PRE_LOOP; i++) { + tinymt32_next_state(random); + } +} +#endif // !defined(USE_STD_RAND) diff -r 000000000000 -r 50683c78264e src/rng.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/rng.h Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,30 @@ +#ifndef RNG_H_ +#define RNG_H_ + +#include + +struct RandGenState; + +class RandGen { +private: + RandGenState *state; + + RandGen(const RandGen&); + RandGen &operator =(const RandGen&); + +public: + RandGen(); + ~RandGen(); + + void seed(uint32_t s); + + uint32_t generate(); + float generate_float(); +}; + +void rng_srand(uint32_t s); +uint32_t rng_rand(); +float rng_frand(); + + +#endif // RNG_H_ diff -r 000000000000 -r 50683c78264e src/scene.cc --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/scene.cc Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,63 @@ +#include "scene.h" +#include "opengl.h" +#include "opt.h" + +extern bool wireframe; +static int max_lights = -1; + +Scene::~Scene() +{ + clear(); +} + +void Scene::clear() +{ + for(size_t i=0; isetup(i); + } else { + glDisable(GL_LIGHT0 + i); + } + } + + for(size_t i=0; irop.transparent ? DRAW_TRANSPARENT : DRAW_SOLID; + if(mask & flags) { + if(wireframe) { + objects[i]->draw_wire(); + } else { + objects[i]->draw(); + } + } + } +} diff -r 000000000000 -r 50683c78264e src/scene.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/scene.h Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,29 @@ +#ifndef SCENE_H_ +#define SCENE_H_ + +#include +#include "object.h" +#include "light.h" + +enum { + DRAW_SOLID = 1, + DRAW_TRANSPARENT = 2, + DRAW_ALL = 0x7fffffff +}; + +class Scene { +public: + std::vector objects; + std::vector lights; + + ~Scene(); + + void clear(); + + void add_object(Object *obj); + void add_light(Light *lt); + + void draw(unsigned int flags = DRAW_ALL) const; +}; + +#endif // SCENE_H_ diff -r 000000000000 -r 50683c78264e src/sdr.c --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/sdr.c Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,407 @@ +#include +#include +#include +#include +#include +#include +#include "opengl.h" + +#if defined(unix) || defined(__unix__) +#include +#include +#endif /* unix */ + +#include "sdr.h" + +static const char *sdrtypestr(unsigned int sdrtype); + +unsigned int create_vertex_shader(const char *src) +{ + return create_shader(src, GL_VERTEX_SHADER); +} + +unsigned int create_pixel_shader(const char *src) +{ + return create_shader(src, GL_FRAGMENT_SHADER); +} + +unsigned int create_tessctl_shader(const char *src) +{ +#ifdef GL_TESS_CONTROL_SHADER + return create_shader(src, GL_TESS_CONTROL_SHADER); +#else + return 0; +#endif +} + +unsigned int create_tesseval_shader(const char *src) +{ +#ifdef GL_TESS_EVALUATION_SHADER + return create_shader(src, GL_TESS_EVALUATION_SHADER); +#else + return 0; +#endif +} + +unsigned int create_geometry_shader(const char *src) +{ +#ifdef GL_GEOMETRY_SHADER + return create_shader(src, GL_GEOMETRY_SHADER); +#else + return 0; +#endif +} + +unsigned int create_shader(const char *src, unsigned int sdr_type) +{ + unsigned int sdr; + int success, info_len; + char *info_str = 0; + GLenum err; + + sdr = glCreateShader(sdr_type); + assert(glGetError() == GL_NO_ERROR); + glShaderSource(sdr, 1, &src, 0); + err = glGetError(); + assert(err == GL_NO_ERROR); + glCompileShader(sdr); + assert(glGetError() == GL_NO_ERROR); + + glGetShaderiv(sdr, GL_COMPILE_STATUS, &success); + assert(glGetError() == GL_NO_ERROR); + glGetShaderiv(sdr, GL_INFO_LOG_LENGTH, &info_len); + assert(glGetError() == GL_NO_ERROR); + + if(info_len) { + if((info_str = malloc(info_len + 1))) { + glGetShaderInfoLog(sdr, info_len, 0, info_str); + assert(glGetError() == GL_NO_ERROR); + info_str[info_len] = 0; + } + } + + if(success) { + fprintf(stderr, info_str ? "done: %s\n" : "done\n", info_str); + } else { + fprintf(stderr, info_str ? "failed: %s\n" : "failed\n", info_str); + glDeleteShader(sdr); + sdr = 0; + } + + free(info_str); + return sdr; +} + +void free_shader(unsigned int sdr) +{ + glDeleteShader(sdr); +} + +unsigned int load_vertex_shader(const char *fname) +{ + return load_shader(fname, GL_VERTEX_SHADER); +} + +unsigned int load_pixel_shader(const char *fname) +{ + return load_shader(fname, GL_FRAGMENT_SHADER); +} + +unsigned int load_tessctl_shader(const char *fname) +{ +#ifdef GL_TESS_CONTROL_SHADER + return load_shader(fname, GL_TESS_CONTROL_SHADER); +#else + return 0; +#endif +} + +unsigned int load_tesseval_shader(const char *fname) +{ +#ifdef GL_TESS_EVALUATION_SHADER + return load_shader(fname, GL_TESS_EVALUATION_SHADER); +#else + return 0; +#endif +} + +unsigned int load_geometry_shader(const char *fname) +{ +#ifdef GL_GEOMETRY_SHADER + return load_shader(fname, GL_GEOMETRY_SHADER); +#else + return 0; +#endif +} + +unsigned int load_shader(const char *fname, unsigned int sdr_type) +{ + unsigned int sdr; + size_t filesize; + FILE *fp; + char *src; + + if(!(fp = fopen(fname, "rb"))) { + fprintf(stderr, "failed to open shader %s: %s\n", fname, strerror(errno)); + return 0; + } + + fseek(fp, 0, SEEK_END); + filesize = ftell(fp); + fseek(fp, 0, SEEK_SET); + + if(!(src = malloc(filesize + 1))) { + fclose(fp); + return 0; + } + fread(src, 1, filesize, fp); + src[filesize] = 0; + fclose(fp); + + fprintf(stderr, "compiling %s shader: %s... ", sdrtypestr(sdr_type), fname); + sdr = create_shader(src, sdr_type); + + free(src); + return sdr; +} + + +/* ---- gpu programs ---- */ + +unsigned int create_program(void) +{ + unsigned int prog = glCreateProgram(); + assert(glGetError() == GL_NO_ERROR); + return prog; +} + +unsigned int create_program_link(unsigned int sdr0, ...) +{ + unsigned int prog, sdr; + va_list ap; + + if(!(prog = create_program())) { + return 0; + } + + attach_shader(prog, sdr0); + if(glGetError()) { + return 0; + } + + va_start(ap, sdr0); + while((sdr = va_arg(ap, unsigned int))) { + attach_shader(prog, sdr); + if(glGetError()) { + return 0; + } + } + va_end(ap); + + if(link_program(prog) == -1) { + free_program(prog); + return 0; + } + return prog; +} + +unsigned int create_program_load(const char *vfile, const char *pfile) +{ + unsigned int vs = 0, ps = 0; + + if(vfile && *vfile && !(vs = load_vertex_shader(vfile))) { + return 0; + } + if(pfile && *pfile && !(ps = load_pixel_shader(pfile))) { + return 0; + } + return create_program_link(vs, ps, 0); +} + +void free_program(unsigned int sdr) +{ + glDeleteProgram(sdr); +} + +void attach_shader(unsigned int prog, unsigned int sdr) +{ + int err; + + if(prog && sdr) { + assert(glGetError() == GL_NO_ERROR); + glAttachShader(prog, sdr); + if((err = glGetError()) != GL_NO_ERROR) { + fprintf(stderr, "failed to attach shader %u to program %u (err: 0x%x)\n", sdr, prog, err); + abort(); + } + } +} + +int link_program(unsigned int prog) +{ + int linked, info_len, retval = 0; + char *info_str = 0; + + glLinkProgram(prog); + assert(glGetError() == GL_NO_ERROR); + glGetProgramiv(prog, GL_LINK_STATUS, &linked); + assert(glGetError() == GL_NO_ERROR); + glGetProgramiv(prog, GL_INFO_LOG_LENGTH, &info_len); + assert(glGetError() == GL_NO_ERROR); + + if(info_len) { + if((info_str = malloc(info_len + 1))) { + glGetProgramInfoLog(prog, info_len, 0, info_str); + assert(glGetError() == GL_NO_ERROR); + info_str[info_len] = 0; + } + } + + if(linked) { + fprintf(stderr, info_str ? "linking done: %s\n" : "linking done\n", info_str); + } else { + fprintf(stderr, info_str ? "linking failed: %s\n" : "linking failed\n", info_str); + retval = -1; + } + + free(info_str); + return retval; +} + +int bind_program(unsigned int prog) +{ + GLenum err; + + glUseProgram(prog); + if(prog && (err = glGetError()) != GL_NO_ERROR) { + /* maybe the program is not linked, try linking first */ + if(err == GL_INVALID_OPERATION) { + if(link_program(prog) == -1) { + return -1; + } + glUseProgram(prog); + return glGetError() == GL_NO_ERROR ? 0 : -1; + } + return -1; + } + return 0; +} + +/* ugly but I'm not going to write the same bloody code over and over */ +#define BEGIN_UNIFORM_CODE \ + int loc, curr_prog; \ + glGetIntegerv(GL_CURRENT_PROGRAM, &curr_prog); \ + if((unsigned int)curr_prog != prog && bind_program(prog) == -1) { \ + return -1; \ + } \ + if((loc = glGetUniformLocation(prog, name)) != -1) + +#define END_UNIFORM_CODE \ + if((unsigned int)curr_prog != prog) { \ + bind_program(curr_prog); \ + } \ + return loc == -1 ? -1 : 0 + +int set_uniform_int(unsigned int prog, const char *name, int val) +{ + BEGIN_UNIFORM_CODE { + glUniform1i(loc, val); + } + END_UNIFORM_CODE; +} + +int set_uniform_float(unsigned int prog, const char *name, float val) +{ + BEGIN_UNIFORM_CODE { + glUniform1f(loc, val); + } + END_UNIFORM_CODE; +} + +int set_uniform_float2(unsigned int prog, const char *name, float x, float y) +{ + BEGIN_UNIFORM_CODE { + glUniform2f(loc, x, y); + } + END_UNIFORM_CODE; +} + +int set_uniform_float3(unsigned int prog, const char *name, float x, float y, float z) +{ + BEGIN_UNIFORM_CODE { + glUniform3f(loc, x, y, z); + } + END_UNIFORM_CODE; +} + +int set_uniform_float4(unsigned int prog, const char *name, float x, float y, float z, float w) +{ + BEGIN_UNIFORM_CODE { + glUniform4f(loc, x, y, z, w); + } + END_UNIFORM_CODE; +} + +int set_uniform_matrix4(unsigned int prog, const char *name, float *mat) +{ + BEGIN_UNIFORM_CODE { + glUniformMatrix4fv(loc, 1, GL_FALSE, mat); + } + END_UNIFORM_CODE; +} + +int set_uniform_matrix4_transposed(unsigned int prog, const char *name, float *mat) +{ + BEGIN_UNIFORM_CODE { + glUniformMatrix4fv(loc, 1, GL_TRUE, mat); + } + END_UNIFORM_CODE; +} + +int get_attrib_loc(unsigned int prog, const char *name) +{ + int loc, curr_prog; + + glGetIntegerv(GL_CURRENT_PROGRAM, &curr_prog); + if((unsigned int)curr_prog != prog && bind_program(prog) == -1) { + return -1; + } + + loc = glGetAttribLocation(prog, (char*)name); + + if((unsigned int)curr_prog != prog) { + bind_program(curr_prog); + } + return loc; +} + +void set_attrib_float3(int attr_loc, float x, float y, float z) +{ + glVertexAttrib3f(attr_loc, x, y, z); +} + +static const char *sdrtypestr(unsigned int sdrtype) +{ + switch(sdrtype) { + case GL_VERTEX_SHADER: + return "vertex"; + case GL_FRAGMENT_SHADER: + return "pixel"; +#ifdef GL_TESS_CONTROL_SHADER + case GL_TESS_CONTROL_SHADER: + return "tessellation control"; +#endif +#ifdef GL_TESS_EVALUATION_SHADER + case GL_TESS_EVALUATION_SHADER: + return "tessellation evaluation"; +#endif +#ifdef GL_GEOMETRY_SHADER + case GL_GEOMETRY_SHADER: + return "geometry"; +#endif + + default: + break; + } + return ""; +} diff -r 000000000000 -r 50683c78264e src/sdr.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/sdr.h Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,52 @@ +#ifndef SDR_H_ +#define SDR_H_ + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/* ---- shaders ---- */ +unsigned int create_vertex_shader(const char *src); +unsigned int create_pixel_shader(const char *src); +unsigned int create_tessctl_shader(const char *src); +unsigned int create_tesseval_shader(const char *src); +unsigned int create_geometry_shader(const char *src); +unsigned int create_shader(const char *src, unsigned int sdr_type); +void free_shader(unsigned int sdr); + +unsigned int load_vertex_shader(const char *fname); +unsigned int load_pixel_shader(const char *fname); +unsigned int load_tessctl_shader(const char *fname); +unsigned int load_tesseval_shader(const char *fname); +unsigned int load_geometry_shader(const char *fname); +unsigned int load_shader(const char *src, unsigned int sdr_type); + +int add_shader(const char *fname, unsigned int sdr); +int remove_shader(const char *fname); + +/* ---- gpu programs ---- */ +unsigned int create_program(void); +unsigned int create_program_link(unsigned int sdr0, ...); +unsigned int create_program_load(const char *vfile, const char *pfile); +void free_program(unsigned int sdr); + +void attach_shader(unsigned int prog, unsigned int sdr); +int link_program(unsigned int prog); +int bind_program(unsigned int prog); + +int set_uniform_int(unsigned int prog, const char *name, int val); +int set_uniform_float(unsigned int prog, const char *name, float val); +int set_uniform_float2(unsigned int prog, const char *name, float x, float y); +int set_uniform_float3(unsigned int prog, const char *name, float x, float y, float z); +int set_uniform_float4(unsigned int prog, const char *name, float x, float y, float z, float w); +int set_uniform_matrix4(unsigned int prog, const char *name, float *mat); +int set_uniform_matrix4_transposed(unsigned int prog, const char *name, float *mat); + +int get_attrib_loc(unsigned int prog, const char *name); +void set_attrib_float3(int attr_loc, float x, float y, float z); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* SDR_H_ */ diff -r 000000000000 -r 50683c78264e src/timer.cc --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/timer.cc Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,118 @@ +#include "timer.h" + +#if defined(__APPLE__) && !defined(__unix__) +#define __unix__ +#endif + +#ifdef __unix__ +#include +#include +#include + +#ifdef CLOCK_MONOTONIC +unsigned long get_time_msec(void) +{ + struct timespec ts; + static struct timespec ts0; + + clock_gettime(CLOCK_MONOTONIC, &ts); + if(ts0.tv_sec == 0 && ts0.tv_nsec == 0) { + ts0 = ts; + return 0; + } + return (ts.tv_sec - ts0.tv_sec) * 1000 + (ts.tv_nsec - ts0.tv_nsec) / 1000000; +} +#else /* no fancy POSIX clocks, fallback to good'ol gettimeofday */ +unsigned long get_time_msec(void) +{ + struct timeval tv; + static struct timeval tv0; + + gettimeofday(&tv, 0); + if(tv0.tv_sec == 0 && tv0.tv_usec == 0) { + tv0 = tv; + return 0; + } + return (tv.tv_sec - tv0.tv_sec) * 1000 + (tv.tv_usec - tv0.tv_usec) / 1000; +} +#endif /* !posix clock */ + +void sleep_msec(unsigned long msec) +{ + usleep(msec * 1000); +} +#endif + +#ifdef WIN32 +#include +#pragma comment(lib, "winmm.lib") + +unsigned long get_time_msec(void) +{ + return timeGetTime(); +} + +void sleep_msec(unsigned long msec) +{ + Sleep(msec); +} +#endif + +double get_time_sec(void) +{ + return get_time_msec() / 1000.0f; +} + +void sleep_sec(double sec) +{ + if(sec > 0.0f) { + sleep_msec(sec * 1000.0f); + } +} + + +Timer::Timer() +{ + reset(); +} + +void Timer::reset() +{ + pause_time = 0; + start_time = get_time_msec(); +} + +void Timer::start() +{ + if(!is_running()) { + // resuming + start_time += get_time_msec() - pause_time; + pause_time = 0; + } +} + +void Timer::stop() +{ + if(is_running()) { + pause_time = get_time_msec(); + } +} + +bool Timer::is_running() const +{ + return pause_time == 0; +} + +unsigned long Timer::get_msec() const +{ + if(!is_running()) { + // in paused state... + return pause_time - start_time; + } + return get_time_msec() - start_time; +} + +double Timer::get_sec() const +{ + return (double)get_msec() / 1000.0; +} diff -r 000000000000 -r 50683c78264e src/timer.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/timer.h Sun Nov 01 00:09:12 2015 +0200 @@ -0,0 +1,29 @@ +#ifndef TIMER_H_ +#define TIMER_H_ + +unsigned long get_time_msec(void); +void sleep_msec(unsigned long msec); + +double get_time_sec(void); +void sleep_sec(double sec); + + +class Timer { +private: + unsigned long start_time, pause_time; + +public: + Timer(); + + void reset(); + + void start(); + void stop(); + + bool is_running() const; + + unsigned long get_msec() const; + double get_sec() const; +}; + +#endif // TIMER_H_